file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
cache.rs
on a type, hold impls here while // folding and add them to the cache later on if we find the trait. orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>, /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias, /// we need the alias element to have an array of items. pub(super) aliases: FxHashMap<String, Vec<IndexItem>>, } impl Cache { pub fn from_krate( renderinfo: RenderInfo, extern_html_root_urls: &BTreeMap<String, String>, dst: &Path, mut krate: clean::Crate, ) -> (clean::Crate, String, Cache) { // Crawl the crate to build various caches used for the output let RenderInfo { inlined: _, external_paths, exact_paths, access_levels, deref_trait_did, deref_mut_trait_did, owned_box_did, } = renderinfo; let external_paths = external_paths.into_iter() .map(|(k, (v, t))| (k, (v, ItemType::from(t)))) .collect(); let mut cache = Cache { impls: Default::default(), external_paths, exact_paths, paths: Default::default(), implementors: Default::default(), stack: Vec::new(), parent_stack: Vec::new(), search_index: Vec::new(), parent_is_trait_impl: false, extern_locations: Default::default(), primitive_locations: Default::default(), stripped_mod: false, access_levels, crate_version: krate.version.take(), orphan_impl_items: Vec::new(), orphan_trait_impls: Vec::new(), traits: krate.external_traits.replace(Default::default()), deref_trait_did, deref_mut_trait_did, owned_box_did, masked_crates: mem::take(&mut krate.masked_crates), aliases: Default::default(), }; // Cache where all our extern crates are located for &(n, ref e) in &krate.externs { let src_root = match e.src { FileName::Real(ref p) => match p.parent() { Some(p) => p.to_path_buf(), None => PathBuf::new(), }, _ => PathBuf::new(), };
cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module)); } // Cache where all known primitives have their documentation located. // // Favor linking to as local extern as possible, so iterate all crates in // reverse topological order. for &(_, ref e) in krate.externs.iter().rev() { for &(def_id, prim, _) in &e.primitives { cache.primitive_locations.insert(prim, def_id); } } for &(def_id, prim, _) in &krate.primitives { cache.primitive_locations.insert(prim, def_id); } cache.stack.push(krate.name.clone()); krate = cache.fold_crate(krate); for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) { if cache.traits.contains_key(&trait_did) { for did in dids { cache.impls.entry(did).or_insert(vec![]).push(impl_.clone()); } } } // Build our search index let index = build_index(&krate, &mut cache); (krate, index, cache) } } impl DocFolder for Cache { fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> { if item.def_id.is_local() { debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id); } // If this is a stripped module, // we don't want it or its children in the search index. let orig_stripped_mod = match item.inner { clean::StrippedItem(box clean::ModuleItem(..)) => { mem::replace(&mut self.stripped_mod, true) } _ => self.stripped_mod, }; // If the impl is from a masked crate or references something from a // masked crate then remove it completely. if let clean::ImplItem(ref i) = item.inner { if self.masked_crates.contains(&item.def_id.krate) || i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) || i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) { return None; } } // Propagate a trait method's documentation to all implementors of the // trait. if let clean::TraitItem(ref t) = item.inner { self.traits.entry(item.def_id).or_insert_with(|| t.clone()); } // Collect all the implementors of traits. if let clean::ImplItem(ref i) = item.inner { if let Some(did) = i.trait_.def_id() { if i.blanket_impl.is_none() { self.implementors.entry(did).or_default().push(Impl { impl_item: item.clone(), }); } } } // Index this method for searching later on. if let Some(ref s) = item.name { let (parent, is_inherent_impl_item) = match item.inner { clean::StrippedItem(..) => ((None, None), false), clean::AssocConstItem(..) | clean::TypedefItem(_, true) if self.parent_is_trait_impl => { // skip associated items in trait impls ((None, None), false) } clean::AssocTypeItem(..) | clean::TyMethodItem(..) | clean::StructFieldItem(..) | clean::VariantItem(..) => { ((Some(*self.parent_stack.last().unwrap()), Some(&self.stack[..self.stack.len() - 1])), false) } clean::MethodItem(..) | clean::AssocConstItem(..) => { if self.parent_stack.is_empty() { ((None, None), false) } else { let last = self.parent_stack.last().unwrap(); let did = *last; let path = match self.paths.get(&did) { // The current stack not necessarily has correlation // for where the type was defined. On the other // hand, `paths` always has the right // information if present. Some(&(ref fqp, ItemType::Trait)) | Some(&(ref fqp, ItemType::Struct)) | Some(&(ref fqp, ItemType::Union)) | Some(&(ref fqp, ItemType::Enum)) => Some(&fqp[..fqp.len() - 1]), Some(..) => Some(&*self.stack), None => None }; ((Some(*last), path), true) } } _ => ((None, Some(&*self.stack)), false) }; match parent { (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => { debug_assert!(!item.is_stripped()); // A crate has a module at its root, containing all items, // which should not be indexed. The crate-item itself is // inserted later on when serializing the search-index. if item.def_id.index!= CRATE_DEF_INDEX { self.search_index.push(IndexItem { ty: item.type_(), name: s.to_string(), path: path.join("::"), desc: shorten(plain_summary_line(item.doc_value())), parent, parent_idx: None, search_type: get_index_search_type(&item), }); } } (Some(parent), None) if is_inherent_impl_item => { // We have a parent, but we don't know where they're // defined yet. Wait for later to index this item. self.orphan_impl_items.push((parent, item.clone())); } _ => {} } } // Keep track of the fully qualified path for this item. let pushed = match item.name { Some(ref n) if!n.is_empty() => { self.stack.push(n.to_string()); true } _ => false, }; match item.inner { clean::StructItem(..) | clean::EnumItem(..) | clean::TypedefItem(..) | clean::TraitItem(..) | clean::FunctionItem(..) | clean::ModuleItem(..) | clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) | clean::ConstantItem(..) | clean::StaticItem(..) | clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..) | clean::ProcMacroItem(..) if!self.stripped_mod => { // Re-exported items mean that the same id can show up twice // in the rustdoc ast that we're looking at. We know, // however, that a re-exported item doesn't show up in the // `public_items` map, so we can skip inserting into the // paths map if there was already an entry present and we're // not a public item. if!self.paths.contains_key(&item.def_id) || self.access_levels.is_public(item.def_id) { self.paths.insert(item.def_id, (self.stack.clone(), item.type_())); } self.add_aliases(&item); } // Link variants to their parent enum because pages aren't emitted // for each variant. clean::VariantItem(..) if!self.stripped_mod => { let mut stack = self.stack.clone(); stack.pop(); self.paths.insert(item.def_id, (stack, ItemType::Enum)); } clean::PrimitiveItem(..) => { self.add_aliases(&item); self.paths.insert(item.def_id, (self.stack.clone(), item.type_())); } _ => {} } // Maintain the parent stack let orig_parent_is_trait_impl = self.parent_is_trait_impl; let parent_pushed = match item.inner { clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem | clean::StructItem(..) | clean::UnionItem(..) => { self.parent_stack.push(item.def_id); self.parent_is_trait_impl = false; true } clean::ImplItem(ref i) => { self.parent_is_trait_impl = i.trait_.is_some(); match i.for_ { clean::ResolvedPath{ did,.. } => { self.parent_stack.push(did); true } ref t => { let prim_did = t.primitive_type().and_then(|t| { self.primitive_locations.get(&t).cloned() }); match prim_did { Some(did) => { self.parent_stack.push(did); true } None => false, } } } } _ => false }; // Once we've recursively found all the generics, hoard off all the // implementations elsewhere. let ret = self.fold_item_recur(item).and_then(|item| { if let clean::Item { inner: clean::ImplItem(_),.. } = item { // Figure out the id of this impl. This may map to a // primitive rather than always to a struct/enum. // Note: matching twice to restrict the lifetime of the `i` borrow. let mut dids = FxHashSet::default(); if let clean::Item { inner: clean::ImplItem(ref i),.. } = item { match i.for_ { clean::ResolvedPath { did,.. } | clean::BorrowedRef { type_: box clean::ResolvedPath { did,.. },.. } => { dids.insert(did); } ref t => { let did = t.primitive_type().and_then(|t| { self.primitive_locations.get(&t).cloned() }); if let Some(did) = did { dids.insert(did); } } } if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) { for bound in generics { if let Some(did) = bound.def_id() { dids.insert(did); } } } } else { unreachable!() }; let impl_item = Impl { impl_item: item, }; if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) { for did in dids { self.impls.entry(did).or_insert(vec![]).push(impl_item.clone()); } } else { let trait_did = impl_item.trait_did().unwrap(); self.orphan_trait_impls.push((trait_did, dids, impl_item)); } None } else { Some(item) } }); if pushed { self.stack.pop().unwrap(); } if parent_pushed { self.parent_stack.pop().unwrap(); } self.stripped_mod = orig_stripped_mod; self.parent_is_trait_impl = orig_parent_is_trait_impl; ret } } impl Cache { fn add_aliases(&mut self, item: &clean::Item) { if item.def_id.index == CRATE_DEF_INDEX { return } if let Some(ref item_name) = item
let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u); cache.extern_locations.insert(n, (e.name.clone(), src_root, extern_location(e, extern_url, &dst))); let did = DefId { krate: n, index: CRATE_DEF_INDEX };
random_line_split
cache.rs
} // Cache where all known primitives have their documentation located. // // Favor linking to as local extern as possible, so iterate all crates in // reverse topological order. for &(_, ref e) in krate.externs.iter().rev() { for &(def_id, prim, _) in &e.primitives { cache.primitive_locations.insert(prim, def_id); } } for &(def_id, prim, _) in &krate.primitives { cache.primitive_locations.insert(prim, def_id); } cache.stack.push(krate.name.clone()); krate = cache.fold_crate(krate); for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) { if cache.traits.contains_key(&trait_did) { for did in dids { cache.impls.entry(did).or_insert(vec![]).push(impl_.clone()); } } } // Build our search index let index = build_index(&krate, &mut cache); (krate, index, cache) } } impl DocFolder for Cache { fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> { if item.def_id.is_local() { debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id); } // If this is a stripped module, // we don't want it or its children in the search index. let orig_stripped_mod = match item.inner { clean::StrippedItem(box clean::ModuleItem(..)) => { mem::replace(&mut self.stripped_mod, true) } _ => self.stripped_mod, }; // If the impl is from a masked crate or references something from a // masked crate then remove it completely. if let clean::ImplItem(ref i) = item.inner { if self.masked_crates.contains(&item.def_id.krate) || i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) || i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) { return None; } } // Propagate a trait method's documentation to all implementors of the // trait. if let clean::TraitItem(ref t) = item.inner { self.traits.entry(item.def_id).or_insert_with(|| t.clone()); } // Collect all the implementors of traits. if let clean::ImplItem(ref i) = item.inner { if let Some(did) = i.trait_.def_id() { if i.blanket_impl.is_none() { self.implementors.entry(did).or_default().push(Impl { impl_item: item.clone(), }); } } } // Index this method for searching later on. if let Some(ref s) = item.name { let (parent, is_inherent_impl_item) = match item.inner { clean::StrippedItem(..) => ((None, None), false), clean::AssocConstItem(..) | clean::TypedefItem(_, true) if self.parent_is_trait_impl => { // skip associated items in trait impls ((None, None), false) } clean::AssocTypeItem(..) | clean::TyMethodItem(..) | clean::StructFieldItem(..) | clean::VariantItem(..) => { ((Some(*self.parent_stack.last().unwrap()), Some(&self.stack[..self.stack.len() - 1])), false) } clean::MethodItem(..) | clean::AssocConstItem(..) => { if self.parent_stack.is_empty() { ((None, None), false) } else { let last = self.parent_stack.last().unwrap(); let did = *last; let path = match self.paths.get(&did) { // The current stack not necessarily has correlation // for where the type was defined. On the other // hand, `paths` always has the right // information if present. Some(&(ref fqp, ItemType::Trait)) | Some(&(ref fqp, ItemType::Struct)) | Some(&(ref fqp, ItemType::Union)) | Some(&(ref fqp, ItemType::Enum)) => Some(&fqp[..fqp.len() - 1]), Some(..) => Some(&*self.stack), None => None }; ((Some(*last), path), true) } } _ => ((None, Some(&*self.stack)), false) }; match parent { (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => { debug_assert!(!item.is_stripped()); // A crate has a module at its root, containing all items, // which should not be indexed. The crate-item itself is // inserted later on when serializing the search-index. if item.def_id.index!= CRATE_DEF_INDEX { self.search_index.push(IndexItem { ty: item.type_(), name: s.to_string(), path: path.join("::"), desc: shorten(plain_summary_line(item.doc_value())), parent, parent_idx: None, search_type: get_index_search_type(&item), }); } } (Some(parent), None) if is_inherent_impl_item => { // We have a parent, but we don't know where they're // defined yet. Wait for later to index this item. self.orphan_impl_items.push((parent, item.clone())); } _ => {} } } // Keep track of the fully qualified path for this item. let pushed = match item.name { Some(ref n) if!n.is_empty() => { self.stack.push(n.to_string()); true } _ => false, }; match item.inner { clean::StructItem(..) | clean::EnumItem(..) | clean::TypedefItem(..) | clean::TraitItem(..) | clean::FunctionItem(..) | clean::ModuleItem(..) | clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) | clean::ConstantItem(..) | clean::StaticItem(..) | clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..) | clean::ProcMacroItem(..) if!self.stripped_mod => { // Re-exported items mean that the same id can show up twice // in the rustdoc ast that we're looking at. We know, // however, that a re-exported item doesn't show up in the // `public_items` map, so we can skip inserting into the // paths map if there was already an entry present and we're // not a public item. if!self.paths.contains_key(&item.def_id) || self.access_levels.is_public(item.def_id) { self.paths.insert(item.def_id, (self.stack.clone(), item.type_())); } self.add_aliases(&item); } // Link variants to their parent enum because pages aren't emitted // for each variant. clean::VariantItem(..) if!self.stripped_mod => { let mut stack = self.stack.clone(); stack.pop(); self.paths.insert(item.def_id, (stack, ItemType::Enum)); } clean::PrimitiveItem(..) => { self.add_aliases(&item); self.paths.insert(item.def_id, (self.stack.clone(), item.type_())); } _ => {} } // Maintain the parent stack let orig_parent_is_trait_impl = self.parent_is_trait_impl; let parent_pushed = match item.inner { clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem | clean::StructItem(..) | clean::UnionItem(..) => { self.parent_stack.push(item.def_id); self.parent_is_trait_impl = false; true } clean::ImplItem(ref i) => { self.parent_is_trait_impl = i.trait_.is_some(); match i.for_ { clean::ResolvedPath{ did,.. } => { self.parent_stack.push(did); true } ref t => { let prim_did = t.primitive_type().and_then(|t| { self.primitive_locations.get(&t).cloned() }); match prim_did { Some(did) => { self.parent_stack.push(did); true } None => false, } } } } _ => false }; // Once we've recursively found all the generics, hoard off all the // implementations elsewhere. let ret = self.fold_item_recur(item).and_then(|item| { if let clean::Item { inner: clean::ImplItem(_),.. } = item { // Figure out the id of this impl. This may map to a // primitive rather than always to a struct/enum. // Note: matching twice to restrict the lifetime of the `i` borrow. let mut dids = FxHashSet::default(); if let clean::Item { inner: clean::ImplItem(ref i),.. } = item { match i.for_ { clean::ResolvedPath { did,.. } | clean::BorrowedRef { type_: box clean::ResolvedPath { did,.. },.. } => { dids.insert(did); } ref t => { let did = t.primitive_type().and_then(|t| { self.primitive_locations.get(&t).cloned() }); if let Some(did) = did { dids.insert(did); } } } if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) { for bound in generics { if let Some(did) = bound.def_id() { dids.insert(did); } } } } else { unreachable!() }; let impl_item = Impl { impl_item: item, }; if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) { for did in dids { self.impls.entry(did).or_insert(vec![]).push(impl_item.clone()); } } else { let trait_did = impl_item.trait_did().unwrap(); self.orphan_trait_impls.push((trait_did, dids, impl_item)); } None } else { Some(item) } }); if pushed { self.stack.pop().unwrap(); } if parent_pushed { self.parent_stack.pop().unwrap(); } self.stripped_mod = orig_stripped_mod; self.parent_is_trait_impl = orig_parent_is_trait_impl; ret } } impl Cache { fn add_aliases(&mut self, item: &clean::Item) { if item.def_id.index == CRATE_DEF_INDEX { return } if let Some(ref item_name) = item.name { let path = self.paths.get(&item.def_id) .map(|p| p.0[..p.0.len() - 1].join("::")) .unwrap_or("std".to_owned()); for alias in item.attrs.lists(sym::doc) .filter(|a| a.check_name(sym::alias)) .filter_map(|a| a.value_str() .map(|s| s.to_string().replace("\"", ""))) .filter(|v|!v.is_empty()) .collect::<FxHashSet<_>>() .into_iter() { self.aliases.entry(alias) .or_insert(Vec::with_capacity(1)) .push(IndexItem { ty: item.type_(), name: item_name.to_string(), path: path.clone(), desc: shorten(plain_summary_line(item.doc_value())), parent: None, parent_idx: None, search_type: get_index_search_type(&item), }); } } } } /// Attempts to find where an external crate is located, given that we're /// rendering in to the specified source destination. fn extern_location(e: &clean::ExternalCrate, extern_url: Option<&str>, dst: &Path) -> ExternalLocation { use ExternalLocation::*; // See if there's documentation generated into the local directory let local_location = dst.join(&e.name); if local_location.is_dir() { return Local; } if let Some(url) = extern_url { let mut url = url.to_string(); if!url.ends_with("/") { url.push('/'); } return Remote(url); } // Failing that, see if there's an attribute specifying where to find this // external crate e.attrs.lists(sym::doc) .filter(|a| a.check_name(sym::html_root_url)) .filter_map(|a| a.value_str()) .map(|url| { let mut url = url.to_string(); if!url.ends_with("/") { url.push('/') } Remote(url) }).next().unwrap_or(Unknown) // Well, at least we tried. } /// Builds the search index from the collected metadata fn
build_index
identifier_name
cache.rs
, index: CRATE_DEF_INDEX }; cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module)); } // Cache where all known primitives have their documentation located. // // Favor linking to as local extern as possible, so iterate all crates in // reverse topological order. for &(_, ref e) in krate.externs.iter().rev() { for &(def_id, prim, _) in &e.primitives { cache.primitive_locations.insert(prim, def_id); } } for &(def_id, prim, _) in &krate.primitives { cache.primitive_locations.insert(prim, def_id); } cache.stack.push(krate.name.clone()); krate = cache.fold_crate(krate); for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) { if cache.traits.contains_key(&trait_did) { for did in dids { cache.impls.entry(did).or_insert(vec![]).push(impl_.clone()); } } } // Build our search index let index = build_index(&krate, &mut cache); (krate, index, cache) } } impl DocFolder for Cache { fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> { if item.def_id.is_local() { debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id); } // If this is a stripped module, // we don't want it or its children in the search index. let orig_stripped_mod = match item.inner { clean::StrippedItem(box clean::ModuleItem(..)) => { mem::replace(&mut self.stripped_mod, true) } _ => self.stripped_mod, }; // If the impl is from a masked crate or references something from a // masked crate then remove it completely. if let clean::ImplItem(ref i) = item.inner { if self.masked_crates.contains(&item.def_id.krate) || i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) || i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) { return None; } } // Propagate a trait method's documentation to all implementors of the // trait. if let clean::TraitItem(ref t) = item.inner { self.traits.entry(item.def_id).or_insert_with(|| t.clone()); } // Collect all the implementors of traits. if let clean::ImplItem(ref i) = item.inner { if let Some(did) = i.trait_.def_id() { if i.blanket_impl.is_none() { self.implementors.entry(did).or_default().push(Impl { impl_item: item.clone(), }); } } } // Index this method for searching later on. if let Some(ref s) = item.name { let (parent, is_inherent_impl_item) = match item.inner { clean::StrippedItem(..) => ((None, None), false), clean::AssocConstItem(..) | clean::TypedefItem(_, true) if self.parent_is_trait_impl => { // skip associated items in trait impls ((None, None), false) } clean::AssocTypeItem(..) | clean::TyMethodItem(..) | clean::StructFieldItem(..) | clean::VariantItem(..) => { ((Some(*self.parent_stack.last().unwrap()), Some(&self.stack[..self.stack.len() - 1])), false) } clean::MethodItem(..) | clean::AssocConstItem(..) => { if self.parent_stack.is_empty() { ((None, None), false) } else { let last = self.parent_stack.last().unwrap(); let did = *last; let path = match self.paths.get(&did) { // The current stack not necessarily has correlation // for where the type was defined. On the other // hand, `paths` always has the right // information if present. Some(&(ref fqp, ItemType::Trait)) | Some(&(ref fqp, ItemType::Struct)) | Some(&(ref fqp, ItemType::Union)) | Some(&(ref fqp, ItemType::Enum)) => Some(&fqp[..fqp.len() - 1]), Some(..) => Some(&*self.stack), None => None }; ((Some(*last), path), true) } } _ => ((None, Some(&*self.stack)), false) }; match parent { (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => { debug_assert!(!item.is_stripped()); // A crate has a module at its root, containing all items, // which should not be indexed. The crate-item itself is // inserted later on when serializing the search-index. if item.def_id.index!= CRATE_DEF_INDEX { self.search_index.push(IndexItem { ty: item.type_(), name: s.to_string(), path: path.join("::"), desc: shorten(plain_summary_line(item.doc_value())), parent, parent_idx: None, search_type: get_index_search_type(&item), }); } } (Some(parent), None) if is_inherent_impl_item => { // We have a parent, but we don't know where they're // defined yet. Wait for later to index this item. self.orphan_impl_items.push((parent, item.clone())); } _ => {} } } // Keep track of the fully qualified path for this item. let pushed = match item.name { Some(ref n) if!n.is_empty() => { self.stack.push(n.to_string()); true } _ => false, }; match item.inner { clean::StructItem(..) | clean::EnumItem(..) | clean::TypedefItem(..) | clean::TraitItem(..) | clean::FunctionItem(..) | clean::ModuleItem(..) | clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) | clean::ConstantItem(..) | clean::StaticItem(..) | clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..) | clean::ProcMacroItem(..) if!self.stripped_mod => { // Re-exported items mean that the same id can show up twice // in the rustdoc ast that we're looking at. We know, // however, that a re-exported item doesn't show up in the // `public_items` map, so we can skip inserting into the // paths map if there was already an entry present and we're // not a public item. if!self.paths.contains_key(&item.def_id) || self.access_levels.is_public(item.def_id) { self.paths.insert(item.def_id, (self.stack.clone(), item.type_())); } self.add_aliases(&item); } // Link variants to their parent enum because pages aren't emitted // for each variant. clean::VariantItem(..) if!self.stripped_mod => { let mut stack = self.stack.clone(); stack.pop(); self.paths.insert(item.def_id, (stack, ItemType::Enum)); } clean::PrimitiveItem(..) => { self.add_aliases(&item); self.paths.insert(item.def_id, (self.stack.clone(), item.type_())); } _ => {} } // Maintain the parent stack let orig_parent_is_trait_impl = self.parent_is_trait_impl; let parent_pushed = match item.inner { clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem | clean::StructItem(..) | clean::UnionItem(..) => { self.parent_stack.push(item.def_id); self.parent_is_trait_impl = false; true } clean::ImplItem(ref i) => { self.parent_is_trait_impl = i.trait_.is_some(); match i.for_ { clean::ResolvedPath{ did,.. } => { self.parent_stack.push(did); true } ref t => { let prim_did = t.primitive_type().and_then(|t| { self.primitive_locations.get(&t).cloned() }); match prim_did { Some(did) => { self.parent_stack.push(did); true } None => false, } } } } _ => false }; // Once we've recursively found all the generics, hoard off all the // implementations elsewhere. let ret = self.fold_item_recur(item).and_then(|item| { if let clean::Item { inner: clean::ImplItem(_),.. } = item { // Figure out the id of this impl. This may map to a // primitive rather than always to a struct/enum. // Note: matching twice to restrict the lifetime of the `i` borrow. let mut dids = FxHashSet::default(); if let clean::Item { inner: clean::ImplItem(ref i),.. } = item { match i.for_ { clean::ResolvedPath { did,.. } | clean::BorrowedRef { type_: box clean::ResolvedPath { did,.. },.. } => { dids.insert(did); } ref t => { let did = t.primitive_type().and_then(|t| { self.primitive_locations.get(&t).cloned() }); if let Some(did) = did { dids.insert(did); } } } if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) { for bound in generics { if let Some(did) = bound.def_id() { dids.insert(did); } } } } else { unreachable!() }; let impl_item = Impl { impl_item: item, }; if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) { for did in dids { self.impls.entry(did).or_insert(vec![]).push(impl_item.clone()); } } else { let trait_did = impl_item.trait_did().unwrap(); self.orphan_trait_impls.push((trait_did, dids, impl_item)); } None } else { Some(item) } }); if pushed { self.stack.pop().unwrap(); } if parent_pushed { self.parent_stack.pop().unwrap(); } self.stripped_mod = orig_stripped_mod; self.parent_is_trait_impl = orig_parent_is_trait_impl; ret } } impl Cache { fn add_aliases(&mut self, item: &clean::Item) { if item.def_id.index == CRATE_DEF_INDEX { return } if let Some(ref item_name) = item.name { let path = self.paths.get(&item.def_id) .map(|p| p.0[..p.0.len() - 1].join("::")) .unwrap_or("std".to_owned()); for alias in item.attrs.lists(sym::doc) .filter(|a| a.check_name(sym::alias)) .filter_map(|a| a.value_str() .map(|s| s.to_string().replace("\"", ""))) .filter(|v|!v.is_empty()) .collect::<FxHashSet<_>>() .into_iter() { self.aliases.entry(alias) .or_insert(Vec::with_capacity(1)) .push(IndexItem { ty: item.type_(), name: item_name.to_string(), path: path.clone(), desc: shorten(plain_summary_line(item.doc_value())), parent: None, parent_idx: None, search_type: get_index_search_type(&item), }); } } } } /// Attempts to find where an external crate is located, given that we're /// rendering in to the specified source destination. fn extern_location(e: &clean::ExternalCrate, extern_url: Option<&str>, dst: &Path) -> ExternalLocation { use ExternalLocation::*; // See if there's documentation generated into the local directory let local_location = dst.join(&e.name); if local_location.is_dir() { return Local; } if let Some(url) = extern_url { let mut url = url.to_string(); if!url.ends_with("/") { url.push('/'); } return Remote(url); } // Failing that, see if there's an attribute specifying where to find this // external crate e.attrs.lists(sym::doc) .filter(|a| a.check_name(sym::html_root_url)) .filter_map(|a| a.value_str()) .map(|url| { let mut url = url.to_string(); if!url.ends_with("/")
{ url.push('/') }
conditional_block
constants.rs
use lazy_static::lazy_static; use crate::options::ConfigColours; // Default widget ID pub const DEFAULT_WIDGET_ID: u64 = 56709; // How long to store data. pub const STALE_MAX_MILLISECONDS: u64 = 600 * 1000; // Keep 10 minutes of data. // How much data is SHOWN pub const DEFAULT_TIME_MILLISECONDS: u64 = 60 * 1000; // Defaults to 1 min. pub const STALE_MIN_MILLISECONDS: u64 = 30 * 1000; // Lowest is 30 seconds pub const TIME_CHANGE_MILLISECONDS: u64 = 15 * 1000; // How much to increment each time pub const AUTOHIDE_TIMEOUT_MILLISECONDS: u64 = 5000; // 5 seconds to autohide pub const TICK_RATE_IN_MILLISECONDS: u64 = 200; // How fast the screen refreshes pub const DEFAULT_REFRESH_RATE_IN_MILLISECONDS: u64 = 1000; pub const MAX_KEY_TIMEOUT_IN_MILLISECONDS: u64 = 1000; // Number of colours to generate for the CPU chart/table pub const NUM_COLOURS: usize = 256; // Limits for when we should stop showing table gaps/labels (anything less means not shown) pub const TABLE_GAP_HEIGHT_LIMIT: u16 = 7; pub const TIME_LABEL_HEIGHT_LIMIT: u16 = 7; // Side borders lazy_static! { pub static ref SIDE_BORDERS: tui::widgets::Borders = tui::widgets::Borders::from_bits_truncate(20); pub static ref TOP_LEFT_RIGHT: tui::widgets::Borders = tui::widgets::Borders::from_bits_truncate(22); pub static ref BOTTOM_LEFT_RIGHT: tui::widgets::Borders = tui::widgets::Borders::from_bits_truncate(28); pub static ref DEFAULT_TEXT_STYLE: tui::style::Style = tui::style::Style::default().fg(tui::style::Color::Gray); pub static ref DEFAULT_HEADER_STYLE: tui::style::Style = tui::style::Style::default().fg(tui::style::Color::LightBlue); } // Colour profiles lazy_static! { pub static ref DEFAULT_LIGHT_MODE_COLOUR_PALETTE: ConfigColours = ConfigColours { text_color: Some("black".to_string()), border_color: Some("black".to_string()), table_header_color: Some("black".to_string()), widget_title_color: Some("black".to_string()), selected_text_color: Some("white".to_string()), graph_color: Some("black".to_string()), disabled_text_color: Some("gray".to_string()), ..ConfigColours::default() }; pub static ref GRUVBOX_COLOUR_PALETTE: ConfigColours = ConfigColours { table_header_color: Some("#ebdbb2".to_string()), all_cpu_color: Some("#cc241d".to_string()), avg_cpu_color: Some("#98971a".to_string()), cpu_core_colors: Some(vec![ "#d79921".to_string(), "#458588".to_string(), "#b16286".to_string(), "#689d6a".to_string(), "#fb4934".to_string(), "#b8bb26".to_string(), "#fe8019".to_string(), "#fabd2f".to_string(), "#83a598".to_string(), "#d3869b".to_string(), "#8ec07c".to_string(), "#d65d0e".to_string(), "#fbf1c7".to_string(), "#ebdbb2".to_string(), "#d5c4a1".to_string(), "#bdae93".to_string(), "#a89984".to_string(), ]), ram_color: Some("#458588".to_string()), swap_color: Some("#fabd2f".to_string()), rx_color: Some("#458588".to_string()), tx_color: Some("#fabd2f".to_string()), rx_total_color: Some("#83a598".to_string()), tx_total_color: Some("#d79921".to_string()), border_color: Some("#ebdbb2".to_string()), highlighted_border_color: Some("#fe8019".to_string()), disabled_text_color: Some("#665c54".to_string()), text_color: Some("#ebdbb2".to_string()), selected_text_color: Some("#1d2021".to_string()), selected_bg_color: Some("#ebdbb2".to_string()), widget_title_color: Some("#ebdbb2".to_string()), graph_color: Some("#ebdbb2".to_string()), high_battery_color: Some("#98971a".to_string()), medium_battery_color: Some("#fabd2f".to_string()), low_battery_color: Some("#fb4934".to_string()) }; pub static ref GRUVBOX_LIGHT_COLOUR_PALETTE: ConfigColours = ConfigColours { table_header_color: Some("#3c3836".to_string()), all_cpu_color: Some("#cc241d".to_string()), avg_cpu_color: Some("#98971a".to_string()), cpu_core_colors: Some(vec![ "#d79921".to_string(), "#458588".to_string(), "#b16286".to_string(), "#689d6a".to_string(), "#fb4934".to_string(), "#b8bb26".to_string(), "#fe8019".to_string(), "#fabd2f".to_string(), "#83a598".to_string(), "#d3869b".to_string(), "#8ec07c".to_string(), "#d65d0e".to_string(), "#928374".to_string(), "#665c54".to_string(), "#504945".to_string(), "#3c3836".to_string(), "#282828".to_string(), ]), ram_color: Some("#458588".to_string()), swap_color: Some("#cc241d".to_string()), rx_color: Some("#458588".to_string()), tx_color: Some("#cc241d".to_string()), rx_total_color: Some("#83a598".to_string()), tx_total_color: Some("#9d0006".to_string()), border_color: Some("#3c3836".to_string()), highlighted_border_color: Some("#fe8019".to_string()), disabled_text_color: Some("#665c54".to_string()), text_color: Some("#3c3836".to_string()), selected_text_color: Some("#f9f5d7".to_string()), selected_bg_color: Some("#665c54".to_string()), widget_title_color: Some("#3c3836".to_string()), graph_color: Some("#3c3836".to_string()), high_battery_color: Some("#98971a".to_string()), medium_battery_color: Some("#fabd2f".to_string()), low_battery_color: Some("#fb4934".to_string()) }; // pub static ref NORD_COLOUR_PALETTE: ConfigColours = ConfigColours { // table_header_color: None,
// rx_color: None, // tx_color: None, // rx_total_color: None, // tx_total_color: None, // border_color: None, // highlighted_border_color: None, // text_color: None, // selected_text_color: None, // selected_bg_color: None, // widget_title_color: None, // graph_color: None, // high_battery_color: None, // medium_battery_color: None, // low_battery_color: None, // disabled_text_color: None, // }; } // FIXME: [HELP] I wanna update this before release... it's missing mouse too. // Help text pub const HELP_CONTENTS_TEXT: [&str; 8] = [ "Press the corresponding numbers to jump to the section, or scroll:", "1 - General", "2 - CPU widget", "3 - Process widget", "4 - Process search widget", "5 - Process sort widget", "6 - Battery widget", "7 - Basic memory widget", ]; pub const GENERAL_HELP_TEXT: [&str; 29] = [ "1 - General", "q, Ctrl-c Quit", "Esc Close dialog windows, search, widgets, or exit expanded mode", "Ctrl-r Reset display and any collected data", "f Freeze/unfreeze updating with new data", "Ctrl-Left, ", "Shift-Left, Move widget selection left", "H, A ", "Ctrl-Right, ", "Shift-Right, Move widget selection right", "L, D ", "Ctrl-Up, ", "Shift-Up, Move widget selection up", "K, W ", "Ctrl-Down, ", "Shift-Down, Move widget selection down", "J, S ", "Left, h Move left within widget", "Down, j Move down within widget", "Up, k Move up within widget", "Right, l Move right within widget", "? Open help menu", "gg Jump to the first entry", "G Jump to the last entry", "e Toggle expanding the currently selected widget", "+ Zoom in on chart (decrease time range)", "- Zoom out on chart (increase time range)", "= Reset zoom", "Mouse scroll Scroll through the tables or zoom in/out of charts by scrolling up/down", ]; pub const CPU_HELP_TEXT: [&str; 2] = [ "2 - CPU widget\n", "Mouse scroll Scrolling over an CPU core/average shows only that entry on the chart", ]; // TODO [Help]: Search in help? // TODO [Help]: Move to using tables for easier formatting? pub const PROCESS_HELP_TEXT: [&str; 13] = [ "3 - Process widget", "dd Kill the selected process", "c Sort by CPU usage, press again to reverse sorting order", "m Sort by memory usage, press again to reverse sorting order", "p Sort by PID name, press again to reverse sorting order", "n Sort by process name, press again to reverse sorting order", "Tab Group/un-group processes with the same name", "Ctrl-f, / Open process search widget", "P Toggle between showing the full command or just the process name", "s, F6 Open process sort widget", "I Invert current sort", "% Toggle between values and percentages for memory usage", "t, F5 Toggle tree mode", ]; pub const SEARCH_HELP_TEXT: [&str; 46] = [ "4 - Process search widget", "Tab Toggle between searching for PID and name", "Esc Close the search widget (retains the filter)", "Ctrl-a Skip to the start of the search query", "Ctrl-e Skip to the end of the search query", "Ctrl-u Clear the current search query", "Backspace Delete the character behind the cursor", "Delete Delete the character at the cursor", "Alt-c, F1 Toggle matching case", "Alt-w, F2 Toggle matching the entire word", "Alt-r, F3 Toggle using regex", "Left, Alt-h Move cursor left", "Right, Alt-l Move cursor right", "", "Supported search types:", "<by name/cmd> ex: btm", "pid ex: pid 825", "cpu, cpu% ex: cpu > 4.2", "mem, mem% ex: mem < 4.2", "memb ex: memb < 100 kb", "read, r/s ex: read >= 1 b", "write, w/s ex: write <= 1 tb", "tread, t.read ex: tread = 1", "twrite, t.write ex: twrite = 1", "state ex: state = running", "", "Comparison operators:", "= ex: cpu = 1", "> ex: cpu > 1", "< ex: cpu < 1", ">= ex: cpu >= 1", "<= ex: cpu <= 1", "", "Logical operators:", "and, &&, <Space> ex: btm and cpu > 1 and mem > 1", "or, || ex: btm or firefox", "", "Supported units:", "B ex: read > 1 b", "KB ex: read > 1 kb", "MB ex: read > 1 mb", "TB ex: read > 1 tb", "KiB ex: read > 1 kib", "MiB ex: read > 1 mib", "GiB ex: read > 1 gib", "TiB ex: read > 1 tib", ]; pub const SORT_HELP_TEXT: [&str; 6] = [ "5 - Sort widget\n", "Down, 'j' Scroll down in list", "Up, 'k' Scroll up in list", "Mouse scroll Scroll through sort widget", "Esc Close the sort widget", "Enter Sort by current selected column", ]; pub const BATTERY_HELP_TEXT: [&str; 3] = [ "6 - Battery widget", "Left Go to previous battery", "Right Go to next battery", ]; pub const BASIC_MEM_HELP_TEXT: [&str; 2] = [ "7 - Basic memory widget", "% Toggle between values and percentages for memory usage", ]; lazy_static! { pub static ref HELP_TEXT: Vec<Vec<&'static str>> = vec![ HELP_CONTENTS_TEXT.to_vec(), GENERAL_HELP_TEXT.to_vec(), CPU_HELP_TEXT.to_vec(), PROCESS_HELP_TEXT.to_vec(), SEARCH_HELP_TEXT.to_vec(), SORT_HELP_TEXT.to_vec(), BATTERY_HELP_TEXT.to_vec(), BASIC_MEM_HELP_TEXT.to_vec(), ]; } // Default layouts pub const DEFAULT_LAYOUT: &str = r##" [[row]] ratio=30 [[row.child]] type="cpu" [[row]] ratio=40 [[row.child]] ratio=4 type="mem" [[row.child]] ratio=3 [[row.child.child]] type="temp" [[row.child.child]] type="disk" [[row]] ratio=30 [[row.child]] type="net" [[row.child]] type="proc" default=true "##; pub const DEFAULT_BATTERY_LAYOUT: &str = r##" [[row]] ratio=30 [[row.child]] ratio=2 type="cpu" [[row.child]] ratio=1 type="battery" [[row]] ratio=40 [[row.child]] ratio=4 type="mem" [[row.child]] ratio=3 [[row.child.child]] type="temp" [[row.child.child]] type="disk" [[row]] ratio=30 [[row.child]] type="net" [[row.child]] type="proc" default=true "##; // Config and flags pub const DEFAULT_CONFIG_FILE_PATH: &str = "bottom/bottom.toml"; pub const CONFIG_TOP_HEAD: &str = r##"# This is bottom's config file. Values in this config file will change when changed in the # interface. You can also manually change these values. Be aware that contents of this file will be overwritten if something is # changed in the application; you can disable writing via the --no_write flag or no_write config option. "##; pub const CONFIG_DISPLAY_OPTIONS_HEAD: &str = r##" # These options represent settings that affect how bottom functions. # If a setting here corresponds to command-line flag, then the flag will temporarily override # the setting. "##; pub const CONFIG_COLOUR_HEAD: &str = r##" # These options represent colour values for various parts of bottom. Note that colour support # will ultimately depend on the terminal - for example, the Terminal for macOS does NOT like # custom colours and it may glitch out. "##; pub const CONFIG_LAYOUT_HEAD: &str = r##" # These options represent how bottom will lay out its widgets. Layouts follow a pattern like this: # [[row]] represents a row in the application. # [[row.child]] represents either a widget or a column. # [[row.child.child]] represents a widget. # # All widgets must have the valid type value set to one of ["cpu", "mem", "proc", "net", "temp", "disk", "empty"]. # All layout components have a ratio value - if this is not set, then it defaults to 1. "##; pub const CONFIG_FILTER_HEAD: &str = r##" # These options represent disabled entries for the temperature and disk widgets. "##;
// all_cpu_color: None, // avg_cpu_color: None, // cpu_core_colors: None, // ram_color: None, // swap_color: None,
random_line_split
shell.rs
request = Request::new_with_str_and_init(url, &opts).map_err(js_err_handler)?; let window = web_sys::window().unwrap(); // Get the response as a future and await it let res_value = JsFuture::from(window.fetch_with_request(&request)) .await .map_err(js_err_handler)?; // Turn that into a proper response object let res: Response = res_value.dyn_into().unwrap(); // If the status is 404, we should return that the request worked but no file existed if res.status() == 404 { return Ok(None); } // Get the body thereof let body_promise = res.text().map_err(js_err_handler)?; let body = JsFuture::from(body_promise).await.map_err(js_err_handler)?; // Convert that into a string (this will be `None` if it wasn't a string in the JS) let body_str = body.as_string(); let body_str = match body_str { Some(body_str) => body_str, None => { return Err(FetchError::NotString { url: url.to_string(), } .into()) } }; // Handle non-200 error codes if res.status() == 200 { Ok(Some(body_str)) } else { Err(FetchError::NotOk { url: url.to_string(), status: res.status(), err: body_str, } .into()) } } /// Gets the render configuration from the JS global variable `__PERSEUS_RENDER_CFG`, which should be inlined by the server. This will /// return `None` on any error (not found, serialization failed, etc.), which should reasonably lead to a `panic!` in the caller. pub fn get_render_cfg() -> Option<HashMap<String, String>>
/// Gets the initial state injected by the server, if there was any. This is used to differentiate initial loads from subsequent ones, /// which have different log chains to prevent double-trips (a common SPA problem). pub fn get_initial_state() -> InitialState { let val_opt = web_sys::window().unwrap().get("__PERSEUS_INITIAL_STATE"); let js_obj = match val_opt { Some(js_obj) => js_obj, None => return InitialState::NotPresent, }; // The object should only actually contain the string value that was injected let state_str = match js_obj.as_string() { Some(state_str) => state_str, None => return InitialState::NotPresent, }; // On the server-side, we encode a `None` value directly (otherwise it will be some convoluted stringified JSON) if state_str == "None" { InitialState::Present(None) } else if state_str.starts_with("error-") { // We strip the prefix and escape any tab/newline control characters (inserted by `fmterr`) // Any others are user-inserted, and this is documented let err_page_data_str = state_str .strip_prefix("error-") .unwrap() .replace("\n", "\\n") .replace("\t", "\\t"); // There will be error page data encoded after `error-` let err_page_data = match serde_json::from_str::<ErrorPageData>(&err_page_data_str) { Ok(render_cfg) => render_cfg, // If there's a serialization error, we'll create a whole new error (500) Err(err) => ErrorPageData { url: "[current]".to_string(), status: 500, err: format!( "couldn't serialize error from server: '{}'", err.to_string() ), }, }; InitialState::Error(err_page_data) } else { InitialState::Present(Some(state_str)) } } /// Marks a checkpoint in the code and alerts any tests that it's been reached by creating an element that represents it. The preferred /// solution would be emitting a DOM event, but the WebDriver specification currently doesn't support waiting on those (go figure). This /// will only create a custom element if the `__PERSEUS_TESTING` JS global variable is set to `true`. /// /// This adds a `<div id="__perseus_checkpoint-<event-name>" />` to the `<div id="__perseus_checkpoints"></div>` element, creating the /// latter if it doesn't exist. Each checkpoint must have a unique name, and if the same checkpoint is executed twice, it'll be added /// with a `-<number>` after it, starting from `0`. In this way, we have a functional checkpoints queue for signalling to test code! /// Note that the checkpoint queue is NOT cleared on subsequent loads. /// /// Note: this is not just for internal usage, it's highly recommended that you use this for your own checkpoints as well! Just make /// sure your tests don't conflict with any internal Perseus checkpoint names (preferably prefix yours with `custom-` or the like, as /// Perseus' checkpoints may change at any time, but won't ever use that namespace). /// /// WARNING: your checkpoint names must not include hyphens! This will result in a `panic!`. pub fn checkpoint(name: &str) { if name.contains('-') { panic!("checkpoint must not contain hyphens, use underscores instead (hyphens are used as an internal delimiter)"); } let val_opt = web_sys::window().unwrap().get("__PERSEUS_TESTING"); let js_obj = match val_opt { Some(js_obj) => js_obj, None => return, }; // The object should only actually contain the string value that was injected let is_testing = match js_obj.as_bool() { Some(cfg_str) => cfg_str, None => return, }; if!is_testing { return; } // If we're here, we're testing // We dispatch a console warning to reduce the likelihood of literal 'testing in prod' crate::web_log!("Perseus is in testing mode. If you're an end-user and seeing this message, please report this as a bug to the website owners!"); // Create a custom element that can be waited for by the WebDriver // This will be removed by the next checkpoint let document = web_sys::window().unwrap().document().unwrap(); let container_opt = document.query_selector("#__perseus_checkpoints").unwrap(); let container: Element; if let Some(container_i) = container_opt { container = container_i; } else { // If the container doesn't exist yet, create it container = document.create_element("div").unwrap(); container.set_id("__perseus_checkpoints"); document .query_selector("body") .unwrap() .unwrap() .append_with_node_1(&container) .unwrap(); } // Get the number of checkpoints that already exist with the same ID // We prevent having to worry about checkpoints whose names are subsets of others by using the hyphen as a delimiter let num_checkpoints = document .query_selector_all(&format!("[id^=__perseus_checkpoint-{}-]", name)) .unwrap() .length(); // Append the new checkpoint let checkpoint = document.create_element("div").unwrap(); checkpoint.set_id(&format!( "__perseus_checkpoint-{}-{}", name, num_checkpoints )); container.append_with_node_1(&checkpoint).unwrap(); } /// A representation of whether or not the initial state was present. If it was, it could be `None` (some templates take no state), and /// if not, then this isn't an initial load, and we need to request the page from the server. It could also be an error that the server /// has rendered. pub enum InitialState { /// A non-error initial state has been injected. Present(Option<String>), /// An initial state ahs been injected that indicates an error. Error(ErrorPageData), /// No initial state has been injected (or if it has, it's been deliberately unset). NotPresent, } /// Fetches the information for the given page and renders it. This should be provided the actual path of the page to render (not just the /// broader template). Asynchronous Wasm is handled here, because only a few cases need it. // TODO handle exceptions higher up pub async fn app_shell( path: String, (template, was_incremental_match): (Template<DomNode>, bool), locale: String, translations_manager: Rc<RefCell<ClientTranslationsManager>>, error_pages: Rc<ErrorPages<DomNode>>, (initial_container, container_rx_elem): (Element, Element), // The container that the server put initial load content into and the reactive container tht we'll actually use ) { checkpoint("app_shell_entry"); // Check if this was an initial load and we already have the state let initial_state = get_initial_state(); match initial_state { // If we do have an initial state, then we have everything we need for immediate hydration (no double trips) // The state is here, and the HTML has already been injected for us (including head metadata) InitialState::Present(state) => { checkpoint("initial_state_present"); // Unset the initial state variable so we perform subsequent renders correctly // This monstrosity is needed until `web-sys` adds a `.set()` method on `Window` Reflect::set( &JsValue::from(web_sys::window().unwrap()), &JsValue::from("__PERSEUS_INITIAL_STATE"), &JsValue::undefined(), ) .unwrap(); // We need to move the server-rendered content from its current container to the reactive container (otherwise Sycamore can't work with it properly) let initial_html = initial_container.inner_html(); container_rx_elem.set_inner_html(&initial_html); initial_container.set_inner_html(""); // Make the initial container invisible initial_container .set_attribute("style", "display: none;") .unwrap(); checkpoint("page_visible"); // Now that the user can see something, we can get the translator let mut translations_manager_mut = translations_manager.borrow_mut(); // This gets an `Rc<Translator>` that references the translations manager, meaning no cloning of translations let translator = translations_manager_mut .get_translator_for_locale(&locale) .await; let translator = match translator { Ok(translator) => translator, Err(err) => { // Directly eliminate the HTML sent in from the server before we render an error page container_rx_elem.set_inner_html(""); match &err { // These errors happen because we couldn't get a translator, so they certainly don't get one ClientError::FetchError(FetchError::NotOk { url, status,.. }) => return error_pages.render_page(url, status, &fmt_err(&err), None, &container_rx_elem), ClientError::FetchError(FetchError::SerFailed { url,.. }) => return error_pages.render_page(url, &500, &fmt_err(&err), None, &container_rx_elem), ClientError::LocaleNotSupported {.. } => return error_pages.render_page(&format!("/{}/...", locale), &404, &fmt_err(&err), None, &container_rx_elem), // No other errors should be returned _ => panic!("expected 'AssetNotOk'/'AssetSerFailed'/'LocaleNotSupported' error, found other unacceptable error") } } }; // Hydrate that static code using the acquired state // BUG (Sycamore): this will double-render if the component is just text (no nodes) sycamore::hydrate_to( // This function provides translator context as needed || template.render_for_template(state, Rc::clone(&translator), false), &container_rx_elem, ); checkpoint("page_interactive"); } // If we have no initial state, we should proceed as usual, fetching the content and state from the server InitialState::NotPresent => { checkpoint("initial_state_not_present"); // If we're getting data about the index page, explicitly set it to that // This can be handled by the Perseus server (and is), but not by static exporting let path = match path.is_empty() { true => "index".to_string(), false => path, }; // Get the static page data let asset_url = format!( "{}/.perseus/page/{}/{}.json?template_name={}&was_incremental_match={}", get_path_prefix_client(), locale, path.to_string(), template.get_path(), was_incremental_match ); // If this doesn't exist, then it's a 404 (we went here by explicit navigation, but it may be an unservable ISR page or the like) let page_data_str = fetch(&asset_url).await; match page_data_str { Ok(page_data_str) => match page_data_str { Some(page_data_str) => { // All good, deserialize the page data let page_data = serde_json::from_str::<PageData>(&page_data_str); match page_data { Ok(page_data) => { // We have the page data ready, render everything // Interpolate the HTML directly into the document (we'll hydrate it later) container_rx_elem.set_inner_html(&page_data.content); // Interpolate the metadata directly into the document's `<head>` // Get the current head let head_elem = web_sys::window() .unwrap() .document() .unwrap() .query_selector("head") .unwrap() .unwrap(); let head_html = head_elem.inner_html(); // We'll assume that there's already previously interpolated head in addition to the hardcoded stuff, but it will be separated by the server-injected delimiter comment // Thus, we replace the stuff after that delimiter comment with the new head let head_parts: Vec<&str> = head_html .split("<!--PERSEUS_INTERPOLATED_HEAD_BEGINS-->") .collect(); let new_head = format!( "{}\n<!--PERSEUS_INTERPOLATED_HEAD_BEGINS-->\n{}", head_parts[0], &page_data.head ); head_elem.set_inner_html(&new_head); checkpoint("page_visible"); // Now that the user can see something, we can get the translator let mut translations_manager_mut = translations_manager.borrow_mut(); // This gets an `Rc<Translator>` that references the translations manager, meaning no cloning of translations let translator = translations_manager_mut .get_translator_for_locale(&locale) .await; let translator = match translator { Ok(translator) => translator, Err(err) => match &err { // These errors happen because we couldn't get a translator, so they certainly don't get one ClientError::FetchError(FetchError::NotOk { url, status,.. }) => return error_pages.render_page(url, status, &fmt_err(&err), None, &container_rx_elem), ClientError::FetchError(FetchError::SerFailed { url,.. }) => return error_pages.render_page(url, &500, &fmt_err(&err), None, &container_rx_elem), ClientError::LocaleNotSupported { locale } => return error_pages.render_page(&format!("/{}/...", locale), &404, &fmt_err(&err), None, &container_rx_elem), // No other errors should be returned _ => panic!("expected 'AssetNotOk'/'AssetSerFailed'/'LocaleNotSupported' error, found other unacceptable error") } }; // Hydrate that static code using the acquired state // BUG (Sycamore): this will double-render if the component is just text (no nodes) sycamore::hydrate_to( // This function provides translator context as needed || { template.render_for_template( page_data.state, Rc::clone(&translator), false, ) }, &container_rx_elem, ); checkpoint("page_interactive"); } // If the page failed to serialize, an exception has occurred Err(err) => panic!("page data couldn't be serialized: '{}'", err), }; } // No translators ready yet None => error_pages.render_page( &asset_url, &404, "page not found", None, &container_rx_elem
{ let val_opt = web_sys::window().unwrap().get("__PERSEUS_RENDER_CFG"); let js_obj = match val_opt { Some(js_obj) => js_obj, None => return None, }; // The object should only actually contain the string value that was injected let cfg_str = match js_obj.as_string() { Some(cfg_str) => cfg_str, None => return None, }; let render_cfg = match serde_json::from_str::<HashMap<String, String>>(&cfg_str) { Ok(render_cfg) => render_cfg, Err(_) => return None, }; Some(render_cfg) }
identifier_body
shell.rs
request = Request::new_with_str_and_init(url, &opts).map_err(js_err_handler)?; let window = web_sys::window().unwrap(); // Get the response as a future and await it let res_value = JsFuture::from(window.fetch_with_request(&request)) .await .map_err(js_err_handler)?; // Turn that into a proper response object let res: Response = res_value.dyn_into().unwrap(); // If the status is 404, we should return that the request worked but no file existed if res.status() == 404 { return Ok(None); } // Get the body thereof let body_promise = res.text().map_err(js_err_handler)?; let body = JsFuture::from(body_promise).await.map_err(js_err_handler)?; // Convert that into a string (this will be `None` if it wasn't a string in the JS) let body_str = body.as_string(); let body_str = match body_str { Some(body_str) => body_str, None => { return Err(FetchError::NotString { url: url.to_string(), } .into()) } }; // Handle non-200 error codes if res.status() == 200 { Ok(Some(body_str)) } else { Err(FetchError::NotOk { url: url.to_string(), status: res.status(), err: body_str, } .into()) } } /// Gets the render configuration from the JS global variable `__PERSEUS_RENDER_CFG`, which should be inlined by the server. This will /// return `None` on any error (not found, serialization failed, etc.), which should reasonably lead to a `panic!` in the caller. pub fn get_render_cfg() -> Option<HashMap<String, String>> { let val_opt = web_sys::window().unwrap().get("__PERSEUS_RENDER_CFG"); let js_obj = match val_opt { Some(js_obj) => js_obj, None => return None, }; // The object should only actually contain the string value that was injected let cfg_str = match js_obj.as_string() { Some(cfg_str) => cfg_str, None => return None, }; let render_cfg = match serde_json::from_str::<HashMap<String, String>>(&cfg_str) { Ok(render_cfg) => render_cfg, Err(_) => return None, }; Some(render_cfg) } /// Gets the initial state injected by the server, if there was any. This is used to differentiate initial loads from subsequent ones, /// which have different log chains to prevent double-trips (a common SPA problem). pub fn
() -> InitialState { let val_opt = web_sys::window().unwrap().get("__PERSEUS_INITIAL_STATE"); let js_obj = match val_opt { Some(js_obj) => js_obj, None => return InitialState::NotPresent, }; // The object should only actually contain the string value that was injected let state_str = match js_obj.as_string() { Some(state_str) => state_str, None => return InitialState::NotPresent, }; // On the server-side, we encode a `None` value directly (otherwise it will be some convoluted stringified JSON) if state_str == "None" { InitialState::Present(None) } else if state_str.starts_with("error-") { // We strip the prefix and escape any tab/newline control characters (inserted by `fmterr`) // Any others are user-inserted, and this is documented let err_page_data_str = state_str .strip_prefix("error-") .unwrap() .replace("\n", "\\n") .replace("\t", "\\t"); // There will be error page data encoded after `error-` let err_page_data = match serde_json::from_str::<ErrorPageData>(&err_page_data_str) { Ok(render_cfg) => render_cfg, // If there's a serialization error, we'll create a whole new error (500) Err(err) => ErrorPageData { url: "[current]".to_string(), status: 500, err: format!( "couldn't serialize error from server: '{}'", err.to_string() ), }, }; InitialState::Error(err_page_data) } else { InitialState::Present(Some(state_str)) } } /// Marks a checkpoint in the code and alerts any tests that it's been reached by creating an element that represents it. The preferred /// solution would be emitting a DOM event, but the WebDriver specification currently doesn't support waiting on those (go figure). This /// will only create a custom element if the `__PERSEUS_TESTING` JS global variable is set to `true`. /// /// This adds a `<div id="__perseus_checkpoint-<event-name>" />` to the `<div id="__perseus_checkpoints"></div>` element, creating the /// latter if it doesn't exist. Each checkpoint must have a unique name, and if the same checkpoint is executed twice, it'll be added /// with a `-<number>` after it, starting from `0`. In this way, we have a functional checkpoints queue for signalling to test code! /// Note that the checkpoint queue is NOT cleared on subsequent loads. /// /// Note: this is not just for internal usage, it's highly recommended that you use this for your own checkpoints as well! Just make /// sure your tests don't conflict with any internal Perseus checkpoint names (preferably prefix yours with `custom-` or the like, as /// Perseus' checkpoints may change at any time, but won't ever use that namespace). /// /// WARNING: your checkpoint names must not include hyphens! This will result in a `panic!`. pub fn checkpoint(name: &str) { if name.contains('-') { panic!("checkpoint must not contain hyphens, use underscores instead (hyphens are used as an internal delimiter)"); } let val_opt = web_sys::window().unwrap().get("__PERSEUS_TESTING"); let js_obj = match val_opt { Some(js_obj) => js_obj, None => return, }; // The object should only actually contain the string value that was injected let is_testing = match js_obj.as_bool() { Some(cfg_str) => cfg_str, None => return, }; if!is_testing { return; } // If we're here, we're testing // We dispatch a console warning to reduce the likelihood of literal 'testing in prod' crate::web_log!("Perseus is in testing mode. If you're an end-user and seeing this message, please report this as a bug to the website owners!"); // Create a custom element that can be waited for by the WebDriver // This will be removed by the next checkpoint let document = web_sys::window().unwrap().document().unwrap(); let container_opt = document.query_selector("#__perseus_checkpoints").unwrap(); let container: Element; if let Some(container_i) = container_opt { container = container_i; } else { // If the container doesn't exist yet, create it container = document.create_element("div").unwrap(); container.set_id("__perseus_checkpoints"); document .query_selector("body") .unwrap() .unwrap() .append_with_node_1(&container) .unwrap(); } // Get the number of checkpoints that already exist with the same ID // We prevent having to worry about checkpoints whose names are subsets of others by using the hyphen as a delimiter let num_checkpoints = document .query_selector_all(&format!("[id^=__perseus_checkpoint-{}-]", name)) .unwrap() .length(); // Append the new checkpoint let checkpoint = document.create_element("div").unwrap(); checkpoint.set_id(&format!( "__perseus_checkpoint-{}-{}", name, num_checkpoints )); container.append_with_node_1(&checkpoint).unwrap(); } /// A representation of whether or not the initial state was present. If it was, it could be `None` (some templates take no state), and /// if not, then this isn't an initial load, and we need to request the page from the server. It could also be an error that the server /// has rendered. pub enum InitialState { /// A non-error initial state has been injected. Present(Option<String>), /// An initial state ahs been injected that indicates an error. Error(ErrorPageData), /// No initial state has been injected (or if it has, it's been deliberately unset). NotPresent, } /// Fetches the information for the given page and renders it. This should be provided the actual path of the page to render (not just the /// broader template). Asynchronous Wasm is handled here, because only a few cases need it. // TODO handle exceptions higher up pub async fn app_shell( path: String, (template, was_incremental_match): (Template<DomNode>, bool), locale: String, translations_manager: Rc<RefCell<ClientTranslationsManager>>, error_pages: Rc<ErrorPages<DomNode>>, (initial_container, container_rx_elem): (Element, Element), // The container that the server put initial load content into and the reactive container tht we'll actually use ) { checkpoint("app_shell_entry"); // Check if this was an initial load and we already have the state let initial_state = get_initial_state(); match initial_state { // If we do have an initial state, then we have everything we need for immediate hydration (no double trips) // The state is here, and the HTML has already been injected for us (including head metadata) InitialState::Present(state) => { checkpoint("initial_state_present"); // Unset the initial state variable so we perform subsequent renders correctly // This monstrosity is needed until `web-sys` adds a `.set()` method on `Window` Reflect::set( &JsValue::from(web_sys::window().unwrap()), &JsValue::from("__PERSEUS_INITIAL_STATE"), &JsValue::undefined(), ) .unwrap(); // We need to move the server-rendered content from its current container to the reactive container (otherwise Sycamore can't work with it properly) let initial_html = initial_container.inner_html(); container_rx_elem.set_inner_html(&initial_html); initial_container.set_inner_html(""); // Make the initial container invisible initial_container .set_attribute("style", "display: none;") .unwrap(); checkpoint("page_visible"); // Now that the user can see something, we can get the translator let mut translations_manager_mut = translations_manager.borrow_mut(); // This gets an `Rc<Translator>` that references the translations manager, meaning no cloning of translations let translator = translations_manager_mut .get_translator_for_locale(&locale) .await; let translator = match translator { Ok(translator) => translator, Err(err) => { // Directly eliminate the HTML sent in from the server before we render an error page container_rx_elem.set_inner_html(""); match &err { // These errors happen because we couldn't get a translator, so they certainly don't get one ClientError::FetchError(FetchError::NotOk { url, status,.. }) => return error_pages.render_page(url, status, &fmt_err(&err), None, &container_rx_elem), ClientError::FetchError(FetchError::SerFailed { url,.. }) => return error_pages.render_page(url, &500, &fmt_err(&err), None, &container_rx_elem), ClientError::LocaleNotSupported {.. } => return error_pages.render_page(&format!("/{}/...", locale), &404, &fmt_err(&err), None, &container_rx_elem), // No other errors should be returned _ => panic!("expected 'AssetNotOk'/'AssetSerFailed'/'LocaleNotSupported' error, found other unacceptable error") } } }; // Hydrate that static code using the acquired state // BUG (Sycamore): this will double-render if the component is just text (no nodes) sycamore::hydrate_to( // This function provides translator context as needed || template.render_for_template(state, Rc::clone(&translator), false), &container_rx_elem, ); checkpoint("page_interactive"); } // If we have no initial state, we should proceed as usual, fetching the content and state from the server InitialState::NotPresent => { checkpoint("initial_state_not_present"); // If we're getting data about the index page, explicitly set it to that // This can be handled by the Perseus server (and is), but not by static exporting let path = match path.is_empty() { true => "index".to_string(), false => path, }; // Get the static page data let asset_url = format!( "{}/.perseus/page/{}/{}.json?template_name={}&was_incremental_match={}", get_path_prefix_client(), locale, path.to_string(), template.get_path(), was_incremental_match ); // If this doesn't exist, then it's a 404 (we went here by explicit navigation, but it may be an unservable ISR page or the like) let page_data_str = fetch(&asset_url).await; match page_data_str { Ok(page_data_str) => match page_data_str { Some(page_data_str) => { // All good, deserialize the page data let page_data = serde_json::from_str::<PageData>(&page_data_str); match page_data { Ok(page_data) => { // We have the page data ready, render everything // Interpolate the HTML directly into the document (we'll hydrate it later) container_rx_elem.set_inner_html(&page_data.content); // Interpolate the metadata directly into the document's `<head>` // Get the current head let head_elem = web_sys::window() .unwrap() .document() .unwrap() .query_selector("head") .unwrap() .unwrap(); let head_html = head_elem.inner_html(); // We'll assume that there's already previously interpolated head in addition to the hardcoded stuff, but it will be separated by the server-injected delimiter comment // Thus, we replace the stuff after that delimiter comment with the new head let head_parts: Vec<&str> = head_html .split("<!--PERSEUS_INTERPOLATED_HEAD_BEGINS-->") .collect(); let new_head = format!( "{}\n<!--PERSEUS_INTERPOLATED_HEAD_BEGINS-->\n{}", head_parts[0], &page_data.head ); head_elem.set_inner_html(&new_head); checkpoint("page_visible"); // Now that the user can see something, we can get the translator let mut translations_manager_mut = translations_manager.borrow_mut(); // This gets an `Rc<Translator>` that references the translations manager, meaning no cloning of translations let translator = translations_manager_mut .get_translator_for_locale(&locale) .await; let translator = match translator { Ok(translator) => translator, Err(err) => match &err { // These errors happen because we couldn't get a translator, so they certainly don't get one ClientError::FetchError(FetchError::NotOk { url, status,.. }) => return error_pages.render_page(url, status, &fmt_err(&err), None, &container_rx_elem), ClientError::FetchError(FetchError::SerFailed { url,.. }) => return error_pages.render_page(url, &500, &fmt_err(&err), None, &container_rx_elem), ClientError::LocaleNotSupported { locale } => return error_pages.render_page(&format!("/{}/...", locale), &404, &fmt_err(&err), None, &container_rx_elem), // No other errors should be returned _ => panic!("expected 'AssetNotOk'/'AssetSerFailed'/'LocaleNotSupported' error, found other unacceptable error") } }; // Hydrate that static code using the acquired state // BUG (Sycamore): this will double-render if the component is just text (no nodes) sycamore::hydrate_to( // This function provides translator context as needed || { template.render_for_template( page_data.state, Rc::clone(&translator), false, ) }, &container_rx_elem, ); checkpoint("page_interactive"); } // If the page failed to serialize, an exception has occurred Err(err) => panic!("page data couldn't be serialized: '{}'", err), }; } // No translators ready yet None => error_pages.render_page( &asset_url, &404, "page not found", None, &container_rx_elem
get_initial_state
identifier_name
shell.rs
let request = Request::new_with_str_and_init(url, &opts).map_err(js_err_handler)?; let window = web_sys::window().unwrap(); // Get the response as a future and await it let res_value = JsFuture::from(window.fetch_with_request(&request)) .await .map_err(js_err_handler)?; // Turn that into a proper response object let res: Response = res_value.dyn_into().unwrap(); // If the status is 404, we should return that the request worked but no file existed if res.status() == 404 { return Ok(None); } // Get the body thereof let body_promise = res.text().map_err(js_err_handler)?; let body = JsFuture::from(body_promise).await.map_err(js_err_handler)?; // Convert that into a string (this will be `None` if it wasn't a string in the JS) let body_str = body.as_string(); let body_str = match body_str { Some(body_str) => body_str, None => { return Err(FetchError::NotString { url: url.to_string(), } .into()) } }; // Handle non-200 error codes if res.status() == 200 { Ok(Some(body_str)) } else { Err(FetchError::NotOk { url: url.to_string(), status: res.status(), err: body_str, } .into()) } } /// Gets the render configuration from the JS global variable `__PERSEUS_RENDER_CFG`, which should be inlined by the server. This will /// return `None` on any error (not found, serialization failed, etc.), which should reasonably lead to a `panic!` in the caller. pub fn get_render_cfg() -> Option<HashMap<String, String>> { let val_opt = web_sys::window().unwrap().get("__PERSEUS_RENDER_CFG"); let js_obj = match val_opt { Some(js_obj) => js_obj, None => return None, }; // The object should only actually contain the string value that was injected let cfg_str = match js_obj.as_string() { Some(cfg_str) => cfg_str, None => return None, }; let render_cfg = match serde_json::from_str::<HashMap<String, String>>(&cfg_str) { Ok(render_cfg) => render_cfg, Err(_) => return None, }; Some(render_cfg) } /// Gets the initial state injected by the server, if there was any. This is used to differentiate initial loads from subsequent ones, /// which have different log chains to prevent double-trips (a common SPA problem). pub fn get_initial_state() -> InitialState { let val_opt = web_sys::window().unwrap().get("__PERSEUS_INITIAL_STATE"); let js_obj = match val_opt { Some(js_obj) => js_obj, None => return InitialState::NotPresent, }; // The object should only actually contain the string value that was injected let state_str = match js_obj.as_string() { Some(state_str) => state_str, None => return InitialState::NotPresent, }; // On the server-side, we encode a `None` value directly (otherwise it will be some convoluted stringified JSON) if state_str == "None" { InitialState::Present(None) } else if state_str.starts_with("error-") { // We strip the prefix and escape any tab/newline control characters (inserted by `fmterr`) // Any others are user-inserted, and this is documented let err_page_data_str = state_str .strip_prefix("error-") .unwrap() .replace("\n", "\\n") .replace("\t", "\\t"); // There will be error page data encoded after `error-` let err_page_data = match serde_json::from_str::<ErrorPageData>(&err_page_data_str) { Ok(render_cfg) => render_cfg, // If there's a serialization error, we'll create a whole new error (500) Err(err) => ErrorPageData { url: "[current]".to_string(), status: 500, err: format!( "couldn't serialize error from server: '{}'", err.to_string() ), }, }; InitialState::Error(err_page_data) } else { InitialState::Present(Some(state_str)) } } /// Marks a checkpoint in the code and alerts any tests that it's been reached by creating an element that represents it. The preferred /// solution would be emitting a DOM event, but the WebDriver specification currently doesn't support waiting on those (go figure). This /// will only create a custom element if the `__PERSEUS_TESTING` JS global variable is set to `true`. /// /// This adds a `<div id="__perseus_checkpoint-<event-name>" />` to the `<div id="__perseus_checkpoints"></div>` element, creating the /// latter if it doesn't exist. Each checkpoint must have a unique name, and if the same checkpoint is executed twice, it'll be added /// with a `-<number>` after it, starting from `0`. In this way, we have a functional checkpoints queue for signalling to test code! /// Note that the checkpoint queue is NOT cleared on subsequent loads. /// /// Note: this is not just for internal usage, it's highly recommended that you use this for your own checkpoints as well! Just make /// sure your tests don't conflict with any internal Perseus checkpoint names (preferably prefix yours with `custom-` or the like, as /// Perseus' checkpoints may change at any time, but won't ever use that namespace). /// /// WARNING: your checkpoint names must not include hyphens! This will result in a `panic!`. pub fn checkpoint(name: &str) { if name.contains('-') { panic!("checkpoint must not contain hyphens, use underscores instead (hyphens are used as an internal delimiter)"); } let val_opt = web_sys::window().unwrap().get("__PERSEUS_TESTING"); let js_obj = match val_opt { Some(js_obj) => js_obj, None => return, }; // The object should only actually contain the string value that was injected let is_testing = match js_obj.as_bool() { Some(cfg_str) => cfg_str, None => return, }; if!is_testing { return; } // If we're here, we're testing // We dispatch a console warning to reduce the likelihood of literal 'testing in prod' crate::web_log!("Perseus is in testing mode. If you're an end-user and seeing this message, please report this as a bug to the website owners!"); // Create a custom element that can be waited for by the WebDriver // This will be removed by the next checkpoint let document = web_sys::window().unwrap().document().unwrap(); let container_opt = document.query_selector("#__perseus_checkpoints").unwrap(); let container: Element; if let Some(container_i) = container_opt { container = container_i; } else { // If the container doesn't exist yet, create it container = document.create_element("div").unwrap(); container.set_id("__perseus_checkpoints"); document .query_selector("body") .unwrap() .unwrap() .append_with_node_1(&container) .unwrap(); } // Get the number of checkpoints that already exist with the same ID // We prevent having to worry about checkpoints whose names are subsets of others by using the hyphen as a delimiter let num_checkpoints = document .query_selector_all(&format!("[id^=__perseus_checkpoint-{}-]", name)) .unwrap() .length(); // Append the new checkpoint let checkpoint = document.create_element("div").unwrap(); checkpoint.set_id(&format!( "__perseus_checkpoint-{}-{}", name, num_checkpoints )); container.append_with_node_1(&checkpoint).unwrap(); }
/// A representation of whether or not the initial state was present. If it was, it could be `None` (some templates take no state), and /// if not, then this isn't an initial load, and we need to request the page from the server. It could also be an error that the server /// has rendered. pub enum InitialState { /// A non-error initial state has been injected. Present(Option<String>), /// An initial state ahs been injected that indicates an error. Error(ErrorPageData), /// No initial state has been injected (or if it has, it's been deliberately unset). NotPresent, } /// Fetches the information for the given page and renders it. This should be provided the actual path of the page to render (not just the /// broader template). Asynchronous Wasm is handled here, because only a few cases need it. // TODO handle exceptions higher up pub async fn app_shell( path: String, (template, was_incremental_match): (Template<DomNode>, bool), locale: String, translations_manager: Rc<RefCell<ClientTranslationsManager>>, error_pages: Rc<ErrorPages<DomNode>>, (initial_container, container_rx_elem): (Element, Element), // The container that the server put initial load content into and the reactive container tht we'll actually use ) { checkpoint("app_shell_entry"); // Check if this was an initial load and we already have the state let initial_state = get_initial_state(); match initial_state { // If we do have an initial state, then we have everything we need for immediate hydration (no double trips) // The state is here, and the HTML has already been injected for us (including head metadata) InitialState::Present(state) => { checkpoint("initial_state_present"); // Unset the initial state variable so we perform subsequent renders correctly // This monstrosity is needed until `web-sys` adds a `.set()` method on `Window` Reflect::set( &JsValue::from(web_sys::window().unwrap()), &JsValue::from("__PERSEUS_INITIAL_STATE"), &JsValue::undefined(), ) .unwrap(); // We need to move the server-rendered content from its current container to the reactive container (otherwise Sycamore can't work with it properly) let initial_html = initial_container.inner_html(); container_rx_elem.set_inner_html(&initial_html); initial_container.set_inner_html(""); // Make the initial container invisible initial_container .set_attribute("style", "display: none;") .unwrap(); checkpoint("page_visible"); // Now that the user can see something, we can get the translator let mut translations_manager_mut = translations_manager.borrow_mut(); // This gets an `Rc<Translator>` that references the translations manager, meaning no cloning of translations let translator = translations_manager_mut .get_translator_for_locale(&locale) .await; let translator = match translator { Ok(translator) => translator, Err(err) => { // Directly eliminate the HTML sent in from the server before we render an error page container_rx_elem.set_inner_html(""); match &err { // These errors happen because we couldn't get a translator, so they certainly don't get one ClientError::FetchError(FetchError::NotOk { url, status,.. }) => return error_pages.render_page(url, status, &fmt_err(&err), None, &container_rx_elem), ClientError::FetchError(FetchError::SerFailed { url,.. }) => return error_pages.render_page(url, &500, &fmt_err(&err), None, &container_rx_elem), ClientError::LocaleNotSupported {.. } => return error_pages.render_page(&format!("/{}/...", locale), &404, &fmt_err(&err), None, &container_rx_elem), // No other errors should be returned _ => panic!("expected 'AssetNotOk'/'AssetSerFailed'/'LocaleNotSupported' error, found other unacceptable error") } } }; // Hydrate that static code using the acquired state // BUG (Sycamore): this will double-render if the component is just text (no nodes) sycamore::hydrate_to( // This function provides translator context as needed || template.render_for_template(state, Rc::clone(&translator), false), &container_rx_elem, ); checkpoint("page_interactive"); } // If we have no initial state, we should proceed as usual, fetching the content and state from the server InitialState::NotPresent => { checkpoint("initial_state_not_present"); // If we're getting data about the index page, explicitly set it to that // This can be handled by the Perseus server (and is), but not by static exporting let path = match path.is_empty() { true => "index".to_string(), false => path, }; // Get the static page data let asset_url = format!( "{}/.perseus/page/{}/{}.json?template_name={}&was_incremental_match={}", get_path_prefix_client(), locale, path.to_string(), template.get_path(), was_incremental_match ); // If this doesn't exist, then it's a 404 (we went here by explicit navigation, but it may be an unservable ISR page or the like) let page_data_str = fetch(&asset_url).await; match page_data_str { Ok(page_data_str) => match page_data_str { Some(page_data_str) => { // All good, deserialize the page data let page_data = serde_json::from_str::<PageData>(&page_data_str); match page_data { Ok(page_data) => { // We have the page data ready, render everything // Interpolate the HTML directly into the document (we'll hydrate it later) container_rx_elem.set_inner_html(&page_data.content); // Interpolate the metadata directly into the document's `<head>` // Get the current head let head_elem = web_sys::window() .unwrap() .document() .unwrap() .query_selector("head") .unwrap() .unwrap(); let head_html = head_elem.inner_html(); // We'll assume that there's already previously interpolated head in addition to the hardcoded stuff, but it will be separated by the server-injected delimiter comment // Thus, we replace the stuff after that delimiter comment with the new head let head_parts: Vec<&str> = head_html .split("<!--PERSEUS_INTERPOLATED_HEAD_BEGINS-->") .collect(); let new_head = format!( "{}\n<!--PERSEUS_INTERPOLATED_HEAD_BEGINS-->\n{}", head_parts[0], &page_data.head ); head_elem.set_inner_html(&new_head); checkpoint("page_visible"); // Now that the user can see something, we can get the translator let mut translations_manager_mut = translations_manager.borrow_mut(); // This gets an `Rc<Translator>` that references the translations manager, meaning no cloning of translations let translator = translations_manager_mut .get_translator_for_locale(&locale) .await; let translator = match translator { Ok(translator) => translator, Err(err) => match &err { // These errors happen because we couldn't get a translator, so they certainly don't get one ClientError::FetchError(FetchError::NotOk { url, status,.. }) => return error_pages.render_page(url, status, &fmt_err(&err), None, &container_rx_elem), ClientError::FetchError(FetchError::SerFailed { url,.. }) => return error_pages.render_page(url, &500, &fmt_err(&err), None, &container_rx_elem), ClientError::LocaleNotSupported { locale } => return error_pages.render_page(&format!("/{}/...", locale), &404, &fmt_err(&err), None, &container_rx_elem), // No other errors should be returned _ => panic!("expected 'AssetNotOk'/'AssetSerFailed'/'LocaleNotSupported' error, found other unacceptable error") } }; // Hydrate that static code using the acquired state // BUG (Sycamore): this will double-render if the component is just text (no nodes) sycamore::hydrate_to( // This function provides translator context as needed || { template.render_for_template( page_data.state, Rc::clone(&translator), false, ) }, &container_rx_elem, ); checkpoint("page_interactive"); } // If the page failed to serialize, an exception has occurred Err(err) => panic!("page data couldn't be serialized: '{}'", err), }; } // No translators ready yet None => error_pages.render_page( &asset_url, &404, "page not found", None, &container_rx_elem,
random_line_split
lib.rs
//! An Entity Component System for game development. //! //! Currently used for personal use (for a roguelike game), this library is highly unstable, and a WIP. #![allow(dead_code)] #![feature(append,drain)] use std::iter; use std::collections::HashMap; use std::ops::{Index, IndexMut}; use std::collections::hash_map::Entry::{Occupied, Vacant}; pub mod component_presence; pub mod family; pub mod builder; pub mod event; pub mod behavior; use family::{FamilyDataHolder, FamilyMap}; use event::{EventDataHolder}; pub use event::EventManager; pub use behavior::BehaviorManager; pub use behavior::Behavior; pub use component_presence::ComponentPresence; /// Type Entity is simply an ID used as indexes. pub type Entity = u32; /// The components macro defines all the structs and traits that manage /// the component part of the ECS. #[macro_export] macro_rules! components { ($data:ident: $([$access:ident, $ty:ty]),+ ) => { use $crate::component_presence::ComponentPresence; use $crate::component_presence::ComponentPresence::*; use $crate::{EntityDataHolder, Component, Entity, ComponentData}; use $crate::family::{FamilyMap}; use std::fmt; pub struct $data { pub components: Vec<&'static str>, pub families: Vec<&'static str>, $( pub $access: ComponentPresence<$ty>, )+ } impl $data { pub fn new_empty() -> $data { $data { components: Vec::new(), families: Vec::new(), $( $access: Lacks, )+ } } } impl fmt::Debug for $data { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let mut b = fmt.debug_struct("EntityData"); b.field("has components", &self.components); b.field("belongs to families", &self.families); /*$( if self.$access.has_it() { b.field(stringify!($access), &self.$access); } )+*/ b.finish() } } impl EntityDataHolder for $data { fn new() -> Self { $data::new_empty() } fn match_families(&self, families: &FamilyMap) -> Vec<&'static str> { let mut v: Vec<&str> = vec!(); // Tuple has the requirements/forbidden vectors for (family, tuple) in families { if $crate::family::matcher(tuple, &self.components) { v.push(family) } } v } fn set_families(&mut self, families: Vec<&'static str>) { self.families = families; } fn belongs_to_family(&self, family: &str) -> bool { self.families.contains(&family) } fn families(&self) -> Vec<&'static str> { self.families.clone() } } $( impl Component<$data> for $ty { fn add_to(self, ent: Entity, data: &mut ComponentData<$data>) { let ent_data: &mut $data = data.components.get_mut(&ent).expect("no entity"); ent_data.components.push(stringify!($access)); ent_data.$access = Has(self); } } )+ } } /// This is a marker trait to be used by the `components!` macro. /// /// This trait is implemented by `EntityData` which is a struct generated /// by the `components!` macro. /// /// `EntityData` will be of the form: /// /// ``` /// struct EntityData { /// component1: ComponentPresence<Component1>, /// component2: ComponentPresence<Component2>, /// //etc... /// } /// ``` /// /// So it will have one field per component defined in the call to `components!` /// You'll access these fields directly when indexing the `data` field of the `EntityManager` pub trait EntityDataHolder { fn new() -> Self; /// Takes a map of all the defined families, /// and returns the families that match this entity. fn match_families(&self, &FamilyMap) -> Vec<&'static str>; /// Sets the families this entity belongs to to `families` fn set_families(&mut self, Vec<&'static str>); fn belongs_to_family(&self, &'static str) -> bool; /// Gets the known families this ent belongs to. fn families(&self) -> Vec<&'static str>; } /// ComponentData knows which entities have which components. pub struct ComponentData<D: EntityDataHolder> { /// components holds the components owned by a certain entity. pub components: HashMap<Entity, D>, /// Family to list of entities. pub families: HashMap<&'static str, Vec<Entity>>, } /// This trait marks a struct as a component. (Automatically handled by macro `components!`) /// /// It should implement the `add_to` function, which is automatically generated /// by the `components!` macro. pub trait Component<D: EntityDataHolder> { /// Adds self to the specified entity. Called by the `EntityManager` fn add_to(self, ent: Entity, data: &mut ComponentData<D>); } impl<D: EntityDataHolder> ComponentData<D> { pub fn new() -> ComponentData<D> { ComponentData { components: HashMap::new(), families: HashMap::new(), } } pub fn get(&self, ent: &Entity) -> Option<&D> { self.components.get(ent) } pub fn get_mut(&mut self, ent: &Entity) -> Option<&mut D> { self.components.get_mut(ent) } pub fn create_component_data_for(&mut self, ent: Entity) { self.components.insert(ent, D::new()); } pub fn clear_family_data_for(&mut self, ent: Entity) { for family in self[ent].families() { self.remove_from_family(family, ent); debug_assert!(!self.families[family].contains(&ent)) } } pub fn
(&mut self, ent: Entity) { self.clear_family_data_for(ent); self.components.remove(&ent); } fn remove_from_family(&mut self, family: &str, ent: Entity) { let mut idx: Option<usize> = None; { let vec = self.families.get_mut(family).expect("No such family"); let op = vec.iter().enumerate().find(|&(_,e)| *e == ent); idx = Some(op.expect("Entity not found in this family").0); } if let Some(idx) = idx { self.families.get_mut(family).unwrap().swap_remove(idx); } else { panic!("Entity not found for family"); } } pub fn set_family_relation(&mut self, family: &'static str, ent: Entity) { match self.families.entry(family) { Vacant(entry) => {entry.insert(vec!(ent));}, Occupied(entry) => { let v = entry.into_mut(); if v.contains(&ent) { return; } v.push(ent); }, } } pub fn members_of(&self, family: &'static str) -> Vec<Entity> { match self.families.get(family) { Some(vec) => vec.clone(), None => vec!(), } } pub fn any_member_of(&self, family: &'static str) -> bool { !self.families.get(family).expect("no such family").is_empty() } } impl<D: EntityDataHolder> Index<Entity> for ComponentData<D> { type Output = D; fn index(&self, index: Entity) -> &D { &self.components.get(&index).expect(&format!("no entity {:?}", index)) } } impl<D: EntityDataHolder> IndexMut<Entity> for ComponentData<D> { fn index_mut(&mut self, index: Entity) -> &mut D { self.components.get_mut(&index).expect("no entity") } } /// The `EntityManager` type manages all the entities. /// /// It is in charge of creating and destroying entities. /// It also takes care of adding or removing components, through the `ComponentData` it contains. /// /// # Examples /// /// Creating a new manager, and adding some (predefined) components to a new entity. /// /// ``` /// let mut manager = EntityManager::new(); /// let ent = manager.new_entity(); /// manager.add_component_to(ent, Position{x: 1, y: 2}); /// ``` pub struct EntityManager<D: EntityDataHolder, F: FamilyDataHolder> { next_idx: usize, reusable_idxs: Vec<usize>, active: Vec<bool>, pub data: ComponentData<D>, /// Contains a list of all defined families, along with its requirements. families: F, } impl<D: EntityDataHolder, F: FamilyDataHolder> EntityManager<D, F> { /// Creates a new EntityManager pub fn new() -> EntityManager<D, F> { EntityManager{ next_idx: 0, reusable_idxs: vec!(), active: vec!(), data: ComponentData::new(), families: F::new(), } } /// Creates a new entity, assigning it an unused ID, returning that ID for further use. pub fn new_entity(&mut self) -> Entity { let idx = match self.reusable_idxs.pop() { None => { let idx = self.next_idx; self.next_idx += 1; idx } Some(idx) => idx, }; // Extend the vec if the idx is bigger. if self.active.len() <= idx { let padding = idx + 1 - self.active.len(); self.active.extend(iter::repeat(false).take(padding)); debug_assert!(self.active.len() == idx+1); } debug_assert!(!self.active[idx]); self.active[idx] = true; let ent = idx as Entity; self.data.create_component_data_for(ent); ent } /// Deletes the entity, removes all data related to it. /// /// Returns a list of events that were related to it, in case you need to do some clean up with them. pub fn delete_entity<Event>(&mut self, ent: Entity, events: &mut EventManager<Event>) -> Vec<Event> where Event: event::EventDataHolder { self.delete_entity_ignore_events(ent); events.clear_events_for(ent) } pub fn delete_entity_ignore_events(&mut self, ent: Entity) { let idx = ent as usize; assert!(self.active[idx]); self.reusable_idxs.push(idx); self.active[idx] = false; self.data.delete_component_data_for(ent); } pub fn build_ent<'a, A,B: EventDataHolder>(&'a mut self, ent: Entity, processor: &'a mut BehaviorManager<A,B>) -> EntityBuilder<D,A,B> { EntityBuilder::new(ent, processor, &mut self.data, self.families.all_families()) } /// Adds the specified component to the entity. pub fn add_component_to<A,B:EventDataHolder,C: Component<D>>(&mut self, e: Entity, c: C, processor: &mut BehaviorManager<A,B>) { //c.add_to(e, &mut self.data); self.build_ent(e, processor).add_component(c).finalize(); } } /// Used by `EntityManager` to add components to an Entity. /// /// An object of this type is obtained by calling `add_component` from an EntityManager pub struct EntityBuilder<'a, EntData: 'a + EntityDataHolder, T: 'a, Ev: event::EventDataHolder + 'a> { data: &'a mut ComponentData<EntData>, families: &'a FamilyMap, processor: &'a mut BehaviorManager<T,Ev>, ent: Entity, } impl<'a, EntData: 'a + EntityDataHolder, T, Ev: event::EventDataHolder> EntityBuilder<'a, EntData, T, Ev> { pub fn new(ent: Entity, processor: &'a mut BehaviorManager<T,Ev>, data: &'a mut ComponentData<EntData>, families: &'a FamilyMap) -> EntityBuilder<'a, EntData, T, Ev> { EntityBuilder { data: data, families: families, processor: processor, ent: ent, } } pub fn add_component<Comp: Component<EntData>>(self, comp: Comp) -> EntityBuilder<'a, EntData, T, Ev> { comp.add_to(self.ent, self.data); self } pub fn finalize(mut self) -> Entity { self.add_all_related_data(); self.ent } pub fn add_all_related_data(&mut self) { let mut families: Vec<&str> = self.data[self.ent].match_families(self.families); families.sort(); families.dedup(); // Clean up current component data, self.data.clear_family_data_for(self.ent); // Give the ComponentDataHolder information about this entities families. for family in families.iter() { self.data.set_family_relation(family, self.ent); } if!self.processor.valid_behaviors_for(families.clone()).is_empty() { self.processor.add_processable(self.ent); } // Give this EntityDataHolder a list of which families this entity has. self.data[self.ent].set_families(families); } } /* fn main() { println!("Hello, world!"); let mut manager = EntityManager::new(); let ent = manager.new_entity(); manager.add_component_to(ent, Position{x:1, y:2}); println!("pos: {:?}", manager.data[ent].position.x); manager.data[ent].position.x += 5; println!("pos: {:?}", manager.data[ent].position.x); println!("has glyph? {:?}", manager.data[ent].glyph.has_it()); } */
delete_component_data_for
identifier_name
lib.rs
//! An Entity Component System for game development. //! //! Currently used for personal use (for a roguelike game), this library is highly unstable, and a WIP. #![allow(dead_code)] #![feature(append,drain)] use std::iter; use std::collections::HashMap; use std::ops::{Index, IndexMut}; use std::collections::hash_map::Entry::{Occupied, Vacant}; pub mod component_presence; pub mod family; pub mod builder; pub mod event; pub mod behavior; use family::{FamilyDataHolder, FamilyMap}; use event::{EventDataHolder}; pub use event::EventManager; pub use behavior::BehaviorManager; pub use behavior::Behavior; pub use component_presence::ComponentPresence; /// Type Entity is simply an ID used as indexes. pub type Entity = u32; /// The components macro defines all the structs and traits that manage /// the component part of the ECS. #[macro_export] macro_rules! components { ($data:ident: $([$access:ident, $ty:ty]),+ ) => { use $crate::component_presence::ComponentPresence; use $crate::component_presence::ComponentPresence::*; use $crate::{EntityDataHolder, Component, Entity, ComponentData}; use $crate::family::{FamilyMap}; use std::fmt; pub struct $data { pub components: Vec<&'static str>, pub families: Vec<&'static str>, $( pub $access: ComponentPresence<$ty>, )+ } impl $data { pub fn new_empty() -> $data { $data { components: Vec::new(), families: Vec::new(), $( $access: Lacks, )+ } } } impl fmt::Debug for $data { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let mut b = fmt.debug_struct("EntityData"); b.field("has components", &self.components); b.field("belongs to families", &self.families); /*$( if self.$access.has_it() { b.field(stringify!($access), &self.$access); } )+*/ b.finish() } } impl EntityDataHolder for $data { fn new() -> Self { $data::new_empty() } fn match_families(&self, families: &FamilyMap) -> Vec<&'static str> { let mut v: Vec<&str> = vec!(); // Tuple has the requirements/forbidden vectors for (family, tuple) in families { if $crate::family::matcher(tuple, &self.components) { v.push(family) } } v } fn set_families(&mut self, families: Vec<&'static str>) { self.families = families; } fn belongs_to_family(&self, family: &str) -> bool { self.families.contains(&family) } fn families(&self) -> Vec<&'static str> { self.families.clone() } } $( impl Component<$data> for $ty { fn add_to(self, ent: Entity, data: &mut ComponentData<$data>) { let ent_data: &mut $data = data.components.get_mut(&ent).expect("no entity"); ent_data.components.push(stringify!($access)); ent_data.$access = Has(self); } } )+ } } /// This is a marker trait to be used by the `components!` macro. /// /// This trait is implemented by `EntityData` which is a struct generated /// by the `components!` macro. /// /// `EntityData` will be of the form: /// /// ``` /// struct EntityData { /// component1: ComponentPresence<Component1>, /// component2: ComponentPresence<Component2>, /// //etc... /// } /// ``` /// /// So it will have one field per component defined in the call to `components!` /// You'll access these fields directly when indexing the `data` field of the `EntityManager` pub trait EntityDataHolder { fn new() -> Self; /// Takes a map of all the defined families, /// and returns the families that match this entity. fn match_families(&self, &FamilyMap) -> Vec<&'static str>; /// Sets the families this entity belongs to to `families` fn set_families(&mut self, Vec<&'static str>); fn belongs_to_family(&self, &'static str) -> bool; /// Gets the known families this ent belongs to. fn families(&self) -> Vec<&'static str>; } /// ComponentData knows which entities have which components. pub struct ComponentData<D: EntityDataHolder> { /// components holds the components owned by a certain entity. pub components: HashMap<Entity, D>, /// Family to list of entities. pub families: HashMap<&'static str, Vec<Entity>>, } /// This trait marks a struct as a component. (Automatically handled by macro `components!`) /// /// It should implement the `add_to` function, which is automatically generated /// by the `components!` macro. pub trait Component<D: EntityDataHolder> { /// Adds self to the specified entity. Called by the `EntityManager` fn add_to(self, ent: Entity, data: &mut ComponentData<D>); } impl<D: EntityDataHolder> ComponentData<D> { pub fn new() -> ComponentData<D> { ComponentData { components: HashMap::new(), families: HashMap::new(), } } pub fn get(&self, ent: &Entity) -> Option<&D> { self.components.get(ent) } pub fn get_mut(&mut self, ent: &Entity) -> Option<&mut D> { self.components.get_mut(ent) } pub fn create_component_data_for(&mut self, ent: Entity) { self.components.insert(ent, D::new()); } pub fn clear_family_data_for(&mut self, ent: Entity) { for family in self[ent].families() { self.remove_from_family(family, ent); debug_assert!(!self.families[family].contains(&ent)) } } pub fn delete_component_data_for(&mut self, ent: Entity) { self.clear_family_data_for(ent); self.components.remove(&ent); } fn remove_from_family(&mut self, family: &str, ent: Entity) { let mut idx: Option<usize> = None; { let vec = self.families.get_mut(family).expect("No such family"); let op = vec.iter().enumerate().find(|&(_,e)| *e == ent); idx = Some(op.expect("Entity not found in this family").0); } if let Some(idx) = idx { self.families.get_mut(family).unwrap().swap_remove(idx); } else { panic!("Entity not found for family"); } } pub fn set_family_relation(&mut self, family: &'static str, ent: Entity) { match self.families.entry(family) { Vacant(entry) => {entry.insert(vec!(ent));}, Occupied(entry) => { let v = entry.into_mut(); if v.contains(&ent) { return; } v.push(ent); }, } } pub fn members_of(&self, family: &'static str) -> Vec<Entity> { match self.families.get(family) { Some(vec) => vec.clone(), None => vec!(), } } pub fn any_member_of(&self, family: &'static str) -> bool { !self.families.get(family).expect("no such family").is_empty() } } impl<D: EntityDataHolder> Index<Entity> for ComponentData<D> { type Output = D; fn index(&self, index: Entity) -> &D { &self.components.get(&index).expect(&format!("no entity {:?}", index)) } } impl<D: EntityDataHolder> IndexMut<Entity> for ComponentData<D> { fn index_mut(&mut self, index: Entity) -> &mut D { self.components.get_mut(&index).expect("no entity") } } /// The `EntityManager` type manages all the entities. /// /// It is in charge of creating and destroying entities. /// It also takes care of adding or removing components, through the `ComponentData` it contains. /// /// # Examples /// /// Creating a new manager, and adding some (predefined) components to a new entity. /// /// ``` /// let mut manager = EntityManager::new(); /// let ent = manager.new_entity(); /// manager.add_component_to(ent, Position{x: 1, y: 2}); /// ``` pub struct EntityManager<D: EntityDataHolder, F: FamilyDataHolder> { next_idx: usize, reusable_idxs: Vec<usize>, active: Vec<bool>, pub data: ComponentData<D>, /// Contains a list of all defined families, along with its requirements. families: F, } impl<D: EntityDataHolder, F: FamilyDataHolder> EntityManager<D, F> { /// Creates a new EntityManager pub fn new() -> EntityManager<D, F> { EntityManager{ next_idx: 0, reusable_idxs: vec!(), active: vec!(), data: ComponentData::new(), families: F::new(), } } /// Creates a new entity, assigning it an unused ID, returning that ID for further use. pub fn new_entity(&mut self) -> Entity { let idx = match self.reusable_idxs.pop() { None => { let idx = self.next_idx; self.next_idx += 1; idx } Some(idx) => idx, }; // Extend the vec if the idx is bigger. if self.active.len() <= idx { let padding = idx + 1 - self.active.len(); self.active.extend(iter::repeat(false).take(padding)); debug_assert!(self.active.len() == idx+1); } debug_assert!(!self.active[idx]); self.active[idx] = true; let ent = idx as Entity; self.data.create_component_data_for(ent); ent } /// Deletes the entity, removes all data related to it. /// /// Returns a list of events that were related to it, in case you need to do some clean up with them. pub fn delete_entity<Event>(&mut self, ent: Entity, events: &mut EventManager<Event>) -> Vec<Event> where Event: event::EventDataHolder { self.delete_entity_ignore_events(ent); events.clear_events_for(ent) } pub fn delete_entity_ignore_events(&mut self, ent: Entity) { let idx = ent as usize; assert!(self.active[idx]); self.reusable_idxs.push(idx); self.active[idx] = false; self.data.delete_component_data_for(ent); } pub fn build_ent<'a, A,B: EventDataHolder>(&'a mut self, ent: Entity, processor: &'a mut BehaviorManager<A,B>) -> EntityBuilder<D,A,B> { EntityBuilder::new(ent, processor, &mut self.data, self.families.all_families()) } /// Adds the specified component to the entity. pub fn add_component_to<A,B:EventDataHolder,C: Component<D>>(&mut self, e: Entity, c: C, processor: &mut BehaviorManager<A,B>) { //c.add_to(e, &mut self.data); self.build_ent(e, processor).add_component(c).finalize(); } } /// Used by `EntityManager` to add components to an Entity. /// /// An object of this type is obtained by calling `add_component` from an EntityManager pub struct EntityBuilder<'a, EntData: 'a + EntityDataHolder, T: 'a, Ev: event::EventDataHolder + 'a> { data: &'a mut ComponentData<EntData>, families: &'a FamilyMap, processor: &'a mut BehaviorManager<T,Ev>, ent: Entity, } impl<'a, EntData: 'a + EntityDataHolder, T, Ev: event::EventDataHolder> EntityBuilder<'a, EntData, T, Ev> { pub fn new(ent: Entity, processor: &'a mut BehaviorManager<T,Ev>, data: &'a mut ComponentData<EntData>, families: &'a FamilyMap) -> EntityBuilder<'a, EntData, T, Ev> { EntityBuilder { data: data, families: families, processor: processor, ent: ent, } } pub fn add_component<Comp: Component<EntData>>(self, comp: Comp) -> EntityBuilder<'a, EntData, T, Ev> { comp.add_to(self.ent, self.data); self } pub fn finalize(mut self) -> Entity { self.add_all_related_data(); self.ent } pub fn add_all_related_data(&mut self) { let mut families: Vec<&str> = self.data[self.ent].match_families(self.families); families.sort(); families.dedup(); // Clean up current component data, self.data.clear_family_data_for(self.ent); // Give the ComponentDataHolder information about this entities families. for family in families.iter() { self.data.set_family_relation(family, self.ent); } if!self.processor.valid_behaviors_for(families.clone()).is_empty()
// Give this EntityDataHolder a list of which families this entity has. self.data[self.ent].set_families(families); } } /* fn main() { println!("Hello, world!"); let mut manager = EntityManager::new(); let ent = manager.new_entity(); manager.add_component_to(ent, Position{x:1, y:2}); println!("pos: {:?}", manager.data[ent].position.x); manager.data[ent].position.x += 5; println!("pos: {:?}", manager.data[ent].position.x); println!("has glyph? {:?}", manager.data[ent].glyph.has_it()); } */
{ self.processor.add_processable(self.ent); }
conditional_block
lib.rs
//! An Entity Component System for game development. //! //! Currently used for personal use (for a roguelike game), this library is highly unstable, and a WIP. #![allow(dead_code)] #![feature(append,drain)] use std::iter; use std::collections::HashMap; use std::ops::{Index, IndexMut}; use std::collections::hash_map::Entry::{Occupied, Vacant}; pub mod component_presence; pub mod family; pub mod builder; pub mod event; pub mod behavior; use family::{FamilyDataHolder, FamilyMap}; use event::{EventDataHolder}; pub use event::EventManager; pub use behavior::BehaviorManager; pub use behavior::Behavior; pub use component_presence::ComponentPresence; /// Type Entity is simply an ID used as indexes. pub type Entity = u32; /// The components macro defines all the structs and traits that manage /// the component part of the ECS. #[macro_export] macro_rules! components { ($data:ident: $([$access:ident, $ty:ty]),+ ) => { use $crate::component_presence::ComponentPresence; use $crate::component_presence::ComponentPresence::*; use $crate::{EntityDataHolder, Component, Entity, ComponentData}; use $crate::family::{FamilyMap}; use std::fmt; pub struct $data { pub components: Vec<&'static str>, pub families: Vec<&'static str>, $( pub $access: ComponentPresence<$ty>, )+ } impl $data { pub fn new_empty() -> $data { $data { components: Vec::new(), families: Vec::new(), $( $access: Lacks, )+ } } } impl fmt::Debug for $data { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let mut b = fmt.debug_struct("EntityData"); b.field("has components", &self.components); b.field("belongs to families", &self.families);
if self.$access.has_it() { b.field(stringify!($access), &self.$access); } )+*/ b.finish() } } impl EntityDataHolder for $data { fn new() -> Self { $data::new_empty() } fn match_families(&self, families: &FamilyMap) -> Vec<&'static str> { let mut v: Vec<&str> = vec!(); // Tuple has the requirements/forbidden vectors for (family, tuple) in families { if $crate::family::matcher(tuple, &self.components) { v.push(family) } } v } fn set_families(&mut self, families: Vec<&'static str>) { self.families = families; } fn belongs_to_family(&self, family: &str) -> bool { self.families.contains(&family) } fn families(&self) -> Vec<&'static str> { self.families.clone() } } $( impl Component<$data> for $ty { fn add_to(self, ent: Entity, data: &mut ComponentData<$data>) { let ent_data: &mut $data = data.components.get_mut(&ent).expect("no entity"); ent_data.components.push(stringify!($access)); ent_data.$access = Has(self); } } )+ } } /// This is a marker trait to be used by the `components!` macro. /// /// This trait is implemented by `EntityData` which is a struct generated /// by the `components!` macro. /// /// `EntityData` will be of the form: /// /// ``` /// struct EntityData { /// component1: ComponentPresence<Component1>, /// component2: ComponentPresence<Component2>, /// //etc... /// } /// ``` /// /// So it will have one field per component defined in the call to `components!` /// You'll access these fields directly when indexing the `data` field of the `EntityManager` pub trait EntityDataHolder { fn new() -> Self; /// Takes a map of all the defined families, /// and returns the families that match this entity. fn match_families(&self, &FamilyMap) -> Vec<&'static str>; /// Sets the families this entity belongs to to `families` fn set_families(&mut self, Vec<&'static str>); fn belongs_to_family(&self, &'static str) -> bool; /// Gets the known families this ent belongs to. fn families(&self) -> Vec<&'static str>; } /// ComponentData knows which entities have which components. pub struct ComponentData<D: EntityDataHolder> { /// components holds the components owned by a certain entity. pub components: HashMap<Entity, D>, /// Family to list of entities. pub families: HashMap<&'static str, Vec<Entity>>, } /// This trait marks a struct as a component. (Automatically handled by macro `components!`) /// /// It should implement the `add_to` function, which is automatically generated /// by the `components!` macro. pub trait Component<D: EntityDataHolder> { /// Adds self to the specified entity. Called by the `EntityManager` fn add_to(self, ent: Entity, data: &mut ComponentData<D>); } impl<D: EntityDataHolder> ComponentData<D> { pub fn new() -> ComponentData<D> { ComponentData { components: HashMap::new(), families: HashMap::new(), } } pub fn get(&self, ent: &Entity) -> Option<&D> { self.components.get(ent) } pub fn get_mut(&mut self, ent: &Entity) -> Option<&mut D> { self.components.get_mut(ent) } pub fn create_component_data_for(&mut self, ent: Entity) { self.components.insert(ent, D::new()); } pub fn clear_family_data_for(&mut self, ent: Entity) { for family in self[ent].families() { self.remove_from_family(family, ent); debug_assert!(!self.families[family].contains(&ent)) } } pub fn delete_component_data_for(&mut self, ent: Entity) { self.clear_family_data_for(ent); self.components.remove(&ent); } fn remove_from_family(&mut self, family: &str, ent: Entity) { let mut idx: Option<usize> = None; { let vec = self.families.get_mut(family).expect("No such family"); let op = vec.iter().enumerate().find(|&(_,e)| *e == ent); idx = Some(op.expect("Entity not found in this family").0); } if let Some(idx) = idx { self.families.get_mut(family).unwrap().swap_remove(idx); } else { panic!("Entity not found for family"); } } pub fn set_family_relation(&mut self, family: &'static str, ent: Entity) { match self.families.entry(family) { Vacant(entry) => {entry.insert(vec!(ent));}, Occupied(entry) => { let v = entry.into_mut(); if v.contains(&ent) { return; } v.push(ent); }, } } pub fn members_of(&self, family: &'static str) -> Vec<Entity> { match self.families.get(family) { Some(vec) => vec.clone(), None => vec!(), } } pub fn any_member_of(&self, family: &'static str) -> bool { !self.families.get(family).expect("no such family").is_empty() } } impl<D: EntityDataHolder> Index<Entity> for ComponentData<D> { type Output = D; fn index(&self, index: Entity) -> &D { &self.components.get(&index).expect(&format!("no entity {:?}", index)) } } impl<D: EntityDataHolder> IndexMut<Entity> for ComponentData<D> { fn index_mut(&mut self, index: Entity) -> &mut D { self.components.get_mut(&index).expect("no entity") } } /// The `EntityManager` type manages all the entities. /// /// It is in charge of creating and destroying entities. /// It also takes care of adding or removing components, through the `ComponentData` it contains. /// /// # Examples /// /// Creating a new manager, and adding some (predefined) components to a new entity. /// /// ``` /// let mut manager = EntityManager::new(); /// let ent = manager.new_entity(); /// manager.add_component_to(ent, Position{x: 1, y: 2}); /// ``` pub struct EntityManager<D: EntityDataHolder, F: FamilyDataHolder> { next_idx: usize, reusable_idxs: Vec<usize>, active: Vec<bool>, pub data: ComponentData<D>, /// Contains a list of all defined families, along with its requirements. families: F, } impl<D: EntityDataHolder, F: FamilyDataHolder> EntityManager<D, F> { /// Creates a new EntityManager pub fn new() -> EntityManager<D, F> { EntityManager{ next_idx: 0, reusable_idxs: vec!(), active: vec!(), data: ComponentData::new(), families: F::new(), } } /// Creates a new entity, assigning it an unused ID, returning that ID for further use. pub fn new_entity(&mut self) -> Entity { let idx = match self.reusable_idxs.pop() { None => { let idx = self.next_idx; self.next_idx += 1; idx } Some(idx) => idx, }; // Extend the vec if the idx is bigger. if self.active.len() <= idx { let padding = idx + 1 - self.active.len(); self.active.extend(iter::repeat(false).take(padding)); debug_assert!(self.active.len() == idx+1); } debug_assert!(!self.active[idx]); self.active[idx] = true; let ent = idx as Entity; self.data.create_component_data_for(ent); ent } /// Deletes the entity, removes all data related to it. /// /// Returns a list of events that were related to it, in case you need to do some clean up with them. pub fn delete_entity<Event>(&mut self, ent: Entity, events: &mut EventManager<Event>) -> Vec<Event> where Event: event::EventDataHolder { self.delete_entity_ignore_events(ent); events.clear_events_for(ent) } pub fn delete_entity_ignore_events(&mut self, ent: Entity) { let idx = ent as usize; assert!(self.active[idx]); self.reusable_idxs.push(idx); self.active[idx] = false; self.data.delete_component_data_for(ent); } pub fn build_ent<'a, A,B: EventDataHolder>(&'a mut self, ent: Entity, processor: &'a mut BehaviorManager<A,B>) -> EntityBuilder<D,A,B> { EntityBuilder::new(ent, processor, &mut self.data, self.families.all_families()) } /// Adds the specified component to the entity. pub fn add_component_to<A,B:EventDataHolder,C: Component<D>>(&mut self, e: Entity, c: C, processor: &mut BehaviorManager<A,B>) { //c.add_to(e, &mut self.data); self.build_ent(e, processor).add_component(c).finalize(); } } /// Used by `EntityManager` to add components to an Entity. /// /// An object of this type is obtained by calling `add_component` from an EntityManager pub struct EntityBuilder<'a, EntData: 'a + EntityDataHolder, T: 'a, Ev: event::EventDataHolder + 'a> { data: &'a mut ComponentData<EntData>, families: &'a FamilyMap, processor: &'a mut BehaviorManager<T,Ev>, ent: Entity, } impl<'a, EntData: 'a + EntityDataHolder, T, Ev: event::EventDataHolder> EntityBuilder<'a, EntData, T, Ev> { pub fn new(ent: Entity, processor: &'a mut BehaviorManager<T,Ev>, data: &'a mut ComponentData<EntData>, families: &'a FamilyMap) -> EntityBuilder<'a, EntData, T, Ev> { EntityBuilder { data: data, families: families, processor: processor, ent: ent, } } pub fn add_component<Comp: Component<EntData>>(self, comp: Comp) -> EntityBuilder<'a, EntData, T, Ev> { comp.add_to(self.ent, self.data); self } pub fn finalize(mut self) -> Entity { self.add_all_related_data(); self.ent } pub fn add_all_related_data(&mut self) { let mut families: Vec<&str> = self.data[self.ent].match_families(self.families); families.sort(); families.dedup(); // Clean up current component data, self.data.clear_family_data_for(self.ent); // Give the ComponentDataHolder information about this entities families. for family in families.iter() { self.data.set_family_relation(family, self.ent); } if!self.processor.valid_behaviors_for(families.clone()).is_empty() { self.processor.add_processable(self.ent); } // Give this EntityDataHolder a list of which families this entity has. self.data[self.ent].set_families(families); } } /* fn main() { println!("Hello, world!"); let mut manager = EntityManager::new(); let ent = manager.new_entity(); manager.add_component_to(ent, Position{x:1, y:2}); println!("pos: {:?}", manager.data[ent].position.x); manager.data[ent].position.x += 5; println!("pos: {:?}", manager.data[ent].position.x); println!("has glyph? {:?}", manager.data[ent].glyph.has_it()); } */
/*$(
random_line_split
lib.rs
//! An Entity Component System for game development. //! //! Currently used for personal use (for a roguelike game), this library is highly unstable, and a WIP. #![allow(dead_code)] #![feature(append,drain)] use std::iter; use std::collections::HashMap; use std::ops::{Index, IndexMut}; use std::collections::hash_map::Entry::{Occupied, Vacant}; pub mod component_presence; pub mod family; pub mod builder; pub mod event; pub mod behavior; use family::{FamilyDataHolder, FamilyMap}; use event::{EventDataHolder}; pub use event::EventManager; pub use behavior::BehaviorManager; pub use behavior::Behavior; pub use component_presence::ComponentPresence; /// Type Entity is simply an ID used as indexes. pub type Entity = u32; /// The components macro defines all the structs and traits that manage /// the component part of the ECS. #[macro_export] macro_rules! components { ($data:ident: $([$access:ident, $ty:ty]),+ ) => { use $crate::component_presence::ComponentPresence; use $crate::component_presence::ComponentPresence::*; use $crate::{EntityDataHolder, Component, Entity, ComponentData}; use $crate::family::{FamilyMap}; use std::fmt; pub struct $data { pub components: Vec<&'static str>, pub families: Vec<&'static str>, $( pub $access: ComponentPresence<$ty>, )+ } impl $data { pub fn new_empty() -> $data { $data { components: Vec::new(), families: Vec::new(), $( $access: Lacks, )+ } } } impl fmt::Debug for $data { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let mut b = fmt.debug_struct("EntityData"); b.field("has components", &self.components); b.field("belongs to families", &self.families); /*$( if self.$access.has_it() { b.field(stringify!($access), &self.$access); } )+*/ b.finish() } } impl EntityDataHolder for $data { fn new() -> Self { $data::new_empty() } fn match_families(&self, families: &FamilyMap) -> Vec<&'static str> { let mut v: Vec<&str> = vec!(); // Tuple has the requirements/forbidden vectors for (family, tuple) in families { if $crate::family::matcher(tuple, &self.components) { v.push(family) } } v } fn set_families(&mut self, families: Vec<&'static str>) { self.families = families; } fn belongs_to_family(&self, family: &str) -> bool { self.families.contains(&family) } fn families(&self) -> Vec<&'static str> { self.families.clone() } } $( impl Component<$data> for $ty { fn add_to(self, ent: Entity, data: &mut ComponentData<$data>) { let ent_data: &mut $data = data.components.get_mut(&ent).expect("no entity"); ent_data.components.push(stringify!($access)); ent_data.$access = Has(self); } } )+ } } /// This is a marker trait to be used by the `components!` macro. /// /// This trait is implemented by `EntityData` which is a struct generated /// by the `components!` macro. /// /// `EntityData` will be of the form: /// /// ``` /// struct EntityData { /// component1: ComponentPresence<Component1>, /// component2: ComponentPresence<Component2>, /// //etc... /// } /// ``` /// /// So it will have one field per component defined in the call to `components!` /// You'll access these fields directly when indexing the `data` field of the `EntityManager` pub trait EntityDataHolder { fn new() -> Self; /// Takes a map of all the defined families, /// and returns the families that match this entity. fn match_families(&self, &FamilyMap) -> Vec<&'static str>; /// Sets the families this entity belongs to to `families` fn set_families(&mut self, Vec<&'static str>); fn belongs_to_family(&self, &'static str) -> bool; /// Gets the known families this ent belongs to. fn families(&self) -> Vec<&'static str>; } /// ComponentData knows which entities have which components. pub struct ComponentData<D: EntityDataHolder> { /// components holds the components owned by a certain entity. pub components: HashMap<Entity, D>, /// Family to list of entities. pub families: HashMap<&'static str, Vec<Entity>>, } /// This trait marks a struct as a component. (Automatically handled by macro `components!`) /// /// It should implement the `add_to` function, which is automatically generated /// by the `components!` macro. pub trait Component<D: EntityDataHolder> { /// Adds self to the specified entity. Called by the `EntityManager` fn add_to(self, ent: Entity, data: &mut ComponentData<D>); } impl<D: EntityDataHolder> ComponentData<D> { pub fn new() -> ComponentData<D> { ComponentData { components: HashMap::new(), families: HashMap::new(), } } pub fn get(&self, ent: &Entity) -> Option<&D> { self.components.get(ent) } pub fn get_mut(&mut self, ent: &Entity) -> Option<&mut D> { self.components.get_mut(ent) } pub fn create_component_data_for(&mut self, ent: Entity) { self.components.insert(ent, D::new()); } pub fn clear_family_data_for(&mut self, ent: Entity) { for family in self[ent].families() { self.remove_from_family(family, ent); debug_assert!(!self.families[family].contains(&ent)) } } pub fn delete_component_data_for(&mut self, ent: Entity) { self.clear_family_data_for(ent); self.components.remove(&ent); } fn remove_from_family(&mut self, family: &str, ent: Entity)
pub fn set_family_relation(&mut self, family: &'static str, ent: Entity) { match self.families.entry(family) { Vacant(entry) => {entry.insert(vec!(ent));}, Occupied(entry) => { let v = entry.into_mut(); if v.contains(&ent) { return; } v.push(ent); }, } } pub fn members_of(&self, family: &'static str) -> Vec<Entity> { match self.families.get(family) { Some(vec) => vec.clone(), None => vec!(), } } pub fn any_member_of(&self, family: &'static str) -> bool { !self.families.get(family).expect("no such family").is_empty() } } impl<D: EntityDataHolder> Index<Entity> for ComponentData<D> { type Output = D; fn index(&self, index: Entity) -> &D { &self.components.get(&index).expect(&format!("no entity {:?}", index)) } } impl<D: EntityDataHolder> IndexMut<Entity> for ComponentData<D> { fn index_mut(&mut self, index: Entity) -> &mut D { self.components.get_mut(&index).expect("no entity") } } /// The `EntityManager` type manages all the entities. /// /// It is in charge of creating and destroying entities. /// It also takes care of adding or removing components, through the `ComponentData` it contains. /// /// # Examples /// /// Creating a new manager, and adding some (predefined) components to a new entity. /// /// ``` /// let mut manager = EntityManager::new(); /// let ent = manager.new_entity(); /// manager.add_component_to(ent, Position{x: 1, y: 2}); /// ``` pub struct EntityManager<D: EntityDataHolder, F: FamilyDataHolder> { next_idx: usize, reusable_idxs: Vec<usize>, active: Vec<bool>, pub data: ComponentData<D>, /// Contains a list of all defined families, along with its requirements. families: F, } impl<D: EntityDataHolder, F: FamilyDataHolder> EntityManager<D, F> { /// Creates a new EntityManager pub fn new() -> EntityManager<D, F> { EntityManager{ next_idx: 0, reusable_idxs: vec!(), active: vec!(), data: ComponentData::new(), families: F::new(), } } /// Creates a new entity, assigning it an unused ID, returning that ID for further use. pub fn new_entity(&mut self) -> Entity { let idx = match self.reusable_idxs.pop() { None => { let idx = self.next_idx; self.next_idx += 1; idx } Some(idx) => idx, }; // Extend the vec if the idx is bigger. if self.active.len() <= idx { let padding = idx + 1 - self.active.len(); self.active.extend(iter::repeat(false).take(padding)); debug_assert!(self.active.len() == idx+1); } debug_assert!(!self.active[idx]); self.active[idx] = true; let ent = idx as Entity; self.data.create_component_data_for(ent); ent } /// Deletes the entity, removes all data related to it. /// /// Returns a list of events that were related to it, in case you need to do some clean up with them. pub fn delete_entity<Event>(&mut self, ent: Entity, events: &mut EventManager<Event>) -> Vec<Event> where Event: event::EventDataHolder { self.delete_entity_ignore_events(ent); events.clear_events_for(ent) } pub fn delete_entity_ignore_events(&mut self, ent: Entity) { let idx = ent as usize; assert!(self.active[idx]); self.reusable_idxs.push(idx); self.active[idx] = false; self.data.delete_component_data_for(ent); } pub fn build_ent<'a, A,B: EventDataHolder>(&'a mut self, ent: Entity, processor: &'a mut BehaviorManager<A,B>) -> EntityBuilder<D,A,B> { EntityBuilder::new(ent, processor, &mut self.data, self.families.all_families()) } /// Adds the specified component to the entity. pub fn add_component_to<A,B:EventDataHolder,C: Component<D>>(&mut self, e: Entity, c: C, processor: &mut BehaviorManager<A,B>) { //c.add_to(e, &mut self.data); self.build_ent(e, processor).add_component(c).finalize(); } } /// Used by `EntityManager` to add components to an Entity. /// /// An object of this type is obtained by calling `add_component` from an EntityManager pub struct EntityBuilder<'a, EntData: 'a + EntityDataHolder, T: 'a, Ev: event::EventDataHolder + 'a> { data: &'a mut ComponentData<EntData>, families: &'a FamilyMap, processor: &'a mut BehaviorManager<T,Ev>, ent: Entity, } impl<'a, EntData: 'a + EntityDataHolder, T, Ev: event::EventDataHolder> EntityBuilder<'a, EntData, T, Ev> { pub fn new(ent: Entity, processor: &'a mut BehaviorManager<T,Ev>, data: &'a mut ComponentData<EntData>, families: &'a FamilyMap) -> EntityBuilder<'a, EntData, T, Ev> { EntityBuilder { data: data, families: families, processor: processor, ent: ent, } } pub fn add_component<Comp: Component<EntData>>(self, comp: Comp) -> EntityBuilder<'a, EntData, T, Ev> { comp.add_to(self.ent, self.data); self } pub fn finalize(mut self) -> Entity { self.add_all_related_data(); self.ent } pub fn add_all_related_data(&mut self) { let mut families: Vec<&str> = self.data[self.ent].match_families(self.families); families.sort(); families.dedup(); // Clean up current component data, self.data.clear_family_data_for(self.ent); // Give the ComponentDataHolder information about this entities families. for family in families.iter() { self.data.set_family_relation(family, self.ent); } if!self.processor.valid_behaviors_for(families.clone()).is_empty() { self.processor.add_processable(self.ent); } // Give this EntityDataHolder a list of which families this entity has. self.data[self.ent].set_families(families); } } /* fn main() { println!("Hello, world!"); let mut manager = EntityManager::new(); let ent = manager.new_entity(); manager.add_component_to(ent, Position{x:1, y:2}); println!("pos: {:?}", manager.data[ent].position.x); manager.data[ent].position.x += 5; println!("pos: {:?}", manager.data[ent].position.x); println!("has glyph? {:?}", manager.data[ent].glyph.has_it()); } */
{ let mut idx: Option<usize> = None; { let vec = self.families.get_mut(family).expect("No such family"); let op = vec.iter().enumerate().find(|&(_,e)| *e == ent); idx = Some(op.expect("Entity not found in this family").0); } if let Some(idx) = idx { self.families.get_mut(family).unwrap().swap_remove(idx); } else { panic!("Entity not found for family"); } }
identifier_body
baconian.rs
//! Bacon's cipher, or the Baconian cipher, hides a secret message in plain sight rather than //! generating ciphertext (steganography). It was devised by Sir Francis Bacon in 1605. //! //! Each character of the plaintext message is encoded as a 5-bit binary character. //! These characters are then "hidden" in a decoy message through the use of font variation. //! This cipher is very easy to crack once the method of hiding is known. As such, this implementation includes //! the option to set whether the substitution is use_distinct_alphabet for the whole alphabet, //! or whether it follows the classical method of treating 'I' and 'J', and 'U' and 'V' as //! interchangeable characters - as would have been the case in Bacon's time. //! //! If no concealing text is given and the boilerplate of "Lorem ipsum..." is used, //! a plaintext message of up to ~50 characters may be hidden. //! use crate::common::cipher::Cipher; use lipsum::lipsum; use std::collections::HashMap; use std::string::String; // The default code length const CODE_LEN: usize = 5; // Code mappings: // * note: that str is preferred over char as it cannot be guaranteed that // there will be a single codepoint for a given character. lazy_static! { static ref CODE_MAP: HashMap<&'static str, &'static str> = hashmap! { "A" => "AAAAA", "B" => "AAAAB", "C" => "AAABA", "D" => "AAABB", "E" => "AABAA", "F" => "AABAB", "G" => "AABBA", "H" => "AABBB", "I" => "ABAAA", "J" => "ABAAB", "K" => "ABABA", "L" => "ABABB", "M" => "ABBAA", "N" => "ABBAB", "O" => "ABBBA", "P" => "ABBBB", "Q" => "BAAAA", "R" => "BAAAB", "S" => "BAABA", "T" => "BAABB", "U" => "BABAA", "V" => "BABAB", "W" => "BABBA", "X" => "BABBB", "Y" => "BBAAA", "Z" => "BBAAB" }; } // A mapping of alphabet to italic UTF-8 italic codes lazy_static! { static ref ITALIC_CODES: HashMap<&'static str, char> = hashmap!{ // Using Mathematical Italic "A" => '\u{1D434}', "B" => '\u{1D435}', "C" => '\u{1D436}', "D" => '\u{1D437}', "E" => '\u{1D438}', "F" => '\u{1D439}', "G" => '\u{1D43a}', "H" => '\u{1D43b}', "I" => '\u{1D43c}', "J" => '\u{1D43d}', "K" => '\u{1D43e}', "L" => '\u{1D43f}', "M" => '\u{1D440}', "N" => '\u{1D441}', "O" => '\u{1D442}', "P" => '\u{1D443}', "Q" => '\u{1D444}', "R" => '\u{1D445}', "S" => '\u{1D446}', "T" => '\u{1D447}', "U" => '\u{1D448}', "V" => '\u{1D449}', "W" => '\u{1D44a}', "X" => '\u{1D44b}', "Y" => '\u{1D44c}', "Z" => '\u{1D44d}', // Using Mathematical Sans-Serif Italic "a" => '\u{1D622}', "b" => '\u{1D623}', "c" => '\u{1D624}', "d" => '\u{1D625}', "e" => '\u{1D626}', "f" => '\u{1D627}', "g" => '\u{1D628}', "h" => '\u{1D629}', "i" => '\u{1D62a}', "j" => '\u{1D62b}', "k" => '\u{1D62c}', "l" => '\u{1D62d}', "m" => '\u{1D62e}', "n" => '\u{1D62f}', "o" => '\u{1D630}', "p" => '\u{1D631}', "q" => '\u{1D632}', "r" => '\u{1D633}', "s" => '\u{1D634}', "t" => '\u{1D635}', "u" => '\u{1D636}', "v" => '\u{1D637}', "w" => '\u{1D638}', "x" => '\u{1D639}', "y" => '\u{1D63a}', "z" => '\u{1D63b}' }; } /// Get the code for a given key (source character) fn get_code(use_distinct_alphabet: bool, key: &str) -> String { let mut code = String::new(); // Need to handle 'I'/'J' and 'U'/'V' // for traditional usage. let mut key_upper = key.to_uppercase(); if!use_distinct_alphabet { match key_upper.as_str() { "J" => key_upper = "I".to_string(), "U" => key_upper = "V".to_string(), _ => {} } } if CODE_MAP.contains_key(key_upper.as_str()) { code.push_str(CODE_MAP.get(key_upper.as_str()).unwrap()); } code } /// Gets the key (the source character) for a given cipher text code fn get_key(code: &str) -> String { let mut key = String::new(); for (_key, val) in CODE_MAP.iter() { if val == &code { key.push_str(_key); } } key } /// This struct is created by the `new()` method. See its documentation for more. pub struct Baconian { use_distinct_alphabet: bool, decoy_text: String, } impl Cipher for Baconian { type Key = (bool, Option<String>); type Algorithm = Baconian; /// Initialise a Baconian cipher /// /// The `key` tuple maps to the following: `(bool, Option<str>) = (use_distinct_alphabet, decoy_text)`. /// Where... /// /// * The encoding will be use_distinct_alphabet for all alphabetical characters, or classical /// where I, J, U and V are mapped to the same value pairs /// * An optional decoy message that will will be used to hide the message - /// default is boilerplate "Lorem ipsum" text. /// fn new(key: (bool, Option<String>)) -> Baconian
/// Encrypt a message using the Baconian cipher /// /// * The message to be encrypted can only be ~18% of the decoy_text as each character /// of message is encoded by 5 encoding characters `AAAAA`, `AAAAB`, etc. /// * The italicised ciphertext is then hidden in a decoy text, where, for each 'B' /// in the ciphertext, the character is italicised in the decoy_text. /// /// # Examples /// Basic usage: /// /// ``` /// use cipher_crypt::{Cipher, Baconian}; /// /// let b = Baconian::new((false, None));; /// let message = "Hello"; /// let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘤𝘰n"; /// /// assert_eq!(cipher_text, b.encrypt(message).unwrap()); /// ``` fn encrypt(&self, message: &str) -> Result<String, &'static str> { let num_non_alphas = self .decoy_text .chars() .filter(|c|!c.is_alphabetic()) .count(); // Check whether the message fits in the decoy // Note: that non-alphabetical characters will be skipped. if (message.len() * CODE_LEN) > self.decoy_text.len() - num_non_alphas { return Err("Message too long for supplied decoy text."); } // Iterate through the message encoding each char (ignoring non-alphabetical chars) let secret: String = message .chars() .map(|c| get_code(self.use_distinct_alphabet, &c.to_string())) .collect(); let mut num_alphas = 0; let mut num_non_alphas = 0; for c in self.decoy_text.chars() { if num_alphas == secret.len() { break; } if c.is_alphabetic() { num_alphas += 1 } else { num_non_alphas += 1 }; } let decoy_slice: String = self .decoy_text .chars() .take(num_alphas + num_non_alphas) .collect(); // We now have an encoded message, `secret`, in which each character of of the // original plaintext is now represented by a 5-bit binary character, // "AAAAA", "ABABA" etc. // We now overlay the encoded text onto the decoy slice, and // where the binary 'B' is found the decoy slice char is swapped for an italic let mut decoy_msg = String::new(); let mut secret_iter = secret.chars(); for c in decoy_slice.chars() { if c.is_alphabetic() { if let Some(sc) = secret_iter.next() { if sc == 'B' { // match the binary 'B' and swap for italic let italic = *ITALIC_CODES.get(c.to_string().as_str()).unwrap(); decoy_msg.push(italic); } else { decoy_msg.push(c); } } } else { decoy_msg.push(c); } } Ok(decoy_msg) } /// Decrypt a message that was encrypted with the Baconian cipher /// /// # Examples /// Basic usage: /// /// ``` /// use cipher_crypt::{Cipher, Baconian}; /// /// let b = Baconian::new((false, None));; /// let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘯𝘦 t"; /// /// assert_eq!("HELLO", b.decrypt(cipher_text).unwrap()); /// ``` /// fn decrypt(&self, message: &str) -> Result<String, &'static str> { // The message is decoy text // Iterate through swapping any alphabetical chars found in the ITALIC_CODES // set to be 'B', else 'A', skip anything else. let ciphertext: String = message .chars() .filter(|c| c.is_alphabetic()) .map(|c| { if ITALIC_CODES.iter().any(|e| *e.1 == c) { 'B' } else { 'A' } }) .collect(); let mut plaintext = String::new(); let mut code = String::new(); for c in ciphertext.chars() { code.push(c); if code.len() == CODE_LEN { // If we have the right length code plaintext += &get_key(&code); code.clear(); } } Ok(plaintext) } } #[cfg(test)] mod tests { use super::*; #[test] fn encrypt_simple() { let b = Baconian::new((false, None)); let message = "Hello"; let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘤𝘰n"; assert_eq!(cipher_text, b.encrypt(message).unwrap()); } // Need to test that the traditional and use_distinct_alphabet codes give different results #[test] fn encrypt_trad_v_dist() { let b_trad = Baconian::new((false, None)); let b_dist = Baconian::new((true, None)); let message = "I JADE YOU VERVENT UNICORN"; assert_ne!( b_dist.encrypt(&message).unwrap(), b_trad.encrypt(message).unwrap() ); } #[test] fn encrypt_message_spaced() { let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let b = Baconian::new((false, Some(decoy_text))); let message = "Peace, Freedom 🗡️ and Liberty!"; let cipher_text = "T𝘩𝘦 𝘸𝘰rl𝘥\'s a bubble; an𝘥 the 𝘭ife o𝘧 m𝘢𝘯 les𝘴 th𝘢n a sp𝘢n. \ In hi𝘴 𝘤o𝘯𝘤𝘦pt𝘪𝘰n wretche𝘥; 𝘧r𝘰m th𝘦 𝘸o𝘮b 𝘴𝘰 t𝘰 the tomb: \ 𝐶ur𝘴t f𝘳om t𝘩𝘦 cr𝘢𝘥𝘭𝘦, and"; assert_eq!(cipher_text, b.encrypt(message).unwrap()); } // use_distinct_alphabet lexicon #[test] #[should_panic(expected = r#"Message too long for supplied decoy text."#)] fn encrypt_decoy_too_short() { let b = Baconian::new((false, None)); let message = "This is a long message that will be too long to encode using \ the default decoy text. In order to have a long message encoded you need a \ decoy text that is at least five times as long, plus the non-alphabeticals."; b.encrypt(message).unwrap(); } #[test] fn encrypt_with_use_distinct_alphabet_codeset() { let message = "Peace, Freedom 🗡️ and Liberty!"; let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let cipher_text = "T𝘩𝘦 𝘸𝘰rl𝘥's a bubble; an𝘥 the 𝘭ife o𝘧 m𝘢𝘯 les𝘴 th𝘢n a sp𝘢n. \ In hi𝘴 𝘤o𝘯𝘤𝘦pt𝘪𝘰n wretche𝘥; 𝘧r𝘰m th𝘦 𝘸o𝘮b 𝘴𝘰 t𝘰 the tomb: \ 𝐶ur𝘴t f𝘳om t𝘩𝘦 cr𝘢𝘥𝘭𝘦, and"; let b = Baconian::new((true, Some(decoy_text))); assert_eq!(cipher_text, b.encrypt(message).unwrap()); } #[test] fn decrypt_a_classic() { let cipher_text = String::from("Let's c𝘰mp𝘳𝘰𝘮is𝘦. 𝐻old off th𝘦 at𝘵a𝘤k"); let message = "ATTACK"; let decoy_text = String::from("Let's compromise. Hold off the attack"); let b = Baconian::new((true, Some(decoy_text))); assert_eq!(message, b.decrypt(&cipher_text).unwrap()); } #[test] fn decrypt_traditional() { let cipher_text = String::from( "T𝘩e wor𝘭d's a bubble; an𝘥 𝘵he 𝘭if𝘦 𝘰f man 𝘭𝘦𝘴s 𝘵h𝘢n 𝘢 𝘴p𝘢n. \ 𝐼n h𝘪s c𝘰nce𝘱𝘵i𝘰n 𝘸re𝘵che𝘥; 𝘧r𝘰𝘮 th𝘦 𝘸𝘰m𝘣 s𝘰 t𝘰 𝘵h𝘦 t𝘰mb: \ Curs𝘵 fr𝘰𝘮 𝘵h𝘦 cra𝘥l𝘦, 𝘢n𝘥", ); // Note: the substitution for 'I'/'J' and 'U'/'V' let message = "IIADEYOVVERVENTVNICORN"; let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let b = Baconian::new((false, Some(decoy_text))); assert_eq!(message, b.decrypt(&cipher_text).unwrap()); } }
{ Baconian { use_distinct_alphabet: key.0, decoy_text: key.1.unwrap_or_else(|| lipsum(160)), } }
identifier_body
baconian.rs
//! Bacon's cipher, or the Baconian cipher, hides a secret message in plain sight rather than //! generating ciphertext (steganography). It was devised by Sir Francis Bacon in 1605. //! //! Each character of the plaintext message is encoded as a 5-bit binary character. //! These characters are then "hidden" in a decoy message through the use of font variation. //! This cipher is very easy to crack once the method of hiding is known. As such, this implementation includes //! the option to set whether the substitution is use_distinct_alphabet for the whole alphabet, //! or whether it follows the classical method of treating 'I' and 'J', and 'U' and 'V' as //! interchangeable characters - as would have been the case in Bacon's time. //! //! If no concealing text is given and the boilerplate of "Lorem ipsum..." is used, //! a plaintext message of up to ~50 characters may be hidden. //! use crate::common::cipher::Cipher; use lipsum::lipsum; use std::collections::HashMap; use std::string::String; // The default code length const CODE_LEN: usize = 5; // Code mappings: // * note: that str is preferred over char as it cannot be guaranteed that // there will be a single codepoint for a given character. lazy_static! { static ref CODE_MAP: HashMap<&'static str, &'static str> = hashmap! { "A" => "AAAAA", "B" => "AAAAB", "C" => "AAABA", "D" => "AAABB", "E" => "AABAA", "F" => "AABAB", "G" => "AABBA", "H" => "AABBB", "I" => "ABAAA", "J" => "ABAAB", "K" => "ABABA", "L" => "ABABB", "M" => "ABBAA", "N" => "ABBAB", "O" => "ABBBA", "P" => "ABBBB", "Q" => "BAAAA", "R" => "BAAAB", "S" => "BAABA", "T" => "BAABB", "U" => "BABAA", "V" => "BABAB", "W" => "BABBA", "X" => "BABBB", "Y" => "BBAAA", "Z" => "BBAAB" }; } // A mapping of alphabet to italic UTF-8 italic codes lazy_static! { static ref ITALIC_CODES: HashMap<&'static str, char> = hashmap!{ // Using Mathematical Italic "A" => '\u{1D434}', "B" => '\u{1D435}', "C" => '\u{1D436}', "D" => '\u{1D437}', "E" => '\u{1D438}', "F" => '\u{1D439}', "G" => '\u{1D43a}', "H" => '\u{1D43b}', "I" => '\u{1D43c}', "J" => '\u{1D43d}', "K" => '\u{1D43e}', "L" => '\u{1D43f}', "M" => '\u{1D440}', "N" => '\u{1D441}', "O" => '\u{1D442}', "P" => '\u{1D443}', "Q" => '\u{1D444}', "R" => '\u{1D445}', "S" => '\u{1D446}', "T" => '\u{1D447}', "U" => '\u{1D448}', "V" => '\u{1D449}', "W" => '\u{1D44a}', "X" => '\u{1D44b}', "Y" => '\u{1D44c}', "Z" => '\u{1D44d}', // Using Mathematical Sans-Serif Italic "a" => '\u{1D622}', "b" => '\u{1D623}', "c" => '\u{1D624}', "d" => '\u{1D625}', "e" => '\u{1D626}', "f" => '\u{1D627}', "g" => '\u{1D628}', "h" => '\u{1D629}', "i" => '\u{1D62a}', "j" => '\u{1D62b}', "k" => '\u{1D62c}', "l" => '\u{1D62d}', "m" => '\u{1D62e}', "n" => '\u{1D62f}', "o" => '\u{1D630}', "p" => '\u{1D631}', "q" => '\u{1D632}', "r" => '\u{1D633}', "s" => '\u{1D634}', "t" => '\u{1D635}', "u" => '\u{1D636}', "v" => '\u{1D637}', "w" => '\u{1D638}', "x" => '\u{1D639}', "y" => '\u{1D63a}', "z" => '\u{1D63b}' }; } /// Get the code for a given key (source character) fn get_code(use_distinct_alphabet: bool, key: &str) -> String { let mut code = String::new(); // Need to handle 'I'/'J' and 'U'/'V' // for traditional usage. let mut key_upper = key.to_uppercase(); if!use_distinct_alphabet { match key_upper.as_str() { "J" => key_upper = "I".to_string(), "U" => key_upper = "V".to_string(), _ => {} } } if CODE_MAP.contains_key(key_upper.as_str()) { code.push_str(CODE_MAP.get(key_upper.as_str()).unwrap()); } code } /// Gets the key (the source character) for a given cipher text code fn get_key(code: &str) -> String { let mut key = String::new(); for (_key, val) in CODE_MAP.iter() { if val == &code { key.push_str(_key); } } key } /// This struct is created by the `new()` method. See its documentation for more. pub struct Baconian { use_distinct_alphabet: bool, decoy_text: String, } impl Cipher for Baconian { type Key = (bool, Option<String>); type Algorithm = Baconian; /// Initialise a Baconian cipher /// /// The `key` tuple maps to the following: `(bool, Option<str>) = (use_distinct_alphabet, decoy_text)`. /// Where... /// /// * The encoding will be use_distinct_alphabet for all alphabetical characters, or classical /// where I, J, U and V are mapped to the same value pairs /// * An optional decoy message that will will be used to hide the message - /// default is boilerplate "Lorem ipsum" text. /// fn new(key: (bool, Option<String>)) -> Baconian { Baconian { use_distinct_alphabet: key.0, decoy_text: key.1.unwrap_or_else(|| lipsum(160)), } } /// Encrypt a message using the Baconian cipher /// /// * The message to be encrypted can only be ~18% of the decoy_text as each character /// of message is encoded by 5 encoding characters `AAAAA`, `AAAAB`, etc. /// * The italicised ciphertext is then hidden in a decoy text, where, for each 'B' /// in the ciphertext, the character is italicised in the decoy_text. /// /// # Examples /// Basic usage: /// /// ``` /// use cipher_crypt::{Cipher, Baconian}; /// /// let b = Baconian::new((false, None));; /// let message = "Hello"; /// let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘤𝘰n"; /// /// assert_eq!(cipher_text, b.encrypt(message).unwrap()); /// ``` fn encrypt(&self, message: &str) -> Result<String, &'static str> { let num_non_alphas = self .decoy_text .chars() .filter(|c|!c.is_alphabetic()) .count(); // Check whether the message fits in the decoy // Note: that non-alphabetical characters will be skipped. if (message.len() * CODE_LEN) > self.decoy_text.len() - num_non_alphas { return Err("Message too long for supplied decoy text."); } // Iterate through the message encoding each char (ignoring non-alphabetical chars) let secret: String = message .chars() .map(|c| get_code(self.use_distinct_alphabet, &c.to_string())) .collect(); let mut num_alphas = 0; let mut num_non_alphas = 0; for c in self.decoy_text.chars() { if num_alphas == secret.len() { break; } if c.is_alphabetic() { num_alphas += 1 } else { num_non_alphas += 1 }; } let decoy_slice: String = self .decoy_text .chars() .take(num_alphas + num_non_alphas) .collect(); // We now have an encoded message, `secret`, in which each character of of the // original plaintext is now represented by a 5-bit binary character, // "AAAAA", "ABABA" etc. // We now overlay the encoded text onto the decoy slice, and // where the binary 'B' is found the decoy slice char is swapped for an italic let mut decoy_msg = String::new(); let mut secret_iter = secret.chars(); for c in decoy_slice.chars() { if c.is_alphabetic() { if let Some(sc) = secret_iter.next() { if sc == 'B' { // match the binary 'B' and swap for italic let italic = *ITALIC_CODES.get(c.to_string().as_str()).unwrap(); decoy_msg.push(italic); } else { decoy_msg.push(c); } } } else { decoy_msg.push(c); } } Ok(decoy_msg) } /// Decrypt a message that was encrypted with the Baconian cipher /// /// # Examples /// Basic usage: /// /// ``` /// use cipher_crypt::{Cipher, Baconian}; /// /// let b = Baconian::new((false, None));; /// let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘯𝘦 t"; /// /// assert_eq!("HELLO", b.decrypt(cipher_text).unwrap()); /// ``` /// fn decrypt(&self, message: &str) -> Result<String, &'static str> { // The message is decoy text // Iterate through swapping any alphabetical chars found in the ITALIC_CODES // set to be 'B', else 'A', skip anything else. let ciphertext: String = message .chars() .filter(|c| c.is_alphabetic()) .map(|c| { if ITALIC_CODES.iter().any(|e| *e.1 == c) { 'B' } else { 'A' } }) .collect(); let mut plaintext = String::new(); let mut code = String::new(); for c in ciphertext.chars() { code.push(c); if code.len() == CODE_LEN { // If we have the right length code plaintext += &get_key(&code); code.clear(); } } Ok(plaintext) } } #[cfg(test)] mod tests { use super::*; #[test] fn encrypt_simple() { let b = Baconian::new((false, None)); let m
o"; let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘤𝘰n"; assert_eq!(cipher_text, b.encrypt(message).unwrap()); } // Need to test that the traditional and use_distinct_alphabet codes give different results #[test] fn encrypt_trad_v_dist() { let b_trad = Baconian::new((false, None)); let b_dist = Baconian::new((true, None)); let message = "I JADE YOU VERVENT UNICORN"; assert_ne!( b_dist.encrypt(&message).unwrap(), b_trad.encrypt(message).unwrap() ); } #[test] fn encrypt_message_spaced() { let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let b = Baconian::new((false, Some(decoy_text))); let message = "Peace, Freedom 🗡️ and Liberty!"; let cipher_text = "T𝘩𝘦 𝘸𝘰rl𝘥\'s a bubble; an𝘥 the 𝘭ife o𝘧 m𝘢𝘯 les𝘴 th𝘢n a sp𝘢n. \ In hi𝘴 𝘤o𝘯𝘤𝘦pt𝘪𝘰n wretche𝘥; 𝘧r𝘰m th𝘦 𝘸o𝘮b 𝘴𝘰 t𝘰 the tomb: \ 𝐶ur𝘴t f𝘳om t𝘩𝘦 cr𝘢𝘥𝘭𝘦, and"; assert_eq!(cipher_text, b.encrypt(message).unwrap()); } // use_distinct_alphabet lexicon #[test] #[should_panic(expected = r#"Message too long for supplied decoy text."#)] fn encrypt_decoy_too_short() { let b = Baconian::new((false, None)); let message = "This is a long message that will be too long to encode using \ the default decoy text. In order to have a long message encoded you need a \ decoy text that is at least five times as long, plus the non-alphabeticals."; b.encrypt(message).unwrap(); } #[test] fn encrypt_with_use_distinct_alphabet_codeset() { let message = "Peace, Freedom 🗡️ and Liberty!"; let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let cipher_text = "T𝘩𝘦 𝘸𝘰rl𝘥's a bubble; an𝘥 the 𝘭ife o𝘧 m𝘢𝘯 les𝘴 th𝘢n a sp𝘢n. \ In hi𝘴 𝘤o𝘯𝘤𝘦pt𝘪𝘰n wretche𝘥; 𝘧r𝘰m th𝘦 𝘸o𝘮b 𝘴𝘰 t𝘰 the tomb: \ 𝐶ur𝘴t f𝘳om t𝘩𝘦 cr𝘢𝘥𝘭𝘦, and"; let b = Baconian::new((true, Some(decoy_text))); assert_eq!(cipher_text, b.encrypt(message).unwrap()); } #[test] fn decrypt_a_classic() { let cipher_text = String::from("Let's c𝘰mp𝘳𝘰𝘮is𝘦. 𝐻old off th𝘦 at𝘵a𝘤k"); let message = "ATTACK"; let decoy_text = String::from("Let's compromise. Hold off the attack"); let b = Baconian::new((true, Some(decoy_text))); assert_eq!(message, b.decrypt(&cipher_text).unwrap()); } #[test] fn decrypt_traditional() { let cipher_text = String::from( "T𝘩e wor𝘭d's a bubble; an𝘥 𝘵he 𝘭if𝘦 𝘰f man 𝘭𝘦𝘴s 𝘵h𝘢n 𝘢 𝘴p𝘢n. \ 𝐼n h𝘪s c𝘰nce𝘱𝘵i𝘰n 𝘸re𝘵che𝘥; 𝘧r𝘰𝘮 th𝘦 𝘸𝘰m𝘣 s𝘰 t𝘰 𝘵h𝘦 t𝘰mb: \ Curs𝘵 fr𝘰𝘮 𝘵h𝘦 cra𝘥l𝘦, 𝘢n𝘥", ); // Note: the substitution for 'I'/'J' and 'U'/'V' let message = "IIADEYOVVERVENTVNICORN"; let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let b = Baconian::new((false, Some(decoy_text))); assert_eq!(message, b.decrypt(&cipher_text).unwrap()); } }
essage = "Hell
identifier_name
baconian.rs
//! Bacon's cipher, or the Baconian cipher, hides a secret message in plain sight rather than //! generating ciphertext (steganography). It was devised by Sir Francis Bacon in 1605. //! //! Each character of the plaintext message is encoded as a 5-bit binary character. //! These characters are then "hidden" in a decoy message through the use of font variation. //! This cipher is very easy to crack once the method of hiding is known. As such, this implementation includes //! the option to set whether the substitution is use_distinct_alphabet for the whole alphabet, //! or whether it follows the classical method of treating 'I' and 'J', and 'U' and 'V' as //! interchangeable characters - as would have been the case in Bacon's time. //! //! If no concealing text is given and the boilerplate of "Lorem ipsum..." is used, //! a plaintext message of up to ~50 characters may be hidden. //! use crate::common::cipher::Cipher; use lipsum::lipsum; use std::collections::HashMap; use std::string::String; // The default code length const CODE_LEN: usize = 5; // Code mappings: // * note: that str is preferred over char as it cannot be guaranteed that // there will be a single codepoint for a given character. lazy_static! { static ref CODE_MAP: HashMap<&'static str, &'static str> = hashmap! { "A" => "AAAAA", "B" => "AAAAB", "C" => "AAABA", "D" => "AAABB", "E" => "AABAA", "F" => "AABAB", "G" => "AABBA", "H" => "AABBB", "I" => "ABAAA", "J" => "ABAAB", "K" => "ABABA", "L" => "ABABB", "M" => "ABBAA", "N" => "ABBAB", "O" => "ABBBA", "P" => "ABBBB", "Q" => "BAAAA", "R" => "BAAAB", "S" => "BAABA", "T" => "BAABB", "U" => "BABAA", "V" => "BABAB", "W" => "BABBA", "X" => "BABBB", "Y" => "BBAAA", "Z" => "BBAAB" }; } // A mapping of alphabet to italic UTF-8 italic codes lazy_static! { static ref ITALIC_CODES: HashMap<&'static str, char> = hashmap!{ // Using Mathematical Italic "A" => '\u{1D434}', "B" => '\u{1D435}', "C" => '\u{1D436}', "D" => '\u{1D437}', "E" => '\u{1D438}', "F" => '\u{1D439}', "G" => '\u{1D43a}', "H" => '\u{1D43b}', "I" => '\u{1D43c}', "J" => '\u{1D43d}', "K" => '\u{1D43e}', "L" => '\u{1D43f}', "M" => '\u{1D440}', "N" => '\u{1D441}', "O" => '\u{1D442}', "P" => '\u{1D443}', "Q" => '\u{1D444}', "R" => '\u{1D445}', "S" => '\u{1D446}', "T" => '\u{1D447}', "U" => '\u{1D448}', "V" => '\u{1D449}', "W" => '\u{1D44a}', "X" => '\u{1D44b}', "Y" => '\u{1D44c}', "Z" => '\u{1D44d}', // Using Mathematical Sans-Serif Italic "a" => '\u{1D622}', "b" => '\u{1D623}', "c" => '\u{1D624}', "d" => '\u{1D625}', "e" => '\u{1D626}', "f" => '\u{1D627}', "g" => '\u{1D628}', "h" => '\u{1D629}', "i" => '\u{1D62a}', "j" => '\u{1D62b}', "k" => '\u{1D62c}', "l" => '\u{1D62d}', "m" => '\u{1D62e}', "n" => '\u{1D62f}', "o" => '\u{1D630}', "p" => '\u{1D631}', "q" => '\u{1D632}', "r" => '\u{1D633}', "s" => '\u{1D634}', "t" => '\u{1D635}', "u" => '\u{1D636}', "v" => '\u{1D637}', "w" => '\u{1D638}', "x" => '\u{1D639}', "y" => '\u{1D63a}', "z" => '\u{1D63b}' }; } /// Get the code for a given key (source character) fn get_code(use_distinct_alphabet: bool, key: &str) -> String { let mut code = String::new(); // Need to handle 'I'/'J' and 'U'/'V' // for traditional usage. let mut key_upper = key.to_uppercase(); if!use_distinct_alphabet { match key_upper.as_str() { "J" => key_upper = "I".to_string(), "U" => key_upper = "V".to_string(), _ => {} } } if CODE_MAP.contains_key(key_upper.as_str()) { code.push_str(CODE_MAP.get(key_upper.as_str()).unwrap()); } code } /// Gets the key (the source character) for a given cipher text code fn get_key(code: &str) -> String { let mut key = String::new(); for (_key, val) in CODE_MAP.iter() { if val == &code { key.push_str(_key); } } key } /// This struct is created by the `new()` method. See its documentation for more. pub struct Baconian { use_distinct_alphabet: bool, decoy_text: String, } impl Cipher for Baconian { type Key = (bool, Option<String>); type Algorithm = Baconian; /// Initialise a Baconian cipher /// /// The `key` tuple maps to the following: `(bool, Option<str>) = (use_distinct_alphabet, decoy_text)`. /// Where... /// /// * The encoding will be use_distinct_alphabet for all alphabetical characters, or classical /// where I, J, U and V are mapped to the same value pairs /// * An optional decoy message that will will be used to hide the message - /// default is boilerplate "Lorem ipsum" text. /// fn new(key: (bool, Option<String>)) -> Baconian { Baconian { use_distinct_alphabet: key.0, decoy_text: key.1.unwrap_or_else(|| lipsum(160)), } } /// Encrypt a message using the Baconian cipher /// /// * The message to be encrypted can only be ~18% of the decoy_text as each character /// of message is encoded by 5 encoding characters `AAAAA`, `AAAAB`, etc. /// * The italicised ciphertext is then hidden in a decoy text, where, for each 'B' /// in the ciphertext, the character is italicised in the decoy_text. /// /// # Examples /// Basic usage: /// /// ``` /// use cipher_crypt::{Cipher, Baconian}; /// /// let b = Baconian::new((false, None));; /// let message = "Hello"; /// let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘤𝘰n"; /// /// assert_eq!(cipher_text, b.encrypt(message).unwrap()); /// ``` fn encrypt(&self, message: &str) -> Result<String, &'static str> { let num_non_alphas = self .decoy_text .chars() .filter(|c|!c.is_alphabetic()) .count(); // Check whether the message fits in the decoy // Note: that non-alphabetical characters will be skipped. if (message.len() * CODE_LEN) > self.decoy_text.len() - num_non_alphas { return Err("Message too long for supplied decoy text."); } // Iterate through the message encoding each char (ignoring non-alphabetical chars) let secret: String = message .chars() .map(|c| get_code(self.use_distinct_alphabet, &c.to_string())) .collect(); let mut num_alphas = 0; let mut num_non_alphas = 0; for c in self.decoy_text.chars() { if num_alphas == secret.len() { break; } if c.is_alphabetic() { num_alphas += 1 } else { num_non_alphas += 1 }; } let decoy_slice: String = self .decoy_text .chars() .take(num_alphas + num_non_alphas) .collect(); // We now have an encoded message, `secret`, in which each character of of the // original plaintext is now represented by a 5-bit binary character, // "AAAAA", "ABABA" etc. // We now overlay the encoded text onto the decoy slice, and // where the binary 'B' is found the decoy slice char is swapped for an italic let mut decoy_msg = String::new(); let mut secret_iter = secret.chars(); for c in decoy_slice.chars() { if c.is_alphabetic() { if let Some(sc) = secret_iter.next() { if sc == 'B' { // match the binary 'B' and swap for italic let italic = *ITALIC_CODES.get(c.to_string().as_str()).unwrap(); decoy_msg.push(italic); } else { decoy_msg.push(c); } } } else { decoy_msg.push(c); } } Ok(decoy_msg) } /// Decrypt a message that was encrypted with the Baconian cipher /// /// # Examples /// Basic usage: /// /// ``` /// use cipher_crypt::{Cipher, Baconian}; /// /// let b = Baconian::new((false, None));; /// let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘯𝘦 t"; /// /// assert_eq!("HELLO", b.decrypt(cipher_text).unwrap()); /// ``` /// fn decrypt(&self, message: &str) -> Result<String, &'static str> { // The message is decoy text // Iterate through swapping any alphabetical chars found in the ITALIC_CODES // set to be 'B', else 'A', skip anything else. let ciphertext: String = message .chars() .filter(|c| c.is_alphabetic()) .map(|c| { if ITALIC_CODES.iter().any(|e| *e.1 == c) { 'B' } else { 'A' } }) .collect(); let mut plaintext = String::new(); let mut code = String::new(); for c in ciphertext.chars() { code.push(c); if code.len() == CODE_LEN { // If we have the right length code plaintext += &get_key(&code); code.clear(); } } Ok(plaintext) } } #[cfg(test)] mod tests { use super::*; #[test] fn encrypt_simple() { let b = Baconian::new((false, None)); let message = "Hello"; let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘤𝘰n";
} // Need to test that the traditional and use_distinct_alphabet codes give different results #[test] fn encrypt_trad_v_dist() { let b_trad = Baconian::new((false, None)); let b_dist = Baconian::new((true, None)); let message = "I JADE YOU VERVENT UNICORN"; assert_ne!( b_dist.encrypt(&message).unwrap(), b_trad.encrypt(message).unwrap() ); } #[test] fn encrypt_message_spaced() { let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let b = Baconian::new((false, Some(decoy_text))); let message = "Peace, Freedom 🗡️ and Liberty!"; let cipher_text = "T𝘩𝘦 𝘸𝘰rl𝘥\'s a bubble; an𝘥 the 𝘭ife o𝘧 m𝘢𝘯 les𝘴 th𝘢n a sp𝘢n. \ In hi𝘴 𝘤o𝘯𝘤𝘦pt𝘪𝘰n wretche𝘥; 𝘧r𝘰m th𝘦 𝘸o𝘮b 𝘴𝘰 t𝘰 the tomb: \ 𝐶ur𝘴t f𝘳om t𝘩𝘦 cr𝘢𝘥𝘭𝘦, and"; assert_eq!(cipher_text, b.encrypt(message).unwrap()); } // use_distinct_alphabet lexicon #[test] #[should_panic(expected = r#"Message too long for supplied decoy text."#)] fn encrypt_decoy_too_short() { let b = Baconian::new((false, None)); let message = "This is a long message that will be too long to encode using \ the default decoy text. In order to have a long message encoded you need a \ decoy text that is at least five times as long, plus the non-alphabeticals."; b.encrypt(message).unwrap(); } #[test] fn encrypt_with_use_distinct_alphabet_codeset() { let message = "Peace, Freedom 🗡️ and Liberty!"; let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let cipher_text = "T𝘩𝘦 𝘸𝘰rl𝘥's a bubble; an𝘥 the 𝘭ife o𝘧 m𝘢𝘯 les𝘴 th𝘢n a sp𝘢n. \ In hi𝘴 𝘤o𝘯𝘤𝘦pt𝘪𝘰n wretche𝘥; 𝘧r𝘰m th𝘦 𝘸o𝘮b 𝘴𝘰 t𝘰 the tomb: \ 𝐶ur𝘴t f𝘳om t𝘩𝘦 cr𝘢𝘥𝘭𝘦, and"; let b = Baconian::new((true, Some(decoy_text))); assert_eq!(cipher_text, b.encrypt(message).unwrap()); } #[test] fn decrypt_a_classic() { let cipher_text = String::from("Let's c𝘰mp𝘳𝘰𝘮is𝘦. 𝐻old off th𝘦 at𝘵a𝘤k"); let message = "ATTACK"; let decoy_text = String::from("Let's compromise. Hold off the attack"); let b = Baconian::new((true, Some(decoy_text))); assert_eq!(message, b.decrypt(&cipher_text).unwrap()); } #[test] fn decrypt_traditional() { let cipher_text = String::from( "T𝘩e wor𝘭d's a bubble; an𝘥 𝘵he 𝘭if𝘦 𝘰f man 𝘭𝘦𝘴s 𝘵h𝘢n 𝘢 𝘴p𝘢n. \ 𝐼n h𝘪s c𝘰nce𝘱𝘵i𝘰n 𝘸re𝘵che𝘥; 𝘧r𝘰𝘮 th𝘦 𝘸𝘰m𝘣 s𝘰 t𝘰 𝘵h𝘦 t𝘰mb: \ Curs𝘵 fr𝘰𝘮 𝘵h𝘦 cra𝘥l𝘦, 𝘢n𝘥", ); // Note: the substitution for 'I'/'J' and 'U'/'V' let message = "IIADEYOVVERVENTVNICORN"; let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let b = Baconian::new((false, Some(decoy_text))); assert_eq!(message, b.decrypt(&cipher_text).unwrap()); } }
assert_eq!(cipher_text, b.encrypt(message).unwrap());
random_line_split
recv_stream.rs
VarInt, }; /// A stream that can only be used to receive data /// /// `stop(0)` is implicitly called on drop unless: /// - A variant of [`ReadError`] has been yielded by a read call /// - [`stop()`] was called explicitly /// /// # Closing a stream /// /// When a stream is expected to be closed gracefully the sender should call /// [`SendStream::finish`]. However there is no guarantee the connected [`RecvStream`] will /// receive the "finished" notification in the same QUIC frame as the last frame which /// carried data. /// /// Even if the application layer logic already knows it read all the data because it does /// its own framing, it should still read until it reaches the end of the [`RecvStream`]. /// Otherwise it risks inadvertently calling [`RecvStream::stop`] if it drops the stream. /// And calling [`RecvStream::stop`] could result in the connected [`SendStream::finish`] /// call failing with a [`WriteError::Stopped`] error. /// /// For example if exactly 10 bytes are to be read, you still need to explicitly read the /// end of the stream: /// /// ```no_run /// # use quinn::{SendStream, RecvStream}; /// # async fn func( /// # mut send_stream: SendStream, /// # mut recv_stream: RecvStream, /// # ) -> anyhow::Result<()> /// # { /// // In the sending task /// send_stream.write(&b"0123456789"[..]).await?; /// send_stream.finish().await?; /// /// // In the receiving task /// let mut buf = [0u8; 10]; /// let data = recv_stream.read_exact(&mut buf).await?; /// if recv_stream.read_to_end(0).await.is_err() { /// // Discard unexpected data and notify the peer to stop sending it /// let _ = recv_stream.stop(0u8.into()); /// } /// # Ok(()) /// # } /// ``` /// /// An alternative approach, used in HTTP/3, is to specify a particular error code used with `stop` /// that indicates graceful receiver-initiated stream shutdown, rather than a true error condition. /// /// [`RecvStream::read_chunk`] could be used instead which does not take ownership and /// allows using an explicit call to [`RecvStream::stop`] with a custom error code. /// /// [`ReadError`]: crate::ReadError /// [`stop()`]: RecvStream::stop /// [`SendStream::finish`]: crate::SendStream::finish /// [`WriteError::Stopped`]: crate::WriteError::Stopped #[derive(Debug)] pub struct RecvStream { conn: ConnectionRef, stream: StreamId, is_0rtt: bool, all_data_read: bool, reset: Option<VarInt>, } impl RecvStream { pub(crate) fn new(conn: ConnectionRef, stream: StreamId, is_0rtt: bool) -> Self { Self { conn, stream, is_0rtt, all_data_read: false, reset: None, } } /// Read data contiguously from the stream. /// /// Yields the number of bytes read into `buf` on success, or `None` if the stream was finished. pub async fn
(&mut self, buf: &mut [u8]) -> Result<Option<usize>, ReadError> { Read { stream: self, buf: ReadBuf::new(buf), } .await } /// Read an exact number of bytes contiguously from the stream. /// /// See [`read()`] for details. /// /// [`read()`]: RecvStream::read pub async fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), ReadExactError> { ReadExact { stream: self, buf: ReadBuf::new(buf), } .await } fn poll_read( &mut self, cx: &mut Context, buf: &mut ReadBuf<'_>, ) -> Poll<Result<(), ReadError>> { if buf.remaining() == 0 { return Poll::Ready(Ok(())); } self.poll_read_generic(cx, true, |chunks| { let mut read = false; loop { if buf.remaining() == 0 { // We know `read` is `true` because `buf.remaining()` was not 0 before return ReadStatus::Readable(()); } match chunks.next(buf.remaining()) { Ok(Some(chunk)) => { buf.put_slice(&chunk.bytes); read = true; } res => return (if read { Some(()) } else { None }, res.err()).into(), } } }) .map(|res| res.map(|_| ())) } /// Read the next segment of data /// /// Yields `None` if the stream was finished. Otherwise, yields a segment of data and its /// offset in the stream. If `ordered` is `true`, the chunk's offset will be immediately after /// the last data yielded by `read()` or `read_chunk()`. If `ordered` is `false`, segments may /// be received in any order, and the `Chunk`'s `offset` field can be used to determine /// ordering in the caller. Unordered reads are less prone to head-of-line blocking within a /// stream, but require the application to manage reassembling the original data. /// /// Slightly more efficient than `read` due to not copying. Chunk boundaries do not correspond /// to peer writes, and hence cannot be used as framing. pub async fn read_chunk( &mut self, max_length: usize, ordered: bool, ) -> Result<Option<Chunk>, ReadError> { ReadChunk { stream: self, max_length, ordered, } .await } /// Foundation of [`Self::read_chunk`] fn poll_read_chunk( &mut self, cx: &mut Context, max_length: usize, ordered: bool, ) -> Poll<Result<Option<Chunk>, ReadError>> { self.poll_read_generic(cx, ordered, |chunks| match chunks.next(max_length) { Ok(Some(chunk)) => ReadStatus::Readable(chunk), res => (None, res.err()).into(), }) } /// Read the next segments of data /// /// Fills `bufs` with the segments of data beginning immediately after the /// last data yielded by `read` or `read_chunk`, or `None` if the stream was /// finished. /// /// Slightly more efficient than `read` due to not copying. Chunk boundaries /// do not correspond to peer writes, and hence cannot be used as framing. pub async fn read_chunks(&mut self, bufs: &mut [Bytes]) -> Result<Option<usize>, ReadError> { ReadChunks { stream: self, bufs }.await } /// Foundation of [`Self::read_chunks`] fn poll_read_chunks( &mut self, cx: &mut Context, bufs: &mut [Bytes], ) -> Poll<Result<Option<usize>, ReadError>> { if bufs.is_empty() { return Poll::Ready(Ok(Some(0))); } self.poll_read_generic(cx, true, |chunks| { let mut read = 0; loop { if read >= bufs.len() { // We know `read > 0` because `bufs` cannot be empty here return ReadStatus::Readable(read); } match chunks.next(usize::MAX) { Ok(Some(chunk)) => { bufs[read] = chunk.bytes; read += 1; } res => return (if read == 0 { None } else { Some(read) }, res.err()).into(), } } }) } /// Convenience method to read all remaining data into a buffer /// /// Fails with [`ReadToEndError::TooLong`] on reading more than `size_limit` bytes, discarding /// all data read. Uses unordered reads to be more efficient than using `AsyncRead` would /// allow. `size_limit` should be set to limit worst-case memory use. /// /// If unordered reads have already been made, the resulting buffer may have gaps containing /// arbitrary data. /// /// [`ReadToEndError::TooLong`]: crate::ReadToEndError::TooLong pub async fn read_to_end(&mut self, size_limit: usize) -> Result<Vec<u8>, ReadToEndError> { ReadToEnd { stream: self, size_limit, read: Vec::new(), start: u64::max_value(), end: 0, } .await } /// Stop accepting data /// /// Discards unread data and notifies the peer to stop transmitting. Once stopped, further /// attempts to operate on a stream will yield `UnknownStream` errors. pub fn stop(&mut self, error_code: VarInt) -> Result<(), UnknownStream> { let mut conn = self.conn.state.lock("RecvStream::stop"); if self.is_0rtt && conn.check_0rtt().is_err() { return Ok(()); } conn.inner.recv_stream(self.stream).stop(error_code)?; conn.wake(); self.all_data_read = true; Ok(()) } /// Check if this stream has been opened during 0-RTT. /// /// In which case any non-idempotent request should be considered dangerous at the application /// level. Because read data is subject to replay attacks. pub fn is_0rtt(&self) -> bool { self.is_0rtt } /// Get the identity of this stream pub fn id(&self) -> StreamId { self.stream } /// Handle common logic related to reading out of a receive stream /// /// This takes an `FnMut` closure that takes care of the actual reading process, matching /// the detailed read semantics for the calling function with a particular return type. /// The closure can read from the passed `&mut Chunks` and has to return the status after /// reading: the amount of data read, and the status after the final read call. fn poll_read_generic<T, U>( &mut self, cx: &mut Context, ordered: bool, mut read_fn: T, ) -> Poll<Result<Option<U>, ReadError>> where T: FnMut(&mut Chunks) -> ReadStatus<U>, { use proto::ReadError::*; if self.all_data_read { return Poll::Ready(Ok(None)); } let mut conn = self.conn.state.lock("RecvStream::poll_read"); if self.is_0rtt { conn.check_0rtt().map_err(|()| ReadError::ZeroRttRejected)?; } // If we stored an error during a previous call, return it now. This can happen if a // `read_fn` both wants to return data and also returns an error in its final stream status. let status = match self.reset.take() { Some(code) => ReadStatus::Failed(None, Reset(code)), None => { let mut recv = conn.inner.recv_stream(self.stream); let mut chunks = recv.read(ordered)?; let status = read_fn(&mut chunks); if chunks.finalize().should_transmit() { conn.wake(); } status } }; match status { ReadStatus::Readable(read) => Poll::Ready(Ok(Some(read))), ReadStatus::Finished(read) => { self.all_data_read = true; Poll::Ready(Ok(read)) } ReadStatus::Failed(read, Blocked) => match read { Some(val) => Poll::Ready(Ok(Some(val))), None => { if let Some(ref x) = conn.error { return Poll::Ready(Err(ReadError::ConnectionLost(x.clone()))); } conn.blocked_readers.insert(self.stream, cx.waker().clone()); Poll::Pending } }, ReadStatus::Failed(read, Reset(error_code)) => match read { None => { self.all_data_read = true; Poll::Ready(Err(ReadError::Reset(error_code))) } done => { self.reset = Some(error_code); Poll::Ready(Ok(done)) } }, } } } enum ReadStatus<T> { Readable(T), Finished(Option<T>), Failed(Option<T>, proto::ReadError), } impl<T> From<(Option<T>, Option<proto::ReadError>)> for ReadStatus<T> { fn from(status: (Option<T>, Option<proto::ReadError>)) -> Self { match status { (read, None) => Self::Finished(read), (read, Some(e)) => Self::Failed(read, e), } } } /// Future produced by [`RecvStream::read_to_end()`]. /// /// [`RecvStream::read_to_end()`]: crate::RecvStream::read_to_end #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadToEnd<'a> { stream: &'a mut RecvStream, read: Vec<(Bytes, u64)>, start: u64, end: u64, size_limit: usize, } impl Future for ReadToEnd<'_> { type Output = Result<Vec<u8>, ReadToEndError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { loop { match ready!(self.stream.poll_read_chunk(cx, usize::MAX, false))? { Some(chunk) => { self.start = self.start.min(chunk.offset); let end = chunk.bytes.len() as u64 + chunk.offset; if (end - self.start) > self.size_limit as u64 { return Poll::Ready(Err(ReadToEndError::TooLong)); } self.end = self.end.max(end); self.read.push((chunk.bytes, chunk.offset)); } None => { if self.end == 0 { // Never received anything return Poll::Ready(Ok(Vec::new())); } let start = self.start; let mut buffer = vec![0; (self.end - start) as usize]; for (data, offset) in self.read.drain(..) { let offset = (offset - start) as usize; buffer[offset..offset + data.len()].copy_from_slice(&data); } return Poll::Ready(Ok(buffer)); } } } } } /// Errors from [`RecvStream::read_to_end`] #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadToEndError { /// An error occurred during reading #[error("read error: {0}")] Read(#[from] ReadError), /// The stream is larger than the user-supplied limit #[error("stream too long")] TooLong, } #[cfg(feature = "futures-io")] impl futures_io::AsyncRead for RecvStream { fn poll_read( self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8], ) -> Poll<io::Result<usize>> { let mut buf = ReadBuf::new(buf); ready!(RecvStream::poll_read(self.get_mut(), cx, &mut buf))?; Poll::Ready(Ok(buf.filled().len())) } } impl tokio::io::AsyncRead for RecvStream { fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { ready!(Self::poll_read(self.get_mut(), cx, buf))?; Poll::Ready(Ok(())) } } impl Drop for RecvStream { fn drop(&mut self) { let mut conn = self.conn.state.lock("RecvStream::drop"); // clean up any previously registered wakers conn.blocked_readers.remove(&self.stream); if conn.error.is_some() || (self.is_0rtt && conn.check_0rtt().is_err()) { return; } if!self.all_data_read { // Ignore UnknownStream errors let _ = conn.inner.recv_stream(self.stream).stop(0u32.into()); conn.wake(); } } } /// Errors that arise from reading from a stream. #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadError { /// The peer abandoned transmitting data on this stream /// /// Carries an application-defined error code. #[error("stream reset by peer: error {0}")] Reset(VarInt), /// The connection was lost #[error("connection lost")] ConnectionLost(#[from] ConnectionError), /// The stream has already been stopped, finished, or reset #[error("unknown stream")] UnknownStream, /// Attempted an ordered read following an unordered read /// /// Performing an unordered read allows discontinuities to arise in the receive buffer of a /// stream which cannot be recovered, making further ordered reads impossible. #[error("ordered read after unordered read")] IllegalOrderedRead, /// This was a 0-RTT stream and the server rejected it /// /// Can only occur on clients for 0-RTT streams, which can be opened using /// [`Connecting::into_0rtt()`]. /// /// [`Connecting::into_0rtt()`]: crate::Connecting::into_0rtt() #[error("0-RTT rejected")] ZeroRttRejected, } impl From<ReadableError> for ReadError { fn from(e: ReadableError) -> Self { match e { ReadableError::UnknownStream => Self::UnknownStream, ReadableError::IllegalOrderedRead => Self::IllegalOrderedRead, } } } impl From<ReadError> for io::Error { fn from(x: ReadError) -> Self { use self::ReadError::*; let kind = match x { Reset {.. } | ZeroRttRejected => io::ErrorKind::ConnectionReset, ConnectionLost(_) | UnknownStream => io::ErrorKind::NotConnected, IllegalOrderedRead => io::ErrorKind::InvalidInput, }; Self::new(kind, x) } } /// Future produced by [`RecvStream::read()`]. /// /// [`RecvStream::read()`]: crate::RecvStream::read #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct Read<'a> { stream: &'a mut RecvStream, buf: ReadBuf<'a>, } impl<'a> Future for Read<'a> { type Output = Result<Option<usize>, ReadError>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let this = self.get_mut(); ready!(this.stream.poll_read(cx, &mut this.buf))?; match this.buf.filled().len() { 0 if this.buf.capacity()!= 0 => Poll::Ready(Ok(None)), n => Poll::Ready(Ok(Some(n))), } } } /// Future produced by [`RecvStream::read_exact()`]. /// /// [`RecvStream::read_exact()`]: crate::RecvStream::read_exact #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadExact<'a> { stream: &'a mut RecvStream, buf: ReadBuf<'a>, } impl<'a> Future for ReadExact<'a> { type Output = Result<(), ReadExactError>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let this = self.get_mut(); let mut remaining = this.buf.remaining(); while remaining > 0 { ready!(this.stream.poll_read(cx, &mut this.buf))?; let new = this.buf.remaining(); if new == remaining { return Poll::Ready(Err(ReadExactError::FinishedEarly)); } remaining = new; } Poll::Ready(Ok(())) } } /// Errors that arise from reading from a stream. #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadExactError { /// The stream finished before all bytes were read #[error("stream finished early")] FinishedEarly, /// A read error occurred #[error(transparent)] ReadError(#[from] ReadError), } /// Future produced by [`RecvStream::read_chunk()`]. /// /// [`RecvStream::read_chunk()`]: crate::RecvStream::read_chunk #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadChunk<'a> { stream: &'a mut RecvStream, max_length: usize, ordered: bool, } impl<'a> Future for ReadChunk<'a> { type Output = Result<Option<Chunk>, ReadError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let (max_length, ordered) = (self.max_length, self.ordered); self.stream.
read
identifier_name
recv_stream.rs
}, VarInt, }; /// A stream that can only be used to receive data /// /// `stop(0)` is implicitly called on drop unless: /// - A variant of [`ReadError`] has been yielded by a read call /// - [`stop()`] was called explicitly /// /// # Closing a stream /// /// When a stream is expected to be closed gracefully the sender should call /// [`SendStream::finish`]. However there is no guarantee the connected [`RecvStream`] will /// receive the "finished" notification in the same QUIC frame as the last frame which /// carried data. /// /// Even if the application layer logic already knows it read all the data because it does /// its own framing, it should still read until it reaches the end of the [`RecvStream`]. /// Otherwise it risks inadvertently calling [`RecvStream::stop`] if it drops the stream. /// And calling [`RecvStream::stop`] could result in the connected [`SendStream::finish`] /// call failing with a [`WriteError::Stopped`] error. /// /// For example if exactly 10 bytes are to be read, you still need to explicitly read the /// end of the stream: /// /// ```no_run /// # use quinn::{SendStream, RecvStream}; /// # async fn func( /// # mut send_stream: SendStream, /// # mut recv_stream: RecvStream, /// # ) -> anyhow::Result<()> /// # { /// // In the sending task /// send_stream.write(&b"0123456789"[..]).await?; /// send_stream.finish().await?; /// /// // In the receiving task /// let mut buf = [0u8; 10]; /// let data = recv_stream.read_exact(&mut buf).await?; /// if recv_stream.read_to_end(0).await.is_err() { /// // Discard unexpected data and notify the peer to stop sending it /// let _ = recv_stream.stop(0u8.into()); /// } /// # Ok(()) /// # } /// ``` /// /// An alternative approach, used in HTTP/3, is to specify a particular error code used with `stop` /// that indicates graceful receiver-initiated stream shutdown, rather than a true error condition. /// /// [`RecvStream::read_chunk`] could be used instead which does not take ownership and /// allows using an explicit call to [`RecvStream::stop`] with a custom error code. /// /// [`ReadError`]: crate::ReadError /// [`stop()`]: RecvStream::stop /// [`SendStream::finish`]: crate::SendStream::finish /// [`WriteError::Stopped`]: crate::WriteError::Stopped #[derive(Debug)] pub struct RecvStream { conn: ConnectionRef, stream: StreamId, is_0rtt: bool, all_data_read: bool, reset: Option<VarInt>, } impl RecvStream { pub(crate) fn new(conn: ConnectionRef, stream: StreamId, is_0rtt: bool) -> Self { Self { conn, stream, is_0rtt, all_data_read: false, reset: None, } } /// Read data contiguously from the stream. /// /// Yields the number of bytes read into `buf` on success, or `None` if the stream was finished. pub async fn read(&mut self, buf: &mut [u8]) -> Result<Option<usize>, ReadError> { Read { stream: self, buf: ReadBuf::new(buf), } .await } /// Read an exact number of bytes contiguously from the stream. /// /// See [`read()`] for details. /// /// [`read()`]: RecvStream::read pub async fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), ReadExactError> { ReadExact { stream: self, buf: ReadBuf::new(buf), } .await } fn poll_read( &mut self, cx: &mut Context, buf: &mut ReadBuf<'_>, ) -> Poll<Result<(), ReadError>> { if buf.remaining() == 0 { return Poll::Ready(Ok(())); } self.poll_read_generic(cx, true, |chunks| { let mut read = false; loop { if buf.remaining() == 0 { // We know `read` is `true` because `buf.remaining()` was not 0 before return ReadStatus::Readable(()); } match chunks.next(buf.remaining()) { Ok(Some(chunk)) => { buf.put_slice(&chunk.bytes); read = true; } res => return (if read { Some(()) } else { None }, res.err()).into(), } } }) .map(|res| res.map(|_| ())) } /// Read the next segment of data /// /// Yields `None` if the stream was finished. Otherwise, yields a segment of data and its /// offset in the stream. If `ordered` is `true`, the chunk's offset will be immediately after /// the last data yielded by `read()` or `read_chunk()`. If `ordered` is `false`, segments may /// be received in any order, and the `Chunk`'s `offset` field can be used to determine /// ordering in the caller. Unordered reads are less prone to head-of-line blocking within a /// stream, but require the application to manage reassembling the original data. /// /// Slightly more efficient than `read` due to not copying. Chunk boundaries do not correspond /// to peer writes, and hence cannot be used as framing. pub async fn read_chunk( &mut self, max_length: usize, ordered: bool, ) -> Result<Option<Chunk>, ReadError> { ReadChunk { stream: self, max_length, ordered, } .await } /// Foundation of [`Self::read_chunk`] fn poll_read_chunk( &mut self, cx: &mut Context, max_length: usize, ordered: bool, ) -> Poll<Result<Option<Chunk>, ReadError>> { self.poll_read_generic(cx, ordered, |chunks| match chunks.next(max_length) { Ok(Some(chunk)) => ReadStatus::Readable(chunk), res => (None, res.err()).into(), }) } /// Read the next segments of data /// /// Fills `bufs` with the segments of data beginning immediately after the /// last data yielded by `read` or `read_chunk`, or `None` if the stream was /// finished. /// /// Slightly more efficient than `read` due to not copying. Chunk boundaries /// do not correspond to peer writes, and hence cannot be used as framing. pub async fn read_chunks(&mut self, bufs: &mut [Bytes]) -> Result<Option<usize>, ReadError> { ReadChunks { stream: self, bufs }.await } /// Foundation of [`Self::read_chunks`] fn poll_read_chunks( &mut self, cx: &mut Context, bufs: &mut [Bytes], ) -> Poll<Result<Option<usize>, ReadError>> { if bufs.is_empty() { return Poll::Ready(Ok(Some(0))); } self.poll_read_generic(cx, true, |chunks| { let mut read = 0; loop { if read >= bufs.len() { // We know `read > 0` because `bufs` cannot be empty here return ReadStatus::Readable(read); } match chunks.next(usize::MAX) { Ok(Some(chunk)) => { bufs[read] = chunk.bytes; read += 1; } res => return (if read == 0 { None } else { Some(read) }, res.err()).into(), } } }) } /// Convenience method to read all remaining data into a buffer /// /// Fails with [`ReadToEndError::TooLong`] on reading more than `size_limit` bytes, discarding /// all data read. Uses unordered reads to be more efficient than using `AsyncRead` would /// allow. `size_limit` should be set to limit worst-case memory use. /// /// If unordered reads have already been made, the resulting buffer may have gaps containing /// arbitrary data. /// /// [`ReadToEndError::TooLong`]: crate::ReadToEndError::TooLong pub async fn read_to_end(&mut self, size_limit: usize) -> Result<Vec<u8>, ReadToEndError> { ReadToEnd { stream: self, size_limit, read: Vec::new(), start: u64::max_value(), end: 0, } .await } /// Stop accepting data /// /// Discards unread data and notifies the peer to stop transmitting. Once stopped, further /// attempts to operate on a stream will yield `UnknownStream` errors. pub fn stop(&mut self, error_code: VarInt) -> Result<(), UnknownStream> { let mut conn = self.conn.state.lock("RecvStream::stop"); if self.is_0rtt && conn.check_0rtt().is_err() { return Ok(()); } conn.inner.recv_stream(self.stream).stop(error_code)?; conn.wake(); self.all_data_read = true; Ok(()) } /// Check if this stream has been opened during 0-RTT. /// /// In which case any non-idempotent request should be considered dangerous at the application /// level. Because read data is subject to replay attacks. pub fn is_0rtt(&self) -> bool { self.is_0rtt } /// Get the identity of this stream pub fn id(&self) -> StreamId { self.stream } /// Handle common logic related to reading out of a receive stream /// /// This takes an `FnMut` closure that takes care of the actual reading process, matching /// the detailed read semantics for the calling function with a particular return type. /// The closure can read from the passed `&mut Chunks` and has to return the status after /// reading: the amount of data read, and the status after the final read call. fn poll_read_generic<T, U>( &mut self, cx: &mut Context, ordered: bool, mut read_fn: T, ) -> Poll<Result<Option<U>, ReadError>> where T: FnMut(&mut Chunks) -> ReadStatus<U>, { use proto::ReadError::*; if self.all_data_read { return Poll::Ready(Ok(None)); } let mut conn = self.conn.state.lock("RecvStream::poll_read"); if self.is_0rtt { conn.check_0rtt().map_err(|()| ReadError::ZeroRttRejected)?; } // If we stored an error during a previous call, return it now. This can happen if a // `read_fn` both wants to return data and also returns an error in its final stream status. let status = match self.reset.take() { Some(code) => ReadStatus::Failed(None, Reset(code)), None => { let mut recv = conn.inner.recv_stream(self.stream); let mut chunks = recv.read(ordered)?; let status = read_fn(&mut chunks); if chunks.finalize().should_transmit() { conn.wake(); } status } }; match status { ReadStatus::Readable(read) => Poll::Ready(Ok(Some(read))), ReadStatus::Finished(read) => { self.all_data_read = true; Poll::Ready(Ok(read)) } ReadStatus::Failed(read, Blocked) => match read { Some(val) => Poll::Ready(Ok(Some(val))), None => { if let Some(ref x) = conn.error { return Poll::Ready(Err(ReadError::ConnectionLost(x.clone()))); } conn.blocked_readers.insert(self.stream, cx.waker().clone()); Poll::Pending } }, ReadStatus::Failed(read, Reset(error_code)) => match read { None => { self.all_data_read = true; Poll::Ready(Err(ReadError::Reset(error_code))) } done => { self.reset = Some(error_code); Poll::Ready(Ok(done)) } }, } } } enum ReadStatus<T> { Readable(T), Finished(Option<T>), Failed(Option<T>, proto::ReadError), } impl<T> From<(Option<T>, Option<proto::ReadError>)> for ReadStatus<T> { fn from(status: (Option<T>, Option<proto::ReadError>)) -> Self { match status { (read, None) => Self::Finished(read), (read, Some(e)) => Self::Failed(read, e), } } } /// Future produced by [`RecvStream::read_to_end()`]. /// /// [`RecvStream::read_to_end()`]: crate::RecvStream::read_to_end #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadToEnd<'a> { stream: &'a mut RecvStream, read: Vec<(Bytes, u64)>, start: u64, end: u64, size_limit: usize, } impl Future for ReadToEnd<'_> { type Output = Result<Vec<u8>, ReadToEndError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { loop { match ready!(self.stream.poll_read_chunk(cx, usize::MAX, false))? { Some(chunk) => { self.start = self.start.min(chunk.offset); let end = chunk.bytes.len() as u64 + chunk.offset; if (end - self.start) > self.size_limit as u64 { return Poll::Ready(Err(ReadToEndError::TooLong)); } self.end = self.end.max(end); self.read.push((chunk.bytes, chunk.offset)); } None => { if self.end == 0 { // Never received anything return Poll::Ready(Ok(Vec::new())); } let start = self.start; let mut buffer = vec![0; (self.end - start) as usize]; for (data, offset) in self.read.drain(..) { let offset = (offset - start) as usize; buffer[offset..offset + data.len()].copy_from_slice(&data); } return Poll::Ready(Ok(buffer)); } } } } } /// Errors from [`RecvStream::read_to_end`] #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadToEndError { /// An error occurred during reading #[error("read error: {0}")] Read(#[from] ReadError), /// The stream is larger than the user-supplied limit #[error("stream too long")] TooLong, } #[cfg(feature = "futures-io")] impl futures_io::AsyncRead for RecvStream { fn poll_read( self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8], ) -> Poll<io::Result<usize>> { let mut buf = ReadBuf::new(buf); ready!(RecvStream::poll_read(self.get_mut(), cx, &mut buf))?; Poll::Ready(Ok(buf.filled().len())) } } impl tokio::io::AsyncRead for RecvStream { fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { ready!(Self::poll_read(self.get_mut(), cx, buf))?; Poll::Ready(Ok(())) } } impl Drop for RecvStream { fn drop(&mut self) { let mut conn = self.conn.state.lock("RecvStream::drop"); // clean up any previously registered wakers conn.blocked_readers.remove(&self.stream); if conn.error.is_some() || (self.is_0rtt && conn.check_0rtt().is_err()) { return; } if!self.all_data_read { // Ignore UnknownStream errors let _ = conn.inner.recv_stream(self.stream).stop(0u32.into()); conn.wake(); } } } /// Errors that arise from reading from a stream. #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadError { /// The peer abandoned transmitting data on this stream /// /// Carries an application-defined error code. #[error("stream reset by peer: error {0}")] Reset(VarInt), /// The connection was lost
UnknownStream, /// Attempted an ordered read following an unordered read /// /// Performing an unordered read allows discontinuities to arise in the receive buffer of a /// stream which cannot be recovered, making further ordered reads impossible. #[error("ordered read after unordered read")] IllegalOrderedRead, /// This was a 0-RTT stream and the server rejected it /// /// Can only occur on clients for 0-RTT streams, which can be opened using /// [`Connecting::into_0rtt()`]. /// /// [`Connecting::into_0rtt()`]: crate::Connecting::into_0rtt() #[error("0-RTT rejected")] ZeroRttRejected, } impl From<ReadableError> for ReadError { fn from(e: ReadableError) -> Self { match e { ReadableError::UnknownStream => Self::UnknownStream, ReadableError::IllegalOrderedRead => Self::IllegalOrderedRead, } } } impl From<ReadError> for io::Error { fn from(x: ReadError) -> Self { use self::ReadError::*; let kind = match x { Reset {.. } | ZeroRttRejected => io::ErrorKind::ConnectionReset, ConnectionLost(_) | UnknownStream => io::ErrorKind::NotConnected, IllegalOrderedRead => io::ErrorKind::InvalidInput, }; Self::new(kind, x) } } /// Future produced by [`RecvStream::read()`]. /// /// [`RecvStream::read()`]: crate::RecvStream::read #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct Read<'a> { stream: &'a mut RecvStream, buf: ReadBuf<'a>, } impl<'a> Future for Read<'a> { type Output = Result<Option<usize>, ReadError>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let this = self.get_mut(); ready!(this.stream.poll_read(cx, &mut this.buf))?; match this.buf.filled().len() { 0 if this.buf.capacity()!= 0 => Poll::Ready(Ok(None)), n => Poll::Ready(Ok(Some(n))), } } } /// Future produced by [`RecvStream::read_exact()`]. /// /// [`RecvStream::read_exact()`]: crate::RecvStream::read_exact #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadExact<'a> { stream: &'a mut RecvStream, buf: ReadBuf<'a>, } impl<'a> Future for ReadExact<'a> { type Output = Result<(), ReadExactError>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let this = self.get_mut(); let mut remaining = this.buf.remaining(); while remaining > 0 { ready!(this.stream.poll_read(cx, &mut this.buf))?; let new = this.buf.remaining(); if new == remaining { return Poll::Ready(Err(ReadExactError::FinishedEarly)); } remaining = new; } Poll::Ready(Ok(())) } } /// Errors that arise from reading from a stream. #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadExactError { /// The stream finished before all bytes were read #[error("stream finished early")] FinishedEarly, /// A read error occurred #[error(transparent)] ReadError(#[from] ReadError), } /// Future produced by [`RecvStream::read_chunk()`]. /// /// [`RecvStream::read_chunk()`]: crate::RecvStream::read_chunk #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadChunk<'a> { stream: &'a mut RecvStream, max_length: usize, ordered: bool, } impl<'a> Future for ReadChunk<'a> { type Output = Result<Option<Chunk>, ReadError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let (max_length, ordered) = (self.max_length, self.ordered); self.stream.poll
#[error("connection lost")] ConnectionLost(#[from] ConnectionError), /// The stream has already been stopped, finished, or reset #[error("unknown stream")]
random_line_split
recv_stream.rs
VarInt, }; /// A stream that can only be used to receive data /// /// `stop(0)` is implicitly called on drop unless: /// - A variant of [`ReadError`] has been yielded by a read call /// - [`stop()`] was called explicitly /// /// # Closing a stream /// /// When a stream is expected to be closed gracefully the sender should call /// [`SendStream::finish`]. However there is no guarantee the connected [`RecvStream`] will /// receive the "finished" notification in the same QUIC frame as the last frame which /// carried data. /// /// Even if the application layer logic already knows it read all the data because it does /// its own framing, it should still read until it reaches the end of the [`RecvStream`]. /// Otherwise it risks inadvertently calling [`RecvStream::stop`] if it drops the stream. /// And calling [`RecvStream::stop`] could result in the connected [`SendStream::finish`] /// call failing with a [`WriteError::Stopped`] error. /// /// For example if exactly 10 bytes are to be read, you still need to explicitly read the /// end of the stream: /// /// ```no_run /// # use quinn::{SendStream, RecvStream}; /// # async fn func( /// # mut send_stream: SendStream, /// # mut recv_stream: RecvStream, /// # ) -> anyhow::Result<()> /// # { /// // In the sending task /// send_stream.write(&b"0123456789"[..]).await?; /// send_stream.finish().await?; /// /// // In the receiving task /// let mut buf = [0u8; 10]; /// let data = recv_stream.read_exact(&mut buf).await?; /// if recv_stream.read_to_end(0).await.is_err() { /// // Discard unexpected data and notify the peer to stop sending it /// let _ = recv_stream.stop(0u8.into()); /// } /// # Ok(()) /// # } /// ``` /// /// An alternative approach, used in HTTP/3, is to specify a particular error code used with `stop` /// that indicates graceful receiver-initiated stream shutdown, rather than a true error condition. /// /// [`RecvStream::read_chunk`] could be used instead which does not take ownership and /// allows using an explicit call to [`RecvStream::stop`] with a custom error code. /// /// [`ReadError`]: crate::ReadError /// [`stop()`]: RecvStream::stop /// [`SendStream::finish`]: crate::SendStream::finish /// [`WriteError::Stopped`]: crate::WriteError::Stopped #[derive(Debug)] pub struct RecvStream { conn: ConnectionRef, stream: StreamId, is_0rtt: bool, all_data_read: bool, reset: Option<VarInt>, } impl RecvStream { pub(crate) fn new(conn: ConnectionRef, stream: StreamId, is_0rtt: bool) -> Self { Self { conn, stream, is_0rtt, all_data_read: false, reset: None, } } /// Read data contiguously from the stream. /// /// Yields the number of bytes read into `buf` on success, or `None` if the stream was finished. pub async fn read(&mut self, buf: &mut [u8]) -> Result<Option<usize>, ReadError> { Read { stream: self, buf: ReadBuf::new(buf), } .await } /// Read an exact number of bytes contiguously from the stream. /// /// See [`read()`] for details. /// /// [`read()`]: RecvStream::read pub async fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), ReadExactError> { ReadExact { stream: self, buf: ReadBuf::new(buf), } .await } fn poll_read( &mut self, cx: &mut Context, buf: &mut ReadBuf<'_>, ) -> Poll<Result<(), ReadError>> { if buf.remaining() == 0 { return Poll::Ready(Ok(())); } self.poll_read_generic(cx, true, |chunks| { let mut read = false; loop { if buf.remaining() == 0 { // We know `read` is `true` because `buf.remaining()` was not 0 before return ReadStatus::Readable(()); } match chunks.next(buf.remaining()) { Ok(Some(chunk)) => { buf.put_slice(&chunk.bytes); read = true; } res => return (if read { Some(()) } else { None }, res.err()).into(), } } }) .map(|res| res.map(|_| ())) } /// Read the next segment of data /// /// Yields `None` if the stream was finished. Otherwise, yields a segment of data and its /// offset in the stream. If `ordered` is `true`, the chunk's offset will be immediately after /// the last data yielded by `read()` or `read_chunk()`. If `ordered` is `false`, segments may /// be received in any order, and the `Chunk`'s `offset` field can be used to determine /// ordering in the caller. Unordered reads are less prone to head-of-line blocking within a /// stream, but require the application to manage reassembling the original data. /// /// Slightly more efficient than `read` due to not copying. Chunk boundaries do not correspond /// to peer writes, and hence cannot be used as framing. pub async fn read_chunk( &mut self, max_length: usize, ordered: bool, ) -> Result<Option<Chunk>, ReadError> { ReadChunk { stream: self, max_length, ordered, } .await } /// Foundation of [`Self::read_chunk`] fn poll_read_chunk( &mut self, cx: &mut Context, max_length: usize, ordered: bool, ) -> Poll<Result<Option<Chunk>, ReadError>> { self.poll_read_generic(cx, ordered, |chunks| match chunks.next(max_length) { Ok(Some(chunk)) => ReadStatus::Readable(chunk), res => (None, res.err()).into(), }) } /// Read the next segments of data /// /// Fills `bufs` with the segments of data beginning immediately after the /// last data yielded by `read` or `read_chunk`, or `None` if the stream was /// finished. /// /// Slightly more efficient than `read` due to not copying. Chunk boundaries /// do not correspond to peer writes, and hence cannot be used as framing. pub async fn read_chunks(&mut self, bufs: &mut [Bytes]) -> Result<Option<usize>, ReadError> { ReadChunks { stream: self, bufs }.await } /// Foundation of [`Self::read_chunks`] fn poll_read_chunks( &mut self, cx: &mut Context, bufs: &mut [Bytes], ) -> Poll<Result<Option<usize>, ReadError>> { if bufs.is_empty() { return Poll::Ready(Ok(Some(0))); } self.poll_read_generic(cx, true, |chunks| { let mut read = 0; loop { if read >= bufs.len() { // We know `read > 0` because `bufs` cannot be empty here return ReadStatus::Readable(read); } match chunks.next(usize::MAX) { Ok(Some(chunk)) => { bufs[read] = chunk.bytes; read += 1; } res => return (if read == 0 { None } else { Some(read) }, res.err()).into(), } } }) } /// Convenience method to read all remaining data into a buffer /// /// Fails with [`ReadToEndError::TooLong`] on reading more than `size_limit` bytes, discarding /// all data read. Uses unordered reads to be more efficient than using `AsyncRead` would /// allow. `size_limit` should be set to limit worst-case memory use. /// /// If unordered reads have already been made, the resulting buffer may have gaps containing /// arbitrary data. /// /// [`ReadToEndError::TooLong`]: crate::ReadToEndError::TooLong pub async fn read_to_end(&mut self, size_limit: usize) -> Result<Vec<u8>, ReadToEndError> { ReadToEnd { stream: self, size_limit, read: Vec::new(), start: u64::max_value(), end: 0, } .await } /// Stop accepting data /// /// Discards unread data and notifies the peer to stop transmitting. Once stopped, further /// attempts to operate on a stream will yield `UnknownStream` errors. pub fn stop(&mut self, error_code: VarInt) -> Result<(), UnknownStream> { let mut conn = self.conn.state.lock("RecvStream::stop"); if self.is_0rtt && conn.check_0rtt().is_err() { return Ok(()); } conn.inner.recv_stream(self.stream).stop(error_code)?; conn.wake(); self.all_data_read = true; Ok(()) } /// Check if this stream has been opened during 0-RTT. /// /// In which case any non-idempotent request should be considered dangerous at the application /// level. Because read data is subject to replay attacks. pub fn is_0rtt(&self) -> bool { self.is_0rtt } /// Get the identity of this stream pub fn id(&self) -> StreamId { self.stream } /// Handle common logic related to reading out of a receive stream /// /// This takes an `FnMut` closure that takes care of the actual reading process, matching /// the detailed read semantics for the calling function with a particular return type. /// The closure can read from the passed `&mut Chunks` and has to return the status after /// reading: the amount of data read, and the status after the final read call. fn poll_read_generic<T, U>( &mut self, cx: &mut Context, ordered: bool, mut read_fn: T, ) -> Poll<Result<Option<U>, ReadError>> where T: FnMut(&mut Chunks) -> ReadStatus<U>, { use proto::ReadError::*; if self.all_data_read { return Poll::Ready(Ok(None)); } let mut conn = self.conn.state.lock("RecvStream::poll_read"); if self.is_0rtt { conn.check_0rtt().map_err(|()| ReadError::ZeroRttRejected)?; } // If we stored an error during a previous call, return it now. This can happen if a // `read_fn` both wants to return data and also returns an error in its final stream status. let status = match self.reset.take() { Some(code) => ReadStatus::Failed(None, Reset(code)), None => { let mut recv = conn.inner.recv_stream(self.stream); let mut chunks = recv.read(ordered)?; let status = read_fn(&mut chunks); if chunks.finalize().should_transmit() { conn.wake(); } status } }; match status { ReadStatus::Readable(read) => Poll::Ready(Ok(Some(read))), ReadStatus::Finished(read) => { self.all_data_read = true; Poll::Ready(Ok(read)) } ReadStatus::Failed(read, Blocked) => match read { Some(val) => Poll::Ready(Ok(Some(val))), None => { if let Some(ref x) = conn.error { return Poll::Ready(Err(ReadError::ConnectionLost(x.clone()))); } conn.blocked_readers.insert(self.stream, cx.waker().clone()); Poll::Pending } }, ReadStatus::Failed(read, Reset(error_code)) => match read { None => { self.all_data_read = true; Poll::Ready(Err(ReadError::Reset(error_code))) } done => { self.reset = Some(error_code); Poll::Ready(Ok(done)) } }, } } } enum ReadStatus<T> { Readable(T), Finished(Option<T>), Failed(Option<T>, proto::ReadError), } impl<T> From<(Option<T>, Option<proto::ReadError>)> for ReadStatus<T> { fn from(status: (Option<T>, Option<proto::ReadError>)) -> Self { match status { (read, None) => Self::Finished(read), (read, Some(e)) => Self::Failed(read, e), } } } /// Future produced by [`RecvStream::read_to_end()`]. /// /// [`RecvStream::read_to_end()`]: crate::RecvStream::read_to_end #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadToEnd<'a> { stream: &'a mut RecvStream, read: Vec<(Bytes, u64)>, start: u64, end: u64, size_limit: usize, } impl Future for ReadToEnd<'_> { type Output = Result<Vec<u8>, ReadToEndError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { loop { match ready!(self.stream.poll_read_chunk(cx, usize::MAX, false))? { Some(chunk) => { self.start = self.start.min(chunk.offset); let end = chunk.bytes.len() as u64 + chunk.offset; if (end - self.start) > self.size_limit as u64 { return Poll::Ready(Err(ReadToEndError::TooLong)); } self.end = self.end.max(end); self.read.push((chunk.bytes, chunk.offset)); } None => { if self.end == 0 { // Never received anything return Poll::Ready(Ok(Vec::new())); } let start = self.start; let mut buffer = vec![0; (self.end - start) as usize]; for (data, offset) in self.read.drain(..) { let offset = (offset - start) as usize; buffer[offset..offset + data.len()].copy_from_slice(&data); } return Poll::Ready(Ok(buffer)); } } } } } /// Errors from [`RecvStream::read_to_end`] #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadToEndError { /// An error occurred during reading #[error("read error: {0}")] Read(#[from] ReadError), /// The stream is larger than the user-supplied limit #[error("stream too long")] TooLong, } #[cfg(feature = "futures-io")] impl futures_io::AsyncRead for RecvStream { fn poll_read( self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8], ) -> Poll<io::Result<usize>> { let mut buf = ReadBuf::new(buf); ready!(RecvStream::poll_read(self.get_mut(), cx, &mut buf))?; Poll::Ready(Ok(buf.filled().len())) } } impl tokio::io::AsyncRead for RecvStream { fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { ready!(Self::poll_read(self.get_mut(), cx, buf))?; Poll::Ready(Ok(())) } } impl Drop for RecvStream { fn drop(&mut self) { let mut conn = self.conn.state.lock("RecvStream::drop"); // clean up any previously registered wakers conn.blocked_readers.remove(&self.stream); if conn.error.is_some() || (self.is_0rtt && conn.check_0rtt().is_err()) { return; } if!self.all_data_read { // Ignore UnknownStream errors let _ = conn.inner.recv_stream(self.stream).stop(0u32.into()); conn.wake(); } } } /// Errors that arise from reading from a stream. #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadError { /// The peer abandoned transmitting data on this stream /// /// Carries an application-defined error code. #[error("stream reset by peer: error {0}")] Reset(VarInt), /// The connection was lost #[error("connection lost")] ConnectionLost(#[from] ConnectionError), /// The stream has already been stopped, finished, or reset #[error("unknown stream")] UnknownStream, /// Attempted an ordered read following an unordered read /// /// Performing an unordered read allows discontinuities to arise in the receive buffer of a /// stream which cannot be recovered, making further ordered reads impossible. #[error("ordered read after unordered read")] IllegalOrderedRead, /// This was a 0-RTT stream and the server rejected it /// /// Can only occur on clients for 0-RTT streams, which can be opened using /// [`Connecting::into_0rtt()`]. /// /// [`Connecting::into_0rtt()`]: crate::Connecting::into_0rtt() #[error("0-RTT rejected")] ZeroRttRejected, } impl From<ReadableError> for ReadError { fn from(e: ReadableError) -> Self { match e { ReadableError::UnknownStream => Self::UnknownStream, ReadableError::IllegalOrderedRead => Self::IllegalOrderedRead, } } } impl From<ReadError> for io::Error { fn from(x: ReadError) -> Self { use self::ReadError::*; let kind = match x { Reset {.. } | ZeroRttRejected => io::ErrorKind::ConnectionReset, ConnectionLost(_) | UnknownStream => io::ErrorKind::NotConnected, IllegalOrderedRead => io::ErrorKind::InvalidInput, }; Self::new(kind, x) } } /// Future produced by [`RecvStream::read()`]. /// /// [`RecvStream::read()`]: crate::RecvStream::read #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct Read<'a> { stream: &'a mut RecvStream, buf: ReadBuf<'a>, } impl<'a> Future for Read<'a> { type Output = Result<Option<usize>, ReadError>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output>
} /// Future produced by [`RecvStream::read_exact()`]. /// /// [`RecvStream::read_exact()`]: crate::RecvStream::read_exact #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadExact<'a> { stream: &'a mut RecvStream, buf: ReadBuf<'a>, } impl<'a> Future for ReadExact<'a> { type Output = Result<(), ReadExactError>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let this = self.get_mut(); let mut remaining = this.buf.remaining(); while remaining > 0 { ready!(this.stream.poll_read(cx, &mut this.buf))?; let new = this.buf.remaining(); if new == remaining { return Poll::Ready(Err(ReadExactError::FinishedEarly)); } remaining = new; } Poll::Ready(Ok(())) } } /// Errors that arise from reading from a stream. #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadExactError { /// The stream finished before all bytes were read #[error("stream finished early")] FinishedEarly, /// A read error occurred #[error(transparent)] ReadError(#[from] ReadError), } /// Future produced by [`RecvStream::read_chunk()`]. /// /// [`RecvStream::read_chunk()`]: crate::RecvStream::read_chunk #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadChunk<'a> { stream: &'a mut RecvStream, max_length: usize, ordered: bool, } impl<'a> Future for ReadChunk<'a> { type Output = Result<Option<Chunk>, ReadError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let (max_length, ordered) = (self.max_length, self.ordered); self.stream.
{ let this = self.get_mut(); ready!(this.stream.poll_read(cx, &mut this.buf))?; match this.buf.filled().len() { 0 if this.buf.capacity() != 0 => Poll::Ready(Ok(None)), n => Poll::Ready(Ok(Some(n))), } }
identifier_body
conf.rs
use crate::ecies; use crate::hash256::Hash256; use crate::keys::{public_to_slice, sign, slice_to_public}; use crate::messages::{Message, NodeKey, Version, PROTOCOL_VERSION, NODE_NONE}; use crate::util::secs_since; use secp256k1::{ecdh, Secp256k1, PublicKey, SecretKey}; use std::str::FromStr; use std::time::UNIX_EPOCH; use structopt::StructOpt; use tiny_keccak::Keccak; #[derive(StructOpt,Debug)] /// Sender information. pub struct Wallet { #[structopt(long)] /// Public address of sender to be used as input. /// pub in_address: String, #[structopt(long)] /// input UTXO amount /// pub in_amount: f64, #[structopt(long, parse(try_from_str="Hash256::decode"))] /// OutPoint transaction id. /// pub outpoint_hash: Hash256, #[structopt(long)] /// OutPoint vout index. /// pub outpoint_index: u32, #[structopt(long)] /// Private key to sign sender input. /// /// Supported format: WIF (Wallet Import Format) - base56check encoded string. /// /// > bitcoin-cli -regtest dumpprivkey "address" /// pub secret: String, #[structopt(long)] /// Public addrss to be used as output for change. /// /// > bitcoin-cli -regtest getnewaddress /// pub out_address: String, #[structopt(long)] /// Change from input transaction. /// Amout that should be returned to new sender address and don't burned or spent for writing data. /// pub change: f64, } #[derive(StructOpt, Debug)] /// Eth node info pub struct EthWallet { #[structopt(long)] /// Node public key /// pub pub_key: HexData, #[structopt(long, required_unless="crypto")] /// Secret key. Having this key drastically improve the performance. /// pub secret: Option<String>, #[structopt(long, required_unless="secret")] /// Crypto part of privkey file. /// Generating private key on ETH will take a lot of time (for undiscovered yet reason), /// so if you have it from another sources just provide the secret key /// pub crypto: Option<String>, #[structopt(long)] /// Secret key password /// pub password: String, #[structopt(long)] /// Public addrss to be used as output. /// pub out_address: String, /// Transfered value /// #[structopt(long)] pub value: u128, /// Gas paid up front for transaction execution /// #[structopt(long, default_value="21000")] pub gas: u128, /// Gas price /// #[structopt(long, default_value="1000000000")] pub gas_price: u128, } /// Initial encryption configuration #[derive(Clone)] pub struct EncOpt { pub node_public: PublicKey, pub node_secret: SecretKey, pub msg_secret: SecretKey, pub enc_version: Vec<u8>, pub nonce: Hash256, } pub trait Sender { fn change(&self) -> f64 {0.0} fn secret(&self) -> Option<String> {None} fn crypto(&self) -> Option<String> {None} fn pub_key(&self) -> Vec<u8> {vec![]} fn password(&self) -> String {String::new()} fn in_amount(&self) -> f64 {0.0} fn in_address(&self) -> String {String::new()} fn out_address(&self) -> String; fn outpoint_hash(&self) -> Hash256 {Hash256::default()} fn outpoint_index(&self) -> u32 {0} fn gas(&self) -> u128 {0} fn gas_price(&self) -> u128 {0} fn value(&self) -> u128 {0} fn encryption_conf(&self) -> Option<EncOpt> { None } fn version(&self, cfg: &Option<EncOpt>) -> Message; } impl Sender for Wallet { fn in_address(&self) -> String {return self.in_address.clone();} fn out_address(&self) -> String {return self.out_address.clone();} fn outpoint_hash(&self) -> Hash256 {return self.outpoint_hash;} fn outpoint_index(&self) -> u32 {return self.outpoint_index;} fn change(&self) -> f64 {return self.change;} fn in_amount(&self) -> f64 {return self.in_amount;} fn secret(&self) -> Option<String> {return Some(self.secret.clone());} fn version(&self, _cfg: &Option<EncOpt>) -> Message { let version = Version { version: PROTOCOL_VERSION, services: NODE_NONE, timestamp: secs_since(UNIX_EPOCH) as i64, user_agent: "umbrella".to_string(), ..Default::default() }; Message::Version(version) } } impl Sender for EthWallet { fn pub_key(&self) -> Vec<u8> {self.pub_key.0.clone()} fn secret(&self) -> Option<String> {self.secret.clone()} fn crypto(&self) -> Option<String> {self.crypto.clone()} fn password(&self) -> String {self.password.clone()} fn out_address(&self) -> String {self.out_address.clone()} fn gas(&self) -> u128 {self.gas} fn
(&self) -> u128 {self.value} fn gas_price(&self) -> u128 {self.gas_price} fn encryption_conf(&self) -> Option<EncOpt> { let mut rng = rand::thread_rng(); let pub_key:PublicKey = slice_to_public(&self.pub_key.0).unwrap(); let nonce: Hash256 = Hash256::random(); let secp = Secp256k1::new(); let (node_secret, node_public) = secp.generate_keypair(&mut rng); let (msg, msg_secret) = encrypt_node_version(pub_key, node_public, node_secret, nonce); Some(EncOpt { node_public: node_public, node_secret: node_secret, msg_secret: msg_secret, enc_version: msg, nonce: nonce, }) } fn version(&self, cfg: &Option<EncOpt>) -> Message { let version = NodeKey { version: cfg.as_ref().unwrap().enc_version.clone(), }; Message::NodeKey(version) } } /// Probably a part of version message with encryption support /// fn encrypt_node_version(pub_key:PublicKey , node_public:PublicKey , node_secret:SecretKey , nonce: Hash256) -> (Vec<u8>, SecretKey) { let mut rng = rand::thread_rng(); let secp = Secp256k1::new(); let mut version = [0u8;194]; //sig + public + 2*h256 + 1 version[193] = 0x0; let (sig, rest) = version.split_at_mut(65); let (version_pub, rest) = rest.split_at_mut(32); let (node_pub, rest) = rest.split_at_mut(64); let (data_nonce, _) = rest.split_at_mut(32); let (sec1, pub1) = secp.generate_keypair(&mut rng); let pub1 = public_to_slice(&pub1); let sec1 = SecretKey::from_slice(&sec1[..32]).unwrap(); let shr = &ecdh::shared_secret_point(&pub_key, &node_secret)[..32]; let xor = Hash256::from_slice(&shr) ^ nonce; //signature sig.copy_from_slice(&sign(&sec1, &xor)); Keccak::keccak256(&pub1, version_pub); node_pub.copy_from_slice(&public_to_slice(&node_public)); data_nonce.copy_from_slice(nonce.as_bytes()); (ecies::encrypt(&pub_key, &[], &version).unwrap(), sec1) } #[derive(Debug)] pub struct HexData(pub Vec<u8>); impl FromStr for HexData { type Err = hex::FromHexError; fn from_str(s: &str) -> Result<Self, Self::Err> { hex::decode(s).map(HexData) } } #[derive(StructOpt, Debug)] pub struct Data { #[structopt(long)] /// Public address to pay for data storage. /// /// > bitcoin-cli -regtest getnewaddress /// pub dust_address: String, #[structopt(long, default_value="0.0001")] /// Amount to pay for data storage. /// pub dust_amount: f64, #[structopt(long)] /// Data to be incuded in output. /// pub data: HexData, } #[derive(StructOpt, Debug)] /// Network configuration. /// pub enum Network { #[structopt(name="bch", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash main network BCH{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bch-test", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash test network BCHTest{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bch-reg", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash Regtest network BCHReg{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="eth", raw(setting="structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Ethereum network Eth{ #[structopt(flatten)] sender: EthWallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bsv", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin SV Regtest network BSV{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bsv-reg", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin SV Regtest network BSVReg{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, } impl Network { pub fn network(&self) -> crate::network::Network { match *self { Network::BCH{..} => crate::network::Network::Mainnet, Network::BCHTest{..}=> crate::network::Network::Testnet, Network::BCHReg{..} => crate::network::Network::Regtest, Network::Eth{..} => crate::network::Network::Ethereum, Network::BSV{..} => crate::network::Network::BsvMainnet, Network::BSVReg{..} => crate::network::Network::BsvRegtest, } } } #[derive(StructOpt, Debug)] #[structopt(name="umbrella", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Make a note on transaction within a network selected by <SUBCOMMAND>. /// /// Run `help <SUBCOMMAND>` for [OPTIONS] description. pub struct Opt { #[structopt(subcommand)] pub network: Network, /// Silence all output #[structopt(short = "q", long = "quiet")] pub quiet: bool, } impl Opt { pub fn sender(&self) -> &dyn Sender { match &self.network { Network::BCH {sender,..} => sender, Network::BCHTest{sender,..} => sender, Network::BCHReg {sender,..} => sender, Network::Eth {sender,..} => sender, Network::BSV {sender,..} => sender, Network::BSVReg {sender,..} => sender, } } pub fn data(&self) -> &Data{ match &self.network { Network::BCH {sender:_, data} => data, Network::BCHTest{sender:_, data} => data, Network::BCHReg {sender:_, data} => data, Network::Eth {sender:_, data} => data, Network::BSV {sender:_, data} => data, Network::BSVReg {sender:_, data} => data, } } } #[cfg(test)] mod tests { use super::*; #[ignore] #[test] fn help_network() { Opt::from_iter(&["umbrella", "help", "bch-reg"]); } }
value
identifier_name
conf.rs
use crate::ecies; use crate::hash256::Hash256; use crate::keys::{public_to_slice, sign, slice_to_public}; use crate::messages::{Message, NodeKey, Version, PROTOCOL_VERSION, NODE_NONE}; use crate::util::secs_since; use secp256k1::{ecdh, Secp256k1, PublicKey, SecretKey}; use std::str::FromStr; use std::time::UNIX_EPOCH; use structopt::StructOpt; use tiny_keccak::Keccak; #[derive(StructOpt,Debug)] /// Sender information. pub struct Wallet { #[structopt(long)] /// Public address of sender to be used as input. /// pub in_address: String, #[structopt(long)] /// input UTXO amount /// pub in_amount: f64, #[structopt(long, parse(try_from_str="Hash256::decode"))] /// OutPoint transaction id. /// pub outpoint_hash: Hash256, #[structopt(long)] /// OutPoint vout index. /// pub outpoint_index: u32, #[structopt(long)] /// Private key to sign sender input. /// /// Supported format: WIF (Wallet Import Format) - base56check encoded string. /// /// > bitcoin-cli -regtest dumpprivkey "address" /// pub secret: String, #[structopt(long)] /// Public addrss to be used as output for change. /// /// > bitcoin-cli -regtest getnewaddress /// pub out_address: String, #[structopt(long)] /// Change from input transaction. /// Amout that should be returned to new sender address and don't burned or spent for writing data. /// pub change: f64, } #[derive(StructOpt, Debug)] /// Eth node info pub struct EthWallet { #[structopt(long)] /// Node public key /// pub pub_key: HexData, #[structopt(long, required_unless="crypto")] /// Secret key. Having this key drastically improve the performance. /// pub secret: Option<String>, #[structopt(long, required_unless="secret")] /// Crypto part of privkey file. /// Generating private key on ETH will take a lot of time (for undiscovered yet reason), /// so if you have it from another sources just provide the secret key /// pub crypto: Option<String>, #[structopt(long)] /// Secret key password /// pub password: String, #[structopt(long)] /// Public addrss to be used as output. /// pub out_address: String, /// Transfered value /// #[structopt(long)] pub value: u128, /// Gas paid up front for transaction execution /// #[structopt(long, default_value="21000")] pub gas: u128, /// Gas price /// #[structopt(long, default_value="1000000000")] pub gas_price: u128, } /// Initial encryption configuration #[derive(Clone)] pub struct EncOpt { pub node_public: PublicKey, pub node_secret: SecretKey, pub msg_secret: SecretKey, pub enc_version: Vec<u8>, pub nonce: Hash256, } pub trait Sender { fn change(&self) -> f64 {0.0} fn secret(&self) -> Option<String> {None} fn crypto(&self) -> Option<String> {None} fn pub_key(&self) -> Vec<u8> {vec![]} fn password(&self) -> String {String::new()} fn in_amount(&self) -> f64 {0.0} fn in_address(&self) -> String {String::new()} fn out_address(&self) -> String; fn outpoint_hash(&self) -> Hash256 {Hash256::default()} fn outpoint_index(&self) -> u32 {0} fn gas(&self) -> u128 {0} fn gas_price(&self) -> u128 {0} fn value(&self) -> u128 {0} fn encryption_conf(&self) -> Option<EncOpt> { None } fn version(&self, cfg: &Option<EncOpt>) -> Message; } impl Sender for Wallet { fn in_address(&self) -> String {return self.in_address.clone();} fn out_address(&self) -> String {return self.out_address.clone();} fn outpoint_hash(&self) -> Hash256 {return self.outpoint_hash;} fn outpoint_index(&self) -> u32 {return self.outpoint_index;} fn change(&self) -> f64 {return self.change;} fn in_amount(&self) -> f64 {return self.in_amount;} fn secret(&self) -> Option<String> {return Some(self.secret.clone());} fn version(&self, _cfg: &Option<EncOpt>) -> Message { let version = Version { version: PROTOCOL_VERSION, services: NODE_NONE, timestamp: secs_since(UNIX_EPOCH) as i64, user_agent: "umbrella".to_string(), ..Default::default() }; Message::Version(version) } } impl Sender for EthWallet { fn pub_key(&self) -> Vec<u8> {self.pub_key.0.clone()}
fn gas(&self) -> u128 {self.gas} fn value(&self) -> u128 {self.value} fn gas_price(&self) -> u128 {self.gas_price} fn encryption_conf(&self) -> Option<EncOpt> { let mut rng = rand::thread_rng(); let pub_key:PublicKey = slice_to_public(&self.pub_key.0).unwrap(); let nonce: Hash256 = Hash256::random(); let secp = Secp256k1::new(); let (node_secret, node_public) = secp.generate_keypair(&mut rng); let (msg, msg_secret) = encrypt_node_version(pub_key, node_public, node_secret, nonce); Some(EncOpt { node_public: node_public, node_secret: node_secret, msg_secret: msg_secret, enc_version: msg, nonce: nonce, }) } fn version(&self, cfg: &Option<EncOpt>) -> Message { let version = NodeKey { version: cfg.as_ref().unwrap().enc_version.clone(), }; Message::NodeKey(version) } } /// Probably a part of version message with encryption support /// fn encrypt_node_version(pub_key:PublicKey , node_public:PublicKey , node_secret:SecretKey , nonce: Hash256) -> (Vec<u8>, SecretKey) { let mut rng = rand::thread_rng(); let secp = Secp256k1::new(); let mut version = [0u8;194]; //sig + public + 2*h256 + 1 version[193] = 0x0; let (sig, rest) = version.split_at_mut(65); let (version_pub, rest) = rest.split_at_mut(32); let (node_pub, rest) = rest.split_at_mut(64); let (data_nonce, _) = rest.split_at_mut(32); let (sec1, pub1) = secp.generate_keypair(&mut rng); let pub1 = public_to_slice(&pub1); let sec1 = SecretKey::from_slice(&sec1[..32]).unwrap(); let shr = &ecdh::shared_secret_point(&pub_key, &node_secret)[..32]; let xor = Hash256::from_slice(&shr) ^ nonce; //signature sig.copy_from_slice(&sign(&sec1, &xor)); Keccak::keccak256(&pub1, version_pub); node_pub.copy_from_slice(&public_to_slice(&node_public)); data_nonce.copy_from_slice(nonce.as_bytes()); (ecies::encrypt(&pub_key, &[], &version).unwrap(), sec1) } #[derive(Debug)] pub struct HexData(pub Vec<u8>); impl FromStr for HexData { type Err = hex::FromHexError; fn from_str(s: &str) -> Result<Self, Self::Err> { hex::decode(s).map(HexData) } } #[derive(StructOpt, Debug)] pub struct Data { #[structopt(long)] /// Public address to pay for data storage. /// /// > bitcoin-cli -regtest getnewaddress /// pub dust_address: String, #[structopt(long, default_value="0.0001")] /// Amount to pay for data storage. /// pub dust_amount: f64, #[structopt(long)] /// Data to be incuded in output. /// pub data: HexData, } #[derive(StructOpt, Debug)] /// Network configuration. /// pub enum Network { #[structopt(name="bch", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash main network BCH{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bch-test", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash test network BCHTest{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bch-reg", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash Regtest network BCHReg{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="eth", raw(setting="structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Ethereum network Eth{ #[structopt(flatten)] sender: EthWallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bsv", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin SV Regtest network BSV{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bsv-reg", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin SV Regtest network BSVReg{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, } impl Network { pub fn network(&self) -> crate::network::Network { match *self { Network::BCH{..} => crate::network::Network::Mainnet, Network::BCHTest{..}=> crate::network::Network::Testnet, Network::BCHReg{..} => crate::network::Network::Regtest, Network::Eth{..} => crate::network::Network::Ethereum, Network::BSV{..} => crate::network::Network::BsvMainnet, Network::BSVReg{..} => crate::network::Network::BsvRegtest, } } } #[derive(StructOpt, Debug)] #[structopt(name="umbrella", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Make a note on transaction within a network selected by <SUBCOMMAND>. /// /// Run `help <SUBCOMMAND>` for [OPTIONS] description. pub struct Opt { #[structopt(subcommand)] pub network: Network, /// Silence all output #[structopt(short = "q", long = "quiet")] pub quiet: bool, } impl Opt { pub fn sender(&self) -> &dyn Sender { match &self.network { Network::BCH {sender,..} => sender, Network::BCHTest{sender,..} => sender, Network::BCHReg {sender,..} => sender, Network::Eth {sender,..} => sender, Network::BSV {sender,..} => sender, Network::BSVReg {sender,..} => sender, } } pub fn data(&self) -> &Data{ match &self.network { Network::BCH {sender:_, data} => data, Network::BCHTest{sender:_, data} => data, Network::BCHReg {sender:_, data} => data, Network::Eth {sender:_, data} => data, Network::BSV {sender:_, data} => data, Network::BSVReg {sender:_, data} => data, } } } #[cfg(test)] mod tests { use super::*; #[ignore] #[test] fn help_network() { Opt::from_iter(&["umbrella", "help", "bch-reg"]); } }
fn secret(&self) -> Option<String> {self.secret.clone()} fn crypto(&self) -> Option<String> {self.crypto.clone()} fn password(&self) -> String {self.password.clone()} fn out_address(&self) -> String {self.out_address.clone()}
random_line_split
conf.rs
use crate::ecies; use crate::hash256::Hash256; use crate::keys::{public_to_slice, sign, slice_to_public}; use crate::messages::{Message, NodeKey, Version, PROTOCOL_VERSION, NODE_NONE}; use crate::util::secs_since; use secp256k1::{ecdh, Secp256k1, PublicKey, SecretKey}; use std::str::FromStr; use std::time::UNIX_EPOCH; use structopt::StructOpt; use tiny_keccak::Keccak; #[derive(StructOpt,Debug)] /// Sender information. pub struct Wallet { #[structopt(long)] /// Public address of sender to be used as input. /// pub in_address: String, #[structopt(long)] /// input UTXO amount /// pub in_amount: f64, #[structopt(long, parse(try_from_str="Hash256::decode"))] /// OutPoint transaction id. /// pub outpoint_hash: Hash256, #[structopt(long)] /// OutPoint vout index. /// pub outpoint_index: u32, #[structopt(long)] /// Private key to sign sender input. /// /// Supported format: WIF (Wallet Import Format) - base56check encoded string. /// /// > bitcoin-cli -regtest dumpprivkey "address" /// pub secret: String, #[structopt(long)] /// Public addrss to be used as output for change. /// /// > bitcoin-cli -regtest getnewaddress /// pub out_address: String, #[structopt(long)] /// Change from input transaction. /// Amout that should be returned to new sender address and don't burned or spent for writing data. /// pub change: f64, } #[derive(StructOpt, Debug)] /// Eth node info pub struct EthWallet { #[structopt(long)] /// Node public key /// pub pub_key: HexData, #[structopt(long, required_unless="crypto")] /// Secret key. Having this key drastically improve the performance. /// pub secret: Option<String>, #[structopt(long, required_unless="secret")] /// Crypto part of privkey file. /// Generating private key on ETH will take a lot of time (for undiscovered yet reason), /// so if you have it from another sources just provide the secret key /// pub crypto: Option<String>, #[structopt(long)] /// Secret key password /// pub password: String, #[structopt(long)] /// Public addrss to be used as output. /// pub out_address: String, /// Transfered value /// #[structopt(long)] pub value: u128, /// Gas paid up front for transaction execution /// #[structopt(long, default_value="21000")] pub gas: u128, /// Gas price /// #[structopt(long, default_value="1000000000")] pub gas_price: u128, } /// Initial encryption configuration #[derive(Clone)] pub struct EncOpt { pub node_public: PublicKey, pub node_secret: SecretKey, pub msg_secret: SecretKey, pub enc_version: Vec<u8>, pub nonce: Hash256, } pub trait Sender { fn change(&self) -> f64 {0.0} fn secret(&self) -> Option<String> {None} fn crypto(&self) -> Option<String> {None} fn pub_key(&self) -> Vec<u8> {vec![]} fn password(&self) -> String {String::new()} fn in_amount(&self) -> f64 {0.0} fn in_address(&self) -> String {String::new()} fn out_address(&self) -> String; fn outpoint_hash(&self) -> Hash256 {Hash256::default()} fn outpoint_index(&self) -> u32 {0} fn gas(&self) -> u128 {0} fn gas_price(&self) -> u128 {0} fn value(&self) -> u128
fn encryption_conf(&self) -> Option<EncOpt> { None } fn version(&self, cfg: &Option<EncOpt>) -> Message; } impl Sender for Wallet { fn in_address(&self) -> String {return self.in_address.clone();} fn out_address(&self) -> String {return self.out_address.clone();} fn outpoint_hash(&self) -> Hash256 {return self.outpoint_hash;} fn outpoint_index(&self) -> u32 {return self.outpoint_index;} fn change(&self) -> f64 {return self.change;} fn in_amount(&self) -> f64 {return self.in_amount;} fn secret(&self) -> Option<String> {return Some(self.secret.clone());} fn version(&self, _cfg: &Option<EncOpt>) -> Message { let version = Version { version: PROTOCOL_VERSION, services: NODE_NONE, timestamp: secs_since(UNIX_EPOCH) as i64, user_agent: "umbrella".to_string(), ..Default::default() }; Message::Version(version) } } impl Sender for EthWallet { fn pub_key(&self) -> Vec<u8> {self.pub_key.0.clone()} fn secret(&self) -> Option<String> {self.secret.clone()} fn crypto(&self) -> Option<String> {self.crypto.clone()} fn password(&self) -> String {self.password.clone()} fn out_address(&self) -> String {self.out_address.clone()} fn gas(&self) -> u128 {self.gas} fn value(&self) -> u128 {self.value} fn gas_price(&self) -> u128 {self.gas_price} fn encryption_conf(&self) -> Option<EncOpt> { let mut rng = rand::thread_rng(); let pub_key:PublicKey = slice_to_public(&self.pub_key.0).unwrap(); let nonce: Hash256 = Hash256::random(); let secp = Secp256k1::new(); let (node_secret, node_public) = secp.generate_keypair(&mut rng); let (msg, msg_secret) = encrypt_node_version(pub_key, node_public, node_secret, nonce); Some(EncOpt { node_public: node_public, node_secret: node_secret, msg_secret: msg_secret, enc_version: msg, nonce: nonce, }) } fn version(&self, cfg: &Option<EncOpt>) -> Message { let version = NodeKey { version: cfg.as_ref().unwrap().enc_version.clone(), }; Message::NodeKey(version) } } /// Probably a part of version message with encryption support /// fn encrypt_node_version(pub_key:PublicKey , node_public:PublicKey , node_secret:SecretKey , nonce: Hash256) -> (Vec<u8>, SecretKey) { let mut rng = rand::thread_rng(); let secp = Secp256k1::new(); let mut version = [0u8;194]; //sig + public + 2*h256 + 1 version[193] = 0x0; let (sig, rest) = version.split_at_mut(65); let (version_pub, rest) = rest.split_at_mut(32); let (node_pub, rest) = rest.split_at_mut(64); let (data_nonce, _) = rest.split_at_mut(32); let (sec1, pub1) = secp.generate_keypair(&mut rng); let pub1 = public_to_slice(&pub1); let sec1 = SecretKey::from_slice(&sec1[..32]).unwrap(); let shr = &ecdh::shared_secret_point(&pub_key, &node_secret)[..32]; let xor = Hash256::from_slice(&shr) ^ nonce; //signature sig.copy_from_slice(&sign(&sec1, &xor)); Keccak::keccak256(&pub1, version_pub); node_pub.copy_from_slice(&public_to_slice(&node_public)); data_nonce.copy_from_slice(nonce.as_bytes()); (ecies::encrypt(&pub_key, &[], &version).unwrap(), sec1) } #[derive(Debug)] pub struct HexData(pub Vec<u8>); impl FromStr for HexData { type Err = hex::FromHexError; fn from_str(s: &str) -> Result<Self, Self::Err> { hex::decode(s).map(HexData) } } #[derive(StructOpt, Debug)] pub struct Data { #[structopt(long)] /// Public address to pay for data storage. /// /// > bitcoin-cli -regtest getnewaddress /// pub dust_address: String, #[structopt(long, default_value="0.0001")] /// Amount to pay for data storage. /// pub dust_amount: f64, #[structopt(long)] /// Data to be incuded in output. /// pub data: HexData, } #[derive(StructOpt, Debug)] /// Network configuration. /// pub enum Network { #[structopt(name="bch", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash main network BCH{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bch-test", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash test network BCHTest{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bch-reg", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash Regtest network BCHReg{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="eth", raw(setting="structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Ethereum network Eth{ #[structopt(flatten)] sender: EthWallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bsv", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin SV Regtest network BSV{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bsv-reg", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin SV Regtest network BSVReg{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, } impl Network { pub fn network(&self) -> crate::network::Network { match *self { Network::BCH{..} => crate::network::Network::Mainnet, Network::BCHTest{..}=> crate::network::Network::Testnet, Network::BCHReg{..} => crate::network::Network::Regtest, Network::Eth{..} => crate::network::Network::Ethereum, Network::BSV{..} => crate::network::Network::BsvMainnet, Network::BSVReg{..} => crate::network::Network::BsvRegtest, } } } #[derive(StructOpt, Debug)] #[structopt(name="umbrella", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Make a note on transaction within a network selected by <SUBCOMMAND>. /// /// Run `help <SUBCOMMAND>` for [OPTIONS] description. pub struct Opt { #[structopt(subcommand)] pub network: Network, /// Silence all output #[structopt(short = "q", long = "quiet")] pub quiet: bool, } impl Opt { pub fn sender(&self) -> &dyn Sender { match &self.network { Network::BCH {sender,..} => sender, Network::BCHTest{sender,..} => sender, Network::BCHReg {sender,..} => sender, Network::Eth {sender,..} => sender, Network::BSV {sender,..} => sender, Network::BSVReg {sender,..} => sender, } } pub fn data(&self) -> &Data{ match &self.network { Network::BCH {sender:_, data} => data, Network::BCHTest{sender:_, data} => data, Network::BCHReg {sender:_, data} => data, Network::Eth {sender:_, data} => data, Network::BSV {sender:_, data} => data, Network::BSVReg {sender:_, data} => data, } } } #[cfg(test)] mod tests { use super::*; #[ignore] #[test] fn help_network() { Opt::from_iter(&["umbrella", "help", "bch-reg"]); } }
{0}
identifier_body
main.rs
use std::cell::Cell; fn main() { variable_bindings(); functions(); primitive_types(); comments(); if_(); loops(); ownership(); reference_and_borrowing(); lifetimes(); mutability(); struct_(); enums(); match_(); patterns(); method_syntax(); vectors(); strings(); generics(); traits(); drop(); if_let(); trait_objects(); closures(); } fn variable_bindings() { // Variable bindings let x = 5; println!("{}", x); // Patterns let (x, y) = (2, 3); println!("{}, {}", x, y); // Type annotation let y: u32 = 10; println!("{}", y); // Mutability let mut x = 10; println!("x is {} before mutation", x); x = 5; println!("x is {} after mutation", x); // Initializing bindings // The following won't compile because x is not initialized. // let x: i32; // println!("{}", x); // Scope and shadowing { println!("x is {} inside the scope, before shadowing", x); let x: u16 = 121; println!("x is {} inside the scope", x); } println!("x is {} outside the scope", x); // Here the variable is no longer mutable let x = x; println!("x is {}", x); } fn functions() { addition(50, 100); println!("{} plus one is {}", 10, add_by_one(10)); // Expression vs statements // expression returns a value, statements don't // This is an declaration statement // let x = 10; // The evaluation of "x = 10" is empty tuple () // Expression statement turns express to statments. println!("{} is even? {}", 3, is_even(3)); // Function pointers let f: fn(i32) -> i32 = add_by_one; println!("Using function pointers {}", f(10)); } fn addition(x: i32, y: i32) { println!("{} + {} = {}", x, y, x + y); } fn add_by_one(x: i32) -> i32 { x + 1 } fn is_even(i: i32) -> bool { if i % 2 == 0 { return true; } false } // Can be used as any type fn diverges() ->! { loop {}; } fn
() { // Booleans let x: bool = false; println!("x is {}", x); // char, supports Unicode let x: char = 'A'; println!("x is {}", x); // Numeric values // signed and fixed size let x: i8 = -12; println!("x is {}", x); // unsigned and fixed size let x: u8 = 12; println!("x is {}", x); // variable size (depending on underlying machine size) let x: usize = 1200; println!("x is {}", x); // floating point let x = 1.0; println!("x is {}", x); // Arrays (fixed sized) let a: [u8; 3] = [1, 2, 3]; println!("a[0] is {}", a[0]); // shorthand initialization let a = [100; 20]; println!("a[0] is {}", a[0]); println!("length of a is {}", a.len()); // Slices let complete = &a[..]; println!("length of complete is {}", complete.len()); let some: &[u32] = &a[5..10]; println!("length of some is {}", some.len()); // str // Is an unsized type // Tuples // Ordered list of fixed size let mut x: (i32, &str) = (1, "hello"); let y = (2, "hellos"); x = y; // accessing values in tuple with destructuring let let (number, word) = x; println!("There are {} {}.", number, word); // single element tuple (0,); // Tuple indexing println!("There are {} {}.", x.0, x.1); } /// # Doc comments here /// /// Markdown is supported fn comments() { //! # This documents the containing element //! instead of the following element (0,); // This is a line comment. } fn if_() { let x = 5; if x == 5 { println!("x is five!"); } else if x == 6 { println!("x is six!"); } else { println!("x is not five or six :("); } // if is an expression let y = if x == 6 { 10 } else { 20 }; println!("y is {}", y); } fn loops() { // loop // indefinite loop loop { break; } // while let mut x = 0; while x < 2 { println!("x is now {} in while loop", x); x += 1; } // for // for var in expression { code } for x in 0..5 { println!("x is now {} in for loop", x); } // Enumerate for (i, j) in (5..10).enumerate() { println!("i is {} and j is {}", i, j); } // Ending iteration early // break let mut x = 5; loop { x += x - 3; println!("x is {}", x); if x % 5 == 0 { break; } } // continue for x in 0..10 { if x % 2 == 0 { continue; } println!("x is {}", x); } // Loop labels 'outer: for x in 0..6 { 'inner: for y in 0..6 { if x % 2 == 0 { continue 'outer }; if y % 2 == 0 { continue 'inner }; println!("x is {} and y is {}", x, y); } } } fn ownership() { //! using zero-cost abstractions //! ownership is a primary example of zero-cost abstractions //! all features talked about are done compile time // Vector v will be deallocated deterministically after it goes out of scope // even if it is allocated on the heap let v = vec![1, 2, 3]; // The ownership is transferred to v2 let v2 = v; // println!("v[0] is: {}", v[0]); // This will generate an error. take_ownership(v2); // println!("v2[0] is: {}", v2[0]); // This will also generate an error. // Copy types (trait) let v = 1; let v2 = v; println!("v is {} and v2 is {}", v, v2); } fn take_ownership(v: Vec<i32>) -> i32 { // nothing happens v[0] } fn reference_and_borrowing() { let v = vec![1, 2, 3]; take_reference(&v); println!("v[0] is {}", v[0]); // Mutable reference let mut x = 5; { let y = &mut x; *y += 1; } println!("Mutable x is now {}", x); // The rules // Borrower scope should never lasts longer than the owner // You can only have one or the other type of borrows // Only one mutable reference is allowed } fn take_reference(v: &Vec<i32>) -> i32 { // v[1] = 1; // Reference (borrowed) are immutable. v[0] } fn lifetimes() { explicit_lifetime(&10); function_with_lifetime(); let e = ExplicitLifetime { x: &5 }; println!("{}", e.x()); // Static lifetime for the entire program. let x: &'static str = "Hello World!"; println!("{}", x); // Lifetime Elision // input lifetime: parameter // output lifetime: return value // elide input lifetime and use this to infer output lifetime // 1. each argument has distinct life time // 2. if only one input lifetime, same output lifetime. // 3. if multiple lifetime, but one is "self", lifetime of self for output // otherwise, fail. } fn explicit_lifetime<'a>(x: &'a i32) { println!("x is {}", x); } fn function_with_lifetime<'a, 'b>() { } // The ExplicitLifetime struct cannot outlive the x it contains struct ExplicitLifetime<'a> { x: &'a i32, } impl<'a> ExplicitLifetime<'a> { fn x(&self) -> &'a i32 { self.x } } fn mutability() { // mutable variable binding let mut x = 5; x = 6; println!("{}", x); // mutable reference let mut x = 5; let y = &mut x; // This is immutable reference. *y = 10; println!("y is {}", *y); let mut x = 5; let mut z = 10; let mut y = &mut x; y = &mut z; println!("y is {}", *y); // Interior vs exterior mutability // Field level mutability struct Point { x: i32, y: Cell<i32>, } let point = Point { x: 10, y: Cell::new(10) }; point.y.set(11); println!("point is {}, {:?}", point.x, point.y); } fn struct_() { // Update syntax struct Point3d { x: i32, y: i32, z: i32, } let a = Point3d { x: 1, y: 2, z: 3 }; let b = Point3d { y: 10,.. a }; println!("{}, {}, {}", a.x, a.y, a.z); println!("{}, {}, {}", a.x, b.y, b.z); // Tuple structs // better to use struct than tuple structs struct Color(i32, i32, i32); // "newtype" pattern struct Inches(i32); let length = Inches(10); let Inches(integer_length) = length; println!("length is {} inches", integer_length); // Unit-like struct struct Unit; let x = Unit; } fn enums() { enum Message { Quit, ChangeColor(i32, i32, i32), Move {x: i32, y: i32}, Write(String), } let m1 = Message::Quit; let m2 = Message::Move {x: 10, y: 20}; // Constructor as functions let m3 = Message::Write("Hello World!".to_string()); } fn match_() { let x = 5; match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), 4 => println!("four"), 5 => println!("five"), _ => println!("something else"), } let number = match x { 1 => "one", 2 => "two", 5 => "five", _ => "other", }; // Matching on enums enum Message { Quit, Move {x: i32, y: i32}, } let msg = Message::Move {x: 1, y: 2}; match msg { Message::Quit => println!("Quitting"), Message::Move {x: x, y: y} => println!("Moving to {} {}", x, y), } } fn patterns() { let x = "x"; let c = "c"; match c { x => println!("x: {} c: {}", x, c), } println!("x: {}", x); // Multiple patterns match x { "x" | "y" => println!("is x or y"), _ => println!("not x or y"), } // Destrcturing struct Point { x: i32, y: i32, } let origin = Point { x: 0, y: 0 }; match origin { Point { x: x1,.. } => println!("({}, 0)", x1), } // Ignoring bindings // Use _ or.. inside the pattern // ref and ref mut let mut x = 5; match x { ref r => println!("Got a reference to {}", r), } match x { ref mut mr => println!("Got a mutable reference to {}", mr), } // Ranges // Use..., mostly used with integers and chars // Bindings // Use @ match x { a @ 1... 2 | a @ 3... 5 => println!("one through five ({}).", a), 6... 10 => println!("six through ten"), _ => println!("everything else"), } // Guards enum OptionalInt { Value(i32), Missing, } let x = OptionalInt::Value(5); match x { OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"), OptionalInt::Value(..) => println!("Got an int!"), OptionalInt::Missing => println!("No such luck!"), } } fn method_syntax() { struct Circle { x: f64, y: f64, radius: f64, } impl Circle { // Associated function fn new(x: f64, y: f64, radius: f64) -> Circle { Circle { x: x, y: y, radius: radius, } } fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } fn grow(&self, increment: f64) -> Circle { Circle { x: self.x, y: self.y, radius: self.radius + increment } } } let c = Circle::new(0.0, 0.0, 2.0); println!("area is {}", c.area()); // Chaining method calls println!("c2's area is {}", c.grow(2.0).area()); // Builder pattern struct CircleBuilder { x: f64, y: f64, radius: f64, } impl CircleBuilder { fn new() -> CircleBuilder { CircleBuilder { x: 0.0, y: 0.0, radius: 1.0 } } fn x(&mut self, coordinate: f64) -> &mut CircleBuilder { self.x = coordinate; self } fn y(&mut self, coordinate: f64) -> &mut CircleBuilder { self.y = coordinate; self } fn radius(&mut self, coordinate: f64) -> &mut CircleBuilder { self.radius = coordinate; self } fn finalize(&self) -> Circle { Circle::new(self.x, self.y, self.radius) } } let c3 = CircleBuilder::new() .x(3.0) .radius(10.0) .finalize(); println!("area is {}", c3.area()); } fn vectors() { let v = vec![1, 2, 3, 4, 5]; let v2 = vec![0; 10]; // ten zeros println!("the third element is {}", v[2]); // Index is usize type // Iterating for i in &v2 { println!("A reference to {}", i); } } fn strings() { // resizable, a sequence of utf-8 characters, not null terminated // &str is a string slice, has fixed size. let greeting = "Hello there."; // &'static str let s = "foo bar"; let s2 = "foo\ bar"; println!("{}", s); println!("{}", s2); let mut s = "Hello".to_string(); // String s.push_str(", world."); println!("{}", s); // Indexing // because of utf-8 strings do not support indexing let name = "赵洋磊"; for b in name.as_bytes() { print!("{} ", b); } println!(""); for c in name.chars() { print!("{} ", c); } println!(""); // Slicing // but for some reason you can do slicing let last_name = &name[0..3]; // byte offsets, has to end on character boundary println!("{}", last_name); // Concatenation let hello = "Hello ".to_string(); let world = "world!"; let hello_world = hello + world; println!("{}", hello_world); } fn generics() { enum MyOption<T> { // T is just convention. Some(T), None, } let x: MyOption<i32> = MyOption::Some(5); let y: MyOption<f64> = MyOption::Some(10.24); // Also can have mutliple types. // enum Result<A, Z> {} // Generic functions // fn takes_anything<T>(x: T) { // } // Generic structs // struct Point<T> { // x: T, // y: T, // } // impl<T> Point<T> {} } fn traits() { trait HasArea { fn area(&self) -> f64; } struct Circle { radius: f64, } impl HasArea for Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } } struct Square { side: f64, } impl HasArea for Square { fn area(&self) -> f64 { self.side * self.side } } // Trait bounds on generic functions fn print_area<T: HasArea>(shape: T) { println!("This shape has an area of {}", shape.area()); } let c = Circle { radius: 2.0 }; let s = Square { side: 2.0 }; print_area(c); print_area(s); // Trait bounds on generic structs struct Rectangle<T> { width: T, height: T, } impl<T: PartialEq> Rectangle<T> { fn is_square(&self) -> bool { self.width == self.height } } let r = Rectangle { width: 47, height: 47, }; println!("This is a square? {}", r.is_square()); // Rules for implementing traits impl HasArea for i32 { fn area(&self) -> f64 { *self as f64 } } println!("silly {}", 5.area()); // Two rules: // Traits has to be defined in your scope to apply (use "use") // Either the trait, or the type you're writing impl for, must be defined by you. // Mutliple bounds // use + // fn foo<T: Clone + Debug>(x: T) {} // Where clause // syntax sugar // fn foo<T: Clone, K: Clone + Debug>(x: T, y: K) {} // equals // fn bar<T, K>(x: T, y: K) where T: Clone, K: Clone + Debug {} // Default methods trait foo { fn is_valid(&self) -> bool; fn is_invalid(&self) -> bool {!self.is_valid() } } // Inheritance trait bar : foo { fn is_good(&self); } // Deriving #[derive(Debug)] struct Foo; println!("{:?}", Foo); } fn drop() { // A special trait from Rust standard library. When things goes out of scope. struct Firework { strength: i32, }; impl Drop for Firework { fn drop(&mut self) { println!("Dropping {}!", self.strength); } } // First in, last out let small = Firework { strength: 1 }; let big = Firework { strength: 100 }; } fn if_let() { let option = Option::Some(5); if let Some(x) = option { println!("{}", x); } else { println!("Nothing"); } let mut v = vec![1, 3, 5, 7, 11]; while let Some(x) = v.pop() { println!("{}", x); } } fn trait_objects() { trait Foo { fn method(&self) -> String; } impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } } impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } } let x = 5u8; let y = "Hello".to_string(); // Static dispatching fn do_something<T: Foo>(x: T) { println!("{}", x.method()); } do_something(x); do_something(y); // Trait objects can store any type that implement the trait. // obtained by casting or coercing // Dynamic dispatching fn do_something_else(x: &Foo) { println!("{}", x.method()); } do_something_else(&x); } fn closures() { // This is a closure: |args| expression let plus_one = |x: i32| x + 1; assert_eq!(2, plus_one(1)); // {} is expression, so multiline closure, arguments/return value don't // have to be annotated, but could let plus_two = |x| -> i32 { let mut result: i32 = x; result += 2; result }; assert_eq!(4, plus_two(2)); let num = 5; // Here plus_num borrows the variable binding num let plus_num = |x: i32| x + num; // move closures // regular closure, which borrows the variable num_a, and modify the // underlying value in the closure. let mut num_a = 5; { let mut add_num = |x: i32| num_a += x; add_num(5); } assert_eq!(10, num_a); // move closures, which creates an copy and takes ownership of the variable let mut num_b = 5; { let mut add_num = move |x: i32| num_b += x; add_num(5); } assert_eq!(5, num_b); // Closures are traits, Fn, FnMut, FnOnce. // The following is statically dispatched fn call_with_one<F>(some_closure: F) -> i32 where F: Fn(i32) -> i32 { some_closure(1) } let answer = call_with_one(|x| x + 2); assert_eq!(3, answer); // This is dynamically dispatched (trait object) fn call_with_two(some_closure: &Fn(i32) -> i32) -> i32 { some_closure(2) } let answer = call_with_two(&|x| x + 2); assert_eq!(4, answer); // How to return a closure fn factory() -> Box<Fn(i32) -> i32> { let num = 5; Box::new(move |x| x + num) } let f = factory(); let answer = f(1); assert_eq!(6, answer);
primitive_types
identifier_name
main.rs
use std::cell::Cell; fn main() { variable_bindings(); functions(); primitive_types(); comments(); if_(); loops(); ownership(); reference_and_borrowing(); lifetimes(); mutability(); struct_(); enums(); match_(); patterns(); method_syntax(); vectors(); strings(); generics(); traits(); drop(); if_let(); trait_objects(); closures(); } fn variable_bindings() { // Variable bindings let x = 5; println!("{}", x); // Patterns let (x, y) = (2, 3); println!("{}, {}", x, y); // Type annotation let y: u32 = 10; println!("{}", y); // Mutability let mut x = 10; println!("x is {} before mutation", x); x = 5; println!("x is {} after mutation", x); // Initializing bindings // The following won't compile because x is not initialized. // let x: i32; // println!("{}", x); // Scope and shadowing { println!("x is {} inside the scope, before shadowing", x); let x: u16 = 121; println!("x is {} inside the scope", x); } println!("x is {} outside the scope", x); // Here the variable is no longer mutable let x = x; println!("x is {}", x); } fn functions() { addition(50, 100); println!("{} plus one is {}", 10, add_by_one(10)); // Expression vs statements // expression returns a value, statements don't // This is an declaration statement // let x = 10; // The evaluation of "x = 10" is empty tuple () // Expression statement turns express to statments. println!("{} is even? {}", 3, is_even(3)); // Function pointers let f: fn(i32) -> i32 = add_by_one; println!("Using function pointers {}", f(10)); } fn addition(x: i32, y: i32) { println!("{} + {} = {}", x, y, x + y); } fn add_by_one(x: i32) -> i32 { x + 1 } fn is_even(i: i32) -> bool { if i % 2 == 0 { return true; } false } // Can be used as any type fn diverges() ->! { loop {}; } fn primitive_types() { // Booleans let x: bool = false; println!("x is {}", x); // char, supports Unicode let x: char = 'A'; println!("x is {}", x); // Numeric values // signed and fixed size let x: i8 = -12; println!("x is {}", x); // unsigned and fixed size let x: u8 = 12; println!("x is {}", x); // variable size (depending on underlying machine size) let x: usize = 1200; println!("x is {}", x); // floating point let x = 1.0; println!("x is {}", x); // Arrays (fixed sized) let a: [u8; 3] = [1, 2, 3]; println!("a[0] is {}", a[0]); // shorthand initialization let a = [100; 20]; println!("a[0] is {}", a[0]); println!("length of a is {}", a.len()); // Slices let complete = &a[..]; println!("length of complete is {}", complete.len()); let some: &[u32] = &a[5..10]; println!("length of some is {}", some.len()); // str // Is an unsized type // Tuples // Ordered list of fixed size let mut x: (i32, &str) = (1, "hello"); let y = (2, "hellos"); x = y; // accessing values in tuple with destructuring let let (number, word) = x; println!("There are {} {}.", number, word); // single element tuple (0,); // Tuple indexing println!("There are {} {}.", x.0, x.1); } /// # Doc comments here /// /// Markdown is supported fn comments() { //! # This documents the containing element //! instead of the following element (0,); // This is a line comment. } fn if_() { let x = 5; if x == 5 { println!("x is five!"); } else if x == 6 { println!("x is six!"); } else { println!("x is not five or six :("); } // if is an expression let y = if x == 6 { 10 } else { 20 }; println!("y is {}", y); } fn loops() { // loop // indefinite loop loop { break; } // while let mut x = 0; while x < 2 { println!("x is now {} in while loop", x); x += 1; } // for // for var in expression { code } for x in 0..5 { println!("x is now {} in for loop", x); } // Enumerate for (i, j) in (5..10).enumerate() { println!("i is {} and j is {}", i, j); } // Ending iteration early // break let mut x = 5; loop { x += x - 3; println!("x is {}", x); if x % 5 == 0 { break; } } // continue for x in 0..10 { if x % 2 == 0 { continue; } println!("x is {}", x); } // Loop labels 'outer: for x in 0..6 { 'inner: for y in 0..6 { if x % 2 == 0 { continue 'outer }; if y % 2 == 0 { continue 'inner }; println!("x is {} and y is {}", x, y); } } } fn ownership() { //! using zero-cost abstractions //! ownership is a primary example of zero-cost abstractions //! all features talked about are done compile time // Vector v will be deallocated deterministically after it goes out of scope // even if it is allocated on the heap let v = vec![1, 2, 3]; // The ownership is transferred to v2 let v2 = v; // println!("v[0] is: {}", v[0]); // This will generate an error. take_ownership(v2); // println!("v2[0] is: {}", v2[0]); // This will also generate an error. // Copy types (trait) let v = 1; let v2 = v; println!("v is {} and v2 is {}", v, v2); } fn take_ownership(v: Vec<i32>) -> i32 { // nothing happens v[0] } fn reference_and_borrowing() { let v = vec![1, 2, 3]; take_reference(&v); println!("v[0] is {}", v[0]); // Mutable reference let mut x = 5; { let y = &mut x; *y += 1; } println!("Mutable x is now {}", x); // The rules // Borrower scope should never lasts longer than the owner // You can only have one or the other type of borrows // Only one mutable reference is allowed } fn take_reference(v: &Vec<i32>) -> i32 { // v[1] = 1; // Reference (borrowed) are immutable. v[0] } fn lifetimes() { explicit_lifetime(&10); function_with_lifetime(); let e = ExplicitLifetime { x: &5 }; println!("{}", e.x()); // Static lifetime for the entire program. let x: &'static str = "Hello World!"; println!("{}", x); // Lifetime Elision // input lifetime: parameter // output lifetime: return value // elide input lifetime and use this to infer output lifetime // 1. each argument has distinct life time // 2. if only one input lifetime, same output lifetime. // 3. if multiple lifetime, but one is "self", lifetime of self for output // otherwise, fail. } fn explicit_lifetime<'a>(x: &'a i32) { println!("x is {}", x); } fn function_with_lifetime<'a, 'b>() { } // The ExplicitLifetime struct cannot outlive the x it contains struct ExplicitLifetime<'a> { x: &'a i32, } impl<'a> ExplicitLifetime<'a> { fn x(&self) -> &'a i32 { self.x } } fn mutability() { // mutable variable binding let mut x = 5; x = 6; println!("{}", x); // mutable reference let mut x = 5; let y = &mut x; // This is immutable reference. *y = 10; println!("y is {}", *y); let mut x = 5; let mut z = 10; let mut y = &mut x; y = &mut z; println!("y is {}", *y); // Interior vs exterior mutability // Field level mutability struct Point { x: i32, y: Cell<i32>, } let point = Point { x: 10, y: Cell::new(10) }; point.y.set(11); println!("point is {}, {:?}", point.x, point.y); } fn struct_() { // Update syntax struct Point3d { x: i32, y: i32, z: i32, } let a = Point3d { x: 1, y: 2, z: 3 }; let b = Point3d { y: 10,.. a }; println!("{}, {}, {}", a.x, a.y, a.z); println!("{}, {}, {}", a.x, b.y, b.z); // Tuple structs // better to use struct than tuple structs struct Color(i32, i32, i32); // "newtype" pattern struct Inches(i32); let length = Inches(10); let Inches(integer_length) = length; println!("length is {} inches", integer_length); // Unit-like struct struct Unit; let x = Unit; } fn enums() { enum Message { Quit, ChangeColor(i32, i32, i32), Move {x: i32, y: i32}, Write(String), } let m1 = Message::Quit; let m2 = Message::Move {x: 10, y: 20}; // Constructor as functions let m3 = Message::Write("Hello World!".to_string()); } fn match_() { let x = 5; match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), 4 => println!("four"), 5 => println!("five"), _ => println!("something else"), } let number = match x { 1 => "one", 2 => "two", 5 => "five", _ => "other", }; // Matching on enums enum Message { Quit, Move {x: i32, y: i32}, } let msg = Message::Move {x: 1, y: 2}; match msg { Message::Quit => println!("Quitting"), Message::Move {x: x, y: y} => println!("Moving to {} {}", x, y), } } fn patterns() { let x = "x"; let c = "c"; match c { x => println!("x: {} c: {}", x, c), } println!("x: {}", x); // Multiple patterns match x { "x" | "y" => println!("is x or y"), _ => println!("not x or y"), } // Destrcturing struct Point { x: i32, y: i32, } let origin = Point { x: 0, y: 0 }; match origin { Point { x: x1,.. } => println!("({}, 0)", x1), } // Ignoring bindings // Use _ or.. inside the pattern // ref and ref mut let mut x = 5; match x { ref r => println!("Got a reference to {}", r), } match x { ref mut mr => println!("Got a mutable reference to {}", mr), } // Ranges // Use..., mostly used with integers and chars // Bindings // Use @ match x { a @ 1... 2 | a @ 3... 5 => println!("one through five ({}).", a), 6... 10 => println!("six through ten"), _ => println!("everything else"), } // Guards enum OptionalInt { Value(i32), Missing, } let x = OptionalInt::Value(5); match x { OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"), OptionalInt::Value(..) => println!("Got an int!"), OptionalInt::Missing => println!("No such luck!"), } } fn method_syntax() { struct Circle { x: f64, y: f64, radius: f64, } impl Circle { // Associated function fn new(x: f64, y: f64, radius: f64) -> Circle { Circle { x: x, y: y, radius: radius, } } fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } fn grow(&self, increment: f64) -> Circle { Circle { x: self.x, y: self.y, radius: self.radius + increment } } } let c = Circle::new(0.0, 0.0, 2.0); println!("area is {}", c.area()); // Chaining method calls println!("c2's area is {}", c.grow(2.0).area()); // Builder pattern struct CircleBuilder { x: f64, y: f64, radius: f64, } impl CircleBuilder { fn new() -> CircleBuilder { CircleBuilder { x: 0.0, y: 0.0, radius: 1.0 } } fn x(&mut self, coordinate: f64) -> &mut CircleBuilder { self.x = coordinate; self } fn y(&mut self, coordinate: f64) -> &mut CircleBuilder { self.y = coordinate; self } fn radius(&mut self, coordinate: f64) -> &mut CircleBuilder { self.radius = coordinate; self } fn finalize(&self) -> Circle { Circle::new(self.x, self.y, self.radius) } } let c3 = CircleBuilder::new() .x(3.0) .radius(10.0) .finalize(); println!("area is {}", c3.area()); } fn vectors() { let v = vec![1, 2, 3, 4, 5]; let v2 = vec![0; 10]; // ten zeros println!("the third element is {}", v[2]); // Index is usize type // Iterating for i in &v2 { println!("A reference to {}", i); } } fn strings() { // resizable, a sequence of utf-8 characters, not null terminated // &str is a string slice, has fixed size. let greeting = "Hello there."; // &'static str let s = "foo bar"; let s2 = "foo\ bar"; println!("{}", s); println!("{}", s2); let mut s = "Hello".to_string(); // String s.push_str(", world."); println!("{}", s); // Indexing // because of utf-8 strings do not support indexing let name = "赵洋磊"; for b in name.as_bytes() { print!("{} ", b); } println!(""); for c in name.chars() { print!("{} ", c); } println!(""); // Slicing // but for some reason you can do slicing let last_name = &name[0..3]; // byte offsets, has to end on character boundary println!("{}", last_name); // Concatenation let hello = "Hello ".to_string(); let world = "world!"; let hello_world = hello + world; println!("{}", hello_world); } fn generics() { enum MyOption<T> { // T is just convention. Some(T), None, } let x: MyOption<i32> = MyOption::Some(5); let y: MyOption<f64> = MyOption::Some(10.24); // Also can have mutliple types. // enum Result<A, Z> {} // Generic functions // fn takes_anything<T>(x: T) { // } // Generic structs // struct Point<T> { // x: T, // y: T, // } // impl<T> Point<T> {} } fn traits() { trait HasArea { fn area(&self) -> f64; } struct Circle { radius: f64, } impl HasArea for Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } } struct Square { side: f64, } impl HasArea for Square { fn area(&self) -> f64 { self.side * self.side } } // Trait bounds on generic functions fn print_area<T: HasArea>(shape: T) { println!("This shape has an area of {}", shape.area()); } let c = Circle { radius: 2.0 }; let s = Square { side: 2.0 }; print_area(c); print_area(s); // Trait bounds on generic structs struct Rectangle<T> { width: T, height: T, } impl<T: PartialEq> Rectangle<T> { fn is_square(&self) -> bool { self.width == self.height } } let r = Rectangle { width: 47, height: 47, }; println!("This is a square? {}", r.is_square()); // Rules for implementing traits impl HasArea for i32 { fn area(&self) -> f64 { *self as f64 } } println!("silly {}", 5.area()); // Two rules: // Traits has to be defined in your scope to apply (use "use") // Either the trait, or the type you're writing impl for, must be defined by you. // Mutliple bounds // use + // fn foo<T: Clone + Debug>(x: T) {} // Where clause // syntax sugar // fn foo<T: Clone, K: Clone + Debug>(x: T, y: K) {} // equals // fn bar<T, K>(x: T, y: K) where T: Clone, K: Clone + Debug {} // Default methods trait foo { fn is_valid(&self) -> bool; fn is_invalid(&self) -> bool {!sel
// Inheritance trait bar : foo { fn is_good(&self); } // Deriving #[derive(Debug)] struct Foo; println!("{:?}", Foo); } fn drop() { // A special trait from Rust standard library. When things goes out of scope. struct Firework { strength: i32, }; impl Drop for Firework { fn drop(&mut self) { println!("Dropping {}!", self.strength); } } // First in, last out let small = Firework { strength: 1 }; let big = Firework { strength: 100 }; } fn if_let() { let option = Option::Some(5); if let Some(x) = option { println!("{}", x); } else { println!("Nothing"); } let mut v = vec![1, 3, 5, 7, 11]; while let Some(x) = v.pop() { println!("{}", x); } } fn trait_objects() { trait Foo { fn method(&self) -> String; } impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } } impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } } let x = 5u8; let y = "Hello".to_string(); // Static dispatching fn do_something<T: Foo>(x: T) { println!("{}", x.method()); } do_something(x); do_something(y); // Trait objects can store any type that implement the trait. // obtained by casting or coercing // Dynamic dispatching fn do_something_else(x: &Foo) { println!("{}", x.method()); } do_something_else(&x); } fn closures() { // This is a closure: |args| expression let plus_one = |x: i32| x + 1; assert_eq!(2, plus_one(1)); // {} is expression, so multiline closure, arguments/return value don't // have to be annotated, but could let plus_two = |x| -> i32 { let mut result: i32 = x; result += 2; result }; assert_eq!(4, plus_two(2)); let num = 5; // Here plus_num borrows the variable binding num let plus_num = |x: i32| x + num; // move closures // regular closure, which borrows the variable num_a, and modify the // underlying value in the closure. let mut num_a = 5; { let mut add_num = |x: i32| num_a += x; add_num(5); } assert_eq!(10, num_a); // move closures, which creates an copy and takes ownership of the variable let mut num_b = 5; { let mut add_num = move |x: i32| num_b += x; add_num(5); } assert_eq!(5, num_b); // Closures are traits, Fn, FnMut, FnOnce. // The following is statically dispatched fn call_with_one<F>(some_closure: F) -> i32 where F: Fn(i32) -> i32 { some_closure(1) } let answer = call_with_one(|x| x + 2); assert_eq!(3, answer); // This is dynamically dispatched (trait object) fn call_with_two(some_closure: &Fn(i32) -> i32) -> i32 { some_closure(2) } let answer = call_with_two(&|x| x + 2); assert_eq!(4, answer); // How to return a closure fn factory() -> Box<Fn(i32) -> i32> { let num = 5; Box::new(move |x| x + num) } let f = factory(); let answer = f(1); assert_eq!(6, answer);
f.is_valid() } }
identifier_body
main.rs
use std::cell::Cell; fn main() { variable_bindings(); functions(); primitive_types(); comments(); if_(); loops(); ownership(); reference_and_borrowing(); lifetimes(); mutability(); struct_(); enums(); match_(); patterns(); method_syntax(); vectors(); strings(); generics(); traits(); drop(); if_let(); trait_objects(); closures(); } fn variable_bindings() { // Variable bindings let x = 5; println!("{}", x); // Patterns let (x, y) = (2, 3); println!("{}, {}", x, y); // Type annotation let y: u32 = 10; println!("{}", y); // Mutability let mut x = 10; println!("x is {} before mutation", x); x = 5; println!("x is {} after mutation", x); // Initializing bindings // The following won't compile because x is not initialized. // let x: i32; // println!("{}", x); // Scope and shadowing { println!("x is {} inside the scope, before shadowing", x); let x: u16 = 121; println!("x is {} inside the scope", x); } println!("x is {} outside the scope", x); // Here the variable is no longer mutable let x = x; println!("x is {}", x); } fn functions() { addition(50, 100); println!("{} plus one is {}", 10, add_by_one(10)); // Expression vs statements // expression returns a value, statements don't // This is an declaration statement // let x = 10; // The evaluation of "x = 10" is empty tuple () // Expression statement turns express to statments. println!("{} is even? {}", 3, is_even(3)); // Function pointers let f: fn(i32) -> i32 = add_by_one; println!("Using function pointers {}", f(10)); } fn addition(x: i32, y: i32) { println!("{} + {} = {}", x, y, x + y); } fn add_by_one(x: i32) -> i32 { x + 1 } fn is_even(i: i32) -> bool { if i % 2 == 0 { return true; } false } // Can be used as any type fn diverges() ->! { loop {}; } fn primitive_types() { // Booleans let x: bool = false; println!("x is {}", x); // char, supports Unicode let x: char = 'A'; println!("x is {}", x); // Numeric values // signed and fixed size let x: i8 = -12; println!("x is {}", x); // unsigned and fixed size let x: u8 = 12; println!("x is {}", x); // variable size (depending on underlying machine size) let x: usize = 1200; println!("x is {}", x); // floating point let x = 1.0; println!("x is {}", x); // Arrays (fixed sized) let a: [u8; 3] = [1, 2, 3]; println!("a[0] is {}", a[0]); // shorthand initialization let a = [100; 20]; println!("a[0] is {}", a[0]); println!("length of a is {}", a.len()); // Slices let complete = &a[..]; println!("length of complete is {}", complete.len()); let some: &[u32] = &a[5..10]; println!("length of some is {}", some.len()); // str // Is an unsized type // Tuples // Ordered list of fixed size let mut x: (i32, &str) = (1, "hello"); let y = (2, "hellos"); x = y; // accessing values in tuple with destructuring let let (number, word) = x; println!("There are {} {}.", number, word); // single element tuple (0,); // Tuple indexing println!("There are {} {}.", x.0, x.1); } /// # Doc comments here /// /// Markdown is supported fn comments() { //! # This documents the containing element //! instead of the following element (0,); // This is a line comment. } fn if_() { let x = 5; if x == 5 { println!("x is five!"); } else if x == 6 { println!("x is six!"); } else { println!("x is not five or six :("); } // if is an expression let y = if x == 6 { 10 } else { 20 }; println!("y is {}", y); } fn loops() { // loop // indefinite loop loop { break; } // while let mut x = 0; while x < 2 { println!("x is now {} in while loop", x); x += 1; } // for // for var in expression { code } for x in 0..5 { println!("x is now {} in for loop", x); } // Enumerate for (i, j) in (5..10).enumerate() { println!("i is {} and j is {}", i, j); } // Ending iteration early // break let mut x = 5; loop { x += x - 3; println!("x is {}", x); if x % 5 == 0 { break; } } // continue for x in 0..10 { if x % 2 == 0 { continue; } println!("x is {}", x); } // Loop labels 'outer: for x in 0..6 { 'inner: for y in 0..6 { if x % 2 == 0 { continue 'outer }; if y % 2 == 0 { continue 'inner }; println!("x is {} and y is {}", x, y); } } } fn ownership() { //! using zero-cost abstractions //! ownership is a primary example of zero-cost abstractions //! all features talked about are done compile time // Vector v will be deallocated deterministically after it goes out of scope // even if it is allocated on the heap let v = vec![1, 2, 3]; // The ownership is transferred to v2 let v2 = v; // println!("v[0] is: {}", v[0]); // This will generate an error. take_ownership(v2); // println!("v2[0] is: {}", v2[0]); // This will also generate an error. // Copy types (trait) let v = 1; let v2 = v; println!("v is {} and v2 is {}", v, v2); } fn take_ownership(v: Vec<i32>) -> i32 { // nothing happens v[0] } fn reference_and_borrowing() { let v = vec![1, 2, 3]; take_reference(&v); println!("v[0] is {}", v[0]); // Mutable reference let mut x = 5; { let y = &mut x; *y += 1; } println!("Mutable x is now {}", x); // The rules // Borrower scope should never lasts longer than the owner // You can only have one or the other type of borrows // Only one mutable reference is allowed } fn take_reference(v: &Vec<i32>) -> i32 { // v[1] = 1; // Reference (borrowed) are immutable. v[0] } fn lifetimes() { explicit_lifetime(&10); function_with_lifetime(); let e = ExplicitLifetime { x: &5 }; println!("{}", e.x()); // Static lifetime for the entire program. let x: &'static str = "Hello World!"; println!("{}", x); // Lifetime Elision // input lifetime: parameter // output lifetime: return value // elide input lifetime and use this to infer output lifetime // 1. each argument has distinct life time // 2. if only one input lifetime, same output lifetime. // 3. if multiple lifetime, but one is "self", lifetime of self for output // otherwise, fail. } fn explicit_lifetime<'a>(x: &'a i32) { println!("x is {}", x); } fn function_with_lifetime<'a, 'b>() { } // The ExplicitLifetime struct cannot outlive the x it contains struct ExplicitLifetime<'a> { x: &'a i32, } impl<'a> ExplicitLifetime<'a> { fn x(&self) -> &'a i32 { self.x } } fn mutability() { // mutable variable binding let mut x = 5; x = 6; println!("{}", x); // mutable reference let mut x = 5; let y = &mut x; // This is immutable reference. *y = 10; println!("y is {}", *y); let mut x = 5; let mut z = 10; let mut y = &mut x; y = &mut z; println!("y is {}", *y); // Interior vs exterior mutability // Field level mutability struct Point { x: i32, y: Cell<i32>, } let point = Point { x: 10, y: Cell::new(10) }; point.y.set(11); println!("point is {}, {:?}", point.x, point.y); } fn struct_() { // Update syntax struct Point3d { x: i32, y: i32, z: i32, } let a = Point3d { x: 1, y: 2, z: 3 }; let b = Point3d { y: 10,.. a }; println!("{}, {}, {}", a.x, a.y, a.z); println!("{}, {}, {}", a.x, b.y, b.z); // Tuple structs // better to use struct than tuple structs struct Color(i32, i32, i32); // "newtype" pattern struct Inches(i32); let length = Inches(10); let Inches(integer_length) = length; println!("length is {} inches", integer_length); // Unit-like struct struct Unit; let x = Unit; } fn enums() { enum Message { Quit, ChangeColor(i32, i32, i32), Move {x: i32, y: i32}, Write(String), } let m1 = Message::Quit; let m2 = Message::Move {x: 10, y: 20}; // Constructor as functions let m3 = Message::Write("Hello World!".to_string()); } fn match_() { let x = 5; match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), 4 => println!("four"), 5 => println!("five"), _ => println!("something else"), } let number = match x { 1 => "one", 2 => "two", 5 => "five", _ => "other", }; // Matching on enums enum Message { Quit, Move {x: i32, y: i32}, } let msg = Message::Move {x: 1, y: 2}; match msg { Message::Quit => println!("Quitting"), Message::Move {x: x, y: y} => println!("Moving to {} {}", x, y), } } fn patterns() { let x = "x"; let c = "c"; match c { x => println!("x: {} c: {}", x, c), } println!("x: {}", x); // Multiple patterns match x { "x" | "y" => println!("is x or y"), _ => println!("not x or y"), } // Destrcturing struct Point { x: i32, y: i32, } let origin = Point { x: 0, y: 0 }; match origin { Point { x: x1,.. } => println!("({}, 0)", x1), } // Ignoring bindings // Use _ or.. inside the pattern // ref and ref mut let mut x = 5; match x { ref r => println!("Got a reference to {}", r), } match x { ref mut mr => println!("Got a mutable reference to {}", mr), } // Ranges // Use..., mostly used with integers and chars // Bindings // Use @ match x { a @ 1... 2 | a @ 3... 5 => println!("one through five ({}).", a), 6... 10 => println!("six through ten"), _ => println!("everything else"), } // Guards enum OptionalInt { Value(i32), Missing, } let x = OptionalInt::Value(5); match x { OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"), OptionalInt::Value(..) => println!("Got an int!"), OptionalInt::Missing => println!("No such luck!"), } } fn method_syntax() { struct Circle { x: f64, y: f64, radius: f64, } impl Circle { // Associated function fn new(x: f64, y: f64, radius: f64) -> Circle { Circle { x: x, y: y, radius: radius, } } fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } fn grow(&self, increment: f64) -> Circle { Circle { x: self.x, y: self.y, radius: self.radius + increment } } } let c = Circle::new(0.0, 0.0, 2.0); println!("area is {}", c.area()); // Chaining method calls println!("c2's area is {}", c.grow(2.0).area()); // Builder pattern struct CircleBuilder { x: f64, y: f64, radius: f64, } impl CircleBuilder { fn new() -> CircleBuilder { CircleBuilder { x: 0.0, y: 0.0, radius: 1.0 } } fn x(&mut self, coordinate: f64) -> &mut CircleBuilder { self.x = coordinate; self } fn y(&mut self, coordinate: f64) -> &mut CircleBuilder { self.y = coordinate; self } fn radius(&mut self, coordinate: f64) -> &mut CircleBuilder { self.radius = coordinate; self } fn finalize(&self) -> Circle { Circle::new(self.x, self.y, self.radius) } } let c3 = CircleBuilder::new() .x(3.0) .radius(10.0) .finalize(); println!("area is {}", c3.area()); } fn vectors() { let v = vec![1, 2, 3, 4, 5]; let v2 = vec![0; 10]; // ten zeros println!("the third element is {}", v[2]); // Index is usize type // Iterating
} } fn strings() { // resizable, a sequence of utf-8 characters, not null terminated // &str is a string slice, has fixed size. let greeting = "Hello there."; // &'static str let s = "foo bar"; let s2 = "foo\ bar"; println!("{}", s); println!("{}", s2); let mut s = "Hello".to_string(); // String s.push_str(", world."); println!("{}", s); // Indexing // because of utf-8 strings do not support indexing let name = "赵洋磊"; for b in name.as_bytes() { print!("{} ", b); } println!(""); for c in name.chars() { print!("{} ", c); } println!(""); // Slicing // but for some reason you can do slicing let last_name = &name[0..3]; // byte offsets, has to end on character boundary println!("{}", last_name); // Concatenation let hello = "Hello ".to_string(); let world = "world!"; let hello_world = hello + world; println!("{}", hello_world); } fn generics() { enum MyOption<T> { // T is just convention. Some(T), None, } let x: MyOption<i32> = MyOption::Some(5); let y: MyOption<f64> = MyOption::Some(10.24); // Also can have mutliple types. // enum Result<A, Z> {} // Generic functions // fn takes_anything<T>(x: T) { // } // Generic structs // struct Point<T> { // x: T, // y: T, // } // impl<T> Point<T> {} } fn traits() { trait HasArea { fn area(&self) -> f64; } struct Circle { radius: f64, } impl HasArea for Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } } struct Square { side: f64, } impl HasArea for Square { fn area(&self) -> f64 { self.side * self.side } } // Trait bounds on generic functions fn print_area<T: HasArea>(shape: T) { println!("This shape has an area of {}", shape.area()); } let c = Circle { radius: 2.0 }; let s = Square { side: 2.0 }; print_area(c); print_area(s); // Trait bounds on generic structs struct Rectangle<T> { width: T, height: T, } impl<T: PartialEq> Rectangle<T> { fn is_square(&self) -> bool { self.width == self.height } } let r = Rectangle { width: 47, height: 47, }; println!("This is a square? {}", r.is_square()); // Rules for implementing traits impl HasArea for i32 { fn area(&self) -> f64 { *self as f64 } } println!("silly {}", 5.area()); // Two rules: // Traits has to be defined in your scope to apply (use "use") // Either the trait, or the type you're writing impl for, must be defined by you. // Mutliple bounds // use + // fn foo<T: Clone + Debug>(x: T) {} // Where clause // syntax sugar // fn foo<T: Clone, K: Clone + Debug>(x: T, y: K) {} // equals // fn bar<T, K>(x: T, y: K) where T: Clone, K: Clone + Debug {} // Default methods trait foo { fn is_valid(&self) -> bool; fn is_invalid(&self) -> bool {!self.is_valid() } } // Inheritance trait bar : foo { fn is_good(&self); } // Deriving #[derive(Debug)] struct Foo; println!("{:?}", Foo); } fn drop() { // A special trait from Rust standard library. When things goes out of scope. struct Firework { strength: i32, }; impl Drop for Firework { fn drop(&mut self) { println!("Dropping {}!", self.strength); } } // First in, last out let small = Firework { strength: 1 }; let big = Firework { strength: 100 }; } fn if_let() { let option = Option::Some(5); if let Some(x) = option { println!("{}", x); } else { println!("Nothing"); } let mut v = vec![1, 3, 5, 7, 11]; while let Some(x) = v.pop() { println!("{}", x); } } fn trait_objects() { trait Foo { fn method(&self) -> String; } impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } } impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } } let x = 5u8; let y = "Hello".to_string(); // Static dispatching fn do_something<T: Foo>(x: T) { println!("{}", x.method()); } do_something(x); do_something(y); // Trait objects can store any type that implement the trait. // obtained by casting or coercing // Dynamic dispatching fn do_something_else(x: &Foo) { println!("{}", x.method()); } do_something_else(&x); } fn closures() { // This is a closure: |args| expression let plus_one = |x: i32| x + 1; assert_eq!(2, plus_one(1)); // {} is expression, so multiline closure, arguments/return value don't // have to be annotated, but could let plus_two = |x| -> i32 { let mut result: i32 = x; result += 2; result }; assert_eq!(4, plus_two(2)); let num = 5; // Here plus_num borrows the variable binding num let plus_num = |x: i32| x + num; // move closures // regular closure, which borrows the variable num_a, and modify the // underlying value in the closure. let mut num_a = 5; { let mut add_num = |x: i32| num_a += x; add_num(5); } assert_eq!(10, num_a); // move closures, which creates an copy and takes ownership of the variable let mut num_b = 5; { let mut add_num = move |x: i32| num_b += x; add_num(5); } assert_eq!(5, num_b); // Closures are traits, Fn, FnMut, FnOnce. // The following is statically dispatched fn call_with_one<F>(some_closure: F) -> i32 where F: Fn(i32) -> i32 { some_closure(1) } let answer = call_with_one(|x| x + 2); assert_eq!(3, answer); // This is dynamically dispatched (trait object) fn call_with_two(some_closure: &Fn(i32) -> i32) -> i32 { some_closure(2) } let answer = call_with_two(&|x| x + 2); assert_eq!(4, answer); // How to return a closure fn factory() -> Box<Fn(i32) -> i32> { let num = 5; Box::new(move |x| x + num) } let f = factory(); let answer = f(1); assert_eq!(6, answer); }
for i in &v2 { println!("A reference to {}", i);
random_line_split
mod.rs
//! Provides structs used to interact with the cypher transaction endpoint //! //! The types declared in this module, save for `Statement`, don't need to be instantiated //! directly, since they can be obtained from the `GraphClient`. //! //! # Examples //! //! ## Execute a single query //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! let graph = GraphClient::connect(URL).unwrap(); //! //! graph.cypher().exec("CREATE (n:CYPHER_QUERY {value: 1})").unwrap(); //! let result = graph.cypher().exec("MATCH (n:CYPHER_QUERY) RETURN n.value AS value").unwrap(); //! # assert_eq!(result.data.len(), 1); //! //! // Iterate over the results //! for row in result.rows() { //! let value = row.get::<i32>("value").unwrap(); // or: let value: i32 = row.get("value"); //! assert_eq!(value, 1); //! } //! # graph.cypher().exec("MATCH (n:CYPHER_QUERY) delete n"); //! ``` //! //! ## Execute multiple queries //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! # let graph = GraphClient::connect(URL).unwrap(); //! let mut query = graph.cypher().query() //! .with_statement("MATCH (n:SOME_CYPHER_QUERY) RETURN n.value as value") //! .with_statement("MATCH (n:OTHER_CYPHER_QUERY) RETURN n"); //! //! let results = query.send().unwrap(); //! //! for row in results[0].rows() { //! let value: i32 = row.get("value").unwrap(); //! assert_eq!(value, 1); //! } //! ``` //! //! ## Start a transaction //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! # let graph = GraphClient::connect(URL).unwrap(); //! let (transaction, results) = graph.cypher().transaction() //! .with_statement("MATCH (n:TRANSACTION_CYPHER_QUERY) RETURN n") //! .begin().unwrap(); //! //! # assert_eq!(results.len(), 1); //! ``` pub mod transaction; pub mod statement; pub mod result; pub use self::statement::Statement; pub use self::transaction::Transaction; pub use self::result::CypherResult; use std::convert::Into; use std::collections::BTreeMap; use hyper::client::{Client, Response}; use hyper::header::Headers; use url::Url; use serde::Deserialize; use serde_json::{self, Value}; use serde_json::de as json_de; use serde_json::ser as json_ser; use serde_json::value as json_value; use self::result::{QueryResult, ResultTrait}; use ::error::GraphError; #[cfg(feature = "rustc-serialize")] fn check_param_errors_for_rustc_serialize(statements: &Vec<Statement>) -> Result<(), GraphError> { for stmt in statements.iter() { if stmt.has_param_errors() { let entry = stmt.param_errors().iter().nth(1).unwrap(); return Err(GraphError::new( &format!("Error at parameter '{}' of query '{}': {}", entry.0, stmt.statement(), entry.1) )); } }
#[cfg(not(feature = "rustc-serialize"))] fn check_param_errors_for_rustc_serialize(_: &Vec<Statement>) -> Result<(), GraphError> { Ok(()) } fn send_query(client: &Client, endpoint: &str, headers: &Headers, statements: Vec<Statement>) -> Result<Response, GraphError> { if cfg!(feature = "rustc-serialize") { try!(check_param_errors_for_rustc_serialize(&statements)); } let mut json = BTreeMap::new(); json.insert("statements", statements); let json = match serde_json::to_string(&json) { Ok(json) => json, Err(e) => { error!("Unable to serialize request: {}", e); return Err(GraphError::new_error(Box::new(e))); } }; let req = client.post(endpoint) .headers(headers.clone()) .body(&json); debug!("Seding query:\n{}", json_ser::to_string_pretty(&json).unwrap_or(String::new())); let res = try!(req.send()); Ok(res) } fn parse_response<T: Deserialize + ResultTrait>(res: &mut Response) -> Result<T, GraphError> { let value = json_de::from_reader(res); let result = match value.and_then(|v: Value| json_value::from_value::<T>(v.clone())) { Ok(result) => result, Err(e) => { error!("Unable to parse response: {}", e); return Err(GraphError::new_error(Box::new(e))); } }; if result.errors().len() > 0 { return Err(GraphError::new_neo4j_error(result.errors().clone())); } Ok(result) } /// Represents the cypher endpoint of a neo4j server /// /// The `Cypher` struct holds information about the cypher enpoint. It is used to create the queries /// that are sent to the server. pub struct Cypher { endpoint: Url, client: Client, headers: Headers, } impl Cypher { /// Creates a new Cypher /// /// Its arguments are the cypher transaction endpoint and the HTTP headers containing HTTP /// Basic Authentication, if needed. pub fn new(endpoint: Url, headers: Headers) -> Self { Cypher { endpoint: endpoint, client: Client::new(), headers: headers, } } fn endpoint(&self) -> &Url { &self.endpoint } fn client(&self) -> &Client { &self.client } fn headers(&self) -> &Headers { &self.headers } /// Creates a new `CypherQuery` pub fn query(&self) -> CypherQuery { CypherQuery { statements: Vec::new(), cypher: &self, } } /// Executes the given `Statement` /// /// Parameter can be anything that implements `Into<Statement>`, `&str` or `Statement` itself pub fn exec<S: Into<Statement>>(&self, statement: S) -> Result<CypherResult, GraphError> { let mut query = self.query(); query.add_statement(statement); let mut results = try!(query.send()); match results.pop() { Some(result) => Ok(result), None => Err(GraphError::new("No results returned from server")), } } /// Creates a new `Transaction` pub fn transaction(&self) -> Transaction<self::transaction::Created> { Transaction::new(&self.endpoint.to_string(), &self.headers) } } /// Represents a cypher query /// /// A cypher query is composed by statements, each one containing the query itself and its parameters. /// /// The query parameters must implement `Serialize` so they can be serialized into JSON in order to /// be sent to the server pub struct CypherQuery<'a> { statements: Vec<Statement>, cypher: &'a Cypher, } impl<'a> CypherQuery<'a> { /// Adds statements in builder style pub fn with_statement<T: Into<Statement>>(mut self, statement: T) -> Self { self.add_statement(statement); self } pub fn add_statement<T: Into<Statement>>(&mut self, statement: T) { self.statements.push(statement.into()); } pub fn statements(&self) -> &Vec<Statement> { &self.statements } pub fn set_statements(&mut self, statements: Vec<Statement>) { self.statements = statements; } /// Sends the query to the server /// /// The statements contained in the query are sent to the server and the results are parsed /// into a `Vec<CypherResult>` in order to match the response of the neo4j api. pub fn send(self) -> Result<Vec<CypherResult>, GraphError> { let client = self.cypher.client(); let endpoint = format!("{}/{}", self.cypher.endpoint(), "commit"); let headers = self.cypher.headers(); let mut res = try!(send_query(client, &endpoint, headers, self.statements)); let result: QueryResult = try!(parse_response(&mut res)); if result.errors().len() > 0 { return Err(GraphError::new_neo4j_error(result.errors().clone())) } Ok(result.results) } } #[cfg(test)] mod tests { use super::*; use ::cypher::result::Row; fn get_cypher() -> Cypher { use hyper::Url; use hyper::header::{Authorization, Basic, ContentType, Headers}; let cypher_endpoint = Url::parse("http://localhost:7474/db/data/transaction").unwrap(); let mut headers = Headers::new(); headers.set(Authorization( Basic { username: "neo4j".to_owned(), password: Some("neo4j".to_owned()), } )); headers.set(ContentType::json()); Cypher::new(cypher_endpoint, headers) } #[test] fn query_without_params() { let result = get_cypher().exec("MATCH (n:TEST_CYPHER) RETURN n").unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_string_param() { let statement = Statement::new("MATCH (n:TEST_CYPHER {name: {name}}) RETURN n") .with_param("name", "Neo"); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_int_param() { let statement = Statement::new("MATCH (n:TEST_CYPHER {value: {value}}) RETURN n") .with_param("value", 42); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_complex_param() { #[cfg(not(feature = "rustc-serialize"))] mod inner { #[derive(Serialize, Deserialize)] pub struct ComplexType { pub name: String, pub value: i32, } } #[cfg(feature = "rustc-serialize")] mod inner { #[derive(RustcEncodable, RustcDecodable)] pub struct ComplexType { pub name: String, pub value: i32, } } let cypher = get_cypher(); let complex_param = inner::ComplexType { name: "Complex".to_owned(), value: 42, }; let statement = Statement::new("CREATE (n:TEST_CYPHER_COMPLEX_PARAM {p})") .with_param("p", &complex_param); let result = cypher.exec(statement); assert!(result.is_ok()); let results = cypher.exec("MATCH (n:TEST_CYPHER_COMPLEX_PARAM) RETURN n").unwrap(); let rows: Vec<Row> = results.rows().take(1).collect(); let row = rows.first().unwrap(); let complex_result: inner::ComplexType = row.get("n").unwrap(); assert_eq!(complex_result.name, "Complex"); assert_eq!(complex_result.value, 42); cypher.exec("MATCH (n:TEST_CYPHER_COMPLEX_PARAM) DELETE n").unwrap(); } #[test] fn query_with_multiple_params() { let statement = Statement::new( "MATCH (n:TEST_CYPHER {name: {name}}) WHERE n.value = {value} RETURN n") .with_param("name", "Neo") .with_param("value", 42); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn multiple_queries() { let cypher = get_cypher(); let statement1 = Statement::new("MATCH (n:TEST_CYPHER) RETURN n"); let statement2 = Statement::new("MATCH (n:TEST_CYPHER) RETURN n"); let query = cypher.query() .with_statement(statement1) .with_statement(statement2); let results = query.send().unwrap(); assert_eq!(results.len(), 2); } }
Ok(()) }
random_line_split
mod.rs
//! Provides structs used to interact with the cypher transaction endpoint //! //! The types declared in this module, save for `Statement`, don't need to be instantiated //! directly, since they can be obtained from the `GraphClient`. //! //! # Examples //! //! ## Execute a single query //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! let graph = GraphClient::connect(URL).unwrap(); //! //! graph.cypher().exec("CREATE (n:CYPHER_QUERY {value: 1})").unwrap(); //! let result = graph.cypher().exec("MATCH (n:CYPHER_QUERY) RETURN n.value AS value").unwrap(); //! # assert_eq!(result.data.len(), 1); //! //! // Iterate over the results //! for row in result.rows() { //! let value = row.get::<i32>("value").unwrap(); // or: let value: i32 = row.get("value"); //! assert_eq!(value, 1); //! } //! # graph.cypher().exec("MATCH (n:CYPHER_QUERY) delete n"); //! ``` //! //! ## Execute multiple queries //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! # let graph = GraphClient::connect(URL).unwrap(); //! let mut query = graph.cypher().query() //! .with_statement("MATCH (n:SOME_CYPHER_QUERY) RETURN n.value as value") //! .with_statement("MATCH (n:OTHER_CYPHER_QUERY) RETURN n"); //! //! let results = query.send().unwrap(); //! //! for row in results[0].rows() { //! let value: i32 = row.get("value").unwrap(); //! assert_eq!(value, 1); //! } //! ``` //! //! ## Start a transaction //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! # let graph = GraphClient::connect(URL).unwrap(); //! let (transaction, results) = graph.cypher().transaction() //! .with_statement("MATCH (n:TRANSACTION_CYPHER_QUERY) RETURN n") //! .begin().unwrap(); //! //! # assert_eq!(results.len(), 1); //! ``` pub mod transaction; pub mod statement; pub mod result; pub use self::statement::Statement; pub use self::transaction::Transaction; pub use self::result::CypherResult; use std::convert::Into; use std::collections::BTreeMap; use hyper::client::{Client, Response}; use hyper::header::Headers; use url::Url; use serde::Deserialize; use serde_json::{self, Value}; use serde_json::de as json_de; use serde_json::ser as json_ser; use serde_json::value as json_value; use self::result::{QueryResult, ResultTrait}; use ::error::GraphError; #[cfg(feature = "rustc-serialize")] fn check_param_errors_for_rustc_serialize(statements: &Vec<Statement>) -> Result<(), GraphError> { for stmt in statements.iter() { if stmt.has_param_errors() { let entry = stmt.param_errors().iter().nth(1).unwrap(); return Err(GraphError::new( &format!("Error at parameter '{}' of query '{}': {}", entry.0, stmt.statement(), entry.1) )); } } Ok(()) } #[cfg(not(feature = "rustc-serialize"))] fn check_param_errors_for_rustc_serialize(_: &Vec<Statement>) -> Result<(), GraphError> { Ok(()) } fn send_query(client: &Client, endpoint: &str, headers: &Headers, statements: Vec<Statement>) -> Result<Response, GraphError> { if cfg!(feature = "rustc-serialize") { try!(check_param_errors_for_rustc_serialize(&statements)); } let mut json = BTreeMap::new(); json.insert("statements", statements); let json = match serde_json::to_string(&json) { Ok(json) => json, Err(e) => { error!("Unable to serialize request: {}", e); return Err(GraphError::new_error(Box::new(e))); } }; let req = client.post(endpoint) .headers(headers.clone()) .body(&json); debug!("Seding query:\n{}", json_ser::to_string_pretty(&json).unwrap_or(String::new())); let res = try!(req.send()); Ok(res) } fn parse_response<T: Deserialize + ResultTrait>(res: &mut Response) -> Result<T, GraphError> { let value = json_de::from_reader(res); let result = match value.and_then(|v: Value| json_value::from_value::<T>(v.clone())) { Ok(result) => result, Err(e) => { error!("Unable to parse response: {}", e); return Err(GraphError::new_error(Box::new(e))); } }; if result.errors().len() > 0 { return Err(GraphError::new_neo4j_error(result.errors().clone())); } Ok(result) } /// Represents the cypher endpoint of a neo4j server /// /// The `Cypher` struct holds information about the cypher enpoint. It is used to create the queries /// that are sent to the server. pub struct Cypher { endpoint: Url, client: Client, headers: Headers, } impl Cypher { /// Creates a new Cypher /// /// Its arguments are the cypher transaction endpoint and the HTTP headers containing HTTP /// Basic Authentication, if needed. pub fn new(endpoint: Url, headers: Headers) -> Self { Cypher { endpoint: endpoint, client: Client::new(), headers: headers, } } fn endpoint(&self) -> &Url { &self.endpoint } fn client(&self) -> &Client { &self.client } fn headers(&self) -> &Headers { &self.headers } /// Creates a new `CypherQuery` pub fn query(&self) -> CypherQuery { CypherQuery { statements: Vec::new(), cypher: &self, } } /// Executes the given `Statement` /// /// Parameter can be anything that implements `Into<Statement>`, `&str` or `Statement` itself pub fn exec<S: Into<Statement>>(&self, statement: S) -> Result<CypherResult, GraphError> { let mut query = self.query(); query.add_statement(statement); let mut results = try!(query.send()); match results.pop() { Some(result) => Ok(result), None => Err(GraphError::new("No results returned from server")), } } /// Creates a new `Transaction` pub fn transaction(&self) -> Transaction<self::transaction::Created> { Transaction::new(&self.endpoint.to_string(), &self.headers) } } /// Represents a cypher query /// /// A cypher query is composed by statements, each one containing the query itself and its parameters. /// /// The query parameters must implement `Serialize` so they can be serialized into JSON in order to /// be sent to the server pub struct CypherQuery<'a> { statements: Vec<Statement>, cypher: &'a Cypher, } impl<'a> CypherQuery<'a> { /// Adds statements in builder style pub fn with_statement<T: Into<Statement>>(mut self, statement: T) -> Self { self.add_statement(statement); self } pub fn add_statement<T: Into<Statement>>(&mut self, statement: T) { self.statements.push(statement.into()); } pub fn statements(&self) -> &Vec<Statement> { &self.statements } pub fn set_statements(&mut self, statements: Vec<Statement>) { self.statements = statements; } /// Sends the query to the server /// /// The statements contained in the query are sent to the server and the results are parsed /// into a `Vec<CypherResult>` in order to match the response of the neo4j api. pub fn send(self) -> Result<Vec<CypherResult>, GraphError> { let client = self.cypher.client(); let endpoint = format!("{}/{}", self.cypher.endpoint(), "commit"); let headers = self.cypher.headers(); let mut res = try!(send_query(client, &endpoint, headers, self.statements)); let result: QueryResult = try!(parse_response(&mut res)); if result.errors().len() > 0 { return Err(GraphError::new_neo4j_error(result.errors().clone())) } Ok(result.results) } } #[cfg(test)] mod tests { use super::*; use ::cypher::result::Row; fn get_cypher() -> Cypher { use hyper::Url; use hyper::header::{Authorization, Basic, ContentType, Headers}; let cypher_endpoint = Url::parse("http://localhost:7474/db/data/transaction").unwrap(); let mut headers = Headers::new(); headers.set(Authorization( Basic { username: "neo4j".to_owned(), password: Some("neo4j".to_owned()), } )); headers.set(ContentType::json()); Cypher::new(cypher_endpoint, headers) } #[test] fn query_without_params() { let result = get_cypher().exec("MATCH (n:TEST_CYPHER) RETURN n").unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_string_param() { let statement = Statement::new("MATCH (n:TEST_CYPHER {name: {name}}) RETURN n") .with_param("name", "Neo"); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_int_param() { let statement = Statement::new("MATCH (n:TEST_CYPHER {value: {value}}) RETURN n") .with_param("value", 42); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_complex_param() { #[cfg(not(feature = "rustc-serialize"))] mod inner { #[derive(Serialize, Deserialize)] pub struct ComplexType { pub name: String, pub value: i32, } } #[cfg(feature = "rustc-serialize")] mod inner { #[derive(RustcEncodable, RustcDecodable)] pub struct ComplexType { pub name: String, pub value: i32, } } let cypher = get_cypher(); let complex_param = inner::ComplexType { name: "Complex".to_owned(), value: 42, }; let statement = Statement::new("CREATE (n:TEST_CYPHER_COMPLEX_PARAM {p})") .with_param("p", &complex_param); let result = cypher.exec(statement); assert!(result.is_ok()); let results = cypher.exec("MATCH (n:TEST_CYPHER_COMPLEX_PARAM) RETURN n").unwrap(); let rows: Vec<Row> = results.rows().take(1).collect(); let row = rows.first().unwrap(); let complex_result: inner::ComplexType = row.get("n").unwrap(); assert_eq!(complex_result.name, "Complex"); assert_eq!(complex_result.value, 42); cypher.exec("MATCH (n:TEST_CYPHER_COMPLEX_PARAM) DELETE n").unwrap(); } #[test] fn query_with_multiple_params() { let statement = Statement::new( "MATCH (n:TEST_CYPHER {name: {name}}) WHERE n.value = {value} RETURN n") .with_param("name", "Neo") .with_param("value", 42); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn multiple_queries()
}
{ let cypher = get_cypher(); let statement1 = Statement::new("MATCH (n:TEST_CYPHER) RETURN n"); let statement2 = Statement::new("MATCH (n:TEST_CYPHER) RETURN n"); let query = cypher.query() .with_statement(statement1) .with_statement(statement2); let results = query.send().unwrap(); assert_eq!(results.len(), 2); }
identifier_body
mod.rs
//! Provides structs used to interact with the cypher transaction endpoint //! //! The types declared in this module, save for `Statement`, don't need to be instantiated //! directly, since they can be obtained from the `GraphClient`. //! //! # Examples //! //! ## Execute a single query //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! let graph = GraphClient::connect(URL).unwrap(); //! //! graph.cypher().exec("CREATE (n:CYPHER_QUERY {value: 1})").unwrap(); //! let result = graph.cypher().exec("MATCH (n:CYPHER_QUERY) RETURN n.value AS value").unwrap(); //! # assert_eq!(result.data.len(), 1); //! //! // Iterate over the results //! for row in result.rows() { //! let value = row.get::<i32>("value").unwrap(); // or: let value: i32 = row.get("value"); //! assert_eq!(value, 1); //! } //! # graph.cypher().exec("MATCH (n:CYPHER_QUERY) delete n"); //! ``` //! //! ## Execute multiple queries //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! # let graph = GraphClient::connect(URL).unwrap(); //! let mut query = graph.cypher().query() //! .with_statement("MATCH (n:SOME_CYPHER_QUERY) RETURN n.value as value") //! .with_statement("MATCH (n:OTHER_CYPHER_QUERY) RETURN n"); //! //! let results = query.send().unwrap(); //! //! for row in results[0].rows() { //! let value: i32 = row.get("value").unwrap(); //! assert_eq!(value, 1); //! } //! ``` //! //! ## Start a transaction //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! # let graph = GraphClient::connect(URL).unwrap(); //! let (transaction, results) = graph.cypher().transaction() //! .with_statement("MATCH (n:TRANSACTION_CYPHER_QUERY) RETURN n") //! .begin().unwrap(); //! //! # assert_eq!(results.len(), 1); //! ``` pub mod transaction; pub mod statement; pub mod result; pub use self::statement::Statement; pub use self::transaction::Transaction; pub use self::result::CypherResult; use std::convert::Into; use std::collections::BTreeMap; use hyper::client::{Client, Response}; use hyper::header::Headers; use url::Url; use serde::Deserialize; use serde_json::{self, Value}; use serde_json::de as json_de; use serde_json::ser as json_ser; use serde_json::value as json_value; use self::result::{QueryResult, ResultTrait}; use ::error::GraphError; #[cfg(feature = "rustc-serialize")] fn check_param_errors_for_rustc_serialize(statements: &Vec<Statement>) -> Result<(), GraphError> { for stmt in statements.iter() { if stmt.has_param_errors() { let entry = stmt.param_errors().iter().nth(1).unwrap(); return Err(GraphError::new( &format!("Error at parameter '{}' of query '{}': {}", entry.0, stmt.statement(), entry.1) )); } } Ok(()) } #[cfg(not(feature = "rustc-serialize"))] fn check_param_errors_for_rustc_serialize(_: &Vec<Statement>) -> Result<(), GraphError> { Ok(()) } fn
(client: &Client, endpoint: &str, headers: &Headers, statements: Vec<Statement>) -> Result<Response, GraphError> { if cfg!(feature = "rustc-serialize") { try!(check_param_errors_for_rustc_serialize(&statements)); } let mut json = BTreeMap::new(); json.insert("statements", statements); let json = match serde_json::to_string(&json) { Ok(json) => json, Err(e) => { error!("Unable to serialize request: {}", e); return Err(GraphError::new_error(Box::new(e))); } }; let req = client.post(endpoint) .headers(headers.clone()) .body(&json); debug!("Seding query:\n{}", json_ser::to_string_pretty(&json).unwrap_or(String::new())); let res = try!(req.send()); Ok(res) } fn parse_response<T: Deserialize + ResultTrait>(res: &mut Response) -> Result<T, GraphError> { let value = json_de::from_reader(res); let result = match value.and_then(|v: Value| json_value::from_value::<T>(v.clone())) { Ok(result) => result, Err(e) => { error!("Unable to parse response: {}", e); return Err(GraphError::new_error(Box::new(e))); } }; if result.errors().len() > 0 { return Err(GraphError::new_neo4j_error(result.errors().clone())); } Ok(result) } /// Represents the cypher endpoint of a neo4j server /// /// The `Cypher` struct holds information about the cypher enpoint. It is used to create the queries /// that are sent to the server. pub struct Cypher { endpoint: Url, client: Client, headers: Headers, } impl Cypher { /// Creates a new Cypher /// /// Its arguments are the cypher transaction endpoint and the HTTP headers containing HTTP /// Basic Authentication, if needed. pub fn new(endpoint: Url, headers: Headers) -> Self { Cypher { endpoint: endpoint, client: Client::new(), headers: headers, } } fn endpoint(&self) -> &Url { &self.endpoint } fn client(&self) -> &Client { &self.client } fn headers(&self) -> &Headers { &self.headers } /// Creates a new `CypherQuery` pub fn query(&self) -> CypherQuery { CypherQuery { statements: Vec::new(), cypher: &self, } } /// Executes the given `Statement` /// /// Parameter can be anything that implements `Into<Statement>`, `&str` or `Statement` itself pub fn exec<S: Into<Statement>>(&self, statement: S) -> Result<CypherResult, GraphError> { let mut query = self.query(); query.add_statement(statement); let mut results = try!(query.send()); match results.pop() { Some(result) => Ok(result), None => Err(GraphError::new("No results returned from server")), } } /// Creates a new `Transaction` pub fn transaction(&self) -> Transaction<self::transaction::Created> { Transaction::new(&self.endpoint.to_string(), &self.headers) } } /// Represents a cypher query /// /// A cypher query is composed by statements, each one containing the query itself and its parameters. /// /// The query parameters must implement `Serialize` so they can be serialized into JSON in order to /// be sent to the server pub struct CypherQuery<'a> { statements: Vec<Statement>, cypher: &'a Cypher, } impl<'a> CypherQuery<'a> { /// Adds statements in builder style pub fn with_statement<T: Into<Statement>>(mut self, statement: T) -> Self { self.add_statement(statement); self } pub fn add_statement<T: Into<Statement>>(&mut self, statement: T) { self.statements.push(statement.into()); } pub fn statements(&self) -> &Vec<Statement> { &self.statements } pub fn set_statements(&mut self, statements: Vec<Statement>) { self.statements = statements; } /// Sends the query to the server /// /// The statements contained in the query are sent to the server and the results are parsed /// into a `Vec<CypherResult>` in order to match the response of the neo4j api. pub fn send(self) -> Result<Vec<CypherResult>, GraphError> { let client = self.cypher.client(); let endpoint = format!("{}/{}", self.cypher.endpoint(), "commit"); let headers = self.cypher.headers(); let mut res = try!(send_query(client, &endpoint, headers, self.statements)); let result: QueryResult = try!(parse_response(&mut res)); if result.errors().len() > 0 { return Err(GraphError::new_neo4j_error(result.errors().clone())) } Ok(result.results) } } #[cfg(test)] mod tests { use super::*; use ::cypher::result::Row; fn get_cypher() -> Cypher { use hyper::Url; use hyper::header::{Authorization, Basic, ContentType, Headers}; let cypher_endpoint = Url::parse("http://localhost:7474/db/data/transaction").unwrap(); let mut headers = Headers::new(); headers.set(Authorization( Basic { username: "neo4j".to_owned(), password: Some("neo4j".to_owned()), } )); headers.set(ContentType::json()); Cypher::new(cypher_endpoint, headers) } #[test] fn query_without_params() { let result = get_cypher().exec("MATCH (n:TEST_CYPHER) RETURN n").unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_string_param() { let statement = Statement::new("MATCH (n:TEST_CYPHER {name: {name}}) RETURN n") .with_param("name", "Neo"); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_int_param() { let statement = Statement::new("MATCH (n:TEST_CYPHER {value: {value}}) RETURN n") .with_param("value", 42); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_complex_param() { #[cfg(not(feature = "rustc-serialize"))] mod inner { #[derive(Serialize, Deserialize)] pub struct ComplexType { pub name: String, pub value: i32, } } #[cfg(feature = "rustc-serialize")] mod inner { #[derive(RustcEncodable, RustcDecodable)] pub struct ComplexType { pub name: String, pub value: i32, } } let cypher = get_cypher(); let complex_param = inner::ComplexType { name: "Complex".to_owned(), value: 42, }; let statement = Statement::new("CREATE (n:TEST_CYPHER_COMPLEX_PARAM {p})") .with_param("p", &complex_param); let result = cypher.exec(statement); assert!(result.is_ok()); let results = cypher.exec("MATCH (n:TEST_CYPHER_COMPLEX_PARAM) RETURN n").unwrap(); let rows: Vec<Row> = results.rows().take(1).collect(); let row = rows.first().unwrap(); let complex_result: inner::ComplexType = row.get("n").unwrap(); assert_eq!(complex_result.name, "Complex"); assert_eq!(complex_result.value, 42); cypher.exec("MATCH (n:TEST_CYPHER_COMPLEX_PARAM) DELETE n").unwrap(); } #[test] fn query_with_multiple_params() { let statement = Statement::new( "MATCH (n:TEST_CYPHER {name: {name}}) WHERE n.value = {value} RETURN n") .with_param("name", "Neo") .with_param("value", 42); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn multiple_queries() { let cypher = get_cypher(); let statement1 = Statement::new("MATCH (n:TEST_CYPHER) RETURN n"); let statement2 = Statement::new("MATCH (n:TEST_CYPHER) RETURN n"); let query = cypher.query() .with_statement(statement1) .with_statement(statement2); let results = query.send().unwrap(); assert_eq!(results.len(), 2); } }
send_query
identifier_name
text.rs
//! This protocol is used to handle input and output of //! text-based information intended for the system user during the operation of code in the boot //! services environment. Also included here are the definitions of three console devices: one for input //! and one each for normal output and errors. use core::fmt; use crate::{ status::{Error, Status, Warning}, system::SystemTable, Event, }; /// Keystroke information for the key that was pressed. #[derive(Clone, Copy, Debug, Default)] #[repr(C)] pub struct TextInputKey { /// If there is a pending keystroke, then ScanCode is the EFI scan code defined in /// Table 104. pub ScanCode: u16, /// The UnicodeChar is the actual printable /// character or is zero if the key does not represent a printable /// character (control key, function key, etc.). pub UnicodeChar: u16, } /// This protocol is used to obtain input from the ConsoleIn device. The EFI specification requires that /// the EFI_SIMPLE_TEXT_INPUT_PROTOCOL supports the same languages as the corresponding /// EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL. #[repr(C)] pub struct TextInput { /// Reset the ConsoleIn device. pub Reset: extern "win64" fn(&TextInput, bool) -> Status, /// Returns the next input character. pub ReadKeyStroke: extern "win64" fn(&TextInput, &mut TextInputKey) -> Status, /// Event to use with EFI_BOOT_SERVICES.WaitForEvent() to wait for a key to be available. pub WaitForKey: Event, } impl TextInput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Returns the next input character, if it exists. pub fn try_read_key_stroke(&self) -> Result<TextInputKey, Error> { let mut key = TextInputKey::default(); (self.ReadKeyStroke)(self, &mut key)?; Ok(key) } /// Returns the next input character after waiting for it. pub fn read_key_stroke( &self, system_table: &'static SystemTable, ) -> Result<TextInputKey, Error> { system_table.BootServices.wait_for_event(&self.WaitForKey)?; self.try_read_key_stroke() } } /// The following data values in the SIMPLE_TEXT_OUTPUT_MODE interface are read-only and are /// changed by using the appropriate interface functions. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct TextOutputMode { /// The number of modes supported by QueryMode() and SetMode(). pub MaxMode: i32, /// The text mode of the output device(s). pub Mode: i32, /// The current character output attribute. pub Attribute: i32, /// The cursor’s column. pub CursorColumn: i32, /// The cursor’s row. pub CursorRow: i32, /// The cursor is currently visible or not. pub CursorVisible: bool, } /// This protocol is used to control text-based output devices. #[repr(C)] pub struct TextOutput { /// Reset the ConsoleOut device. pub Reset: extern "win64" fn(&TextOutput, bool) -> Status, /// Displays the string on the device at the current cursor location. pub OutputString: extern "win64" fn(&TextOutput, *const u16) -> Status, /// Tests to see if the ConsoleOut device supports this string. pub TestString: extern "win64" fn(&TextOutput, *const u16) -> Status, /// Queries information concerning the output device’s supported text mode. pub QueryMode: extern "win64" fn(&TextOutput, usize, &mut usize, &mut usize) -> Status, /// Sets the current mode of the output device. pub SetMode: extern "win64" fn(&TextOutput, usize) -> Status, /// Sets the foreground and background color of the text that is output. pub SetAttribute: extern "win64" fn(&TextOutput, usize) -> Status, /// Clears the screen with the currently set background color. pub ClearScreen: extern "win64" fn(&TextOutput) -> Status, /// Sets the current cursor position. pub SetCursorPosition: extern "win64" fn(&TextOutput, usize, usize) -> Status, /// Turns the visibility of the cursor on/off. pub EnableCursor: extern "win64" fn(&TextOutput, bool) -> Status, /// Reference to SIMPLE_TEXT_OUTPUT_MODE data. pub Mode: &'static TextOutputMode, } impl TextOutput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Displays the string on the device at the current cursor location. pub fn output_string(&self, string: &str) -> Result<Warning, Error> { with_utf16_str(string, |utf16| (self.OutputString)(self, utf16)) } /// Tests to see if the ConsoleOut device supports this string. pub fn test_string(&self, string: &str) -> Result<(), Error> { with_utf16_str(string, |utf16| (self.TestString)(self, utf16))?; Ok(()) } /// Queries information concerning the output device’s supported text mode. /// /// Returns the number of columns and rows, if successful. pub fn query_mode(&self, mode_number: usize) -> Result<(usize, usize), Error> { let mut columns: usize = 0; let mut rows: usize = 0; (self.QueryMode)(self, mode_number, &mut columns, &mut rows)?; Ok((columns, rows)) } /// Sets the current mode of the output device. pub fn set_mode(&self, mode: usize) -> Result<(), Error> { (self.SetMode)(self, mode)?; Ok(()) } /// Sets the foreground and background color of the text that is output. pub fn set_attribute(&self, attribute: Color) -> Result<(), Error> { (self.SetAttribute)(self, attribute.0)?; Ok(()) } /// Clears the screen with the currently set background color. pub fn clear_screen(&self) -> Result<(), Error> { (self.ClearScreen)(self)?; Ok(()) } /// Sets the current cursor position. pub fn set_cursor_position(&self, column: usize, row: usize) -> Result<(), Error> { (self.SetCursorPosition)(self, column, row)?; Ok(()) } /// Turns the visibility of the cursor on/off. pub fn enable_cursor(&self, enable: bool) -> Result<(), Error> { (self.EnableCursor)(self, enable)?; Ok(()) } } impl<'a> fmt::Write for &'a TextOutput { fn write_str(&mut self, s: &str) -> fmt::Result { self.output_string(s).map_err(|_| fmt::Error).map(|_| ()) } } /// Executes the given function with the UTF16-encoded string. /// /// `function` will get a UTF16-encoded null-terminated string as its argument when its called. /// /// `function` may be called multiple times. This is because the string is converted /// to UTF16 in a fixed size buffer to avoid allocations. As a consequence, any string /// longer than the buffer needs the function to be called multiple times. fn with_utf16_str<FunctionType>(string: &str, function: FunctionType) -> Result<Warning, Error> where FunctionType: Fn(*const u16) -> Status, { const BUFFER_SIZE: usize = 256; let mut buffer = [0u16; BUFFER_SIZE]; let mut current_index = 0; let warning = Warning::Success; // Flushes the buffer let flush_buffer = |ref mut buffer: &mut [u16; BUFFER_SIZE], ref mut current_index, ref mut warning| -> Result<(), Error> { buffer[*current_index] = 0; *current_index = 0; if *warning == Warning::Success { *warning = function(buffer.as_ptr())?; } else { function(buffer.as_ptr())?; } Ok(()) }; for character in string.chars() { // If there is not enough space in the buffer, flush it if current_index + character.len_utf16() + 1 >= BUFFER_SIZE { flush_buffer(&mut buffer, current_index, warning)?; } character.encode_utf16(&mut buffer[current_index..]); current_index += character.len_utf16(); } flush_buffer(&mut buffer, current_index, warning)?; Ok(warning) } /// Represents color information for text. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct Color(usize); impl Color { /// Creates new color information from the foreground and background color. pub const fn new(foreground: ForegroundColor, background: BackgroundColor) -> Color { Color(foreground as usize | background as usize) } } /// Represents a foreground color for text. #[derive(Clone, Copy, Debug)] #[repr(usize)] pub enum Foregrou
// Represents the foreground color black. Black = 0x00, /// Represents the foreground color blue. Blue = 0x01, /// Represents the foreground color green. Green = 0x02, /// Represents the foreground color cyan. Cyan = 0x03, /// Represents the foreground color red. Red = 0x04, /// Represents the foreground color magenta. Magenta = 0x05, /// Represents the foreground color brown. Brown = 0x06, /// Represents the foreground color light gray. LightGray = 0x07, /// Represents the foreground color dark gray. DarkGray = 0x08, /// Represents the foreground color light blue. LightBlue = 0x09, /// Represents the foreground color light green. LightGreen = 0x0a, /// Represents the foreground color light cyan. LightCyan = 0x0b, /// Represents the foreground color light red. LightRed = 0x0c, /// Represents the foreground color light magenta. LightMagenta = 0x0d, /// Represents the foreground color yellow. Yellow = 0x0e, /// Represents the foreground color white. White = 0x0f, } /// Represents a background color for text. #[derive(Clone, Copy, Debug)] #[repr(usize)] pub enum BackgroundColor { /// Represents the background color black. Black = 0x00, /// Represents the background color blue. Blue = 0x10, /// Represents the background color green. Green = 0x20, /// Represents the background color cyan. Cyan = 0x30, /// Represents the background color red. Red = 0x40, /// Represents the background color magenta. Magenta = 0x50, /// Represents the background color brown. Brown = 0x60, /// Represents the background color light gray. LightGray = 0x70, }
ndColor { /
identifier_name
text.rs
//! This protocol is used to handle input and output of //! text-based information intended for the system user during the operation of code in the boot //! services environment. Also included here are the definitions of three console devices: one for input //! and one each for normal output and errors. use core::fmt; use crate::{ status::{Error, Status, Warning}, system::SystemTable, Event, }; /// Keystroke information for the key that was pressed. #[derive(Clone, Copy, Debug, Default)] #[repr(C)] pub struct TextInputKey { /// If there is a pending keystroke, then ScanCode is the EFI scan code defined in /// Table 104. pub ScanCode: u16, /// The UnicodeChar is the actual printable /// character or is zero if the key does not represent a printable /// character (control key, function key, etc.). pub UnicodeChar: u16, } /// This protocol is used to obtain input from the ConsoleIn device. The EFI specification requires that /// the EFI_SIMPLE_TEXT_INPUT_PROTOCOL supports the same languages as the corresponding /// EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL. #[repr(C)] pub struct TextInput { /// Reset the ConsoleIn device. pub Reset: extern "win64" fn(&TextInput, bool) -> Status, /// Returns the next input character. pub ReadKeyStroke: extern "win64" fn(&TextInput, &mut TextInputKey) -> Status, /// Event to use with EFI_BOOT_SERVICES.WaitForEvent() to wait for a key to be available. pub WaitForKey: Event, } impl TextInput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Returns the next input character, if it exists. pub fn try_read_key_stroke(&self) -> Result<TextInputKey, Error> { let mut key = TextInputKey::default(); (self.ReadKeyStroke)(self, &mut key)?; Ok(key) } /// Returns the next input character after waiting for it. pub fn read_key_stroke( &self, system_table: &'static SystemTable, ) -> Result<TextInputKey, Error> { system_table.BootServices.wait_for_event(&self.WaitForKey)?; self.try_read_key_stroke() } } /// The following data values in the SIMPLE_TEXT_OUTPUT_MODE interface are read-only and are /// changed by using the appropriate interface functions. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct TextOutputMode { /// The number of modes supported by QueryMode() and SetMode(). pub MaxMode: i32, /// The text mode of the output device(s). pub Mode: i32, /// The current character output attribute. pub Attribute: i32, /// The cursor’s column. pub CursorColumn: i32, /// The cursor’s row. pub CursorRow: i32, /// The cursor is currently visible or not. pub CursorVisible: bool, } /// This protocol is used to control text-based output devices. #[repr(C)] pub struct TextOutput { /// Reset the ConsoleOut device. pub Reset: extern "win64" fn(&TextOutput, bool) -> Status, /// Displays the string on the device at the current cursor location. pub OutputString: extern "win64" fn(&TextOutput, *const u16) -> Status, /// Tests to see if the ConsoleOut device supports this string. pub TestString: extern "win64" fn(&TextOutput, *const u16) -> Status, /// Queries information concerning the output device’s supported text mode. pub QueryMode: extern "win64" fn(&TextOutput, usize, &mut usize, &mut usize) -> Status, /// Sets the current mode of the output device. pub SetMode: extern "win64" fn(&TextOutput, usize) -> Status, /// Sets the foreground and background color of the text that is output. pub SetAttribute: extern "win64" fn(&TextOutput, usize) -> Status, /// Clears the screen with the currently set background color. pub ClearScreen: extern "win64" fn(&TextOutput) -> Status, /// Sets the current cursor position. pub SetCursorPosition: extern "win64" fn(&TextOutput, usize, usize) -> Status, /// Turns the visibility of the cursor on/off. pub EnableCursor: extern "win64" fn(&TextOutput, bool) -> Status, /// Reference to SIMPLE_TEXT_OUTPUT_MODE data. pub Mode: &'static TextOutputMode, } impl TextOutput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Displays the string on the device at the current cursor location. pub fn output_string(&self, string: &str) -> Result<Warning, Error> { with_utf16_str(string, |utf16| (self.OutputString)(self, utf16)) } /// Tests to see if the ConsoleOut device supports this string. pub fn test_string(&self, string: &str) -> Result<(), Error> { with_utf16_str(string, |utf16| (self.TestString)(self, utf16))?; Ok(()) } /// Queries information concerning the output device’s supported text mode. /// /// Returns the number of columns and rows, if successful. pub fn query_mode(&self, mode_number: usize) -> Result<(usize, usize), Error> { let mut columns: usize = 0; let mut rows: usize = 0; (self.QueryMode)(self, mode_number, &mut columns, &mut rows)?; Ok((columns, rows)) } /// Sets the current mode of the output device. pub fn set_mode(&self, mode: usize) -> Result<(), Error> { (self.SetMode)(self, mode)?; Ok(()) } /// Sets the foreground and background color of the text that is output. pub fn set_attribute(&self, attribute: Color) -> Result<(), Error> { (self.SetAttribute)(self, attribute.0)?; Ok(()) } /// Clears the screen with the currently set background color. pub fn clear_screen(&self) -> Result<(), Error> { (self.ClearScreen)(self)?; Ok(()) } /// Sets the current cursor position. pub fn set_cursor_position(&self, column: usize, row: usize) -> Result<(), Error> { (self.SetCursorPosition)(self, column, row)?; Ok(()) } /// Turns the visibility of the cursor on/off. pub fn enable_cursor(&self, enable: bool) -> Result<(), Error> { (self.EnableCursor)(self, enable)?; Ok(()) } } impl<'a> fmt::Write for &'a TextOutput { fn write_str(&mut self, s: &str) -> fmt::Result {
Executes the given function with the UTF16-encoded string. /// /// `function` will get a UTF16-encoded null-terminated string as its argument when its called. /// /// `function` may be called multiple times. This is because the string is converted /// to UTF16 in a fixed size buffer to avoid allocations. As a consequence, any string /// longer than the buffer needs the function to be called multiple times. fn with_utf16_str<FunctionType>(string: &str, function: FunctionType) -> Result<Warning, Error> where FunctionType: Fn(*const u16) -> Status, { const BUFFER_SIZE: usize = 256; let mut buffer = [0u16; BUFFER_SIZE]; let mut current_index = 0; let warning = Warning::Success; // Flushes the buffer let flush_buffer = |ref mut buffer: &mut [u16; BUFFER_SIZE], ref mut current_index, ref mut warning| -> Result<(), Error> { buffer[*current_index] = 0; *current_index = 0; if *warning == Warning::Success { *warning = function(buffer.as_ptr())?; } else { function(buffer.as_ptr())?; } Ok(()) }; for character in string.chars() { // If there is not enough space in the buffer, flush it if current_index + character.len_utf16() + 1 >= BUFFER_SIZE { flush_buffer(&mut buffer, current_index, warning)?; } character.encode_utf16(&mut buffer[current_index..]); current_index += character.len_utf16(); } flush_buffer(&mut buffer, current_index, warning)?; Ok(warning) } /// Represents color information for text. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct Color(usize); impl Color { /// Creates new color information from the foreground and background color. pub const fn new(foreground: ForegroundColor, background: BackgroundColor) -> Color { Color(foreground as usize | background as usize) } } /// Represents a foreground color for text. #[derive(Clone, Copy, Debug)] #[repr(usize)] pub enum ForegroundColor { /// Represents the foreground color black. Black = 0x00, /// Represents the foreground color blue. Blue = 0x01, /// Represents the foreground color green. Green = 0x02, /// Represents the foreground color cyan. Cyan = 0x03, /// Represents the foreground color red. Red = 0x04, /// Represents the foreground color magenta. Magenta = 0x05, /// Represents the foreground color brown. Brown = 0x06, /// Represents the foreground color light gray. LightGray = 0x07, /// Represents the foreground color dark gray. DarkGray = 0x08, /// Represents the foreground color light blue. LightBlue = 0x09, /// Represents the foreground color light green. LightGreen = 0x0a, /// Represents the foreground color light cyan. LightCyan = 0x0b, /// Represents the foreground color light red. LightRed = 0x0c, /// Represents the foreground color light magenta. LightMagenta = 0x0d, /// Represents the foreground color yellow. Yellow = 0x0e, /// Represents the foreground color white. White = 0x0f, } /// Represents a background color for text. #[derive(Clone, Copy, Debug)] #[repr(usize)] pub enum BackgroundColor { /// Represents the background color black. Black = 0x00, /// Represents the background color blue. Blue = 0x10, /// Represents the background color green. Green = 0x20, /// Represents the background color cyan. Cyan = 0x30, /// Represents the background color red. Red = 0x40, /// Represents the background color magenta. Magenta = 0x50, /// Represents the background color brown. Brown = 0x60, /// Represents the background color light gray. LightGray = 0x70, }
self.output_string(s).map_err(|_| fmt::Error).map(|_| ()) } } ///
identifier_body
text.rs
//! This protocol is used to handle input and output of //! text-based information intended for the system user during the operation of code in the boot //! services environment. Also included here are the definitions of three console devices: one for input //! and one each for normal output and errors. use core::fmt; use crate::{ status::{Error, Status, Warning}, system::SystemTable, Event, }; /// Keystroke information for the key that was pressed. #[derive(Clone, Copy, Debug, Default)] #[repr(C)] pub struct TextInputKey { /// If there is a pending keystroke, then ScanCode is the EFI scan code defined in /// Table 104. pub ScanCode: u16, /// The UnicodeChar is the actual printable /// character or is zero if the key does not represent a printable /// character (control key, function key, etc.). pub UnicodeChar: u16, } /// This protocol is used to obtain input from the ConsoleIn device. The EFI specification requires that /// the EFI_SIMPLE_TEXT_INPUT_PROTOCOL supports the same languages as the corresponding /// EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL. #[repr(C)] pub struct TextInput { /// Reset the ConsoleIn device. pub Reset: extern "win64" fn(&TextInput, bool) -> Status, /// Returns the next input character. pub ReadKeyStroke: extern "win64" fn(&TextInput, &mut TextInputKey) -> Status, /// Event to use with EFI_BOOT_SERVICES.WaitForEvent() to wait for a key to be available. pub WaitForKey: Event, } impl TextInput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Returns the next input character, if it exists. pub fn try_read_key_stroke(&self) -> Result<TextInputKey, Error> { let mut key = TextInputKey::default(); (self.ReadKeyStroke)(self, &mut key)?; Ok(key) } /// Returns the next input character after waiting for it. pub fn read_key_stroke( &self, system_table: &'static SystemTable, ) -> Result<TextInputKey, Error> { system_table.BootServices.wait_for_event(&self.WaitForKey)?; self.try_read_key_stroke() } } /// The following data values in the SIMPLE_TEXT_OUTPUT_MODE interface are read-only and are /// changed by using the appropriate interface functions. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct TextOutputMode { /// The number of modes supported by QueryMode() and SetMode(). pub MaxMode: i32, /// The text mode of the output device(s). pub Mode: i32, /// The current character output attribute. pub Attribute: i32, /// The cursor’s column. pub CursorColumn: i32, /// The cursor’s row. pub CursorRow: i32, /// The cursor is currently visible or not. pub CursorVisible: bool, } /// This protocol is used to control text-based output devices. #[repr(C)] pub struct TextOutput { /// Reset the ConsoleOut device. pub Reset: extern "win64" fn(&TextOutput, bool) -> Status, /// Displays the string on the device at the current cursor location. pub OutputString: extern "win64" fn(&TextOutput, *const u16) -> Status, /// Tests to see if the ConsoleOut device supports this string. pub TestString: extern "win64" fn(&TextOutput, *const u16) -> Status, /// Queries information concerning the output device’s supported text mode. pub QueryMode: extern "win64" fn(&TextOutput, usize, &mut usize, &mut usize) -> Status, /// Sets the current mode of the output device. pub SetMode: extern "win64" fn(&TextOutput, usize) -> Status, /// Sets the foreground and background color of the text that is output. pub SetAttribute: extern "win64" fn(&TextOutput, usize) -> Status, /// Clears the screen with the currently set background color. pub ClearScreen: extern "win64" fn(&TextOutput) -> Status, /// Sets the current cursor position. pub SetCursorPosition: extern "win64" fn(&TextOutput, usize, usize) -> Status, /// Turns the visibility of the cursor on/off. pub EnableCursor: extern "win64" fn(&TextOutput, bool) -> Status, /// Reference to SIMPLE_TEXT_OUTPUT_MODE data. pub Mode: &'static TextOutputMode, } impl TextOutput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Displays the string on the device at the current cursor location. pub fn output_string(&self, string: &str) -> Result<Warning, Error> { with_utf16_str(string, |utf16| (self.OutputString)(self, utf16)) } /// Tests to see if the ConsoleOut device supports this string. pub fn test_string(&self, string: &str) -> Result<(), Error> { with_utf16_str(string, |utf16| (self.TestString)(self, utf16))?; Ok(()) } /// Queries information concerning the output device’s supported text mode. /// /// Returns the number of columns and rows, if successful. pub fn query_mode(&self, mode_number: usize) -> Result<(usize, usize), Error> { let mut columns: usize = 0; let mut rows: usize = 0; (self.QueryMode)(self, mode_number, &mut columns, &mut rows)?; Ok((columns, rows)) } /// Sets the current mode of the output device. pub fn set_mode(&self, mode: usize) -> Result<(), Error> { (self.SetMode)(self, mode)?; Ok(()) } /// Sets the foreground and background color of the text that is output. pub fn set_attribute(&self, attribute: Color) -> Result<(), Error> { (self.SetAttribute)(self, attribute.0)?; Ok(()) } /// Clears the screen with the currently set background color. pub fn clear_screen(&self) -> Result<(), Error> { (self.ClearScreen)(self)?; Ok(()) } /// Sets the current cursor position. pub fn set_cursor_position(&self, column: usize, row: usize) -> Result<(), Error> { (self.SetCursorPosition)(self, column, row)?; Ok(()) } /// Turns the visibility of the cursor on/off. pub fn enable_cursor(&self, enable: bool) -> Result<(), Error> { (self.EnableCursor)(self, enable)?; Ok(()) } } impl<'a> fmt::Write for &'a TextOutput { fn write_str(&mut self, s: &str) -> fmt::Result { self.output_string(s).map_err(|_| fmt::Error).map(|_| ()) } } /// Executes the given function with the UTF16-encoded string. /// /// `function` will get a UTF16-encoded null-terminated string as its argument when its called. /// /// `function` may be called multiple times. This is because the string is converted /// to UTF16 in a fixed size buffer to avoid allocations. As a consequence, any string /// longer than the buffer needs the function to be called multiple times. fn with_utf16_str<FunctionType>(string: &str, function: FunctionType) -> Result<Warning, Error> where FunctionType: Fn(*const u16) -> Status, { const BUFFER_SIZE: usize = 256; let mut buffer = [0u16; BUFFER_SIZE]; let mut current_index = 0; let warning = Warning::Success; // Flushes the buffer let flush_buffer = |ref mut buffer: &mut [u16; BUFFER_SIZE], ref mut current_index, ref mut warning| -> Result<(), Error> { buffer[*current_index] = 0; *current_index = 0; if *warning == Warning::Success { *warning = function(buffer.as_ptr())?; } else { function(buffer.as_ptr())?; } Ok(()) }; for character in string.chars() { // If there is not enough space in the buffer, flush it if current_index + character.len_utf16() + 1 >= BUFFER_SIZE { flush_buffer(&mut buffer, current_index, warning)?; } character.encode_utf16(&mut buffer[current_index..]); current_index += character.len_utf16(); } flush_buffer(&mut buffer, current_index, warning)?; Ok(warning) } /// Represents color information for text. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct Color(usize); impl Color { /// Creates new color information from the foreground and background color. pub const fn new(foreground: ForegroundColor, background: BackgroundColor) -> Color { Color(foreground as usize | background as usize) } } /// Represents a foreground color for text. #[derive(Clone, Copy, Debug)] #[repr(usize)] pub enum ForegroundColor { /// Represents the foreground color black. Black = 0x00, /// Represents the foreground color blue. Blue = 0x01, /// Represents the foreground color green. Green = 0x02, /// Represents the foreground color cyan. Cyan = 0x03, /// Represents the foreground color red. Red = 0x04, /// Represents the foreground color magenta. Magenta = 0x05, /// Represents the foreground color brown. Brown = 0x06, /// Represents the foreground color light gray. LightGray = 0x07, /// Represents the foreground color dark gray. DarkGray = 0x08, /// Represents the foreground color light blue. LightBlue = 0x09, /// Represents the foreground color light green. LightGreen = 0x0a, /// Represents the foreground color light cyan. LightCyan = 0x0b, /// Represents the foreground color light red. LightRed = 0x0c, /// Represents the foreground color light magenta. LightMagenta = 0x0d, /// Represents the foreground color yellow. Yellow = 0x0e, /// Represents the foreground color white. White = 0x0f, } /// Represents a background color for text. #[derive(Clone, Copy, Debug)] #[repr(usize)] pub enum BackgroundColor { /// Represents the background color black. Black = 0x00,
/// Represents the background color blue. Blue = 0x10, /// Represents the background color green. Green = 0x20, /// Represents the background color cyan. Cyan = 0x30, /// Represents the background color red. Red = 0x40, /// Represents the background color magenta. Magenta = 0x50, /// Represents the background color brown. Brown = 0x60, /// Represents the background color light gray. LightGray = 0x70, }
random_line_split
text.rs
//! This protocol is used to handle input and output of //! text-based information intended for the system user during the operation of code in the boot //! services environment. Also included here are the definitions of three console devices: one for input //! and one each for normal output and errors. use core::fmt; use crate::{ status::{Error, Status, Warning}, system::SystemTable, Event, }; /// Keystroke information for the key that was pressed. #[derive(Clone, Copy, Debug, Default)] #[repr(C)] pub struct TextInputKey { /// If there is a pending keystroke, then ScanCode is the EFI scan code defined in /// Table 104. pub ScanCode: u16, /// The UnicodeChar is the actual printable /// character or is zero if the key does not represent a printable /// character (control key, function key, etc.). pub UnicodeChar: u16, } /// This protocol is used to obtain input from the ConsoleIn device. The EFI specification requires that /// the EFI_SIMPLE_TEXT_INPUT_PROTOCOL supports the same languages as the corresponding /// EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL. #[repr(C)] pub struct TextInput { /// Reset the ConsoleIn device. pub Reset: extern "win64" fn(&TextInput, bool) -> Status, /// Returns the next input character. pub ReadKeyStroke: extern "win64" fn(&TextInput, &mut TextInputKey) -> Status, /// Event to use with EFI_BOOT_SERVICES.WaitForEvent() to wait for a key to be available. pub WaitForKey: Event, } impl TextInput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Returns the next input character, if it exists. pub fn try_read_key_stroke(&self) -> Result<TextInputKey, Error> { let mut key = TextInputKey::default(); (self.ReadKeyStroke)(self, &mut key)?; Ok(key) } /// Returns the next input character after waiting for it. pub fn read_key_stroke( &self, system_table: &'static SystemTable, ) -> Result<TextInputKey, Error> { system_table.BootServices.wait_for_event(&self.WaitForKey)?; self.try_read_key_stroke() } } /// The following data values in the SIMPLE_TEXT_OUTPUT_MODE interface are read-only and are /// changed by using the appropriate interface functions. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct TextOutputMode { /// The number of modes supported by QueryMode() and SetMode(). pub MaxMode: i32, /// The text mode of the output device(s). pub Mode: i32, /// The current character output attribute. pub Attribute: i32, /// The cursor’s column. pub CursorColumn: i32, /// The cursor’s row. pub CursorRow: i32, /// The cursor is currently visible or not. pub CursorVisible: bool, } /// This protocol is used to control text-based output devices. #[repr(C)] pub struct TextOutput { /// Reset the ConsoleOut device. pub Reset: extern "win64" fn(&TextOutput, bool) -> Status, /// Displays the string on the device at the current cursor location. pub OutputString: extern "win64" fn(&TextOutput, *const u16) -> Status, /// Tests to see if the ConsoleOut device supports this string. pub TestString: extern "win64" fn(&TextOutput, *const u16) -> Status, /// Queries information concerning the output device’s supported text mode. pub QueryMode: extern "win64" fn(&TextOutput, usize, &mut usize, &mut usize) -> Status, /// Sets the current mode of the output device. pub SetMode: extern "win64" fn(&TextOutput, usize) -> Status, /// Sets the foreground and background color of the text that is output. pub SetAttribute: extern "win64" fn(&TextOutput, usize) -> Status, /// Clears the screen with the currently set background color. pub ClearScreen: extern "win64" fn(&TextOutput) -> Status, /// Sets the current cursor position. pub SetCursorPosition: extern "win64" fn(&TextOutput, usize, usize) -> Status, /// Turns the visibility of the cursor on/off. pub EnableCursor: extern "win64" fn(&TextOutput, bool) -> Status, /// Reference to SIMPLE_TEXT_OUTPUT_MODE data. pub Mode: &'static TextOutputMode, } impl TextOutput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Displays the string on the device at the current cursor location. pub fn output_string(&self, string: &str) -> Result<Warning, Error> { with_utf16_str(string, |utf16| (self.OutputString)(self, utf16)) } /// Tests to see if the ConsoleOut device supports this string. pub fn test_string(&self, string: &str) -> Result<(), Error> { with_utf16_str(string, |utf16| (self.TestString)(self, utf16))?; Ok(()) } /// Queries information concerning the output device’s supported text mode. /// /// Returns the number of columns and rows, if successful. pub fn query_mode(&self, mode_number: usize) -> Result<(usize, usize), Error> { let mut columns: usize = 0; let mut rows: usize = 0; (self.QueryMode)(self, mode_number, &mut columns, &mut rows)?; Ok((columns, rows)) } /// Sets the current mode of the output device. pub fn set_mode(&self, mode: usize) -> Result<(), Error> { (self.SetMode)(self, mode)?; Ok(()) } /// Sets the foreground and background color of the text that is output. pub fn set_attribute(&self, attribute: Color) -> Result<(), Error> { (self.SetAttribute)(self, attribute.0)?; Ok(()) } /// Clears the screen with the currently set background color. pub fn clear_screen(&self) -> Result<(), Error> { (self.ClearScreen)(self)?; Ok(()) } /// Sets the current cursor position. pub fn set_cursor_position(&self, column: usize, row: usize) -> Result<(), Error> { (self.SetCursorPosition)(self, column, row)?; Ok(()) } /// Turns the visibility of the cursor on/off. pub fn enable_cursor(&self, enable: bool) -> Result<(), Error> { (self.EnableCursor)(self, enable)?; Ok(()) } } impl<'a> fmt::Write for &'a TextOutput { fn write_str(&mut self, s: &str) -> fmt::Result { self.output_string(s).map_err(|_| fmt::Error).map(|_| ()) } } /// Executes the given function with the UTF16-encoded string. /// /// `function` will get a UTF16-encoded null-terminated string as its argument when its called. /// /// `function` may be called multiple times. This is because the string is converted /// to UTF16 in a fixed size buffer to avoid allocations. As a consequence, any string /// longer than the buffer needs the function to be called multiple times. fn with_utf16_str<FunctionType>(string: &str, function: FunctionType) -> Result<Warning, Error> where FunctionType: Fn(*const u16) -> Status, { const BUFFER_SIZE: usize = 256; let mut buffer = [0u16; BUFFER_SIZE]; let mut current_index = 0; let warning = Warning::Success; // Flushes the buffer let flush_buffer = |ref mut buffer: &mut [u16; BUFFER_SIZE], ref mut current_index, ref mut warning| -> Result<(), Error> { buffer[*current_index] = 0; *current_index = 0; if *warning == Warning::Success {
function(buffer.as_ptr())?; } Ok(()) }; for character in string.chars() { // If there is not enough space in the buffer, flush it if current_index + character.len_utf16() + 1 >= BUFFER_SIZE { flush_buffer(&mut buffer, current_index, warning)?; } character.encode_utf16(&mut buffer[current_index..]); current_index += character.len_utf16(); } flush_buffer(&mut buffer, current_index, warning)?; Ok(warning) } /// Represents color information for text. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct Color(usize); impl Color { /// Creates new color information from the foreground and background color. pub const fn new(foreground: ForegroundColor, background: BackgroundColor) -> Color { Color(foreground as usize | background as usize) } } /// Represents a foreground color for text. #[derive(Clone, Copy, Debug)] #[repr(usize)] pub enum ForegroundColor { /// Represents the foreground color black. Black = 0x00, /// Represents the foreground color blue. Blue = 0x01, /// Represents the foreground color green. Green = 0x02, /// Represents the foreground color cyan. Cyan = 0x03, /// Represents the foreground color red. Red = 0x04, /// Represents the foreground color magenta. Magenta = 0x05, /// Represents the foreground color brown. Brown = 0x06, /// Represents the foreground color light gray. LightGray = 0x07, /// Represents the foreground color dark gray. DarkGray = 0x08, /// Represents the foreground color light blue. LightBlue = 0x09, /// Represents the foreground color light green. LightGreen = 0x0a, /// Represents the foreground color light cyan. LightCyan = 0x0b, /// Represents the foreground color light red. LightRed = 0x0c, /// Represents the foreground color light magenta. LightMagenta = 0x0d, /// Represents the foreground color yellow. Yellow = 0x0e, /// Represents the foreground color white. White = 0x0f, } /// Represents a background color for text. #[derive(Clone, Copy, Debug)] #[repr(usize)] pub enum BackgroundColor { /// Represents the background color black. Black = 0x00, /// Represents the background color blue. Blue = 0x10, /// Represents the background color green. Green = 0x20, /// Represents the background color cyan. Cyan = 0x30, /// Represents the background color red. Red = 0x40, /// Represents the background color magenta. Magenta = 0x50, /// Represents the background color brown. Brown = 0x60, /// Represents the background color light gray. LightGray = 0x70, }
*warning = function(buffer.as_ptr())?; } else {
conditional_block
context.rs
use std::{ alloc::Layout, cell::{Ref, RefMut}, marker::PhantomData, mem::size_of, panic::AssertUnwindSafe, ptr::NonNull, sync::atomic::{AtomicBool, Ordering}, }; use anyhow::anyhow; use bytemuck::{Pod, Zeroable}; use feather_common::Game; use feather_ecs::EntityBuilder; use quill_common::Component; use serde::de::DeserializeOwned; use vec_arena::Arena; use wasmer::{FromToNativeWasmType, Instance}; use crate::{host_function::WasmHostFunction, thread_pinned::ThreadPinned, PluginId}; mod native; mod wasm; /// Wraps a pointer into a plugin's memory space. #[derive(Copy, Clone, PartialEq, Eq, Zeroable)] #[repr(transparent)] pub struct PluginPtr<T> { pub ptr: u64, pub _marker: PhantomData<*const T>, } impl<T> PluginPtr<T> { pub fn as_native(&self) -> *const T { self.ptr as usize as *const T } /// # Safety /// Adding `n` to this pointer /// must produce a pointer within the same allocated /// object. #[must_use = "PluginPtr::add returns a new pointer"] pub unsafe fn add(self, n: usize) -> Self { Self { ptr: self.ptr + (n * size_of::<T>()) as u64, _marker: self._marker, } } /// # Safety /// The cast must be valid. pub unsafe fn cast<U>(self) -> PluginPtr<U> { PluginPtr { ptr: self.ptr, _marker: PhantomData, } } } unsafe impl<T: Copy +'static> Pod for PluginPtr<T> {} /// Wraps a pointer into a plugin's memory space. #[derive(Copy, Clone, PartialEq, Eq, Zeroable)] #[repr(transparent)] pub struct PluginPtrMut<T> { pub ptr: u64, pub _marker: PhantomData<*mut T>, } impl<T> PluginPtrMut<T> { pub fn as_native(&self) -> *mut T { self.ptr as usize as *mut T } /// # Safety /// A null pointer must be valid in the context it is used. pub unsafe fn null() -> Self { Self { ptr: 0, _marker: PhantomData, } } /// # Safety /// Adding `n` to this pointer /// must produce a pointer within the same allocated /// object. #[must_use = "PluginPtrMut::add returns a new pointer"] pub unsafe fn add(self, n: usize) -> Self { Self { ptr: self.ptr + (n * size_of::<T>()) as u64, _marker: self._marker, } } /// # Safety /// The cast must be valid. pub unsafe fn cast<U>(self) -> PluginPtrMut<U> { PluginPtrMut { ptr: self.ptr, _marker: PhantomData, } } } unsafe impl<T: Copy +'static> Pod for PluginPtrMut<T> {} unsafe impl<T: Copy> FromToNativeWasmType for PluginPtr<T> { type Native = i64; fn from_native(native: Self::Native) -> Self { Self { ptr: native as u64, _marker: PhantomData, } } fn to_native(self) -> Self::Native { self.ptr as i64 } } unsafe impl<T: Copy> FromToNativeWasmType for PluginPtrMut<T> { type Native = i64; fn from_native(native: Self::Native) -> Self { Self { ptr: native as u64, _marker: PhantomData, } } fn to_native(self) -> Self::Native { self.ptr as i64 } } /// Context of a running plugin. /// /// Provides methods to access plugin memory, /// invoke exported functions, and access the `Game`. /// /// This type abstracts over WASM or native plugins, /// providing the same interface for both. /// /// # Safety /// The `native` version of the plugin context /// dereferences raw pointers. We assume pointers /// passed by plugins are valid. Most functions /// will cause undefined behavior if these constraints /// are violated. /// /// We type-encode that a pointer originates from a plugin /// using the `PluginPtr` structs. Methods that /// dereference pointers take instances of these /// structs. Since creating a `PluginPtr` is unsafe, /// `PluginContext` methods don't have to be marked /// unsafe. /// /// On WASM targets, the plugin is never trusted, /// and pointer accesses are checked. Undefined behavior /// can never occur as a result of malicious plugin input. pub struct PluginContext { inner: Inner, /// Whether the plugin is currently being invoked /// on the main thread. /// If this is `true`, then plugin functions are on the call stack. invoking_on_main_thread: AtomicBool, /// The current `Game`. /// /// Set to `None` if `invoking_on_main_thread` is `false`. /// Otherwise, must point to a valid game. The pointer /// must be cleared after the plugin finishes executing /// or we risk a dangling reference. game: ThreadPinned<Option<NonNull<Game>>>, /// ID of the plugin. id: PluginId, /// Active entity builders for the plugin. pub entity_builders: ThreadPinned<Arena<EntityBuilder>>, } impl PluginContext { /// Creates a new WASM plugin context. pub fn new_wasm(id: PluginId) -> Self { Self { inner: Inner::Wasm(ThreadPinned::new(wasm::WasmPluginContext::new())), invoking_on_main_thread: AtomicBool::new(false), game: ThreadPinned::new(None), id, entity_builders: ThreadPinned::new(Arena::new()), } } /// Creates a new native plugin context. pub fn new_native(id: PluginId) -> Self { Self { inner: Inner::Native(native::NativePluginContext::new()), invoking_on_main_thread: AtomicBool::new(false), game: ThreadPinned::new(None), id, entity_builders: ThreadPinned::new(Arena::new()), } } pub fn init_with_instance(&self, instance: &Instance) -> anyhow::Result<()> { match &self.inner { Inner::Wasm(w) => w.borrow_mut().init_with_instance(instance), Inner::Native(_) => panic!("cannot initialize native plugin context"), } } /// Enters the plugin context, invoking a function inside the plugin. /// /// # Panics /// Panics if we are already inside the plugin context. /// Panics if not called on the main thread. pub fn enter<R>(&self, game: &mut Game, callback: impl FnOnce() -> R) -> R { let was_already_entered = self.invoking_on_main_thread.swap(true, Ordering::SeqCst); assert!(!was_already_entered, "cannot recursively invoke a plugin"); *self.game.borrow_mut() = Some(NonNull::from(game)); // If a panic occurs, we need to catch it so // we clear `self.game`. Otherwise, we get // a dangling pointer. let result = std::panic::catch_unwind(AssertUnwindSafe(callback)); self.invoking_on_main_thread.store(false, Ordering::SeqCst); *self.game.borrow_mut() = None; self.bump_reset(); result.unwrap() } /// Gets a mutable reference to the `Game`. /// /// # Panics /// Panics if the plugin is not currently being /// invoked on the main thread. pub fn game_mut(&self) -> RefMut<Game> { let ptr = self.game.borrow_mut(); RefMut::map(ptr, |ptr| { let game_ptr = ptr.expect("plugin is not exeuctugin"); assert!(self.invoking_on_main_thread.load(Ordering::Relaxed)); // SAFETY: `game_ptr` points to a valid `Game` whenever // the plugin is executing. If the plugin is not // executing, then we already panicked when unwrapping `ptr`. unsafe { &mut *game_ptr.as_ptr() } }) } /// Gets the plugin ID. pub fn plugin_id(&self) -> PluginId { self.id } /// Accesses a byte slice in the plugin's memory space. /// /// # Safety /// **WASM**: mutating plugin memory or invoking /// plugin functions while this byte slice is /// alive is undefined behavior. /// **Native**: `ptr` must be valid. pub unsafe fn deref_bytes(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<&[u8]> { match &self.inner { Inner::Wasm(w) => { let w = w.borrow(); let bytes = w.deref_bytes(ptr, len)?; Ok(unsafe { std::slice::from_raw_parts(bytes.as_ptr(), bytes.len()) }) } Inner::Native(n) => n.deref_bytes(ptr, len), } } /// Accesses a byte slice in the plugin's memory space. /// /// # Safety /// **WASM**: accessing plugin memory or invoking /// plugin functions while this byte slice is /// alive is undefined behavior. /// **Native**: `ptr` must be valid and the aliasing /// rules must not be violated. pub unsafe fn deref_bytes_mut( &self, ptr: PluginPtrMut<u8>, len: u32, ) -> anyhow::Result<&mut [u8]> { match &self.inner { Inner::Wasm(w) => { let w = w.borrow(); let bytes = w.deref_bytes_mut(ptr, len)?; Ok(unsafe { std::slice::from_raw_parts_mut(bytes.as_mut_ptr(), bytes.len()) }) } Inner::Native(n) => n.deref_bytes_mut(ptr, len), } } /// Accesses a `Pod` value in the plugin's memory space. pub fn read_pod<T: Pod>(&self, ptr: PluginPtr<T>) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), size_of::<T>() as u32)?; bytemuck::try_from_bytes(bytes) .map_err(|_| anyhow!("badly aligned data")) .map(|val| *val) } } /// Accesses a `bincode`-encoded value in the plugin's memory space. pub fn read_bincode<T: DeserializeOwned>( &self, ptr: PluginPtr<u8>, len: u32, ) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; bincode::deserialize(bytes).map_err(From::from) } } /// Accesses a `json`-encoded value in the plugin's memory space. pub fn read_json<T: DeserializeOwned>( &self, ptr: PluginPtr<u8>, len: u32, ) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; serde_json::from_slice(bytes).map_err(From::from) } } /// Deserializes a component value in the plugin's memory space. pub fn read_component<T: Component>(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; T::from_bytes(bytes) .ok_or_else(|| anyhow!("malformed component")) .map(|(component, _bytes_read)| component) } } /// Reads a string from the plugin's memory space. pub fn read_string(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<String> { // SAFETY: we do not return a reference to these bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; let string = std::str::from_utf8(bytes)?.to_owned(); Ok(string) } } /// Reads a `Vec<u8>` from the plugin's memory space. pub fn read_bytes(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<Vec<u8>> { // SAFETY: we do not return a reference to these bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; Ok(bytes.to_owned()) } } /// Allocates some memory within the plugin's bump /// allocator. /// /// The memory is reset after the plugin finishes /// executing the current system. pub fn bump_allocate(&self, layout: Layout) -> anyhow::Result<PluginPtrMut<u8>> { match &self.inner { Inner::Wasm(w) => w.borrow().bump_allocate(layout), Inner::Native(n) => n.bump_allocate(layout), } } /// Bump allocates some memory, then copies `data` into it. pub fn bump_allocate_and_write_bytes(&self, data: &[u8]) -> anyhow::Result<PluginPtrMut<u8>> { let layout = Layout::array::<u8>(data.len())?; let ptr = self.bump_allocate(layout)?; // SAFETY: our access to these bytes is isolated to the // current function. `ptr` is valid as it was just allocated. unsafe { self.write_bytes(ptr, data)?; }
Ok(ptr) } /// Writes `data` to `ptr`. /// /// # Safety /// **WASM**: No concerns. /// **NATIVE**: `ptr` must point to a slice /// of at least `len` valid bytes. pub unsafe fn write_bytes(&self, ptr: PluginPtrMut<u8>, data: &[u8]) -> anyhow::Result<()> { let bytes = self.deref_bytes_mut(ptr, data.len() as u32)?; bytes.copy_from_slice(data); Ok(()) } /// Writes a `Pod` type to `ptr`. pub fn write_pod<T: Pod>(&self, ptr: PluginPtrMut<T>, value: T) -> anyhow::Result<()> { // SAFETY: Unlike `write_bytes`, we know `ptr` is valid for values // of type `T` because of its type parameter. unsafe { self.write_bytes(ptr.cast(), bytemuck::bytes_of(&value)) } } /// Deallocates all bump-allocated memory. fn bump_reset(&self) { match &self.inner { Inner::Wasm(w) => w.borrow().bump_reset(), Inner::Native(n) => n.bump_reset(), } } } enum Inner { Wasm(ThreadPinned<wasm::WasmPluginContext>), Native(native::NativePluginContext), }
random_line_split
context.rs
use std::{ alloc::Layout, cell::{Ref, RefMut}, marker::PhantomData, mem::size_of, panic::AssertUnwindSafe, ptr::NonNull, sync::atomic::{AtomicBool, Ordering}, }; use anyhow::anyhow; use bytemuck::{Pod, Zeroable}; use feather_common::Game; use feather_ecs::EntityBuilder; use quill_common::Component; use serde::de::DeserializeOwned; use vec_arena::Arena; use wasmer::{FromToNativeWasmType, Instance}; use crate::{host_function::WasmHostFunction, thread_pinned::ThreadPinned, PluginId}; mod native; mod wasm; /// Wraps a pointer into a plugin's memory space. #[derive(Copy, Clone, PartialEq, Eq, Zeroable)] #[repr(transparent)] pub struct PluginPtr<T> { pub ptr: u64, pub _marker: PhantomData<*const T>, } impl<T> PluginPtr<T> { pub fn as_native(&self) -> *const T { self.ptr as usize as *const T } /// # Safety /// Adding `n` to this pointer /// must produce a pointer within the same allocated /// object. #[must_use = "PluginPtr::add returns a new pointer"] pub unsafe fn add(self, n: usize) -> Self { Self { ptr: self.ptr + (n * size_of::<T>()) as u64, _marker: self._marker, } } /// # Safety /// The cast must be valid. pub unsafe fn cast<U>(self) -> PluginPtr<U> { PluginPtr { ptr: self.ptr, _marker: PhantomData, } } } unsafe impl<T: Copy +'static> Pod for PluginPtr<T> {} /// Wraps a pointer into a plugin's memory space. #[derive(Copy, Clone, PartialEq, Eq, Zeroable)] #[repr(transparent)] pub struct PluginPtrMut<T> { pub ptr: u64, pub _marker: PhantomData<*mut T>, } impl<T> PluginPtrMut<T> { pub fn as_native(&self) -> *mut T { self.ptr as usize as *mut T } /// # Safety /// A null pointer must be valid in the context it is used. pub unsafe fn null() -> Self { Self { ptr: 0, _marker: PhantomData, } } /// # Safety /// Adding `n` to this pointer /// must produce a pointer within the same allocated /// object. #[must_use = "PluginPtrMut::add returns a new pointer"] pub unsafe fn add(self, n: usize) -> Self { Self { ptr: self.ptr + (n * size_of::<T>()) as u64, _marker: self._marker, } } /// # Safety /// The cast must be valid. pub unsafe fn cast<U>(self) -> PluginPtrMut<U> { PluginPtrMut { ptr: self.ptr, _marker: PhantomData, } } } unsafe impl<T: Copy +'static> Pod for PluginPtrMut<T> {} unsafe impl<T: Copy> FromToNativeWasmType for PluginPtr<T> { type Native = i64; fn from_native(native: Self::Native) -> Self { Self { ptr: native as u64, _marker: PhantomData, } } fn to_native(self) -> Self::Native { self.ptr as i64 } } unsafe impl<T: Copy> FromToNativeWasmType for PluginPtrMut<T> { type Native = i64; fn from_native(native: Self::Native) -> Self { Self { ptr: native as u64, _marker: PhantomData, } } fn to_native(self) -> Self::Native { self.ptr as i64 } } /// Context of a running plugin. /// /// Provides methods to access plugin memory, /// invoke exported functions, and access the `Game`. /// /// This type abstracts over WASM or native plugins, /// providing the same interface for both. /// /// # Safety /// The `native` version of the plugin context /// dereferences raw pointers. We assume pointers /// passed by plugins are valid. Most functions /// will cause undefined behavior if these constraints /// are violated. /// /// We type-encode that a pointer originates from a plugin /// using the `PluginPtr` structs. Methods that /// dereference pointers take instances of these /// structs. Since creating a `PluginPtr` is unsafe, /// `PluginContext` methods don't have to be marked /// unsafe. /// /// On WASM targets, the plugin is never trusted, /// and pointer accesses are checked. Undefined behavior /// can never occur as a result of malicious plugin input. pub struct PluginContext { inner: Inner, /// Whether the plugin is currently being invoked /// on the main thread. /// If this is `true`, then plugin functions are on the call stack. invoking_on_main_thread: AtomicBool, /// The current `Game`. /// /// Set to `None` if `invoking_on_main_thread` is `false`. /// Otherwise, must point to a valid game. The pointer /// must be cleared after the plugin finishes executing /// or we risk a dangling reference. game: ThreadPinned<Option<NonNull<Game>>>, /// ID of the plugin. id: PluginId, /// Active entity builders for the plugin. pub entity_builders: ThreadPinned<Arena<EntityBuilder>>, } impl PluginContext { /// Creates a new WASM plugin context. pub fn new_wasm(id: PluginId) -> Self { Self { inner: Inner::Wasm(ThreadPinned::new(wasm::WasmPluginContext::new())), invoking_on_main_thread: AtomicBool::new(false), game: ThreadPinned::new(None), id, entity_builders: ThreadPinned::new(Arena::new()), } } /// Creates a new native plugin context. pub fn new_native(id: PluginId) -> Self
pub fn init_with_instance(&self, instance: &Instance) -> anyhow::Result<()> { match &self.inner { Inner::Wasm(w) => w.borrow_mut().init_with_instance(instance), Inner::Native(_) => panic!("cannot initialize native plugin context"), } } /// Enters the plugin context, invoking a function inside the plugin. /// /// # Panics /// Panics if we are already inside the plugin context. /// Panics if not called on the main thread. pub fn enter<R>(&self, game: &mut Game, callback: impl FnOnce() -> R) -> R { let was_already_entered = self.invoking_on_main_thread.swap(true, Ordering::SeqCst); assert!(!was_already_entered, "cannot recursively invoke a plugin"); *self.game.borrow_mut() = Some(NonNull::from(game)); // If a panic occurs, we need to catch it so // we clear `self.game`. Otherwise, we get // a dangling pointer. let result = std::panic::catch_unwind(AssertUnwindSafe(callback)); self.invoking_on_main_thread.store(false, Ordering::SeqCst); *self.game.borrow_mut() = None; self.bump_reset(); result.unwrap() } /// Gets a mutable reference to the `Game`. /// /// # Panics /// Panics if the plugin is not currently being /// invoked on the main thread. pub fn game_mut(&self) -> RefMut<Game> { let ptr = self.game.borrow_mut(); RefMut::map(ptr, |ptr| { let game_ptr = ptr.expect("plugin is not exeuctugin"); assert!(self.invoking_on_main_thread.load(Ordering::Relaxed)); // SAFETY: `game_ptr` points to a valid `Game` whenever // the plugin is executing. If the plugin is not // executing, then we already panicked when unwrapping `ptr`. unsafe { &mut *game_ptr.as_ptr() } }) } /// Gets the plugin ID. pub fn plugin_id(&self) -> PluginId { self.id } /// Accesses a byte slice in the plugin's memory space. /// /// # Safety /// **WASM**: mutating plugin memory or invoking /// plugin functions while this byte slice is /// alive is undefined behavior. /// **Native**: `ptr` must be valid. pub unsafe fn deref_bytes(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<&[u8]> { match &self.inner { Inner::Wasm(w) => { let w = w.borrow(); let bytes = w.deref_bytes(ptr, len)?; Ok(unsafe { std::slice::from_raw_parts(bytes.as_ptr(), bytes.len()) }) } Inner::Native(n) => n.deref_bytes(ptr, len), } } /// Accesses a byte slice in the plugin's memory space. /// /// # Safety /// **WASM**: accessing plugin memory or invoking /// plugin functions while this byte slice is /// alive is undefined behavior. /// **Native**: `ptr` must be valid and the aliasing /// rules must not be violated. pub unsafe fn deref_bytes_mut( &self, ptr: PluginPtrMut<u8>, len: u32, ) -> anyhow::Result<&mut [u8]> { match &self.inner { Inner::Wasm(w) => { let w = w.borrow(); let bytes = w.deref_bytes_mut(ptr, len)?; Ok(unsafe { std::slice::from_raw_parts_mut(bytes.as_mut_ptr(), bytes.len()) }) } Inner::Native(n) => n.deref_bytes_mut(ptr, len), } } /// Accesses a `Pod` value in the plugin's memory space. pub fn read_pod<T: Pod>(&self, ptr: PluginPtr<T>) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), size_of::<T>() as u32)?; bytemuck::try_from_bytes(bytes) .map_err(|_| anyhow!("badly aligned data")) .map(|val| *val) } } /// Accesses a `bincode`-encoded value in the plugin's memory space. pub fn read_bincode<T: DeserializeOwned>( &self, ptr: PluginPtr<u8>, len: u32, ) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; bincode::deserialize(bytes).map_err(From::from) } } /// Accesses a `json`-encoded value in the plugin's memory space. pub fn read_json<T: DeserializeOwned>( &self, ptr: PluginPtr<u8>, len: u32, ) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; serde_json::from_slice(bytes).map_err(From::from) } } /// Deserializes a component value in the plugin's memory space. pub fn read_component<T: Component>(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; T::from_bytes(bytes) .ok_or_else(|| anyhow!("malformed component")) .map(|(component, _bytes_read)| component) } } /// Reads a string from the plugin's memory space. pub fn read_string(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<String> { // SAFETY: we do not return a reference to these bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; let string = std::str::from_utf8(bytes)?.to_owned(); Ok(string) } } /// Reads a `Vec<u8>` from the plugin's memory space. pub fn read_bytes(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<Vec<u8>> { // SAFETY: we do not return a reference to these bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; Ok(bytes.to_owned()) } } /// Allocates some memory within the plugin's bump /// allocator. /// /// The memory is reset after the plugin finishes /// executing the current system. pub fn bump_allocate(&self, layout: Layout) -> anyhow::Result<PluginPtrMut<u8>> { match &self.inner { Inner::Wasm(w) => w.borrow().bump_allocate(layout), Inner::Native(n) => n.bump_allocate(layout), } } /// Bump allocates some memory, then copies `data` into it. pub fn bump_allocate_and_write_bytes(&self, data: &[u8]) -> anyhow::Result<PluginPtrMut<u8>> { let layout = Layout::array::<u8>(data.len())?; let ptr = self.bump_allocate(layout)?; // SAFETY: our access to these bytes is isolated to the // current function. `ptr` is valid as it was just allocated. unsafe { self.write_bytes(ptr, data)?; } Ok(ptr) } /// Writes `data` to `ptr`. /// /// # Safety /// **WASM**: No concerns. /// **NATIVE**: `ptr` must point to a slice /// of at least `len` valid bytes. pub unsafe fn write_bytes(&self, ptr: PluginPtrMut<u8>, data: &[u8]) -> anyhow::Result<()> { let bytes = self.deref_bytes_mut(ptr, data.len() as u32)?; bytes.copy_from_slice(data); Ok(()) } /// Writes a `Pod` type to `ptr`. pub fn write_pod<T: Pod>(&self, ptr: PluginPtrMut<T>, value: T) -> anyhow::Result<()> { // SAFETY: Unlike `write_bytes`, we know `ptr` is valid for values // of type `T` because of its type parameter. unsafe { self.write_bytes(ptr.cast(), bytemuck::bytes_of(&value)) } } /// Deallocates all bump-allocated memory. fn bump_reset(&self) { match &self.inner { Inner::Wasm(w) => w.borrow().bump_reset(), Inner::Native(n) => n.bump_reset(), } } } enum Inner { Wasm(ThreadPinned<wasm::WasmPluginContext>), Native(native::NativePluginContext), }
{ Self { inner: Inner::Native(native::NativePluginContext::new()), invoking_on_main_thread: AtomicBool::new(false), game: ThreadPinned::new(None), id, entity_builders: ThreadPinned::new(Arena::new()), } }
identifier_body
context.rs
use std::{ alloc::Layout, cell::{Ref, RefMut}, marker::PhantomData, mem::size_of, panic::AssertUnwindSafe, ptr::NonNull, sync::atomic::{AtomicBool, Ordering}, }; use anyhow::anyhow; use bytemuck::{Pod, Zeroable}; use feather_common::Game; use feather_ecs::EntityBuilder; use quill_common::Component; use serde::de::DeserializeOwned; use vec_arena::Arena; use wasmer::{FromToNativeWasmType, Instance}; use crate::{host_function::WasmHostFunction, thread_pinned::ThreadPinned, PluginId}; mod native; mod wasm; /// Wraps a pointer into a plugin's memory space. #[derive(Copy, Clone, PartialEq, Eq, Zeroable)] #[repr(transparent)] pub struct PluginPtr<T> { pub ptr: u64, pub _marker: PhantomData<*const T>, } impl<T> PluginPtr<T> { pub fn as_native(&self) -> *const T { self.ptr as usize as *const T } /// # Safety /// Adding `n` to this pointer /// must produce a pointer within the same allocated /// object. #[must_use = "PluginPtr::add returns a new pointer"] pub unsafe fn add(self, n: usize) -> Self { Self { ptr: self.ptr + (n * size_of::<T>()) as u64, _marker: self._marker, } } /// # Safety /// The cast must be valid. pub unsafe fn cast<U>(self) -> PluginPtr<U> { PluginPtr { ptr: self.ptr, _marker: PhantomData, } } } unsafe impl<T: Copy +'static> Pod for PluginPtr<T> {} /// Wraps a pointer into a plugin's memory space. #[derive(Copy, Clone, PartialEq, Eq, Zeroable)] #[repr(transparent)] pub struct PluginPtrMut<T> { pub ptr: u64, pub _marker: PhantomData<*mut T>, } impl<T> PluginPtrMut<T> { pub fn as_native(&self) -> *mut T { self.ptr as usize as *mut T } /// # Safety /// A null pointer must be valid in the context it is used. pub unsafe fn null() -> Self { Self { ptr: 0, _marker: PhantomData, } } /// # Safety /// Adding `n` to this pointer /// must produce a pointer within the same allocated /// object. #[must_use = "PluginPtrMut::add returns a new pointer"] pub unsafe fn add(self, n: usize) -> Self { Self { ptr: self.ptr + (n * size_of::<T>()) as u64, _marker: self._marker, } } /// # Safety /// The cast must be valid. pub unsafe fn cast<U>(self) -> PluginPtrMut<U> { PluginPtrMut { ptr: self.ptr, _marker: PhantomData, } } } unsafe impl<T: Copy +'static> Pod for PluginPtrMut<T> {} unsafe impl<T: Copy> FromToNativeWasmType for PluginPtr<T> { type Native = i64; fn from_native(native: Self::Native) -> Self { Self { ptr: native as u64, _marker: PhantomData, } } fn to_native(self) -> Self::Native { self.ptr as i64 } } unsafe impl<T: Copy> FromToNativeWasmType for PluginPtrMut<T> { type Native = i64; fn from_native(native: Self::Native) -> Self { Self { ptr: native as u64, _marker: PhantomData, } } fn to_native(self) -> Self::Native { self.ptr as i64 } } /// Context of a running plugin. /// /// Provides methods to access plugin memory, /// invoke exported functions, and access the `Game`. /// /// This type abstracts over WASM or native plugins, /// providing the same interface for both. /// /// # Safety /// The `native` version of the plugin context /// dereferences raw pointers. We assume pointers /// passed by plugins are valid. Most functions /// will cause undefined behavior if these constraints /// are violated. /// /// We type-encode that a pointer originates from a plugin /// using the `PluginPtr` structs. Methods that /// dereference pointers take instances of these /// structs. Since creating a `PluginPtr` is unsafe, /// `PluginContext` methods don't have to be marked /// unsafe. /// /// On WASM targets, the plugin is never trusted, /// and pointer accesses are checked. Undefined behavior /// can never occur as a result of malicious plugin input. pub struct PluginContext { inner: Inner, /// Whether the plugin is currently being invoked /// on the main thread. /// If this is `true`, then plugin functions are on the call stack. invoking_on_main_thread: AtomicBool, /// The current `Game`. /// /// Set to `None` if `invoking_on_main_thread` is `false`. /// Otherwise, must point to a valid game. The pointer /// must be cleared after the plugin finishes executing /// or we risk a dangling reference. game: ThreadPinned<Option<NonNull<Game>>>, /// ID of the plugin. id: PluginId, /// Active entity builders for the plugin. pub entity_builders: ThreadPinned<Arena<EntityBuilder>>, } impl PluginContext { /// Creates a new WASM plugin context. pub fn new_wasm(id: PluginId) -> Self { Self { inner: Inner::Wasm(ThreadPinned::new(wasm::WasmPluginContext::new())), invoking_on_main_thread: AtomicBool::new(false), game: ThreadPinned::new(None), id, entity_builders: ThreadPinned::new(Arena::new()), } } /// Creates a new native plugin context. pub fn new_native(id: PluginId) -> Self { Self { inner: Inner::Native(native::NativePluginContext::new()), invoking_on_main_thread: AtomicBool::new(false), game: ThreadPinned::new(None), id, entity_builders: ThreadPinned::new(Arena::new()), } } pub fn init_with_instance(&self, instance: &Instance) -> anyhow::Result<()> { match &self.inner { Inner::Wasm(w) => w.borrow_mut().init_with_instance(instance), Inner::Native(_) => panic!("cannot initialize native plugin context"), } } /// Enters the plugin context, invoking a function inside the plugin. /// /// # Panics /// Panics if we are already inside the plugin context. /// Panics if not called on the main thread. pub fn enter<R>(&self, game: &mut Game, callback: impl FnOnce() -> R) -> R { let was_already_entered = self.invoking_on_main_thread.swap(true, Ordering::SeqCst); assert!(!was_already_entered, "cannot recursively invoke a plugin"); *self.game.borrow_mut() = Some(NonNull::from(game)); // If a panic occurs, we need to catch it so // we clear `self.game`. Otherwise, we get // a dangling pointer. let result = std::panic::catch_unwind(AssertUnwindSafe(callback)); self.invoking_on_main_thread.store(false, Ordering::SeqCst); *self.game.borrow_mut() = None; self.bump_reset(); result.unwrap() } /// Gets a mutable reference to the `Game`. /// /// # Panics /// Panics if the plugin is not currently being /// invoked on the main thread. pub fn game_mut(&self) -> RefMut<Game> { let ptr = self.game.borrow_mut(); RefMut::map(ptr, |ptr| { let game_ptr = ptr.expect("plugin is not exeuctugin"); assert!(self.invoking_on_main_thread.load(Ordering::Relaxed)); // SAFETY: `game_ptr` points to a valid `Game` whenever // the plugin is executing. If the plugin is not // executing, then we already panicked when unwrapping `ptr`. unsafe { &mut *game_ptr.as_ptr() } }) } /// Gets the plugin ID. pub fn plugin_id(&self) -> PluginId { self.id } /// Accesses a byte slice in the plugin's memory space. /// /// # Safety /// **WASM**: mutating plugin memory or invoking /// plugin functions while this byte slice is /// alive is undefined behavior. /// **Native**: `ptr` must be valid. pub unsafe fn deref_bytes(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<&[u8]> { match &self.inner { Inner::Wasm(w) => { let w = w.borrow(); let bytes = w.deref_bytes(ptr, len)?; Ok(unsafe { std::slice::from_raw_parts(bytes.as_ptr(), bytes.len()) }) } Inner::Native(n) => n.deref_bytes(ptr, len), } } /// Accesses a byte slice in the plugin's memory space. /// /// # Safety /// **WASM**: accessing plugin memory or invoking /// plugin functions while this byte slice is /// alive is undefined behavior. /// **Native**: `ptr` must be valid and the aliasing /// rules must not be violated. pub unsafe fn deref_bytes_mut( &self, ptr: PluginPtrMut<u8>, len: u32, ) -> anyhow::Result<&mut [u8]> { match &self.inner { Inner::Wasm(w) => { let w = w.borrow(); let bytes = w.deref_bytes_mut(ptr, len)?; Ok(unsafe { std::slice::from_raw_parts_mut(bytes.as_mut_ptr(), bytes.len()) }) } Inner::Native(n) => n.deref_bytes_mut(ptr, len), } } /// Accesses a `Pod` value in the plugin's memory space. pub fn read_pod<T: Pod>(&self, ptr: PluginPtr<T>) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), size_of::<T>() as u32)?; bytemuck::try_from_bytes(bytes) .map_err(|_| anyhow!("badly aligned data")) .map(|val| *val) } } /// Accesses a `bincode`-encoded value in the plugin's memory space. pub fn read_bincode<T: DeserializeOwned>( &self, ptr: PluginPtr<u8>, len: u32, ) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; bincode::deserialize(bytes).map_err(From::from) } } /// Accesses a `json`-encoded value in the plugin's memory space. pub fn
<T: DeserializeOwned>( &self, ptr: PluginPtr<u8>, len: u32, ) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; serde_json::from_slice(bytes).map_err(From::from) } } /// Deserializes a component value in the plugin's memory space. pub fn read_component<T: Component>(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; T::from_bytes(bytes) .ok_or_else(|| anyhow!("malformed component")) .map(|(component, _bytes_read)| component) } } /// Reads a string from the plugin's memory space. pub fn read_string(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<String> { // SAFETY: we do not return a reference to these bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; let string = std::str::from_utf8(bytes)?.to_owned(); Ok(string) } } /// Reads a `Vec<u8>` from the plugin's memory space. pub fn read_bytes(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<Vec<u8>> { // SAFETY: we do not return a reference to these bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; Ok(bytes.to_owned()) } } /// Allocates some memory within the plugin's bump /// allocator. /// /// The memory is reset after the plugin finishes /// executing the current system. pub fn bump_allocate(&self, layout: Layout) -> anyhow::Result<PluginPtrMut<u8>> { match &self.inner { Inner::Wasm(w) => w.borrow().bump_allocate(layout), Inner::Native(n) => n.bump_allocate(layout), } } /// Bump allocates some memory, then copies `data` into it. pub fn bump_allocate_and_write_bytes(&self, data: &[u8]) -> anyhow::Result<PluginPtrMut<u8>> { let layout = Layout::array::<u8>(data.len())?; let ptr = self.bump_allocate(layout)?; // SAFETY: our access to these bytes is isolated to the // current function. `ptr` is valid as it was just allocated. unsafe { self.write_bytes(ptr, data)?; } Ok(ptr) } /// Writes `data` to `ptr`. /// /// # Safety /// **WASM**: No concerns. /// **NATIVE**: `ptr` must point to a slice /// of at least `len` valid bytes. pub unsafe fn write_bytes(&self, ptr: PluginPtrMut<u8>, data: &[u8]) -> anyhow::Result<()> { let bytes = self.deref_bytes_mut(ptr, data.len() as u32)?; bytes.copy_from_slice(data); Ok(()) } /// Writes a `Pod` type to `ptr`. pub fn write_pod<T: Pod>(&self, ptr: PluginPtrMut<T>, value: T) -> anyhow::Result<()> { // SAFETY: Unlike `write_bytes`, we know `ptr` is valid for values // of type `T` because of its type parameter. unsafe { self.write_bytes(ptr.cast(), bytemuck::bytes_of(&value)) } } /// Deallocates all bump-allocated memory. fn bump_reset(&self) { match &self.inner { Inner::Wasm(w) => w.borrow().bump_reset(), Inner::Native(n) => n.bump_reset(), } } } enum Inner { Wasm(ThreadPinned<wasm::WasmPluginContext>), Native(native::NativePluginContext), }
read_json
identifier_name
lib.rs
// This component uses Sciter Engine, // copyright Terra Informatica Software, Inc. // (http://terrainformatica.com/). /*! # Rust bindings library for Sciter engine. [Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine with GPU accelerated rendering designed to render modern desktop application UI. It's a compact, single dll/dylib/so file (4-8 mb) engine without any additional dependencies. Check the [screenshot gallery](https://github.com/oskca/sciter#sciter-desktop-ui-examples) of the desktop UI examples. Sciter supports all standard elements defined in HTML5 specification [with some additions](https://sciter.com/developers/for-web-programmers/). CSS is extended to better support the Desktop UI development, e.g. flow and flex units, vertical and horizontal alignment, OS theming. [Sciter SDK](https://sciter.com/download/) comes with a demo "browser" with builtin DOM inspector, script debugger and documentation viewer: ![Sciter tools](https://sciter.com/images/sciter-tools.png) Check <https://sciter.com> website and its [documentation resources](https://sciter.com/developers/) for engine principles, architecture and more. ## Brief look: Here is a minimal sciter app: ```no_run extern crate sciter; fn main() { let mut frame = sciter::Window::new(); frame.load_file("minimal.htm"); frame.run_app(); } ``` It looks similar like this: ![Minimal sciter sample](https://i.imgur.com/ojcM5JJ.png) Check [rust-sciter/examples](https://github.com/sciter-sdk/rust-sciter/tree/master/examples) folder for more complex usage and module-level sections for the guides about: * [Window](window/index.html) creation. * [Behaviors](dom/event/index.html) and event handling. * [DOM](dom/index.html) access methods. * Sciter [Value](value/index.html) interface. */ #![doc(html_logo_url = "https://sciter.com/screenshots/slide-sciter-osx.png", html_favicon_url = "https://sciter.com/wp-content/themes/sciter/!images/favicon.ico")] // documentation test: // #![warn(missing_docs)] /* Clippy lints */ #![allow(clippy::needless_return, clippy::let_and_return)] // past habits #![allow(clippy::redundant_field_names)] // since Rust 1.17 and less readable #![allow(clippy::unreadable_literal)] // C++ SDK constants #![allow(clippy::upper_case_acronyms)]// C++ SDK constants #![allow(clippy::deprecated_semver)] // `#[deprecated(since="Sciter 4.4.3.24")]` is not a semver format. #![allow(clippy::result_unit_err)] // Sciter returns BOOL, but `Result<(), ()>` is more strict even without error description. // #![allow(clippy::cast_ptr_alignment)] // 0.0.195 only /* Macros */ #[cfg(target_os = "macos")] #[macro_use] extern crate objc; #[macro_use] extern crate lazy_static; #[macro_use] pub mod macros; mod capi; #[doc(hidden)] pub use capi::scdom::{HELEMENT}; pub use capi::scdef::{GFX_LAYER, SCRIPT_RUNTIME_FEATURES}; /* Rust interface */ mod platform; mod eventhandler; pub mod dom; pub mod graphics; pub mod host; pub mod om; pub mod request; pub mod types; pub mod utf; pub mod value; pub mod video; pub mod window; pub mod windowless; pub use dom::Element; pub use dom::event::EventHandler; pub use host::{Archive, Host, HostHandler}; pub use value::{Value, FromValue}; pub use window::Window; /// Builder pattern for window creation. See [`window::Builder`](window/struct.Builder.html) documentation. /// /// For example, /// /// ```rust,no_run /// let mut frame = sciter::WindowBuilder::main_window() /// .with_size((800,600)) /// .glassy() /// .fixed() /// .create(); /// ``` pub type WindowBuilder = window::Builder; /* Loader */ pub use capi::scapi::{ISciterAPI}; use capi::scgraphics::SciterGraphicsAPI; use capi::screquest::SciterRequestAPI; #[cfg(windows)] mod ext { // Note: // Sciter 4.x shipped with universal "sciter.dll" library for different builds: // bin/32, bin/64, bin/skia32, bin/skia64 // However it is quite inconvenient now (e.g. we can not put x64 and x86 builds in %PATH%) // #![allow(non_snake_case, non_camel_case_types)] use capi::scapi::{ISciterAPI}; use capi::sctypes::{LPCSTR, LPCVOID, BOOL}; type ApiType = *const ISciterAPI; type FuncType = extern "system" fn () -> *const ISciterAPI; pub static mut CUSTOM_DLL_PATH: Option<String> = None; extern "system" { fn LoadLibraryA(lpFileName: LPCSTR) -> LPCVOID; fn FreeLibrary(dll: LPCVOID) -> BOOL; fn GetProcAddress(hModule: LPCVOID, lpProcName: LPCSTR) -> LPCVOID; } pub fn try_load_library(permanent: bool) -> ::std::result::Result<ApiType, String> { use std::ffi::CString; use std::path::Path; fn try_load(path: &Path) -> Option<LPCVOID> { let path = CString::new(format!("{}", path.display())).expect("invalid library path"); let dll = unsafe { LoadLibraryA(path.as_ptr()) }; if!dll.is_null() { Some(dll) } else { None } } fn in_global() -> Option<LPCVOID> { // modern dll name let mut dll = unsafe { LoadLibraryA(b"sciter.dll\0".as_ptr() as LPCSTR) }; if dll.is_null() { // try to load with old names let alternate = if cfg!(target_arch = "x86_64") { b"sciter64.dll\0" } else { b"sciter32.dll\0" }; dll = unsafe { LoadLibraryA(alternate.as_ptr() as LPCSTR) }; } if!dll.is_null() { Some(dll) } else { None } } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { try_load(Path::new(path)) } else { in_global() }; if let Some(dll) = dll { // get the "SciterAPI" exported symbol let sym = unsafe { GetProcAddress(dll, b"SciterAPI\0".as_ptr() as LPCSTR) }; if sym.is_null() { return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned()); } if!permanent { unsafe { FreeLibrary(dll) }; return Ok(0 as ApiType); } let get_api: FuncType = unsafe { std::mem::transmute(sym) }; return Ok(get_api()); } let sdkbin = if cfg!(target_arch = "x86_64") { "bin/64" } else { "bin/32" }; let msg = format!("Please verify that Sciter SDK is installed and its binaries (from SDK/{}) are available in PATH.", sdkbin); Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n {}", "sciter.dll", msg)) } pub unsafe fn SciterAPI() -> *const ISciterAPI { match try_load_library(true) { Ok(api) => api, Err(error) => panic!("{}", error), } } } #[cfg(all(feature = "dynamic", unix))] mod ext { #![allow(non_snake_case, non_camel_case_types)] extern crate libc; pub static mut CUSTOM_DLL_PATH: Option<String> = None; #[cfg(target_os = "linux")] const DLL_NAMES: &[&str] = &[ "libsciter-gtk.so" ]; // "libsciter.dylib" since Sciter 4.4.6.3. #[cfg(target_os = "macos")] const DLL_NAMES: &[&str] = &[ "libsciter.dylib", "sciter-osx-64.dylib" ]; use capi::scapi::ISciterAPI; use capi::sctypes::{LPVOID, LPCSTR}; type FuncType = extern "system" fn () -> *const ISciterAPI; type ApiType = *const ISciterAPI; pub fn try_load_library(permanent: bool) -> ::std::result::Result<ApiType, String> { use std::ffi::CString; use std::os::unix::ffi::OsStrExt; use std::path::{Path}; // Try to load the library from a specified absolute path. fn try_load(path: &Path) -> Option<LPVOID> { let bytes = path.as_os_str().as_bytes(); if let Ok(cstr) = CString::new(bytes) { let dll = unsafe { libc::dlopen(cstr.as_ptr(), libc::RTLD_LOCAL | libc::RTLD_LAZY) }; if!dll.is_null() { return Some(dll) } } None } // Try to find a library (by one of its names) in a specified path. fn try_load_from(dir: Option<&Path>) -> Option<LPVOID> { let dll = DLL_NAMES.iter() .map(|name| { let mut path = dir.map(Path::to_owned).unwrap_or_default(); path.push(name); path }) .map(|path| try_load(&path)) .find(|dll| dll.is_some()) .map(|o| o.unwrap()); if dll.is_some() { return dll; } None } // Try to load from the current directory. fn in_current_dir() -> Option<LPVOID> { if let Ok(dir) = ::std::env::current_exe() { if let Some(dir) = dir.parent() { let dll = try_load_from(Some(dir)); if dll.is_some() { return dll; } if cfg!(target_os = "macos") { // "(bundle folder)/Contents/Frameworks/" let mut path = dir.to_owned(); path.push("../Frameworks/libsciter.dylib"); let dll = try_load(&path); if dll.is_some() { return dll; } let mut path = dir.to_owned(); path.push("../Frameworks/sciter-osx-64.dylib"); let dll = try_load(&path); if dll.is_some() { return dll; } } } } None } // Try to load indirectly via `dlopen("dll.so")`. fn in_global() -> Option<LPVOID> { try_load_from(None) } // Try to find in $PATH. fn in_paths() -> Option<LPVOID> { use std::env; if let Some(paths) = env::var_os("PATH") { for path in env::split_paths(&paths) { if let Some(dll) = try_load_from(Some(&path)) { return Some(dll); } } } None } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { try_load(Path::new(path)) } else { in_current_dir().or_else(in_paths).or_else(in_global) }; if let Some(dll) = dll { // get the "SciterAPI" exported symbol let sym = unsafe { libc::dlsym(dll, b"SciterAPI\0".as_ptr() as LPCSTR) }; if sym.is_null() { return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned()); } if!permanent { unsafe { libc::dlclose(dll) }; return Ok(0 as ApiType); } let get_api: FuncType = unsafe { std::mem::transmute(sym) }; return Ok(get_api()); } let sdkbin = if cfg!(target_os = "macos") { "bin.osx" } else { "bin.lnx" }; let msg = format!("Please verify that Sciter SDK is installed and its binaries (from {}) are available in PATH.", sdkbin); Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n {}", DLL_NAMES[0], msg)) } pub fn SciterAPI() -> *const ISciterAPI { match try_load_library(true) { Ok(api) => api, Err(error) => panic!("{}", error), } } } #[cfg(all(target_os = "linux", not(feature = "dynamic")))] mod ext { // Note: // Since 4.1.4 library name has been changed to "libsciter-gtk" (without 32/64 suffix). // Since 3.3.1.6 library name was changed to "libsciter". // However CC requires `-l sciter` form. #[link(name = "sciter-gtk")] extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI; } } #[cfg(all(target_os = "macos", target_arch = "x86_64", not(feature = "dynamic")))] mod ext { #[link(name = "libsciter", kind = "dylib")] extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI; } } /// Getting ISciterAPI reference, can be used for manual API calling. #[doc(hidden)] #[allow(non_snake_case)] pub fn SciterAPI<'a>() -> &'a ISciterAPI { let ap = unsafe { if cfg!(feature="extension") { // TODO: it's not good to raise a panic inside `lazy_static!`, // because it wents into recursive panicing. // // Somehow, `cargo test --all` tests all the features, // also sometimes it comes even without `cfg!(test)`. // Well, the culprit is "examples/extensions" which uses the "extension" feature, // but how on earth it builds without `cfg(test)`? // if cfg!(test) { &*ext::SciterAPI() } else { EXT_API //.or_else(|| Some(&*ext::SciterAPI())) .expect("Sciter API is not available yet, call `sciter::set_api()` first.") } } else { &*ext::SciterAPI() } }; let abi_version = ap.version; if cfg!(feature = "windowless") { assert!(abi_version >= 0x0001_0001, "Incompatible Sciter build and \"windowless\" feature"); } if cfg!(not(feature = "windowless"))
return ap; } /// Getting ISciterAPI reference, can be used for manual API calling. /// /// Bypasses ABI compatability checks. #[doc(hidden)] #[allow(non_snake_case)] pub fn SciterAPI_unchecked<'a>() -> &'a ISciterAPI { let ap = unsafe { if cfg!(feature="extension") { EXT_API.expect("Sciter API is not available yet, call `sciter::set_api()` first.") } else { &*ext::SciterAPI() } }; return ap; } lazy_static! { static ref _API: &'static ISciterAPI = SciterAPI(); static ref _GAPI: &'static SciterGraphicsAPI = { if version_num() < 0x0401_0A00 { panic!("Graphics API is incompatible since 4.1.10 (your version is {})", version()); } unsafe { &*(SciterAPI().GetSciterGraphicsAPI)() } }; static ref _RAPI: &'static SciterRequestAPI = unsafe { &*(SciterAPI().GetSciterRequestAPI)() }; } /// Set a custom path to the Sciter dynamic library. /// /// Note: Must be called first before any other function. /// /// Returns error if the specified library can not be loaded. /// /// # Example /// /// ```rust /// if sciter::set_library("~/lib/sciter/bin.gtk/x64/libsciter-gtk.so").is_ok() { /// println!("loaded Sciter version {}", sciter::version()); /// } /// ``` pub fn set_library(custom_path: &str) -> ::std::result::Result<(), String> { #[cfg(not(feature = "dynamic"))] fn set_impl(_: &str) -> ::std::result::Result<(), String> { Err("Don't use `sciter::set_library()` in static builds.\n Build with the feature \"dynamic\" instead.".to_owned()) } #[cfg(feature = "dynamic")] fn set_impl(path: &str) -> ::std::result::Result<(), String> { unsafe { ext::CUSTOM_DLL_PATH = Some(path.to_owned()); } ext::try_load_library(false).map(|_| ()) } set_impl(custom_path) } static mut EXT_API: Option<&'static ISciterAPI> = None; /// Set the Sciter API coming from `SciterLibraryInit`. /// /// Note: Must be called first before any other function. pub fn set_host_api(api: &'static ISciterAPI) { if cfg!(feature="extension") { unsafe { EXT_API.replace(api); } } } /// Sciter engine version number (e.g. `0x03030200`). /// /// Note: does not return the `build` part because it doesn't fit in `0..255` byte range. /// Use [`sciter::version()`](fn.version.html) instead which returns the complete version string. pub fn version_num() -> u32 { use types::BOOL; let v1 = (_API.SciterVersion)(true as BOOL); let v2 = (_API.SciterVersion)(false as BOOL); let (major, minor, revision, _build) = (v1 >> 16 & 0xFF, v1 & 0xFF, v2 >> 16 & 0xFF, v2 & 0xFF); let num = (major << 24) | (minor << 16) | (revision << 8); // let num = ((v1 >> 16) << 24) | ((v1 & 0xFFFF) << 16) | ((v2 >> 16) << 8) | (v2 & 0xFFFF); return num; } /// Sciter engine version string (e.g. "`3.3.2.0`"). pub fn version() -> String { use types::BOOL; let v1 = (_API.SciterVersion)(true as BOOL); let v2 = (_API.SciterVersion)(false as BOOL); let num = [v1 >> 16, v1 & 0xFFFF, v2 >> 16, v2 & 0xFFFF]; let version = format!("{}.{}.{}.{}", num[0], num[1], num[2], num[3]); return version; } /// Sciter API version. /// /// Returns: /// /// * `0x0000_0001` for regular builds, `0x0001_0001` for windowless builds. /// * `0x0000_0002` since 4.4.2.14 (a breaking change in assets with [SOM builds](https://sciter.com/native-code-exposure-to-script/)) /// * `0x0000_0003` since 4.4.2.16 /// * `0x0000_0004` since 4.4.2.17 (a breaking change in SOM passport) /// * `0x0000_0005` since 4.4.3.20 (a breaking change in `INITIALIZATION_PARAMS`, SOM in event handlers fix) /// * `0x0000_0006` since 4.4.3.24 (TIScript native API is gone, use SOM instead) /// * `0x0000_0007` since 4.4.5.4 (DOM-Value conversion functions were added, no breaking change) /// * `0x0000_0008` since 4.4.6.7 (Sciter and Sciter.Lite are unified in ISciterAPI) /// * `0x0000_0009` since 4.4.7.0 (ISciterAPI unification between all platforms) /// /// Since 4.4.0.3. pub fn api_version() -> u32 { _API.version } /// Returns true for windowless builds. pub fn is_windowless() -> bool { api_version() >= 0x0001_0001 } /// Various global Sciter engine options. /// /// Used by [`sciter::set_options()`](fn.set_options.html). /// /// See also [per-window options](window/enum.Options.html). #[derive(Copy, Clone)] pub enum RuntimeOptions<'a> { /// global; value: the full path to the Sciter dynamic library (dll/dylib/so), /// must be called before any other Sciter function. LibraryPath(&'a str), /// global; value: [`GFX_LAYER`](enum.GFX_LAYER.html), must be called before any window creation. GfxLayer(GFX_LAYER), /// global; value: `true` - the engine will use a "unisex" theme that is common for all platforms. /// That UX theme is not using OS primitives for rendering input elements. /// Use it if you want exactly the same (modulo fonts) look-n-feel on all platforms. UxTheming(bool), /// global or per-window; enables Sciter Inspector for all windows, must be called before any window creation. DebugMode(bool), /// global or per-window; value: combination of [`SCRIPT_RUNTIME_FEATURES`](enum.SCRIPT_RUNTIME_FEATURES.html) flags. /// /// Note that these features have been disabled by default /// since [4.2.5.0](https://rawgit.com/c-smile/sciter-sdk/7036a9c7912ac30d9f369d9abb87b278d2d54c6d/logfile.htm). ScriptFeatures(u8), /// global; value: milliseconds, connection timeout of http client. ConnectionTimeout(u32), /// global; value: `0` - drop connection, `1` - use builtin dialog, `2` - accept connection silently. OnHttpsError(u8), // global; value: json with GPU black list, see the `gpu-blacklist.json` resource. // Not used in Sciter 4, in fact: https://sciter.com/forums/topic/how-to-use-the-gpu-blacklist/#post-59338 // GpuBlacklist(&'a str), /// global; value: script source to be loaded into each view before any other script execution. InitScript(&'a str), /// global; value - max request length in megabytes (1024*1024 bytes), since 4.3.0.15. MaxHttpDataLength(usize), /// global or per-window; value: `true` - `1px` in CSS is treated as `1dip`, otherwise `1px` is a physical pixel (by default). /// /// since [4.4.5.0](https://rawgit.com/c-smile/sciter-sdk/aafb625bb0bc317d79c0a14d02b5730f6a02b48a/logfile.htm). LogicalPixel(bool), } /// Set various global Sciter engine options, see the [`RuntimeOptions`](enum.RuntimeOptions.html). pub fn set_options(options: RuntimeOptions) -> std::result::Result<(), ()> { use RuntimeOptions::*; use capi::scdef::SCITER_RT_OPTIONS::*; let (option, value) = match options { ConnectionTimeout(ms) => (SCITER_CONNECTION_TIMEOUT, ms as usize), OnHttpsError(behavior) => (SCITER_HTTPS_ERROR, behavior as usize), // GpuBlacklist(json) => (SCITER_SET_GPU_BLACKLIST, json.as_bytes().as_ptr() as usize), InitScript(script) => (SCITER_SET_INIT_SCRIPT, script.as_bytes().as_ptr() as usize), ScriptFeatures(mask) => (SCITER_SET_SCRIPT_RUNTIME_FEATURES, mask as usize), GfxLayer(backend) => (SCITER_SET_GFX_LAYER, backend as usize), DebugMode(enable) => (SCITER_SET_DEBUG_MODE, enable as usize), UxTheming(enable) => (SCITER_SET_UX_THEMING, enable as usize), MaxHttpDataLength(value) => (SCITER_SET_MAX_HTTP_DATA_LENGTH, value), LogicalPixel(enable) => (SCITER_SET_PX_AS_DIP, enable as usize), LibraryPath(path) => { return set_library(path).map_err(|_|()); } }; let ok = (_API.SciterSetOption)(std::ptr::null_mut(), option, value); if ok!= 0 { Ok(()) } else { Err(()) } } /// Set a global variable by its path to all windows. /// /// This variable will be accessible in all windows via `globalThis[path]` or just `path`. /// /// Note that this call affects only _new_ windows, /// so it's preferred to call it before the main window creation. /// /// See also per-window [`Window::set_variable`](window/struct.Window.html#method.set_variable) /// to assign a global to a single window only. pub fn set_variable(path: &str, value: Value) -> dom::Result<()> { let ws = s2u!(path); let ok = (_API.SciterSetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_cptr()); if ok == dom::SCDOM_RESULT::OK { Ok(()) } else { Err(ok) } } /// Get a global variable by its path. /// /// See the per-window [`Window::get_variable`](window/struct.Window.html#method.get_variable). #[doc(hidden)] pub fn get_variable(path: &str) -> dom::Result<Value> { let ws = s2u!(path); let mut value = Value::new(); let ok = (_API.SciterGetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_mut_ptr()); if ok == dom::SCDOM_RESULT::OK { Ok(value) } else { Err(ok) } }
{ assert!(abi_version < 0x0001_0000, "Incompatible Sciter build and \"windowless\" feature"); }
conditional_block
lib.rs
// This component uses Sciter Engine, // copyright Terra Informatica Software, Inc. // (http://terrainformatica.com/). /*! # Rust bindings library for Sciter engine. [Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine with GPU accelerated rendering designed to render modern desktop application UI. It's a compact, single dll/dylib/so file (4-8 mb) engine without any additional dependencies. Check the [screenshot gallery](https://github.com/oskca/sciter#sciter-desktop-ui-examples) of the desktop UI examples. Sciter supports all standard elements defined in HTML5 specification [with some additions](https://sciter.com/developers/for-web-programmers/). CSS is extended to better support the Desktop UI development, e.g. flow and flex units, vertical and horizontal alignment, OS theming. [Sciter SDK](https://sciter.com/download/) comes with a demo "browser" with builtin DOM inspector, script debugger and documentation viewer: ![Sciter tools](https://sciter.com/images/sciter-tools.png) Check <https://sciter.com> website and its [documentation resources](https://sciter.com/developers/) for engine principles, architecture and more. ## Brief look: Here is a minimal sciter app: ```no_run extern crate sciter; fn main() { let mut frame = sciter::Window::new(); frame.load_file("minimal.htm"); frame.run_app(); } ``` It looks similar like this: ![Minimal sciter sample](https://i.imgur.com/ojcM5JJ.png) Check [rust-sciter/examples](https://github.com/sciter-sdk/rust-sciter/tree/master/examples) folder for more complex usage and module-level sections for the guides about: * [Window](window/index.html) creation. * [Behaviors](dom/event/index.html) and event handling. * [DOM](dom/index.html) access methods. * Sciter [Value](value/index.html) interface. */ #![doc(html_logo_url = "https://sciter.com/screenshots/slide-sciter-osx.png", html_favicon_url = "https://sciter.com/wp-content/themes/sciter/!images/favicon.ico")] // documentation test: // #![warn(missing_docs)] /* Clippy lints */ #![allow(clippy::needless_return, clippy::let_and_return)] // past habits #![allow(clippy::redundant_field_names)] // since Rust 1.17 and less readable #![allow(clippy::unreadable_literal)] // C++ SDK constants #![allow(clippy::upper_case_acronyms)]// C++ SDK constants #![allow(clippy::deprecated_semver)] // `#[deprecated(since="Sciter 4.4.3.24")]` is not a semver format. #![allow(clippy::result_unit_err)] // Sciter returns BOOL, but `Result<(), ()>` is more strict even without error description. // #![allow(clippy::cast_ptr_alignment)] // 0.0.195 only /* Macros */ #[cfg(target_os = "macos")] #[macro_use] extern crate objc; #[macro_use] extern crate lazy_static; #[macro_use] pub mod macros; mod capi; #[doc(hidden)] pub use capi::scdom::{HELEMENT}; pub use capi::scdef::{GFX_LAYER, SCRIPT_RUNTIME_FEATURES}; /* Rust interface */ mod platform; mod eventhandler; pub mod dom; pub mod graphics; pub mod host; pub mod om; pub mod request; pub mod types; pub mod utf; pub mod value; pub mod video; pub mod window; pub mod windowless; pub use dom::Element; pub use dom::event::EventHandler; pub use host::{Archive, Host, HostHandler}; pub use value::{Value, FromValue}; pub use window::Window; /// Builder pattern for window creation. See [`window::Builder`](window/struct.Builder.html) documentation. /// /// For example, /// /// ```rust,no_run /// let mut frame = sciter::WindowBuilder::main_window() /// .with_size((800,600)) /// .glassy() /// .fixed() /// .create(); /// ``` pub type WindowBuilder = window::Builder; /* Loader */ pub use capi::scapi::{ISciterAPI}; use capi::scgraphics::SciterGraphicsAPI; use capi::screquest::SciterRequestAPI; #[cfg(windows)] mod ext { // Note: // Sciter 4.x shipped with universal "sciter.dll" library for different builds: // bin/32, bin/64, bin/skia32, bin/skia64 // However it is quite inconvenient now (e.g. we can not put x64 and x86 builds in %PATH%) // #![allow(non_snake_case, non_camel_case_types)] use capi::scapi::{ISciterAPI}; use capi::sctypes::{LPCSTR, LPCVOID, BOOL}; type ApiType = *const ISciterAPI; type FuncType = extern "system" fn () -> *const ISciterAPI; pub static mut CUSTOM_DLL_PATH: Option<String> = None; extern "system" { fn LoadLibraryA(lpFileName: LPCSTR) -> LPCVOID; fn FreeLibrary(dll: LPCVOID) -> BOOL; fn GetProcAddress(hModule: LPCVOID, lpProcName: LPCSTR) -> LPCVOID; } pub fn try_load_library(permanent: bool) -> ::std::result::Result<ApiType, String> { use std::ffi::CString; use std::path::Path; fn try_load(path: &Path) -> Option<LPCVOID> { let path = CString::new(format!("{}", path.display())).expect("invalid library path"); let dll = unsafe { LoadLibraryA(path.as_ptr()) }; if!dll.is_null() { Some(dll) } else { None } } fn in_global() -> Option<LPCVOID> { // modern dll name let mut dll = unsafe { LoadLibraryA(b"sciter.dll\0".as_ptr() as LPCSTR) }; if dll.is_null() { // try to load with old names let alternate = if cfg!(target_arch = "x86_64") { b"sciter64.dll\0" } else { b"sciter32.dll\0" }; dll = unsafe { LoadLibraryA(alternate.as_ptr() as LPCSTR) }; } if!dll.is_null() { Some(dll) } else { None } } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { try_load(Path::new(path)) } else { in_global() }; if let Some(dll) = dll { // get the "SciterAPI" exported symbol let sym = unsafe { GetProcAddress(dll, b"SciterAPI\0".as_ptr() as LPCSTR) }; if sym.is_null() { return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned()); } if!permanent { unsafe { FreeLibrary(dll) }; return Ok(0 as ApiType); } let get_api: FuncType = unsafe { std::mem::transmute(sym) }; return Ok(get_api()); } let sdkbin = if cfg!(target_arch = "x86_64") { "bin/64" } else { "bin/32" }; let msg = format!("Please verify that Sciter SDK is installed and its binaries (from SDK/{}) are available in PATH.", sdkbin); Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n {}", "sciter.dll", msg)) } pub unsafe fn SciterAPI() -> *const ISciterAPI { match try_load_library(true) { Ok(api) => api, Err(error) => panic!("{}", error), } } } #[cfg(all(feature = "dynamic", unix))] mod ext { #![allow(non_snake_case, non_camel_case_types)] extern crate libc; pub static mut CUSTOM_DLL_PATH: Option<String> = None; #[cfg(target_os = "linux")] const DLL_NAMES: &[&str] = &[ "libsciter-gtk.so" ]; // "libsciter.dylib" since Sciter 4.4.6.3. #[cfg(target_os = "macos")] const DLL_NAMES: &[&str] = &[ "libsciter.dylib", "sciter-osx-64.dylib" ]; use capi::scapi::ISciterAPI; use capi::sctypes::{LPVOID, LPCSTR}; type FuncType = extern "system" fn () -> *const ISciterAPI; type ApiType = *const ISciterAPI; pub fn try_load_library(permanent: bool) -> ::std::result::Result<ApiType, String> { use std::ffi::CString; use std::os::unix::ffi::OsStrExt; use std::path::{Path}; // Try to load the library from a specified absolute path. fn try_load(path: &Path) -> Option<LPVOID> { let bytes = path.as_os_str().as_bytes(); if let Ok(cstr) = CString::new(bytes) { let dll = unsafe { libc::dlopen(cstr.as_ptr(), libc::RTLD_LOCAL | libc::RTLD_LAZY) }; if!dll.is_null() { return Some(dll) } } None } // Try to find a library (by one of its names) in a specified path. fn try_load_from(dir: Option<&Path>) -> Option<LPVOID> { let dll = DLL_NAMES.iter() .map(|name| { let mut path = dir.map(Path::to_owned).unwrap_or_default(); path.push(name); path }) .map(|path| try_load(&path)) .find(|dll| dll.is_some()) .map(|o| o.unwrap()); if dll.is_some() { return dll; } None } // Try to load from the current directory. fn in_current_dir() -> Option<LPVOID> { if let Ok(dir) = ::std::env::current_exe() { if let Some(dir) = dir.parent() { let dll = try_load_from(Some(dir)); if dll.is_some() { return dll; } if cfg!(target_os = "macos") { // "(bundle folder)/Contents/Frameworks/" let mut path = dir.to_owned(); path.push("../Frameworks/libsciter.dylib"); let dll = try_load(&path); if dll.is_some() { return dll; } let mut path = dir.to_owned(); path.push("../Frameworks/sciter-osx-64.dylib"); let dll = try_load(&path); if dll.is_some() { return dll; } } } } None } // Try to load indirectly via `dlopen("dll.so")`. fn in_global() -> Option<LPVOID> { try_load_from(None) } // Try to find in $PATH. fn in_paths() -> Option<LPVOID> { use std::env; if let Some(paths) = env::var_os("PATH") { for path in env::split_paths(&paths) { if let Some(dll) = try_load_from(Some(&path)) { return Some(dll); } } } None } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { try_load(Path::new(path)) } else { in_current_dir().or_else(in_paths).or_else(in_global) }; if let Some(dll) = dll { // get the "SciterAPI" exported symbol let sym = unsafe { libc::dlsym(dll, b"SciterAPI\0".as_ptr() as LPCSTR) }; if sym.is_null() { return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned()); } if!permanent { unsafe { libc::dlclose(dll) }; return Ok(0 as ApiType); } let get_api: FuncType = unsafe { std::mem::transmute(sym) }; return Ok(get_api()); } let sdkbin = if cfg!(target_os = "macos") { "bin.osx" } else { "bin.lnx" }; let msg = format!("Please verify that Sciter SDK is installed and its binaries (from {}) are available in PATH.", sdkbin); Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n {}", DLL_NAMES[0], msg)) } pub fn SciterAPI() -> *const ISciterAPI { match try_load_library(true) { Ok(api) => api, Err(error) => panic!("{}", error), } } } #[cfg(all(target_os = "linux", not(feature = "dynamic")))] mod ext { // Note: // Since 4.1.4 library name has been changed to "libsciter-gtk" (without 32/64 suffix). // Since 3.3.1.6 library name was changed to "libsciter". // However CC requires `-l sciter` form. #[link(name = "sciter-gtk")] extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI; } } #[cfg(all(target_os = "macos", target_arch = "x86_64", not(feature = "dynamic")))] mod ext { #[link(name = "libsciter", kind = "dylib")] extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI; } } /// Getting ISciterAPI reference, can be used for manual API calling. #[doc(hidden)] #[allow(non_snake_case)] pub fn SciterAPI<'a>() -> &'a ISciterAPI { let ap = unsafe { if cfg!(feature="extension") { // TODO: it's not good to raise a panic inside `lazy_static!`, // because it wents into recursive panicing. // // Somehow, `cargo test --all` tests all the features, // also sometimes it comes even without `cfg!(test)`. // Well, the culprit is "examples/extensions" which uses the "extension" feature, // but how on earth it builds without `cfg(test)`? // if cfg!(test) { &*ext::SciterAPI() } else { EXT_API //.or_else(|| Some(&*ext::SciterAPI())) .expect("Sciter API is not available yet, call `sciter::set_api()` first.") } } else { &*ext::SciterAPI() } }; let abi_version = ap.version; if cfg!(feature = "windowless") { assert!(abi_version >= 0x0001_0001, "Incompatible Sciter build and \"windowless\" feature"); } if cfg!(not(feature = "windowless")) { assert!(abi_version < 0x0001_0000, "Incompatible Sciter build and \"windowless\" feature"); } return ap; } /// Getting ISciterAPI reference, can be used for manual API calling. /// /// Bypasses ABI compatability checks. #[doc(hidden)] #[allow(non_snake_case)] pub fn SciterAPI_unchecked<'a>() -> &'a ISciterAPI { let ap = unsafe { if cfg!(feature="extension") { EXT_API.expect("Sciter API is not available yet, call `sciter::set_api()` first.") } else { &*ext::SciterAPI() } }; return ap; } lazy_static! { static ref _API: &'static ISciterAPI = SciterAPI(); static ref _GAPI: &'static SciterGraphicsAPI = { if version_num() < 0x0401_0A00 { panic!("Graphics API is incompatible since 4.1.10 (your version is {})", version()); } unsafe { &*(SciterAPI().GetSciterGraphicsAPI)() } }; static ref _RAPI: &'static SciterRequestAPI = unsafe { &*(SciterAPI().GetSciterRequestAPI)() }; } /// Set a custom path to the Sciter dynamic library. /// /// Note: Must be called first before any other function. /// /// Returns error if the specified library can not be loaded. /// /// # Example /// /// ```rust /// if sciter::set_library("~/lib/sciter/bin.gtk/x64/libsciter-gtk.so").is_ok() { /// println!("loaded Sciter version {}", sciter::version()); /// } /// ``` pub fn set_library(custom_path: &str) -> ::std::result::Result<(), String> { #[cfg(not(feature = "dynamic"))] fn set_impl(_: &str) -> ::std::result::Result<(), String> { Err("Don't use `sciter::set_library()` in static builds.\n Build with the feature \"dynamic\" instead.".to_owned()) } #[cfg(feature = "dynamic")] fn set_impl(path: &str) -> ::std::result::Result<(), String> { unsafe { ext::CUSTOM_DLL_PATH = Some(path.to_owned()); } ext::try_load_library(false).map(|_| ()) } set_impl(custom_path) } static mut EXT_API: Option<&'static ISciterAPI> = None; /// Set the Sciter API coming from `SciterLibraryInit`. /// /// Note: Must be called first before any other function. pub fn set_host_api(api: &'static ISciterAPI) { if cfg!(feature="extension") { unsafe { EXT_API.replace(api); } } } /// Sciter engine version number (e.g. `0x03030200`). /// /// Note: does not return the `build` part because it doesn't fit in `0..255` byte range. /// Use [`sciter::version()`](fn.version.html) instead which returns the complete version string. pub fn version_num() -> u32 { use types::BOOL; let v1 = (_API.SciterVersion)(true as BOOL); let v2 = (_API.SciterVersion)(false as BOOL); let (major, minor, revision, _build) = (v1 >> 16 & 0xFF, v1 & 0xFF, v2 >> 16 & 0xFF, v2 & 0xFF); let num = (major << 24) | (minor << 16) | (revision << 8); // let num = ((v1 >> 16) << 24) | ((v1 & 0xFFFF) << 16) | ((v2 >> 16) << 8) | (v2 & 0xFFFF); return num; } /// Sciter engine version string (e.g. "`3.3.2.0`"). pub fn version() -> String { use types::BOOL; let v1 = (_API.SciterVersion)(true as BOOL); let v2 = (_API.SciterVersion)(false as BOOL); let num = [v1 >> 16, v1 & 0xFFFF, v2 >> 16, v2 & 0xFFFF]; let version = format!("{}.{}.{}.{}", num[0], num[1], num[2], num[3]); return version; } /// Sciter API version. /// /// Returns: /// /// * `0x0000_0001` for regular builds, `0x0001_0001` for windowless builds. /// * `0x0000_0002` since 4.4.2.14 (a breaking change in assets with [SOM builds](https://sciter.com/native-code-exposure-to-script/)) /// * `0x0000_0003` since 4.4.2.16 /// * `0x0000_0004` since 4.4.2.17 (a breaking change in SOM passport) /// * `0x0000_0005` since 4.4.3.20 (a breaking change in `INITIALIZATION_PARAMS`, SOM in event handlers fix) /// * `0x0000_0006` since 4.4.3.24 (TIScript native API is gone, use SOM instead) /// * `0x0000_0007` since 4.4.5.4 (DOM-Value conversion functions were added, no breaking change) /// * `0x0000_0008` since 4.4.6.7 (Sciter and Sciter.Lite are unified in ISciterAPI) /// * `0x0000_0009` since 4.4.7.0 (ISciterAPI unification between all platforms) /// /// Since 4.4.0.3. pub fn api_version() -> u32 { _API.version } /// Returns true for windowless builds. pub fn is_windowless() -> bool { api_version() >= 0x0001_0001 } /// Various global Sciter engine options. /// /// Used by [`sciter::set_options()`](fn.set_options.html). /// /// See also [per-window options](window/enum.Options.html). #[derive(Copy, Clone)] pub enum RuntimeOptions<'a> { /// global; value: the full path to the Sciter dynamic library (dll/dylib/so), /// must be called before any other Sciter function. LibraryPath(&'a str), /// global; value: [`GFX_LAYER`](enum.GFX_LAYER.html), must be called before any window creation. GfxLayer(GFX_LAYER), /// global; value: `true` - the engine will use a "unisex" theme that is common for all platforms. /// That UX theme is not using OS primitives for rendering input elements. /// Use it if you want exactly the same (modulo fonts) look-n-feel on all platforms. UxTheming(bool), /// global or per-window; enables Sciter Inspector for all windows, must be called before any window creation. DebugMode(bool), /// global or per-window; value: combination of [`SCRIPT_RUNTIME_FEATURES`](enum.SCRIPT_RUNTIME_FEATURES.html) flags. /// /// Note that these features have been disabled by default /// since [4.2.5.0](https://rawgit.com/c-smile/sciter-sdk/7036a9c7912ac30d9f369d9abb87b278d2d54c6d/logfile.htm). ScriptFeatures(u8), /// global; value: milliseconds, connection timeout of http client. ConnectionTimeout(u32), /// global; value: `0` - drop connection, `1` - use builtin dialog, `2` - accept connection silently. OnHttpsError(u8), // global; value: json with GPU black list, see the `gpu-blacklist.json` resource. // Not used in Sciter 4, in fact: https://sciter.com/forums/topic/how-to-use-the-gpu-blacklist/#post-59338 // GpuBlacklist(&'a str), /// global; value: script source to be loaded into each view before any other script execution. InitScript(&'a str), /// global; value - max request length in megabytes (1024*1024 bytes), since 4.3.0.15. MaxHttpDataLength(usize), /// global or per-window; value: `true` - `1px` in CSS is treated as `1dip`, otherwise `1px` is a physical pixel (by default). /// /// since [4.4.5.0](https://rawgit.com/c-smile/sciter-sdk/aafb625bb0bc317d79c0a14d02b5730f6a02b48a/logfile.htm). LogicalPixel(bool), } /// Set various global Sciter engine options, see the [`RuntimeOptions`](enum.RuntimeOptions.html). pub fn set_options(options: RuntimeOptions) -> std::result::Result<(), ()> { use RuntimeOptions::*; use capi::scdef::SCITER_RT_OPTIONS::*; let (option, value) = match options { ConnectionTimeout(ms) => (SCITER_CONNECTION_TIMEOUT, ms as usize), OnHttpsError(behavior) => (SCITER_HTTPS_ERROR, behavior as usize), // GpuBlacklist(json) => (SCITER_SET_GPU_BLACKLIST, json.as_bytes().as_ptr() as usize), InitScript(script) => (SCITER_SET_INIT_SCRIPT, script.as_bytes().as_ptr() as usize), ScriptFeatures(mask) => (SCITER_SET_SCRIPT_RUNTIME_FEATURES, mask as usize), GfxLayer(backend) => (SCITER_SET_GFX_LAYER, backend as usize), DebugMode(enable) => (SCITER_SET_DEBUG_MODE, enable as usize), UxTheming(enable) => (SCITER_SET_UX_THEMING, enable as usize), MaxHttpDataLength(value) => (SCITER_SET_MAX_HTTP_DATA_LENGTH, value), LogicalPixel(enable) => (SCITER_SET_PX_AS_DIP, enable as usize), LibraryPath(path) => { return set_library(path).map_err(|_|()); } }; let ok = (_API.SciterSetOption)(std::ptr::null_mut(), option, value); if ok!= 0 { Ok(()) } else { Err(()) } } /// Set a global variable by its path to all windows. /// /// This variable will be accessible in all windows via `globalThis[path]` or just `path`. /// /// Note that this call affects only _new_ windows, /// so it's preferred to call it before the main window creation. /// /// See also per-window [`Window::set_variable`](window/struct.Window.html#method.set_variable) /// to assign a global to a single window only. pub fn set_variable(path: &str, value: Value) -> dom::Result<()>
/// Get a global variable by its path. /// /// See the per-window [`Window::get_variable`](window/struct.Window.html#method.get_variable). #[doc(hidden)] pub fn get_variable(path: &str) -> dom::Result<Value> { let ws = s2u!(path); let mut value = Value::new(); let ok = (_API.SciterGetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_mut_ptr()); if ok == dom::SCDOM_RESULT::OK { Ok(value) } else { Err(ok) } }
{ let ws = s2u!(path); let ok = (_API.SciterSetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_cptr()); if ok == dom::SCDOM_RESULT::OK { Ok(()) } else { Err(ok) } }
identifier_body
lib.rs
// This component uses Sciter Engine, // copyright Terra Informatica Software, Inc. // (http://terrainformatica.com/). /*! # Rust bindings library for Sciter engine. [Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine with GPU accelerated rendering designed to render modern desktop application UI. It's a compact, single dll/dylib/so file (4-8 mb) engine without any additional dependencies. Check the [screenshot gallery](https://github.com/oskca/sciter#sciter-desktop-ui-examples) of the desktop UI examples. Sciter supports all standard elements defined in HTML5 specification [with some additions](https://sciter.com/developers/for-web-programmers/). CSS is extended to better support the Desktop UI development, e.g. flow and flex units, vertical and horizontal alignment, OS theming. [Sciter SDK](https://sciter.com/download/) comes with a demo "browser" with builtin DOM inspector, script debugger and documentation viewer: ![Sciter tools](https://sciter.com/images/sciter-tools.png) Check <https://sciter.com> website and its [documentation resources](https://sciter.com/developers/) for engine principles, architecture and more. ## Brief look: Here is a minimal sciter app: ```no_run extern crate sciter; fn main() { let mut frame = sciter::Window::new(); frame.load_file("minimal.htm"); frame.run_app(); } ``` It looks similar like this: ![Minimal sciter sample](https://i.imgur.com/ojcM5JJ.png) Check [rust-sciter/examples](https://github.com/sciter-sdk/rust-sciter/tree/master/examples) folder for more complex usage and module-level sections for the guides about: * [Window](window/index.html) creation. * [Behaviors](dom/event/index.html) and event handling. * [DOM](dom/index.html) access methods. * Sciter [Value](value/index.html) interface. */ #![doc(html_logo_url = "https://sciter.com/screenshots/slide-sciter-osx.png", html_favicon_url = "https://sciter.com/wp-content/themes/sciter/!images/favicon.ico")] // documentation test: // #![warn(missing_docs)] /* Clippy lints */ #![allow(clippy::needless_return, clippy::let_and_return)] // past habits #![allow(clippy::redundant_field_names)] // since Rust 1.17 and less readable #![allow(clippy::unreadable_literal)] // C++ SDK constants #![allow(clippy::upper_case_acronyms)]// C++ SDK constants #![allow(clippy::deprecated_semver)] // `#[deprecated(since="Sciter 4.4.3.24")]` is not a semver format. #![allow(clippy::result_unit_err)] // Sciter returns BOOL, but `Result<(), ()>` is more strict even without error description. // #![allow(clippy::cast_ptr_alignment)] // 0.0.195 only /* Macros */ #[cfg(target_os = "macos")] #[macro_use] extern crate objc; #[macro_use] extern crate lazy_static; #[macro_use] pub mod macros; mod capi; #[doc(hidden)] pub use capi::scdom::{HELEMENT}; pub use capi::scdef::{GFX_LAYER, SCRIPT_RUNTIME_FEATURES}; /* Rust interface */ mod platform; mod eventhandler; pub mod dom; pub mod graphics; pub mod host; pub mod om; pub mod request; pub mod types; pub mod utf; pub mod value; pub mod video; pub mod window; pub mod windowless; pub use dom::Element; pub use dom::event::EventHandler; pub use host::{Archive, Host, HostHandler}; pub use value::{Value, FromValue}; pub use window::Window; /// Builder pattern for window creation. See [`window::Builder`](window/struct.Builder.html) documentation. /// /// For example, /// /// ```rust,no_run /// let mut frame = sciter::WindowBuilder::main_window() /// .with_size((800,600)) /// .glassy() /// .fixed() /// .create(); /// ``` pub type WindowBuilder = window::Builder; /* Loader */ pub use capi::scapi::{ISciterAPI}; use capi::scgraphics::SciterGraphicsAPI; use capi::screquest::SciterRequestAPI; #[cfg(windows)] mod ext { // Note: // Sciter 4.x shipped with universal "sciter.dll" library for different builds: // bin/32, bin/64, bin/skia32, bin/skia64 // However it is quite inconvenient now (e.g. we can not put x64 and x86 builds in %PATH%) // #![allow(non_snake_case, non_camel_case_types)] use capi::scapi::{ISciterAPI}; use capi::sctypes::{LPCSTR, LPCVOID, BOOL}; type ApiType = *const ISciterAPI; type FuncType = extern "system" fn () -> *const ISciterAPI; pub static mut CUSTOM_DLL_PATH: Option<String> = None; extern "system" { fn LoadLibraryA(lpFileName: LPCSTR) -> LPCVOID; fn FreeLibrary(dll: LPCVOID) -> BOOL; fn GetProcAddress(hModule: LPCVOID, lpProcName: LPCSTR) -> LPCVOID; } pub fn
(permanent: bool) -> ::std::result::Result<ApiType, String> { use std::ffi::CString; use std::path::Path; fn try_load(path: &Path) -> Option<LPCVOID> { let path = CString::new(format!("{}", path.display())).expect("invalid library path"); let dll = unsafe { LoadLibraryA(path.as_ptr()) }; if!dll.is_null() { Some(dll) } else { None } } fn in_global() -> Option<LPCVOID> { // modern dll name let mut dll = unsafe { LoadLibraryA(b"sciter.dll\0".as_ptr() as LPCSTR) }; if dll.is_null() { // try to load with old names let alternate = if cfg!(target_arch = "x86_64") { b"sciter64.dll\0" } else { b"sciter32.dll\0" }; dll = unsafe { LoadLibraryA(alternate.as_ptr() as LPCSTR) }; } if!dll.is_null() { Some(dll) } else { None } } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { try_load(Path::new(path)) } else { in_global() }; if let Some(dll) = dll { // get the "SciterAPI" exported symbol let sym = unsafe { GetProcAddress(dll, b"SciterAPI\0".as_ptr() as LPCSTR) }; if sym.is_null() { return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned()); } if!permanent { unsafe { FreeLibrary(dll) }; return Ok(0 as ApiType); } let get_api: FuncType = unsafe { std::mem::transmute(sym) }; return Ok(get_api()); } let sdkbin = if cfg!(target_arch = "x86_64") { "bin/64" } else { "bin/32" }; let msg = format!("Please verify that Sciter SDK is installed and its binaries (from SDK/{}) are available in PATH.", sdkbin); Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n {}", "sciter.dll", msg)) } pub unsafe fn SciterAPI() -> *const ISciterAPI { match try_load_library(true) { Ok(api) => api, Err(error) => panic!("{}", error), } } } #[cfg(all(feature = "dynamic", unix))] mod ext { #![allow(non_snake_case, non_camel_case_types)] extern crate libc; pub static mut CUSTOM_DLL_PATH: Option<String> = None; #[cfg(target_os = "linux")] const DLL_NAMES: &[&str] = &[ "libsciter-gtk.so" ]; // "libsciter.dylib" since Sciter 4.4.6.3. #[cfg(target_os = "macos")] const DLL_NAMES: &[&str] = &[ "libsciter.dylib", "sciter-osx-64.dylib" ]; use capi::scapi::ISciterAPI; use capi::sctypes::{LPVOID, LPCSTR}; type FuncType = extern "system" fn () -> *const ISciterAPI; type ApiType = *const ISciterAPI; pub fn try_load_library(permanent: bool) -> ::std::result::Result<ApiType, String> { use std::ffi::CString; use std::os::unix::ffi::OsStrExt; use std::path::{Path}; // Try to load the library from a specified absolute path. fn try_load(path: &Path) -> Option<LPVOID> { let bytes = path.as_os_str().as_bytes(); if let Ok(cstr) = CString::new(bytes) { let dll = unsafe { libc::dlopen(cstr.as_ptr(), libc::RTLD_LOCAL | libc::RTLD_LAZY) }; if!dll.is_null() { return Some(dll) } } None } // Try to find a library (by one of its names) in a specified path. fn try_load_from(dir: Option<&Path>) -> Option<LPVOID> { let dll = DLL_NAMES.iter() .map(|name| { let mut path = dir.map(Path::to_owned).unwrap_or_default(); path.push(name); path }) .map(|path| try_load(&path)) .find(|dll| dll.is_some()) .map(|o| o.unwrap()); if dll.is_some() { return dll; } None } // Try to load from the current directory. fn in_current_dir() -> Option<LPVOID> { if let Ok(dir) = ::std::env::current_exe() { if let Some(dir) = dir.parent() { let dll = try_load_from(Some(dir)); if dll.is_some() { return dll; } if cfg!(target_os = "macos") { // "(bundle folder)/Contents/Frameworks/" let mut path = dir.to_owned(); path.push("../Frameworks/libsciter.dylib"); let dll = try_load(&path); if dll.is_some() { return dll; } let mut path = dir.to_owned(); path.push("../Frameworks/sciter-osx-64.dylib"); let dll = try_load(&path); if dll.is_some() { return dll; } } } } None } // Try to load indirectly via `dlopen("dll.so")`. fn in_global() -> Option<LPVOID> { try_load_from(None) } // Try to find in $PATH. fn in_paths() -> Option<LPVOID> { use std::env; if let Some(paths) = env::var_os("PATH") { for path in env::split_paths(&paths) { if let Some(dll) = try_load_from(Some(&path)) { return Some(dll); } } } None } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { try_load(Path::new(path)) } else { in_current_dir().or_else(in_paths).or_else(in_global) }; if let Some(dll) = dll { // get the "SciterAPI" exported symbol let sym = unsafe { libc::dlsym(dll, b"SciterAPI\0".as_ptr() as LPCSTR) }; if sym.is_null() { return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned()); } if!permanent { unsafe { libc::dlclose(dll) }; return Ok(0 as ApiType); } let get_api: FuncType = unsafe { std::mem::transmute(sym) }; return Ok(get_api()); } let sdkbin = if cfg!(target_os = "macos") { "bin.osx" } else { "bin.lnx" }; let msg = format!("Please verify that Sciter SDK is installed and its binaries (from {}) are available in PATH.", sdkbin); Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n {}", DLL_NAMES[0], msg)) } pub fn SciterAPI() -> *const ISciterAPI { match try_load_library(true) { Ok(api) => api, Err(error) => panic!("{}", error), } } } #[cfg(all(target_os = "linux", not(feature = "dynamic")))] mod ext { // Note: // Since 4.1.4 library name has been changed to "libsciter-gtk" (without 32/64 suffix). // Since 3.3.1.6 library name was changed to "libsciter". // However CC requires `-l sciter` form. #[link(name = "sciter-gtk")] extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI; } } #[cfg(all(target_os = "macos", target_arch = "x86_64", not(feature = "dynamic")))] mod ext { #[link(name = "libsciter", kind = "dylib")] extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI; } } /// Getting ISciterAPI reference, can be used for manual API calling. #[doc(hidden)] #[allow(non_snake_case)] pub fn SciterAPI<'a>() -> &'a ISciterAPI { let ap = unsafe { if cfg!(feature="extension") { // TODO: it's not good to raise a panic inside `lazy_static!`, // because it wents into recursive panicing. // // Somehow, `cargo test --all` tests all the features, // also sometimes it comes even without `cfg!(test)`. // Well, the culprit is "examples/extensions" which uses the "extension" feature, // but how on earth it builds without `cfg(test)`? // if cfg!(test) { &*ext::SciterAPI() } else { EXT_API //.or_else(|| Some(&*ext::SciterAPI())) .expect("Sciter API is not available yet, call `sciter::set_api()` first.") } } else { &*ext::SciterAPI() } }; let abi_version = ap.version; if cfg!(feature = "windowless") { assert!(abi_version >= 0x0001_0001, "Incompatible Sciter build and \"windowless\" feature"); } if cfg!(not(feature = "windowless")) { assert!(abi_version < 0x0001_0000, "Incompatible Sciter build and \"windowless\" feature"); } return ap; } /// Getting ISciterAPI reference, can be used for manual API calling. /// /// Bypasses ABI compatability checks. #[doc(hidden)] #[allow(non_snake_case)] pub fn SciterAPI_unchecked<'a>() -> &'a ISciterAPI { let ap = unsafe { if cfg!(feature="extension") { EXT_API.expect("Sciter API is not available yet, call `sciter::set_api()` first.") } else { &*ext::SciterAPI() } }; return ap; } lazy_static! { static ref _API: &'static ISciterAPI = SciterAPI(); static ref _GAPI: &'static SciterGraphicsAPI = { if version_num() < 0x0401_0A00 { panic!("Graphics API is incompatible since 4.1.10 (your version is {})", version()); } unsafe { &*(SciterAPI().GetSciterGraphicsAPI)() } }; static ref _RAPI: &'static SciterRequestAPI = unsafe { &*(SciterAPI().GetSciterRequestAPI)() }; } /// Set a custom path to the Sciter dynamic library. /// /// Note: Must be called first before any other function. /// /// Returns error if the specified library can not be loaded. /// /// # Example /// /// ```rust /// if sciter::set_library("~/lib/sciter/bin.gtk/x64/libsciter-gtk.so").is_ok() { /// println!("loaded Sciter version {}", sciter::version()); /// } /// ``` pub fn set_library(custom_path: &str) -> ::std::result::Result<(), String> { #[cfg(not(feature = "dynamic"))] fn set_impl(_: &str) -> ::std::result::Result<(), String> { Err("Don't use `sciter::set_library()` in static builds.\n Build with the feature \"dynamic\" instead.".to_owned()) } #[cfg(feature = "dynamic")] fn set_impl(path: &str) -> ::std::result::Result<(), String> { unsafe { ext::CUSTOM_DLL_PATH = Some(path.to_owned()); } ext::try_load_library(false).map(|_| ()) } set_impl(custom_path) } static mut EXT_API: Option<&'static ISciterAPI> = None; /// Set the Sciter API coming from `SciterLibraryInit`. /// /// Note: Must be called first before any other function. pub fn set_host_api(api: &'static ISciterAPI) { if cfg!(feature="extension") { unsafe { EXT_API.replace(api); } } } /// Sciter engine version number (e.g. `0x03030200`). /// /// Note: does not return the `build` part because it doesn't fit in `0..255` byte range. /// Use [`sciter::version()`](fn.version.html) instead which returns the complete version string. pub fn version_num() -> u32 { use types::BOOL; let v1 = (_API.SciterVersion)(true as BOOL); let v2 = (_API.SciterVersion)(false as BOOL); let (major, minor, revision, _build) = (v1 >> 16 & 0xFF, v1 & 0xFF, v2 >> 16 & 0xFF, v2 & 0xFF); let num = (major << 24) | (minor << 16) | (revision << 8); // let num = ((v1 >> 16) << 24) | ((v1 & 0xFFFF) << 16) | ((v2 >> 16) << 8) | (v2 & 0xFFFF); return num; } /// Sciter engine version string (e.g. "`3.3.2.0`"). pub fn version() -> String { use types::BOOL; let v1 = (_API.SciterVersion)(true as BOOL); let v2 = (_API.SciterVersion)(false as BOOL); let num = [v1 >> 16, v1 & 0xFFFF, v2 >> 16, v2 & 0xFFFF]; let version = format!("{}.{}.{}.{}", num[0], num[1], num[2], num[3]); return version; } /// Sciter API version. /// /// Returns: /// /// * `0x0000_0001` for regular builds, `0x0001_0001` for windowless builds. /// * `0x0000_0002` since 4.4.2.14 (a breaking change in assets with [SOM builds](https://sciter.com/native-code-exposure-to-script/)) /// * `0x0000_0003` since 4.4.2.16 /// * `0x0000_0004` since 4.4.2.17 (a breaking change in SOM passport) /// * `0x0000_0005` since 4.4.3.20 (a breaking change in `INITIALIZATION_PARAMS`, SOM in event handlers fix) /// * `0x0000_0006` since 4.4.3.24 (TIScript native API is gone, use SOM instead) /// * `0x0000_0007` since 4.4.5.4 (DOM-Value conversion functions were added, no breaking change) /// * `0x0000_0008` since 4.4.6.7 (Sciter and Sciter.Lite are unified in ISciterAPI) /// * `0x0000_0009` since 4.4.7.0 (ISciterAPI unification between all platforms) /// /// Since 4.4.0.3. pub fn api_version() -> u32 { _API.version } /// Returns true for windowless builds. pub fn is_windowless() -> bool { api_version() >= 0x0001_0001 } /// Various global Sciter engine options. /// /// Used by [`sciter::set_options()`](fn.set_options.html). /// /// See also [per-window options](window/enum.Options.html). #[derive(Copy, Clone)] pub enum RuntimeOptions<'a> { /// global; value: the full path to the Sciter dynamic library (dll/dylib/so), /// must be called before any other Sciter function. LibraryPath(&'a str), /// global; value: [`GFX_LAYER`](enum.GFX_LAYER.html), must be called before any window creation. GfxLayer(GFX_LAYER), /// global; value: `true` - the engine will use a "unisex" theme that is common for all platforms. /// That UX theme is not using OS primitives for rendering input elements. /// Use it if you want exactly the same (modulo fonts) look-n-feel on all platforms. UxTheming(bool), /// global or per-window; enables Sciter Inspector for all windows, must be called before any window creation. DebugMode(bool), /// global or per-window; value: combination of [`SCRIPT_RUNTIME_FEATURES`](enum.SCRIPT_RUNTIME_FEATURES.html) flags. /// /// Note that these features have been disabled by default /// since [4.2.5.0](https://rawgit.com/c-smile/sciter-sdk/7036a9c7912ac30d9f369d9abb87b278d2d54c6d/logfile.htm). ScriptFeatures(u8), /// global; value: milliseconds, connection timeout of http client. ConnectionTimeout(u32), /// global; value: `0` - drop connection, `1` - use builtin dialog, `2` - accept connection silently. OnHttpsError(u8), // global; value: json with GPU black list, see the `gpu-blacklist.json` resource. // Not used in Sciter 4, in fact: https://sciter.com/forums/topic/how-to-use-the-gpu-blacklist/#post-59338 // GpuBlacklist(&'a str), /// global; value: script source to be loaded into each view before any other script execution. InitScript(&'a str), /// global; value - max request length in megabytes (1024*1024 bytes), since 4.3.0.15. MaxHttpDataLength(usize), /// global or per-window; value: `true` - `1px` in CSS is treated as `1dip`, otherwise `1px` is a physical pixel (by default). /// /// since [4.4.5.0](https://rawgit.com/c-smile/sciter-sdk/aafb625bb0bc317d79c0a14d02b5730f6a02b48a/logfile.htm). LogicalPixel(bool), } /// Set various global Sciter engine options, see the [`RuntimeOptions`](enum.RuntimeOptions.html). pub fn set_options(options: RuntimeOptions) -> std::result::Result<(), ()> { use RuntimeOptions::*; use capi::scdef::SCITER_RT_OPTIONS::*; let (option, value) = match options { ConnectionTimeout(ms) => (SCITER_CONNECTION_TIMEOUT, ms as usize), OnHttpsError(behavior) => (SCITER_HTTPS_ERROR, behavior as usize), // GpuBlacklist(json) => (SCITER_SET_GPU_BLACKLIST, json.as_bytes().as_ptr() as usize), InitScript(script) => (SCITER_SET_INIT_SCRIPT, script.as_bytes().as_ptr() as usize), ScriptFeatures(mask) => (SCITER_SET_SCRIPT_RUNTIME_FEATURES, mask as usize), GfxLayer(backend) => (SCITER_SET_GFX_LAYER, backend as usize), DebugMode(enable) => (SCITER_SET_DEBUG_MODE, enable as usize), UxTheming(enable) => (SCITER_SET_UX_THEMING, enable as usize), MaxHttpDataLength(value) => (SCITER_SET_MAX_HTTP_DATA_LENGTH, value), LogicalPixel(enable) => (SCITER_SET_PX_AS_DIP, enable as usize), LibraryPath(path) => { return set_library(path).map_err(|_|()); } }; let ok = (_API.SciterSetOption)(std::ptr::null_mut(), option, value); if ok!= 0 { Ok(()) } else { Err(()) } } /// Set a global variable by its path to all windows. /// /// This variable will be accessible in all windows via `globalThis[path]` or just `path`. /// /// Note that this call affects only _new_ windows, /// so it's preferred to call it before the main window creation. /// /// See also per-window [`Window::set_variable`](window/struct.Window.html#method.set_variable) /// to assign a global to a single window only. pub fn set_variable(path: &str, value: Value) -> dom::Result<()> { let ws = s2u!(path); let ok = (_API.SciterSetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_cptr()); if ok == dom::SCDOM_RESULT::OK { Ok(()) } else { Err(ok) } } /// Get a global variable by its path. /// /// See the per-window [`Window::get_variable`](window/struct.Window.html#method.get_variable). #[doc(hidden)] pub fn get_variable(path: &str) -> dom::Result<Value> { let ws = s2u!(path); let mut value = Value::new(); let ok = (_API.SciterGetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_mut_ptr()); if ok == dom::SCDOM_RESULT::OK { Ok(value) } else { Err(ok) } }
try_load_library
identifier_name
lib.rs
// This component uses Sciter Engine, // copyright Terra Informatica Software, Inc. // (http://terrainformatica.com/). /*! # Rust bindings library for Sciter engine. [Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine with GPU accelerated rendering designed to render modern desktop application UI. It's a compact, single dll/dylib/so file (4-8 mb) engine without any additional dependencies. Check the [screenshot gallery](https://github.com/oskca/sciter#sciter-desktop-ui-examples) of the desktop UI examples. Sciter supports all standard elements defined in HTML5 specification [with some additions](https://sciter.com/developers/for-web-programmers/). CSS is extended to better support the Desktop UI development, e.g. flow and flex units, vertical and horizontal alignment, OS theming. [Sciter SDK](https://sciter.com/download/) comes with a demo "browser" with builtin DOM inspector, script debugger and documentation viewer: ![Sciter tools](https://sciter.com/images/sciter-tools.png) Check <https://sciter.com> website and its [documentation resources](https://sciter.com/developers/) for engine principles, architecture and more. ## Brief look: Here is a minimal sciter app: ```no_run extern crate sciter; fn main() { let mut frame = sciter::Window::new(); frame.load_file("minimal.htm"); frame.run_app(); } ``` It looks similar like this: ![Minimal sciter sample](https://i.imgur.com/ojcM5JJ.png) Check [rust-sciter/examples](https://github.com/sciter-sdk/rust-sciter/tree/master/examples) folder for more complex usage and module-level sections for the guides about: * [Window](window/index.html) creation. * [Behaviors](dom/event/index.html) and event handling. * [DOM](dom/index.html) access methods. * Sciter [Value](value/index.html) interface. */ #![doc(html_logo_url = "https://sciter.com/screenshots/slide-sciter-osx.png", html_favicon_url = "https://sciter.com/wp-content/themes/sciter/!images/favicon.ico")] // documentation test: // #![warn(missing_docs)] /* Clippy lints */ #![allow(clippy::needless_return, clippy::let_and_return)] // past habits #![allow(clippy::redundant_field_names)] // since Rust 1.17 and less readable #![allow(clippy::unreadable_literal)] // C++ SDK constants #![allow(clippy::upper_case_acronyms)]// C++ SDK constants #![allow(clippy::deprecated_semver)] // `#[deprecated(since="Sciter 4.4.3.24")]` is not a semver format. #![allow(clippy::result_unit_err)] // Sciter returns BOOL, but `Result<(), ()>` is more strict even without error description. // #![allow(clippy::cast_ptr_alignment)] // 0.0.195 only /* Macros */ #[cfg(target_os = "macos")] #[macro_use] extern crate objc; #[macro_use] extern crate lazy_static; #[macro_use] pub mod macros; mod capi; #[doc(hidden)] pub use capi::scdom::{HELEMENT}; pub use capi::scdef::{GFX_LAYER, SCRIPT_RUNTIME_FEATURES}; /* Rust interface */ mod platform; mod eventhandler; pub mod dom; pub mod graphics; pub mod host; pub mod om; pub mod request; pub mod types; pub mod utf; pub mod value; pub mod video; pub mod window; pub mod windowless; pub use dom::Element; pub use dom::event::EventHandler; pub use host::{Archive, Host, HostHandler}; pub use value::{Value, FromValue}; pub use window::Window; /// Builder pattern for window creation. See [`window::Builder`](window/struct.Builder.html) documentation. /// /// For example, /// /// ```rust,no_run /// let mut frame = sciter::WindowBuilder::main_window() /// .with_size((800,600)) /// .glassy() /// .fixed() /// .create(); /// ``` pub type WindowBuilder = window::Builder; /* Loader */ pub use capi::scapi::{ISciterAPI}; use capi::scgraphics::SciterGraphicsAPI; use capi::screquest::SciterRequestAPI; #[cfg(windows)] mod ext { // Note: // Sciter 4.x shipped with universal "sciter.dll" library for different builds: // bin/32, bin/64, bin/skia32, bin/skia64 // However it is quite inconvenient now (e.g. we can not put x64 and x86 builds in %PATH%) // #![allow(non_snake_case, non_camel_case_types)] use capi::scapi::{ISciterAPI}; use capi::sctypes::{LPCSTR, LPCVOID, BOOL}; type ApiType = *const ISciterAPI; type FuncType = extern "system" fn () -> *const ISciterAPI; pub static mut CUSTOM_DLL_PATH: Option<String> = None; extern "system" { fn LoadLibraryA(lpFileName: LPCSTR) -> LPCVOID; fn FreeLibrary(dll: LPCVOID) -> BOOL; fn GetProcAddress(hModule: LPCVOID, lpProcName: LPCSTR) -> LPCVOID; } pub fn try_load_library(permanent: bool) -> ::std::result::Result<ApiType, String> { use std::ffi::CString; use std::path::Path; fn try_load(path: &Path) -> Option<LPCVOID> { let path = CString::new(format!("{}", path.display())).expect("invalid library path"); let dll = unsafe { LoadLibraryA(path.as_ptr()) }; if!dll.is_null() { Some(dll) } else { None } } fn in_global() -> Option<LPCVOID> { // modern dll name let mut dll = unsafe { LoadLibraryA(b"sciter.dll\0".as_ptr() as LPCSTR) }; if dll.is_null() { // try to load with old names let alternate = if cfg!(target_arch = "x86_64") { b"sciter64.dll\0" } else { b"sciter32.dll\0" }; dll = unsafe { LoadLibraryA(alternate.as_ptr() as LPCSTR) }; } if!dll.is_null() { Some(dll) } else { None } } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { try_load(Path::new(path)) } else { in_global() }; if let Some(dll) = dll { // get the "SciterAPI" exported symbol let sym = unsafe { GetProcAddress(dll, b"SciterAPI\0".as_ptr() as LPCSTR) }; if sym.is_null() { return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned()); } if!permanent { unsafe { FreeLibrary(dll) }; return Ok(0 as ApiType); } let get_api: FuncType = unsafe { std::mem::transmute(sym) }; return Ok(get_api()); } let sdkbin = if cfg!(target_arch = "x86_64") { "bin/64" } else { "bin/32" }; let msg = format!("Please verify that Sciter SDK is installed and its binaries (from SDK/{}) are available in PATH.", sdkbin); Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n {}", "sciter.dll", msg)) } pub unsafe fn SciterAPI() -> *const ISciterAPI {
Err(error) => panic!("{}", error), } } } #[cfg(all(feature = "dynamic", unix))] mod ext { #![allow(non_snake_case, non_camel_case_types)] extern crate libc; pub static mut CUSTOM_DLL_PATH: Option<String> = None; #[cfg(target_os = "linux")] const DLL_NAMES: &[&str] = &[ "libsciter-gtk.so" ]; // "libsciter.dylib" since Sciter 4.4.6.3. #[cfg(target_os = "macos")] const DLL_NAMES: &[&str] = &[ "libsciter.dylib", "sciter-osx-64.dylib" ]; use capi::scapi::ISciterAPI; use capi::sctypes::{LPVOID, LPCSTR}; type FuncType = extern "system" fn () -> *const ISciterAPI; type ApiType = *const ISciterAPI; pub fn try_load_library(permanent: bool) -> ::std::result::Result<ApiType, String> { use std::ffi::CString; use std::os::unix::ffi::OsStrExt; use std::path::{Path}; // Try to load the library from a specified absolute path. fn try_load(path: &Path) -> Option<LPVOID> { let bytes = path.as_os_str().as_bytes(); if let Ok(cstr) = CString::new(bytes) { let dll = unsafe { libc::dlopen(cstr.as_ptr(), libc::RTLD_LOCAL | libc::RTLD_LAZY) }; if!dll.is_null() { return Some(dll) } } None } // Try to find a library (by one of its names) in a specified path. fn try_load_from(dir: Option<&Path>) -> Option<LPVOID> { let dll = DLL_NAMES.iter() .map(|name| { let mut path = dir.map(Path::to_owned).unwrap_or_default(); path.push(name); path }) .map(|path| try_load(&path)) .find(|dll| dll.is_some()) .map(|o| o.unwrap()); if dll.is_some() { return dll; } None } // Try to load from the current directory. fn in_current_dir() -> Option<LPVOID> { if let Ok(dir) = ::std::env::current_exe() { if let Some(dir) = dir.parent() { let dll = try_load_from(Some(dir)); if dll.is_some() { return dll; } if cfg!(target_os = "macos") { // "(bundle folder)/Contents/Frameworks/" let mut path = dir.to_owned(); path.push("../Frameworks/libsciter.dylib"); let dll = try_load(&path); if dll.is_some() { return dll; } let mut path = dir.to_owned(); path.push("../Frameworks/sciter-osx-64.dylib"); let dll = try_load(&path); if dll.is_some() { return dll; } } } } None } // Try to load indirectly via `dlopen("dll.so")`. fn in_global() -> Option<LPVOID> { try_load_from(None) } // Try to find in $PATH. fn in_paths() -> Option<LPVOID> { use std::env; if let Some(paths) = env::var_os("PATH") { for path in env::split_paths(&paths) { if let Some(dll) = try_load_from(Some(&path)) { return Some(dll); } } } None } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { try_load(Path::new(path)) } else { in_current_dir().or_else(in_paths).or_else(in_global) }; if let Some(dll) = dll { // get the "SciterAPI" exported symbol let sym = unsafe { libc::dlsym(dll, b"SciterAPI\0".as_ptr() as LPCSTR) }; if sym.is_null() { return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned()); } if!permanent { unsafe { libc::dlclose(dll) }; return Ok(0 as ApiType); } let get_api: FuncType = unsafe { std::mem::transmute(sym) }; return Ok(get_api()); } let sdkbin = if cfg!(target_os = "macos") { "bin.osx" } else { "bin.lnx" }; let msg = format!("Please verify that Sciter SDK is installed and its binaries (from {}) are available in PATH.", sdkbin); Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n {}", DLL_NAMES[0], msg)) } pub fn SciterAPI() -> *const ISciterAPI { match try_load_library(true) { Ok(api) => api, Err(error) => panic!("{}", error), } } } #[cfg(all(target_os = "linux", not(feature = "dynamic")))] mod ext { // Note: // Since 4.1.4 library name has been changed to "libsciter-gtk" (without 32/64 suffix). // Since 3.3.1.6 library name was changed to "libsciter". // However CC requires `-l sciter` form. #[link(name = "sciter-gtk")] extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI; } } #[cfg(all(target_os = "macos", target_arch = "x86_64", not(feature = "dynamic")))] mod ext { #[link(name = "libsciter", kind = "dylib")] extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI; } } /// Getting ISciterAPI reference, can be used for manual API calling. #[doc(hidden)] #[allow(non_snake_case)] pub fn SciterAPI<'a>() -> &'a ISciterAPI { let ap = unsafe { if cfg!(feature="extension") { // TODO: it's not good to raise a panic inside `lazy_static!`, // because it wents into recursive panicing. // // Somehow, `cargo test --all` tests all the features, // also sometimes it comes even without `cfg!(test)`. // Well, the culprit is "examples/extensions" which uses the "extension" feature, // but how on earth it builds without `cfg(test)`? // if cfg!(test) { &*ext::SciterAPI() } else { EXT_API //.or_else(|| Some(&*ext::SciterAPI())) .expect("Sciter API is not available yet, call `sciter::set_api()` first.") } } else { &*ext::SciterAPI() } }; let abi_version = ap.version; if cfg!(feature = "windowless") { assert!(abi_version >= 0x0001_0001, "Incompatible Sciter build and \"windowless\" feature"); } if cfg!(not(feature = "windowless")) { assert!(abi_version < 0x0001_0000, "Incompatible Sciter build and \"windowless\" feature"); } return ap; } /// Getting ISciterAPI reference, can be used for manual API calling. /// /// Bypasses ABI compatability checks. #[doc(hidden)] #[allow(non_snake_case)] pub fn SciterAPI_unchecked<'a>() -> &'a ISciterAPI { let ap = unsafe { if cfg!(feature="extension") { EXT_API.expect("Sciter API is not available yet, call `sciter::set_api()` first.") } else { &*ext::SciterAPI() } }; return ap; } lazy_static! { static ref _API: &'static ISciterAPI = SciterAPI(); static ref _GAPI: &'static SciterGraphicsAPI = { if version_num() < 0x0401_0A00 { panic!("Graphics API is incompatible since 4.1.10 (your version is {})", version()); } unsafe { &*(SciterAPI().GetSciterGraphicsAPI)() } }; static ref _RAPI: &'static SciterRequestAPI = unsafe { &*(SciterAPI().GetSciterRequestAPI)() }; } /// Set a custom path to the Sciter dynamic library. /// /// Note: Must be called first before any other function. /// /// Returns error if the specified library can not be loaded. /// /// # Example /// /// ```rust /// if sciter::set_library("~/lib/sciter/bin.gtk/x64/libsciter-gtk.so").is_ok() { /// println!("loaded Sciter version {}", sciter::version()); /// } /// ``` pub fn set_library(custom_path: &str) -> ::std::result::Result<(), String> { #[cfg(not(feature = "dynamic"))] fn set_impl(_: &str) -> ::std::result::Result<(), String> { Err("Don't use `sciter::set_library()` in static builds.\n Build with the feature \"dynamic\" instead.".to_owned()) } #[cfg(feature = "dynamic")] fn set_impl(path: &str) -> ::std::result::Result<(), String> { unsafe { ext::CUSTOM_DLL_PATH = Some(path.to_owned()); } ext::try_load_library(false).map(|_| ()) } set_impl(custom_path) } static mut EXT_API: Option<&'static ISciterAPI> = None; /// Set the Sciter API coming from `SciterLibraryInit`. /// /// Note: Must be called first before any other function. pub fn set_host_api(api: &'static ISciterAPI) { if cfg!(feature="extension") { unsafe { EXT_API.replace(api); } } } /// Sciter engine version number (e.g. `0x03030200`). /// /// Note: does not return the `build` part because it doesn't fit in `0..255` byte range. /// Use [`sciter::version()`](fn.version.html) instead which returns the complete version string. pub fn version_num() -> u32 { use types::BOOL; let v1 = (_API.SciterVersion)(true as BOOL); let v2 = (_API.SciterVersion)(false as BOOL); let (major, minor, revision, _build) = (v1 >> 16 & 0xFF, v1 & 0xFF, v2 >> 16 & 0xFF, v2 & 0xFF); let num = (major << 24) | (minor << 16) | (revision << 8); // let num = ((v1 >> 16) << 24) | ((v1 & 0xFFFF) << 16) | ((v2 >> 16) << 8) | (v2 & 0xFFFF); return num; } /// Sciter engine version string (e.g. "`3.3.2.0`"). pub fn version() -> String { use types::BOOL; let v1 = (_API.SciterVersion)(true as BOOL); let v2 = (_API.SciterVersion)(false as BOOL); let num = [v1 >> 16, v1 & 0xFFFF, v2 >> 16, v2 & 0xFFFF]; let version = format!("{}.{}.{}.{}", num[0], num[1], num[2], num[3]); return version; } /// Sciter API version. /// /// Returns: /// /// * `0x0000_0001` for regular builds, `0x0001_0001` for windowless builds. /// * `0x0000_0002` since 4.4.2.14 (a breaking change in assets with [SOM builds](https://sciter.com/native-code-exposure-to-script/)) /// * `0x0000_0003` since 4.4.2.16 /// * `0x0000_0004` since 4.4.2.17 (a breaking change in SOM passport) /// * `0x0000_0005` since 4.4.3.20 (a breaking change in `INITIALIZATION_PARAMS`, SOM in event handlers fix) /// * `0x0000_0006` since 4.4.3.24 (TIScript native API is gone, use SOM instead) /// * `0x0000_0007` since 4.4.5.4 (DOM-Value conversion functions were added, no breaking change) /// * `0x0000_0008` since 4.4.6.7 (Sciter and Sciter.Lite are unified in ISciterAPI) /// * `0x0000_0009` since 4.4.7.0 (ISciterAPI unification between all platforms) /// /// Since 4.4.0.3. pub fn api_version() -> u32 { _API.version } /// Returns true for windowless builds. pub fn is_windowless() -> bool { api_version() >= 0x0001_0001 } /// Various global Sciter engine options. /// /// Used by [`sciter::set_options()`](fn.set_options.html). /// /// See also [per-window options](window/enum.Options.html). #[derive(Copy, Clone)] pub enum RuntimeOptions<'a> { /// global; value: the full path to the Sciter dynamic library (dll/dylib/so), /// must be called before any other Sciter function. LibraryPath(&'a str), /// global; value: [`GFX_LAYER`](enum.GFX_LAYER.html), must be called before any window creation. GfxLayer(GFX_LAYER), /// global; value: `true` - the engine will use a "unisex" theme that is common for all platforms. /// That UX theme is not using OS primitives for rendering input elements. /// Use it if you want exactly the same (modulo fonts) look-n-feel on all platforms. UxTheming(bool), /// global or per-window; enables Sciter Inspector for all windows, must be called before any window creation. DebugMode(bool), /// global or per-window; value: combination of [`SCRIPT_RUNTIME_FEATURES`](enum.SCRIPT_RUNTIME_FEATURES.html) flags. /// /// Note that these features have been disabled by default /// since [4.2.5.0](https://rawgit.com/c-smile/sciter-sdk/7036a9c7912ac30d9f369d9abb87b278d2d54c6d/logfile.htm). ScriptFeatures(u8), /// global; value: milliseconds, connection timeout of http client. ConnectionTimeout(u32), /// global; value: `0` - drop connection, `1` - use builtin dialog, `2` - accept connection silently. OnHttpsError(u8), // global; value: json with GPU black list, see the `gpu-blacklist.json` resource. // Not used in Sciter 4, in fact: https://sciter.com/forums/topic/how-to-use-the-gpu-blacklist/#post-59338 // GpuBlacklist(&'a str), /// global; value: script source to be loaded into each view before any other script execution. InitScript(&'a str), /// global; value - max request length in megabytes (1024*1024 bytes), since 4.3.0.15. MaxHttpDataLength(usize), /// global or per-window; value: `true` - `1px` in CSS is treated as `1dip`, otherwise `1px` is a physical pixel (by default). /// /// since [4.4.5.0](https://rawgit.com/c-smile/sciter-sdk/aafb625bb0bc317d79c0a14d02b5730f6a02b48a/logfile.htm). LogicalPixel(bool), } /// Set various global Sciter engine options, see the [`RuntimeOptions`](enum.RuntimeOptions.html). pub fn set_options(options: RuntimeOptions) -> std::result::Result<(), ()> { use RuntimeOptions::*; use capi::scdef::SCITER_RT_OPTIONS::*; let (option, value) = match options { ConnectionTimeout(ms) => (SCITER_CONNECTION_TIMEOUT, ms as usize), OnHttpsError(behavior) => (SCITER_HTTPS_ERROR, behavior as usize), // GpuBlacklist(json) => (SCITER_SET_GPU_BLACKLIST, json.as_bytes().as_ptr() as usize), InitScript(script) => (SCITER_SET_INIT_SCRIPT, script.as_bytes().as_ptr() as usize), ScriptFeatures(mask) => (SCITER_SET_SCRIPT_RUNTIME_FEATURES, mask as usize), GfxLayer(backend) => (SCITER_SET_GFX_LAYER, backend as usize), DebugMode(enable) => (SCITER_SET_DEBUG_MODE, enable as usize), UxTheming(enable) => (SCITER_SET_UX_THEMING, enable as usize), MaxHttpDataLength(value) => (SCITER_SET_MAX_HTTP_DATA_LENGTH, value), LogicalPixel(enable) => (SCITER_SET_PX_AS_DIP, enable as usize), LibraryPath(path) => { return set_library(path).map_err(|_|()); } }; let ok = (_API.SciterSetOption)(std::ptr::null_mut(), option, value); if ok!= 0 { Ok(()) } else { Err(()) } } /// Set a global variable by its path to all windows. /// /// This variable will be accessible in all windows via `globalThis[path]` or just `path`. /// /// Note that this call affects only _new_ windows, /// so it's preferred to call it before the main window creation. /// /// See also per-window [`Window::set_variable`](window/struct.Window.html#method.set_variable) /// to assign a global to a single window only. pub fn set_variable(path: &str, value: Value) -> dom::Result<()> { let ws = s2u!(path); let ok = (_API.SciterSetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_cptr()); if ok == dom::SCDOM_RESULT::OK { Ok(()) } else { Err(ok) } } /// Get a global variable by its path. /// /// See the per-window [`Window::get_variable`](window/struct.Window.html#method.get_variable). #[doc(hidden)] pub fn get_variable(path: &str) -> dom::Result<Value> { let ws = s2u!(path); let mut value = Value::new(); let ok = (_API.SciterGetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_mut_ptr()); if ok == dom::SCDOM_RESULT::OK { Ok(value) } else { Err(ok) } }
match try_load_library(true) { Ok(api) => api,
random_line_split
lib.rs
use cpython::{ py_class, py_exception, py_module_initializer, ObjectProtocol, PyClone, PyDrop, PyErr, PyObject, PyResult, PySequence, PythonObject, exc::{TypeError} }; use search::Graph; use std::cell::RefCell; use std::collections::{BTreeSet, HashMap}; use std::convert::TryInto; mod search; #[cfg(feature = "python2")] pub type Int = std::os::raw::c_long; #[cfg(feature = "python3")] pub type Int = isize; // Simple utility, make a hash set out of python sequence macro_rules! hash_seq { ($py:expr, $seq:expr) => { $seq.iter($py)? .filter_map(|v| match v { Ok(v) => v.hash($py).ok(), _ => None, }) .collect() }; } // Small utility to log using python logger. macro_rules! warn { ($py:expr, $message:expr) => { $py.import("logging")? .call($py, "getLogger", ("to",), None)? .call_method($py, "warning", (&$message,), None)?; }; } ////////////////////////////////////////////////// // MODULE SETUP // NOTE: "_internal" is the name of this module after build process moves it py_module_initializer!(_internal, |py, m| { m.add(py, "__doc__", "Simple plugin based A to B function chaining. You could be wanting to convert between a chain of types, or traverse a bunch of object oriented links. If you're often thinking \"I have this, how can I get that\", then this type of solution could help. >>> conv = Conversions() >>> conv.add_conversion(1, str, [\"url\"], WebPage, [], load_webpage) >>> conv.add_revealer(str, http_revealer) # optional convenience >>> conv.convert(\"http://somewhere.html\", WebPage) ")?; m.add(py, "ConversionError", py.get_type::<ConversionError>())?; m.add_class::<Conversions>(py)?; Ok(()) }); ////////////////////////////////////////////////// ////////////////////////////////////////////////// // Exceptions py_exception!(to, ConversionError); // Triggered when errors occurred during conversion process ////////////////////////////////////////////////// py_class!(class Conversions |py| { data graph: RefCell<Graph<Int, Int, Int>>; data functions: RefCell<HashMap<Int, PyObject>>; data revealers: RefCell<HashMap<Int, Vec<PyObject>>>; def __new__(_cls) -> PyResult<Conversions> { Conversions::create_instance( py, RefCell::new(Graph::new()), RefCell::new(HashMap::new()), RefCell::new(HashMap::new()), ) } /// Add a function so it may be used as a step in the composition process later. /// Eventually a composition chain will consist of a number of these functions placed back to back. /// So the simpler, smaller and more focused the function the better. /// /// Args: /// cost (int): /// A number representing how much work this function needs to do. /// Lower numbers are prioritized. This lets the composition prefer the cheapest option. /// eg: just getting an attribute would be a low number. Accessing an network service would be higher etc /// type_in (Type[A]): /// Type of input expected. /// eg str / MyClass or a composite type eg frozenset([Type1, Type2]) /// variations_in (Sequence[Hashable]): /// A sequence of hashable "tags" further describing the input type. /// For the node to be used, all these variations are required (dependencies). /// This is useful if the more simple type is not enough by itself. /// eg: str (can be path/url/email/name/etc) /// type_out (Type[B]): /// Same as "type_in", but representing the output of the transmutation. /// variations_out (Sequence[Hashable]): /// Same as "variations_in" except that variations are descriptive and not dependencies. /// They can satisfy dependencies for transmuters further down the chain. /// function (Callable[[A], B]): /// The converter itself. Take a single input, produce a single output. /// It is important that only an simple conversion is made, and that any deviation is raised as an Error. /// eg: maybe some attribute is not available and usually you'd return None. There is no strict type /// checking here, so raise an error and bail instead. def add_conversion( &self, cost: Int, type_in: &PyObject, variations_in: &PySequence, type_out: &PyObject, variations_out: &PySequence, function: PyObject ) -> PyResult<PyObject> { let hash_in = type_in.hash(py)?; let hash_out = type_out.hash(py)?; let hash_func = function.hash(py)?; let hash_var_in = hash_seq!(py, variations_in); let hash_var_out = hash_seq!(py, variations_out); // Store a reference to the python object in this outer layer // but refer to it via its hash. self.functions(py).borrow_mut().insert(hash_func, function); self.graph(py).borrow_mut().add_edge( cost.try_into().expect("Cost needs to be an int"), hash_in, hash_var_in, hash_out, hash_var_out, hash_func, ); Ok(py.None()) } /// Supply a function that will attempt to reveal insights into the provided data as variations. /// This is a convenience aid, to assist in detecting input variations automatically so they do not /// need to be expicitly specified. /// The activator function should run quickly so as to keep the entire process smooth. /// ie simple attribute checks, string regex etc /// /// Important note: These functions are not run on intermediate conversions, but only on the /// supplied data. /// /// Args: /// type_in (Type[A]): /// The type of input this function accepts. /// function (Callable[[A], Iterator[Hashable]]): /// Function that takes the value provided (of the type above) and yields any variations it finds. /// eg: str type could check for link type if the string is http://something.html and /// yield "protocol" "http" "url" def add_revealer(&self, type_in: &PyObject, function: PyObject) -> PyResult<PyObject> { self.revealers(py).borrow_mut().entry(type_in.hash(py)?).or_insert(Vec::new()).push(function); Ok(py.None()) } /// From a given type, attempt to produce a requested type. /// OR from some given data, attempt to traverse links to get the requested data. /// /// Args: /// value (Any): The input you have going into the process. This can be anything. /// type_want (Type[B]): /// The type you want to recieve. A chain of converters will be produced /// attempting to attain this type. /// variations_want (Sequence[Hashable]): /// A sequence of variations further describing the type you wish to attain. /// This is optional but can help guide the selection of converters through more complex transitions. /// type_have (Type[A]): /// An optional override for the starting type. /// If not provided the type of the value is taken instead. /// variations_have (Sequence[Hashable]): /// Optionally include any extra variations to the input. /// If context is known but hard to detect this can help direct a more complex /// transmutation. /// explicit (bool): /// If this is True, the "variations_have" argument will entirely override /// any detected tags. Enable this to use precisesly what you specify (no automatic detection). /// Returns: /// B: Whatever the result requested happens to be def convert( &self, value: PyObject, type_want: &PyObject, variations_want: Option<&PySequence> = None, type_have: Option<&PyObject> = None, variations_have: Option<&PySequence> = None, explicit: bool = false, debug: bool = false, ) -> PyResult<PyObject> { let hash_in = match type_have { Some(type_override) => type_override.hash(py)?, None => value.get_type(py).into_object().hash(py)? }; let hash_out = type_want.hash(py)?; let hash_var_out = match variations_want { Some(vars) => hash_seq!(py, vars), None => BTreeSet::new(), }; let mut hash_var_in = match variations_have { Some(vars) => hash_seq!(py, vars), None => BTreeSet::new(), }; if!explicit { // We don't want to be explicit, so // run the activator to detect initial variations if let Some(funcs) = self.revealers(py).borrow().get(&hash_in) { for func in funcs { for variation in func.call(py, (value.clone_ref(py),), None)?.iter(py)? { hash_var_in.insert(variation?.hash(py)?); } } }
// and there are still errors. Raise with info from all of them. let mut skip_edges = BTreeSet::new(); let mut errors = Vec::new(); 'outer: for _ in 0..10 { if let Some(edges) = self.graph(py).borrow().search(hash_in, &hash_var_in, hash_out, &hash_var_out, &skip_edges) { let functions = self.functions(py).borrow(); let mut result = value.clone_ref(py); for edge in edges { let func = functions.get(&edge.data).expect("Function is there"); if debug { warn!(py, format!("{}({}) ->...", func.to_string(), result.to_string())); } match func.call(py, (result,), None) { Ok(res) => { if debug { warn!(py, format!("... -> {}", res.to_string())); } result = res; }, Err(mut err) => { let message = format!( "{}: {}", err.get_type(py).name(py), err.instance(py).str(py)?.to_string(py)?, ); warn!(py, message); errors.push(message); // Ignore these when trying again. // This allows some level of failure // and with enough edges perhaps we // can find another path. skip_edges.insert(edge); continue 'outer } }; } return Ok(result) } break } if errors.len()!= 0 { Err(PyErr::new::<ConversionError, _>(py, format!( "Some problems occurred during the conversion process:\n{}", errors.join("\n") ))) } else { Err(PyErr::new::<TypeError, _>( py, format!( "Could not convert {} to {}. Perhaps some conversion steps are missing.", value, type_want ))) } } /////////////////////////////////////////////////////////////// // Satisfy python garbage collector // because we hold a reference to some functions provided def __traverse__(&self, visit) { for function in self.functions(py).borrow().values() { visit.call(function)?; } for functions in self.revealers(py).borrow().values() { for function in functions { visit.call(function)?; } } Ok(()) } def __clear__(&self) { for (_, func) in self.functions(py).borrow_mut().drain() { func.release_ref(py); } for (_, mut funcs) in self.revealers(py).borrow_mut().drain() { for func in funcs.drain(..) { func.release_ref(py); } } } /////////////////////////////////////////////////////////////// });
} // Retry a few times, if something breaks along the way. // Collect errors. // If we run out of paths to take or run out of reties,
random_line_split
lib.rs
//! This crate wraps [libkres](https://knot-resolver.cz) from //! [CZ.NIC Labs](https://labs.nic.cz). libkres is an implementation of a full DNS recursive resolver, //! including cache and DNSSEC validation. It doesn't require a specific I/O model and instead provides //! a generic interface for pushing/pulling DNS messages until the request is satisfied. //! //! The interface provided implements a minimal subset of operations from the engine: //! //! * `struct kr_context` is wrapped by [Context](struct.Context.html). Functions from libkres that //! operate on `struct kr_context` are accessed using methods on [Context](struct.Context.html). //! The context implements lock guards for all FFI calls on context, and all FFI calls on request //! that borrows given context. //! //! * `struct kr_request` is wrapped by [Request](struct.Request.html). Methods on //! [Request](struct.Request.html) are used to safely access the fields of `struct kr_request`. //! Methods that wrap FFI calls lock request and its context for thread-safe access. //! //! Example: //! //! ``` //! use std::net::{SocketAddr, UdpSocket}; //! use kres::{Context, Request, State}; //! //! // DNS message wire format //! let question = [2, 104, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1]; //! let from_addr = "127.0.0.1:1234".parse::<SocketAddr>().unwrap(); //! //! let context = Context::new(); //! let req = Request::new(context.clone()); //! let mut state = req.consume(&question, from_addr); //! while state == State::PRODUCE { //! state = match req.produce() { //! Some((msg, addr_set)) => { //! // This can be any I/O model the application uses //! let mut socket = UdpSocket::bind("0.0.0.0:0").unwrap(); //! socket.send_to(&msg, &addr_set[0]).unwrap(); //! let mut buf = [0; 512]; //! let (amt, src) = socket.recv_from(&mut buf).unwrap(); //! // Pass the response back to the request //! req.consume(&buf[..amt], src) //! }, //! None => { //! break; //! } //! } //! } //! //! // Convert request into final answer //! let answer = req.finish(state).unwrap(); //! ``` #[cfg(feature = "jemalloc")] use jemallocator; #[cfg(feature = "jemalloc")] #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; use bytes::Bytes; use parking_lot::{Mutex, MutexGuard}; use std::ffi::{CStr, CString}; use std::io::{Error, ErrorKind, Result}; use std::mem; use std::net::{IpAddr, SocketAddr}; use std::ptr; use std::sync::Arc; /// Number of tries to produce a next message const MAX_PRODUCE_TRIES : usize = 3; // Wrapped C library mod c { #![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] include!(concat!(env!("OUT_DIR"), "/bindings.rs")); } /// Request state enumeration pub use self::c::lkr_state as State; /// Shared context for the request resolution. /// All requests create with a given context use its facilities: /// * Trust Anchor storage /// * Root Server bootstrap set /// * Cache /// * Default EDNS options /// * Default options pub struct Context { inner: Mutex<*mut c::lkr_context>, } /* Context itself is not thread-safe, but Mutex wrapping it is */ unsafe impl Send for Context {} unsafe impl Sync for Context {} impl Context { /// Create an empty context without internal cache pub fn new() -> Arc<Self> { unsafe { Arc::new(Self { inner: Mutex::new(c::lkr_context_new()), }) } } /// Create an empty context with local disk cache pub fn with_cache(path: &str, max_bytes: usize) -> Result<Arc<Self>> { unsafe { let inner = c::lkr_context_new(); let path_c = CString::new(path).unwrap(); let cache_c = CStr::from_bytes_with_nul(b"cache\0").unwrap(); match c::lkr_cache_open(inner, path_c.as_ptr(), max_bytes) { 0 => { c::lkr_module_load(inner, cache_c.as_ptr()); Ok(Arc::new(Self { inner: Mutex::new(inner), })) } _ => Err(Error::new(ErrorKind::Other, "failed to open cache")), } } } /// Add a resolver module, see [Knot Resolver modules](https://knot-resolver.readthedocs.io/en/stable/modules.html) for reference pub fn add_module(&self, name: &str) -> Result<()> { let inner = self.locked(); let name_c = CString::new(name)?; unsafe { let res = c::lkr_module_load(*inner, name_c.as_ptr()); if res!= 0 { return Err(Error::new(ErrorKind::NotFound, "failed to load module")); } } Ok(()) } /// Remove a resolver module, see [Knot Resolver modules](https://knot-resolver.readthedocs.io/en/stable/modules.html) for reference pub fn remove_module(&self, name: &str) -> Result<()> { let inner = self.locked(); let name_c = CString::new(name)?; unsafe { let res = c::lkr_module_unload(*inner, name_c.as_ptr()); if res!= 0 { return Err(Error::new(ErrorKind::NotFound, "failed to unload module")); } } Ok(()) } /// Add a root server hint to the context. The root server hints are used to bootstrap the resolver, there must be at least one. pub fn add_root_hint(&self, addr: IpAddr) -> Result<()> { let inner = self.locked(); let slice = match addr { IpAddr::V4(ip) => ip.octets().to_vec(), IpAddr::V6(ip) => ip.octets().to_vec(), }; unsafe { let res = c::lkr_root_hint(*inner, slice.as_ptr(), slice.len()); if res!= 0 { return Err(Error::new( ErrorKind::InvalidInput, "failed to add a root hint", )); } } Ok(()) } /// Add a trust anchor to the resolver. If the context has at least 1 trust anchor, it will perform DNSSEC validation under it. pub fn add_trust_anchor(&self, rdata: &[u8]) -> Result<()> { let inner = self.locked(); unsafe { let res = c::lkr_trust_anchor(*inner, rdata.as_ptr(), rdata.len()); if res!= 0 { return Err(Error::new( ErrorKind::InvalidInput, "failed to add trust anchor", )); } } Ok(()) } /// Set or reset verbose mode pub fn set_verbose(&self, val: bool) { let inner = self.locked(); unsafe { c::lkr_verbose(*inner, val); } } fn locked(&self) -> MutexGuard<*mut c::lkr_context> { self.inner.lock() } } impl Drop for Context { fn drop(&mut self) { let inner = self.locked(); if!inner.is_null() { unsafe { c::lkr_context_free(*inner); } } } } /// Request wraps `struct kr_request` and keeps a reference for the context. /// The request is not automatically executed, it must be driven the caller to completion. pub struct Request { context: Arc<Context>, inner: Mutex<*mut c::lkr_request>, } /* Neither request nor context are thread safe. * Both request and context pointers is guarded by a mutex, * and must be locked during any operation on the request. */ unsafe impl Send for Request {} unsafe impl Sync for Request {} impl Request { /// Create a new request under the context. The request is bound to the context for its lifetime. pub fn new(context: Arc<Context>) -> Self { let inner = unsafe { c::lkr_request_new(*context.locked()) }; Self { context, inner: Mutex::new(inner), } } /// Consume an input from the caller, this is typically either a client query or response to an outbound query. pub fn consume(&self, msg: &[u8], from: SocketAddr) -> State { let (_context, inner) = self.locked(); let from = socket2::SockAddr::from(from); let msg_ptr = if!msg.is_empty() { msg.as_ptr() } else { ptr::null() }; unsafe { c::lkr_consume(*inner, from.as_ptr() as *const _, msg_ptr, msg.len()) } } /// Generate an outbound query for the request. This should be called when `consume()` returns a `Produce` state. pub fn produce(&self) -> Option<(Bytes, Vec<SocketAddr>)> { let mut msg = vec![0; 512]; let mut addresses = Vec::new(); let mut sa_vec: Vec<*mut c::sockaddr> = vec![ptr::null_mut(); 4]; let (_context, inner) = self.locked(); let state = { let mut state = State::PRODUCE; let mut tries = MAX_PRODUCE_TRIES; while state == State::PRODUCE { if tries == 0 { break; } tries -= 1; // Prepare socket address vector let addr_ptr = sa_vec.as_mut_ptr(); let addr_capacity = sa_vec.capacity(); // Prepare message buffer let msg_capacity = msg.capacity(); let msg_ptr = msg.as_mut_ptr(); let mut msg_size = msg_capacity; // Generate next message unsafe { mem::forget(msg); mem::forget(sa_vec); state = c::lkr_produce( *inner, addr_ptr, addr_capacity, msg_ptr, &mut msg_size, false, ); // Rebuild vectors from modified pointers msg = Vec::from_raw_parts(msg_ptr, msg_size, msg_capacity); sa_vec = Vec::from_raw_parts(addr_ptr, addr_capacity, addr_capacity); } } state }; match state { State::DONE => None, State::CONSUME => { for ptr_addr in sa_vec { if ptr_addr.is_null() { break; } let addr = unsafe { socket2::SockAddr::from_raw_parts( ptr_addr as *const _, c::lkr_sockaddr_len(ptr_addr) as u32, ) }; if let Some(as_inet) = addr.as_inet() { addresses.push(as_inet.into()); } else { addresses.push(addr.as_inet6().unwrap().into()); } } Some((Bytes::from(msg), addresses)) } _ => None, } } /// Finish request processing and convert Request into the final answer. pub fn finish(self, state: State) -> Result<Bytes> { let (_context, inner) = self.locked(); let answer_len = unsafe { c::lkr_finish(*inner, state) }; if answer_len == 0 { return Err(ErrorKind::UnexpectedEof.into()) } let mut v: Vec<u8> = Vec::with_capacity(answer_len); let p = v.as_mut_ptr(); let v = unsafe { mem::forget(v); c::lkr_write_answer(*inner, p, answer_len); Vec::from_raw_parts(p, answer_len, answer_len) }; Ok(Bytes::from(v)) } fn locked( &self, ) -> ( MutexGuard<*mut c::lkr_context>, MutexGuard<*mut c::lkr_request>, ) { (self.context.locked(), self.inner.lock()) } } impl Drop for Request { fn drop(&mut self) { let (_context, mut inner) = self.locked(); if!inner.is_null() { unsafe { c::lkr_request_free(*inner); *inner = ptr::null_mut(); } } } } #[cfg(test)] mod tests { use super::{Context, Request, State}; use dnssector::constants::*; use dnssector::synth::gen; use dnssector::{DNSSector, Section}; use std::net::SocketAddr; #[test] fn context_create() { let context = Context::new(); let r1 = Request::new(context.clone()); let r2 = Request::new(context.clone()); let (_, p1) = r1.locked(); let (_, p2) = r2.locked(); assert!(*p1!= *p2); } #[test] fn context_create_cached() { assert!(Context::with_cache(".", 64 * 1024).is_ok()); } #[test] fn context_root_hints() { let context = Context::new(); assert!(context.add_root_hint("127.0.0.1".parse().unwrap()).is_ok()); assert!(context.add_root_hint("::1".parse().unwrap()).is_ok()); } #[test] fn
() { let context = Context::new(); assert!(context.add_module("iterate").is_ok()); assert!(context.remove_module("iterate").is_ok()); } #[test] fn context_trust_anchor() { let context = Context::new(); let ta = gen::RR::from_string( ". 0 IN DS 20326 8 2 E06D44B80B8F1D39A95C0B0D7C65D08458E880409BBC683457104237C7F8EC8D", ) .unwrap(); assert!(context.add_trust_anchor(ta.rdata()).is_ok()); } #[test] fn context_verbose() { let context = Context::new(); context.set_verbose(true); context.set_verbose(false); } #[test] fn request_processing() { let context = Context::new(); // Create a ". NS" query (priming) let request = Request::new(context.clone()); let buf = gen::query( b".", Type::from_string("NS").unwrap(), Class::from_string("IN").unwrap(), ) .unwrap(); // Push it as a question to request let addr = "1.1.1.1:53".parse::<SocketAddr>().unwrap(); request.consume(buf.packet(), addr); // Generate an outbound query let state = match request.produce() { Some((buf, addresses)) => { // Generate a mock answer to the outbound query let mut resp = DNSSector::new(buf.to_vec()).unwrap().parse().unwrap(); resp.set_response(true); resp.insert_rr( Section::Answer, gen::RR::from_string(". 86399 IN NS e.root-servers.net").unwrap(), ) .unwrap(); resp.insert_rr( Section::Additional, gen::RR::from_string("e.root-servers.net 86399 IN A 192.203.230.10").unwrap(), ) .unwrap(); // Consume the mock answer and expect resolution to be done request.consume(resp.packet(), addresses[0]) } None => State::DONE, }; // Get final answer assert_eq!(state, State::DONE); let buf = request.finish(state).unwrap(); let resp = DNSSector::new(buf.to_vec()).unwrap().parse(); assert!(resp.is_ok()); } }
context_with_module
identifier_name
lib.rs
//! This crate wraps [libkres](https://knot-resolver.cz) from //! [CZ.NIC Labs](https://labs.nic.cz). libkres is an implementation of a full DNS recursive resolver, //! including cache and DNSSEC validation. It doesn't require a specific I/O model and instead provides //! a generic interface for pushing/pulling DNS messages until the request is satisfied. //! //! The interface provided implements a minimal subset of operations from the engine: //! //! * `struct kr_context` is wrapped by [Context](struct.Context.html). Functions from libkres that //! operate on `struct kr_context` are accessed using methods on [Context](struct.Context.html). //! The context implements lock guards for all FFI calls on context, and all FFI calls on request //! that borrows given context. //! //! * `struct kr_request` is wrapped by [Request](struct.Request.html). Methods on //! [Request](struct.Request.html) are used to safely access the fields of `struct kr_request`. //! Methods that wrap FFI calls lock request and its context for thread-safe access. //! //! Example: //! //! ``` //! use std::net::{SocketAddr, UdpSocket}; //! use kres::{Context, Request, State}; //! //! // DNS message wire format //! let question = [2, 104, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1]; //! let from_addr = "127.0.0.1:1234".parse::<SocketAddr>().unwrap(); //! //! let context = Context::new(); //! let req = Request::new(context.clone()); //! let mut state = req.consume(&question, from_addr); //! while state == State::PRODUCE { //! state = match req.produce() { //! Some((msg, addr_set)) => { //! // This can be any I/O model the application uses //! let mut socket = UdpSocket::bind("0.0.0.0:0").unwrap(); //! socket.send_to(&msg, &addr_set[0]).unwrap(); //! let mut buf = [0; 512]; //! let (amt, src) = socket.recv_from(&mut buf).unwrap(); //! // Pass the response back to the request //! req.consume(&buf[..amt], src) //! }, //! None => { //! break; //! } //! } //! } //! //! // Convert request into final answer //! let answer = req.finish(state).unwrap(); //! ``` #[cfg(feature = "jemalloc")] use jemallocator; #[cfg(feature = "jemalloc")] #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; use bytes::Bytes; use parking_lot::{Mutex, MutexGuard}; use std::ffi::{CStr, CString}; use std::io::{Error, ErrorKind, Result}; use std::mem; use std::net::{IpAddr, SocketAddr}; use std::ptr; use std::sync::Arc; /// Number of tries to produce a next message const MAX_PRODUCE_TRIES : usize = 3; // Wrapped C library mod c { #![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] include!(concat!(env!("OUT_DIR"), "/bindings.rs")); } /// Request state enumeration pub use self::c::lkr_state as State; /// Shared context for the request resolution. /// All requests create with a given context use its facilities: /// * Trust Anchor storage /// * Root Server bootstrap set /// * Cache /// * Default EDNS options /// * Default options pub struct Context { inner: Mutex<*mut c::lkr_context>, } /* Context itself is not thread-safe, but Mutex wrapping it is */ unsafe impl Send for Context {} unsafe impl Sync for Context {} impl Context { /// Create an empty context without internal cache pub fn new() -> Arc<Self> { unsafe { Arc::new(Self { inner: Mutex::new(c::lkr_context_new()), }) } } /// Create an empty context with local disk cache pub fn with_cache(path: &str, max_bytes: usize) -> Result<Arc<Self>> { unsafe { let inner = c::lkr_context_new(); let path_c = CString::new(path).unwrap(); let cache_c = CStr::from_bytes_with_nul(b"cache\0").unwrap(); match c::lkr_cache_open(inner, path_c.as_ptr(), max_bytes) { 0 => { c::lkr_module_load(inner, cache_c.as_ptr()); Ok(Arc::new(Self { inner: Mutex::new(inner), })) } _ => Err(Error::new(ErrorKind::Other, "failed to open cache")), } } } /// Add a resolver module, see [Knot Resolver modules](https://knot-resolver.readthedocs.io/en/stable/modules.html) for reference pub fn add_module(&self, name: &str) -> Result<()> { let inner = self.locked(); let name_c = CString::new(name)?; unsafe { let res = c::lkr_module_load(*inner, name_c.as_ptr()); if res!= 0 { return Err(Error::new(ErrorKind::NotFound, "failed to load module")); } } Ok(()) } /// Remove a resolver module, see [Knot Resolver modules](https://knot-resolver.readthedocs.io/en/stable/modules.html) for reference pub fn remove_module(&self, name: &str) -> Result<()> { let inner = self.locked(); let name_c = CString::new(name)?; unsafe { let res = c::lkr_module_unload(*inner, name_c.as_ptr()); if res!= 0 { return Err(Error::new(ErrorKind::NotFound, "failed to unload module")); } } Ok(()) } /// Add a root server hint to the context. The root server hints are used to bootstrap the resolver, there must be at least one. pub fn add_root_hint(&self, addr: IpAddr) -> Result<()> { let inner = self.locked(); let slice = match addr { IpAddr::V4(ip) => ip.octets().to_vec(), IpAddr::V6(ip) => ip.octets().to_vec(), }; unsafe { let res = c::lkr_root_hint(*inner, slice.as_ptr(), slice.len()); if res!= 0 { return Err(Error::new( ErrorKind::InvalidInput, "failed to add a root hint", )); } } Ok(()) } /// Add a trust anchor to the resolver. If the context has at least 1 trust anchor, it will perform DNSSEC validation under it. pub fn add_trust_anchor(&self, rdata: &[u8]) -> Result<()> { let inner = self.locked(); unsafe { let res = c::lkr_trust_anchor(*inner, rdata.as_ptr(), rdata.len()); if res!= 0 { return Err(Error::new( ErrorKind::InvalidInput, "failed to add trust anchor", )); } } Ok(()) } /// Set or reset verbose mode pub fn set_verbose(&self, val: bool) { let inner = self.locked(); unsafe { c::lkr_verbose(*inner, val); } } fn locked(&self) -> MutexGuard<*mut c::lkr_context> { self.inner.lock() } } impl Drop for Context { fn drop(&mut self) { let inner = self.locked(); if!inner.is_null() { unsafe { c::lkr_context_free(*inner); }
} } /// Request wraps `struct kr_request` and keeps a reference for the context. /// The request is not automatically executed, it must be driven the caller to completion. pub struct Request { context: Arc<Context>, inner: Mutex<*mut c::lkr_request>, } /* Neither request nor context are thread safe. * Both request and context pointers is guarded by a mutex, * and must be locked during any operation on the request. */ unsafe impl Send for Request {} unsafe impl Sync for Request {} impl Request { /// Create a new request under the context. The request is bound to the context for its lifetime. pub fn new(context: Arc<Context>) -> Self { let inner = unsafe { c::lkr_request_new(*context.locked()) }; Self { context, inner: Mutex::new(inner), } } /// Consume an input from the caller, this is typically either a client query or response to an outbound query. pub fn consume(&self, msg: &[u8], from: SocketAddr) -> State { let (_context, inner) = self.locked(); let from = socket2::SockAddr::from(from); let msg_ptr = if!msg.is_empty() { msg.as_ptr() } else { ptr::null() }; unsafe { c::lkr_consume(*inner, from.as_ptr() as *const _, msg_ptr, msg.len()) } } /// Generate an outbound query for the request. This should be called when `consume()` returns a `Produce` state. pub fn produce(&self) -> Option<(Bytes, Vec<SocketAddr>)> { let mut msg = vec![0; 512]; let mut addresses = Vec::new(); let mut sa_vec: Vec<*mut c::sockaddr> = vec![ptr::null_mut(); 4]; let (_context, inner) = self.locked(); let state = { let mut state = State::PRODUCE; let mut tries = MAX_PRODUCE_TRIES; while state == State::PRODUCE { if tries == 0 { break; } tries -= 1; // Prepare socket address vector let addr_ptr = sa_vec.as_mut_ptr(); let addr_capacity = sa_vec.capacity(); // Prepare message buffer let msg_capacity = msg.capacity(); let msg_ptr = msg.as_mut_ptr(); let mut msg_size = msg_capacity; // Generate next message unsafe { mem::forget(msg); mem::forget(sa_vec); state = c::lkr_produce( *inner, addr_ptr, addr_capacity, msg_ptr, &mut msg_size, false, ); // Rebuild vectors from modified pointers msg = Vec::from_raw_parts(msg_ptr, msg_size, msg_capacity); sa_vec = Vec::from_raw_parts(addr_ptr, addr_capacity, addr_capacity); } } state }; match state { State::DONE => None, State::CONSUME => { for ptr_addr in sa_vec { if ptr_addr.is_null() { break; } let addr = unsafe { socket2::SockAddr::from_raw_parts( ptr_addr as *const _, c::lkr_sockaddr_len(ptr_addr) as u32, ) }; if let Some(as_inet) = addr.as_inet() { addresses.push(as_inet.into()); } else { addresses.push(addr.as_inet6().unwrap().into()); } } Some((Bytes::from(msg), addresses)) } _ => None, } } /// Finish request processing and convert Request into the final answer. pub fn finish(self, state: State) -> Result<Bytes> { let (_context, inner) = self.locked(); let answer_len = unsafe { c::lkr_finish(*inner, state) }; if answer_len == 0 { return Err(ErrorKind::UnexpectedEof.into()) } let mut v: Vec<u8> = Vec::with_capacity(answer_len); let p = v.as_mut_ptr(); let v = unsafe { mem::forget(v); c::lkr_write_answer(*inner, p, answer_len); Vec::from_raw_parts(p, answer_len, answer_len) }; Ok(Bytes::from(v)) } fn locked( &self, ) -> ( MutexGuard<*mut c::lkr_context>, MutexGuard<*mut c::lkr_request>, ) { (self.context.locked(), self.inner.lock()) } } impl Drop for Request { fn drop(&mut self) { let (_context, mut inner) = self.locked(); if!inner.is_null() { unsafe { c::lkr_request_free(*inner); *inner = ptr::null_mut(); } } } } #[cfg(test)] mod tests { use super::{Context, Request, State}; use dnssector::constants::*; use dnssector::synth::gen; use dnssector::{DNSSector, Section}; use std::net::SocketAddr; #[test] fn context_create() { let context = Context::new(); let r1 = Request::new(context.clone()); let r2 = Request::new(context.clone()); let (_, p1) = r1.locked(); let (_, p2) = r2.locked(); assert!(*p1!= *p2); } #[test] fn context_create_cached() { assert!(Context::with_cache(".", 64 * 1024).is_ok()); } #[test] fn context_root_hints() { let context = Context::new(); assert!(context.add_root_hint("127.0.0.1".parse().unwrap()).is_ok()); assert!(context.add_root_hint("::1".parse().unwrap()).is_ok()); } #[test] fn context_with_module() { let context = Context::new(); assert!(context.add_module("iterate").is_ok()); assert!(context.remove_module("iterate").is_ok()); } #[test] fn context_trust_anchor() { let context = Context::new(); let ta = gen::RR::from_string( ". 0 IN DS 20326 8 2 E06D44B80B8F1D39A95C0B0D7C65D08458E880409BBC683457104237C7F8EC8D", ) .unwrap(); assert!(context.add_trust_anchor(ta.rdata()).is_ok()); } #[test] fn context_verbose() { let context = Context::new(); context.set_verbose(true); context.set_verbose(false); } #[test] fn request_processing() { let context = Context::new(); // Create a ". NS" query (priming) let request = Request::new(context.clone()); let buf = gen::query( b".", Type::from_string("NS").unwrap(), Class::from_string("IN").unwrap(), ) .unwrap(); // Push it as a question to request let addr = "1.1.1.1:53".parse::<SocketAddr>().unwrap(); request.consume(buf.packet(), addr); // Generate an outbound query let state = match request.produce() { Some((buf, addresses)) => { // Generate a mock answer to the outbound query let mut resp = DNSSector::new(buf.to_vec()).unwrap().parse().unwrap(); resp.set_response(true); resp.insert_rr( Section::Answer, gen::RR::from_string(". 86399 IN NS e.root-servers.net").unwrap(), ) .unwrap(); resp.insert_rr( Section::Additional, gen::RR::from_string("e.root-servers.net 86399 IN A 192.203.230.10").unwrap(), ) .unwrap(); // Consume the mock answer and expect resolution to be done request.consume(resp.packet(), addresses[0]) } None => State::DONE, }; // Get final answer assert_eq!(state, State::DONE); let buf = request.finish(state).unwrap(); let resp = DNSSector::new(buf.to_vec()).unwrap().parse(); assert!(resp.is_ok()); } }
}
random_line_split
lib.rs
//! This crate wraps [libkres](https://knot-resolver.cz) from //! [CZ.NIC Labs](https://labs.nic.cz). libkres is an implementation of a full DNS recursive resolver, //! including cache and DNSSEC validation. It doesn't require a specific I/O model and instead provides //! a generic interface for pushing/pulling DNS messages until the request is satisfied. //! //! The interface provided implements a minimal subset of operations from the engine: //! //! * `struct kr_context` is wrapped by [Context](struct.Context.html). Functions from libkres that //! operate on `struct kr_context` are accessed using methods on [Context](struct.Context.html). //! The context implements lock guards for all FFI calls on context, and all FFI calls on request //! that borrows given context. //! //! * `struct kr_request` is wrapped by [Request](struct.Request.html). Methods on //! [Request](struct.Request.html) are used to safely access the fields of `struct kr_request`. //! Methods that wrap FFI calls lock request and its context for thread-safe access. //! //! Example: //! //! ``` //! use std::net::{SocketAddr, UdpSocket}; //! use kres::{Context, Request, State}; //! //! // DNS message wire format //! let question = [2, 104, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1]; //! let from_addr = "127.0.0.1:1234".parse::<SocketAddr>().unwrap(); //! //! let context = Context::new(); //! let req = Request::new(context.clone()); //! let mut state = req.consume(&question, from_addr); //! while state == State::PRODUCE { //! state = match req.produce() { //! Some((msg, addr_set)) => { //! // This can be any I/O model the application uses //! let mut socket = UdpSocket::bind("0.0.0.0:0").unwrap(); //! socket.send_to(&msg, &addr_set[0]).unwrap(); //! let mut buf = [0; 512]; //! let (amt, src) = socket.recv_from(&mut buf).unwrap(); //! // Pass the response back to the request //! req.consume(&buf[..amt], src) //! }, //! None => { //! break; //! } //! } //! } //! //! // Convert request into final answer //! let answer = req.finish(state).unwrap(); //! ``` #[cfg(feature = "jemalloc")] use jemallocator; #[cfg(feature = "jemalloc")] #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; use bytes::Bytes; use parking_lot::{Mutex, MutexGuard}; use std::ffi::{CStr, CString}; use std::io::{Error, ErrorKind, Result}; use std::mem; use std::net::{IpAddr, SocketAddr}; use std::ptr; use std::sync::Arc; /// Number of tries to produce a next message const MAX_PRODUCE_TRIES : usize = 3; // Wrapped C library mod c { #![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] include!(concat!(env!("OUT_DIR"), "/bindings.rs")); } /// Request state enumeration pub use self::c::lkr_state as State; /// Shared context for the request resolution. /// All requests create with a given context use its facilities: /// * Trust Anchor storage /// * Root Server bootstrap set /// * Cache /// * Default EDNS options /// * Default options pub struct Context { inner: Mutex<*mut c::lkr_context>, } /* Context itself is not thread-safe, but Mutex wrapping it is */ unsafe impl Send for Context {} unsafe impl Sync for Context {} impl Context { /// Create an empty context without internal cache pub fn new() -> Arc<Self> { unsafe { Arc::new(Self { inner: Mutex::new(c::lkr_context_new()), }) } } /// Create an empty context with local disk cache pub fn with_cache(path: &str, max_bytes: usize) -> Result<Arc<Self>> { unsafe { let inner = c::lkr_context_new(); let path_c = CString::new(path).unwrap(); let cache_c = CStr::from_bytes_with_nul(b"cache\0").unwrap(); match c::lkr_cache_open(inner, path_c.as_ptr(), max_bytes) { 0 => { c::lkr_module_load(inner, cache_c.as_ptr()); Ok(Arc::new(Self { inner: Mutex::new(inner), })) } _ => Err(Error::new(ErrorKind::Other, "failed to open cache")), } } } /// Add a resolver module, see [Knot Resolver modules](https://knot-resolver.readthedocs.io/en/stable/modules.html) for reference pub fn add_module(&self, name: &str) -> Result<()> { let inner = self.locked(); let name_c = CString::new(name)?; unsafe { let res = c::lkr_module_load(*inner, name_c.as_ptr()); if res!= 0 { return Err(Error::new(ErrorKind::NotFound, "failed to load module")); } } Ok(()) } /// Remove a resolver module, see [Knot Resolver modules](https://knot-resolver.readthedocs.io/en/stable/modules.html) for reference pub fn remove_module(&self, name: &str) -> Result<()> { let inner = self.locked(); let name_c = CString::new(name)?; unsafe { let res = c::lkr_module_unload(*inner, name_c.as_ptr()); if res!= 0 { return Err(Error::new(ErrorKind::NotFound, "failed to unload module")); } } Ok(()) } /// Add a root server hint to the context. The root server hints are used to bootstrap the resolver, there must be at least one. pub fn add_root_hint(&self, addr: IpAddr) -> Result<()> { let inner = self.locked(); let slice = match addr { IpAddr::V4(ip) => ip.octets().to_vec(), IpAddr::V6(ip) => ip.octets().to_vec(), }; unsafe { let res = c::lkr_root_hint(*inner, slice.as_ptr(), slice.len()); if res!= 0 { return Err(Error::new( ErrorKind::InvalidInput, "failed to add a root hint", )); } } Ok(()) } /// Add a trust anchor to the resolver. If the context has at least 1 trust anchor, it will perform DNSSEC validation under it. pub fn add_trust_anchor(&self, rdata: &[u8]) -> Result<()> { let inner = self.locked(); unsafe { let res = c::lkr_trust_anchor(*inner, rdata.as_ptr(), rdata.len()); if res!= 0 { return Err(Error::new( ErrorKind::InvalidInput, "failed to add trust anchor", )); } } Ok(()) } /// Set or reset verbose mode pub fn set_verbose(&self, val: bool) { let inner = self.locked(); unsafe { c::lkr_verbose(*inner, val); } } fn locked(&self) -> MutexGuard<*mut c::lkr_context> { self.inner.lock() } } impl Drop for Context { fn drop(&mut self) { let inner = self.locked(); if!inner.is_null() { unsafe { c::lkr_context_free(*inner); } } } } /// Request wraps `struct kr_request` and keeps a reference for the context. /// The request is not automatically executed, it must be driven the caller to completion. pub struct Request { context: Arc<Context>, inner: Mutex<*mut c::lkr_request>, } /* Neither request nor context are thread safe. * Both request and context pointers is guarded by a mutex, * and must be locked during any operation on the request. */ unsafe impl Send for Request {} unsafe impl Sync for Request {} impl Request { /// Create a new request under the context. The request is bound to the context for its lifetime. pub fn new(context: Arc<Context>) -> Self { let inner = unsafe { c::lkr_request_new(*context.locked()) }; Self { context, inner: Mutex::new(inner), } } /// Consume an input from the caller, this is typically either a client query or response to an outbound query. pub fn consume(&self, msg: &[u8], from: SocketAddr) -> State
/// Generate an outbound query for the request. This should be called when `consume()` returns a `Produce` state. pub fn produce(&self) -> Option<(Bytes, Vec<SocketAddr>)> { let mut msg = vec![0; 512]; let mut addresses = Vec::new(); let mut sa_vec: Vec<*mut c::sockaddr> = vec![ptr::null_mut(); 4]; let (_context, inner) = self.locked(); let state = { let mut state = State::PRODUCE; let mut tries = MAX_PRODUCE_TRIES; while state == State::PRODUCE { if tries == 0 { break; } tries -= 1; // Prepare socket address vector let addr_ptr = sa_vec.as_mut_ptr(); let addr_capacity = sa_vec.capacity(); // Prepare message buffer let msg_capacity = msg.capacity(); let msg_ptr = msg.as_mut_ptr(); let mut msg_size = msg_capacity; // Generate next message unsafe { mem::forget(msg); mem::forget(sa_vec); state = c::lkr_produce( *inner, addr_ptr, addr_capacity, msg_ptr, &mut msg_size, false, ); // Rebuild vectors from modified pointers msg = Vec::from_raw_parts(msg_ptr, msg_size, msg_capacity); sa_vec = Vec::from_raw_parts(addr_ptr, addr_capacity, addr_capacity); } } state }; match state { State::DONE => None, State::CONSUME => { for ptr_addr in sa_vec { if ptr_addr.is_null() { break; } let addr = unsafe { socket2::SockAddr::from_raw_parts( ptr_addr as *const _, c::lkr_sockaddr_len(ptr_addr) as u32, ) }; if let Some(as_inet) = addr.as_inet() { addresses.push(as_inet.into()); } else { addresses.push(addr.as_inet6().unwrap().into()); } } Some((Bytes::from(msg), addresses)) } _ => None, } } /// Finish request processing and convert Request into the final answer. pub fn finish(self, state: State) -> Result<Bytes> { let (_context, inner) = self.locked(); let answer_len = unsafe { c::lkr_finish(*inner, state) }; if answer_len == 0 { return Err(ErrorKind::UnexpectedEof.into()) } let mut v: Vec<u8> = Vec::with_capacity(answer_len); let p = v.as_mut_ptr(); let v = unsafe { mem::forget(v); c::lkr_write_answer(*inner, p, answer_len); Vec::from_raw_parts(p, answer_len, answer_len) }; Ok(Bytes::from(v)) } fn locked( &self, ) -> ( MutexGuard<*mut c::lkr_context>, MutexGuard<*mut c::lkr_request>, ) { (self.context.locked(), self.inner.lock()) } } impl Drop for Request { fn drop(&mut self) { let (_context, mut inner) = self.locked(); if!inner.is_null() { unsafe { c::lkr_request_free(*inner); *inner = ptr::null_mut(); } } } } #[cfg(test)] mod tests { use super::{Context, Request, State}; use dnssector::constants::*; use dnssector::synth::gen; use dnssector::{DNSSector, Section}; use std::net::SocketAddr; #[test] fn context_create() { let context = Context::new(); let r1 = Request::new(context.clone()); let r2 = Request::new(context.clone()); let (_, p1) = r1.locked(); let (_, p2) = r2.locked(); assert!(*p1!= *p2); } #[test] fn context_create_cached() { assert!(Context::with_cache(".", 64 * 1024).is_ok()); } #[test] fn context_root_hints() { let context = Context::new(); assert!(context.add_root_hint("127.0.0.1".parse().unwrap()).is_ok()); assert!(context.add_root_hint("::1".parse().unwrap()).is_ok()); } #[test] fn context_with_module() { let context = Context::new(); assert!(context.add_module("iterate").is_ok()); assert!(context.remove_module("iterate").is_ok()); } #[test] fn context_trust_anchor() { let context = Context::new(); let ta = gen::RR::from_string( ". 0 IN DS 20326 8 2 E06D44B80B8F1D39A95C0B0D7C65D08458E880409BBC683457104237C7F8EC8D", ) .unwrap(); assert!(context.add_trust_anchor(ta.rdata()).is_ok()); } #[test] fn context_verbose() { let context = Context::new(); context.set_verbose(true); context.set_verbose(false); } #[test] fn request_processing() { let context = Context::new(); // Create a ". NS" query (priming) let request = Request::new(context.clone()); let buf = gen::query( b".", Type::from_string("NS").unwrap(), Class::from_string("IN").unwrap(), ) .unwrap(); // Push it as a question to request let addr = "1.1.1.1:53".parse::<SocketAddr>().unwrap(); request.consume(buf.packet(), addr); // Generate an outbound query let state = match request.produce() { Some((buf, addresses)) => { // Generate a mock answer to the outbound query let mut resp = DNSSector::new(buf.to_vec()).unwrap().parse().unwrap(); resp.set_response(true); resp.insert_rr( Section::Answer, gen::RR::from_string(". 86399 IN NS e.root-servers.net").unwrap(), ) .unwrap(); resp.insert_rr( Section::Additional, gen::RR::from_string("e.root-servers.net 86399 IN A 192.203.230.10").unwrap(), ) .unwrap(); // Consume the mock answer and expect resolution to be done request.consume(resp.packet(), addresses[0]) } None => State::DONE, }; // Get final answer assert_eq!(state, State::DONE); let buf = request.finish(state).unwrap(); let resp = DNSSector::new(buf.to_vec()).unwrap().parse(); assert!(resp.is_ok()); } }
{ let (_context, inner) = self.locked(); let from = socket2::SockAddr::from(from); let msg_ptr = if !msg.is_empty() { msg.as_ptr() } else { ptr::null() }; unsafe { c::lkr_consume(*inner, from.as_ptr() as *const _, msg_ptr, msg.len()) } }
identifier_body
e.rs
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::*; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 1000000007; #[allow(unused_macros)] macro_rules! debug { ($($a:expr),* $(,)*) => { #[cfg(debug_assertions)] eprintln!(concat!($("| ", stringify!($a), "={:?} "),*, "|"), $(&$a),*); }; } fn main() { input! { n: usize, k: usize, a: [[i64; n]; n], } let row = |i| i; let col = |j| n + j; let mut graph = MinCostFlowGraph::new(2 * n + 2); let source = 2 * n; let target = 2 * n + 1; for i in 0..n { for j in 0..n { graph.add_edge(col(j), row(i), 1, 10000000000 - a[i][j]); } } for i in 0..n { graph.add_edge(source, col(i), k as i64, 0); graph.add_edge(row(i), target, k as i64, 0); } graph.add_edge(source, target, 100000000, 10000000000); graph.flow(source, target, 100000000); let mut result = 0; let mut s = vec![vec!['.'; n]; n]; for e in graph.edges() { debug!(e.from, e.to, e.cap, e.flow, e.cost); if e.from!= source && e.to!= target && e.flow >= 1 { let i = e.to; let j = e.from - n; result += a[i][j]; s[i][j] = 'X'; } } println!("{}", result); for i in 0..n { println!("{}", s[i].iter().collect::<String>()); } } //https://github.com/rust-lang-ja/ac-library-rs pub mod internal_type_traits { use std::{ fmt, iter::{Product, Sum}, ops::{ Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, Mul, MulAssign, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, }, }; // Skipped: // // - `is_signed_int_t<T>` (probably won't be used directly in `modint.rs`) // - `is_unsigned_int_t<T>` (probably won't be used directly in `modint.rs`) // - `to_unsigned_t<T>` (not used in `fenwicktree.rs`) /// Corresponds to `std::is_integral` in C++. // We will remove unnecessary bounds later. // // Maybe we should rename this to `PrimitiveInteger` or something, as it probably won't be used in the // same way as the original ACL. pub trait Integral: 'static + Send + Sync + Copy + Ord + Not<Output = Self> + Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Div<Output = Self> + Rem<Output = Self> + AddAssign + SubAssign + MulAssign + DivAssign + RemAssign + Sum + Product + BitOr<Output = Self> + BitAnd<Output = Self> + BitXor<Output = Self> + BitOrAssign + BitAndAssign + BitXorAssign + Shl<Output = Self> + Shr<Output = Self> + ShlAssign + ShrAssign + fmt::Display + fmt::Debug + fmt::Binary + fmt::Octal + Zero + One + BoundedBelow + BoundedAbove { } /// Class that has additive identity element pub trait Zero { /// The additive identity element fn zero() -> Self; } /// Class that has multiplicative identity element pub trait One { /// The multiplicative identity element fn one() -> Self; } pub trait BoundedBelow { fn min_value() -> Self; } pub trait BoundedAbove { fn max_value() -> Self; } macro_rules! impl_integral { ($($ty:ty),*) => { $( impl Zero for $ty { #[inline] fn zero() -> Self { 0 } } impl One for $ty { #[inline] fn one() -> Self { 1 } } impl BoundedBelow for $ty { #[inline] fn min_value() -> Self { Self::min_value() } } impl BoundedAbove for $ty { #[inline] fn max_value() -> Self { Self::max_value() } } impl Integral for $ty {} )* }; } impl_integral!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize); } pub mod mincostflow { use crate::internal_type_traits::Integral; pub struct MinCostFlowEdge<T> { pub from: usize, pub to: usize, pub cap: T, pub flow: T, pub cost: T, } pub struct MinCostFlowGraph<T> { pos: Vec<(usize, usize)>, g: Vec<Vec<_Edge<T>>>, cost_sum: T, } impl<T> MinCostFlowGraph<T> where T: Integral + std::ops::Neg<Output = T>, { pub fn new(n: usize) -> Self { Self { pos: vec![], g: (0..n).map(|_| vec![]).collect(), cost_sum: T::zero(), } } pub fn get_edge(&self, i: usize) -> MinCostFlowEdge<T> { assert!(i < self.pos.len()); let e = &self.g[self.pos[i].0][self.pos[i].1]; let re = &self.g[e.to][e.rev]; MinCostFlowEdge { from: self.pos[i].0, to: e.to, cap: e.cap + re.cap, flow: re.cap, cost: e.cost, } } pub fn edges(&self) -> Vec<MinCostFlowEdge<T>> { let m = self.pos.len(); let mut result = vec![]; for i in 0..m { result.push(self.get_edge(i)); } result } pub fn add_edge(&mut self, from: usize, to: usize, cap: T, cost: T) -> usize { assert!(from < self.g.len()); assert!(to < self.g.len()); assert_ne!(from, to); assert!(cap >= T::zero()); assert!(cost >= T::zero()); self.pos.push((from, self.g[from].len())); self.cost_sum += cost; let rev = self.g[to].len(); self.g[from].push(_Edge { to, rev, cap, cost }); let rev = self.g[from].len() - 1; self.g[to].push(_Edge { to: from, rev, cap: T::zero(), cost: -cost, }); self.pos.len() - 1 } /// Returns (maximum flow, cost) pub fn flow(&mut self, source: usize, sink: usize, flow_limit: T) -> (T, T) { self.slope(source, sink, flow_limit).pop().unwrap() } pub fn slope(&mut self, source: usize, sink: usize, flow_limit: T) -> Vec<(T, T)> { let n = self.g.len(); assert!(source < n); assert!(sink < n); assert_ne!(source, sink); let mut dual = vec![T::zero(); n]; let mut prev_v = vec![0; n]; let mut prev_e = vec![0; n]; let mut flow = T::zero(); let mut cost = T::zero(); let mut prev_cost: Option<T> = None; let mut result = vec![(flow, cost)]; while flow < flow_limit { if!self.refine_dual(source, sink, &mut dual, &mut prev_v, &mut prev_e) { break; } let mut c = flow_limit - flow; let mut v = sink; while v!= source { c = std::cmp::min(c, self.g[prev_v[v]][prev_e[v]].cap); v = prev_v[v]; } let mut v = sink; while v!= source { self.g[prev_v[v]][prev_e[v]].cap -= c; let rev = self.g[prev_v[v]][prev_e[v]].rev; self.g[v][rev].cap += c; v = prev_v[v]; } let d = -dual[source]; flow += c; cost += d * c; if prev_cost == Some(d) { assert!(result.pop().is_some()); } result.push((flow, cost)); prev_cost = Some(cost); } result } fn
( &self, source: usize, sink: usize, dual: &mut [T], pv: &mut [usize], pe: &mut [usize], ) -> bool { let n = self.g.len(); let mut dist = vec![self.cost_sum; n]; let mut vis = vec![false; n]; let mut que = std::collections::BinaryHeap::new(); dist[source] = T::zero(); que.push((std::cmp::Reverse(T::zero()), source)); while let Some((_, v)) = que.pop() { if vis[v] { continue; } vis[v] = true; if v == sink { break; } for (i, e) in self.g[v].iter().enumerate() { if vis[e.to] || e.cap == T::zero() { continue; } let cost = e.cost - dual[e.to] + dual[v]; if dist[e.to] - dist[v] > cost { dist[e.to] = dist[v] + cost; pv[e.to] = v; pe[e.to] = i; que.push((std::cmp::Reverse(dist[e.to]), e.to)); } } } if!vis[sink] { return false; } for v in 0..n { if!vis[v] { continue; } dual[v] -= dist[sink] - dist[v]; } true } } struct _Edge<T> { to: usize, rev: usize, cap: T, cost: T, } #[cfg(test)] mod tests { use super::*; #[test] fn test_min_cost_flow() { let mut graph = MinCostFlowGraph::new(4); graph.add_edge(0, 1, 2, 1); graph.add_edge(0, 2, 1, 2); graph.add_edge(1, 2, 1, 1); graph.add_edge(1, 3, 1, 3); graph.add_edge(2, 3, 2, 1); let (flow, cost) = graph.flow(0, 3, 2); assert_eq!(flow, 2); assert_eq!(cost, 6); } } } use mincostflow::*;
refine_dual
identifier_name
e.rs
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::*; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 1000000007; #[allow(unused_macros)] macro_rules! debug { ($($a:expr),* $(,)*) => { #[cfg(debug_assertions)] eprintln!(concat!($("| ", stringify!($a), "={:?} "),*, "|"), $(&$a),*); }; } fn main() { input! { n: usize, k: usize, a: [[i64; n]; n], } let row = |i| i; let col = |j| n + j; let mut graph = MinCostFlowGraph::new(2 * n + 2); let source = 2 * n; let target = 2 * n + 1; for i in 0..n { for j in 0..n { graph.add_edge(col(j), row(i), 1, 10000000000 - a[i][j]); } } for i in 0..n { graph.add_edge(source, col(i), k as i64, 0); graph.add_edge(row(i), target, k as i64, 0); } graph.add_edge(source, target, 100000000, 10000000000); graph.flow(source, target, 100000000); let mut result = 0; let mut s = vec![vec!['.'; n]; n]; for e in graph.edges() { debug!(e.from, e.to, e.cap, e.flow, e.cost); if e.from!= source && e.to!= target && e.flow >= 1 { let i = e.to; let j = e.from - n; result += a[i][j]; s[i][j] = 'X'; } } println!("{}", result); for i in 0..n { println!("{}", s[i].iter().collect::<String>()); } } //https://github.com/rust-lang-ja/ac-library-rs pub mod internal_type_traits { use std::{ fmt, iter::{Product, Sum}, ops::{ Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, Mul, MulAssign, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, }, }; // Skipped: // // - `is_signed_int_t<T>` (probably won't be used directly in `modint.rs`) // - `is_unsigned_int_t<T>` (probably won't be used directly in `modint.rs`) // - `to_unsigned_t<T>` (not used in `fenwicktree.rs`) /// Corresponds to `std::is_integral` in C++. // We will remove unnecessary bounds later. // // Maybe we should rename this to `PrimitiveInteger` or something, as it probably won't be used in the // same way as the original ACL. pub trait Integral: 'static + Send + Sync + Copy + Ord + Not<Output = Self> + Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Div<Output = Self> + Rem<Output = Self> + AddAssign + SubAssign + MulAssign + DivAssign + RemAssign + Sum + Product + BitOr<Output = Self> + BitAnd<Output = Self> + BitXor<Output = Self> + BitOrAssign + BitAndAssign + BitXorAssign + Shl<Output = Self> + Shr<Output = Self> + ShlAssign + ShrAssign + fmt::Display + fmt::Debug + fmt::Binary + fmt::Octal + Zero + One + BoundedBelow + BoundedAbove { } /// Class that has additive identity element pub trait Zero { /// The additive identity element fn zero() -> Self; } /// Class that has multiplicative identity element pub trait One { /// The multiplicative identity element fn one() -> Self; } pub trait BoundedBelow { fn min_value() -> Self; } pub trait BoundedAbove { fn max_value() -> Self; } macro_rules! impl_integral { ($($ty:ty),*) => { $( impl Zero for $ty { #[inline] fn zero() -> Self { 0 } } impl One for $ty { #[inline] fn one() -> Self { 1 } } impl BoundedBelow for $ty { #[inline] fn min_value() -> Self { Self::min_value() } } impl BoundedAbove for $ty { #[inline] fn max_value() -> Self { Self::max_value() } } impl Integral for $ty {} )* }; } impl_integral!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize); } pub mod mincostflow { use crate::internal_type_traits::Integral; pub struct MinCostFlowEdge<T> { pub from: usize, pub to: usize, pub cap: T, pub flow: T, pub cost: T, } pub struct MinCostFlowGraph<T> { pos: Vec<(usize, usize)>, g: Vec<Vec<_Edge<T>>>, cost_sum: T, } impl<T> MinCostFlowGraph<T> where T: Integral + std::ops::Neg<Output = T>, { pub fn new(n: usize) -> Self { Self { pos: vec![], g: (0..n).map(|_| vec![]).collect(), cost_sum: T::zero(), } } pub fn get_edge(&self, i: usize) -> MinCostFlowEdge<T> { assert!(i < self.pos.len()); let e = &self.g[self.pos[i].0][self.pos[i].1]; let re = &self.g[e.to][e.rev]; MinCostFlowEdge { from: self.pos[i].0, to: e.to, cap: e.cap + re.cap, flow: re.cap, cost: e.cost, } } pub fn edges(&self) -> Vec<MinCostFlowEdge<T>> { let m = self.pos.len(); let mut result = vec![]; for i in 0..m { result.push(self.get_edge(i)); } result } pub fn add_edge(&mut self, from: usize, to: usize, cap: T, cost: T) -> usize { assert!(from < self.g.len()); assert!(to < self.g.len()); assert_ne!(from, to); assert!(cap >= T::zero()); assert!(cost >= T::zero()); self.pos.push((from, self.g[from].len())); self.cost_sum += cost; let rev = self.g[to].len(); self.g[from].push(_Edge { to, rev, cap, cost }); let rev = self.g[from].len() - 1; self.g[to].push(_Edge { to: from, rev, cap: T::zero(), cost: -cost, }); self.pos.len() - 1 } /// Returns (maximum flow, cost) pub fn flow(&mut self, source: usize, sink: usize, flow_limit: T) -> (T, T) { self.slope(source, sink, flow_limit).pop().unwrap() } pub fn slope(&mut self, source: usize, sink: usize, flow_limit: T) -> Vec<(T, T)> { let n = self.g.len(); assert!(source < n); assert!(sink < n); assert_ne!(source, sink); let mut dual = vec![T::zero(); n]; let mut prev_v = vec![0; n]; let mut prev_e = vec![0; n]; let mut flow = T::zero(); let mut cost = T::zero(); let mut prev_cost: Option<T> = None; let mut result = vec![(flow, cost)]; while flow < flow_limit { if!self.refine_dual(source, sink, &mut dual, &mut prev_v, &mut prev_e) { break; } let mut c = flow_limit - flow; let mut v = sink; while v!= source { c = std::cmp::min(c, self.g[prev_v[v]][prev_e[v]].cap); v = prev_v[v]; } let mut v = sink; while v!= source { self.g[prev_v[v]][prev_e[v]].cap -= c; let rev = self.g[prev_v[v]][prev_e[v]].rev; self.g[v][rev].cap += c; v = prev_v[v]; } let d = -dual[source]; flow += c; cost += d * c; if prev_cost == Some(d) { assert!(result.pop().is_some()); } result.push((flow, cost)); prev_cost = Some(cost); } result } fn refine_dual( &self, source: usize, sink: usize, dual: &mut [T], pv: &mut [usize], pe: &mut [usize], ) -> bool { let n = self.g.len(); let mut dist = vec![self.cost_sum; n]; let mut vis = vec![false; n]; let mut que = std::collections::BinaryHeap::new(); dist[source] = T::zero(); que.push((std::cmp::Reverse(T::zero()), source)); while let Some((_, v)) = que.pop() { if vis[v] { continue; } vis[v] = true; if v == sink { break; } for (i, e) in self.g[v].iter().enumerate() { if vis[e.to] || e.cap == T::zero() { continue; } let cost = e.cost - dual[e.to] + dual[v]; if dist[e.to] - dist[v] > cost
} } if!vis[sink] { return false; } for v in 0..n { if!vis[v] { continue; } dual[v] -= dist[sink] - dist[v]; } true } } struct _Edge<T> { to: usize, rev: usize, cap: T, cost: T, } #[cfg(test)] mod tests { use super::*; #[test] fn test_min_cost_flow() { let mut graph = MinCostFlowGraph::new(4); graph.add_edge(0, 1, 2, 1); graph.add_edge(0, 2, 1, 2); graph.add_edge(1, 2, 1, 1); graph.add_edge(1, 3, 1, 3); graph.add_edge(2, 3, 2, 1); let (flow, cost) = graph.flow(0, 3, 2); assert_eq!(flow, 2); assert_eq!(cost, 6); } } } use mincostflow::*;
{ dist[e.to] = dist[v] + cost; pv[e.to] = v; pe[e.to] = i; que.push((std::cmp::Reverse(dist[e.to]), e.to)); }
conditional_block
e.rs
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::*; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 1000000007; #[allow(unused_macros)] macro_rules! debug { ($($a:expr),* $(,)*) => { #[cfg(debug_assertions)] eprintln!(concat!($("| ", stringify!($a), "={:?} "),*, "|"), $(&$a),*); }; } fn main() { input! { n: usize, k: usize, a: [[i64; n]; n], } let row = |i| i; let col = |j| n + j; let mut graph = MinCostFlowGraph::new(2 * n + 2); let source = 2 * n; let target = 2 * n + 1; for i in 0..n { for j in 0..n { graph.add_edge(col(j), row(i), 1, 10000000000 - a[i][j]); } } for i in 0..n { graph.add_edge(source, col(i), k as i64, 0); graph.add_edge(row(i), target, k as i64, 0); } graph.add_edge(source, target, 100000000, 10000000000); graph.flow(source, target, 100000000); let mut result = 0; let mut s = vec![vec!['.'; n]; n]; for e in graph.edges() { debug!(e.from, e.to, e.cap, e.flow, e.cost); if e.from!= source && e.to!= target && e.flow >= 1 { let i = e.to; let j = e.from - n; result += a[i][j]; s[i][j] = 'X'; } } println!("{}", result); for i in 0..n { println!("{}", s[i].iter().collect::<String>()); } } //https://github.com/rust-lang-ja/ac-library-rs pub mod internal_type_traits { use std::{ fmt, iter::{Product, Sum}, ops::{ Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, Mul, MulAssign, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, }, }; // Skipped: // // - `is_signed_int_t<T>` (probably won't be used directly in `modint.rs`) // - `is_unsigned_int_t<T>` (probably won't be used directly in `modint.rs`) // - `to_unsigned_t<T>` (not used in `fenwicktree.rs`) /// Corresponds to `std::is_integral` in C++. // We will remove unnecessary bounds later. // // Maybe we should rename this to `PrimitiveInteger` or something, as it probably won't be used in the // same way as the original ACL. pub trait Integral: 'static + Send + Sync + Copy + Ord + Not<Output = Self> + Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Div<Output = Self> + Rem<Output = Self> + AddAssign + SubAssign + MulAssign + DivAssign + RemAssign + Sum + Product + BitOr<Output = Self> + BitAnd<Output = Self> + BitXor<Output = Self> + BitOrAssign + BitAndAssign + BitXorAssign + Shl<Output = Self> + Shr<Output = Self> + ShlAssign + ShrAssign + fmt::Display + fmt::Debug + fmt::Binary + fmt::Octal + Zero + One + BoundedBelow + BoundedAbove { } /// Class that has additive identity element pub trait Zero { /// The additive identity element fn zero() -> Self; } /// Class that has multiplicative identity element pub trait One { /// The multiplicative identity element fn one() -> Self; } pub trait BoundedBelow { fn min_value() -> Self; } pub trait BoundedAbove { fn max_value() -> Self; } macro_rules! impl_integral { ($($ty:ty),*) => { $( impl Zero for $ty { #[inline] fn zero() -> Self { 0 } } impl One for $ty { #[inline] fn one() -> Self { 1 } } impl BoundedBelow for $ty { #[inline] fn min_value() -> Self {
} } impl BoundedAbove for $ty { #[inline] fn max_value() -> Self { Self::max_value() } } impl Integral for $ty {} )* }; } impl_integral!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize); } pub mod mincostflow { use crate::internal_type_traits::Integral; pub struct MinCostFlowEdge<T> { pub from: usize, pub to: usize, pub cap: T, pub flow: T, pub cost: T, } pub struct MinCostFlowGraph<T> { pos: Vec<(usize, usize)>, g: Vec<Vec<_Edge<T>>>, cost_sum: T, } impl<T> MinCostFlowGraph<T> where T: Integral + std::ops::Neg<Output = T>, { pub fn new(n: usize) -> Self { Self { pos: vec![], g: (0..n).map(|_| vec![]).collect(), cost_sum: T::zero(), } } pub fn get_edge(&self, i: usize) -> MinCostFlowEdge<T> { assert!(i < self.pos.len()); let e = &self.g[self.pos[i].0][self.pos[i].1]; let re = &self.g[e.to][e.rev]; MinCostFlowEdge { from: self.pos[i].0, to: e.to, cap: e.cap + re.cap, flow: re.cap, cost: e.cost, } } pub fn edges(&self) -> Vec<MinCostFlowEdge<T>> { let m = self.pos.len(); let mut result = vec![]; for i in 0..m { result.push(self.get_edge(i)); } result } pub fn add_edge(&mut self, from: usize, to: usize, cap: T, cost: T) -> usize { assert!(from < self.g.len()); assert!(to < self.g.len()); assert_ne!(from, to); assert!(cap >= T::zero()); assert!(cost >= T::zero()); self.pos.push((from, self.g[from].len())); self.cost_sum += cost; let rev = self.g[to].len(); self.g[from].push(_Edge { to, rev, cap, cost }); let rev = self.g[from].len() - 1; self.g[to].push(_Edge { to: from, rev, cap: T::zero(), cost: -cost, }); self.pos.len() - 1 } /// Returns (maximum flow, cost) pub fn flow(&mut self, source: usize, sink: usize, flow_limit: T) -> (T, T) { self.slope(source, sink, flow_limit).pop().unwrap() } pub fn slope(&mut self, source: usize, sink: usize, flow_limit: T) -> Vec<(T, T)> { let n = self.g.len(); assert!(source < n); assert!(sink < n); assert_ne!(source, sink); let mut dual = vec![T::zero(); n]; let mut prev_v = vec![0; n]; let mut prev_e = vec![0; n]; let mut flow = T::zero(); let mut cost = T::zero(); let mut prev_cost: Option<T> = None; let mut result = vec![(flow, cost)]; while flow < flow_limit { if!self.refine_dual(source, sink, &mut dual, &mut prev_v, &mut prev_e) { break; } let mut c = flow_limit - flow; let mut v = sink; while v!= source { c = std::cmp::min(c, self.g[prev_v[v]][prev_e[v]].cap); v = prev_v[v]; } let mut v = sink; while v!= source { self.g[prev_v[v]][prev_e[v]].cap -= c; let rev = self.g[prev_v[v]][prev_e[v]].rev; self.g[v][rev].cap += c; v = prev_v[v]; } let d = -dual[source]; flow += c; cost += d * c; if prev_cost == Some(d) { assert!(result.pop().is_some()); } result.push((flow, cost)); prev_cost = Some(cost); } result } fn refine_dual( &self, source: usize, sink: usize, dual: &mut [T], pv: &mut [usize], pe: &mut [usize], ) -> bool { let n = self.g.len(); let mut dist = vec![self.cost_sum; n]; let mut vis = vec![false; n]; let mut que = std::collections::BinaryHeap::new(); dist[source] = T::zero(); que.push((std::cmp::Reverse(T::zero()), source)); while let Some((_, v)) = que.pop() { if vis[v] { continue; } vis[v] = true; if v == sink { break; } for (i, e) in self.g[v].iter().enumerate() { if vis[e.to] || e.cap == T::zero() { continue; } let cost = e.cost - dual[e.to] + dual[v]; if dist[e.to] - dist[v] > cost { dist[e.to] = dist[v] + cost; pv[e.to] = v; pe[e.to] = i; que.push((std::cmp::Reverse(dist[e.to]), e.to)); } } } if!vis[sink] { return false; } for v in 0..n { if!vis[v] { continue; } dual[v] -= dist[sink] - dist[v]; } true } } struct _Edge<T> { to: usize, rev: usize, cap: T, cost: T, } #[cfg(test)] mod tests { use super::*; #[test] fn test_min_cost_flow() { let mut graph = MinCostFlowGraph::new(4); graph.add_edge(0, 1, 2, 1); graph.add_edge(0, 2, 1, 2); graph.add_edge(1, 2, 1, 1); graph.add_edge(1, 3, 1, 3); graph.add_edge(2, 3, 2, 1); let (flow, cost) = graph.flow(0, 3, 2); assert_eq!(flow, 2); assert_eq!(cost, 6); } } } use mincostflow::*;
Self::min_value()
random_line_split
e.rs
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::*; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 1000000007; #[allow(unused_macros)] macro_rules! debug { ($($a:expr),* $(,)*) => { #[cfg(debug_assertions)] eprintln!(concat!($("| ", stringify!($a), "={:?} "),*, "|"), $(&$a),*); }; } fn main() { input! { n: usize, k: usize, a: [[i64; n]; n], } let row = |i| i; let col = |j| n + j; let mut graph = MinCostFlowGraph::new(2 * n + 2); let source = 2 * n; let target = 2 * n + 1; for i in 0..n { for j in 0..n { graph.add_edge(col(j), row(i), 1, 10000000000 - a[i][j]); } } for i in 0..n { graph.add_edge(source, col(i), k as i64, 0); graph.add_edge(row(i), target, k as i64, 0); } graph.add_edge(source, target, 100000000, 10000000000); graph.flow(source, target, 100000000); let mut result = 0; let mut s = vec![vec!['.'; n]; n]; for e in graph.edges() { debug!(e.from, e.to, e.cap, e.flow, e.cost); if e.from!= source && e.to!= target && e.flow >= 1 { let i = e.to; let j = e.from - n; result += a[i][j]; s[i][j] = 'X'; } } println!("{}", result); for i in 0..n { println!("{}", s[i].iter().collect::<String>()); } } //https://github.com/rust-lang-ja/ac-library-rs pub mod internal_type_traits { use std::{ fmt, iter::{Product, Sum}, ops::{ Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, Mul, MulAssign, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, }, }; // Skipped: // // - `is_signed_int_t<T>` (probably won't be used directly in `modint.rs`) // - `is_unsigned_int_t<T>` (probably won't be used directly in `modint.rs`) // - `to_unsigned_t<T>` (not used in `fenwicktree.rs`) /// Corresponds to `std::is_integral` in C++. // We will remove unnecessary bounds later. // // Maybe we should rename this to `PrimitiveInteger` or something, as it probably won't be used in the // same way as the original ACL. pub trait Integral: 'static + Send + Sync + Copy + Ord + Not<Output = Self> + Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Div<Output = Self> + Rem<Output = Self> + AddAssign + SubAssign + MulAssign + DivAssign + RemAssign + Sum + Product + BitOr<Output = Self> + BitAnd<Output = Self> + BitXor<Output = Self> + BitOrAssign + BitAndAssign + BitXorAssign + Shl<Output = Self> + Shr<Output = Self> + ShlAssign + ShrAssign + fmt::Display + fmt::Debug + fmt::Binary + fmt::Octal + Zero + One + BoundedBelow + BoundedAbove { } /// Class that has additive identity element pub trait Zero { /// The additive identity element fn zero() -> Self; } /// Class that has multiplicative identity element pub trait One { /// The multiplicative identity element fn one() -> Self; } pub trait BoundedBelow { fn min_value() -> Self; } pub trait BoundedAbove { fn max_value() -> Self; } macro_rules! impl_integral { ($($ty:ty),*) => { $( impl Zero for $ty { #[inline] fn zero() -> Self { 0 } } impl One for $ty { #[inline] fn one() -> Self { 1 } } impl BoundedBelow for $ty { #[inline] fn min_value() -> Self { Self::min_value() } } impl BoundedAbove for $ty { #[inline] fn max_value() -> Self { Self::max_value() } } impl Integral for $ty {} )* }; } impl_integral!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize); } pub mod mincostflow { use crate::internal_type_traits::Integral; pub struct MinCostFlowEdge<T> { pub from: usize, pub to: usize, pub cap: T, pub flow: T, pub cost: T, } pub struct MinCostFlowGraph<T> { pos: Vec<(usize, usize)>, g: Vec<Vec<_Edge<T>>>, cost_sum: T, } impl<T> MinCostFlowGraph<T> where T: Integral + std::ops::Neg<Output = T>, { pub fn new(n: usize) -> Self { Self { pos: vec![], g: (0..n).map(|_| vec![]).collect(), cost_sum: T::zero(), } } pub fn get_edge(&self, i: usize) -> MinCostFlowEdge<T> { assert!(i < self.pos.len()); let e = &self.g[self.pos[i].0][self.pos[i].1]; let re = &self.g[e.to][e.rev]; MinCostFlowEdge { from: self.pos[i].0, to: e.to, cap: e.cap + re.cap, flow: re.cap, cost: e.cost, } } pub fn edges(&self) -> Vec<MinCostFlowEdge<T>> { let m = self.pos.len(); let mut result = vec![]; for i in 0..m { result.push(self.get_edge(i)); } result } pub fn add_edge(&mut self, from: usize, to: usize, cap: T, cost: T) -> usize { assert!(from < self.g.len()); assert!(to < self.g.len()); assert_ne!(from, to); assert!(cap >= T::zero()); assert!(cost >= T::zero()); self.pos.push((from, self.g[from].len())); self.cost_sum += cost; let rev = self.g[to].len(); self.g[from].push(_Edge { to, rev, cap, cost }); let rev = self.g[from].len() - 1; self.g[to].push(_Edge { to: from, rev, cap: T::zero(), cost: -cost, }); self.pos.len() - 1 } /// Returns (maximum flow, cost) pub fn flow(&mut self, source: usize, sink: usize, flow_limit: T) -> (T, T) { self.slope(source, sink, flow_limit).pop().unwrap() } pub fn slope(&mut self, source: usize, sink: usize, flow_limit: T) -> Vec<(T, T)>
while v!= source { c = std::cmp::min(c, self.g[prev_v[v]][prev_e[v]].cap); v = prev_v[v]; } let mut v = sink; while v!= source { self.g[prev_v[v]][prev_e[v]].cap -= c; let rev = self.g[prev_v[v]][prev_e[v]].rev; self.g[v][rev].cap += c; v = prev_v[v]; } let d = -dual[source]; flow += c; cost += d * c; if prev_cost == Some(d) { assert!(result.pop().is_some()); } result.push((flow, cost)); prev_cost = Some(cost); } result } fn refine_dual( &self, source: usize, sink: usize, dual: &mut [T], pv: &mut [usize], pe: &mut [usize], ) -> bool { let n = self.g.len(); let mut dist = vec![self.cost_sum; n]; let mut vis = vec![false; n]; let mut que = std::collections::BinaryHeap::new(); dist[source] = T::zero(); que.push((std::cmp::Reverse(T::zero()), source)); while let Some((_, v)) = que.pop() { if vis[v] { continue; } vis[v] = true; if v == sink { break; } for (i, e) in self.g[v].iter().enumerate() { if vis[e.to] || e.cap == T::zero() { continue; } let cost = e.cost - dual[e.to] + dual[v]; if dist[e.to] - dist[v] > cost { dist[e.to] = dist[v] + cost; pv[e.to] = v; pe[e.to] = i; que.push((std::cmp::Reverse(dist[e.to]), e.to)); } } } if!vis[sink] { return false; } for v in 0..n { if!vis[v] { continue; } dual[v] -= dist[sink] - dist[v]; } true } } struct _Edge<T> { to: usize, rev: usize, cap: T, cost: T, } #[cfg(test)] mod tests { use super::*; #[test] fn test_min_cost_flow() { let mut graph = MinCostFlowGraph::new(4); graph.add_edge(0, 1, 2, 1); graph.add_edge(0, 2, 1, 2); graph.add_edge(1, 2, 1, 1); graph.add_edge(1, 3, 1, 3); graph.add_edge(2, 3, 2, 1); let (flow, cost) = graph.flow(0, 3, 2); assert_eq!(flow, 2); assert_eq!(cost, 6); } } } use mincostflow::*;
{ let n = self.g.len(); assert!(source < n); assert!(sink < n); assert_ne!(source, sink); let mut dual = vec![T::zero(); n]; let mut prev_v = vec![0; n]; let mut prev_e = vec![0; n]; let mut flow = T::zero(); let mut cost = T::zero(); let mut prev_cost: Option<T> = None; let mut result = vec![(flow, cost)]; while flow < flow_limit { if !self.refine_dual(source, sink, &mut dual, &mut prev_v, &mut prev_e) { break; } let mut c = flow_limit - flow; let mut v = sink;
identifier_body
api.rs
// Copyright (c) 2019 Cloudflare, Inc. All rights reserved. // SPDX-License-Identifier: BSD-3-Clause use super::dev_lock::LockReadGuard; use super::drop_privileges::get_saved_ids; use super::{AllowedIP, Device, Error, SocketAddr}; use crate::device::Action; use crate::serialization::KeyBytes; use crate::x25519; use hex::encode as encode_hex; use libc::*; use std::fs::{create_dir, remove_file}; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::net::{UnixListener, UnixStream}; use std::sync::atomic::Ordering; const SOCK_DIR: &str = "/var/run/wireguard/"; fn create_sock_dir() { let _ = create_dir(SOCK_DIR); // Create the directory if it does not exist if let Ok((saved_uid, saved_gid)) = get_saved_ids() { unsafe { let c_path = std::ffi::CString::new(SOCK_DIR).unwrap(); // The directory is under the root user, but we want to be able to // delete the files there when we exit, so we need to change the owner chown( c_path.as_bytes_with_nul().as_ptr() as _, saved_uid, saved_gid, ); } } } impl Device { /// Register the api handler for this Device. The api handler receives stream connections on a Unix socket /// with a known path: /var/run/wireguard/{tun_name}.sock. pub fn register_api_handler(&mut self) -> Result<(), Error> { let path = format!("{}/{}.sock", SOCK_DIR, self.iface.name()?); create_sock_dir(); let _ = remove_file(&path); // Attempt to remove the socket if already exists let api_listener = UnixListener::bind(&path).map_err(Error::ApiSocket)?; // Bind a new socket to the path self.cleanup_paths.push(path.clone()); self.queue.new_event( api_listener.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api unix socket let (api_conn, _) = match api_listener.accept() { Ok(conn) => conn, _ => return Action::Continue, }; let mut reader = BufReader::new(&api_conn); let mut writer = BufWriter::new(&api_conn); let mut cmd = String::new(); if reader.read_line(&mut cmd).is_ok() { cmd.pop(); // pop the new line character let status = match cmd.as_ref() { // Only two commands are legal according to the protocol, get=1 and set=1. "get=1" => api_get(&mut writer, d), "set=1" => api_set(&mut reader, d), _ => EIO, }; // The protocol requires to return an error code as the response, or zero on success writeln!(writer, "errno={}\n", status).ok(); } Action::Continue // Indicates the worker thread should continue as normal }), )?; self.register_monitor(path)?; self.register_api_signal_handlers() } pub fn register_api_fd(&mut self, fd: i32) -> Result<(), Error> { let io_file = unsafe { UnixStream::from_raw_fd(fd) }; self.queue.new_event( io_file.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api file descriptor let mut reader = BufReader::new(&io_file); let mut writer = BufWriter::new(&io_file); let mut cmd = String::new(); if reader.read_line(&mut cmd).is_ok() { cmd.pop(); // pop the new line character let status = match cmd.as_ref() { // Only two commands are legal according to the protocol, get=1 and set=1. "get=1" => api_get(&mut writer, d), "set=1" => api_set(&mut reader, d), _ => EIO, }; // The protocol requires to return an error code as the response, or zero on success writeln!(writer, "errno={}\n", status).ok(); } else { // The remote side is likely closed; we should trigger an exit. d.trigger_exit(); return Action::Exit; } Action::Continue // Indicates the worker thread should continue as normal }), )?; Ok(()) } fn register_monitor(&self, path: String) -> Result<(), Error> { self.queue.new_periodic_event( Box::new(move |d, _| { // This is not a very nice hack to detect if the control socket was removed // and exiting nicely as a result. We check every 3 seconds in a loop if the // file was deleted by stating it. // The problem is that on linux inotify can be used quite beautifully to detect // deletion, and kqueue EVFILT_VNODE can be used for the same purpose, but that // will require introducing new events, for no measurable benefit. // TODO: Could this be an issue if we restart the service too quickly? let path = std::path::Path::new(&path); if!path.exists() { d.trigger_exit(); return Action::Exit; } // Periodically read the mtu of the interface in case it changes if let Ok(mtu) = d.iface.mtu() { d.mtu.store(mtu, Ordering::Relaxed); } Action::Continue }), std::time::Duration::from_millis(1000), )?; Ok(()) } fn register_api_signal_handlers(&self) -> Result<(), Error> { self.queue .new_signal_event(SIGINT, Box::new(move |_, _| Action::Exit))?; self.queue .new_signal_event(SIGTERM, Box::new(move |_, _| Action::Exit))?; Ok(()) } } #[allow(unused_must_use)] fn api_get(writer: &mut BufWriter<&UnixStream>, d: &Device) -> i32 { // get command requires an empty line, but there is no reason to be religious about it if let Some(ref k) = d.key_pair { writeln!(writer, "own_public_key={}", encode_hex(k.1.as_bytes())); } if d.listen_port!= 0 { writeln!(writer, "listen_port={}", d.listen_port); } if let Some(fwmark) = d.fwmark { writeln!(writer, "fwmark={}", fwmark); } for (k, p) in d.peers.iter() { let p = p.lock(); writeln!(writer, "public_key={}", encode_hex(k.as_bytes())); if let Some(ref key) = p.preshared_key() { writeln!(writer, "preshared_key={}", encode_hex(key)); } if let Some(keepalive) = p.persistent_keepalive() { writeln!(writer, "persistent_keepalive_interval={}", keepalive); } if let Some(ref addr) = p.endpoint().addr { writeln!(writer, "endpoint={}", addr); } for (ip, cidr) in p.allowed_ips() { writeln!(writer, "allowed_ip={}/{}", ip, cidr); } if let Some(time) = p.time_since_last_handshake() { writeln!(writer, "last_handshake_time_sec={}", time.as_secs()); writeln!(writer, "last_handshake_time_nsec={}", time.subsec_nanos()); } let (_, tx_bytes, rx_bytes,..) = p.tunnel.stats(); writeln!(writer, "rx_bytes={}", rx_bytes); writeln!(writer, "tx_bytes={}", tx_bytes); } 0 } fn api_set(reader: &mut BufReader<&UnixStream>, d: &mut LockReadGuard<Device>) -> i32
match key { "private_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => { device.set_key(x25519::StaticSecret::from(key_bytes.0)) } Err(_) => return EINVAL, }, "listen_port" => match val.parse::<u16>() { Ok(port) => match device.open_listen_socket(port) { Ok(()) => {} Err(_) => return EADDRINUSE, }, Err(_) => return EINVAL, }, #[cfg(any( target_os = "android", target_os = "fuchsia", target_os = "linux" ))] "fwmark" => match val.parse::<u32>() { Ok(mark) => match device.set_fwmark(mark) { Ok(()) => {} Err(_) => return EADDRINUSE, }, Err(_) => return EINVAL, }, "replace_peers" => match val.parse::<bool>() { Ok(true) => device.clear_peers(), Ok(false) => {} Err(_) => return EINVAL, }, "public_key" => match val.parse::<KeyBytes>() { // Indicates a new peer section Ok(key_bytes) => { return api_set_peer( reader, device, x25519::PublicKey::from(key_bytes.0), ) } Err(_) => return EINVAL, }, _ => return EINVAL, } } cmd.clear(); } 0 }, ) .unwrap_or(EIO) } fn api_set_peer( reader: &mut BufReader<&UnixStream>, d: &mut Device, pub_key: x25519::PublicKey, ) -> i32 { let mut cmd = String::new(); let mut remove = false; let mut replace_ips = false; let mut endpoint = None; let mut keepalive = None; let mut public_key = pub_key; let mut preshared_key = None; let mut allowed_ips: Vec<AllowedIP> = vec![]; while reader.read_line(&mut cmd).is_ok() { cmd.pop(); // remove newline if any if cmd.is_empty() { d.update_peer( public_key, remove, replace_ips, endpoint, allowed_ips.as_slice(), keepalive, preshared_key, ); allowed_ips.clear(); //clear the vector content after update return 0; // Done } { let parsed_cmd: Vec<&str> = cmd.splitn(2, '=').collect(); if parsed_cmd.len()!= 2 { return EPROTO; } let (key, val) = (parsed_cmd[0], parsed_cmd[1]); match key { "remove" => match val.parse::<bool>() { Ok(true) => remove = true, Ok(false) => remove = false, Err(_) => return EINVAL, }, "preshared_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => preshared_key = Some(key_bytes.0), Err(_) => return EINVAL, }, "endpoint" => match val.parse::<SocketAddr>() { Ok(addr) => endpoint = Some(addr), Err(_) => return EINVAL, }, "persistent_keepalive_interval" => match val.parse::<u16>() { Ok(interval) => keepalive = Some(interval), Err(_) => return EINVAL, }, "replace_allowed_ips" => match val.parse::<bool>() { Ok(true) => replace_ips = true, Ok(false) => replace_ips = false, Err(_) => return EINVAL, }, "allowed_ip" => match val.parse::<AllowedIP>() { Ok(ip) => allowed_ips.push(ip), Err(_) => return EINVAL, }, "public_key" => { // Indicates a new peer section. Commit changes for current peer, and continue to next peer d.update_peer( public_key, remove, replace_ips, endpoint, allowed_ips.as_slice(), keepalive, preshared_key, ); allowed_ips.clear(); //clear the vector content after update match val.parse::<KeyBytes>() { Ok(key_bytes) => public_key = key_bytes.0.into(), Err(_) => return EINVAL, } } "protocol_version" => match val.parse::<u32>() { Ok(1) => {} // Only version 1 is legal _ => return EINVAL, }, _ => return EINVAL, } } cmd.clear(); } 0 }
{ d.try_writeable( |device| device.trigger_yield(), |device| { device.cancel_yield(); let mut cmd = String::new(); while reader.read_line(&mut cmd).is_ok() { cmd.pop(); // remove newline if any if cmd.is_empty() { return 0; // Done } { let parsed_cmd: Vec<&str> = cmd.split('=').collect(); if parsed_cmd.len() != 2 { return EPROTO; } let (key, val) = (parsed_cmd[0], parsed_cmd[1]);
identifier_body
api.rs
// Copyright (c) 2019 Cloudflare, Inc. All rights reserved. // SPDX-License-Identifier: BSD-3-Clause use super::dev_lock::LockReadGuard; use super::drop_privileges::get_saved_ids; use super::{AllowedIP, Device, Error, SocketAddr}; use crate::device::Action; use crate::serialization::KeyBytes; use crate::x25519; use hex::encode as encode_hex; use libc::*; use std::fs::{create_dir, remove_file}; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::net::{UnixListener, UnixStream}; use std::sync::atomic::Ordering; const SOCK_DIR: &str = "/var/run/wireguard/"; fn create_sock_dir() { let _ = create_dir(SOCK_DIR); // Create the directory if it does not exist if let Ok((saved_uid, saved_gid)) = get_saved_ids() { unsafe { let c_path = std::ffi::CString::new(SOCK_DIR).unwrap(); // The directory is under the root user, but we want to be able to // delete the files there when we exit, so we need to change the owner chown( c_path.as_bytes_with_nul().as_ptr() as _, saved_uid, saved_gid, ); } } } impl Device { /// Register the api handler for this Device. The api handler receives stream connections on a Unix socket /// with a known path: /var/run/wireguard/{tun_name}.sock. pub fn register_api_handler(&mut self) -> Result<(), Error> { let path = format!("{}/{}.sock", SOCK_DIR, self.iface.name()?); create_sock_dir(); let _ = remove_file(&path); // Attempt to remove the socket if already exists let api_listener = UnixListener::bind(&path).map_err(Error::ApiSocket)?; // Bind a new socket to the path self.cleanup_paths.push(path.clone()); self.queue.new_event( api_listener.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api unix socket let (api_conn, _) = match api_listener.accept() { Ok(conn) => conn, _ => return Action::Continue, }; let mut reader = BufReader::new(&api_conn); let mut writer = BufWriter::new(&api_conn); let mut cmd = String::new(); if reader.read_line(&mut cmd).is_ok() { cmd.pop(); // pop the new line character let status = match cmd.as_ref() { // Only two commands are legal according to the protocol, get=1 and set=1. "get=1" => api_get(&mut writer, d), "set=1" => api_set(&mut reader, d), _ => EIO, }; // The protocol requires to return an error code as the response, or zero on success writeln!(writer, "errno={}\n", status).ok(); } Action::Continue // Indicates the worker thread should continue as normal }), )?; self.register_monitor(path)?; self.register_api_signal_handlers() } pub fn register_api_fd(&mut self, fd: i32) -> Result<(), Error> { let io_file = unsafe { UnixStream::from_raw_fd(fd) }; self.queue.new_event( io_file.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api file descriptor let mut reader = BufReader::new(&io_file); let mut writer = BufWriter::new(&io_file); let mut cmd = String::new(); if reader.read_line(&mut cmd).is_ok() { cmd.pop(); // pop the new line character let status = match cmd.as_ref() { // Only two commands are legal according to the protocol, get=1 and set=1. "get=1" => api_get(&mut writer, d), "set=1" => api_set(&mut reader, d), _ => EIO, }; // The protocol requires to return an error code as the response, or zero on success writeln!(writer, "errno={}\n", status).ok(); } else { // The remote side is likely closed; we should trigger an exit. d.trigger_exit(); return Action::Exit; } Action::Continue // Indicates the worker thread should continue as normal }), )?; Ok(()) } fn register_monitor(&self, path: String) -> Result<(), Error> { self.queue.new_periodic_event( Box::new(move |d, _| { // This is not a very nice hack to detect if the control socket was removed // and exiting nicely as a result. We check every 3 seconds in a loop if the // file was deleted by stating it. // The problem is that on linux inotify can be used quite beautifully to detect // deletion, and kqueue EVFILT_VNODE can be used for the same purpose, but that // will require introducing new events, for no measurable benefit. // TODO: Could this be an issue if we restart the service too quickly? let path = std::path::Path::new(&path); if!path.exists() { d.trigger_exit(); return Action::Exit; } // Periodically read the mtu of the interface in case it changes if let Ok(mtu) = d.iface.mtu() { d.mtu.store(mtu, Ordering::Relaxed); } Action::Continue }), std::time::Duration::from_millis(1000), )?; Ok(()) } fn register_api_signal_handlers(&self) -> Result<(), Error> { self.queue .new_signal_event(SIGINT, Box::new(move |_, _| Action::Exit))?; self.queue .new_signal_event(SIGTERM, Box::new(move |_, _| Action::Exit))?; Ok(()) } } #[allow(unused_must_use)] fn api_get(writer: &mut BufWriter<&UnixStream>, d: &Device) -> i32 { // get command requires an empty line, but there is no reason to be religious about it if let Some(ref k) = d.key_pair { writeln!(writer, "own_public_key={}", encode_hex(k.1.as_bytes())); } if d.listen_port!= 0 { writeln!(writer, "listen_port={}", d.listen_port); } if let Some(fwmark) = d.fwmark { writeln!(writer, "fwmark={}", fwmark); } for (k, p) in d.peers.iter() { let p = p.lock(); writeln!(writer, "public_key={}", encode_hex(k.as_bytes())); if let Some(ref key) = p.preshared_key() { writeln!(writer, "preshared_key={}", encode_hex(key)); } if let Some(keepalive) = p.persistent_keepalive() { writeln!(writer, "persistent_keepalive_interval={}", keepalive); } if let Some(ref addr) = p.endpoint().addr { writeln!(writer, "endpoint={}", addr); } for (ip, cidr) in p.allowed_ips() { writeln!(writer, "allowed_ip={}/{}", ip, cidr); } if let Some(time) = p.time_since_last_handshake() { writeln!(writer, "last_handshake_time_sec={}", time.as_secs()); writeln!(writer, "last_handshake_time_nsec={}", time.subsec_nanos()); } let (_, tx_bytes, rx_bytes,..) = p.tunnel.stats(); writeln!(writer, "rx_bytes={}", rx_bytes); writeln!(writer, "tx_bytes={}", tx_bytes); } 0 } fn api_set(reader: &mut BufReader<&UnixStream>, d: &mut LockReadGuard<Device>) -> i32 { d.try_writeable( |device| device.trigger_yield(), |device| { device.cancel_yield(); let mut cmd = String::new(); while reader.read_line(&mut cmd).is_ok() { cmd.pop(); // remove newline if any if cmd.is_empty() { return 0; // Done } { let parsed_cmd: Vec<&str> = cmd.split('=').collect(); if parsed_cmd.len()!= 2 { return EPROTO; } let (key, val) = (parsed_cmd[0], parsed_cmd[1]); match key { "private_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => { device.set_key(x25519::StaticSecret::from(key_bytes.0)) } Err(_) => return EINVAL, }, "listen_port" => match val.parse::<u16>() { Ok(port) => match device.open_listen_socket(port) { Ok(()) => {} Err(_) => return EADDRINUSE, }, Err(_) => return EINVAL, }, #[cfg(any( target_os = "android",
Ok(mark) => match device.set_fwmark(mark) { Ok(()) => {} Err(_) => return EADDRINUSE, }, Err(_) => return EINVAL, }, "replace_peers" => match val.parse::<bool>() { Ok(true) => device.clear_peers(), Ok(false) => {} Err(_) => return EINVAL, }, "public_key" => match val.parse::<KeyBytes>() { // Indicates a new peer section Ok(key_bytes) => { return api_set_peer( reader, device, x25519::PublicKey::from(key_bytes.0), ) } Err(_) => return EINVAL, }, _ => return EINVAL, } } cmd.clear(); } 0 }, ) .unwrap_or(EIO) } fn api_set_peer( reader: &mut BufReader<&UnixStream>, d: &mut Device, pub_key: x25519::PublicKey, ) -> i32 { let mut cmd = String::new(); let mut remove = false; let mut replace_ips = false; let mut endpoint = None; let mut keepalive = None; let mut public_key = pub_key; let mut preshared_key = None; let mut allowed_ips: Vec<AllowedIP> = vec![]; while reader.read_line(&mut cmd).is_ok() { cmd.pop(); // remove newline if any if cmd.is_empty() { d.update_peer( public_key, remove, replace_ips, endpoint, allowed_ips.as_slice(), keepalive, preshared_key, ); allowed_ips.clear(); //clear the vector content after update return 0; // Done } { let parsed_cmd: Vec<&str> = cmd.splitn(2, '=').collect(); if parsed_cmd.len()!= 2 { return EPROTO; } let (key, val) = (parsed_cmd[0], parsed_cmd[1]); match key { "remove" => match val.parse::<bool>() { Ok(true) => remove = true, Ok(false) => remove = false, Err(_) => return EINVAL, }, "preshared_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => preshared_key = Some(key_bytes.0), Err(_) => return EINVAL, }, "endpoint" => match val.parse::<SocketAddr>() { Ok(addr) => endpoint = Some(addr), Err(_) => return EINVAL, }, "persistent_keepalive_interval" => match val.parse::<u16>() { Ok(interval) => keepalive = Some(interval), Err(_) => return EINVAL, }, "replace_allowed_ips" => match val.parse::<bool>() { Ok(true) => replace_ips = true, Ok(false) => replace_ips = false, Err(_) => return EINVAL, }, "allowed_ip" => match val.parse::<AllowedIP>() { Ok(ip) => allowed_ips.push(ip), Err(_) => return EINVAL, }, "public_key" => { // Indicates a new peer section. Commit changes for current peer, and continue to next peer d.update_peer( public_key, remove, replace_ips, endpoint, allowed_ips.as_slice(), keepalive, preshared_key, ); allowed_ips.clear(); //clear the vector content after update match val.parse::<KeyBytes>() { Ok(key_bytes) => public_key = key_bytes.0.into(), Err(_) => return EINVAL, } } "protocol_version" => match val.parse::<u32>() { Ok(1) => {} // Only version 1 is legal _ => return EINVAL, }, _ => return EINVAL, } } cmd.clear(); } 0 }
target_os = "fuchsia", target_os = "linux" ))] "fwmark" => match val.parse::<u32>() {
random_line_split
api.rs
// Copyright (c) 2019 Cloudflare, Inc. All rights reserved. // SPDX-License-Identifier: BSD-3-Clause use super::dev_lock::LockReadGuard; use super::drop_privileges::get_saved_ids; use super::{AllowedIP, Device, Error, SocketAddr}; use crate::device::Action; use crate::serialization::KeyBytes; use crate::x25519; use hex::encode as encode_hex; use libc::*; use std::fs::{create_dir, remove_file}; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::net::{UnixListener, UnixStream}; use std::sync::atomic::Ordering; const SOCK_DIR: &str = "/var/run/wireguard/"; fn create_sock_dir() { let _ = create_dir(SOCK_DIR); // Create the directory if it does not exist if let Ok((saved_uid, saved_gid)) = get_saved_ids() { unsafe { let c_path = std::ffi::CString::new(SOCK_DIR).unwrap(); // The directory is under the root user, but we want to be able to // delete the files there when we exit, so we need to change the owner chown( c_path.as_bytes_with_nul().as_ptr() as _, saved_uid, saved_gid, ); } } } impl Device { /// Register the api handler for this Device. The api handler receives stream connections on a Unix socket /// with a known path: /var/run/wireguard/{tun_name}.sock. pub fn register_api_handler(&mut self) -> Result<(), Error> { let path = format!("{}/{}.sock", SOCK_DIR, self.iface.name()?); create_sock_dir(); let _ = remove_file(&path); // Attempt to remove the socket if already exists let api_listener = UnixListener::bind(&path).map_err(Error::ApiSocket)?; // Bind a new socket to the path self.cleanup_paths.push(path.clone()); self.queue.new_event( api_listener.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api unix socket let (api_conn, _) = match api_listener.accept() { Ok(conn) => conn, _ => return Action::Continue, }; let mut reader = BufReader::new(&api_conn); let mut writer = BufWriter::new(&api_conn); let mut cmd = String::new(); if reader.read_line(&mut cmd).is_ok() { cmd.pop(); // pop the new line character let status = match cmd.as_ref() { // Only two commands are legal according to the protocol, get=1 and set=1. "get=1" => api_get(&mut writer, d), "set=1" => api_set(&mut reader, d), _ => EIO, }; // The protocol requires to return an error code as the response, or zero on success writeln!(writer, "errno={}\n", status).ok(); } Action::Continue // Indicates the worker thread should continue as normal }), )?; self.register_monitor(path)?; self.register_api_signal_handlers() } pub fn
(&mut self, fd: i32) -> Result<(), Error> { let io_file = unsafe { UnixStream::from_raw_fd(fd) }; self.queue.new_event( io_file.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api file descriptor let mut reader = BufReader::new(&io_file); let mut writer = BufWriter::new(&io_file); let mut cmd = String::new(); if reader.read_line(&mut cmd).is_ok() { cmd.pop(); // pop the new line character let status = match cmd.as_ref() { // Only two commands are legal according to the protocol, get=1 and set=1. "get=1" => api_get(&mut writer, d), "set=1" => api_set(&mut reader, d), _ => EIO, }; // The protocol requires to return an error code as the response, or zero on success writeln!(writer, "errno={}\n", status).ok(); } else { // The remote side is likely closed; we should trigger an exit. d.trigger_exit(); return Action::Exit; } Action::Continue // Indicates the worker thread should continue as normal }), )?; Ok(()) } fn register_monitor(&self, path: String) -> Result<(), Error> { self.queue.new_periodic_event( Box::new(move |d, _| { // This is not a very nice hack to detect if the control socket was removed // and exiting nicely as a result. We check every 3 seconds in a loop if the // file was deleted by stating it. // The problem is that on linux inotify can be used quite beautifully to detect // deletion, and kqueue EVFILT_VNODE can be used for the same purpose, but that // will require introducing new events, for no measurable benefit. // TODO: Could this be an issue if we restart the service too quickly? let path = std::path::Path::new(&path); if!path.exists() { d.trigger_exit(); return Action::Exit; } // Periodically read the mtu of the interface in case it changes if let Ok(mtu) = d.iface.mtu() { d.mtu.store(mtu, Ordering::Relaxed); } Action::Continue }), std::time::Duration::from_millis(1000), )?; Ok(()) } fn register_api_signal_handlers(&self) -> Result<(), Error> { self.queue .new_signal_event(SIGINT, Box::new(move |_, _| Action::Exit))?; self.queue .new_signal_event(SIGTERM, Box::new(move |_, _| Action::Exit))?; Ok(()) } } #[allow(unused_must_use)] fn api_get(writer: &mut BufWriter<&UnixStream>, d: &Device) -> i32 { // get command requires an empty line, but there is no reason to be religious about it if let Some(ref k) = d.key_pair { writeln!(writer, "own_public_key={}", encode_hex(k.1.as_bytes())); } if d.listen_port!= 0 { writeln!(writer, "listen_port={}", d.listen_port); } if let Some(fwmark) = d.fwmark { writeln!(writer, "fwmark={}", fwmark); } for (k, p) in d.peers.iter() { let p = p.lock(); writeln!(writer, "public_key={}", encode_hex(k.as_bytes())); if let Some(ref key) = p.preshared_key() { writeln!(writer, "preshared_key={}", encode_hex(key)); } if let Some(keepalive) = p.persistent_keepalive() { writeln!(writer, "persistent_keepalive_interval={}", keepalive); } if let Some(ref addr) = p.endpoint().addr { writeln!(writer, "endpoint={}", addr); } for (ip, cidr) in p.allowed_ips() { writeln!(writer, "allowed_ip={}/{}", ip, cidr); } if let Some(time) = p.time_since_last_handshake() { writeln!(writer, "last_handshake_time_sec={}", time.as_secs()); writeln!(writer, "last_handshake_time_nsec={}", time.subsec_nanos()); } let (_, tx_bytes, rx_bytes,..) = p.tunnel.stats(); writeln!(writer, "rx_bytes={}", rx_bytes); writeln!(writer, "tx_bytes={}", tx_bytes); } 0 } fn api_set(reader: &mut BufReader<&UnixStream>, d: &mut LockReadGuard<Device>) -> i32 { d.try_writeable( |device| device.trigger_yield(), |device| { device.cancel_yield(); let mut cmd = String::new(); while reader.read_line(&mut cmd).is_ok() { cmd.pop(); // remove newline if any if cmd.is_empty() { return 0; // Done } { let parsed_cmd: Vec<&str> = cmd.split('=').collect(); if parsed_cmd.len()!= 2 { return EPROTO; } let (key, val) = (parsed_cmd[0], parsed_cmd[1]); match key { "private_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => { device.set_key(x25519::StaticSecret::from(key_bytes.0)) } Err(_) => return EINVAL, }, "listen_port" => match val.parse::<u16>() { Ok(port) => match device.open_listen_socket(port) { Ok(()) => {} Err(_) => return EADDRINUSE, }, Err(_) => return EINVAL, }, #[cfg(any( target_os = "android", target_os = "fuchsia", target_os = "linux" ))] "fwmark" => match val.parse::<u32>() { Ok(mark) => match device.set_fwmark(mark) { Ok(()) => {} Err(_) => return EADDRINUSE, }, Err(_) => return EINVAL, }, "replace_peers" => match val.parse::<bool>() { Ok(true) => device.clear_peers(), Ok(false) => {} Err(_) => return EINVAL, }, "public_key" => match val.parse::<KeyBytes>() { // Indicates a new peer section Ok(key_bytes) => { return api_set_peer( reader, device, x25519::PublicKey::from(key_bytes.0), ) } Err(_) => return EINVAL, }, _ => return EINVAL, } } cmd.clear(); } 0 }, ) .unwrap_or(EIO) } fn api_set_peer( reader: &mut BufReader<&UnixStream>, d: &mut Device, pub_key: x25519::PublicKey, ) -> i32 { let mut cmd = String::new(); let mut remove = false; let mut replace_ips = false; let mut endpoint = None; let mut keepalive = None; let mut public_key = pub_key; let mut preshared_key = None; let mut allowed_ips: Vec<AllowedIP> = vec![]; while reader.read_line(&mut cmd).is_ok() { cmd.pop(); // remove newline if any if cmd.is_empty() { d.update_peer( public_key, remove, replace_ips, endpoint, allowed_ips.as_slice(), keepalive, preshared_key, ); allowed_ips.clear(); //clear the vector content after update return 0; // Done } { let parsed_cmd: Vec<&str> = cmd.splitn(2, '=').collect(); if parsed_cmd.len()!= 2 { return EPROTO; } let (key, val) = (parsed_cmd[0], parsed_cmd[1]); match key { "remove" => match val.parse::<bool>() { Ok(true) => remove = true, Ok(false) => remove = false, Err(_) => return EINVAL, }, "preshared_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => preshared_key = Some(key_bytes.0), Err(_) => return EINVAL, }, "endpoint" => match val.parse::<SocketAddr>() { Ok(addr) => endpoint = Some(addr), Err(_) => return EINVAL, }, "persistent_keepalive_interval" => match val.parse::<u16>() { Ok(interval) => keepalive = Some(interval), Err(_) => return EINVAL, }, "replace_allowed_ips" => match val.parse::<bool>() { Ok(true) => replace_ips = true, Ok(false) => replace_ips = false, Err(_) => return EINVAL, }, "allowed_ip" => match val.parse::<AllowedIP>() { Ok(ip) => allowed_ips.push(ip), Err(_) => return EINVAL, }, "public_key" => { // Indicates a new peer section. Commit changes for current peer, and continue to next peer d.update_peer( public_key, remove, replace_ips, endpoint, allowed_ips.as_slice(), keepalive, preshared_key, ); allowed_ips.clear(); //clear the vector content after update match val.parse::<KeyBytes>() { Ok(key_bytes) => public_key = key_bytes.0.into(), Err(_) => return EINVAL, } } "protocol_version" => match val.parse::<u32>() { Ok(1) => {} // Only version 1 is legal _ => return EINVAL, }, _ => return EINVAL, } } cmd.clear(); } 0 }
register_api_fd
identifier_name
api.rs
// Copyright (c) 2019 Cloudflare, Inc. All rights reserved. // SPDX-License-Identifier: BSD-3-Clause use super::dev_lock::LockReadGuard; use super::drop_privileges::get_saved_ids; use super::{AllowedIP, Device, Error, SocketAddr}; use crate::device::Action; use crate::serialization::KeyBytes; use crate::x25519; use hex::encode as encode_hex; use libc::*; use std::fs::{create_dir, remove_file}; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::net::{UnixListener, UnixStream}; use std::sync::atomic::Ordering; const SOCK_DIR: &str = "/var/run/wireguard/"; fn create_sock_dir() { let _ = create_dir(SOCK_DIR); // Create the directory if it does not exist if let Ok((saved_uid, saved_gid)) = get_saved_ids() { unsafe { let c_path = std::ffi::CString::new(SOCK_DIR).unwrap(); // The directory is under the root user, but we want to be able to // delete the files there when we exit, so we need to change the owner chown( c_path.as_bytes_with_nul().as_ptr() as _, saved_uid, saved_gid, ); } } } impl Device { /// Register the api handler for this Device. The api handler receives stream connections on a Unix socket /// with a known path: /var/run/wireguard/{tun_name}.sock. pub fn register_api_handler(&mut self) -> Result<(), Error> { let path = format!("{}/{}.sock", SOCK_DIR, self.iface.name()?); create_sock_dir(); let _ = remove_file(&path); // Attempt to remove the socket if already exists let api_listener = UnixListener::bind(&path).map_err(Error::ApiSocket)?; // Bind a new socket to the path self.cleanup_paths.push(path.clone()); self.queue.new_event( api_listener.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api unix socket let (api_conn, _) = match api_listener.accept() { Ok(conn) => conn, _ => return Action::Continue, }; let mut reader = BufReader::new(&api_conn); let mut writer = BufWriter::new(&api_conn); let mut cmd = String::new(); if reader.read_line(&mut cmd).is_ok() { cmd.pop(); // pop the new line character let status = match cmd.as_ref() { // Only two commands are legal according to the protocol, get=1 and set=1. "get=1" => api_get(&mut writer, d), "set=1" => api_set(&mut reader, d), _ => EIO, }; // The protocol requires to return an error code as the response, or zero on success writeln!(writer, "errno={}\n", status).ok(); } Action::Continue // Indicates the worker thread should continue as normal }), )?; self.register_monitor(path)?; self.register_api_signal_handlers() } pub fn register_api_fd(&mut self, fd: i32) -> Result<(), Error> { let io_file = unsafe { UnixStream::from_raw_fd(fd) }; self.queue.new_event( io_file.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api file descriptor let mut reader = BufReader::new(&io_file); let mut writer = BufWriter::new(&io_file); let mut cmd = String::new(); if reader.read_line(&mut cmd).is_ok() { cmd.pop(); // pop the new line character let status = match cmd.as_ref() { // Only two commands are legal according to the protocol, get=1 and set=1. "get=1" => api_get(&mut writer, d), "set=1" => api_set(&mut reader, d), _ => EIO, }; // The protocol requires to return an error code as the response, or zero on success writeln!(writer, "errno={}\n", status).ok(); } else { // The remote side is likely closed; we should trigger an exit. d.trigger_exit(); return Action::Exit; } Action::Continue // Indicates the worker thread should continue as normal }), )?; Ok(()) } fn register_monitor(&self, path: String) -> Result<(), Error> { self.queue.new_periodic_event( Box::new(move |d, _| { // This is not a very nice hack to detect if the control socket was removed // and exiting nicely as a result. We check every 3 seconds in a loop if the // file was deleted by stating it. // The problem is that on linux inotify can be used quite beautifully to detect // deletion, and kqueue EVFILT_VNODE can be used for the same purpose, but that // will require introducing new events, for no measurable benefit. // TODO: Could this be an issue if we restart the service too quickly? let path = std::path::Path::new(&path); if!path.exists() { d.trigger_exit(); return Action::Exit; } // Periodically read the mtu of the interface in case it changes if let Ok(mtu) = d.iface.mtu() { d.mtu.store(mtu, Ordering::Relaxed); } Action::Continue }), std::time::Duration::from_millis(1000), )?; Ok(()) } fn register_api_signal_handlers(&self) -> Result<(), Error> { self.queue .new_signal_event(SIGINT, Box::new(move |_, _| Action::Exit))?; self.queue .new_signal_event(SIGTERM, Box::new(move |_, _| Action::Exit))?; Ok(()) } } #[allow(unused_must_use)] fn api_get(writer: &mut BufWriter<&UnixStream>, d: &Device) -> i32 { // get command requires an empty line, but there is no reason to be religious about it if let Some(ref k) = d.key_pair { writeln!(writer, "own_public_key={}", encode_hex(k.1.as_bytes())); } if d.listen_port!= 0 { writeln!(writer, "listen_port={}", d.listen_port); } if let Some(fwmark) = d.fwmark { writeln!(writer, "fwmark={}", fwmark); } for (k, p) in d.peers.iter() { let p = p.lock(); writeln!(writer, "public_key={}", encode_hex(k.as_bytes())); if let Some(ref key) = p.preshared_key() { writeln!(writer, "preshared_key={}", encode_hex(key)); } if let Some(keepalive) = p.persistent_keepalive() { writeln!(writer, "persistent_keepalive_interval={}", keepalive); } if let Some(ref addr) = p.endpoint().addr { writeln!(writer, "endpoint={}", addr); } for (ip, cidr) in p.allowed_ips() { writeln!(writer, "allowed_ip={}/{}", ip, cidr); } if let Some(time) = p.time_since_last_handshake() { writeln!(writer, "last_handshake_time_sec={}", time.as_secs()); writeln!(writer, "last_handshake_time_nsec={}", time.subsec_nanos()); } let (_, tx_bytes, rx_bytes,..) = p.tunnel.stats(); writeln!(writer, "rx_bytes={}", rx_bytes); writeln!(writer, "tx_bytes={}", tx_bytes); } 0 } fn api_set(reader: &mut BufReader<&UnixStream>, d: &mut LockReadGuard<Device>) -> i32 { d.try_writeable( |device| device.trigger_yield(), |device| { device.cancel_yield(); let mut cmd = String::new(); while reader.read_line(&mut cmd).is_ok() { cmd.pop(); // remove newline if any if cmd.is_empty() { return 0; // Done } { let parsed_cmd: Vec<&str> = cmd.split('=').collect(); if parsed_cmd.len()!= 2 { return EPROTO; } let (key, val) = (parsed_cmd[0], parsed_cmd[1]); match key { "private_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => { device.set_key(x25519::StaticSecret::from(key_bytes.0)) } Err(_) => return EINVAL, }, "listen_port" => match val.parse::<u16>() { Ok(port) => match device.open_listen_socket(port) { Ok(()) => {} Err(_) => return EADDRINUSE, }, Err(_) => return EINVAL, }, #[cfg(any( target_os = "android", target_os = "fuchsia", target_os = "linux" ))] "fwmark" => match val.parse::<u32>() { Ok(mark) => match device.set_fwmark(mark) { Ok(()) => {} Err(_) => return EADDRINUSE, }, Err(_) => return EINVAL, }, "replace_peers" => match val.parse::<bool>() { Ok(true) => device.clear_peers(), Ok(false) => {} Err(_) => return EINVAL, }, "public_key" => match val.parse::<KeyBytes>() { // Indicates a new peer section Ok(key_bytes) => { return api_set_peer( reader, device, x25519::PublicKey::from(key_bytes.0), ) } Err(_) => return EINVAL, }, _ => return EINVAL, } } cmd.clear(); } 0 }, ) .unwrap_or(EIO) } fn api_set_peer( reader: &mut BufReader<&UnixStream>, d: &mut Device, pub_key: x25519::PublicKey, ) -> i32 { let mut cmd = String::new(); let mut remove = false; let mut replace_ips = false; let mut endpoint = None; let mut keepalive = None; let mut public_key = pub_key; let mut preshared_key = None; let mut allowed_ips: Vec<AllowedIP> = vec![]; while reader.read_line(&mut cmd).is_ok() { cmd.pop(); // remove newline if any if cmd.is_empty() { d.update_peer( public_key, remove, replace_ips, endpoint, allowed_ips.as_slice(), keepalive, preshared_key, ); allowed_ips.clear(); //clear the vector content after update return 0; // Done } { let parsed_cmd: Vec<&str> = cmd.splitn(2, '=').collect(); if parsed_cmd.len()!= 2
let (key, val) = (parsed_cmd[0], parsed_cmd[1]); match key { "remove" => match val.parse::<bool>() { Ok(true) => remove = true, Ok(false) => remove = false, Err(_) => return EINVAL, }, "preshared_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => preshared_key = Some(key_bytes.0), Err(_) => return EINVAL, }, "endpoint" => match val.parse::<SocketAddr>() { Ok(addr) => endpoint = Some(addr), Err(_) => return EINVAL, }, "persistent_keepalive_interval" => match val.parse::<u16>() { Ok(interval) => keepalive = Some(interval), Err(_) => return EINVAL, }, "replace_allowed_ips" => match val.parse::<bool>() { Ok(true) => replace_ips = true, Ok(false) => replace_ips = false, Err(_) => return EINVAL, }, "allowed_ip" => match val.parse::<AllowedIP>() { Ok(ip) => allowed_ips.push(ip), Err(_) => return EINVAL, }, "public_key" => { // Indicates a new peer section. Commit changes for current peer, and continue to next peer d.update_peer( public_key, remove, replace_ips, endpoint, allowed_ips.as_slice(), keepalive, preshared_key, ); allowed_ips.clear(); //clear the vector content after update match val.parse::<KeyBytes>() { Ok(key_bytes) => public_key = key_bytes.0.into(), Err(_) => return EINVAL, } } "protocol_version" => match val.parse::<u32>() { Ok(1) => {} // Only version 1 is legal _ => return EINVAL, }, _ => return EINVAL, } } cmd.clear(); } 0 }
{ return EPROTO; }
conditional_block
report.rs
//! Coverage report generation. //! //! # Template directory structure //! //! The coverage report produce two classes of files: //! //! * One summary page //! * Source file pages, one page per source. //! //! `cargo cov` uses [Tera templates](https://github.com/Keats/tera#readme). Template files are stored using this //! directory structure: //! //! ```text //! cargo-cov/res/templates/«name»/ //! config.toml //! tera/ //! summary_template.ext //! file_template.ext //! ... //! static/ //! common.css //! common.js //! ... //! ``` //! //! When rendered, the output will have this structure: //! //! ```text //! /path/to/workspace/target/cov/report/ //! static/ //! common.css //! common.js //! ... //! summary.ext //! file_123.ext //! file_124.ext //! ... //! ``` //! //! # Summary page //! //! If a summary page is needed, add the following section to `config.toml`: //! //! ```toml //! [summary] //! template = "summary_template.ext" //! output = "summary.ext" //! ``` //! //! The summary page will be rendered to the file `summary.ext` using this data: //! //! ```json //! { //! "crate_path": "/path/to/workspace", //! "files": [ //! { //! "symbol": 123, //! "path": "/path/to/workspace/src/lib.rs", //! "summary": { //! "lines_count": 500, //! "lines_covered": 499, //! "branches_count": 700, //! "branches_executed": 650, //! "branches_taken": 520, //! "functions_count": 40, //! "functions_called": 39 //! } //! }, //! ... //! ] //! } //! ``` //! //! # File pages //! //! If the file pages are needed, add the following section to `config.toml`: //! //! ```toml //! [summary] //! template = "file_template.ext" //! output = "file_{{ symbol }}.ext" //! ``` //! //! The output filename itself is a Tera template. The file pages will be rendered using this data: //! //! ```json //! { //! "crate_path": "/path/to/workspace", //! "symbol": 123, //! "path": "/path/to/workspace/src/lib.rs", //! "summary": { //! "lines_count": 500, //! ... //! }, //! "lines": [ //! { //! "line": 1, //! "source": "/// First line of the source code", //! "count": null, //! "branches": [] //! }, //! { //! "line": 2, //! "source": "pub fn second_line_of_source_code() {", //! "count": 12, //! "branches": [ //! { //! "count": 6, //! "symbol": 456, //! "path": "/path/to/workspace/src/lib.rs", //! "line": 3, //! "column: 0 //! }, //! ... //! ] //! }, //! ... //! ], //! "functions": [ //! { //! "symbol": 789, //! "name": "_ZN10crate_name26second_line_of_source_code17hce04ea776f1a67beE", //! "line": 2, //! "column": 0, //! "summary": { //! "blocks_count": 100, //! "blocks_executed": 90, //! "entry_count": 12, //! "exit_count": 10, //! "branches_count": 250, //! "branches_executed": 225, //! "branches_taken": 219 //! } //! }, //! ... //! ] //! } //! ``` use error::{Result, ResultExt}; use sourcepath::{SourceType, identify_source_path}; use template::new as new_template; use utils::{clean_dir, parent_3}; use copy_dir::copy_dir; use cov::{self, Gcov, Graph, Interner, Report, Symbol}; use serde_json::Value; use tera::{Context, Tera}; use std::ffi::OsStr; use std::fs::{File, create_dir_all, read_dir}; use std::io::{BufRead, BufReader, Read, Write}; use std::path::{Path, PathBuf}; /// Entry point of `cargo cov report` subcommand. Renders the coverage report using a template. pub fn generate(cov_build_path: &Path, template_name: &OsStr, allowed_source_types: SourceType) -> Result<Option<PathBuf>> { let report_path = cov_build_path.with_file_name("report"); clean_dir(&report_path).chain_err(|| "Cannot clean report directory")?; create_dir_all(&report_path)?; let mut interner = Interner::new(); let graph = create_graph(cov_build_path, &mut interner).chain_err(|| "Cannot create graph")?; let report = graph.report(); render(&report_path, template_name, allowed_source_types, &report, &interner).chain_err(|| "Cannot render report") } /// Creates an analyzed [`Graph`] from all GCNO and GCDA inside the `target/cov/build` folder. /// /// [`Graph`]:../../cov/graph/struct.Graph.html fn create_graph(cov_build_path: &Path, interner: &mut Interner) -> cov::Result<Graph> { let mut graph = Graph::default(); for extension in &["gcno", "gcda"] { progress!("Parsing", "*.{} files", extension); for entry in read_dir(cov_build_path.join(extension))? { let path = entry?.path(); if path.extension() == Some(OsStr::new(extension)) { trace!("merging {} {:?}", extension, path); graph.merge(Gcov::open(path, interner)?)?; } } } graph.analyze(); Ok(graph) } /// Renders the `report` into `report_path` using a template. /// /// If the template has a summary page, returns the path of the rendered summary. fn render(report_path: &Path, template_name: &OsStr, allowed_source_types: SourceType, report: &Report, interner: &Interner) -> Result<Option<PathBuf>> { use toml::de::from_slice; let mut template_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); template_path.push("res"); template_path.push("templates"); template_path.push(template_name); trace!("using templates at {:?}", template_path); // Read the template configuration. template_path.push("config.toml"); let mut config_file = File::open(&template_path).chain_err(|| format!("Cannot open template at `{}`", template_path.display()))?; let mut config_bytes = Vec::new(); config_file.read_to_end(&mut config_bytes)?; let config: Config = from_slice(&config_bytes).chain_err(|| "Cannot read template configuration")?; // Copy the static resources if exist. template_path.set_file_name("static"); if template_path.is_dir() { copy_dir(&template_path, report_path.join("static"))?; } template_path.set_file_name("tera"); template_path.push("*"); // The report path is at $crate/target/cov/report, so we call.parent() three times. let crate_path = parent_3(report_path).to_string_lossy(); let mut tera = new_template(template_path.to_str().expect("UTF-8 template path"))?; let mut report_files = report .files .iter() .filter_map(|(&symbol, file)| { let path = &interner[symbol]; let source_type = identify_source_path(path, &crate_path).0; if allowed_source_types.contains(source_type) { Some(ReportFileEntry { symbol, source_type, path, file, }) } else { None } }) .collect::<Vec<_>>(); report_files.sort_by_key(|entry| (entry.source_type, entry.path)); let summary_path = if let Some(summary) = config.summary { Some(write_summary(report_path, &report_files, &tera, &crate_path, &summary).chain_err(|| "Cannot write summary")?) } else { None }; if let Some(files_config) = config.files { tera.add_raw_template("", files_config.output)?; for entry in &report_files { write_file(report_path, interner, entry, &tera, &crate_path, files_config.template).chain_err(|| format!("Cannot write file at `{}`", entry.path))?; } } Ok(summary_path) } struct ReportFileEntry<'a> { symbol: Symbol, source_type: SourceType, path: &'a str, file: &'a ::cov::report::File, } #[derive(Deserialize, Debug)] struct Config<'a> { #[serde(borrow)] summary: Option<FileConfig<'a>>, #[serde(borrow)] files: Option<FileConfig<'a>>, } #[derive(Deserialize, Debug)] struct FileConfig<'a> { #[serde(borrow)] output: &'a str, #[serde(borrow)] template: &'a str, } /// Renders the summary page. fn wr
eport_path: &Path, report_files: &[ReportFileEntry], tera: &Tera, crate_path: &str, config: &FileConfig) -> Result<PathBuf> { let path = report_path.join(config.output); let mut context = Context::new(); let files = report_files .iter() .map(|entry| { json!({ "symbol": entry.symbol, "path": entry.path, "summary": entry.file.summary(), }) }) .collect::<Vec<_>>(); context.add("crate_path", &crate_path); context.add("files", &files); let rendered = tera.render(config.template, &context)?; let mut summary_file = File::create(&path)?; summary_file.write_all(rendered.as_bytes())?; progress!("Created", "{}", path.display()); Ok(path) } /// Renders report for a source path. fn write_file(report_path: &Path, interner: &Interner, entry: &ReportFileEntry, tera: &Tera, crate_path: &str, template_name: &str) -> Result<()> { let mut context = Context::new(); let mut lines = Vec::new(); let mut source_line_number = 1; // Read the source file. if let Ok(source_file) = File::open(entry.path) { let source_file = BufReader::new(source_file); for source_line in source_file.lines() { let (count, branches) = if let Some(line) = entry.file.lines.get(&source_line_number) { let (count, branches) = serialize_line(line, interner); (Some(count), branches) } else { (None, Vec::new()) }; lines.push(json!({ "line": source_line_number, "source": source_line?, "count": count, "branches": branches, })); source_line_number += 1; } } // Add the remaining lines absent from the source file. lines.extend(entry.file.lines.range(source_line_number..).map(|(line_number, line)| { let (count, branches) = serialize_line(line, interner); json!({ "line": *line_number, "count": Some(count), "source": Value::Null, "branches": branches, }) })); // Collect function info let functions = entry .file .functions .iter() .map(|f| { let name = &interner[f.name]; json!({ "symbol": f.name, "name": name, "line": f.line, "column": f.column, "summary": &f.summary, }) }) .collect::<Vec<_>>(); context.add("crate_path", &crate_path); context.add("symbol", &entry.symbol); context.add("path", &entry.path); context.add("summary", &entry.file.summary()); context.add("lines", &lines); context.add("functions", &functions); let filename = tera.render("", &context)?; let path = report_path.join(filename); let rendered = tera.render(template_name, &context)?; let mut file_file = File::create(path)?; file_file.write_all(rendered.as_bytes())?; Ok(()) } /// Serializes a source line as a branch target into JSON value. fn serialize_line(line: &::cov::report::Line, interner: &Interner) -> (u64, Vec<Value>) { ( line.count, line.branches .iter() .map(|branch| { json!({ "count": branch.count, "symbol": branch.filename, "path": &interner[branch.filename], "line": branch.line, "column": branch.column, }) }) .collect(), ) }
ite_summary(r
identifier_name
report.rs
//! Coverage report generation. //! //! # Template directory structure //! //! The coverage report produce two classes of files: //! //! * One summary page //! * Source file pages, one page per source. //! //! `cargo cov` uses [Tera templates](https://github.com/Keats/tera#readme). Template files are stored using this //! directory structure: //! //! ```text //! cargo-cov/res/templates/«name»/ //! config.toml //! tera/ //! summary_template.ext //! file_template.ext //! ... //! static/ //! common.css //! common.js //! ... //! ``` //! //! When rendered, the output will have this structure: //! //! ```text //! /path/to/workspace/target/cov/report/ //! static/ //! common.css //! common.js //! ... //! summary.ext //! file_123.ext //! file_124.ext //! ... //! ``` //! //! # Summary page //! //! If a summary page is needed, add the following section to `config.toml`: //! //! ```toml //! [summary] //! template = "summary_template.ext" //! output = "summary.ext" //! ``` //! //! The summary page will be rendered to the file `summary.ext` using this data: //! //! ```json //! { //! "crate_path": "/path/to/workspace", //! "files": [ //! { //! "symbol": 123, //! "path": "/path/to/workspace/src/lib.rs", //! "summary": { //! "lines_count": 500, //! "lines_covered": 499, //! "branches_count": 700, //! "branches_executed": 650, //! "branches_taken": 520, //! "functions_count": 40, //! "functions_called": 39 //! } //! }, //! ... //! ] //! } //! ``` //! //! # File pages //! //! If the file pages are needed, add the following section to `config.toml`: //! //! ```toml //! [summary] //! template = "file_template.ext" //! output = "file_{{ symbol }}.ext" //! ``` //! //! The output filename itself is a Tera template. The file pages will be rendered using this data: //! //! ```json //! { //! "crate_path": "/path/to/workspace", //! "symbol": 123, //! "path": "/path/to/workspace/src/lib.rs", //! "summary": { //! "lines_count": 500, //! ... //! }, //! "lines": [ //! { //! "line": 1, //! "source": "/// First line of the source code", //! "count": null, //! "branches": [] //! }, //! { //! "line": 2, //! "source": "pub fn second_line_of_source_code() {", //! "count": 12, //! "branches": [ //! { //! "count": 6, //! "symbol": 456, //! "path": "/path/to/workspace/src/lib.rs", //! "line": 3, //! "column: 0 //! }, //! ... //! ] //! }, //! ... //! ], //! "functions": [ //! { //! "symbol": 789, //! "name": "_ZN10crate_name26second_line_of_source_code17hce04ea776f1a67beE", //! "line": 2, //! "column": 0, //! "summary": { //! "blocks_count": 100, //! "blocks_executed": 90, //! "entry_count": 12, //! "exit_count": 10,
//! } //! }, //! ... //! ] //! } //! ``` use error::{Result, ResultExt}; use sourcepath::{SourceType, identify_source_path}; use template::new as new_template; use utils::{clean_dir, parent_3}; use copy_dir::copy_dir; use cov::{self, Gcov, Graph, Interner, Report, Symbol}; use serde_json::Value; use tera::{Context, Tera}; use std::ffi::OsStr; use std::fs::{File, create_dir_all, read_dir}; use std::io::{BufRead, BufReader, Read, Write}; use std::path::{Path, PathBuf}; /// Entry point of `cargo cov report` subcommand. Renders the coverage report using a template. pub fn generate(cov_build_path: &Path, template_name: &OsStr, allowed_source_types: SourceType) -> Result<Option<PathBuf>> { let report_path = cov_build_path.with_file_name("report"); clean_dir(&report_path).chain_err(|| "Cannot clean report directory")?; create_dir_all(&report_path)?; let mut interner = Interner::new(); let graph = create_graph(cov_build_path, &mut interner).chain_err(|| "Cannot create graph")?; let report = graph.report(); render(&report_path, template_name, allowed_source_types, &report, &interner).chain_err(|| "Cannot render report") } /// Creates an analyzed [`Graph`] from all GCNO and GCDA inside the `target/cov/build` folder. /// /// [`Graph`]:../../cov/graph/struct.Graph.html fn create_graph(cov_build_path: &Path, interner: &mut Interner) -> cov::Result<Graph> { let mut graph = Graph::default(); for extension in &["gcno", "gcda"] { progress!("Parsing", "*.{} files", extension); for entry in read_dir(cov_build_path.join(extension))? { let path = entry?.path(); if path.extension() == Some(OsStr::new(extension)) { trace!("merging {} {:?}", extension, path); graph.merge(Gcov::open(path, interner)?)?; } } } graph.analyze(); Ok(graph) } /// Renders the `report` into `report_path` using a template. /// /// If the template has a summary page, returns the path of the rendered summary. fn render(report_path: &Path, template_name: &OsStr, allowed_source_types: SourceType, report: &Report, interner: &Interner) -> Result<Option<PathBuf>> { use toml::de::from_slice; let mut template_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); template_path.push("res"); template_path.push("templates"); template_path.push(template_name); trace!("using templates at {:?}", template_path); // Read the template configuration. template_path.push("config.toml"); let mut config_file = File::open(&template_path).chain_err(|| format!("Cannot open template at `{}`", template_path.display()))?; let mut config_bytes = Vec::new(); config_file.read_to_end(&mut config_bytes)?; let config: Config = from_slice(&config_bytes).chain_err(|| "Cannot read template configuration")?; // Copy the static resources if exist. template_path.set_file_name("static"); if template_path.is_dir() { copy_dir(&template_path, report_path.join("static"))?; } template_path.set_file_name("tera"); template_path.push("*"); // The report path is at $crate/target/cov/report, so we call.parent() three times. let crate_path = parent_3(report_path).to_string_lossy(); let mut tera = new_template(template_path.to_str().expect("UTF-8 template path"))?; let mut report_files = report .files .iter() .filter_map(|(&symbol, file)| { let path = &interner[symbol]; let source_type = identify_source_path(path, &crate_path).0; if allowed_source_types.contains(source_type) { Some(ReportFileEntry { symbol, source_type, path, file, }) } else { None } }) .collect::<Vec<_>>(); report_files.sort_by_key(|entry| (entry.source_type, entry.path)); let summary_path = if let Some(summary) = config.summary { Some(write_summary(report_path, &report_files, &tera, &crate_path, &summary).chain_err(|| "Cannot write summary")?) } else { None }; if let Some(files_config) = config.files { tera.add_raw_template("", files_config.output)?; for entry in &report_files { write_file(report_path, interner, entry, &tera, &crate_path, files_config.template).chain_err(|| format!("Cannot write file at `{}`", entry.path))?; } } Ok(summary_path) } struct ReportFileEntry<'a> { symbol: Symbol, source_type: SourceType, path: &'a str, file: &'a ::cov::report::File, } #[derive(Deserialize, Debug)] struct Config<'a> { #[serde(borrow)] summary: Option<FileConfig<'a>>, #[serde(borrow)] files: Option<FileConfig<'a>>, } #[derive(Deserialize, Debug)] struct FileConfig<'a> { #[serde(borrow)] output: &'a str, #[serde(borrow)] template: &'a str, } /// Renders the summary page. fn write_summary(report_path: &Path, report_files: &[ReportFileEntry], tera: &Tera, crate_path: &str, config: &FileConfig) -> Result<PathBuf> { let path = report_path.join(config.output); let mut context = Context::new(); let files = report_files .iter() .map(|entry| { json!({ "symbol": entry.symbol, "path": entry.path, "summary": entry.file.summary(), }) }) .collect::<Vec<_>>(); context.add("crate_path", &crate_path); context.add("files", &files); let rendered = tera.render(config.template, &context)?; let mut summary_file = File::create(&path)?; summary_file.write_all(rendered.as_bytes())?; progress!("Created", "{}", path.display()); Ok(path) } /// Renders report for a source path. fn write_file(report_path: &Path, interner: &Interner, entry: &ReportFileEntry, tera: &Tera, crate_path: &str, template_name: &str) -> Result<()> { let mut context = Context::new(); let mut lines = Vec::new(); let mut source_line_number = 1; // Read the source file. if let Ok(source_file) = File::open(entry.path) { let source_file = BufReader::new(source_file); for source_line in source_file.lines() { let (count, branches) = if let Some(line) = entry.file.lines.get(&source_line_number) { let (count, branches) = serialize_line(line, interner); (Some(count), branches) } else { (None, Vec::new()) }; lines.push(json!({ "line": source_line_number, "source": source_line?, "count": count, "branches": branches, })); source_line_number += 1; } } // Add the remaining lines absent from the source file. lines.extend(entry.file.lines.range(source_line_number..).map(|(line_number, line)| { let (count, branches) = serialize_line(line, interner); json!({ "line": *line_number, "count": Some(count), "source": Value::Null, "branches": branches, }) })); // Collect function info let functions = entry .file .functions .iter() .map(|f| { let name = &interner[f.name]; json!({ "symbol": f.name, "name": name, "line": f.line, "column": f.column, "summary": &f.summary, }) }) .collect::<Vec<_>>(); context.add("crate_path", &crate_path); context.add("symbol", &entry.symbol); context.add("path", &entry.path); context.add("summary", &entry.file.summary()); context.add("lines", &lines); context.add("functions", &functions); let filename = tera.render("", &context)?; let path = report_path.join(filename); let rendered = tera.render(template_name, &context)?; let mut file_file = File::create(path)?; file_file.write_all(rendered.as_bytes())?; Ok(()) } /// Serializes a source line as a branch target into JSON value. fn serialize_line(line: &::cov::report::Line, interner: &Interner) -> (u64, Vec<Value>) { ( line.count, line.branches .iter() .map(|branch| { json!({ "count": branch.count, "symbol": branch.filename, "path": &interner[branch.filename], "line": branch.line, "column": branch.column, }) }) .collect(), ) }
//! "branches_count": 250, //! "branches_executed": 225, //! "branches_taken": 219
random_line_split
report.rs
//! Coverage report generation. //! //! # Template directory structure //! //! The coverage report produce two classes of files: //! //! * One summary page //! * Source file pages, one page per source. //! //! `cargo cov` uses [Tera templates](https://github.com/Keats/tera#readme). Template files are stored using this //! directory structure: //! //! ```text //! cargo-cov/res/templates/«name»/ //! config.toml //! tera/ //! summary_template.ext //! file_template.ext //! ... //! static/ //! common.css //! common.js //! ... //! ``` //! //! When rendered, the output will have this structure: //! //! ```text //! /path/to/workspace/target/cov/report/ //! static/ //! common.css //! common.js //! ... //! summary.ext //! file_123.ext //! file_124.ext //! ... //! ``` //! //! # Summary page //! //! If a summary page is needed, add the following section to `config.toml`: //! //! ```toml //! [summary] //! template = "summary_template.ext" //! output = "summary.ext" //! ``` //! //! The summary page will be rendered to the file `summary.ext` using this data: //! //! ```json //! { //! "crate_path": "/path/to/workspace", //! "files": [ //! { //! "symbol": 123, //! "path": "/path/to/workspace/src/lib.rs", //! "summary": { //! "lines_count": 500, //! "lines_covered": 499, //! "branches_count": 700, //! "branches_executed": 650, //! "branches_taken": 520, //! "functions_count": 40, //! "functions_called": 39 //! } //! }, //! ... //! ] //! } //! ``` //! //! # File pages //! //! If the file pages are needed, add the following section to `config.toml`: //! //! ```toml //! [summary] //! template = "file_template.ext" //! output = "file_{{ symbol }}.ext" //! ``` //! //! The output filename itself is a Tera template. The file pages will be rendered using this data: //! //! ```json //! { //! "crate_path": "/path/to/workspace", //! "symbol": 123, //! "path": "/path/to/workspace/src/lib.rs", //! "summary": { //! "lines_count": 500, //! ... //! }, //! "lines": [ //! { //! "line": 1, //! "source": "/// First line of the source code", //! "count": null, //! "branches": [] //! }, //! { //! "line": 2, //! "source": "pub fn second_line_of_source_code() {", //! "count": 12, //! "branches": [ //! { //! "count": 6, //! "symbol": 456, //! "path": "/path/to/workspace/src/lib.rs", //! "line": 3, //! "column: 0 //! }, //! ... //! ] //! }, //! ... //! ], //! "functions": [ //! { //! "symbol": 789, //! "name": "_ZN10crate_name26second_line_of_source_code17hce04ea776f1a67beE", //! "line": 2, //! "column": 0, //! "summary": { //! "blocks_count": 100, //! "blocks_executed": 90, //! "entry_count": 12, //! "exit_count": 10, //! "branches_count": 250, //! "branches_executed": 225, //! "branches_taken": 219 //! } //! }, //! ... //! ] //! } //! ``` use error::{Result, ResultExt}; use sourcepath::{SourceType, identify_source_path}; use template::new as new_template; use utils::{clean_dir, parent_3}; use copy_dir::copy_dir; use cov::{self, Gcov, Graph, Interner, Report, Symbol}; use serde_json::Value; use tera::{Context, Tera}; use std::ffi::OsStr; use std::fs::{File, create_dir_all, read_dir}; use std::io::{BufRead, BufReader, Read, Write}; use std::path::{Path, PathBuf}; /// Entry point of `cargo cov report` subcommand. Renders the coverage report using a template. pub fn generate(cov_build_path: &Path, template_name: &OsStr, allowed_source_types: SourceType) -> Result<Option<PathBuf>> { let report_path = cov_build_path.with_file_name("report"); clean_dir(&report_path).chain_err(|| "Cannot clean report directory")?; create_dir_all(&report_path)?; let mut interner = Interner::new(); let graph = create_graph(cov_build_path, &mut interner).chain_err(|| "Cannot create graph")?; let report = graph.report(); render(&report_path, template_name, allowed_source_types, &report, &interner).chain_err(|| "Cannot render report") } /// Creates an analyzed [`Graph`] from all GCNO and GCDA inside the `target/cov/build` folder. /// /// [`Graph`]:../../cov/graph/struct.Graph.html fn create_graph(cov_build_path: &Path, interner: &mut Interner) -> cov::Result<Graph> {
/// Renders the `report` into `report_path` using a template. /// /// If the template has a summary page, returns the path of the rendered summary. fn render(report_path: &Path, template_name: &OsStr, allowed_source_types: SourceType, report: &Report, interner: &Interner) -> Result<Option<PathBuf>> { use toml::de::from_slice; let mut template_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); template_path.push("res"); template_path.push("templates"); template_path.push(template_name); trace!("using templates at {:?}", template_path); // Read the template configuration. template_path.push("config.toml"); let mut config_file = File::open(&template_path).chain_err(|| format!("Cannot open template at `{}`", template_path.display()))?; let mut config_bytes = Vec::new(); config_file.read_to_end(&mut config_bytes)?; let config: Config = from_slice(&config_bytes).chain_err(|| "Cannot read template configuration")?; // Copy the static resources if exist. template_path.set_file_name("static"); if template_path.is_dir() { copy_dir(&template_path, report_path.join("static"))?; } template_path.set_file_name("tera"); template_path.push("*"); // The report path is at $crate/target/cov/report, so we call.parent() three times. let crate_path = parent_3(report_path).to_string_lossy(); let mut tera = new_template(template_path.to_str().expect("UTF-8 template path"))?; let mut report_files = report .files .iter() .filter_map(|(&symbol, file)| { let path = &interner[symbol]; let source_type = identify_source_path(path, &crate_path).0; if allowed_source_types.contains(source_type) { Some(ReportFileEntry { symbol, source_type, path, file, }) } else { None } }) .collect::<Vec<_>>(); report_files.sort_by_key(|entry| (entry.source_type, entry.path)); let summary_path = if let Some(summary) = config.summary { Some(write_summary(report_path, &report_files, &tera, &crate_path, &summary).chain_err(|| "Cannot write summary")?) } else { None }; if let Some(files_config) = config.files { tera.add_raw_template("", files_config.output)?; for entry in &report_files { write_file(report_path, interner, entry, &tera, &crate_path, files_config.template).chain_err(|| format!("Cannot write file at `{}`", entry.path))?; } } Ok(summary_path) } struct ReportFileEntry<'a> { symbol: Symbol, source_type: SourceType, path: &'a str, file: &'a ::cov::report::File, } #[derive(Deserialize, Debug)] struct Config<'a> { #[serde(borrow)] summary: Option<FileConfig<'a>>, #[serde(borrow)] files: Option<FileConfig<'a>>, } #[derive(Deserialize, Debug)] struct FileConfig<'a> { #[serde(borrow)] output: &'a str, #[serde(borrow)] template: &'a str, } /// Renders the summary page. fn write_summary(report_path: &Path, report_files: &[ReportFileEntry], tera: &Tera, crate_path: &str, config: &FileConfig) -> Result<PathBuf> { let path = report_path.join(config.output); let mut context = Context::new(); let files = report_files .iter() .map(|entry| { json!({ "symbol": entry.symbol, "path": entry.path, "summary": entry.file.summary(), }) }) .collect::<Vec<_>>(); context.add("crate_path", &crate_path); context.add("files", &files); let rendered = tera.render(config.template, &context)?; let mut summary_file = File::create(&path)?; summary_file.write_all(rendered.as_bytes())?; progress!("Created", "{}", path.display()); Ok(path) } /// Renders report for a source path. fn write_file(report_path: &Path, interner: &Interner, entry: &ReportFileEntry, tera: &Tera, crate_path: &str, template_name: &str) -> Result<()> { let mut context = Context::new(); let mut lines = Vec::new(); let mut source_line_number = 1; // Read the source file. if let Ok(source_file) = File::open(entry.path) { let source_file = BufReader::new(source_file); for source_line in source_file.lines() { let (count, branches) = if let Some(line) = entry.file.lines.get(&source_line_number) { let (count, branches) = serialize_line(line, interner); (Some(count), branches) } else { (None, Vec::new()) }; lines.push(json!({ "line": source_line_number, "source": source_line?, "count": count, "branches": branches, })); source_line_number += 1; } } // Add the remaining lines absent from the source file. lines.extend(entry.file.lines.range(source_line_number..).map(|(line_number, line)| { let (count, branches) = serialize_line(line, interner); json!({ "line": *line_number, "count": Some(count), "source": Value::Null, "branches": branches, }) })); // Collect function info let functions = entry .file .functions .iter() .map(|f| { let name = &interner[f.name]; json!({ "symbol": f.name, "name": name, "line": f.line, "column": f.column, "summary": &f.summary, }) }) .collect::<Vec<_>>(); context.add("crate_path", &crate_path); context.add("symbol", &entry.symbol); context.add("path", &entry.path); context.add("summary", &entry.file.summary()); context.add("lines", &lines); context.add("functions", &functions); let filename = tera.render("", &context)?; let path = report_path.join(filename); let rendered = tera.render(template_name, &context)?; let mut file_file = File::create(path)?; file_file.write_all(rendered.as_bytes())?; Ok(()) } /// Serializes a source line as a branch target into JSON value. fn serialize_line(line: &::cov::report::Line, interner: &Interner) -> (u64, Vec<Value>) { ( line.count, line.branches .iter() .map(|branch| { json!({ "count": branch.count, "symbol": branch.filename, "path": &interner[branch.filename], "line": branch.line, "column": branch.column, }) }) .collect(), ) }
let mut graph = Graph::default(); for extension in &["gcno", "gcda"] { progress!("Parsing", "*.{} files", extension); for entry in read_dir(cov_build_path.join(extension))? { let path = entry?.path(); if path.extension() == Some(OsStr::new(extension)) { trace!("merging {} {:?}", extension, path); graph.merge(Gcov::open(path, interner)?)?; } } } graph.analyze(); Ok(graph) }
identifier_body
report.rs
//! Coverage report generation. //! //! # Template directory structure //! //! The coverage report produce two classes of files: //! //! * One summary page //! * Source file pages, one page per source. //! //! `cargo cov` uses [Tera templates](https://github.com/Keats/tera#readme). Template files are stored using this //! directory structure: //! //! ```text //! cargo-cov/res/templates/«name»/ //! config.toml //! tera/ //! summary_template.ext //! file_template.ext //! ... //! static/ //! common.css //! common.js //! ... //! ``` //! //! When rendered, the output will have this structure: //! //! ```text //! /path/to/workspace/target/cov/report/ //! static/ //! common.css //! common.js //! ... //! summary.ext //! file_123.ext //! file_124.ext //! ... //! ``` //! //! # Summary page //! //! If a summary page is needed, add the following section to `config.toml`: //! //! ```toml //! [summary] //! template = "summary_template.ext" //! output = "summary.ext" //! ``` //! //! The summary page will be rendered to the file `summary.ext` using this data: //! //! ```json //! { //! "crate_path": "/path/to/workspace", //! "files": [ //! { //! "symbol": 123, //! "path": "/path/to/workspace/src/lib.rs", //! "summary": { //! "lines_count": 500, //! "lines_covered": 499, //! "branches_count": 700, //! "branches_executed": 650, //! "branches_taken": 520, //! "functions_count": 40, //! "functions_called": 39 //! } //! }, //! ... //! ] //! } //! ``` //! //! # File pages //! //! If the file pages are needed, add the following section to `config.toml`: //! //! ```toml //! [summary] //! template = "file_template.ext" //! output = "file_{{ symbol }}.ext" //! ``` //! //! The output filename itself is a Tera template. The file pages will be rendered using this data: //! //! ```json //! { //! "crate_path": "/path/to/workspace", //! "symbol": 123, //! "path": "/path/to/workspace/src/lib.rs", //! "summary": { //! "lines_count": 500, //! ... //! }, //! "lines": [ //! { //! "line": 1, //! "source": "/// First line of the source code", //! "count": null, //! "branches": [] //! }, //! { //! "line": 2, //! "source": "pub fn second_line_of_source_code() {", //! "count": 12, //! "branches": [ //! { //! "count": 6, //! "symbol": 456, //! "path": "/path/to/workspace/src/lib.rs", //! "line": 3, //! "column: 0 //! }, //! ... //! ] //! }, //! ... //! ], //! "functions": [ //! { //! "symbol": 789, //! "name": "_ZN10crate_name26second_line_of_source_code17hce04ea776f1a67beE", //! "line": 2, //! "column": 0, //! "summary": { //! "blocks_count": 100, //! "blocks_executed": 90, //! "entry_count": 12, //! "exit_count": 10, //! "branches_count": 250, //! "branches_executed": 225, //! "branches_taken": 219 //! } //! }, //! ... //! ] //! } //! ``` use error::{Result, ResultExt}; use sourcepath::{SourceType, identify_source_path}; use template::new as new_template; use utils::{clean_dir, parent_3}; use copy_dir::copy_dir; use cov::{self, Gcov, Graph, Interner, Report, Symbol}; use serde_json::Value; use tera::{Context, Tera}; use std::ffi::OsStr; use std::fs::{File, create_dir_all, read_dir}; use std::io::{BufRead, BufReader, Read, Write}; use std::path::{Path, PathBuf}; /// Entry point of `cargo cov report` subcommand. Renders the coverage report using a template. pub fn generate(cov_build_path: &Path, template_name: &OsStr, allowed_source_types: SourceType) -> Result<Option<PathBuf>> { let report_path = cov_build_path.with_file_name("report"); clean_dir(&report_path).chain_err(|| "Cannot clean report directory")?; create_dir_all(&report_path)?; let mut interner = Interner::new(); let graph = create_graph(cov_build_path, &mut interner).chain_err(|| "Cannot create graph")?; let report = graph.report(); render(&report_path, template_name, allowed_source_types, &report, &interner).chain_err(|| "Cannot render report") } /// Creates an analyzed [`Graph`] from all GCNO and GCDA inside the `target/cov/build` folder. /// /// [`Graph`]:../../cov/graph/struct.Graph.html fn create_graph(cov_build_path: &Path, interner: &mut Interner) -> cov::Result<Graph> { let mut graph = Graph::default(); for extension in &["gcno", "gcda"] { progress!("Parsing", "*.{} files", extension); for entry in read_dir(cov_build_path.join(extension))? { let path = entry?.path(); if path.extension() == Some(OsStr::new(extension)) {
} } graph.analyze(); Ok(graph) } /// Renders the `report` into `report_path` using a template. /// /// If the template has a summary page, returns the path of the rendered summary. fn render(report_path: &Path, template_name: &OsStr, allowed_source_types: SourceType, report: &Report, interner: &Interner) -> Result<Option<PathBuf>> { use toml::de::from_slice; let mut template_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); template_path.push("res"); template_path.push("templates"); template_path.push(template_name); trace!("using templates at {:?}", template_path); // Read the template configuration. template_path.push("config.toml"); let mut config_file = File::open(&template_path).chain_err(|| format!("Cannot open template at `{}`", template_path.display()))?; let mut config_bytes = Vec::new(); config_file.read_to_end(&mut config_bytes)?; let config: Config = from_slice(&config_bytes).chain_err(|| "Cannot read template configuration")?; // Copy the static resources if exist. template_path.set_file_name("static"); if template_path.is_dir() { copy_dir(&template_path, report_path.join("static"))?; } template_path.set_file_name("tera"); template_path.push("*"); // The report path is at $crate/target/cov/report, so we call.parent() three times. let crate_path = parent_3(report_path).to_string_lossy(); let mut tera = new_template(template_path.to_str().expect("UTF-8 template path"))?; let mut report_files = report .files .iter() .filter_map(|(&symbol, file)| { let path = &interner[symbol]; let source_type = identify_source_path(path, &crate_path).0; if allowed_source_types.contains(source_type) { Some(ReportFileEntry { symbol, source_type, path, file, }) } else { None } }) .collect::<Vec<_>>(); report_files.sort_by_key(|entry| (entry.source_type, entry.path)); let summary_path = if let Some(summary) = config.summary { Some(write_summary(report_path, &report_files, &tera, &crate_path, &summary).chain_err(|| "Cannot write summary")?) } else { None }; if let Some(files_config) = config.files { tera.add_raw_template("", files_config.output)?; for entry in &report_files { write_file(report_path, interner, entry, &tera, &crate_path, files_config.template).chain_err(|| format!("Cannot write file at `{}`", entry.path))?; } } Ok(summary_path) } struct ReportFileEntry<'a> { symbol: Symbol, source_type: SourceType, path: &'a str, file: &'a ::cov::report::File, } #[derive(Deserialize, Debug)] struct Config<'a> { #[serde(borrow)] summary: Option<FileConfig<'a>>, #[serde(borrow)] files: Option<FileConfig<'a>>, } #[derive(Deserialize, Debug)] struct FileConfig<'a> { #[serde(borrow)] output: &'a str, #[serde(borrow)] template: &'a str, } /// Renders the summary page. fn write_summary(report_path: &Path, report_files: &[ReportFileEntry], tera: &Tera, crate_path: &str, config: &FileConfig) -> Result<PathBuf> { let path = report_path.join(config.output); let mut context = Context::new(); let files = report_files .iter() .map(|entry| { json!({ "symbol": entry.symbol, "path": entry.path, "summary": entry.file.summary(), }) }) .collect::<Vec<_>>(); context.add("crate_path", &crate_path); context.add("files", &files); let rendered = tera.render(config.template, &context)?; let mut summary_file = File::create(&path)?; summary_file.write_all(rendered.as_bytes())?; progress!("Created", "{}", path.display()); Ok(path) } /// Renders report for a source path. fn write_file(report_path: &Path, interner: &Interner, entry: &ReportFileEntry, tera: &Tera, crate_path: &str, template_name: &str) -> Result<()> { let mut context = Context::new(); let mut lines = Vec::new(); let mut source_line_number = 1; // Read the source file. if let Ok(source_file) = File::open(entry.path) { let source_file = BufReader::new(source_file); for source_line in source_file.lines() { let (count, branches) = if let Some(line) = entry.file.lines.get(&source_line_number) { let (count, branches) = serialize_line(line, interner); (Some(count), branches) } else { (None, Vec::new()) }; lines.push(json!({ "line": source_line_number, "source": source_line?, "count": count, "branches": branches, })); source_line_number += 1; } } // Add the remaining lines absent from the source file. lines.extend(entry.file.lines.range(source_line_number..).map(|(line_number, line)| { let (count, branches) = serialize_line(line, interner); json!({ "line": *line_number, "count": Some(count), "source": Value::Null, "branches": branches, }) })); // Collect function info let functions = entry .file .functions .iter() .map(|f| { let name = &interner[f.name]; json!({ "symbol": f.name, "name": name, "line": f.line, "column": f.column, "summary": &f.summary, }) }) .collect::<Vec<_>>(); context.add("crate_path", &crate_path); context.add("symbol", &entry.symbol); context.add("path", &entry.path); context.add("summary", &entry.file.summary()); context.add("lines", &lines); context.add("functions", &functions); let filename = tera.render("", &context)?; let path = report_path.join(filename); let rendered = tera.render(template_name, &context)?; let mut file_file = File::create(path)?; file_file.write_all(rendered.as_bytes())?; Ok(()) } /// Serializes a source line as a branch target into JSON value. fn serialize_line(line: &::cov::report::Line, interner: &Interner) -> (u64, Vec<Value>) { ( line.count, line.branches .iter() .map(|branch| { json!({ "count": branch.count, "symbol": branch.filename, "path": &interner[branch.filename], "line": branch.line, "column": branch.column, }) }) .collect(), ) }
trace!("merging {} {:?}", extension, path); graph.merge(Gcov::open(path, interner)?)?; }
conditional_block
main.rs
= 60; // Second:minute scale. Can be changed for debugging purposes. #[cfg(feature = "tokio")] const COMMAND_DEACTIVATE: u8 = 0; #[cfg(feature = "tokio")] const COMMAND_ACTIVATE: u8 = 1; #[cfg(feature = "tokio")] const COMMAND_TRIGGER: u8 = 2; fn main() { let success = do_main(); std::process::exit(if success { 0 } else { 1 }); } fn do_main() -> bool { let clap_app = ClapApp::new(crate_name!()) .author(crate_authors!()) .version(crate_version!()) // Flags .arg( Arg::with_name("print") .help("Print the idle time to standard output. This is similar to xprintidle.") .long("print") ) .arg( Arg::with_name("not-when-fullscreen") .help("Don't invoke the timer when the current application is fullscreen. \ Useful for preventing the lockscreen when watching videos") .long("not-when-fullscreen") .conflicts_with("print") ) .arg( Arg::with_name("once") .help("Exit after timer command has been invoked once. \ This does not include manual invoking using the socket.") .long("once") .conflicts_with("print") ) // Options .arg( Arg::with_name("time") .help("Set the required amount of idle minutes before invoking timer") .long("time") .takes_value(true) .required_unless("print") .conflicts_with("print") ) .arg( Arg::with_name("timer") .help("Set command to run when the timer goes off") .long("timer") .takes_value(true) .required_unless("print") .conflicts_with("print") ) .arg( Arg::with_name("notify") .help("Run the command passed by --notifier _ seconds before timer goes off") .long("notify") .takes_value(true) .requires("notifier") .conflicts_with("print") ) .arg( Arg::with_name("notifier") .help("Set the command to run when notifier goes off (see --notify)") .long("notifier") .takes_value(true) .requires("notify") .conflicts_with("print") ) .arg( Arg::with_name("canceller") .help("Set the command to run when user cancels the timer after the notifier has already gone off") .long("canceller") .takes_value(true) .requires("notify") .conflicts_with("print") ); #[cfg(feature = "tokio")] let mut clap_app = clap_app; // make mutable #[cfg(feature = "tokio")] { clap_app = clap_app .arg( Arg::with_name("socket") .help("Listen to events over a unix socket") .long("socket") .takes_value(true) .conflicts_with("print") ); } #[cfg(feature = "pulse")] { clap_app = clap_app .arg( Arg::with_name("not-when-audio") .help("Don't invoke the timer when any audio is playing (PulseAudio specific)") .long("not-when-audio") .conflicts_with("print") ); } let matches = clap_app.get_matches(); let display = unsafe { XOpenDisplay(ptr::null()) }; if display.is_null() { eprintln!("failed to open x server"); return false; } let _cleanup = DeferXClose(display); let info = unsafe { XScreenSaverAllocInfo() }; let _cleanup = DeferXFree(info as *mut c_void); if matches.is_present("print") { if let Ok(idle) = get_idle(display, info) { println!("{}", idle); } return true; } let time = value_t_or_exit!(matches, "time", u32) as u64 * SCALE; let app = App { active: true, audio: false, delay: Duration::from_secs(SCALE), display: display, info: info, not_when_fullscreen: matches.is_present("not-when-fullscreen"), once: matches.is_present("once"), time: time, timer: matches.value_of("timer").unwrap().to_string(), notify: value_t!(matches, "notify", u32).ok().map(|notify| notify as u64), notifier: matches.value_of("notifier").map(String::from), canceller: matches.value_of("canceller").map(String::from), ran_notify: false, ran_timer: false, fullscreen: None, time_new: time }; #[cfg(not(feature = "tokio"))] { let mut app = app; loop { if let Some(exit) = app.step() { return exit; } thread::sleep(app.delay); } } #[cfg(feature = "tokio")] { #[cfg(feature = "pulse")] let not_when_audio = matches.is_present("not-when-audio"); let socket = matches.value_of("socket"); let app = Rc::new(RefCell::new(app)); let mut core = Core::new().unwrap(); let handle = Rc::new(core.handle()); let (tx_stop, rx_stop) = mpsc::channel(1); let tx_stop = Some(tx_stop); let tx_stop_clone = RefCell::new(tx_stop.clone()); if let Err(err) = ctrlc::set_handler(move || { if let Some(tx_stop) = tx_stop_clone.borrow_mut().take() { tx_stop.send(()).wait().unwrap(); } }) { eprintln!("failed to create signal handler: {}", err); } if let Some(socket) = socket { let listener = match UnixListener::bind(socket, &handle) { Ok(listener) => listener, Err(err) => { eprintln!("failed to bind unix socket: {}", err); return false; } }; let app = Rc::clone(&app); let handle_clone = Rc::clone(&handle); handle.spawn(listener.incoming() .map_err(|err| eprintln!("listener error: {}", err)) .for_each(move |(conn, _)| { let app = Rc::clone(&app); handle_clone.spawn(future::loop_fn(conn, move |conn| { let app = Rc::clone(&app); io::read_exact(conn, [0; 1]) .map_err(|err| { if err.kind()!= ErrorKind::UnexpectedEof { eprintln!("io error: {}", err); } }) .and_then(move |(conn, buf)| { match buf[0] { COMMAND_ACTIVATE => app.borrow_mut().active = true, COMMAND_DEACTIVATE => app.borrow_mut().active = false, COMMAND_TRIGGER => app.borrow().trigger(), x => eprintln!("unix socket: invalid command: {}", x) } Ok(Loop::Continue(conn)) }) })); Ok(()) })) } #[cfg(feature = "pulse")] let mut _tx_pulse = None; // Keep sender alive. This must be declared after _pulse so it's dropped before. #[cfg(feature = "pulse")] let mut _pulse = None; // Keep pulse alive #[cfg(feature = "pulse")] { if not_when_audio { enum Event { Clear, New, Finish } let (tx, rx) = mpsc::unbounded::<Event>(); // Can't do this last because we need the updated pointer _tx_pulse = Some(tx); let tx = _tx_pulse.as_mut().unwrap(); let pulse = PulseAudio::default(); extern "C" fn sink_info_callback( _: *mut pa_context, info: *const pa_sink_input_info, _: i32, userdata: *mut c_void ) { unsafe { let tx = userdata as *mut _ as *mut mpsc::UnboundedSender<Event>; if info.is_null() { (&*tx).unbounded_send(Event::Finish).unwrap(); } else if (*info).corked == 0 { (&*tx).unbounded_send(Event::New).unwrap(); } } } extern "C" fn subscribe_callback( ctx: *mut pa_context, _: pa_subscription_event_type_t, _: u32, userdata: *mut c_void ) { unsafe { let tx = userdata as *mut _ as *mut mpsc::UnboundedSender<Event>; (&*tx).unbounded_send(Event::Clear).unwrap(); // You *could* keep track of events here (like making change events toggle the on/off status), // but it's not reliable pa_context_get_sink_input_info_list(ctx, Some(sink_info_callback), userdata); } } extern "C" fn state_callback(ctx: *mut pa_context, userdata: *mut c_void) { unsafe { let state = pa_context_get_state(ctx); if state == PA_CONTEXT_READY { pa_context_set_subscribe_callback(ctx, Some(subscribe_callback), userdata); pa_context_subscribe(ctx, PA_SUBSCRIPTION_MASK_SINK_INPUT, None, ptr::null_mut()); // In case audio already plays pa_context_get_sink_input_info_list(ctx, Some(sink_info_callback), userdata); } } } let mut playing = 0; let app = Rc::clone(&app); handle.spawn(rx.for_each(move |event| { match event { Event::Clear => playing = 0, Event::New => playing += 1, Event::Finish => { // We've successfully counted all playing inputs app.borrow_mut().audio = playing!= 0; } } Ok(()) })); let userdata = tx as *mut _ as *mut c_void; unsafe { pa_context_set_state_callback(pulse.ctx, Some(state_callback), userdata); pa_context_connect(pulse.ctx, ptr::null(), 0, ptr::null()); pa_threaded_mainloop_start(pulse.main); } // Keep pulse alive _pulse = Some(pulse); } } let handle_clone = Rc::clone(&handle); handle.spawn(future::loop_fn((), move |_| { let mut tx_stop = tx_stop.clone(); let app = Rc::clone(&app); let delay = app.borrow().delay; Timeout::new(delay, &handle_clone) .unwrap() .map_err(|_| ()) .and_then(move |_| { let step = app.borrow_mut().step(); if step.is_none() { return Ok(Loop::Continue(())); } tx_stop.take().unwrap().send(()).wait().unwrap(); if step.unwrap() { Ok(Loop::Break(())) } else { Err(()) } }) })); let status = core.run(rx_stop.into_future()).is_ok(); if let Some(socket) = socket { if let Err(err) = fs::remove_file(socket) { eprintln!("failed to clean up unix socket: {}", err); } } status } } struct App { active: bool, audio: bool, delay: Duration, display: *mut Display, info: *mut XScreenSaverInfo, not_when_fullscreen: bool, once: bool, time: u64, timer: String, notify: Option<u64>, notifier: Option<String>, canceller: Option<String>, ran_notify: bool, ran_timer: bool, fullscreen: Option<bool>, time_new: u64 } impl App { fn step(&mut self) -> Option<bool> { let active = self.active &&!self.audio; // audio is always false when not-when-audio isn't set, don't worry let default_delay = Duration::from_secs(SCALE); // TODO: const fn let idle = if active
else { None }; if active && self.notify.map(|notify| (idle.unwrap() + notify) >= self.time).unwrap_or(idle.unwrap() >= self.time) { let idle = idle.unwrap(); if self.not_when_fullscreen && self.fullscreen.is_none() { let mut focus = 0u64; let mut revert = 0i32; let mut actual_type = 0u64; let mut actual_format = 0i32; let mut nitems = 0u64; let mut bytes = 0u64; let mut data: *mut u8 = unsafe { mem::uninitialized() }; self.fullscreen = Some(unsafe { XGetInputFocus(self.display, &mut focus as *mut _, &mut revert as *mut _); let cstring = CString::from_vec_unchecked("_NET_WM_STATE".into()); if XGetWindowProperty( self.display, focus, XInternAtom(self.display, cstring.as_ptr(), 0), 0, !0, 0, XA_ATOM, &mut actual_type, &mut actual_format, &mut nitems, &mut bytes, &mut data )!= 0 { eprintln!("failed to get window property"); false } else { // Welcome to hell. // I spent waay to long trying to get `data` to work. // Currently it returns 75, because it overflows 331 to fit into a byte.
{ Some(match get_idle(self.display, self.info) { Ok(idle) => idle / 1000, // Convert to seconds Err(_) => return Some(false) }) }
conditional_block
main.rs
64 = 60; // Second:minute scale. Can be changed for debugging purposes. #[cfg(feature = "tokio")] const COMMAND_DEACTIVATE: u8 = 0; #[cfg(feature = "tokio")] const COMMAND_ACTIVATE: u8 = 1; #[cfg(feature = "tokio")] const COMMAND_TRIGGER: u8 = 2; fn main() { let success = do_main(); std::process::exit(if success { 0 } else { 1 }); } fn do_main() -> bool { let clap_app = ClapApp::new(crate_name!()) .author(crate_authors!()) .version(crate_version!()) // Flags .arg( Arg::with_name("print") .help("Print the idle time to standard output. This is similar to xprintidle.") .long("print") ) .arg( Arg::with_name("not-when-fullscreen") .help("Don't invoke the timer when the current application is fullscreen. \ Useful for preventing the lockscreen when watching videos") .long("not-when-fullscreen") .conflicts_with("print") ) .arg( Arg::with_name("once") .help("Exit after timer command has been invoked once. \ This does not include manual invoking using the socket.") .long("once") .conflicts_with("print") ) // Options .arg( Arg::with_name("time") .help("Set the required amount of idle minutes before invoking timer") .long("time") .takes_value(true) .required_unless("print") .conflicts_with("print") ) .arg( Arg::with_name("timer") .help("Set command to run when the timer goes off") .long("timer") .takes_value(true) .required_unless("print") .conflicts_with("print") ) .arg( Arg::with_name("notify") .help("Run the command passed by --notifier _ seconds before timer goes off") .long("notify") .takes_value(true) .requires("notifier") .conflicts_with("print") ) .arg( Arg::with_name("notifier") .help("Set the command to run when notifier goes off (see --notify)") .long("notifier") .takes_value(true) .requires("notify") .conflicts_with("print") ) .arg( Arg::with_name("canceller") .help("Set the command to run when user cancels the timer after the notifier has already gone off") .long("canceller") .takes_value(true) .requires("notify") .conflicts_with("print") ); #[cfg(feature = "tokio")] let mut clap_app = clap_app; // make mutable #[cfg(feature = "tokio")] { clap_app = clap_app .arg( Arg::with_name("socket") .help("Listen to events over a unix socket") .long("socket") .takes_value(true) .conflicts_with("print") ); } #[cfg(feature = "pulse")] { clap_app = clap_app .arg( Arg::with_name("not-when-audio") .help("Don't invoke the timer when any audio is playing (PulseAudio specific)") .long("not-when-audio") .conflicts_with("print") ); } let matches = clap_app.get_matches(); let display = unsafe { XOpenDisplay(ptr::null()) }; if display.is_null() { eprintln!("failed to open x server"); return false; } let _cleanup = DeferXClose(display); let info = unsafe { XScreenSaverAllocInfo() }; let _cleanup = DeferXFree(info as *mut c_void); if matches.is_present("print") { if let Ok(idle) = get_idle(display, info) { println!("{}", idle); } return true; } let time = value_t_or_exit!(matches, "time", u32) as u64 * SCALE; let app = App { active: true, audio: false, delay: Duration::from_secs(SCALE), display: display, info: info, not_when_fullscreen: matches.is_present("not-when-fullscreen"), once: matches.is_present("once"), time: time, timer: matches.value_of("timer").unwrap().to_string(), notify: value_t!(matches, "notify", u32).ok().map(|notify| notify as u64), notifier: matches.value_of("notifier").map(String::from), canceller: matches.value_of("canceller").map(String::from), ran_notify: false, ran_timer: false, fullscreen: None, time_new: time }; #[cfg(not(feature = "tokio"))] { let mut app = app; loop { if let Some(exit) = app.step() { return exit; }
} #[cfg(feature = "tokio")] { #[cfg(feature = "pulse")] let not_when_audio = matches.is_present("not-when-audio"); let socket = matches.value_of("socket"); let app = Rc::new(RefCell::new(app)); let mut core = Core::new().unwrap(); let handle = Rc::new(core.handle()); let (tx_stop, rx_stop) = mpsc::channel(1); let tx_stop = Some(tx_stop); let tx_stop_clone = RefCell::new(tx_stop.clone()); if let Err(err) = ctrlc::set_handler(move || { if let Some(tx_stop) = tx_stop_clone.borrow_mut().take() { tx_stop.send(()).wait().unwrap(); } }) { eprintln!("failed to create signal handler: {}", err); } if let Some(socket) = socket { let listener = match UnixListener::bind(socket, &handle) { Ok(listener) => listener, Err(err) => { eprintln!("failed to bind unix socket: {}", err); return false; } }; let app = Rc::clone(&app); let handle_clone = Rc::clone(&handle); handle.spawn(listener.incoming() .map_err(|err| eprintln!("listener error: {}", err)) .for_each(move |(conn, _)| { let app = Rc::clone(&app); handle_clone.spawn(future::loop_fn(conn, move |conn| { let app = Rc::clone(&app); io::read_exact(conn, [0; 1]) .map_err(|err| { if err.kind()!= ErrorKind::UnexpectedEof { eprintln!("io error: {}", err); } }) .and_then(move |(conn, buf)| { match buf[0] { COMMAND_ACTIVATE => app.borrow_mut().active = true, COMMAND_DEACTIVATE => app.borrow_mut().active = false, COMMAND_TRIGGER => app.borrow().trigger(), x => eprintln!("unix socket: invalid command: {}", x) } Ok(Loop::Continue(conn)) }) })); Ok(()) })) } #[cfg(feature = "pulse")] let mut _tx_pulse = None; // Keep sender alive. This must be declared after _pulse so it's dropped before. #[cfg(feature = "pulse")] let mut _pulse = None; // Keep pulse alive #[cfg(feature = "pulse")] { if not_when_audio { enum Event { Clear, New, Finish } let (tx, rx) = mpsc::unbounded::<Event>(); // Can't do this last because we need the updated pointer _tx_pulse = Some(tx); let tx = _tx_pulse.as_mut().unwrap(); let pulse = PulseAudio::default(); extern "C" fn sink_info_callback( _: *mut pa_context, info: *const pa_sink_input_info, _: i32, userdata: *mut c_void ) { unsafe { let tx = userdata as *mut _ as *mut mpsc::UnboundedSender<Event>; if info.is_null() { (&*tx).unbounded_send(Event::Finish).unwrap(); } else if (*info).corked == 0 { (&*tx).unbounded_send(Event::New).unwrap(); } } } extern "C" fn subscribe_callback( ctx: *mut pa_context, _: pa_subscription_event_type_t, _: u32, userdata: *mut c_void ) { unsafe { let tx = userdata as *mut _ as *mut mpsc::UnboundedSender<Event>; (&*tx).unbounded_send(Event::Clear).unwrap(); // You *could* keep track of events here (like making change events toggle the on/off status), // but it's not reliable pa_context_get_sink_input_info_list(ctx, Some(sink_info_callback), userdata); } } extern "C" fn state_callback(ctx: *mut pa_context, userdata: *mut c_void) { unsafe { let state = pa_context_get_state(ctx); if state == PA_CONTEXT_READY { pa_context_set_subscribe_callback(ctx, Some(subscribe_callback), userdata); pa_context_subscribe(ctx, PA_SUBSCRIPTION_MASK_SINK_INPUT, None, ptr::null_mut()); // In case audio already plays pa_context_get_sink_input_info_list(ctx, Some(sink_info_callback), userdata); } } } let mut playing = 0; let app = Rc::clone(&app); handle.spawn(rx.for_each(move |event| { match event { Event::Clear => playing = 0, Event::New => playing += 1, Event::Finish => { // We've successfully counted all playing inputs app.borrow_mut().audio = playing!= 0; } } Ok(()) })); let userdata = tx as *mut _ as *mut c_void; unsafe { pa_context_set_state_callback(pulse.ctx, Some(state_callback), userdata); pa_context_connect(pulse.ctx, ptr::null(), 0, ptr::null()); pa_threaded_mainloop_start(pulse.main); } // Keep pulse alive _pulse = Some(pulse); } } let handle_clone = Rc::clone(&handle); handle.spawn(future::loop_fn((), move |_| { let mut tx_stop = tx_stop.clone(); let app = Rc::clone(&app); let delay = app.borrow().delay; Timeout::new(delay, &handle_clone) .unwrap() .map_err(|_| ()) .and_then(move |_| { let step = app.borrow_mut().step(); if step.is_none() { return Ok(Loop::Continue(())); } tx_stop.take().unwrap().send(()).wait().unwrap(); if step.unwrap() { Ok(Loop::Break(())) } else { Err(()) } }) })); let status = core.run(rx_stop.into_future()).is_ok(); if let Some(socket) = socket { if let Err(err) = fs::remove_file(socket) { eprintln!("failed to clean up unix socket: {}", err); } } status } } struct App { active: bool, audio: bool, delay: Duration, display: *mut Display, info: *mut XScreenSaverInfo, not_when_fullscreen: bool, once: bool, time: u64, timer: String, notify: Option<u64>, notifier: Option<String>, canceller: Option<String>, ran_notify: bool, ran_timer: bool, fullscreen: Option<bool>, time_new: u64 } impl App { fn step(&mut self) -> Option<bool> { let active = self.active &&!self.audio; // audio is always false when not-when-audio isn't set, don't worry let default_delay = Duration::from_secs(SCALE); // TODO: const fn let idle = if active { Some(match get_idle(self.display, self.info) { Ok(idle) => idle / 1000, // Convert to seconds Err(_) => return Some(false) }) } else { None }; if active && self.notify.map(|notify| (idle.unwrap() + notify) >= self.time).unwrap_or(idle.unwrap() >= self.time) { let idle = idle.unwrap(); if self.not_when_fullscreen && self.fullscreen.is_none() { let mut focus = 0u64; let mut revert = 0i32; let mut actual_type = 0u64; let mut actual_format = 0i32; let mut nitems = 0u64; let mut bytes = 0u64; let mut data: *mut u8 = unsafe { mem::uninitialized() }; self.fullscreen = Some(unsafe { XGetInputFocus(self.display, &mut focus as *mut _, &mut revert as *mut _); let cstring = CString::from_vec_unchecked("_NET_WM_STATE".into()); if XGetWindowProperty( self.display, focus, XInternAtom(self.display, cstring.as_ptr(), 0), 0, !0, 0, XA_ATOM, &mut actual_type, &mut actual_format, &mut nitems, &mut bytes, &mut data )!= 0 { eprintln!("failed to get window property"); false } else { // Welcome to hell. // I spent waay to long trying to get `data` to work. // Currently it returns 75, because it overflows 331 to fit into a byte.
thread::sleep(app.delay); }
random_line_split
main.rs
= 60; // Second:minute scale. Can be changed for debugging purposes. #[cfg(feature = "tokio")] const COMMAND_DEACTIVATE: u8 = 0; #[cfg(feature = "tokio")] const COMMAND_ACTIVATE: u8 = 1; #[cfg(feature = "tokio")] const COMMAND_TRIGGER: u8 = 2; fn main() { let success = do_main(); std::process::exit(if success { 0 } else { 1 }); } fn do_main() -> bool { let clap_app = ClapApp::new(crate_name!()) .author(crate_authors!()) .version(crate_version!()) // Flags .arg( Arg::with_name("print") .help("Print the idle time to standard output. This is similar to xprintidle.") .long("print") ) .arg( Arg::with_name("not-when-fullscreen") .help("Don't invoke the timer when the current application is fullscreen. \ Useful for preventing the lockscreen when watching videos") .long("not-when-fullscreen") .conflicts_with("print") ) .arg( Arg::with_name("once") .help("Exit after timer command has been invoked once. \ This does not include manual invoking using the socket.") .long("once") .conflicts_with("print") ) // Options .arg( Arg::with_name("time") .help("Set the required amount of idle minutes before invoking timer") .long("time") .takes_value(true) .required_unless("print") .conflicts_with("print") ) .arg( Arg::with_name("timer") .help("Set command to run when the timer goes off") .long("timer") .takes_value(true) .required_unless("print") .conflicts_with("print") ) .arg( Arg::with_name("notify") .help("Run the command passed by --notifier _ seconds before timer goes off") .long("notify") .takes_value(true) .requires("notifier") .conflicts_with("print") ) .arg( Arg::with_name("notifier") .help("Set the command to run when notifier goes off (see --notify)") .long("notifier") .takes_value(true) .requires("notify") .conflicts_with("print") ) .arg( Arg::with_name("canceller") .help("Set the command to run when user cancels the timer after the notifier has already gone off") .long("canceller") .takes_value(true) .requires("notify") .conflicts_with("print") ); #[cfg(feature = "tokio")] let mut clap_app = clap_app; // make mutable #[cfg(feature = "tokio")] { clap_app = clap_app .arg( Arg::with_name("socket") .help("Listen to events over a unix socket") .long("socket") .takes_value(true) .conflicts_with("print") ); } #[cfg(feature = "pulse")] { clap_app = clap_app .arg( Arg::with_name("not-when-audio") .help("Don't invoke the timer when any audio is playing (PulseAudio specific)") .long("not-when-audio") .conflicts_with("print") ); } let matches = clap_app.get_matches(); let display = unsafe { XOpenDisplay(ptr::null()) }; if display.is_null() { eprintln!("failed to open x server"); return false; } let _cleanup = DeferXClose(display); let info = unsafe { XScreenSaverAllocInfo() }; let _cleanup = DeferXFree(info as *mut c_void); if matches.is_present("print") { if let Ok(idle) = get_idle(display, info) { println!("{}", idle); } return true; } let time = value_t_or_exit!(matches, "time", u32) as u64 * SCALE; let app = App { active: true, audio: false, delay: Duration::from_secs(SCALE), display: display, info: info, not_when_fullscreen: matches.is_present("not-when-fullscreen"), once: matches.is_present("once"), time: time, timer: matches.value_of("timer").unwrap().to_string(), notify: value_t!(matches, "notify", u32).ok().map(|notify| notify as u64), notifier: matches.value_of("notifier").map(String::from), canceller: matches.value_of("canceller").map(String::from), ran_notify: false, ran_timer: false, fullscreen: None, time_new: time }; #[cfg(not(feature = "tokio"))] { let mut app = app; loop { if let Some(exit) = app.step() { return exit; } thread::sleep(app.delay); } } #[cfg(feature = "tokio")] { #[cfg(feature = "pulse")] let not_when_audio = matches.is_present("not-when-audio"); let socket = matches.value_of("socket"); let app = Rc::new(RefCell::new(app)); let mut core = Core::new().unwrap(); let handle = Rc::new(core.handle()); let (tx_stop, rx_stop) = mpsc::channel(1); let tx_stop = Some(tx_stop); let tx_stop_clone = RefCell::new(tx_stop.clone()); if let Err(err) = ctrlc::set_handler(move || { if let Some(tx_stop) = tx_stop_clone.borrow_mut().take() { tx_stop.send(()).wait().unwrap(); } }) { eprintln!("failed to create signal handler: {}", err); } if let Some(socket) = socket { let listener = match UnixListener::bind(socket, &handle) { Ok(listener) => listener, Err(err) => { eprintln!("failed to bind unix socket: {}", err); return false; } }; let app = Rc::clone(&app); let handle_clone = Rc::clone(&handle); handle.spawn(listener.incoming() .map_err(|err| eprintln!("listener error: {}", err)) .for_each(move |(conn, _)| { let app = Rc::clone(&app); handle_clone.spawn(future::loop_fn(conn, move |conn| { let app = Rc::clone(&app); io::read_exact(conn, [0; 1]) .map_err(|err| { if err.kind()!= ErrorKind::UnexpectedEof { eprintln!("io error: {}", err); } }) .and_then(move |(conn, buf)| { match buf[0] { COMMAND_ACTIVATE => app.borrow_mut().active = true, COMMAND_DEACTIVATE => app.borrow_mut().active = false, COMMAND_TRIGGER => app.borrow().trigger(), x => eprintln!("unix socket: invalid command: {}", x) } Ok(Loop::Continue(conn)) }) })); Ok(()) })) } #[cfg(feature = "pulse")] let mut _tx_pulse = None; // Keep sender alive. This must be declared after _pulse so it's dropped before. #[cfg(feature = "pulse")] let mut _pulse = None; // Keep pulse alive #[cfg(feature = "pulse")] { if not_when_audio { enum Event { Clear, New, Finish } let (tx, rx) = mpsc::unbounded::<Event>(); // Can't do this last because we need the updated pointer _tx_pulse = Some(tx); let tx = _tx_pulse.as_mut().unwrap(); let pulse = PulseAudio::default(); extern "C" fn sink_info_callback( _: *mut pa_context, info: *const pa_sink_input_info, _: i32, userdata: *mut c_void ) { unsafe { let tx = userdata as *mut _ as *mut mpsc::UnboundedSender<Event>; if info.is_null() { (&*tx).unbounded_send(Event::Finish).unwrap(); } else if (*info).corked == 0 { (&*tx).unbounded_send(Event::New).unwrap(); } } } extern "C" fn subscribe_callback( ctx: *mut pa_context, _: pa_subscription_event_type_t, _: u32, userdata: *mut c_void ) { unsafe { let tx = userdata as *mut _ as *mut mpsc::UnboundedSender<Event>; (&*tx).unbounded_send(Event::Clear).unwrap(); // You *could* keep track of events here (like making change events toggle the on/off status), // but it's not reliable pa_context_get_sink_input_info_list(ctx, Some(sink_info_callback), userdata); } } extern "C" fn state_callback(ctx: *mut pa_context, userdata: *mut c_void)
let mut playing = 0; let app = Rc::clone(&app); handle.spawn(rx.for_each(move |event| { match event { Event::Clear => playing = 0, Event::New => playing += 1, Event::Finish => { // We've successfully counted all playing inputs app.borrow_mut().audio = playing!= 0; } } Ok(()) })); let userdata = tx as *mut _ as *mut c_void; unsafe { pa_context_set_state_callback(pulse.ctx, Some(state_callback), userdata); pa_context_connect(pulse.ctx, ptr::null(), 0, ptr::null()); pa_threaded_mainloop_start(pulse.main); } // Keep pulse alive _pulse = Some(pulse); } } let handle_clone = Rc::clone(&handle); handle.spawn(future::loop_fn((), move |_| { let mut tx_stop = tx_stop.clone(); let app = Rc::clone(&app); let delay = app.borrow().delay; Timeout::new(delay, &handle_clone) .unwrap() .map_err(|_| ()) .and_then(move |_| { let step = app.borrow_mut().step(); if step.is_none() { return Ok(Loop::Continue(())); } tx_stop.take().unwrap().send(()).wait().unwrap(); if step.unwrap() { Ok(Loop::Break(())) } else { Err(()) } }) })); let status = core.run(rx_stop.into_future()).is_ok(); if let Some(socket) = socket { if let Err(err) = fs::remove_file(socket) { eprintln!("failed to clean up unix socket: {}", err); } } status } } struct App { active: bool, audio: bool, delay: Duration, display: *mut Display, info: *mut XScreenSaverInfo, not_when_fullscreen: bool, once: bool, time: u64, timer: String, notify: Option<u64>, notifier: Option<String>, canceller: Option<String>, ran_notify: bool, ran_timer: bool, fullscreen: Option<bool>, time_new: u64 } impl App { fn step(&mut self) -> Option<bool> { let active = self.active &&!self.audio; // audio is always false when not-when-audio isn't set, don't worry let default_delay = Duration::from_secs(SCALE); // TODO: const fn let idle = if active { Some(match get_idle(self.display, self.info) { Ok(idle) => idle / 1000, // Convert to seconds Err(_) => return Some(false) }) } else { None }; if active && self.notify.map(|notify| (idle.unwrap() + notify) >= self.time).unwrap_or(idle.unwrap() >= self.time) { let idle = idle.unwrap(); if self.not_when_fullscreen && self.fullscreen.is_none() { let mut focus = 0u64; let mut revert = 0i32; let mut actual_type = 0u64; let mut actual_format = 0i32; let mut nitems = 0u64; let mut bytes = 0u64; let mut data: *mut u8 = unsafe { mem::uninitialized() }; self.fullscreen = Some(unsafe { XGetInputFocus(self.display, &mut focus as *mut _, &mut revert as *mut _); let cstring = CString::from_vec_unchecked("_NET_WM_STATE".into()); if XGetWindowProperty( self.display, focus, XInternAtom(self.display, cstring.as_ptr(), 0), 0, !0, 0, XA_ATOM, &mut actual_type, &mut actual_format, &mut nitems, &mut bytes, &mut data )!= 0 { eprintln!("failed to get window property"); false } else { // Welcome to hell. // I spent waay to long trying to get `data` to work. // Currently it returns 75, because it overflows 331 to fit into a byte.
{ unsafe { let state = pa_context_get_state(ctx); if state == PA_CONTEXT_READY { pa_context_set_subscribe_callback(ctx, Some(subscribe_callback), userdata); pa_context_subscribe(ctx, PA_SUBSCRIPTION_MASK_SINK_INPUT, None, ptr::null_mut()); // In case audio already plays pa_context_get_sink_input_info_list(ctx, Some(sink_info_callback), userdata); } } }
identifier_body
main.rs
.takes_value(true) .requires("notify") .conflicts_with("print") ); #[cfg(feature = "tokio")] let mut clap_app = clap_app; // make mutable #[cfg(feature = "tokio")] { clap_app = clap_app .arg( Arg::with_name("socket") .help("Listen to events over a unix socket") .long("socket") .takes_value(true) .conflicts_with("print") ); } #[cfg(feature = "pulse")] { clap_app = clap_app .arg( Arg::with_name("not-when-audio") .help("Don't invoke the timer when any audio is playing (PulseAudio specific)") .long("not-when-audio") .conflicts_with("print") ); } let matches = clap_app.get_matches(); let display = unsafe { XOpenDisplay(ptr::null()) }; if display.is_null() { eprintln!("failed to open x server"); return false; } let _cleanup = DeferXClose(display); let info = unsafe { XScreenSaverAllocInfo() }; let _cleanup = DeferXFree(info as *mut c_void); if matches.is_present("print") { if let Ok(idle) = get_idle(display, info) { println!("{}", idle); } return true; } let time = value_t_or_exit!(matches, "time", u32) as u64 * SCALE; let app = App { active: true, audio: false, delay: Duration::from_secs(SCALE), display: display, info: info, not_when_fullscreen: matches.is_present("not-when-fullscreen"), once: matches.is_present("once"), time: time, timer: matches.value_of("timer").unwrap().to_string(), notify: value_t!(matches, "notify", u32).ok().map(|notify| notify as u64), notifier: matches.value_of("notifier").map(String::from), canceller: matches.value_of("canceller").map(String::from), ran_notify: false, ran_timer: false, fullscreen: None, time_new: time }; #[cfg(not(feature = "tokio"))] { let mut app = app; loop { if let Some(exit) = app.step() { return exit; } thread::sleep(app.delay); } } #[cfg(feature = "tokio")] { #[cfg(feature = "pulse")] let not_when_audio = matches.is_present("not-when-audio"); let socket = matches.value_of("socket"); let app = Rc::new(RefCell::new(app)); let mut core = Core::new().unwrap(); let handle = Rc::new(core.handle()); let (tx_stop, rx_stop) = mpsc::channel(1); let tx_stop = Some(tx_stop); let tx_stop_clone = RefCell::new(tx_stop.clone()); if let Err(err) = ctrlc::set_handler(move || { if let Some(tx_stop) = tx_stop_clone.borrow_mut().take() { tx_stop.send(()).wait().unwrap(); } }) { eprintln!("failed to create signal handler: {}", err); } if let Some(socket) = socket { let listener = match UnixListener::bind(socket, &handle) { Ok(listener) => listener, Err(err) => { eprintln!("failed to bind unix socket: {}", err); return false; } }; let app = Rc::clone(&app); let handle_clone = Rc::clone(&handle); handle.spawn(listener.incoming() .map_err(|err| eprintln!("listener error: {}", err)) .for_each(move |(conn, _)| { let app = Rc::clone(&app); handle_clone.spawn(future::loop_fn(conn, move |conn| { let app = Rc::clone(&app); io::read_exact(conn, [0; 1]) .map_err(|err| { if err.kind()!= ErrorKind::UnexpectedEof { eprintln!("io error: {}", err); } }) .and_then(move |(conn, buf)| { match buf[0] { COMMAND_ACTIVATE => app.borrow_mut().active = true, COMMAND_DEACTIVATE => app.borrow_mut().active = false, COMMAND_TRIGGER => app.borrow().trigger(), x => eprintln!("unix socket: invalid command: {}", x) } Ok(Loop::Continue(conn)) }) })); Ok(()) })) } #[cfg(feature = "pulse")] let mut _tx_pulse = None; // Keep sender alive. This must be declared after _pulse so it's dropped before. #[cfg(feature = "pulse")] let mut _pulse = None; // Keep pulse alive #[cfg(feature = "pulse")] { if not_when_audio { enum Event { Clear, New, Finish } let (tx, rx) = mpsc::unbounded::<Event>(); // Can't do this last because we need the updated pointer _tx_pulse = Some(tx); let tx = _tx_pulse.as_mut().unwrap(); let pulse = PulseAudio::default(); extern "C" fn sink_info_callback( _: *mut pa_context, info: *const pa_sink_input_info, _: i32, userdata: *mut c_void ) { unsafe { let tx = userdata as *mut _ as *mut mpsc::UnboundedSender<Event>; if info.is_null() { (&*tx).unbounded_send(Event::Finish).unwrap(); } else if (*info).corked == 0 { (&*tx).unbounded_send(Event::New).unwrap(); } } } extern "C" fn subscribe_callback( ctx: *mut pa_context, _: pa_subscription_event_type_t, _: u32, userdata: *mut c_void ) { unsafe { let tx = userdata as *mut _ as *mut mpsc::UnboundedSender<Event>; (&*tx).unbounded_send(Event::Clear).unwrap(); // You *could* keep track of events here (like making change events toggle the on/off status), // but it's not reliable pa_context_get_sink_input_info_list(ctx, Some(sink_info_callback), userdata); } } extern "C" fn state_callback(ctx: *mut pa_context, userdata: *mut c_void) { unsafe { let state = pa_context_get_state(ctx); if state == PA_CONTEXT_READY { pa_context_set_subscribe_callback(ctx, Some(subscribe_callback), userdata); pa_context_subscribe(ctx, PA_SUBSCRIPTION_MASK_SINK_INPUT, None, ptr::null_mut()); // In case audio already plays pa_context_get_sink_input_info_list(ctx, Some(sink_info_callback), userdata); } } } let mut playing = 0; let app = Rc::clone(&app); handle.spawn(rx.for_each(move |event| { match event { Event::Clear => playing = 0, Event::New => playing += 1, Event::Finish => { // We've successfully counted all playing inputs app.borrow_mut().audio = playing!= 0; } } Ok(()) })); let userdata = tx as *mut _ as *mut c_void; unsafe { pa_context_set_state_callback(pulse.ctx, Some(state_callback), userdata); pa_context_connect(pulse.ctx, ptr::null(), 0, ptr::null()); pa_threaded_mainloop_start(pulse.main); } // Keep pulse alive _pulse = Some(pulse); } } let handle_clone = Rc::clone(&handle); handle.spawn(future::loop_fn((), move |_| { let mut tx_stop = tx_stop.clone(); let app = Rc::clone(&app); let delay = app.borrow().delay; Timeout::new(delay, &handle_clone) .unwrap() .map_err(|_| ()) .and_then(move |_| { let step = app.borrow_mut().step(); if step.is_none() { return Ok(Loop::Continue(())); } tx_stop.take().unwrap().send(()).wait().unwrap(); if step.unwrap() { Ok(Loop::Break(())) } else { Err(()) } }) })); let status = core.run(rx_stop.into_future()).is_ok(); if let Some(socket) = socket { if let Err(err) = fs::remove_file(socket) { eprintln!("failed to clean up unix socket: {}", err); } } status } } struct App { active: bool, audio: bool, delay: Duration, display: *mut Display, info: *mut XScreenSaverInfo, not_when_fullscreen: bool, once: bool, time: u64, timer: String, notify: Option<u64>, notifier: Option<String>, canceller: Option<String>, ran_notify: bool, ran_timer: bool, fullscreen: Option<bool>, time_new: u64 } impl App { fn step(&mut self) -> Option<bool> { let active = self.active &&!self.audio; // audio is always false when not-when-audio isn't set, don't worry let default_delay = Duration::from_secs(SCALE); // TODO: const fn let idle = if active { Some(match get_idle(self.display, self.info) { Ok(idle) => idle / 1000, // Convert to seconds Err(_) => return Some(false) }) } else { None }; if active && self.notify.map(|notify| (idle.unwrap() + notify) >= self.time).unwrap_or(idle.unwrap() >= self.time) { let idle = idle.unwrap(); if self.not_when_fullscreen && self.fullscreen.is_none() { let mut focus = 0u64; let mut revert = 0i32; let mut actual_type = 0u64; let mut actual_format = 0i32; let mut nitems = 0u64; let mut bytes = 0u64; let mut data: *mut u8 = unsafe { mem::uninitialized() }; self.fullscreen = Some(unsafe { XGetInputFocus(self.display, &mut focus as *mut _, &mut revert as *mut _); let cstring = CString::from_vec_unchecked("_NET_WM_STATE".into()); if XGetWindowProperty( self.display, focus, XInternAtom(self.display, cstring.as_ptr(), 0), 0, !0, 0, XA_ATOM, &mut actual_type, &mut actual_format, &mut nitems, &mut bytes, &mut data )!= 0 { eprintln!("failed to get window property"); false } else { // Welcome to hell. // I spent waay to long trying to get `data` to work. // Currently it returns 75, because it overflows 331 to fit into a byte. // Changing `data` to a *mut u64 gives me 210453397504. // I have no idea why, and at this point I don't want to know. // So here I'll just compare it to 75 and assume fullscreen. let mut fullscreen = false; for i in 0..nitems as isize { let cstring = CString::from_vec_unchecked("_NET_WM_STATE_FULLSCREEN".into()); if *data.offset(i) == (XInternAtom(self.display, cstring.as_ptr(), 0) & 0xFF) as u8 { fullscreen = true; break; } } XFree(data as *mut c_void); fullscreen } }); } if!self.not_when_fullscreen ||!self.fullscreen.unwrap() { if self.notify.is_some() &&!self.ran_notify { invoke(self.notifier.as_ref().unwrap()); self.ran_notify = true; self.delay = Duration::from_secs(1); // Since the delay is usually a minute, I could've exceeded both the notify and the timer. // The simple solution is to change the timer to a point where it's guaranteed // it's been _ seconds since the notifier. self.time_new = idle + self.notify.unwrap(); } else if idle >= self.time_new &&!self.ran_timer { self.trigger(); if self.once { return Some(true); } self.ran_timer = true; self.delay = default_delay; } } } else { if self.ran_notify &&!self.ran_timer { // In case the user goes back from being idle between the notify and timer if let Some(canceller) = self.canceller.as_ref() { invoke(canceller); } } self.delay = default_delay; self.ran_notify = false; self.ran_timer = false; self.fullscreen = None; } None } fn trigger(&self) { invoke(&self.timer); } } fn
get_idle
identifier_name
decoder.rs
use std::cmp; use std::io::{self, Read}; use encoding_rs::{Decoder, Encoding, UTF_8}; /// A BOM is at least 2 bytes and at most 3 bytes. /// /// If fewer than 2 bytes are available to be read at the beginning of a /// reader, then a BOM is `None`. #[derive(Clone, Copy, Debug, Eq, PartialEq)] struct Bom { bytes: [u8; 3], len: usize, } impl Bom { fn as_slice(&self) -> &[u8] { &self.bytes[0..self.len] } fn decoder(&self) -> Option<Decoder> { let bom = self.as_slice(); if bom.len() < 3 { return None; } if let Some((enc, _)) = Encoding::for_bom(bom) { if enc!= UTF_8 { return Some(enc.new_decoder_with_bom_removal()); } } None } } /// `BomPeeker` wraps `R` and satisfies the `io::Read` interface while also /// providing a peek at the BOM if one exists. Peeking at the BOM does not /// advance the reader. struct BomPeeker<R> { rdr: R, bom: Option<Bom>, nread: usize, } impl<R: io::Read> BomPeeker<R> { /// Create a new BomPeeker. /// /// The first three bytes can be read using the `peek_bom` method, but /// will not advance the reader. fn new(rdr: R) -> BomPeeker<R> { BomPeeker { rdr: rdr, bom: None, nread: 0 } } /// Peek at the first three bytes of the underlying reader. /// /// This does not advance the reader provided by `BomPeeker`. /// /// If the underlying reader does not have at least two bytes available, /// then `None` is returned. fn peek_bom(&mut self) -> io::Result<Bom> { if let Some(bom) = self.bom { return Ok(bom); } self.bom = Some(Bom { bytes: [0; 3], len: 0 }); let mut buf = [0u8; 3]; let bom_len = read_full(&mut self.rdr, &mut buf)?; self.bom = Some(Bom { bytes: buf, len: bom_len }); Ok(self.bom.unwrap()) } } impl<R: io::Read> io::Read for BomPeeker<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { if self.nread < 3 { let bom = self.peek_bom()?; let bom = bom.as_slice(); if self.nread < bom.len() { let rest = &bom[self.nread..]; let len = cmp::min(buf.len(), rest.len()); buf[..len].copy_from_slice(&rest[..len]); self.nread += len; return Ok(len); } } let nread = self.rdr.read(buf)?; self.nread += nread; Ok(nread) } } /// Like `io::Read::read_exact`, except it never returns `UnexpectedEof` and /// instead returns the number of bytes read if EOF is seen before filling /// `buf`. fn read_full<R: io::Read>( mut rdr: R, mut buf: &mut [u8], ) -> io::Result<usize> { let mut nread = 0; while!buf.is_empty() { match rdr.read(buf) { Ok(0) => break,
Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {} Err(e) => return Err(e), } } Ok(nread) } /// A reader that transcodes to UTF-8. The source encoding is determined by /// inspecting the BOM from the stream read from `R`, if one exists. If a /// UTF-16 BOM exists, then the source stream is transcoded to UTF-8 with /// invalid UTF-16 sequences translated to the Unicode replacement character. /// In all other cases, the underlying reader is passed through unchanged. /// /// `R` is the type of the underlying reader and `B` is the type of an internal /// buffer used to store the results of transcoding. /// /// Note that not all methods on `io::Read` work with this implementation. /// For example, the `bytes` adapter method attempts to read a single byte at /// a time, but this implementation requires a buffer of size at least `4`. If /// a buffer of size less than 4 is given, then an error is returned. pub struct DecodeReader<R, B> { /// The underlying reader, wrapped in a peeker for reading a BOM if one /// exists. rdr: BomPeeker<R>, /// The internal buffer to store transcoded bytes before they are read by /// callers. buf: B, /// The current position in `buf`. Subsequent reads start here. pos: usize, /// The number of transcoded bytes in `buf`. Subsequent reads end here. buflen: usize, /// Whether this is the first read or not (in which we inspect the BOM). first: bool, /// Whether a "last" read has occurred. After this point, EOF will always /// be returned. last: bool, /// The underlying text decoder derived from the BOM, if one exists. decoder: Option<Decoder>, } impl<R: io::Read, B: AsMut<[u8]>> DecodeReader<R, B> { /// Create a new transcoder that converts a source stream to valid UTF-8. /// /// If an encoding is specified, then it is used to transcode `rdr` to /// UTF-8. Otherwise, if no encoding is specified, and if a UTF-16 BOM is /// found, then the corresponding UTF-16 encoding is used to transcode /// `rdr` to UTF-8. In all other cases, `rdr` is assumed to be at least /// ASCII-compatible and passed through untouched. /// /// Errors in the encoding of `rdr` are handled with the Unicode /// replacement character. If no encoding of `rdr` is specified, then /// errors are not handled. pub fn new( rdr: R, buf: B, enc: Option<&'static Encoding>, ) -> DecodeReader<R, B> { DecodeReader { rdr: BomPeeker::new(rdr), buf: buf, buflen: 0, pos: 0, first: enc.is_none(), last: false, decoder: enc.map(|enc| enc.new_decoder_with_bom_removal()), } } /// Fill the internal buffer from the underlying reader. /// /// If there are unread bytes in the internal buffer, then we move them /// to the beginning of the internal buffer and fill the remainder. /// /// If the internal buffer is too small to read additional bytes, then an /// error is returned. #[inline(always)] // massive perf benefit (???) fn fill(&mut self) -> io::Result<()> { if self.pos < self.buflen { if self.buflen >= self.buf.as_mut().len() { return Err(io::Error::new( io::ErrorKind::Other, "DecodeReader: internal buffer exhausted")); } let newlen = self.buflen - self.pos; let mut tmp = Vec::with_capacity(newlen); tmp.extend_from_slice(&self.buf.as_mut()[self.pos..self.buflen]); self.buf.as_mut()[..newlen].copy_from_slice(&tmp); self.buflen = newlen; } else { self.buflen = 0; } self.pos = 0; self.buflen += self.rdr.read(&mut self.buf.as_mut()[self.buflen..])?; Ok(()) } /// Transcode the inner stream to UTF-8 in `buf`. This assumes that there /// is a decoder capable of transcoding the inner stream to UTF-8. This /// returns the number of bytes written to `buf`. /// /// When this function returns, exactly one of the following things will /// be true: /// /// 1. A non-zero number of bytes were written to `buf`. /// 2. The underlying reader reached EOF. /// 3. An error is returned: the internal buffer ran out of room. /// 4. An I/O error occurred. /// /// Note that `buf` must have at least 4 bytes of space. fn transcode(&mut self, buf: &mut [u8]) -> io::Result<usize> { assert!(buf.len() >= 4); if self.last { return Ok(0); } if self.pos >= self.buflen { self.fill()?; } let mut nwrite = 0; loop { let (_, nin, nout, _) = self.decoder.as_mut().unwrap().decode_to_utf8( &self.buf.as_mut()[self.pos..self.buflen], buf, false); self.pos += nin; nwrite += nout; // If we've written at least one byte to the caller-provided // buffer, then our mission is complete. if nwrite > 0 { break; } // Otherwise, we know that our internal buffer has insufficient // data to transcode at least one char, so we attempt to refill it. self.fill()?; // Quit on EOF. if self.buflen == 0 { self.pos = 0; self.last = true; let (_, _, nout, _) = self.decoder.as_mut().unwrap().decode_to_utf8( &[], buf, true); return Ok(nout); } } Ok(nwrite) } #[inline(never)] // impacts perf... fn detect(&mut self) -> io::Result<()> { let bom = self.rdr.peek_bom()?; self.decoder = bom.decoder(); Ok(()) } } impl<R: io::Read, B: AsMut<[u8]>> io::Read for DecodeReader<R, B> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { if self.first { self.first = false; self.detect()?; } if self.decoder.is_none() { return self.rdr.read(buf); } // When decoding UTF-8, we need at least 4 bytes of space to guarantee // that we can decode at least one codepoint. If we don't have it, we // can either return `0` for the number of bytes read or return an // error. Since `0` would be interpreted as a possibly premature EOF, // we opt for an error. if buf.len() < 4 { return Err(io::Error::new( io::ErrorKind::Other, "DecodeReader: byte buffer must have length at least 4")); } self.transcode(buf) } } #[cfg(test)] mod tests { use std::io::Read; use encoding_rs::Encoding; use super::{Bom, BomPeeker, DecodeReader}; fn read_to_string<R: Read>(mut rdr: R) -> String { let mut s = String::new(); rdr.read_to_string(&mut s).unwrap(); s } #[test] fn peeker_empty() { let buf = []; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!(Bom { bytes: [0; 3], len: 0}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_one() { let buf = [1]; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!( Bom { bytes: [1, 0, 0], len: 1}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_two() { let buf = [1, 2]; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!( Bom { bytes: [1, 2, 0], len: 2}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(2, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(2, tmp[1]); assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_three() { let buf = [1, 2, 3]; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!( Bom { bytes: [1, 2, 3], len: 3}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(3, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(2, tmp[1]); assert_eq!(3, tmp[2]); assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_four() { let buf = [1, 2, 3, 4]; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!( Bom { bytes: [1, 2, 3], len: 3}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(3, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(2, tmp[1]); assert_eq!(3, tmp[2]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(4, tmp[0]); assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_one_at_a_time() { let buf = [1, 2, 3, 4]; let mut peeker = BomPeeker::new(&buf[..]); let mut tmp = [0; 1]; assert_eq!(0, peeker.read(&mut tmp[..0]).unwrap()); assert_eq!(0, tmp[0]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(2, tmp[0]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(3, tmp[0]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(4, tmp[0]); } // In cases where all we have is a bom, we expect the bytes to be // passed through unchanged. #[test] fn trans_utf16_bom() { let srcbuf = vec![0xFF, 0xFE]; let mut dstbuf = vec![0; 8 * (1<<10)]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); let n = rdr.read(&mut dstbuf).unwrap(); assert_eq!(&*srcbuf, &dstbuf[..n]); let srcbuf = vec![0xFE, 0xFF]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); let n = rdr.read(&mut dstbuf).unwrap(); assert_eq!(&*srcbuf, &dstbuf[..n]); let srcbuf = vec![0xEF, 0xBB, 0xBF]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); let n = rdr.read(&mut dstbuf).unwrap(); assert_eq!(&*srcbuf, &dstbuf[..n]); } // Test basic UTF-16 decoding. #[test] fn trans_utf16_basic() { let srcbuf = vec![0xFF, 0xFE, 0x61, 0x00]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); assert_eq!("a", read_to_string(&mut rdr)); let srcbuf = vec![0xFE, 0xFF, 0x00, 0x61]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); assert_eq!("a", read_to_string(&mut rdr)); } // Test incomplete UTF-16 decoding. This ensures we see a replacement char // if the stream ends with an unpaired code unit. #[test] fn trans_utf16_incomplete() { let srcbuf = vec![0xFF, 0xFE, 0x61, 0x00, 0x00]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); assert_eq!("a\u{FFFD}", read_to_string(&mut rdr)); } macro_rules! test_trans_simple { ($name:ident, $enc:expr, $srcbytes:expr, $dst:expr) => { #[test] fn $name() { let srcbuf = &$srcbytes[..]; let enc = Encoding::for_label($enc.as_bytes()); let mut rdr = DecodeReader::new( &*srcbuf, vec![0; 8 * (1<<10)], enc); assert_eq!($dst, read_to_string(&mut rdr)); } } } // This isn't exhaustive obviously, but it lets us test base level support. test_trans_simple!(trans_simple_auto, "does not exist", b"\xD0\x96", "Ж"); test_trans_simple!(trans_simple_utf8, "utf-8", b"\xD0\x96", "Ж"); test_trans_simple!(trans_simple_utf16le, "utf-16le", b"\x16\x04", "Ж"); test_trans_simple!(trans_simple_utf16be, "utf-16be", b"\x04\x16", "Ж"); test_trans_simple!(trans_simple_chinese, "chinese", b"\xA7\xA8", "Ж"); test_trans_simple!(trans_simple_korean, "korean", b"\xAC\xA8", "Ж"); test_trans_simple!( trans_simple_big5_hkscs, "big5-hkscs", b"\xC7\xFA", "Ж"); test_trans_simple!(trans_simple_gbk, "gbk", b"\xA7\xA8", "Ж"); test_trans_simple!(trans_simple_sjis, "sjis", b"\x84\x47", "Ж"); test_trans_simple!(trans_simple_eucjp, "euc-jp", b"\xA7\xA8", "Ж"); test_trans_simple!(trans_simple_latin1, "latin1", b"\xA9", "©"); }
Ok(n) => { nread += n; let tmp = buf; buf = &mut tmp[n..]; }
random_line_split
decoder.rs
use std::cmp; use std::io::{self, Read}; use encoding_rs::{Decoder, Encoding, UTF_8}; /// A BOM is at least 2 bytes and at most 3 bytes. /// /// If fewer than 2 bytes are available to be read at the beginning of a /// reader, then a BOM is `None`. #[derive(Clone, Copy, Debug, Eq, PartialEq)] struct Bom { bytes: [u8; 3], len: usize, } impl Bom { fn as_slice(&self) -> &[u8] { &self.bytes[0..self.len] } fn decoder(&self) -> Option<Decoder> { let bom = self.as_slice(); if bom.len() < 3 { return None; } if let Some((enc, _)) = Encoding::for_bom(bom) { if enc!= UTF_8 { return Some(enc.new_decoder_with_bom_removal()); } } None } } /// `BomPeeker` wraps `R` and satisfies the `io::Read` interface while also /// providing a peek at the BOM if one exists. Peeking at the BOM does not /// advance the reader. struct BomPeeker<R> { rdr: R, bom: Option<Bom>, nread: usize, } impl<R: io::Read> BomPeeker<R> { /// Create a new BomPeeker. /// /// The first three bytes can be read using the `peek_bom` method, but /// will not advance the reader. fn new(rdr: R) -> BomPeeker<R> { BomPeeker { rdr: rdr, bom: None, nread: 0 } } /// Peek at the first three bytes of the underlying reader. /// /// This does not advance the reader provided by `BomPeeker`. /// /// If the underlying reader does not have at least two bytes available, /// then `None` is returned. fn peek_bom(&mut self) -> io::Result<Bom> { if let Some(bom) = self.bom { return Ok(bom); } self.bom = Some(Bom { bytes: [0; 3], len: 0 }); let mut buf = [0u8; 3]; let bom_len = read_full(&mut self.rdr, &mut buf)?; self.bom = Some(Bom { bytes: buf, len: bom_len }); Ok(self.bom.unwrap()) } } impl<R: io::Read> io::Read for BomPeeker<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { if self.nread < 3 { let bom = self.peek_bom()?; let bom = bom.as_slice(); if self.nread < bom.len() { let rest = &bom[self.nread..]; let len = cmp::min(buf.len(), rest.len()); buf[..len].copy_from_slice(&rest[..len]); self.nread += len; return Ok(len); } } let nread = self.rdr.read(buf)?; self.nread += nread; Ok(nread) } } /// Like `io::Read::read_exact`, except it never returns `UnexpectedEof` and /// instead returns the number of bytes read if EOF is seen before filling /// `buf`. fn read_full<R: io::Read>( mut rdr: R, mut buf: &mut [u8], ) -> io::Result<usize> { let mut nread = 0; while!buf.is_empty() { match rdr.read(buf) { Ok(0) => break, Ok(n) => { nread += n; let tmp = buf; buf = &mut tmp[n..]; } Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {} Err(e) => return Err(e), } } Ok(nread) } /// A reader that transcodes to UTF-8. The source encoding is determined by /// inspecting the BOM from the stream read from `R`, if one exists. If a /// UTF-16 BOM exists, then the source stream is transcoded to UTF-8 with /// invalid UTF-16 sequences translated to the Unicode replacement character. /// In all other cases, the underlying reader is passed through unchanged. /// /// `R` is the type of the underlying reader and `B` is the type of an internal /// buffer used to store the results of transcoding. /// /// Note that not all methods on `io::Read` work with this implementation. /// For example, the `bytes` adapter method attempts to read a single byte at /// a time, but this implementation requires a buffer of size at least `4`. If /// a buffer of size less than 4 is given, then an error is returned. pub struct DecodeReader<R, B> { /// The underlying reader, wrapped in a peeker for reading a BOM if one /// exists. rdr: BomPeeker<R>, /// The internal buffer to store transcoded bytes before they are read by /// callers. buf: B, /// The current position in `buf`. Subsequent reads start here. pos: usize, /// The number of transcoded bytes in `buf`. Subsequent reads end here. buflen: usize, /// Whether this is the first read or not (in which we inspect the BOM). first: bool, /// Whether a "last" read has occurred. After this point, EOF will always /// be returned. last: bool, /// The underlying text decoder derived from the BOM, if one exists. decoder: Option<Decoder>, } impl<R: io::Read, B: AsMut<[u8]>> DecodeReader<R, B> { /// Create a new transcoder that converts a source stream to valid UTF-8. /// /// If an encoding is specified, then it is used to transcode `rdr` to /// UTF-8. Otherwise, if no encoding is specified, and if a UTF-16 BOM is /// found, then the corresponding UTF-16 encoding is used to transcode /// `rdr` to UTF-8. In all other cases, `rdr` is assumed to be at least /// ASCII-compatible and passed through untouched. /// /// Errors in the encoding of `rdr` are handled with the Unicode /// replacement character. If no encoding of `rdr` is specified, then /// errors are not handled. pub fn new( rdr: R, buf: B, enc: Option<&'static Encoding>, ) -> DecodeReader<R, B> { DecodeReader { rdr: BomPeeker::new(rdr), buf: buf, buflen: 0, pos: 0, first: enc.is_none(), last: false, decoder: enc.map(|enc| enc.new_decoder_with_bom_removal()), } } /// Fill the internal buffer from the underlying reader. /// /// If there are unread bytes in the internal buffer, then we move them /// to the beginning of the internal buffer and fill the remainder. /// /// If the internal buffer is too small to read additional bytes, then an /// error is returned. #[inline(always)] // massive perf benefit (???) fn fill(&mut self) -> io::Result<()> { if self.pos < self.buflen { if self.buflen >= self.buf.as_mut().len() { return Err(io::Error::new( io::ErrorKind::Other, "DecodeReader: internal buffer exhausted")); } let newlen = self.buflen - self.pos; let mut tmp = Vec::with_capacity(newlen); tmp.extend_from_slice(&self.buf.as_mut()[self.pos..self.buflen]); self.buf.as_mut()[..newlen].copy_from_slice(&tmp); self.buflen = newlen; } else { self.buflen = 0; } self.pos = 0; self.buflen += self.rdr.read(&mut self.buf.as_mut()[self.buflen..])?; Ok(()) } /// Transcode the inner stream to UTF-8 in `buf`. This assumes that there /// is a decoder capable of transcoding the inner stream to UTF-8. This /// returns the number of bytes written to `buf`. /// /// When this function returns, exactly one of the following things will /// be true: /// /// 1. A non-zero number of bytes were written to `buf`. /// 2. The underlying reader reached EOF. /// 3. An error is returned: the internal buffer ran out of room. /// 4. An I/O error occurred. /// /// Note that `buf` must have at least 4 bytes of space. fn transcode(&mut self, buf: &mut [u8]) -> io::Result<usize> { assert!(buf.len() >= 4); if self.last { return Ok(0); } if self.pos >= self.buflen { self.fill()?; } let mut nwrite = 0; loop { let (_, nin, nout, _) = self.decoder.as_mut().unwrap().decode_to_utf8( &self.buf.as_mut()[self.pos..self.buflen], buf, false); self.pos += nin; nwrite += nout; // If we've written at least one byte to the caller-provided // buffer, then our mission is complete. if nwrite > 0 { break; } // Otherwise, we know that our internal buffer has insufficient // data to transcode at least one char, so we attempt to refill it. self.fill()?; // Quit on EOF. if self.buflen == 0
} Ok(nwrite) } #[inline(never)] // impacts perf... fn detect(&mut self) -> io::Result<()> { let bom = self.rdr.peek_bom()?; self.decoder = bom.decoder(); Ok(()) } } impl<R: io::Read, B: AsMut<[u8]>> io::Read for DecodeReader<R, B> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { if self.first { self.first = false; self.detect()?; } if self.decoder.is_none() { return self.rdr.read(buf); } // When decoding UTF-8, we need at least 4 bytes of space to guarantee // that we can decode at least one codepoint. If we don't have it, we // can either return `0` for the number of bytes read or return an // error. Since `0` would be interpreted as a possibly premature EOF, // we opt for an error. if buf.len() < 4 { return Err(io::Error::new( io::ErrorKind::Other, "DecodeReader: byte buffer must have length at least 4")); } self.transcode(buf) } } #[cfg(test)] mod tests { use std::io::Read; use encoding_rs::Encoding; use super::{Bom, BomPeeker, DecodeReader}; fn read_to_string<R: Read>(mut rdr: R) -> String { let mut s = String::new(); rdr.read_to_string(&mut s).unwrap(); s } #[test] fn peeker_empty() { let buf = []; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!(Bom { bytes: [0; 3], len: 0}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_one() { let buf = [1]; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!( Bom { bytes: [1, 0, 0], len: 1}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_two() { let buf = [1, 2]; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!( Bom { bytes: [1, 2, 0], len: 2}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(2, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(2, tmp[1]); assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_three() { let buf = [1, 2, 3]; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!( Bom { bytes: [1, 2, 3], len: 3}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(3, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(2, tmp[1]); assert_eq!(3, tmp[2]); assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_four() { let buf = [1, 2, 3, 4]; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!( Bom { bytes: [1, 2, 3], len: 3}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(3, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(2, tmp[1]); assert_eq!(3, tmp[2]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(4, tmp[0]); assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_one_at_a_time() { let buf = [1, 2, 3, 4]; let mut peeker = BomPeeker::new(&buf[..]); let mut tmp = [0; 1]; assert_eq!(0, peeker.read(&mut tmp[..0]).unwrap()); assert_eq!(0, tmp[0]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(2, tmp[0]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(3, tmp[0]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(4, tmp[0]); } // In cases where all we have is a bom, we expect the bytes to be // passed through unchanged. #[test] fn trans_utf16_bom() { let srcbuf = vec![0xFF, 0xFE]; let mut dstbuf = vec![0; 8 * (1<<10)]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); let n = rdr.read(&mut dstbuf).unwrap(); assert_eq!(&*srcbuf, &dstbuf[..n]); let srcbuf = vec![0xFE, 0xFF]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); let n = rdr.read(&mut dstbuf).unwrap(); assert_eq!(&*srcbuf, &dstbuf[..n]); let srcbuf = vec![0xEF, 0xBB, 0xBF]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); let n = rdr.read(&mut dstbuf).unwrap(); assert_eq!(&*srcbuf, &dstbuf[..n]); } // Test basic UTF-16 decoding. #[test] fn trans_utf16_basic() { let srcbuf = vec![0xFF, 0xFE, 0x61, 0x00]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); assert_eq!("a", read_to_string(&mut rdr)); let srcbuf = vec![0xFE, 0xFF, 0x00, 0x61]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); assert_eq!("a", read_to_string(&mut rdr)); } // Test incomplete UTF-16 decoding. This ensures we see a replacement char // if the stream ends with an unpaired code unit. #[test] fn trans_utf16_incomplete() { let srcbuf = vec![0xFF, 0xFE, 0x61, 0x00, 0x00]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); assert_eq!("a\u{FFFD}", read_to_string(&mut rdr)); } macro_rules! test_trans_simple { ($name:ident, $enc:expr, $srcbytes:expr, $dst:expr) => { #[test] fn $name() { let srcbuf = &$srcbytes[..]; let enc = Encoding::for_label($enc.as_bytes()); let mut rdr = DecodeReader::new( &*srcbuf, vec![0; 8 * (1<<10)], enc); assert_eq!($dst, read_to_string(&mut rdr)); } } } // This isn't exhaustive obviously, but it lets us test base level support. test_trans_simple!(trans_simple_auto, "does not exist", b"\xD0\x96", "Ж"); test_trans_simple!(trans_simple_utf8, "utf-8", b"\xD0\x96", "Ж"); test_trans_simple!(trans_simple_utf16le, "utf-16le", b"\x16\x04", "Ж"); test_trans_simple!(trans_simple_utf16be, "utf-16be", b"\x04\x16", "Ж"); test_trans_simple!(trans_simple_chinese, "chinese", b"\xA7\xA8", "Ж"); test_trans_simple!(trans_simple_korean, "korean", b"\xAC\xA8", "Ж"); test_trans_simple!( trans_simple_big5_hkscs, "big5-hkscs", b"\xC7\xFA", "Ж"); test_trans_simple!(trans_simple_gbk, "gbk", b"\xA7\xA8", "Ж"); test_trans_simple!(trans_simple_sjis, "sjis", b"\x84\x47", "Ж"); test_trans_simple!(trans_simple_eucjp, "euc-jp", b"\xA7\xA8", "Ж"); test_trans_simple!(trans_simple_latin1, "latin1", b"\xA9", "©"); }
{ self.pos = 0; self.last = true; let (_, _, nout, _) = self.decoder.as_mut().unwrap().decode_to_utf8( &[], buf, true); return Ok(nout); }
conditional_block
decoder.rs
use std::cmp; use std::io::{self, Read}; use encoding_rs::{Decoder, Encoding, UTF_8}; /// A BOM is at least 2 bytes and at most 3 bytes. /// /// If fewer than 2 bytes are available to be read at the beginning of a /// reader, then a BOM is `None`. #[derive(Clone, Copy, Debug, Eq, PartialEq)] struct Bom { bytes: [u8; 3], len: usize, } impl Bom { fn as_slice(&self) -> &[u8] { &self.bytes[0..self.len] } fn decoder(&self) -> Option<Decoder> { let bom = self.as_slice(); if bom.len() < 3 { return None; } if let Some((enc, _)) = Encoding::for_bom(bom) { if enc!= UTF_8 { return Some(enc.new_decoder_with_bom_removal()); } } None } } /// `BomPeeker` wraps `R` and satisfies the `io::Read` interface while also /// providing a peek at the BOM if one exists. Peeking at the BOM does not /// advance the reader. struct BomPeeker<R> { rdr: R, bom: Option<Bom>, nread: usize, } impl<R: io::Read> BomPeeker<R> { /// Create a new BomPeeker. /// /// The first three bytes can be read using the `peek_bom` method, but /// will not advance the reader. fn new(rdr: R) -> BomPeeker<R> { BomPeeker { rdr: rdr, bom: None, nread: 0 } } /// Peek at the first three bytes of the underlying reader. /// /// This does not advance the reader provided by `BomPeeker`. /// /// If the underlying reader does not have at least two bytes available, /// then `None` is returned. fn peek_bom(&mut self) -> io::Result<Bom> { if let Some(bom) = self.bom { return Ok(bom); } self.bom = Some(Bom { bytes: [0; 3], len: 0 }); let mut buf = [0u8; 3]; let bom_len = read_full(&mut self.rdr, &mut buf)?; self.bom = Some(Bom { bytes: buf, len: bom_len }); Ok(self.bom.unwrap()) } } impl<R: io::Read> io::Read for BomPeeker<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { if self.nread < 3 { let bom = self.peek_bom()?; let bom = bom.as_slice(); if self.nread < bom.len() { let rest = &bom[self.nread..]; let len = cmp::min(buf.len(), rest.len()); buf[..len].copy_from_slice(&rest[..len]); self.nread += len; return Ok(len); } } let nread = self.rdr.read(buf)?; self.nread += nread; Ok(nread) } } /// Like `io::Read::read_exact`, except it never returns `UnexpectedEof` and /// instead returns the number of bytes read if EOF is seen before filling /// `buf`. fn read_full<R: io::Read>( mut rdr: R, mut buf: &mut [u8], ) -> io::Result<usize> { let mut nread = 0; while!buf.is_empty() { match rdr.read(buf) { Ok(0) => break, Ok(n) => { nread += n; let tmp = buf; buf = &mut tmp[n..]; } Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {} Err(e) => return Err(e), } } Ok(nread) } /// A reader that transcodes to UTF-8. The source encoding is determined by /// inspecting the BOM from the stream read from `R`, if one exists. If a /// UTF-16 BOM exists, then the source stream is transcoded to UTF-8 with /// invalid UTF-16 sequences translated to the Unicode replacement character. /// In all other cases, the underlying reader is passed through unchanged. /// /// `R` is the type of the underlying reader and `B` is the type of an internal /// buffer used to store the results of transcoding. /// /// Note that not all methods on `io::Read` work with this implementation. /// For example, the `bytes` adapter method attempts to read a single byte at /// a time, but this implementation requires a buffer of size at least `4`. If /// a buffer of size less than 4 is given, then an error is returned. pub struct DecodeReader<R, B> { /// The underlying reader, wrapped in a peeker for reading a BOM if one /// exists. rdr: BomPeeker<R>, /// The internal buffer to store transcoded bytes before they are read by /// callers. buf: B, /// The current position in `buf`. Subsequent reads start here. pos: usize, /// The number of transcoded bytes in `buf`. Subsequent reads end here. buflen: usize, /// Whether this is the first read or not (in which we inspect the BOM). first: bool, /// Whether a "last" read has occurred. After this point, EOF will always /// be returned. last: bool, /// The underlying text decoder derived from the BOM, if one exists. decoder: Option<Decoder>, } impl<R: io::Read, B: AsMut<[u8]>> DecodeReader<R, B> { /// Create a new transcoder that converts a source stream to valid UTF-8. /// /// If an encoding is specified, then it is used to transcode `rdr` to /// UTF-8. Otherwise, if no encoding is specified, and if a UTF-16 BOM is /// found, then the corresponding UTF-16 encoding is used to transcode /// `rdr` to UTF-8. In all other cases, `rdr` is assumed to be at least /// ASCII-compatible and passed through untouched. /// /// Errors in the encoding of `rdr` are handled with the Unicode /// replacement character. If no encoding of `rdr` is specified, then /// errors are not handled. pub fn new( rdr: R, buf: B, enc: Option<&'static Encoding>, ) -> DecodeReader<R, B> { DecodeReader { rdr: BomPeeker::new(rdr), buf: buf, buflen: 0, pos: 0, first: enc.is_none(), last: false, decoder: enc.map(|enc| enc.new_decoder_with_bom_removal()), } } /// Fill the internal buffer from the underlying reader. /// /// If there are unread bytes in the internal buffer, then we move them /// to the beginning of the internal buffer and fill the remainder. /// /// If the internal buffer is too small to read additional bytes, then an /// error is returned. #[inline(always)] // massive perf benefit (???) fn fill(&mut self) -> io::Result<()> { if self.pos < self.buflen { if self.buflen >= self.buf.as_mut().len() { return Err(io::Error::new( io::ErrorKind::Other, "DecodeReader: internal buffer exhausted")); } let newlen = self.buflen - self.pos; let mut tmp = Vec::with_capacity(newlen); tmp.extend_from_slice(&self.buf.as_mut()[self.pos..self.buflen]); self.buf.as_mut()[..newlen].copy_from_slice(&tmp); self.buflen = newlen; } else { self.buflen = 0; } self.pos = 0; self.buflen += self.rdr.read(&mut self.buf.as_mut()[self.buflen..])?; Ok(()) } /// Transcode the inner stream to UTF-8 in `buf`. This assumes that there /// is a decoder capable of transcoding the inner stream to UTF-8. This /// returns the number of bytes written to `buf`. /// /// When this function returns, exactly one of the following things will /// be true: /// /// 1. A non-zero number of bytes were written to `buf`. /// 2. The underlying reader reached EOF. /// 3. An error is returned: the internal buffer ran out of room. /// 4. An I/O error occurred. /// /// Note that `buf` must have at least 4 bytes of space. fn transcode(&mut self, buf: &mut [u8]) -> io::Result<usize> { assert!(buf.len() >= 4); if self.last { return Ok(0); } if self.pos >= self.buflen { self.fill()?; } let mut nwrite = 0; loop { let (_, nin, nout, _) = self.decoder.as_mut().unwrap().decode_to_utf8( &self.buf.as_mut()[self.pos..self.buflen], buf, false); self.pos += nin; nwrite += nout; // If we've written at least one byte to the caller-provided // buffer, then our mission is complete. if nwrite > 0 { break; } // Otherwise, we know that our internal buffer has insufficient // data to transcode at least one char, so we attempt to refill it. self.fill()?; // Quit on EOF. if self.buflen == 0 { self.pos = 0; self.last = true; let (_, _, nout, _) = self.decoder.as_mut().unwrap().decode_to_utf8( &[], buf, true); return Ok(nout); } } Ok(nwrite) } #[inline(never)] // impacts perf... fn detect(&mut self) -> io::Result<()> { let bom = self.rdr.peek_bom()?; self.decoder = bom.decoder(); Ok(()) } } impl<R: io::Read, B: AsMut<[u8]>> io::Read for DecodeReader<R, B> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { if self.first { self.first = false; self.detect()?; } if self.decoder.is_none() { return self.rdr.read(buf); } // When decoding UTF-8, we need at least 4 bytes of space to guarantee // that we can decode at least one codepoint. If we don't have it, we // can either return `0` for the number of bytes read or return an // error. Since `0` would be interpreted as a possibly premature EOF, // we opt for an error. if buf.len() < 4 { return Err(io::Error::new( io::ErrorKind::Other, "DecodeReader: byte buffer must have length at least 4")); } self.transcode(buf) } } #[cfg(test)] mod tests { use std::io::Read; use encoding_rs::Encoding; use super::{Bom, BomPeeker, DecodeReader}; fn read_to_string<R: Read>(mut rdr: R) -> String { let mut s = String::new(); rdr.read_to_string(&mut s).unwrap(); s } #[test] fn peeker_empty() { let buf = []; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!(Bom { bytes: [0; 3], len: 0}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_one() { let buf = [1]; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!( Bom { bytes: [1, 0, 0], len: 1}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_two() { let buf = [1, 2]; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!( Bom { bytes: [1, 2, 0], len: 2}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(2, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(2, tmp[1]); assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_three() { let buf = [1, 2, 3]; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!( Bom { bytes: [1, 2, 3], len: 3}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(3, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(2, tmp[1]); assert_eq!(3, tmp[2]); assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_four() { let buf = [1, 2, 3, 4]; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!( Bom { bytes: [1, 2, 3], len: 3}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(3, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(2, tmp[1]); assert_eq!(3, tmp[2]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(4, tmp[0]); assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_one_at_a_time() { let buf = [1, 2, 3, 4]; let mut peeker = BomPeeker::new(&buf[..]); let mut tmp = [0; 1]; assert_eq!(0, peeker.read(&mut tmp[..0]).unwrap()); assert_eq!(0, tmp[0]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(2, tmp[0]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(3, tmp[0]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(4, tmp[0]); } // In cases where all we have is a bom, we expect the bytes to be // passed through unchanged. #[test] fn
() { let srcbuf = vec![0xFF, 0xFE]; let mut dstbuf = vec![0; 8 * (1<<10)]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); let n = rdr.read(&mut dstbuf).unwrap(); assert_eq!(&*srcbuf, &dstbuf[..n]); let srcbuf = vec![0xFE, 0xFF]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); let n = rdr.read(&mut dstbuf).unwrap(); assert_eq!(&*srcbuf, &dstbuf[..n]); let srcbuf = vec![0xEF, 0xBB, 0xBF]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); let n = rdr.read(&mut dstbuf).unwrap(); assert_eq!(&*srcbuf, &dstbuf[..n]); } // Test basic UTF-16 decoding. #[test] fn trans_utf16_basic() { let srcbuf = vec![0xFF, 0xFE, 0x61, 0x00]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); assert_eq!("a", read_to_string(&mut rdr)); let srcbuf = vec![0xFE, 0xFF, 0x00, 0x61]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); assert_eq!("a", read_to_string(&mut rdr)); } // Test incomplete UTF-16 decoding. This ensures we see a replacement char // if the stream ends with an unpaired code unit. #[test] fn trans_utf16_incomplete() { let srcbuf = vec![0xFF, 0xFE, 0x61, 0x00, 0x00]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); assert_eq!("a\u{FFFD}", read_to_string(&mut rdr)); } macro_rules! test_trans_simple { ($name:ident, $enc:expr, $srcbytes:expr, $dst:expr) => { #[test] fn $name() { let srcbuf = &$srcbytes[..]; let enc = Encoding::for_label($enc.as_bytes()); let mut rdr = DecodeReader::new( &*srcbuf, vec![0; 8 * (1<<10)], enc); assert_eq!($dst, read_to_string(&mut rdr)); } } } // This isn't exhaustive obviously, but it lets us test base level support. test_trans_simple!(trans_simple_auto, "does not exist", b"\xD0\x96", "Ж"); test_trans_simple!(trans_simple_utf8, "utf-8", b"\xD0\x96", "Ж"); test_trans_simple!(trans_simple_utf16le, "utf-16le", b"\x16\x04", "Ж"); test_trans_simple!(trans_simple_utf16be, "utf-16be", b"\x04\x16", "Ж"); test_trans_simple!(trans_simple_chinese, "chinese", b"\xA7\xA8", "Ж"); test_trans_simple!(trans_simple_korean, "korean", b"\xAC\xA8", "Ж"); test_trans_simple!( trans_simple_big5_hkscs, "big5-hkscs", b"\xC7\xFA", "Ж"); test_trans_simple!(trans_simple_gbk, "gbk", b"\xA7\xA8", "Ж"); test_trans_simple!(trans_simple_sjis, "sjis", b"\x84\x47", "Ж"); test_trans_simple!(trans_simple_eucjp, "euc-jp", b"\xA7\xA8", "Ж"); test_trans_simple!(trans_simple_latin1, "latin1", b"\xA9", "©"); }
trans_utf16_bom
identifier_name
decoder.rs
use std::cmp; use std::io::{self, Read}; use encoding_rs::{Decoder, Encoding, UTF_8}; /// A BOM is at least 2 bytes and at most 3 bytes. /// /// If fewer than 2 bytes are available to be read at the beginning of a /// reader, then a BOM is `None`. #[derive(Clone, Copy, Debug, Eq, PartialEq)] struct Bom { bytes: [u8; 3], len: usize, } impl Bom { fn as_slice(&self) -> &[u8] { &self.bytes[0..self.len] } fn decoder(&self) -> Option<Decoder>
} /// `BomPeeker` wraps `R` and satisfies the `io::Read` interface while also /// providing a peek at the BOM if one exists. Peeking at the BOM does not /// advance the reader. struct BomPeeker<R> { rdr: R, bom: Option<Bom>, nread: usize, } impl<R: io::Read> BomPeeker<R> { /// Create a new BomPeeker. /// /// The first three bytes can be read using the `peek_bom` method, but /// will not advance the reader. fn new(rdr: R) -> BomPeeker<R> { BomPeeker { rdr: rdr, bom: None, nread: 0 } } /// Peek at the first three bytes of the underlying reader. /// /// This does not advance the reader provided by `BomPeeker`. /// /// If the underlying reader does not have at least two bytes available, /// then `None` is returned. fn peek_bom(&mut self) -> io::Result<Bom> { if let Some(bom) = self.bom { return Ok(bom); } self.bom = Some(Bom { bytes: [0; 3], len: 0 }); let mut buf = [0u8; 3]; let bom_len = read_full(&mut self.rdr, &mut buf)?; self.bom = Some(Bom { bytes: buf, len: bom_len }); Ok(self.bom.unwrap()) } } impl<R: io::Read> io::Read for BomPeeker<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { if self.nread < 3 { let bom = self.peek_bom()?; let bom = bom.as_slice(); if self.nread < bom.len() { let rest = &bom[self.nread..]; let len = cmp::min(buf.len(), rest.len()); buf[..len].copy_from_slice(&rest[..len]); self.nread += len; return Ok(len); } } let nread = self.rdr.read(buf)?; self.nread += nread; Ok(nread) } } /// Like `io::Read::read_exact`, except it never returns `UnexpectedEof` and /// instead returns the number of bytes read if EOF is seen before filling /// `buf`. fn read_full<R: io::Read>( mut rdr: R, mut buf: &mut [u8], ) -> io::Result<usize> { let mut nread = 0; while!buf.is_empty() { match rdr.read(buf) { Ok(0) => break, Ok(n) => { nread += n; let tmp = buf; buf = &mut tmp[n..]; } Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {} Err(e) => return Err(e), } } Ok(nread) } /// A reader that transcodes to UTF-8. The source encoding is determined by /// inspecting the BOM from the stream read from `R`, if one exists. If a /// UTF-16 BOM exists, then the source stream is transcoded to UTF-8 with /// invalid UTF-16 sequences translated to the Unicode replacement character. /// In all other cases, the underlying reader is passed through unchanged. /// /// `R` is the type of the underlying reader and `B` is the type of an internal /// buffer used to store the results of transcoding. /// /// Note that not all methods on `io::Read` work with this implementation. /// For example, the `bytes` adapter method attempts to read a single byte at /// a time, but this implementation requires a buffer of size at least `4`. If /// a buffer of size less than 4 is given, then an error is returned. pub struct DecodeReader<R, B> { /// The underlying reader, wrapped in a peeker for reading a BOM if one /// exists. rdr: BomPeeker<R>, /// The internal buffer to store transcoded bytes before they are read by /// callers. buf: B, /// The current position in `buf`. Subsequent reads start here. pos: usize, /// The number of transcoded bytes in `buf`. Subsequent reads end here. buflen: usize, /// Whether this is the first read or not (in which we inspect the BOM). first: bool, /// Whether a "last" read has occurred. After this point, EOF will always /// be returned. last: bool, /// The underlying text decoder derived from the BOM, if one exists. decoder: Option<Decoder>, } impl<R: io::Read, B: AsMut<[u8]>> DecodeReader<R, B> { /// Create a new transcoder that converts a source stream to valid UTF-8. /// /// If an encoding is specified, then it is used to transcode `rdr` to /// UTF-8. Otherwise, if no encoding is specified, and if a UTF-16 BOM is /// found, then the corresponding UTF-16 encoding is used to transcode /// `rdr` to UTF-8. In all other cases, `rdr` is assumed to be at least /// ASCII-compatible and passed through untouched. /// /// Errors in the encoding of `rdr` are handled with the Unicode /// replacement character. If no encoding of `rdr` is specified, then /// errors are not handled. pub fn new( rdr: R, buf: B, enc: Option<&'static Encoding>, ) -> DecodeReader<R, B> { DecodeReader { rdr: BomPeeker::new(rdr), buf: buf, buflen: 0, pos: 0, first: enc.is_none(), last: false, decoder: enc.map(|enc| enc.new_decoder_with_bom_removal()), } } /// Fill the internal buffer from the underlying reader. /// /// If there are unread bytes in the internal buffer, then we move them /// to the beginning of the internal buffer and fill the remainder. /// /// If the internal buffer is too small to read additional bytes, then an /// error is returned. #[inline(always)] // massive perf benefit (???) fn fill(&mut self) -> io::Result<()> { if self.pos < self.buflen { if self.buflen >= self.buf.as_mut().len() { return Err(io::Error::new( io::ErrorKind::Other, "DecodeReader: internal buffer exhausted")); } let newlen = self.buflen - self.pos; let mut tmp = Vec::with_capacity(newlen); tmp.extend_from_slice(&self.buf.as_mut()[self.pos..self.buflen]); self.buf.as_mut()[..newlen].copy_from_slice(&tmp); self.buflen = newlen; } else { self.buflen = 0; } self.pos = 0; self.buflen += self.rdr.read(&mut self.buf.as_mut()[self.buflen..])?; Ok(()) } /// Transcode the inner stream to UTF-8 in `buf`. This assumes that there /// is a decoder capable of transcoding the inner stream to UTF-8. This /// returns the number of bytes written to `buf`. /// /// When this function returns, exactly one of the following things will /// be true: /// /// 1. A non-zero number of bytes were written to `buf`. /// 2. The underlying reader reached EOF. /// 3. An error is returned: the internal buffer ran out of room. /// 4. An I/O error occurred. /// /// Note that `buf` must have at least 4 bytes of space. fn transcode(&mut self, buf: &mut [u8]) -> io::Result<usize> { assert!(buf.len() >= 4); if self.last { return Ok(0); } if self.pos >= self.buflen { self.fill()?; } let mut nwrite = 0; loop { let (_, nin, nout, _) = self.decoder.as_mut().unwrap().decode_to_utf8( &self.buf.as_mut()[self.pos..self.buflen], buf, false); self.pos += nin; nwrite += nout; // If we've written at least one byte to the caller-provided // buffer, then our mission is complete. if nwrite > 0 { break; } // Otherwise, we know that our internal buffer has insufficient // data to transcode at least one char, so we attempt to refill it. self.fill()?; // Quit on EOF. if self.buflen == 0 { self.pos = 0; self.last = true; let (_, _, nout, _) = self.decoder.as_mut().unwrap().decode_to_utf8( &[], buf, true); return Ok(nout); } } Ok(nwrite) } #[inline(never)] // impacts perf... fn detect(&mut self) -> io::Result<()> { let bom = self.rdr.peek_bom()?; self.decoder = bom.decoder(); Ok(()) } } impl<R: io::Read, B: AsMut<[u8]>> io::Read for DecodeReader<R, B> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { if self.first { self.first = false; self.detect()?; } if self.decoder.is_none() { return self.rdr.read(buf); } // When decoding UTF-8, we need at least 4 bytes of space to guarantee // that we can decode at least one codepoint. If we don't have it, we // can either return `0` for the number of bytes read or return an // error. Since `0` would be interpreted as a possibly premature EOF, // we opt for an error. if buf.len() < 4 { return Err(io::Error::new( io::ErrorKind::Other, "DecodeReader: byte buffer must have length at least 4")); } self.transcode(buf) } } #[cfg(test)] mod tests { use std::io::Read; use encoding_rs::Encoding; use super::{Bom, BomPeeker, DecodeReader}; fn read_to_string<R: Read>(mut rdr: R) -> String { let mut s = String::new(); rdr.read_to_string(&mut s).unwrap(); s } #[test] fn peeker_empty() { let buf = []; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!(Bom { bytes: [0; 3], len: 0}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_one() { let buf = [1]; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!( Bom { bytes: [1, 0, 0], len: 1}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_two() { let buf = [1, 2]; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!( Bom { bytes: [1, 2, 0], len: 2}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(2, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(2, tmp[1]); assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_three() { let buf = [1, 2, 3]; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!( Bom { bytes: [1, 2, 3], len: 3}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(3, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(2, tmp[1]); assert_eq!(3, tmp[2]); assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_four() { let buf = [1, 2, 3, 4]; let mut peeker = BomPeeker::new(&buf[..]); assert_eq!( Bom { bytes: [1, 2, 3], len: 3}, peeker.peek_bom().unwrap()); let mut tmp = [0; 100]; assert_eq!(3, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(2, tmp[1]); assert_eq!(3, tmp[2]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(4, tmp[0]); assert_eq!(0, peeker.read(&mut tmp).unwrap()); } #[test] fn peeker_one_at_a_time() { let buf = [1, 2, 3, 4]; let mut peeker = BomPeeker::new(&buf[..]); let mut tmp = [0; 1]; assert_eq!(0, peeker.read(&mut tmp[..0]).unwrap()); assert_eq!(0, tmp[0]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(1, tmp[0]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(2, tmp[0]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(3, tmp[0]); assert_eq!(1, peeker.read(&mut tmp).unwrap()); assert_eq!(4, tmp[0]); } // In cases where all we have is a bom, we expect the bytes to be // passed through unchanged. #[test] fn trans_utf16_bom() { let srcbuf = vec![0xFF, 0xFE]; let mut dstbuf = vec![0; 8 * (1<<10)]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); let n = rdr.read(&mut dstbuf).unwrap(); assert_eq!(&*srcbuf, &dstbuf[..n]); let srcbuf = vec![0xFE, 0xFF]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); let n = rdr.read(&mut dstbuf).unwrap(); assert_eq!(&*srcbuf, &dstbuf[..n]); let srcbuf = vec![0xEF, 0xBB, 0xBF]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); let n = rdr.read(&mut dstbuf).unwrap(); assert_eq!(&*srcbuf, &dstbuf[..n]); } // Test basic UTF-16 decoding. #[test] fn trans_utf16_basic() { let srcbuf = vec![0xFF, 0xFE, 0x61, 0x00]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); assert_eq!("a", read_to_string(&mut rdr)); let srcbuf = vec![0xFE, 0xFF, 0x00, 0x61]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); assert_eq!("a", read_to_string(&mut rdr)); } // Test incomplete UTF-16 decoding. This ensures we see a replacement char // if the stream ends with an unpaired code unit. #[test] fn trans_utf16_incomplete() { let srcbuf = vec![0xFF, 0xFE, 0x61, 0x00, 0x00]; let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None); assert_eq!("a\u{FFFD}", read_to_string(&mut rdr)); } macro_rules! test_trans_simple { ($name:ident, $enc:expr, $srcbytes:expr, $dst:expr) => { #[test] fn $name() { let srcbuf = &$srcbytes[..]; let enc = Encoding::for_label($enc.as_bytes()); let mut rdr = DecodeReader::new( &*srcbuf, vec![0; 8 * (1<<10)], enc); assert_eq!($dst, read_to_string(&mut rdr)); } } } // This isn't exhaustive obviously, but it lets us test base level support. test_trans_simple!(trans_simple_auto, "does not exist", b"\xD0\x96", "Ж"); test_trans_simple!(trans_simple_utf8, "utf-8", b"\xD0\x96", "Ж"); test_trans_simple!(trans_simple_utf16le, "utf-16le", b"\x16\x04", "Ж"); test_trans_simple!(trans_simple_utf16be, "utf-16be", b"\x04\x16", "Ж"); test_trans_simple!(trans_simple_chinese, "chinese", b"\xA7\xA8", "Ж"); test_trans_simple!(trans_simple_korean, "korean", b"\xAC\xA8", "Ж"); test_trans_simple!( trans_simple_big5_hkscs, "big5-hkscs", b"\xC7\xFA", "Ж"); test_trans_simple!(trans_simple_gbk, "gbk", b"\xA7\xA8", "Ж"); test_trans_simple!(trans_simple_sjis, "sjis", b"\x84\x47", "Ж"); test_trans_simple!(trans_simple_eucjp, "euc-jp", b"\xA7\xA8", "Ж"); test_trans_simple!(trans_simple_latin1, "latin1", b"\xA9", "©"); }
{ let bom = self.as_slice(); if bom.len() < 3 { return None; } if let Some((enc, _)) = Encoding::for_bom(bom) { if enc != UTF_8 { return Some(enc.new_decoder_with_bom_removal()); } } None }
identifier_body
query.rs
use std::borrow::{Borrow, Cow}; use std::collections::HashMap; use std::fmt; use std::iter::FromIterator; use std::hash::{BuildHasher, Hash}; use std::rc::Rc; use std::sync::Arc; use serde::de; use serde::Deserializer; /// Allows access to the query parameters in an url or a body. /// /// Use one of the listed implementations below. Since those may be a bit confusing due to their /// abundant use of generics, basically use any type of `HashMap` that maps'str-likes' to a /// collection of other'str-likes'. Popular instances may be: /// * `HashMap<String, String>` /// * `HashMap<String, Vec<String>>` /// * `HashMap<Cow<'static, str>, Cow<'static, str>>` /// /// You should generally not have to implement this trait yourself, and if you do there are /// additional requirements on your implementation to guarantee standard conformance. Therefore the /// trait is marked as `unsafe`. pub unsafe trait QueryParameter { /// Get the **unique** value associated with a key. /// /// If there are multiple values, return `None`. This is very important to guarantee /// conformance to the RFC. Afaik it prevents potentially subverting validation middleware, /// order dependent processing, or simple confusion between different components who parse the /// query string from different ends. fn unique_value(&self, key: &str) -> Option<Cow<str>>; /// Guarantees that one can grab an owned copy. fn normalize(&self) -> NormalizedParameter; } /// The query parameter normal form. /// /// When a request wants to give access to its query or body parameters by reference, it can do so /// by a reference of the particular trait. But when the representation of the query is not stored /// in the memory associated with the request, it needs to be allocated to outlive the borrow on /// the request. This allocation may as well perform the minimization/normalization into a /// representation actually consumed by the backend. This normal form thus encapsulates the /// associated `clone-into-normal form` by various possible constructors from references [WIP]. /// /// This gives rise to a custom `Cow<QueryParameter>` instance by requiring that normalization into /// memory with unrelated lifetime is always possible. /// /// Internally a hashmap but this may change due to optimizations. #[derive(Clone, Debug, Default)] pub struct NormalizedParameter { /// The value is `None` if the key appeared at least twice. inner: HashMap<Cow<'static, str>, Option<Cow<'static, str>>>, } unsafe impl QueryParameter for NormalizedParameter { fn unique_value(&self, key: &str) -> Option<Cow<str>> { self.inner .get(key) .and_then(|val| val.as_ref().map(Cow::as_ref).map(Cow::Borrowed)) } fn normalize(&self) -> NormalizedParameter { self.clone() } } impl NormalizedParameter { /// Create an empty map. pub fn new() -> Self { NormalizedParameter::default() } /// Insert a key-value-pair or mark key as dead if already present. /// /// Since each key must appear at most once, we do not remove it from the map but instead mark /// the key as having a duplicate entry. pub fn insert_or_poison(&mut self, key: Cow<'static, str>, val: Cow<'static, str>) { let unique_val = Some(val); self.inner .entry(key) .and_modify(|val| *val = None) .or_insert(unique_val); } } impl Borrow<dyn QueryParameter> for NormalizedParameter { fn borrow(&self) -> &(dyn QueryParameter +'static) { self } } impl Borrow<dyn QueryParameter + Send> for NormalizedParameter { fn borrow(&self) -> &(dyn QueryParameter + Send +'static) { self } } impl<'de> de::Deserialize<'de> for NormalizedParameter { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct Visitor(NormalizedParameter); impl<'a> de::Visitor<'a> for Visitor { type Value = NormalizedParameter; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "a sequence of key-value-pairs") } fn visit_seq<A>(mut self, mut access: A) -> Result<Self::Value, A::Error> where A: de::SeqAccess<'a>, {
self.0.insert_or_poison(key.into(), value.into()) } Ok(self.0) } } let visitor = Visitor(NormalizedParameter::default()); deserializer.deserialize_seq(visitor) } } impl<K, V> FromIterator<(K, V)> for NormalizedParameter where K: Into<Cow<'static, str>>, V: Into<Cow<'static, str>>, { fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = (K, V)>, { let mut target = NormalizedParameter::default(); iter.into_iter() .for_each(|(k, v)| target.insert_or_poison(k.into(), v.into())); target } } impl ToOwned for dyn QueryParameter { type Owned = NormalizedParameter; fn to_owned(&self) -> Self::Owned { self.normalize() } } impl ToOwned for dyn QueryParameter + Send { type Owned = NormalizedParameter; fn to_owned(&self) -> Self::Owned { self.normalize() } } /// Return a reference to value in a collection if it is the only one. /// /// For example, a vector of string like types returns a reference to its first /// element if there are no other, else it returns `None`. /// /// If this were done with slices, that would require choosing a particular /// value type of the underlying slice e.g. `[String]`. pub unsafe trait UniqueValue { /// Borrow the unique value reference. fn get_unique(&self) -> Option<&str>; } unsafe impl<K, V, S: BuildHasher> QueryParameter for HashMap<K, V, S> where K: Borrow<str> + Eq + Hash, V: UniqueValue + Eq + Hash, { fn unique_value(&self, key: &str) -> Option<Cow<str>> { self.get(key).and_then(V::get_unique).map(Cow::Borrowed) } fn normalize(&self) -> NormalizedParameter { let inner = self .iter() .filter_map(|(key, val)| { val.get_unique().map(|value| { ( Cow::Owned(key.borrow().to_string()), Some(Cow::Owned(value.to_string())), ) }) }) .collect(); NormalizedParameter { inner } } } unsafe impl<K, V> QueryParameter for Vec<(K, V)> where K: Borrow<str> + Eq + Hash, V: Borrow<str> + Eq + Hash, { fn unique_value(&self, key: &str) -> Option<Cow<str>> { let mut value = None; for entry in self.iter() { if entry.0.borrow() == key { if value.is_some() { return None; } value = Some(Cow::Borrowed(entry.1.borrow())); } } value } fn normalize(&self) -> NormalizedParameter { let mut params = NormalizedParameter::default(); self.iter() .map(|&(ref key, ref val)| { ( Cow::Owned(key.borrow().to_string()), Cow::Owned(val.borrow().to_string()), ) }) .for_each(|(key, val)| params.insert_or_poison(key, val)); params } } unsafe impl<'a, Q: QueryParameter + 'a +?Sized> QueryParameter for &'a Q { fn unique_value(&self, key: &str) -> Option<Cow<str>> { (**self).unique_value(key) } fn normalize(&self) -> NormalizedParameter { (**self).normalize() } } unsafe impl<'a, Q: QueryParameter + 'a +?Sized> QueryParameter for &'a mut Q { fn unique_value(&self, key: &str) -> Option<Cow<str>> { (**self).unique_value(key) } fn normalize(&self) -> NormalizedParameter { (**self).normalize() } } unsafe impl UniqueValue for str { fn get_unique(&self) -> Option<&str> { Some(self) } } unsafe impl UniqueValue for String { fn get_unique(&self) -> Option<&str> { Some(&self) } } unsafe impl<'a, V> UniqueValue for &'a V where V: AsRef<str> +?Sized, { fn get_unique(&self) -> Option<&str> { Some(self.as_ref()) } } unsafe impl<'a> UniqueValue for Cow<'a, str> { fn get_unique(&self) -> Option<&str> { Some(self.as_ref()) } } unsafe impl<V: UniqueValue> UniqueValue for Option<V> { fn get_unique(&self) -> Option<&str> { self.as_ref().and_then(V::get_unique) } } unsafe impl<V: UniqueValue> UniqueValue for [V] { fn get_unique(&self) -> Option<&str> { if self.len() > 1 { None } else { self.get(0).and_then(V::get_unique) } } } unsafe impl<V: UniqueValue +?Sized> UniqueValue for Box<V> { fn get_unique(&self) -> Option<&str> { (**self).get_unique() } } unsafe impl<V: UniqueValue +?Sized> UniqueValue for Rc<V> { fn get_unique(&self) -> Option<&str> { (**self).get_unique() } } unsafe impl<V: UniqueValue +?Sized> UniqueValue for Arc<V> { fn get_unique(&self) -> Option<&str> { (**self).get_unique() } } unsafe impl<V: UniqueValue> UniqueValue for Vec<V> { fn get_unique(&self) -> Option<&str> { if self.len() > 1 { None } else { self.get(0).and_then(V::get_unique) } } } mod test { use super::*; /// Compilation tests for various possible QueryParameter impls. #[allow(unused)] #[allow(dead_code)] fn test_query_parameter_impls() { let _ = (&HashMap::<String, String>::new()) as &dyn QueryParameter; let _ = (&HashMap::<&'static str, &'static str>::new()) as &dyn QueryParameter; let _ = (&HashMap::<Cow<'static, str>, Cow<'static, str>>::new()) as &dyn QueryParameter; let _ = (&HashMap::<String, Vec<String>>::new()) as &dyn QueryParameter; let _ = (&HashMap::<String, Box<String>>::new()) as &dyn QueryParameter; let _ = (&HashMap::<String, Box<[Cow<'static, str>]>>::new()) as &dyn QueryParameter; } }
while let Some((key, value)) = access.next_element::<(String, String)>()? {
random_line_split
query.rs
use std::borrow::{Borrow, Cow}; use std::collections::HashMap; use std::fmt; use std::iter::FromIterator; use std::hash::{BuildHasher, Hash}; use std::rc::Rc; use std::sync::Arc; use serde::de; use serde::Deserializer; /// Allows access to the query parameters in an url or a body. /// /// Use one of the listed implementations below. Since those may be a bit confusing due to their /// abundant use of generics, basically use any type of `HashMap` that maps'str-likes' to a /// collection of other'str-likes'. Popular instances may be: /// * `HashMap<String, String>` /// * `HashMap<String, Vec<String>>` /// * `HashMap<Cow<'static, str>, Cow<'static, str>>` /// /// You should generally not have to implement this trait yourself, and if you do there are /// additional requirements on your implementation to guarantee standard conformance. Therefore the /// trait is marked as `unsafe`. pub unsafe trait QueryParameter { /// Get the **unique** value associated with a key. /// /// If there are multiple values, return `None`. This is very important to guarantee /// conformance to the RFC. Afaik it prevents potentially subverting validation middleware, /// order dependent processing, or simple confusion between different components who parse the /// query string from different ends. fn unique_value(&self, key: &str) -> Option<Cow<str>>; /// Guarantees that one can grab an owned copy. fn normalize(&self) -> NormalizedParameter; } /// The query parameter normal form. /// /// When a request wants to give access to its query or body parameters by reference, it can do so /// by a reference of the particular trait. But when the representation of the query is not stored /// in the memory associated with the request, it needs to be allocated to outlive the borrow on /// the request. This allocation may as well perform the minimization/normalization into a /// representation actually consumed by the backend. This normal form thus encapsulates the /// associated `clone-into-normal form` by various possible constructors from references [WIP]. /// /// This gives rise to a custom `Cow<QueryParameter>` instance by requiring that normalization into /// memory with unrelated lifetime is always possible. /// /// Internally a hashmap but this may change due to optimizations. #[derive(Clone, Debug, Default)] pub struct NormalizedParameter { /// The value is `None` if the key appeared at least twice. inner: HashMap<Cow<'static, str>, Option<Cow<'static, str>>>, } unsafe impl QueryParameter for NormalizedParameter { fn unique_value(&self, key: &str) -> Option<Cow<str>> { self.inner .get(key) .and_then(|val| val.as_ref().map(Cow::as_ref).map(Cow::Borrowed)) } fn normalize(&self) -> NormalizedParameter { self.clone() } } impl NormalizedParameter { /// Create an empty map. pub fn new() -> Self { NormalizedParameter::default() } /// Insert a key-value-pair or mark key as dead if already present. /// /// Since each key must appear at most once, we do not remove it from the map but instead mark /// the key as having a duplicate entry. pub fn insert_or_poison(&mut self, key: Cow<'static, str>, val: Cow<'static, str>) { let unique_val = Some(val); self.inner .entry(key) .and_modify(|val| *val = None) .or_insert(unique_val); } } impl Borrow<dyn QueryParameter> for NormalizedParameter { fn borrow(&self) -> &(dyn QueryParameter +'static) { self } } impl Borrow<dyn QueryParameter + Send> for NormalizedParameter { fn borrow(&self) -> &(dyn QueryParameter + Send +'static) { self } } impl<'de> de::Deserialize<'de> for NormalizedParameter { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct Visitor(NormalizedParameter); impl<'a> de::Visitor<'a> for Visitor { type Value = NormalizedParameter; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "a sequence of key-value-pairs") } fn visit_seq<A>(mut self, mut access: A) -> Result<Self::Value, A::Error> where A: de::SeqAccess<'a>, { while let Some((key, value)) = access.next_element::<(String, String)>()? { self.0.insert_or_poison(key.into(), value.into()) } Ok(self.0) } } let visitor = Visitor(NormalizedParameter::default()); deserializer.deserialize_seq(visitor) } } impl<K, V> FromIterator<(K, V)> for NormalizedParameter where K: Into<Cow<'static, str>>, V: Into<Cow<'static, str>>, { fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = (K, V)>, { let mut target = NormalizedParameter::default(); iter.into_iter() .for_each(|(k, v)| target.insert_or_poison(k.into(), v.into())); target } } impl ToOwned for dyn QueryParameter { type Owned = NormalizedParameter; fn to_owned(&self) -> Self::Owned { self.normalize() } } impl ToOwned for dyn QueryParameter + Send { type Owned = NormalizedParameter; fn to_owned(&self) -> Self::Owned
} /// Return a reference to value in a collection if it is the only one. /// /// For example, a vector of string like types returns a reference to its first /// element if there are no other, else it returns `None`. /// /// If this were done with slices, that would require choosing a particular /// value type of the underlying slice e.g. `[String]`. pub unsafe trait UniqueValue { /// Borrow the unique value reference. fn get_unique(&self) -> Option<&str>; } unsafe impl<K, V, S: BuildHasher> QueryParameter for HashMap<K, V, S> where K: Borrow<str> + Eq + Hash, V: UniqueValue + Eq + Hash, { fn unique_value(&self, key: &str) -> Option<Cow<str>> { self.get(key).and_then(V::get_unique).map(Cow::Borrowed) } fn normalize(&self) -> NormalizedParameter { let inner = self .iter() .filter_map(|(key, val)| { val.get_unique().map(|value| { ( Cow::Owned(key.borrow().to_string()), Some(Cow::Owned(value.to_string())), ) }) }) .collect(); NormalizedParameter { inner } } } unsafe impl<K, V> QueryParameter for Vec<(K, V)> where K: Borrow<str> + Eq + Hash, V: Borrow<str> + Eq + Hash, { fn unique_value(&self, key: &str) -> Option<Cow<str>> { let mut value = None; for entry in self.iter() { if entry.0.borrow() == key { if value.is_some() { return None; } value = Some(Cow::Borrowed(entry.1.borrow())); } } value } fn normalize(&self) -> NormalizedParameter { let mut params = NormalizedParameter::default(); self.iter() .map(|&(ref key, ref val)| { ( Cow::Owned(key.borrow().to_string()), Cow::Owned(val.borrow().to_string()), ) }) .for_each(|(key, val)| params.insert_or_poison(key, val)); params } } unsafe impl<'a, Q: QueryParameter + 'a +?Sized> QueryParameter for &'a Q { fn unique_value(&self, key: &str) -> Option<Cow<str>> { (**self).unique_value(key) } fn normalize(&self) -> NormalizedParameter { (**self).normalize() } } unsafe impl<'a, Q: QueryParameter + 'a +?Sized> QueryParameter for &'a mut Q { fn unique_value(&self, key: &str) -> Option<Cow<str>> { (**self).unique_value(key) } fn normalize(&self) -> NormalizedParameter { (**self).normalize() } } unsafe impl UniqueValue for str { fn get_unique(&self) -> Option<&str> { Some(self) } } unsafe impl UniqueValue for String { fn get_unique(&self) -> Option<&str> { Some(&self) } } unsafe impl<'a, V> UniqueValue for &'a V where V: AsRef<str> +?Sized, { fn get_unique(&self) -> Option<&str> { Some(self.as_ref()) } } unsafe impl<'a> UniqueValue for Cow<'a, str> { fn get_unique(&self) -> Option<&str> { Some(self.as_ref()) } } unsafe impl<V: UniqueValue> UniqueValue for Option<V> { fn get_unique(&self) -> Option<&str> { self.as_ref().and_then(V::get_unique) } } unsafe impl<V: UniqueValue> UniqueValue for [V] { fn get_unique(&self) -> Option<&str> { if self.len() > 1 { None } else { self.get(0).and_then(V::get_unique) } } } unsafe impl<V: UniqueValue +?Sized> UniqueValue for Box<V> { fn get_unique(&self) -> Option<&str> { (**self).get_unique() } } unsafe impl<V: UniqueValue +?Sized> UniqueValue for Rc<V> { fn get_unique(&self) -> Option<&str> { (**self).get_unique() } } unsafe impl<V: UniqueValue +?Sized> UniqueValue for Arc<V> { fn get_unique(&self) -> Option<&str> { (**self).get_unique() } } unsafe impl<V: UniqueValue> UniqueValue for Vec<V> { fn get_unique(&self) -> Option<&str> { if self.len() > 1 { None } else { self.get(0).and_then(V::get_unique) } } } mod test { use super::*; /// Compilation tests for various possible QueryParameter impls. #[allow(unused)] #[allow(dead_code)] fn test_query_parameter_impls() { let _ = (&HashMap::<String, String>::new()) as &dyn QueryParameter; let _ = (&HashMap::<&'static str, &'static str>::new()) as &dyn QueryParameter; let _ = (&HashMap::<Cow<'static, str>, Cow<'static, str>>::new()) as &dyn QueryParameter; let _ = (&HashMap::<String, Vec<String>>::new()) as &dyn QueryParameter; let _ = (&HashMap::<String, Box<String>>::new()) as &dyn QueryParameter; let _ = (&HashMap::<String, Box<[Cow<'static, str>]>>::new()) as &dyn QueryParameter; } }
{ self.normalize() }
identifier_body
query.rs
use std::borrow::{Borrow, Cow}; use std::collections::HashMap; use std::fmt; use std::iter::FromIterator; use std::hash::{BuildHasher, Hash}; use std::rc::Rc; use std::sync::Arc; use serde::de; use serde::Deserializer; /// Allows access to the query parameters in an url or a body. /// /// Use one of the listed implementations below. Since those may be a bit confusing due to their /// abundant use of generics, basically use any type of `HashMap` that maps'str-likes' to a /// collection of other'str-likes'. Popular instances may be: /// * `HashMap<String, String>` /// * `HashMap<String, Vec<String>>` /// * `HashMap<Cow<'static, str>, Cow<'static, str>>` /// /// You should generally not have to implement this trait yourself, and if you do there are /// additional requirements on your implementation to guarantee standard conformance. Therefore the /// trait is marked as `unsafe`. pub unsafe trait QueryParameter { /// Get the **unique** value associated with a key. /// /// If there are multiple values, return `None`. This is very important to guarantee /// conformance to the RFC. Afaik it prevents potentially subverting validation middleware, /// order dependent processing, or simple confusion between different components who parse the /// query string from different ends. fn unique_value(&self, key: &str) -> Option<Cow<str>>; /// Guarantees that one can grab an owned copy. fn normalize(&self) -> NormalizedParameter; } /// The query parameter normal form. /// /// When a request wants to give access to its query or body parameters by reference, it can do so /// by a reference of the particular trait. But when the representation of the query is not stored /// in the memory associated with the request, it needs to be allocated to outlive the borrow on /// the request. This allocation may as well perform the minimization/normalization into a /// representation actually consumed by the backend. This normal form thus encapsulates the /// associated `clone-into-normal form` by various possible constructors from references [WIP]. /// /// This gives rise to a custom `Cow<QueryParameter>` instance by requiring that normalization into /// memory with unrelated lifetime is always possible. /// /// Internally a hashmap but this may change due to optimizations. #[derive(Clone, Debug, Default)] pub struct NormalizedParameter { /// The value is `None` if the key appeared at least twice. inner: HashMap<Cow<'static, str>, Option<Cow<'static, str>>>, } unsafe impl QueryParameter for NormalizedParameter { fn unique_value(&self, key: &str) -> Option<Cow<str>> { self.inner .get(key) .and_then(|val| val.as_ref().map(Cow::as_ref).map(Cow::Borrowed)) } fn normalize(&self) -> NormalizedParameter { self.clone() } } impl NormalizedParameter { /// Create an empty map. pub fn new() -> Self { NormalizedParameter::default() } /// Insert a key-value-pair or mark key as dead if already present. /// /// Since each key must appear at most once, we do not remove it from the map but instead mark /// the key as having a duplicate entry. pub fn insert_or_poison(&mut self, key: Cow<'static, str>, val: Cow<'static, str>) { let unique_val = Some(val); self.inner .entry(key) .and_modify(|val| *val = None) .or_insert(unique_val); } } impl Borrow<dyn QueryParameter> for NormalizedParameter { fn borrow(&self) -> &(dyn QueryParameter +'static) { self } } impl Borrow<dyn QueryParameter + Send> for NormalizedParameter { fn borrow(&self) -> &(dyn QueryParameter + Send +'static) { self } } impl<'de> de::Deserialize<'de> for NormalizedParameter { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct Visitor(NormalizedParameter); impl<'a> de::Visitor<'a> for Visitor { type Value = NormalizedParameter; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "a sequence of key-value-pairs") } fn visit_seq<A>(mut self, mut access: A) -> Result<Self::Value, A::Error> where A: de::SeqAccess<'a>, { while let Some((key, value)) = access.next_element::<(String, String)>()? { self.0.insert_or_poison(key.into(), value.into()) } Ok(self.0) } } let visitor = Visitor(NormalizedParameter::default()); deserializer.deserialize_seq(visitor) } } impl<K, V> FromIterator<(K, V)> for NormalizedParameter where K: Into<Cow<'static, str>>, V: Into<Cow<'static, str>>, { fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = (K, V)>, { let mut target = NormalizedParameter::default(); iter.into_iter() .for_each(|(k, v)| target.insert_or_poison(k.into(), v.into())); target } } impl ToOwned for dyn QueryParameter { type Owned = NormalizedParameter; fn to_owned(&self) -> Self::Owned { self.normalize() } } impl ToOwned for dyn QueryParameter + Send { type Owned = NormalizedParameter; fn to_owned(&self) -> Self::Owned { self.normalize() } } /// Return a reference to value in a collection if it is the only one. /// /// For example, a vector of string like types returns a reference to its first /// element if there are no other, else it returns `None`. /// /// If this were done with slices, that would require choosing a particular /// value type of the underlying slice e.g. `[String]`. pub unsafe trait UniqueValue { /// Borrow the unique value reference. fn get_unique(&self) -> Option<&str>; } unsafe impl<K, V, S: BuildHasher> QueryParameter for HashMap<K, V, S> where K: Borrow<str> + Eq + Hash, V: UniqueValue + Eq + Hash, { fn unique_value(&self, key: &str) -> Option<Cow<str>> { self.get(key).and_then(V::get_unique).map(Cow::Borrowed) } fn normalize(&self) -> NormalizedParameter { let inner = self .iter() .filter_map(|(key, val)| { val.get_unique().map(|value| { ( Cow::Owned(key.borrow().to_string()), Some(Cow::Owned(value.to_string())), ) }) }) .collect(); NormalizedParameter { inner } } } unsafe impl<K, V> QueryParameter for Vec<(K, V)> where K: Borrow<str> + Eq + Hash, V: Borrow<str> + Eq + Hash, { fn unique_value(&self, key: &str) -> Option<Cow<str>> { let mut value = None; for entry in self.iter() { if entry.0.borrow() == key { if value.is_some() { return None; } value = Some(Cow::Borrowed(entry.1.borrow())); } } value } fn normalize(&self) -> NormalizedParameter { let mut params = NormalizedParameter::default(); self.iter() .map(|&(ref key, ref val)| { ( Cow::Owned(key.borrow().to_string()), Cow::Owned(val.borrow().to_string()), ) }) .for_each(|(key, val)| params.insert_or_poison(key, val)); params } } unsafe impl<'a, Q: QueryParameter + 'a +?Sized> QueryParameter for &'a Q { fn unique_value(&self, key: &str) -> Option<Cow<str>> { (**self).unique_value(key) } fn normalize(&self) -> NormalizedParameter { (**self).normalize() } } unsafe impl<'a, Q: QueryParameter + 'a +?Sized> QueryParameter for &'a mut Q { fn unique_value(&self, key: &str) -> Option<Cow<str>> { (**self).unique_value(key) } fn normalize(&self) -> NormalizedParameter { (**self).normalize() } } unsafe impl UniqueValue for str { fn get_unique(&self) -> Option<&str> { Some(self) } } unsafe impl UniqueValue for String { fn get_unique(&self) -> Option<&str> { Some(&self) } } unsafe impl<'a, V> UniqueValue for &'a V where V: AsRef<str> +?Sized, { fn get_unique(&self) -> Option<&str> { Some(self.as_ref()) } } unsafe impl<'a> UniqueValue for Cow<'a, str> { fn get_unique(&self) -> Option<&str> { Some(self.as_ref()) } } unsafe impl<V: UniqueValue> UniqueValue for Option<V> { fn get_unique(&self) -> Option<&str> { self.as_ref().and_then(V::get_unique) } } unsafe impl<V: UniqueValue> UniqueValue for [V] { fn get_unique(&self) -> Option<&str> { if self.len() > 1 { None } else { self.get(0).and_then(V::get_unique) } } } unsafe impl<V: UniqueValue +?Sized> UniqueValue for Box<V> { fn get_unique(&self) -> Option<&str> { (**self).get_unique() } } unsafe impl<V: UniqueValue +?Sized> UniqueValue for Rc<V> { fn get_unique(&self) -> Option<&str> { (**self).get_unique() } } unsafe impl<V: UniqueValue +?Sized> UniqueValue for Arc<V> { fn get_unique(&self) -> Option<&str> { (**self).get_unique() } } unsafe impl<V: UniqueValue> UniqueValue for Vec<V> { fn get_unique(&self) -> Option<&str> { if self.len() > 1
else { self.get(0).and_then(V::get_unique) } } } mod test { use super::*; /// Compilation tests for various possible QueryParameter impls. #[allow(unused)] #[allow(dead_code)] fn test_query_parameter_impls() { let _ = (&HashMap::<String, String>::new()) as &dyn QueryParameter; let _ = (&HashMap::<&'static str, &'static str>::new()) as &dyn QueryParameter; let _ = (&HashMap::<Cow<'static, str>, Cow<'static, str>>::new()) as &dyn QueryParameter; let _ = (&HashMap::<String, Vec<String>>::new()) as &dyn QueryParameter; let _ = (&HashMap::<String, Box<String>>::new()) as &dyn QueryParameter; let _ = (&HashMap::<String, Box<[Cow<'static, str>]>>::new()) as &dyn QueryParameter; } }
{ None }
conditional_block
query.rs
use std::borrow::{Borrow, Cow}; use std::collections::HashMap; use std::fmt; use std::iter::FromIterator; use std::hash::{BuildHasher, Hash}; use std::rc::Rc; use std::sync::Arc; use serde::de; use serde::Deserializer; /// Allows access to the query parameters in an url or a body. /// /// Use one of the listed implementations below. Since those may be a bit confusing due to their /// abundant use of generics, basically use any type of `HashMap` that maps'str-likes' to a /// collection of other'str-likes'. Popular instances may be: /// * `HashMap<String, String>` /// * `HashMap<String, Vec<String>>` /// * `HashMap<Cow<'static, str>, Cow<'static, str>>` /// /// You should generally not have to implement this trait yourself, and if you do there are /// additional requirements on your implementation to guarantee standard conformance. Therefore the /// trait is marked as `unsafe`. pub unsafe trait QueryParameter { /// Get the **unique** value associated with a key. /// /// If there are multiple values, return `None`. This is very important to guarantee /// conformance to the RFC. Afaik it prevents potentially subverting validation middleware, /// order dependent processing, or simple confusion between different components who parse the /// query string from different ends. fn unique_value(&self, key: &str) -> Option<Cow<str>>; /// Guarantees that one can grab an owned copy. fn normalize(&self) -> NormalizedParameter; } /// The query parameter normal form. /// /// When a request wants to give access to its query or body parameters by reference, it can do so /// by a reference of the particular trait. But when the representation of the query is not stored /// in the memory associated with the request, it needs to be allocated to outlive the borrow on /// the request. This allocation may as well perform the minimization/normalization into a /// representation actually consumed by the backend. This normal form thus encapsulates the /// associated `clone-into-normal form` by various possible constructors from references [WIP]. /// /// This gives rise to a custom `Cow<QueryParameter>` instance by requiring that normalization into /// memory with unrelated lifetime is always possible. /// /// Internally a hashmap but this may change due to optimizations. #[derive(Clone, Debug, Default)] pub struct NormalizedParameter { /// The value is `None` if the key appeared at least twice. inner: HashMap<Cow<'static, str>, Option<Cow<'static, str>>>, } unsafe impl QueryParameter for NormalizedParameter { fn
(&self, key: &str) -> Option<Cow<str>> { self.inner .get(key) .and_then(|val| val.as_ref().map(Cow::as_ref).map(Cow::Borrowed)) } fn normalize(&self) -> NormalizedParameter { self.clone() } } impl NormalizedParameter { /// Create an empty map. pub fn new() -> Self { NormalizedParameter::default() } /// Insert a key-value-pair or mark key as dead if already present. /// /// Since each key must appear at most once, we do not remove it from the map but instead mark /// the key as having a duplicate entry. pub fn insert_or_poison(&mut self, key: Cow<'static, str>, val: Cow<'static, str>) { let unique_val = Some(val); self.inner .entry(key) .and_modify(|val| *val = None) .or_insert(unique_val); } } impl Borrow<dyn QueryParameter> for NormalizedParameter { fn borrow(&self) -> &(dyn QueryParameter +'static) { self } } impl Borrow<dyn QueryParameter + Send> for NormalizedParameter { fn borrow(&self) -> &(dyn QueryParameter + Send +'static) { self } } impl<'de> de::Deserialize<'de> for NormalizedParameter { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct Visitor(NormalizedParameter); impl<'a> de::Visitor<'a> for Visitor { type Value = NormalizedParameter; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "a sequence of key-value-pairs") } fn visit_seq<A>(mut self, mut access: A) -> Result<Self::Value, A::Error> where A: de::SeqAccess<'a>, { while let Some((key, value)) = access.next_element::<(String, String)>()? { self.0.insert_or_poison(key.into(), value.into()) } Ok(self.0) } } let visitor = Visitor(NormalizedParameter::default()); deserializer.deserialize_seq(visitor) } } impl<K, V> FromIterator<(K, V)> for NormalizedParameter where K: Into<Cow<'static, str>>, V: Into<Cow<'static, str>>, { fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = (K, V)>, { let mut target = NormalizedParameter::default(); iter.into_iter() .for_each(|(k, v)| target.insert_or_poison(k.into(), v.into())); target } } impl ToOwned for dyn QueryParameter { type Owned = NormalizedParameter; fn to_owned(&self) -> Self::Owned { self.normalize() } } impl ToOwned for dyn QueryParameter + Send { type Owned = NormalizedParameter; fn to_owned(&self) -> Self::Owned { self.normalize() } } /// Return a reference to value in a collection if it is the only one. /// /// For example, a vector of string like types returns a reference to its first /// element if there are no other, else it returns `None`. /// /// If this were done with slices, that would require choosing a particular /// value type of the underlying slice e.g. `[String]`. pub unsafe trait UniqueValue { /// Borrow the unique value reference. fn get_unique(&self) -> Option<&str>; } unsafe impl<K, V, S: BuildHasher> QueryParameter for HashMap<K, V, S> where K: Borrow<str> + Eq + Hash, V: UniqueValue + Eq + Hash, { fn unique_value(&self, key: &str) -> Option<Cow<str>> { self.get(key).and_then(V::get_unique).map(Cow::Borrowed) } fn normalize(&self) -> NormalizedParameter { let inner = self .iter() .filter_map(|(key, val)| { val.get_unique().map(|value| { ( Cow::Owned(key.borrow().to_string()), Some(Cow::Owned(value.to_string())), ) }) }) .collect(); NormalizedParameter { inner } } } unsafe impl<K, V> QueryParameter for Vec<(K, V)> where K: Borrow<str> + Eq + Hash, V: Borrow<str> + Eq + Hash, { fn unique_value(&self, key: &str) -> Option<Cow<str>> { let mut value = None; for entry in self.iter() { if entry.0.borrow() == key { if value.is_some() { return None; } value = Some(Cow::Borrowed(entry.1.borrow())); } } value } fn normalize(&self) -> NormalizedParameter { let mut params = NormalizedParameter::default(); self.iter() .map(|&(ref key, ref val)| { ( Cow::Owned(key.borrow().to_string()), Cow::Owned(val.borrow().to_string()), ) }) .for_each(|(key, val)| params.insert_or_poison(key, val)); params } } unsafe impl<'a, Q: QueryParameter + 'a +?Sized> QueryParameter for &'a Q { fn unique_value(&self, key: &str) -> Option<Cow<str>> { (**self).unique_value(key) } fn normalize(&self) -> NormalizedParameter { (**self).normalize() } } unsafe impl<'a, Q: QueryParameter + 'a +?Sized> QueryParameter for &'a mut Q { fn unique_value(&self, key: &str) -> Option<Cow<str>> { (**self).unique_value(key) } fn normalize(&self) -> NormalizedParameter { (**self).normalize() } } unsafe impl UniqueValue for str { fn get_unique(&self) -> Option<&str> { Some(self) } } unsafe impl UniqueValue for String { fn get_unique(&self) -> Option<&str> { Some(&self) } } unsafe impl<'a, V> UniqueValue for &'a V where V: AsRef<str> +?Sized, { fn get_unique(&self) -> Option<&str> { Some(self.as_ref()) } } unsafe impl<'a> UniqueValue for Cow<'a, str> { fn get_unique(&self) -> Option<&str> { Some(self.as_ref()) } } unsafe impl<V: UniqueValue> UniqueValue for Option<V> { fn get_unique(&self) -> Option<&str> { self.as_ref().and_then(V::get_unique) } } unsafe impl<V: UniqueValue> UniqueValue for [V] { fn get_unique(&self) -> Option<&str> { if self.len() > 1 { None } else { self.get(0).and_then(V::get_unique) } } } unsafe impl<V: UniqueValue +?Sized> UniqueValue for Box<V> { fn get_unique(&self) -> Option<&str> { (**self).get_unique() } } unsafe impl<V: UniqueValue +?Sized> UniqueValue for Rc<V> { fn get_unique(&self) -> Option<&str> { (**self).get_unique() } } unsafe impl<V: UniqueValue +?Sized> UniqueValue for Arc<V> { fn get_unique(&self) -> Option<&str> { (**self).get_unique() } } unsafe impl<V: UniqueValue> UniqueValue for Vec<V> { fn get_unique(&self) -> Option<&str> { if self.len() > 1 { None } else { self.get(0).and_then(V::get_unique) } } } mod test { use super::*; /// Compilation tests for various possible QueryParameter impls. #[allow(unused)] #[allow(dead_code)] fn test_query_parameter_impls() { let _ = (&HashMap::<String, String>::new()) as &dyn QueryParameter; let _ = (&HashMap::<&'static str, &'static str>::new()) as &dyn QueryParameter; let _ = (&HashMap::<Cow<'static, str>, Cow<'static, str>>::new()) as &dyn QueryParameter; let _ = (&HashMap::<String, Vec<String>>::new()) as &dyn QueryParameter; let _ = (&HashMap::<String, Box<String>>::new()) as &dyn QueryParameter; let _ = (&HashMap::<String, Box<[Cow<'static, str>]>>::new()) as &dyn QueryParameter; } }
unique_value
identifier_name
system.rs
use crate::simulation::agent_shader::ty::PushConstantData; use crate::simulation::blur_fade_shader; use crate::simulation::Simulation; use imgui::{Context, Ui}; use imgui_vulkano_renderer::Renderer; use imgui_winit_support::{HiDpiMode, WinitPlatform}; use std::sync::Arc; use std::time::{Duration, Instant}; use vulkano::command_buffer::AutoCommandBufferBuilder; use vulkano::device::{Device, DeviceExtensions, Queue}; use vulkano::image::{ImageUsage, SwapchainImage}; use vulkano::instance::{Instance, PhysicalDevice}; use vulkano::swapchain; use vulkano::swapchain::{ AcquireError, ColorSpace, FullscreenExclusive, PresentMode, Surface, SurfaceTransform, Swapchain, SwapchainCreationError, }; use vulkano::sync; use vulkano::sync::{FlushError, GpuFuture}; use vulkano_win::VkSurfaceBuild; use winit::event::{Event, WindowEvent}; use winit::event_loop::{ControlFlow, EventLoop}; use winit::window::{Window, WindowBuilder}; pub struct System { pub event_loop: EventLoop<()>, pub device: Arc<Device>, pub queue: Arc<Queue>, pub surface: Arc<Surface<Window>>, pub swapchain: Arc<Swapchain<Window>>, pub images: Vec<Arc<SwapchainImage<Window>>>, pub imgui: Context, pub platform: WinitPlatform, pub renderer: Renderer, } impl System { pub fn init(window_title: &str) -> System { // Basic commands taken from the vulkano imgui examples: // https://github.com/Tenebryo/imgui-vulkano-renderer/blob/master/examples/support/mod.rs let instance = { let extensions = vulkano_win::required_extensions(); Instance::new(None, &extensions, None).expect("Failed to create instance.") }; let physical = PhysicalDevice::enumerate(&instance) .next() .expect("No device available"); let event_loop = EventLoop::new(); let surface = WindowBuilder::new() .with_title(window_title.to_owned()) .with_inner_size(winit::dpi::PhysicalSize { width: 2000, height: 1400, }) .build_vk_surface(&event_loop, instance.clone()) .unwrap(); let queue_family = physical .queue_families() .find(|&q| q.supports_graphics() && q.explicitly_supports_transfers() && surface.is_supported(q).unwrap_or(false) ) .expect("Device does not have a queue family that can draw to the window and supports transfers."); let (device, mut queues) = { let device_ext = DeviceExtensions { khr_swapchain: true, // Needed for compute shaders. khr_storage_buffer_storage_class: true, ..DeviceExtensions::none() }; Device::new( physical, physical.supported_features(), &device_ext, [(queue_family, 0.5)].iter().cloned(), ) .expect("Failed to create device") }; let queue = queues.next().unwrap(); let format; let (swapchain, images) = { let caps = surface .capabilities(physical) .expect("Failed to get capabilities."); format = caps.supported_formats[0].0; let dimensions = caps.current_extent.unwrap_or([1280, 1024]); let alpha = caps.supported_composite_alpha.iter().next().unwrap(); let image_usage = ImageUsage { transfer_destination: true, ..ImageUsage::color_attachment() }; Swapchain::new( device.clone(), surface.clone(), caps.min_image_count, format, dimensions, 1, image_usage, &queue, SurfaceTransform::Identity, alpha, PresentMode::Fifo, FullscreenExclusive::Default, true, ColorSpace::SrgbNonLinear, ) .expect("Failed to create swapchain") }; let mut imgui = Context::create(); imgui.set_ini_filename(None); let mut platform = WinitPlatform::init(&mut imgui); platform.attach_window(imgui.io_mut(), &surface.window(), HiDpiMode::Rounded); let renderer = Renderer::init(&mut imgui, device.clone(), queue.clone(), format) .expect("Failed to initialize renderer"); System { event_loop, device, queue, surface, swapchain, images, imgui, platform, renderer, } } pub fn main_loop< F: FnMut( &mut bool, &mut PushConstantData, &mut blur_fade_shader::ty::PushConstantData, &mut Ui, ) +'static, >( self, simulation: Simulation, mut run_ui: F, ) { let System { event_loop, device, queue, surface, mut swapchain, mut images, mut imgui, mut platform, mut renderer, .. } = self; // Apparently there are various reasons why we might need to re-create the swapchain. // For example when the target surface has changed size. // This keeps track of whether the previous frame encountered one of those reasons. let mut recreate_swapchain = false; let mut previous_frame_end = Some(sync::now(device.clone()).boxed()); let mut last_redraw = Instant::now(); let mut sim_parameters: PushConstantData = PushConstantData { // Pixels per second. agent_speed: 100.0, // Radians per second. agent_turn_speed: 50.0,
sensor_radius: 1, // In the range [0 - PI] sensor_angle_spacing: 0.18, // Seconds per frame. (60fps) delta_time: 0.016667, }; let mut fade_parameters: blur_fade_shader::ty::PushConstantData = blur_fade_shader::ty::PushConstantData { // Seconds per frame. (60fps) delta_time: 0.016667, evaporate_speed: 0.9, }; // target 60 fps let target_frame_time = Duration::from_millis(1000 / 60); event_loop.run(move |event, _, control_flow| { *control_flow = ControlFlow::Wait; match event { Event::MainEventsCleared => { platform .prepare_frame(imgui.io_mut(), &surface.window()) .expect("Failed to prepare frame."); surface.window().request_redraw(); } Event::RedrawRequested(_) => { // ---- Stick to the framerate ---- let t = Instant::now(); let since_last = t.duration_since(last_redraw); last_redraw = t; if since_last < target_frame_time { std::thread::sleep(target_frame_time - since_last); } // ---- Cleanup ---- previous_frame_end.as_mut().unwrap().cleanup_finished(); // ---- Recreate swapchain if necessary ---- if recreate_swapchain { let dimensions: [u32; 2] = surface.window().inner_size().into(); let (new_swapchain, new_images) = match swapchain.recreate_with_dimensions(dimensions) { Ok(r) => r, Err(SwapchainCreationError::UnsupportedDimensions) => return, Err(e) => panic!("Failed to recreate swapchain: {:?}", e), }; images = new_images; swapchain = new_swapchain; recreate_swapchain = false; } // ---- Run the user's imgui code ---- let mut ui = imgui.frame(); let mut run = true; run_ui(&mut run, &mut sim_parameters, &mut fade_parameters, &mut ui); if!run { *control_flow = ControlFlow::Exit; } // ---- Create draw commands ---- let (image_num, suboptimal, acquire_future) = match swapchain::acquire_next_image(swapchain.clone(), None) { Ok(r) => r, Err(AcquireError::OutOfDate) => { recreate_swapchain = true; return; } Err(e) => panic!("Failed to acquire next image: {:?}", e), }; if suboptimal { recreate_swapchain = true; } platform.prepare_render(&ui, surface.window()); let draw_data = ui.render(); let extent_x = simulation .result_image .dimensions() .width() .min(images[image_num].dimensions()[0]); let extent_y = simulation .result_image .dimensions() .height() .min(images[image_num].dimensions()[1]); let mut cmd_buf_builder = AutoCommandBufferBuilder::new(device.clone(), queue.family()) .expect("Failed to create command buffer"); cmd_buf_builder .clear_color_image(images[image_num].clone(), [0.0; 4].into()) .unwrap(); cmd_buf_builder .copy_image( simulation.result_image.clone(), [0; 3], 0, 0, images[image_num].clone(), [0; 3], 0, 0, [extent_x, extent_y, 1], 1, ) .expect("Failed to create image copy command"); renderer .draw_commands( &mut cmd_buf_builder, queue.clone(), images[image_num].clone(), draw_data, ) .expect("Rendering failed"); let cmd_buf = cmd_buf_builder .build() .expect("Failed to build command buffer"); // ---- Execute the draw commands ---- let (buffer_1, buffer_2, buffer_3) = simulation.create_command_buffers(&sim_parameters, &fade_parameters); let future = previous_frame_end .take() .unwrap() .join(acquire_future) .then_execute(queue.clone(), buffer_1) .unwrap() .then_execute(queue.clone(), buffer_2) .unwrap() .then_execute(queue.clone(), buffer_3) .unwrap() .then_execute(queue.clone(), cmd_buf) .unwrap() .then_swapchain_present(queue.clone(), swapchain.clone(), image_num) .then_signal_fence_and_flush(); match future { Ok(future) => { previous_frame_end = Some(future.boxed()); } Err(FlushError::OutOfDate) => { recreate_swapchain = true; previous_frame_end = Some(sync::now(device.clone()).boxed()); } Err(e) => { println!("Failed to flush future: {:?}", e); previous_frame_end = Some(sync::now(device.clone()).boxed()); } } } Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => { *control_flow = ControlFlow::Exit; } event => { // Pass events on to imgui. platform.handle_event(imgui.io_mut(), surface.window(), &event); } } }); } }
random_line_split
system.rs
use crate::simulation::agent_shader::ty::PushConstantData; use crate::simulation::blur_fade_shader; use crate::simulation::Simulation; use imgui::{Context, Ui}; use imgui_vulkano_renderer::Renderer; use imgui_winit_support::{HiDpiMode, WinitPlatform}; use std::sync::Arc; use std::time::{Duration, Instant}; use vulkano::command_buffer::AutoCommandBufferBuilder; use vulkano::device::{Device, DeviceExtensions, Queue}; use vulkano::image::{ImageUsage, SwapchainImage}; use vulkano::instance::{Instance, PhysicalDevice}; use vulkano::swapchain; use vulkano::swapchain::{ AcquireError, ColorSpace, FullscreenExclusive, PresentMode, Surface, SurfaceTransform, Swapchain, SwapchainCreationError, }; use vulkano::sync; use vulkano::sync::{FlushError, GpuFuture}; use vulkano_win::VkSurfaceBuild; use winit::event::{Event, WindowEvent}; use winit::event_loop::{ControlFlow, EventLoop}; use winit::window::{Window, WindowBuilder}; pub struct System { pub event_loop: EventLoop<()>, pub device: Arc<Device>, pub queue: Arc<Queue>, pub surface: Arc<Surface<Window>>, pub swapchain: Arc<Swapchain<Window>>, pub images: Vec<Arc<SwapchainImage<Window>>>, pub imgui: Context, pub platform: WinitPlatform, pub renderer: Renderer, } impl System { pub fn init(window_title: &str) -> System
.build_vk_surface(&event_loop, instance.clone()) .unwrap(); let queue_family = physical .queue_families() .find(|&q| q.supports_graphics() && q.explicitly_supports_transfers() && surface.is_supported(q).unwrap_or(false) ) .expect("Device does not have a queue family that can draw to the window and supports transfers."); let (device, mut queues) = { let device_ext = DeviceExtensions { khr_swapchain: true, // Needed for compute shaders. khr_storage_buffer_storage_class: true, ..DeviceExtensions::none() }; Device::new( physical, physical.supported_features(), &device_ext, [(queue_family, 0.5)].iter().cloned(), ) .expect("Failed to create device") }; let queue = queues.next().unwrap(); let format; let (swapchain, images) = { let caps = surface .capabilities(physical) .expect("Failed to get capabilities."); format = caps.supported_formats[0].0; let dimensions = caps.current_extent.unwrap_or([1280, 1024]); let alpha = caps.supported_composite_alpha.iter().next().unwrap(); let image_usage = ImageUsage { transfer_destination: true, ..ImageUsage::color_attachment() }; Swapchain::new( device.clone(), surface.clone(), caps.min_image_count, format, dimensions, 1, image_usage, &queue, SurfaceTransform::Identity, alpha, PresentMode::Fifo, FullscreenExclusive::Default, true, ColorSpace::SrgbNonLinear, ) .expect("Failed to create swapchain") }; let mut imgui = Context::create(); imgui.set_ini_filename(None); let mut platform = WinitPlatform::init(&mut imgui); platform.attach_window(imgui.io_mut(), &surface.window(), HiDpiMode::Rounded); let renderer = Renderer::init(&mut imgui, device.clone(), queue.clone(), format) .expect("Failed to initialize renderer"); System { event_loop, device, queue, surface, swapchain, images, imgui, platform, renderer, } } pub fn main_loop< F: FnMut( &mut bool, &mut PushConstantData, &mut blur_fade_shader::ty::PushConstantData, &mut Ui, ) +'static, >( self, simulation: Simulation, mut run_ui: F, ) { let System { event_loop, device, queue, surface, mut swapchain, mut images, mut imgui, mut platform, mut renderer, .. } = self; // Apparently there are various reasons why we might need to re-create the swapchain. // For example when the target surface has changed size. // This keeps track of whether the previous frame encountered one of those reasons. let mut recreate_swapchain = false; let mut previous_frame_end = Some(sync::now(device.clone()).boxed()); let mut last_redraw = Instant::now(); let mut sim_parameters: PushConstantData = PushConstantData { // Pixels per second. agent_speed: 100.0, // Radians per second. agent_turn_speed: 50.0, sensor_radius: 1, // In the range [0 - PI] sensor_angle_spacing: 0.18, // Seconds per frame. (60fps) delta_time: 0.016667, }; let mut fade_parameters: blur_fade_shader::ty::PushConstantData = blur_fade_shader::ty::PushConstantData { // Seconds per frame. (60fps) delta_time: 0.016667, evaporate_speed: 0.9, }; // target 60 fps let target_frame_time = Duration::from_millis(1000 / 60); event_loop.run(move |event, _, control_flow| { *control_flow = ControlFlow::Wait; match event { Event::MainEventsCleared => { platform .prepare_frame(imgui.io_mut(), &surface.window()) .expect("Failed to prepare frame."); surface.window().request_redraw(); } Event::RedrawRequested(_) => { // ---- Stick to the framerate ---- let t = Instant::now(); let since_last = t.duration_since(last_redraw); last_redraw = t; if since_last < target_frame_time { std::thread::sleep(target_frame_time - since_last); } // ---- Cleanup ---- previous_frame_end.as_mut().unwrap().cleanup_finished(); // ---- Recreate swapchain if necessary ---- if recreate_swapchain { let dimensions: [u32; 2] = surface.window().inner_size().into(); let (new_swapchain, new_images) = match swapchain.recreate_with_dimensions(dimensions) { Ok(r) => r, Err(SwapchainCreationError::UnsupportedDimensions) => return, Err(e) => panic!("Failed to recreate swapchain: {:?}", e), }; images = new_images; swapchain = new_swapchain; recreate_swapchain = false; } // ---- Run the user's imgui code ---- let mut ui = imgui.frame(); let mut run = true; run_ui(&mut run, &mut sim_parameters, &mut fade_parameters, &mut ui); if!run { *control_flow = ControlFlow::Exit; } // ---- Create draw commands ---- let (image_num, suboptimal, acquire_future) = match swapchain::acquire_next_image(swapchain.clone(), None) { Ok(r) => r, Err(AcquireError::OutOfDate) => { recreate_swapchain = true; return; } Err(e) => panic!("Failed to acquire next image: {:?}", e), }; if suboptimal { recreate_swapchain = true; } platform.prepare_render(&ui, surface.window()); let draw_data = ui.render(); let extent_x = simulation .result_image .dimensions() .width() .min(images[image_num].dimensions()[0]); let extent_y = simulation .result_image .dimensions() .height() .min(images[image_num].dimensions()[1]); let mut cmd_buf_builder = AutoCommandBufferBuilder::new(device.clone(), queue.family()) .expect("Failed to create command buffer"); cmd_buf_builder .clear_color_image(images[image_num].clone(), [0.0; 4].into()) .unwrap(); cmd_buf_builder .copy_image( simulation.result_image.clone(), [0; 3], 0, 0, images[image_num].clone(), [0; 3], 0, 0, [extent_x, extent_y, 1], 1, ) .expect("Failed to create image copy command"); renderer .draw_commands( &mut cmd_buf_builder, queue.clone(), images[image_num].clone(), draw_data, ) .expect("Rendering failed"); let cmd_buf = cmd_buf_builder .build() .expect("Failed to build command buffer"); // ---- Execute the draw commands ---- let (buffer_1, buffer_2, buffer_3) = simulation.create_command_buffers(&sim_parameters, &fade_parameters); let future = previous_frame_end .take() .unwrap() .join(acquire_future) .then_execute(queue.clone(), buffer_1) .unwrap() .then_execute(queue.clone(), buffer_2) .unwrap() .then_execute(queue.clone(), buffer_3) .unwrap() .then_execute(queue.clone(), cmd_buf) .unwrap() .then_swapchain_present(queue.clone(), swapchain.clone(), image_num) .then_signal_fence_and_flush(); match future { Ok(future) => { previous_frame_end = Some(future.boxed()); } Err(FlushError::OutOfDate) => { recreate_swapchain = true; previous_frame_end = Some(sync::now(device.clone()).boxed()); } Err(e) => { println!("Failed to flush future: {:?}", e); previous_frame_end = Some(sync::now(device.clone()).boxed()); } } } Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => { *control_flow = ControlFlow::Exit; } event => { // Pass events on to imgui. platform.handle_event(imgui.io_mut(), surface.window(), &event); } } }); } }
{ // Basic commands taken from the vulkano imgui examples: // https://github.com/Tenebryo/imgui-vulkano-renderer/blob/master/examples/support/mod.rs let instance = { let extensions = vulkano_win::required_extensions(); Instance::new(None, &extensions, None).expect("Failed to create instance.") }; let physical = PhysicalDevice::enumerate(&instance) .next() .expect("No device available"); let event_loop = EventLoop::new(); let surface = WindowBuilder::new() .with_title(window_title.to_owned()) .with_inner_size(winit::dpi::PhysicalSize { width: 2000, height: 1400, })
identifier_body
system.rs
use crate::simulation::agent_shader::ty::PushConstantData; use crate::simulation::blur_fade_shader; use crate::simulation::Simulation; use imgui::{Context, Ui}; use imgui_vulkano_renderer::Renderer; use imgui_winit_support::{HiDpiMode, WinitPlatform}; use std::sync::Arc; use std::time::{Duration, Instant}; use vulkano::command_buffer::AutoCommandBufferBuilder; use vulkano::device::{Device, DeviceExtensions, Queue}; use vulkano::image::{ImageUsage, SwapchainImage}; use vulkano::instance::{Instance, PhysicalDevice}; use vulkano::swapchain; use vulkano::swapchain::{ AcquireError, ColorSpace, FullscreenExclusive, PresentMode, Surface, SurfaceTransform, Swapchain, SwapchainCreationError, }; use vulkano::sync; use vulkano::sync::{FlushError, GpuFuture}; use vulkano_win::VkSurfaceBuild; use winit::event::{Event, WindowEvent}; use winit::event_loop::{ControlFlow, EventLoop}; use winit::window::{Window, WindowBuilder}; pub struct System { pub event_loop: EventLoop<()>, pub device: Arc<Device>, pub queue: Arc<Queue>, pub surface: Arc<Surface<Window>>, pub swapchain: Arc<Swapchain<Window>>, pub images: Vec<Arc<SwapchainImage<Window>>>, pub imgui: Context, pub platform: WinitPlatform, pub renderer: Renderer, } impl System { pub fn init(window_title: &str) -> System { // Basic commands taken from the vulkano imgui examples: // https://github.com/Tenebryo/imgui-vulkano-renderer/blob/master/examples/support/mod.rs let instance = { let extensions = vulkano_win::required_extensions(); Instance::new(None, &extensions, None).expect("Failed to create instance.") }; let physical = PhysicalDevice::enumerate(&instance) .next() .expect("No device available"); let event_loop = EventLoop::new(); let surface = WindowBuilder::new() .with_title(window_title.to_owned()) .with_inner_size(winit::dpi::PhysicalSize { width: 2000, height: 1400, }) .build_vk_surface(&event_loop, instance.clone()) .unwrap(); let queue_family = physical .queue_families() .find(|&q| q.supports_graphics() && q.explicitly_supports_transfers() && surface.is_supported(q).unwrap_or(false) ) .expect("Device does not have a queue family that can draw to the window and supports transfers."); let (device, mut queues) = { let device_ext = DeviceExtensions { khr_swapchain: true, // Needed for compute shaders. khr_storage_buffer_storage_class: true, ..DeviceExtensions::none() }; Device::new( physical, physical.supported_features(), &device_ext, [(queue_family, 0.5)].iter().cloned(), ) .expect("Failed to create device") }; let queue = queues.next().unwrap(); let format; let (swapchain, images) = { let caps = surface .capabilities(physical) .expect("Failed to get capabilities."); format = caps.supported_formats[0].0; let dimensions = caps.current_extent.unwrap_or([1280, 1024]); let alpha = caps.supported_composite_alpha.iter().next().unwrap(); let image_usage = ImageUsage { transfer_destination: true, ..ImageUsage::color_attachment() }; Swapchain::new( device.clone(), surface.clone(), caps.min_image_count, format, dimensions, 1, image_usage, &queue, SurfaceTransform::Identity, alpha, PresentMode::Fifo, FullscreenExclusive::Default, true, ColorSpace::SrgbNonLinear, ) .expect("Failed to create swapchain") }; let mut imgui = Context::create(); imgui.set_ini_filename(None); let mut platform = WinitPlatform::init(&mut imgui); platform.attach_window(imgui.io_mut(), &surface.window(), HiDpiMode::Rounded); let renderer = Renderer::init(&mut imgui, device.clone(), queue.clone(), format) .expect("Failed to initialize renderer"); System { event_loop, device, queue, surface, swapchain, images, imgui, platform, renderer, } } pub fn
< F: FnMut( &mut bool, &mut PushConstantData, &mut blur_fade_shader::ty::PushConstantData, &mut Ui, ) +'static, >( self, simulation: Simulation, mut run_ui: F, ) { let System { event_loop, device, queue, surface, mut swapchain, mut images, mut imgui, mut platform, mut renderer, .. } = self; // Apparently there are various reasons why we might need to re-create the swapchain. // For example when the target surface has changed size. // This keeps track of whether the previous frame encountered one of those reasons. let mut recreate_swapchain = false; let mut previous_frame_end = Some(sync::now(device.clone()).boxed()); let mut last_redraw = Instant::now(); let mut sim_parameters: PushConstantData = PushConstantData { // Pixels per second. agent_speed: 100.0, // Radians per second. agent_turn_speed: 50.0, sensor_radius: 1, // In the range [0 - PI] sensor_angle_spacing: 0.18, // Seconds per frame. (60fps) delta_time: 0.016667, }; let mut fade_parameters: blur_fade_shader::ty::PushConstantData = blur_fade_shader::ty::PushConstantData { // Seconds per frame. (60fps) delta_time: 0.016667, evaporate_speed: 0.9, }; // target 60 fps let target_frame_time = Duration::from_millis(1000 / 60); event_loop.run(move |event, _, control_flow| { *control_flow = ControlFlow::Wait; match event { Event::MainEventsCleared => { platform .prepare_frame(imgui.io_mut(), &surface.window()) .expect("Failed to prepare frame."); surface.window().request_redraw(); } Event::RedrawRequested(_) => { // ---- Stick to the framerate ---- let t = Instant::now(); let since_last = t.duration_since(last_redraw); last_redraw = t; if since_last < target_frame_time { std::thread::sleep(target_frame_time - since_last); } // ---- Cleanup ---- previous_frame_end.as_mut().unwrap().cleanup_finished(); // ---- Recreate swapchain if necessary ---- if recreate_swapchain { let dimensions: [u32; 2] = surface.window().inner_size().into(); let (new_swapchain, new_images) = match swapchain.recreate_with_dimensions(dimensions) { Ok(r) => r, Err(SwapchainCreationError::UnsupportedDimensions) => return, Err(e) => panic!("Failed to recreate swapchain: {:?}", e), }; images = new_images; swapchain = new_swapchain; recreate_swapchain = false; } // ---- Run the user's imgui code ---- let mut ui = imgui.frame(); let mut run = true; run_ui(&mut run, &mut sim_parameters, &mut fade_parameters, &mut ui); if!run { *control_flow = ControlFlow::Exit; } // ---- Create draw commands ---- let (image_num, suboptimal, acquire_future) = match swapchain::acquire_next_image(swapchain.clone(), None) { Ok(r) => r, Err(AcquireError::OutOfDate) => { recreate_swapchain = true; return; } Err(e) => panic!("Failed to acquire next image: {:?}", e), }; if suboptimal { recreate_swapchain = true; } platform.prepare_render(&ui, surface.window()); let draw_data = ui.render(); let extent_x = simulation .result_image .dimensions() .width() .min(images[image_num].dimensions()[0]); let extent_y = simulation .result_image .dimensions() .height() .min(images[image_num].dimensions()[1]); let mut cmd_buf_builder = AutoCommandBufferBuilder::new(device.clone(), queue.family()) .expect("Failed to create command buffer"); cmd_buf_builder .clear_color_image(images[image_num].clone(), [0.0; 4].into()) .unwrap(); cmd_buf_builder .copy_image( simulation.result_image.clone(), [0; 3], 0, 0, images[image_num].clone(), [0; 3], 0, 0, [extent_x, extent_y, 1], 1, ) .expect("Failed to create image copy command"); renderer .draw_commands( &mut cmd_buf_builder, queue.clone(), images[image_num].clone(), draw_data, ) .expect("Rendering failed"); let cmd_buf = cmd_buf_builder .build() .expect("Failed to build command buffer"); // ---- Execute the draw commands ---- let (buffer_1, buffer_2, buffer_3) = simulation.create_command_buffers(&sim_parameters, &fade_parameters); let future = previous_frame_end .take() .unwrap() .join(acquire_future) .then_execute(queue.clone(), buffer_1) .unwrap() .then_execute(queue.clone(), buffer_2) .unwrap() .then_execute(queue.clone(), buffer_3) .unwrap() .then_execute(queue.clone(), cmd_buf) .unwrap() .then_swapchain_present(queue.clone(), swapchain.clone(), image_num) .then_signal_fence_and_flush(); match future { Ok(future) => { previous_frame_end = Some(future.boxed()); } Err(FlushError::OutOfDate) => { recreate_swapchain = true; previous_frame_end = Some(sync::now(device.clone()).boxed()); } Err(e) => { println!("Failed to flush future: {:?}", e); previous_frame_end = Some(sync::now(device.clone()).boxed()); } } } Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => { *control_flow = ControlFlow::Exit; } event => { // Pass events on to imgui. platform.handle_event(imgui.io_mut(), surface.window(), &event); } } }); } }
main_loop
identifier_name
peers_tests.rs
#[cfg(not(feature = "native"))] use common::call_back; use common::executor::Timer; use common::for_tests::wait_for_log_re; use common::mm_ctx::{MmArc, MmCtxBuilder}; use common::privkey::key_pair_from_seed; #[cfg(feature = "native")] use common::wio::{drive, CORE}; use common::{block_on, now_float, small_rng}; use crdts::CmRDT; use futures::future::{select, Either}; use futures01::Future; use rand::{self, Rng, RngCore}; use serde_bytes::ByteBuf; use serde_json::Value as Json; use std::net::{Ipv4Addr, SocketAddr}; #[cfg(not(feature = "native"))] use std::os::raw::c_char; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; #[cfg(feature = "native")] use crate::http_fallback::UniqueActorId; #[cfg(any(target_os = "macos", target_os = "linux"))] fn ulimit_n() -> Option<u32> { use std::mem::zeroed; let mut lim: libc::rlimit = unsafe { zeroed() }; let rc = unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut lim) }; if rc == 0 { Some(lim.rlim_cur as u32) } else { None } } #[cfg(not(any(target_os = "macos", target_os = "linux")))] fn ulimit_n() -> Option<u32> { None } async fn peer(conf: Json, port: u16) -> MmArc { if let Some(n) = ulimit_n() { assert!(n > 2000, "`ulimit -n` is too low: {}", n) } let ctx = MmCtxBuilder::new().with_conf(conf).into_mm_arc(); unwrap!(ctx.log.thread_gravity_on()); let seed = fomat!((small_rng().next_u64())); unwrap!(ctx.secp256k1_key_pair.pin(unwrap!(key_pair_from_seed(&seed)))); if let Some(seednodes) = ctx.conf["seednodes"].as_array() { let mut seeds = unwrap!(ctx.seeds.lock()); assert!(seeds.is_empty()); // `fn lp_initpeers` was not invoked. assert!(!seednodes.is_empty()); seeds.push(unwrap!(unwrap!(seednodes[0].as_str()).parse())) } unwrap!(super::initialize(&ctx, 9999, port).await); ctx } async fn destruction_check(mm: MmArc) { mm.stop(); if let Err(err) = wait_for_log_re(&mm, 1., "delete_dugout finished!").await { // NB: We want to know if/when the `peers` destruction doesn't happen, but we don't want to panic about it. pintln!((err)) } } async fn peers_exchange(conf: Json) { let fallback_on = conf["http-fallback"] == "on"; let fallback = if fallback_on { 1 } else { 255 }; let alice = peer(conf.clone(), 2111).await; let bob = peer(conf, 2112).await; if!fallback_on { unwrap!(wait_for_log_re(&alice, 99., r"\[dht-boot] DHT bootstrap \.\.\. Done\.").await); unwrap!(wait_for_log_re(&bob, 33., r"\[dht-boot] DHT bootstrap \.\.\. Done\.").await); } let tested_lengths: &[usize] = &[ 2222, // Send multiple chunks. 1, // Reduce the number of chunks *in the same subject*. // 992 /* (1000 - bencode overhead - checksum) */ * 253 /* Compatible with (1u8..) */ - 1 /* space for number_of_chunks */ ]; let mut rng = small_rng(); for message_len in tested_lengths.iter() { // Send a message to Bob. let message: Vec<u8> = (0..*message_len).map(|_| rng.gen()).collect(); log! ("Sending " (message.len()) " bytes …"); let bob_id = unwrap!(bob.public_id()); let sending_f = unwrap!( super::send( alice.clone(), bob_id, Vec::from(&b"test_dht"[..]), fallback, message.clone() ) .await ); // Get that message from Alice. let validator = super::FixedValidator::Exact(ByteBuf::from(&message[..])); let rc = super::recv(bob.clone(), Vec::from(&b"test_dht"[..]), fallback, validator); let rc = select(Box::pin(rc), Timer::sleep(99.)).await; let received = match rc { Either::Left((rc, _)) => unwrap!(rc), Either::Right(_) => panic!("Out of time waiting for reply"), }; assert_eq!(received, message); if fallback_on { // TODO: Refine the log test. // TODO: Check that the HTTP fallback was NOT used if `!fallback_on`. unwrap!(wait_for_log_re(&alice, 0.1, r"transmit] TBD, time to use the HTTP fallback\.\.\.").await) // TODO: Check the time delta, with fallback 1 the delivery shouldn't take long. } let hn1 = crate::send_handlers_num(); drop(sending_f); let hn2 = crate::send_handlers_num(); if cfg!(feature = "native") { // Dropping SendHandlerRef results in the removal of the corresponding `Arc<SendHandler>`. assert!(hn1 > 0 && hn2 == hn1 - 1, "hn1 {} hn2 {}", hn1, hn2) } else { // `SEND_HANDLERS` only tracks the arcs in the native helper. assert!(hn1 == 0 && hn2 == 0, "hn1 {} hn2 {}", hn1, hn2) } } destruction_check(alice).await; destruction_check(bob).await; } /// Send and receive messages of various length and chunking via the DHT. pub async fn peers_dht() { peers_exchange(json! ({"dht": "on"})).await } #[cfg(not(feature = "native"))] #[no_mangle] pub extern "C" fn test_peers_dht(cb_id: i32) { use std::ptr::null; common::executor::spawn(async move { peers_dht().await; unsafe { call_back(cb_id, null(), 0) } }) } /// Using a minimal one second HTTP fallback which should happen before the DHT kicks in. #[cfg(feature = "native")] pub fn peers_http_fallback_recv() { let ctx = MmCtxBuilder::new().into_mm_arc(); let addr = SocketAddr::new(unwrap!("127.0.0.1".parse()), 30204); let server = unwrap!(super::http_fallback::new_http_fallback(ctx.weak(), addr)); unwrap!(CORE.lock()).spawn(server); block_on(peers_exchange(json! ({ "http-fallback": "on", "seednodes": ["127.0.0.1"], "http-fallback-port": 30204 }))) } #[cfg(not(feature = "native"))] pub fn peers_http_fallback_recv() {} #[cfg(feature = "native")] pub fn peers_direct_send() { use common::for_tests::wait_for_log; // Unstable results on our MacOS CI server, // which isn't a problem in general (direct UDP communication is a best effort optimization) // but is bad for the CI tests. // Might experiment more with MacOS in the future. if cfg!(target_os = "macos") { return; } // NB: Still need the DHT enabled in order for the pings to work. let alice = block_on(peer(json! ({"dht": "on"}), 2121)); let bob = block_on(peer(json! ({"dht": "on"}), 2122)); let bob_id = unwrap!(bob.public_id()); // Bob isn't a friend yet. let alice_pctx = unwrap!(super::PeersContext::from_ctx(&alice)); { let alice_trans = unwrap!(alice_pctx.trans_meta.lock()); assert!(!alice_trans.friends.contains_key(&bob_id)) } let mut rng = small_rng(); let message: Vec<u8> = (0..33).map(|_| rng.gen()).collect(); let _send_f = block_on(super::send( alice.clone(), bob_id, Vec::from(&b"subj"[..]), 255, message.clone(), )); let recv_f = super::recv( bob.clone(), Vec::from(&b"subj"[..]), 255, super::FixedValidator::AnythingGoes, ); // Confirm that Bob was added into the friendlist and that we don't know its address yet. { let alice_trans = unwrap!(alice_pctx.trans_meta.lock()); assert!(alice_trans.friends.contains_key(&bob_id)) } let bob_pctx = unwrap!(super::PeersContext::from_ctx(&bob)); assert_eq!(0, alice_pctx.direct_pings.load(Ordering::Relaxed)); assert_eq!(0, bob_pctx.direct_pings.load(Ordering::Relaxed)); // Hint at the Bob's endpoint. unwrap!(super::investigate_peer(&alice, "127.0.0.1", 2122)); // Direct pings triggered by `investigate_peer`. // NB: The sleep here is larger than expected because the actual pings start to fly only after the DHT initialization kicks in. unwrap!(wait_for_log(&bob.log, 22., &|_| bob_pctx .direct_pings .load(Ordering::Relaxed) > 0)); // Bob's reply. unwrap!(wait_for_log(&alice.log, 22., &|_| alice_pctx .direct_pings .load(Ordering::Relaxed) > 0)); // Confirm that Bob now has the address. let bob_addr = SocketAddr::new(Ipv4Addr::new(127, 0, 0, 1).into(), 2122); { let alice_trans = unwrap!(alice_pctx.trans_meta.lock()); assert!(alice_trans.friends[&bob_id].endpoints.contains_key(&bob_addr)) } // Finally see if Bob got the message. unwrap!(wait_for_log(&bob.log, 1., &|_| bob_pctx
let received = unwrap!(block_on(recv_f)); assert_eq!(received, message); assert!(now_float() - start < 0.1); // Double-check that we're not waiting for DHT chunks. block_on(destruction_check(alice)); block_on(destruction_check(bob)); } /// Check the primitives used to communicate with the HTTP fallback server. /// These are useful in implementing NAT traversal in situations /// where a truly distributed no-single-point-of failure operation is not necessary, /// like when we're using the fallback server to drive a tested mm2 instance. #[cfg(feature = "native")] pub fn peers_http_fallback_kv() { let ctx = MmCtxBuilder::new().into_mm_arc(); let addr = SocketAddr::new(unwrap!("127.0.0.1".parse()), 30205); let server = unwrap!(super::http_fallback::new_http_fallback(ctx.weak(), addr)); unwrap!(CORE.lock()).spawn(server); // Wait for the HTTP server to start. thread::sleep(Duration::from_millis(20)); // Insert several entries in parallel, relying on CRDT to ensure that no entry is lost. let entries = 9; let mut handles = Vec::with_capacity(entries); for en in 1..=entries { let unique_actor_id = (99 + en) as UniqueActorId; let key = fomat!((en)); let f = super::http_fallback::fetch_map(&addr, Vec::from(&b"test-id"[..])); let f = f.and_then(move |mut map| { let read_ctx = map.len(); map.apply(map.update(key, read_ctx.derive_add_ctx(unique_actor_id), |set, ctx| { set.add("1".into(), ctx) })); super::http_fallback::merge_map(&addr, Vec::from(&b"test-id"[..]), &map) }); handles.push((en, drive(f))) } for (en, f) in handles { let map = unwrap!(unwrap!(f.wait())); let _v = unwrap!(map.get(&fomat!((en))).val, "No such value: {}", en); } // See if all entries survived. let map = unwrap!(super::http_fallback::fetch_map(&addr, Vec::from(&b"test-id"[..])).wait()); for en in 1..=entries { let v = unwrap!(map.get(&fomat!((en))).val, "No such value: {}", en); let members = v.read().val; log! ("members of " (en) ": " [members]); } // TODO: Shut down the HTTP server as well. drop(ctx) } #[cfg(not(feature = "native"))] pub fn peers_http_fallback_kv() {}
.direct_chunks .load(Ordering::Relaxed) > 0)); let start = now_float();
random_line_split
peers_tests.rs
#[cfg(not(feature = "native"))] use common::call_back; use common::executor::Timer; use common::for_tests::wait_for_log_re; use common::mm_ctx::{MmArc, MmCtxBuilder}; use common::privkey::key_pair_from_seed; #[cfg(feature = "native")] use common::wio::{drive, CORE}; use common::{block_on, now_float, small_rng}; use crdts::CmRDT; use futures::future::{select, Either}; use futures01::Future; use rand::{self, Rng, RngCore}; use serde_bytes::ByteBuf; use serde_json::Value as Json; use std::net::{Ipv4Addr, SocketAddr}; #[cfg(not(feature = "native"))] use std::os::raw::c_char; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; #[cfg(feature = "native")] use crate::http_fallback::UniqueActorId; #[cfg(any(target_os = "macos", target_os = "linux"))] fn ulimit_n() -> Option<u32> { use std::mem::zeroed; let mut lim: libc::rlimit = unsafe { zeroed() }; let rc = unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut lim) }; if rc == 0 { Some(lim.rlim_cur as u32) } else { None } } #[cfg(not(any(target_os = "macos", target_os = "linux")))] fn ulimit_n() -> Option<u32> { None } async fn peer(conf: Json, port: u16) -> MmArc { if let Some(n) = ulimit_n() { assert!(n > 2000, "`ulimit -n` is too low: {}", n) } let ctx = MmCtxBuilder::new().with_conf(conf).into_mm_arc(); unwrap!(ctx.log.thread_gravity_on()); let seed = fomat!((small_rng().next_u64())); unwrap!(ctx.secp256k1_key_pair.pin(unwrap!(key_pair_from_seed(&seed)))); if let Some(seednodes) = ctx.conf["seednodes"].as_array() { let mut seeds = unwrap!(ctx.seeds.lock()); assert!(seeds.is_empty()); // `fn lp_initpeers` was not invoked. assert!(!seednodes.is_empty()); seeds.push(unwrap!(unwrap!(seednodes[0].as_str()).parse())) } unwrap!(super::initialize(&ctx, 9999, port).await); ctx } async fn destruction_check(mm: MmArc) { mm.stop(); if let Err(err) = wait_for_log_re(&mm, 1., "delete_dugout finished!").await { // NB: We want to know if/when the `peers` destruction doesn't happen, but we don't want to panic about it. pintln!((err)) } } async fn peers_exchange(conf: Json) { let fallback_on = conf["http-fallback"] == "on"; let fallback = if fallback_on { 1 } else { 255 }; let alice = peer(conf.clone(), 2111).await; let bob = peer(conf, 2112).await; if!fallback_on { unwrap!(wait_for_log_re(&alice, 99., r"\[dht-boot] DHT bootstrap \.\.\. Done\.").await); unwrap!(wait_for_log_re(&bob, 33., r"\[dht-boot] DHT bootstrap \.\.\. Done\.").await); } let tested_lengths: &[usize] = &[ 2222, // Send multiple chunks. 1, // Reduce the number of chunks *in the same subject*. // 992 /* (1000 - bencode overhead - checksum) */ * 253 /* Compatible with (1u8..) */ - 1 /* space for number_of_chunks */ ]; let mut rng = small_rng(); for message_len in tested_lengths.iter() { // Send a message to Bob. let message: Vec<u8> = (0..*message_len).map(|_| rng.gen()).collect(); log! ("Sending " (message.len()) " bytes …"); let bob_id = unwrap!(bob.public_id()); let sending_f = unwrap!( super::send( alice.clone(), bob_id, Vec::from(&b"test_dht"[..]), fallback, message.clone() ) .await ); // Get that message from Alice. let validator = super::FixedValidator::Exact(ByteBuf::from(&message[..])); let rc = super::recv(bob.clone(), Vec::from(&b"test_dht"[..]), fallback, validator); let rc = select(Box::pin(rc), Timer::sleep(99.)).await; let received = match rc { Either::Left((rc, _)) => unwrap!(rc), Either::Right(_) => panic!("Out of time waiting for reply"), }; assert_eq!(received, message); if fallback_on { // TODO: Refine the log test. // TODO: Check that the HTTP fallback was NOT used if `!fallback_on`. unwrap!(wait_for_log_re(&alice, 0.1, r"transmit] TBD, time to use the HTTP fallback\.\.\.").await) // TODO: Check the time delta, with fallback 1 the delivery shouldn't take long. } let hn1 = crate::send_handlers_num(); drop(sending_f); let hn2 = crate::send_handlers_num(); if cfg!(feature = "native") { // Dropping SendHandlerRef results in the removal of the corresponding `Arc<SendHandler>`. assert!(hn1 > 0 && hn2 == hn1 - 1, "hn1 {} hn2 {}", hn1, hn2) } else { // `SEND_HANDLERS` only tracks the arcs in the native helper. assert!(hn1 == 0 && hn2 == 0, "hn1 {} hn2 {}", hn1, hn2) } } destruction_check(alice).await; destruction_check(bob).await; } /// Send and receive messages of various length and chunking via the DHT. pub async fn peers_dht() { peers_exchange(json! ({"dht": "on"})).await } #[cfg(not(feature = "native"))] #[no_mangle] pub extern "C" fn test_peers_dht(cb_id: i32) {
/// Using a minimal one second HTTP fallback which should happen before the DHT kicks in. #[cfg(feature = "native")] pub fn peers_http_fallback_recv() { let ctx = MmCtxBuilder::new().into_mm_arc(); let addr = SocketAddr::new(unwrap!("127.0.0.1".parse()), 30204); let server = unwrap!(super::http_fallback::new_http_fallback(ctx.weak(), addr)); unwrap!(CORE.lock()).spawn(server); block_on(peers_exchange(json! ({ "http-fallback": "on", "seednodes": ["127.0.0.1"], "http-fallback-port": 30204 }))) } #[cfg(not(feature = "native"))] pub fn peers_http_fallback_recv() {} #[cfg(feature = "native")] pub fn peers_direct_send() { use common::for_tests::wait_for_log; // Unstable results on our MacOS CI server, // which isn't a problem in general (direct UDP communication is a best effort optimization) // but is bad for the CI tests. // Might experiment more with MacOS in the future. if cfg!(target_os = "macos") { return; } // NB: Still need the DHT enabled in order for the pings to work. let alice = block_on(peer(json! ({"dht": "on"}), 2121)); let bob = block_on(peer(json! ({"dht": "on"}), 2122)); let bob_id = unwrap!(bob.public_id()); // Bob isn't a friend yet. let alice_pctx = unwrap!(super::PeersContext::from_ctx(&alice)); { let alice_trans = unwrap!(alice_pctx.trans_meta.lock()); assert!(!alice_trans.friends.contains_key(&bob_id)) } let mut rng = small_rng(); let message: Vec<u8> = (0..33).map(|_| rng.gen()).collect(); let _send_f = block_on(super::send( alice.clone(), bob_id, Vec::from(&b"subj"[..]), 255, message.clone(), )); let recv_f = super::recv( bob.clone(), Vec::from(&b"subj"[..]), 255, super::FixedValidator::AnythingGoes, ); // Confirm that Bob was added into the friendlist and that we don't know its address yet. { let alice_trans = unwrap!(alice_pctx.trans_meta.lock()); assert!(alice_trans.friends.contains_key(&bob_id)) } let bob_pctx = unwrap!(super::PeersContext::from_ctx(&bob)); assert_eq!(0, alice_pctx.direct_pings.load(Ordering::Relaxed)); assert_eq!(0, bob_pctx.direct_pings.load(Ordering::Relaxed)); // Hint at the Bob's endpoint. unwrap!(super::investigate_peer(&alice, "127.0.0.1", 2122)); // Direct pings triggered by `investigate_peer`. // NB: The sleep here is larger than expected because the actual pings start to fly only after the DHT initialization kicks in. unwrap!(wait_for_log(&bob.log, 22., &|_| bob_pctx .direct_pings .load(Ordering::Relaxed) > 0)); // Bob's reply. unwrap!(wait_for_log(&alice.log, 22., &|_| alice_pctx .direct_pings .load(Ordering::Relaxed) > 0)); // Confirm that Bob now has the address. let bob_addr = SocketAddr::new(Ipv4Addr::new(127, 0, 0, 1).into(), 2122); { let alice_trans = unwrap!(alice_pctx.trans_meta.lock()); assert!(alice_trans.friends[&bob_id].endpoints.contains_key(&bob_addr)) } // Finally see if Bob got the message. unwrap!(wait_for_log(&bob.log, 1., &|_| bob_pctx .direct_chunks .load(Ordering::Relaxed) > 0)); let start = now_float(); let received = unwrap!(block_on(recv_f)); assert_eq!(received, message); assert!(now_float() - start < 0.1); // Double-check that we're not waiting for DHT chunks. block_on(destruction_check(alice)); block_on(destruction_check(bob)); } /// Check the primitives used to communicate with the HTTP fallback server. /// These are useful in implementing NAT traversal in situations /// where a truly distributed no-single-point-of failure operation is not necessary, /// like when we're using the fallback server to drive a tested mm2 instance. #[cfg(feature = "native")] pub fn peers_http_fallback_kv() { let ctx = MmCtxBuilder::new().into_mm_arc(); let addr = SocketAddr::new(unwrap!("127.0.0.1".parse()), 30205); let server = unwrap!(super::http_fallback::new_http_fallback(ctx.weak(), addr)); unwrap!(CORE.lock()).spawn(server); // Wait for the HTTP server to start. thread::sleep(Duration::from_millis(20)); // Insert several entries in parallel, relying on CRDT to ensure that no entry is lost. let entries = 9; let mut handles = Vec::with_capacity(entries); for en in 1..=entries { let unique_actor_id = (99 + en) as UniqueActorId; let key = fomat!((en)); let f = super::http_fallback::fetch_map(&addr, Vec::from(&b"test-id"[..])); let f = f.and_then(move |mut map| { let read_ctx = map.len(); map.apply(map.update(key, read_ctx.derive_add_ctx(unique_actor_id), |set, ctx| { set.add("1".into(), ctx) })); super::http_fallback::merge_map(&addr, Vec::from(&b"test-id"[..]), &map) }); handles.push((en, drive(f))) } for (en, f) in handles { let map = unwrap!(unwrap!(f.wait())); let _v = unwrap!(map.get(&fomat!((en))).val, "No such value: {}", en); } // See if all entries survived. let map = unwrap!(super::http_fallback::fetch_map(&addr, Vec::from(&b"test-id"[..])).wait()); for en in 1..=entries { let v = unwrap!(map.get(&fomat!((en))).val, "No such value: {}", en); let members = v.read().val; log! ("members of " (en) ": " [members]); } // TODO: Shut down the HTTP server as well. drop(ctx) } #[cfg(not(feature = "native"))] pub fn peers_http_fallback_kv() {}
use std::ptr::null; common::executor::spawn(async move { peers_dht().await; unsafe { call_back(cb_id, null(), 0) } }) }
identifier_body
peers_tests.rs
#[cfg(not(feature = "native"))] use common::call_back; use common::executor::Timer; use common::for_tests::wait_for_log_re; use common::mm_ctx::{MmArc, MmCtxBuilder}; use common::privkey::key_pair_from_seed; #[cfg(feature = "native")] use common::wio::{drive, CORE}; use common::{block_on, now_float, small_rng}; use crdts::CmRDT; use futures::future::{select, Either}; use futures01::Future; use rand::{self, Rng, RngCore}; use serde_bytes::ByteBuf; use serde_json::Value as Json; use std::net::{Ipv4Addr, SocketAddr}; #[cfg(not(feature = "native"))] use std::os::raw::c_char; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; #[cfg(feature = "native")] use crate::http_fallback::UniqueActorId; #[cfg(any(target_os = "macos", target_os = "linux"))] fn ulimit_n() -> Option<u32> { use std::mem::zeroed; let mut lim: libc::rlimit = unsafe { zeroed() }; let rc = unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut lim) }; if rc == 0 { Some(lim.rlim_cur as u32) } else { None } } #[cfg(not(any(target_os = "macos", target_os = "linux")))] fn ulimit_n() -> Option<u32> { None } async fn peer(conf: Json, port: u16) -> MmArc { if let Some(n) = ulimit_n() { assert!(n > 2000, "`ulimit -n` is too low: {}", n) } let ctx = MmCtxBuilder::new().with_conf(conf).into_mm_arc(); unwrap!(ctx.log.thread_gravity_on()); let seed = fomat!((small_rng().next_u64())); unwrap!(ctx.secp256k1_key_pair.pin(unwrap!(key_pair_from_seed(&seed)))); if let Some(seednodes) = ctx.conf["seednodes"].as_array() { let mut seeds = unwrap!(ctx.seeds.lock()); assert!(seeds.is_empty()); // `fn lp_initpeers` was not invoked. assert!(!seednodes.is_empty()); seeds.push(unwrap!(unwrap!(seednodes[0].as_str()).parse())) } unwrap!(super::initialize(&ctx, 9999, port).await); ctx } async fn destruction_check(mm: MmArc) { mm.stop(); if let Err(err) = wait_for_log_re(&mm, 1., "delete_dugout finished!").await { // NB: We want to know if/when the `peers` destruction doesn't happen, but we don't want to panic about it. pintln!((err)) } } async fn peers_exchange(conf: Json) { let fallback_on = conf["http-fallback"] == "on"; let fallback = if fallback_on { 1 } else { 255 }; let alice = peer(conf.clone(), 2111).await; let bob = peer(conf, 2112).await; if!fallback_on { unwrap!(wait_for_log_re(&alice, 99., r"\[dht-boot] DHT bootstrap \.\.\. Done\.").await); unwrap!(wait_for_log_re(&bob, 33., r"\[dht-boot] DHT bootstrap \.\.\. Done\.").await); } let tested_lengths: &[usize] = &[ 2222, // Send multiple chunks. 1, // Reduce the number of chunks *in the same subject*. // 992 /* (1000 - bencode overhead - checksum) */ * 253 /* Compatible with (1u8..) */ - 1 /* space for number_of_chunks */ ]; let mut rng = small_rng(); for message_len in tested_lengths.iter() { // Send a message to Bob. let message: Vec<u8> = (0..*message_len).map(|_| rng.gen()).collect(); log! ("Sending " (message.len()) " bytes …"); let bob_id = unwrap!(bob.public_id()); let sending_f = unwrap!( super::send( alice.clone(), bob_id, Vec::from(&b"test_dht"[..]), fallback, message.clone() ) .await ); // Get that message from Alice. let validator = super::FixedValidator::Exact(ByteBuf::from(&message[..])); let rc = super::recv(bob.clone(), Vec::from(&b"test_dht"[..]), fallback, validator); let rc = select(Box::pin(rc), Timer::sleep(99.)).await; let received = match rc { Either::Left((rc, _)) => unwrap!(rc), Either::Right(_) => panic!("Out of time waiting for reply"), }; assert_eq!(received, message); if fallback_on { // TODO: Refine the log test. // TODO: Check that the HTTP fallback was NOT used if `!fallback_on`. unwrap!(wait_for_log_re(&alice, 0.1, r"transmit] TBD, time to use the HTTP fallback\.\.\.").await) // TODO: Check the time delta, with fallback 1 the delivery shouldn't take long. } let hn1 = crate::send_handlers_num(); drop(sending_f); let hn2 = crate::send_handlers_num(); if cfg!(feature = "native") { // Dropping SendHandlerRef results in the removal of the corresponding `Arc<SendHandler>`. assert!(hn1 > 0 && hn2 == hn1 - 1, "hn1 {} hn2 {}", hn1, hn2) } else { // `SEND_HANDLERS` only tracks the arcs in the native helper. assert!(hn1 == 0 && hn2 == 0, "hn1 {} hn2 {}", hn1, hn2) } } destruction_check(alice).await; destruction_check(bob).await; } /// Send and receive messages of various length and chunking via the DHT. pub async fn peers_dht() { peers_exchange(json! ({"dht": "on"})).await } #[cfg(not(feature = "native"))] #[no_mangle] pub extern "C" fn test_peers_dht(cb_id: i32) { use std::ptr::null; common::executor::spawn(async move { peers_dht().await; unsafe { call_back(cb_id, null(), 0) } }) } /// Using a minimal one second HTTP fallback which should happen before the DHT kicks in. #[cfg(feature = "native")] pub fn peers_http_fallback_recv() { let ctx = MmCtxBuilder::new().into_mm_arc(); let addr = SocketAddr::new(unwrap!("127.0.0.1".parse()), 30204); let server = unwrap!(super::http_fallback::new_http_fallback(ctx.weak(), addr)); unwrap!(CORE.lock()).spawn(server); block_on(peers_exchange(json! ({ "http-fallback": "on", "seednodes": ["127.0.0.1"], "http-fallback-port": 30204 }))) } #[cfg(not(feature = "native"))] pub fn peers_http_fallback_recv() {} #[cfg(feature = "native")] pub fn peers_direct_send() { use common::for_tests::wait_for_log; // Unstable results on our MacOS CI server, // which isn't a problem in general (direct UDP communication is a best effort optimization) // but is bad for the CI tests. // Might experiment more with MacOS in the future. if cfg!(target_os = "macos") {
// NB: Still need the DHT enabled in order for the pings to work. let alice = block_on(peer(json! ({"dht": "on"}), 2121)); let bob = block_on(peer(json! ({"dht": "on"}), 2122)); let bob_id = unwrap!(bob.public_id()); // Bob isn't a friend yet. let alice_pctx = unwrap!(super::PeersContext::from_ctx(&alice)); { let alice_trans = unwrap!(alice_pctx.trans_meta.lock()); assert!(!alice_trans.friends.contains_key(&bob_id)) } let mut rng = small_rng(); let message: Vec<u8> = (0..33).map(|_| rng.gen()).collect(); let _send_f = block_on(super::send( alice.clone(), bob_id, Vec::from(&b"subj"[..]), 255, message.clone(), )); let recv_f = super::recv( bob.clone(), Vec::from(&b"subj"[..]), 255, super::FixedValidator::AnythingGoes, ); // Confirm that Bob was added into the friendlist and that we don't know its address yet. { let alice_trans = unwrap!(alice_pctx.trans_meta.lock()); assert!(alice_trans.friends.contains_key(&bob_id)) } let bob_pctx = unwrap!(super::PeersContext::from_ctx(&bob)); assert_eq!(0, alice_pctx.direct_pings.load(Ordering::Relaxed)); assert_eq!(0, bob_pctx.direct_pings.load(Ordering::Relaxed)); // Hint at the Bob's endpoint. unwrap!(super::investigate_peer(&alice, "127.0.0.1", 2122)); // Direct pings triggered by `investigate_peer`. // NB: The sleep here is larger than expected because the actual pings start to fly only after the DHT initialization kicks in. unwrap!(wait_for_log(&bob.log, 22., &|_| bob_pctx .direct_pings .load(Ordering::Relaxed) > 0)); // Bob's reply. unwrap!(wait_for_log(&alice.log, 22., &|_| alice_pctx .direct_pings .load(Ordering::Relaxed) > 0)); // Confirm that Bob now has the address. let bob_addr = SocketAddr::new(Ipv4Addr::new(127, 0, 0, 1).into(), 2122); { let alice_trans = unwrap!(alice_pctx.trans_meta.lock()); assert!(alice_trans.friends[&bob_id].endpoints.contains_key(&bob_addr)) } // Finally see if Bob got the message. unwrap!(wait_for_log(&bob.log, 1., &|_| bob_pctx .direct_chunks .load(Ordering::Relaxed) > 0)); let start = now_float(); let received = unwrap!(block_on(recv_f)); assert_eq!(received, message); assert!(now_float() - start < 0.1); // Double-check that we're not waiting for DHT chunks. block_on(destruction_check(alice)); block_on(destruction_check(bob)); } /// Check the primitives used to communicate with the HTTP fallback server. /// These are useful in implementing NAT traversal in situations /// where a truly distributed no-single-point-of failure operation is not necessary, /// like when we're using the fallback server to drive a tested mm2 instance. #[cfg(feature = "native")] pub fn peers_http_fallback_kv() { let ctx = MmCtxBuilder::new().into_mm_arc(); let addr = SocketAddr::new(unwrap!("127.0.0.1".parse()), 30205); let server = unwrap!(super::http_fallback::new_http_fallback(ctx.weak(), addr)); unwrap!(CORE.lock()).spawn(server); // Wait for the HTTP server to start. thread::sleep(Duration::from_millis(20)); // Insert several entries in parallel, relying on CRDT to ensure that no entry is lost. let entries = 9; let mut handles = Vec::with_capacity(entries); for en in 1..=entries { let unique_actor_id = (99 + en) as UniqueActorId; let key = fomat!((en)); let f = super::http_fallback::fetch_map(&addr, Vec::from(&b"test-id"[..])); let f = f.and_then(move |mut map| { let read_ctx = map.len(); map.apply(map.update(key, read_ctx.derive_add_ctx(unique_actor_id), |set, ctx| { set.add("1".into(), ctx) })); super::http_fallback::merge_map(&addr, Vec::from(&b"test-id"[..]), &map) }); handles.push((en, drive(f))) } for (en, f) in handles { let map = unwrap!(unwrap!(f.wait())); let _v = unwrap!(map.get(&fomat!((en))).val, "No such value: {}", en); } // See if all entries survived. let map = unwrap!(super::http_fallback::fetch_map(&addr, Vec::from(&b"test-id"[..])).wait()); for en in 1..=entries { let v = unwrap!(map.get(&fomat!((en))).val, "No such value: {}", en); let members = v.read().val; log! ("members of " (en) ": " [members]); } // TODO: Shut down the HTTP server as well. drop(ctx) } #[cfg(not(feature = "native"))] pub fn peers_http_fallback_kv() {}
return; }
conditional_block
peers_tests.rs
#[cfg(not(feature = "native"))] use common::call_back; use common::executor::Timer; use common::for_tests::wait_for_log_re; use common::mm_ctx::{MmArc, MmCtxBuilder}; use common::privkey::key_pair_from_seed; #[cfg(feature = "native")] use common::wio::{drive, CORE}; use common::{block_on, now_float, small_rng}; use crdts::CmRDT; use futures::future::{select, Either}; use futures01::Future; use rand::{self, Rng, RngCore}; use serde_bytes::ByteBuf; use serde_json::Value as Json; use std::net::{Ipv4Addr, SocketAddr}; #[cfg(not(feature = "native"))] use std::os::raw::c_char; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; #[cfg(feature = "native")] use crate::http_fallback::UniqueActorId; #[cfg(any(target_os = "macos", target_os = "linux"))] fn ulimit_n() -> Option<u32> { use std::mem::zeroed; let mut lim: libc::rlimit = unsafe { zeroed() }; let rc = unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut lim) }; if rc == 0 { Some(lim.rlim_cur as u32) } else { None } } #[cfg(not(any(target_os = "macos", target_os = "linux")))] fn ulimit_n() -> Option<u32> { None } async fn peer(conf: Json, port: u16) -> MmArc { if let Some(n) = ulimit_n() { assert!(n > 2000, "`ulimit -n` is too low: {}", n) } let ctx = MmCtxBuilder::new().with_conf(conf).into_mm_arc(); unwrap!(ctx.log.thread_gravity_on()); let seed = fomat!((small_rng().next_u64())); unwrap!(ctx.secp256k1_key_pair.pin(unwrap!(key_pair_from_seed(&seed)))); if let Some(seednodes) = ctx.conf["seednodes"].as_array() { let mut seeds = unwrap!(ctx.seeds.lock()); assert!(seeds.is_empty()); // `fn lp_initpeers` was not invoked. assert!(!seednodes.is_empty()); seeds.push(unwrap!(unwrap!(seednodes[0].as_str()).parse())) } unwrap!(super::initialize(&ctx, 9999, port).await); ctx } async fn
(mm: MmArc) { mm.stop(); if let Err(err) = wait_for_log_re(&mm, 1., "delete_dugout finished!").await { // NB: We want to know if/when the `peers` destruction doesn't happen, but we don't want to panic about it. pintln!((err)) } } async fn peers_exchange(conf: Json) { let fallback_on = conf["http-fallback"] == "on"; let fallback = if fallback_on { 1 } else { 255 }; let alice = peer(conf.clone(), 2111).await; let bob = peer(conf, 2112).await; if!fallback_on { unwrap!(wait_for_log_re(&alice, 99., r"\[dht-boot] DHT bootstrap \.\.\. Done\.").await); unwrap!(wait_for_log_re(&bob, 33., r"\[dht-boot] DHT bootstrap \.\.\. Done\.").await); } let tested_lengths: &[usize] = &[ 2222, // Send multiple chunks. 1, // Reduce the number of chunks *in the same subject*. // 992 /* (1000 - bencode overhead - checksum) */ * 253 /* Compatible with (1u8..) */ - 1 /* space for number_of_chunks */ ]; let mut rng = small_rng(); for message_len in tested_lengths.iter() { // Send a message to Bob. let message: Vec<u8> = (0..*message_len).map(|_| rng.gen()).collect(); log! ("Sending " (message.len()) " bytes …"); let bob_id = unwrap!(bob.public_id()); let sending_f = unwrap!( super::send( alice.clone(), bob_id, Vec::from(&b"test_dht"[..]), fallback, message.clone() ) .await ); // Get that message from Alice. let validator = super::FixedValidator::Exact(ByteBuf::from(&message[..])); let rc = super::recv(bob.clone(), Vec::from(&b"test_dht"[..]), fallback, validator); let rc = select(Box::pin(rc), Timer::sleep(99.)).await; let received = match rc { Either::Left((rc, _)) => unwrap!(rc), Either::Right(_) => panic!("Out of time waiting for reply"), }; assert_eq!(received, message); if fallback_on { // TODO: Refine the log test. // TODO: Check that the HTTP fallback was NOT used if `!fallback_on`. unwrap!(wait_for_log_re(&alice, 0.1, r"transmit] TBD, time to use the HTTP fallback\.\.\.").await) // TODO: Check the time delta, with fallback 1 the delivery shouldn't take long. } let hn1 = crate::send_handlers_num(); drop(sending_f); let hn2 = crate::send_handlers_num(); if cfg!(feature = "native") { // Dropping SendHandlerRef results in the removal of the corresponding `Arc<SendHandler>`. assert!(hn1 > 0 && hn2 == hn1 - 1, "hn1 {} hn2 {}", hn1, hn2) } else { // `SEND_HANDLERS` only tracks the arcs in the native helper. assert!(hn1 == 0 && hn2 == 0, "hn1 {} hn2 {}", hn1, hn2) } } destruction_check(alice).await; destruction_check(bob).await; } /// Send and receive messages of various length and chunking via the DHT. pub async fn peers_dht() { peers_exchange(json! ({"dht": "on"})).await } #[cfg(not(feature = "native"))] #[no_mangle] pub extern "C" fn test_peers_dht(cb_id: i32) { use std::ptr::null; common::executor::spawn(async move { peers_dht().await; unsafe { call_back(cb_id, null(), 0) } }) } /// Using a minimal one second HTTP fallback which should happen before the DHT kicks in. #[cfg(feature = "native")] pub fn peers_http_fallback_recv() { let ctx = MmCtxBuilder::new().into_mm_arc(); let addr = SocketAddr::new(unwrap!("127.0.0.1".parse()), 30204); let server = unwrap!(super::http_fallback::new_http_fallback(ctx.weak(), addr)); unwrap!(CORE.lock()).spawn(server); block_on(peers_exchange(json! ({ "http-fallback": "on", "seednodes": ["127.0.0.1"], "http-fallback-port": 30204 }))) } #[cfg(not(feature = "native"))] pub fn peers_http_fallback_recv() {} #[cfg(feature = "native")] pub fn peers_direct_send() { use common::for_tests::wait_for_log; // Unstable results on our MacOS CI server, // which isn't a problem in general (direct UDP communication is a best effort optimization) // but is bad for the CI tests. // Might experiment more with MacOS in the future. if cfg!(target_os = "macos") { return; } // NB: Still need the DHT enabled in order for the pings to work. let alice = block_on(peer(json! ({"dht": "on"}), 2121)); let bob = block_on(peer(json! ({"dht": "on"}), 2122)); let bob_id = unwrap!(bob.public_id()); // Bob isn't a friend yet. let alice_pctx = unwrap!(super::PeersContext::from_ctx(&alice)); { let alice_trans = unwrap!(alice_pctx.trans_meta.lock()); assert!(!alice_trans.friends.contains_key(&bob_id)) } let mut rng = small_rng(); let message: Vec<u8> = (0..33).map(|_| rng.gen()).collect(); let _send_f = block_on(super::send( alice.clone(), bob_id, Vec::from(&b"subj"[..]), 255, message.clone(), )); let recv_f = super::recv( bob.clone(), Vec::from(&b"subj"[..]), 255, super::FixedValidator::AnythingGoes, ); // Confirm that Bob was added into the friendlist and that we don't know its address yet. { let alice_trans = unwrap!(alice_pctx.trans_meta.lock()); assert!(alice_trans.friends.contains_key(&bob_id)) } let bob_pctx = unwrap!(super::PeersContext::from_ctx(&bob)); assert_eq!(0, alice_pctx.direct_pings.load(Ordering::Relaxed)); assert_eq!(0, bob_pctx.direct_pings.load(Ordering::Relaxed)); // Hint at the Bob's endpoint. unwrap!(super::investigate_peer(&alice, "127.0.0.1", 2122)); // Direct pings triggered by `investigate_peer`. // NB: The sleep here is larger than expected because the actual pings start to fly only after the DHT initialization kicks in. unwrap!(wait_for_log(&bob.log, 22., &|_| bob_pctx .direct_pings .load(Ordering::Relaxed) > 0)); // Bob's reply. unwrap!(wait_for_log(&alice.log, 22., &|_| alice_pctx .direct_pings .load(Ordering::Relaxed) > 0)); // Confirm that Bob now has the address. let bob_addr = SocketAddr::new(Ipv4Addr::new(127, 0, 0, 1).into(), 2122); { let alice_trans = unwrap!(alice_pctx.trans_meta.lock()); assert!(alice_trans.friends[&bob_id].endpoints.contains_key(&bob_addr)) } // Finally see if Bob got the message. unwrap!(wait_for_log(&bob.log, 1., &|_| bob_pctx .direct_chunks .load(Ordering::Relaxed) > 0)); let start = now_float(); let received = unwrap!(block_on(recv_f)); assert_eq!(received, message); assert!(now_float() - start < 0.1); // Double-check that we're not waiting for DHT chunks. block_on(destruction_check(alice)); block_on(destruction_check(bob)); } /// Check the primitives used to communicate with the HTTP fallback server. /// These are useful in implementing NAT traversal in situations /// where a truly distributed no-single-point-of failure operation is not necessary, /// like when we're using the fallback server to drive a tested mm2 instance. #[cfg(feature = "native")] pub fn peers_http_fallback_kv() { let ctx = MmCtxBuilder::new().into_mm_arc(); let addr = SocketAddr::new(unwrap!("127.0.0.1".parse()), 30205); let server = unwrap!(super::http_fallback::new_http_fallback(ctx.weak(), addr)); unwrap!(CORE.lock()).spawn(server); // Wait for the HTTP server to start. thread::sleep(Duration::from_millis(20)); // Insert several entries in parallel, relying on CRDT to ensure that no entry is lost. let entries = 9; let mut handles = Vec::with_capacity(entries); for en in 1..=entries { let unique_actor_id = (99 + en) as UniqueActorId; let key = fomat!((en)); let f = super::http_fallback::fetch_map(&addr, Vec::from(&b"test-id"[..])); let f = f.and_then(move |mut map| { let read_ctx = map.len(); map.apply(map.update(key, read_ctx.derive_add_ctx(unique_actor_id), |set, ctx| { set.add("1".into(), ctx) })); super::http_fallback::merge_map(&addr, Vec::from(&b"test-id"[..]), &map) }); handles.push((en, drive(f))) } for (en, f) in handles { let map = unwrap!(unwrap!(f.wait())); let _v = unwrap!(map.get(&fomat!((en))).val, "No such value: {}", en); } // See if all entries survived. let map = unwrap!(super::http_fallback::fetch_map(&addr, Vec::from(&b"test-id"[..])).wait()); for en in 1..=entries { let v = unwrap!(map.get(&fomat!((en))).val, "No such value: {}", en); let members = v.read().val; log! ("members of " (en) ": " [members]); } // TODO: Shut down the HTTP server as well. drop(ctx) } #[cfg(not(feature = "native"))] pub fn peers_http_fallback_kv() {}
destruction_check
identifier_name
lib.rs
OwnerProofSystem, Randomness, LockIdentifier, Filter}, weights::{ Weight, IdentityFee, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND}, }, }; // A few exports that help ease life for downstream crates. #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; pub use sp_runtime::{Permill, Perbill}; pub use pallet_timestamp::Call as TimestampCall; pub use pallet_balances::Call as BalancesCall; pub use pallet_staking::StakerStatus; /// Import the template pallet. pub use pallet_template; pub mod common; pub use common::*; pub use common::opaque; pub mod constants; pub use constants::{time::*, currency::*, fee::*}; pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("bandot"), impl_name: create_runtime_str!("bandot"), authoring_version: 1, spec_version: 1, impl_version: 1, apis: RUNTIME_API_VERSIONS, transaction_version: 1, }; /// The version information used to identify this runtime when compiled natively. #[cfg(feature = "std")] pub fn native_version() -> NativeVersion { NativeVersion { runtime_version: VERSION, can_author_with: Default::default(), } } impl_opaque_keys! { pub struct SessionKeys { pub babe: Babe, pub grandpa: Grandpa, pub im_online: ImOnline, pub authority_discovery: AuthorityDiscovery, //pub parachain_validator: ParachainSessionKeyPlaceholder<Runtime>, } } /// Avoid processing transactions from slots and parachain registrar. pub struct BaseFilter; impl Filter<Call> for BaseFilter { fn filter(_: &Call) -> bool { true } } parameter_types! { pub const BlockHashCount: BlockNumber = 2400; /// We allow for 2 seconds of compute with a 6 second average block time. pub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND; pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); /// Assume 10% of weight for average on_initialize calls. pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get() .saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get(); pub const MaximumBlockLength: u32 = 5 * 1024 * 1024; pub const Version: RuntimeVersion = VERSION; } /// frame_system by skyh 0927 impl frame_system::Trait for Runtime { type BaseCallFilter = BaseFilter; /// filter 0927 type AccountId = AccountId; type AccountData = pallet_balances::AccountData<Balance>; type Header = generic::Header<BlockNumber, BlakeTwo256>; type Lookup = IdentityLookup<AccountId>; type Index = Index; type Hash = Hash; type Hashing = BlakeTwo256; type BlockNumber = BlockNumber; type BlockHashCount = BlockHashCount; type BlockExecutionWeight = BlockExecutionWeight; type ExtrinsicBaseWeight = ExtrinsicBaseWeight; type MaximumBlockLength = MaximumBlockLength; type MaximumBlockWeight = MaximumBlockWeight; type MaximumExtrinsicWeight = MaximumExtrinsicWeight; type AvailableBlockRatio = AvailableBlockRatio; type DbWeight = RocksDbWeight; type PalletInfo = PalletInfo; type Version = Version; type Call = Call; type Event = Event; type Origin = Origin; type OnNewAccount = (); type OnKilledAccount = (); /// type SystemWeightInfo = (); } parameter_types! { pub const EpochDuration: u64 = EPOCH_DURATION_IN_SLOTS; pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK; } /// pallet_babe by skyh 0927 impl pallet_babe::Trait for Runtime { type EpochDuration = EpochDuration; type ExpectedBlockTime = ExpectedBlockTime; type EpochChangeTrigger = pallet_babe::ExternalTrigger; type KeyOwnerProofSystem = Historical; type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, pallet_babe::AuthorityId)>>::Proof; type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, pallet_babe::AuthorityId)>>::IdentificationTuple; type HandleEquivocation = pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, ()>; // Offences type WeightInfo = (); } /// pallet_grandpa by skyh 0927 impl pallet_grandpa::Trait for Runtime { type KeyOwnerProofSystem = Historical; type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof; type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::IdentificationTuple; type HandleEquivocation = pallet_grandpa::EquivocationHandler<Self::KeyOwnerIdentification, ()>; // Offences type WeightInfo = (); type Event = Event; type Call = Call; } parameter_types! { pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17); } /// pallet_session by skyh 0927 impl pallet_session::Trait for Runtime { type Keys = SessionKeys; type ValidatorId = <Self as frame_system::Trait>::AccountId; type ValidatorIdOf = pallet_staking::StashOf<Self>; type ShouldEndSession = Babe; type NextSessionRotation = Babe; type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, Staking>; type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders; type DisabledValidatorsThreshold = DisabledValidatorsThreshold; type WeightInfo = (); type Event = Event; } impl pallet_session::historical::Trait for Runtime { type FullIdentification = pallet_staking::Exposure<AccountId, Balance>; type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>; } /// frame_system::offchain by skyh 0927 impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime where Call: From<C>, { type Extrinsic = UncheckedExtrinsic; type OverarchingCall = Call; } pallet_staking_reward_curve::build! { const REWARD_CURVE: PiecewiseLinear<'static> = curve!( min_inflation: 0_025_000, max_inflation: 0_100_000, ideal_stake: 0_500_000, falloff: 0_050_000, max_piece_count: 40, test_precision: 0_005_000, ); } /// Struct that handles the conversion of Balance -> `u64`. This is used for /// staking's election calculation. pub struct CurrencyToVoteHandler; impl CurrencyToVoteHandler { fn factor() -> Balance
} impl Convert<Balance, u64> for CurrencyToVoteHandler { fn convert(x: Balance) -> u64 { (x / Self::factor()) as u64 } } impl Convert<u128, Balance> for CurrencyToVoteHandler { fn convert(x: u128) -> Balance { x * Self::factor() } } parameter_types! { pub const SessionsPerEra: sp_staking::SessionIndex = 3; // 3 hours pub const BondingDuration: pallet_staking::EraIndex = 4; // 12 hours pub const SlashDeferDuration: pallet_staking::EraIndex = 2; // 6 hours pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE; pub const MaxNominatorRewardedPerValidator: u32 = 64; pub const ElectionLookahead: BlockNumber = EPOCH_DURATION_IN_BLOCKS / 4; pub const StakingUnsignedPriority: TransactionPriority = TransactionPriority::max_value() / 2; pub const MaxIterations: u32 = 5; // 0.05%. The higher the value, the more strict solution acceptance becomes. pub MinSolutionScoreBump: Perbill = Perbill::from_rational_approximation(5u32, 10_000); } /// pallet_staking::offchain by skyh 0927 impl pallet_staking::Trait for Runtime { type Currency = Balances; type UnixTime = Timestamp; type CurrencyToVote = CurrencyToVoteHandler; type RewardRemainder = Treasury; type RewardCurve = RewardCurve; type Slash = Treasury; // send the slashed funds to the pallet treasury. type Reward = (); // rewards are minted from the void type SessionInterface = Self; type SessionsPerEra = SessionsPerEra; type BondingDuration = BondingDuration; type SlashDeferDuration = SlashDeferDuration; /// A super-majority of the council can cancel the slash. type SlashCancelOrigin = frame_system::EnsureRoot<Self::AccountId>; // TODO type NextNewSession = Session; type ElectionLookahead = ElectionLookahead; type UnsignedPriority = StakingUnsignedPriority; type MaxIterations = MaxIterations; type MinSolutionScoreBump = MinSolutionScoreBump; type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator; type WeightInfo = (); type Event = Event; type Call = Call; } parameter_types! { pub const CouncilMotionDuration: BlockNumber = 3 * DAYS; pub const CouncilMaxProposals: u32 = 100; pub const CouncilMaxMembers: u32 = 100; } type CouncilCollective = pallet_collective::Instance1; pub type MoreThanHalfCouncil = EnsureOneOf< AccountId, EnsureRoot<AccountId>, pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective> >; pub type SlashCancelOrigin = EnsureOneOf< AccountId, EnsureRoot<AccountId>, pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective> >; /// pallet_collective by skyh 1020 impl pallet_collective::Trait<CouncilCollective> for Runtime { type MotionDuration = CouncilMotionDuration; type MaxProposals = CouncilMaxProposals; type MaxMembers = CouncilMaxMembers; type DefaultVote = pallet_collective::PrimeDefaultVote; // type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>; type WeightInfo = (); type Origin = Origin; type Proposal = Call; type Event = Event; } parameter_types! { pub const TechnicalMotionDuration: BlockNumber = 3 * DAYS; pub const TechnicalMaxProposals: u32 = 100; pub const TechnicalMaxMembers: u32 = 100; } type TechnicalCollective = pallet_collective::Instance2; impl pallet_collective::Trait<TechnicalCollective> for Runtime { type Origin = Origin; type Proposal = Call; type Event = Event; type MotionDuration = TechnicalMotionDuration; type MaxProposals = TechnicalMaxProposals; type MaxMembers = TechnicalMaxMembers; type DefaultVote = pallet_collective::PrimeDefaultVote; // type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>; type WeightInfo = (); } parameter_types! { pub const LaunchPeriod: BlockNumber = 7 * DAYS; pub const VotingPeriod: BlockNumber = 7 * DAYS; pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS; pub const MinimumDeposit: Balance = 1 * DOLLARS; pub const EnactmentPeriod: BlockNumber = 8 * DAYS; pub const CooloffPeriod: BlockNumber = 7 * DAYS; // One cent: $10,000 / MB pub const PreimageByteDeposit: Balance = 10 * MILLICENTS; pub const InstantAllowed: bool = true; pub const MaxVotes: u32 = 100; pub const MaxProposals: u32 = 100; } /// pallet_democracy by skyh 1020 impl pallet_democracy::Trait for Runtime { type Proposal = Call; type Event = Event; type Currency = Balances; type EnactmentPeriod = EnactmentPeriod; type LaunchPeriod = LaunchPeriod; type VotingPeriod = VotingPeriod; type CooloffPeriod = CooloffPeriod; type PalletsOrigin = OriginCaller; type VetoOrigin = pallet_collective::EnsureMember<AccountId, TechnicalCollective>; type ExternalOrigin = pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>; type ExternalMajorityOrigin = pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>; type ExternalDefaultOrigin = pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, CouncilCollective>; /// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote /// be tabled immediately and with a shorter voting/enactment period. type FastTrackOrigin = pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>; type InstantOrigin = pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>; type InstantAllowed = InstantAllowed; type FastTrackVotingPeriod = FastTrackVotingPeriod; // To cancel a proposal which has been passed, 2/3 of the council must agree to it. type CancellationOrigin = EnsureOneOf< AccountId, EnsureRoot<AccountId>, pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>, >; // To cancel a proposal before it has been passed, the technical committee must be unanimous or // Root must agree. // type CancelProposalOrigin = EnsureOneOf< // AccountId, // EnsureRoot<AccountId>, // pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>, // >; // type BlacklistOrigin = EnsureRoot<AccountId>; // Any single technical committee member may veto a coming council proposal, however they can // only do it once and it lasts only for the cooloff period. type Slash = Treasury; type Scheduler = Scheduler; type MaxVotes = MaxVotes; type MinimumDeposit = MinimumDeposit; type PreimageByteDeposit = PreimageByteDeposit; type OperationalPreimageOrigin = pallet_collective::EnsureMember<AccountId, CouncilCollective>; type WeightInfo = (); // type MaxProposals = MaxProposals; } parameter_types! { pub const CandidacyBond: Balance = 1 * DOLLARS; pub const VotingBond: Balance = 5 * CENTS; /// Daily council elections. pub const TermDuration: BlockNumber = 24 * HOURS; pub const DesiredMembers: u32 = 19; pub const DesiredRunnersUp: u32 = 19; pub const ElectionsPhragmenModuleId: LockIdentifier = *b"phrelect"; } // Make sure that there are no more than MaxMembers members elected via phragmen. const_assert!(DesiredMembers::get() <= CouncilMaxMembers::get()); /// pallet_elections_phragmen by skyh 1020 impl pallet_elections_phragmen::Trait for Runtime { type Event = Event; type Currency = Balances; type ChangeMembers = Council; type InitializeMembers = Council; type CurrencyToVote = CurrencyToVoteHandler; type CandidacyBond = CandidacyBond; type VotingBond = VotingBond; type LoserCandidate = Treasury; type BadReport = Treasury; type KickedMember = Treasury; type DesiredMembers = DesiredMembers; type DesiredRunnersUp = DesiredRunnersUp; type TermDuration = TermDuration; type ModuleId = ElectionsPhragmenModuleId; // type WeightInfo = weights::pallet_elections_phragmen::WeightInfo<Runtime>; type WeightInfo = (); } /// pallet_membership by skyh 1020 impl pallet_membership::Trait<pallet_membership::Instance1> for Runtime { type Event = Event; type AddOrigin = MoreThanHalfCouncil; type RemoveOrigin = MoreThanHalfCouncil; type SwapOrigin = MoreThanHalfCouncil; type ResetOrigin = MoreThanHalfCouncil; type PrimeOrigin = MoreThanHalfCouncil; type MembershipInitialized = TechnicalCommittee; type MembershipChanged = TechnicalCommittee; } parameter_types! { pub const ProposalBond: Permill = Permill::from_percent(5); pub const ProposalBondMinimum: Balance = 20 * DOLLARS; pub const SpendPeriod: BlockNumber = 6 * DAYS; pub const Burn: Permill = Permill::from_perthousand(2); pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry"); pub const TipCountdown: BlockNumber = 1 * DAYS; pub const TipFindersFee: Percent = Percent::from_percent(20); pub const TipReportDepositBase: Balance = 1 * DOLLARS; pub const DataDepositPerByte: Balance = 1 * CENTS; pub const BountyDepositBase: Balance = 1 * DOLLARS; pub const BountyDepositPayoutDelay: BlockNumber = 4 * DAYS; pub const BountyUpdatePeriod: BlockNumber = 90 * DAYS; pub const MaximumReasonLength: u32 = 16384; pub const BountyCuratorDeposit: Permill = Permill::from_percent(50); pub const BountyValueMinimum: Balance = 2 * DOLLARS; } type ApproveOrigin = EnsureOneOf< AccountId, EnsureRoot<AccountId>, pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective> >; /// pallet_treasury by skyh 1020 impl pallet_treasury::Trait for Runtime { type ModuleId = TreasuryModuleId; type Currency = Balances; type ApproveOrigin = ApproveOrigin; type RejectOrigin = MoreThanHalfCouncil; type DataDepositPerByte = DataDepositPerByte; type Tippers = ElectionsPhragmen; type TipCountdown = TipCountdown; type TipFindersFee = TipFindersFee; type TipReportDepositBase = TipReportDepositBase; type BountyDepositBase = BountyDepositBase; type BountyDepositPayoutDelay = BountyDepositPayoutDelay; type BountyUpdatePeriod = BountyUpdatePeriod; type MaximumReasonLength = MaximumReasonLength; type BountyCuratorDeposit = BountyCuratorDeposit; type BountyValueMinimum = BountyValueMinimum; // type BurnDestination = Society; type ProposalBond = ProposalBond; type ProposalBondMinimum = ProposalBondMinimum; type SpendPeriod = SpendPeriod; type OnSlash = Treasury; type Burn = Burn; type BurnDestination = (); // type WeightInfo = weights::pallet_treasury::WeightInfo<Runtime>; type WeightInfo = (); type Event = Event; } parameter_types! { pub const MaxScheduledPerBlock: u32 = 50; } /// pallet_scheduler by skyh 1020 impl pallet_scheduler::Trait for Runtime { type PalletsOrigin = OriginCaller; type MaximumWeight = MaximumBlockWeight; type ScheduleOrigin = EnsureRoot<AccountId>; type MaxScheduledPerBlock = MaxScheduledPerBlock; type WeightInfo = (); type Origin = Origin; type Event = Event; type Call = Call; } parameter_types! { pub const SessionDuration: BlockNumber = EPOCH_DURATION_IN_BLOCKS as _; pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value(); } impl pallet_im_online::Trait for Runtime { type AuthorityId = ImOnlineId; type SessionDuration = SessionDuration; type ReportUnresponsiveness = Offences; type UnsignedPriority = ImOnlineUnsignedPriority; type WeightInfo = (); type Event = Event; } parameter_types! { pub const IndexDeposit: Balance = DOLLARS; } /// pallet_indices by skyh 1020 impl pallet_indices::Trait for Runtime { type AccountIndex = AccountIndex; type Deposit = IndexDeposit; type Currency = Balances; type WeightInfo = (); type Event = Event; } parameter_types! { pub OffencesWeightSoftLimit: Weight = Perbill::from_percent(60) * MaximumBlockWeight::get(); } /// pallet_offences by skyh 1020 impl pallet_offences::Trait for Runtime { type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>; type WeightSoftLimit = OffencesWeightSoftLimit; type OnOffenceHandler = Staking; type Event = Event; } impl pallet_utility::Trait for Runtime { type WeightInfo = (); type Event = Event; type Call = Call; } parameter_types! { pub const MinVestedTransfer: Balance = 100 * DOLLARS; } /// pallet_vesting by skyh 1020 impl pallet_vesting::Trait for Runtime { type Event = Event; type Currency = Balances; type BlockNumberToBalance = ConvertInto; type MinVestedTransfer = MinVestedTransfer; type WeightInfo = (); } impl pallet_authority_discovery::Trait for Runtime {} parameter_types! { pub const UncleGenerations: BlockNumber = 5; } /// pallet_authorship origin impl pallet_authorship::Trait for Runtime { type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>; type UncleGenerations = UncleGenerations; type FilterUncle = (); type EventHandler = (Staking, ()); // ImOnline } parameter_types! { pub const MinimumPeriod: u64 = SLOT_DURATION / 2; } /// pallet_timestamp origin impl pallet_timestamp::Trait for Runtime { /// A timestamp: milliseconds since the unix epoch. type Moment = Moment; type OnTimestampSet = Babe; type MinimumPeriod = MinimumPeriod; type WeightInfo = (); } parameter_types! { pub const ExistentialDeposit: u128 = 500; // 0 pub const MaxLocks: u32 = 50; } /// pallet_balances origin impl pallet_balances::Trait for Runtime { type Balance = Balance; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type MaxLocks = MaxLocks; type AccountStore = System; // type Event = Event; type WeightInfo = (); } parameter_types! { pub const TransactionByteFee: Balance = 1; } /// pallet_transaction_payment origin impl pallet_transaction_payment::Trait for Runtime { type Currency = Balances; type TransactionByteFee = TransactionByteFee; type WeightToFee = IdentityFee<Balance>; type OnTransactionPayment = (); // treasury type FeeMultiplierUpdate = (); // } impl pallet_sudo::Trait for Runtime { type Event = Event; type Call = Call; } /// Configure the template pallet in pallets/template. impl pallet_template::Trait for Runtime { type Event = Event; } // TODO // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( pub enum Runtime where Block = Block, NodeBlock = opaque::Block, UncheckedExtrinsic = UncheckedExtrinsic { System: frame_system::{Module, Call, Config, Storage, Event<T>}, RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage}, Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent}, Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>}, TransactionPayment: pallet_transaction_payment::{Module, Storage}, Sudo: pallet_sudo::{Module, Call, Config<T>, Storage, Event<T>}, Authorship: pallet_authorship::{Module, Call, Storage, Inherent}, Babe: pallet_babe::{Module, Call, Storage, Config, Inherent}, Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event}, Staking: pallet_staking::{Module, Call, Config<T>, Storage, Event<T>}, Session: pallet_session::{Module, Call, Storage, Event, Config<T>}, AuthorityDiscovery: pallet_authority_discovery::{Module, Call, Config}, Council: pallet_collective::<Instance1>::{Module, Call, Storage, Origin<T>, Event<T>, Config<T>}, TechnicalCommittee: pallet_collective::<Instance2>::{Module, Call, Storage, Origin<T>, Event<T>, Config<T>}, Democracy: pallet_democracy::{Module, Call, Storage, Config, Event<T>}, ElectionsPhragmen: pallet_elections_phragmen::{Module, Call, Storage, Event<T>, Config<T>}, TechnicalMembership: pallet_membership::<Instance1>::{Module, Call, Storage, Event<T>, Config<T>}, ImOnline: pallet_im_online::{Module, Call, Storage, Event<T>, ValidateUnsigned, Config<T>}, Indices: pallet_indices::{Module, Call, Storage, Config<T>, Event<T>}, Scheduler: pallet_scheduler::{Module, Call, Storage, Event<T>}, Treasury: pallet_treasury::{Module, Call, Storage, Event<T>}, Offences: pallet_offences::{Module, Call, Storage, Event}, Historical: pallet_session_historical::{Module}, Vesting: pallet_vesting::{Module, Call, Storage, Event<T>, Config<T>}, Utility: pallet_utility::{Module, Call, Event}, // Include the custom logic from the template pallet in the runtime. TemplateModule: pallet_template::{Module, Call, Storage, Event<T>}, } ); /// The address format for describing accounts. pub type Address = AccountId; /// Block header type as expected by this runtime. pub type Header = generic::Header<BlockNumber, BlakeTwo256>; /// Block type as expected by this runtime. pub type Block = generic::Block<Header, UncheckedExtrinsic>; /// A Block signed with a Justification pub type SignedBlock = generic::SignedBlock<Block>; /// BlockId type as expected by this runtime. pub type BlockId = generic::BlockId<Block>; /// The SignedExtension to the basic transaction logic. pub type SignedExtra = ( frame_system::CheckSpecVersion<Runtime>, frame_system::CheckTxVersion<Runtime>, frame_system::CheckGenesis<Runtime>, frame_system::CheckEra<Runtime>, frame_system::CheckNonce<Runtime>, frame_system::CheckWeight<Runtime>, pallet_transaction_payment::ChargeTransactionPayment<Runtime> ); /// Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>; /// Extrinsic type that has already been checked. pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>; /// Executive: handles dispatch to the various modules. pub type Executive = frame_executive::Executive< Runtime, Block, frame_system::ChainContext<Runtime>, Runtime, AllModules, >; impl_runtime_apis! { impl sp_api::Core<Block> for Runtime { fn version() -> RuntimeVersion { VERSION } fn execute_block(block: Block) { Executive::execute_block(block) } fn initialize_block(header: &<Block as BlockT>::Header) { Executive::initialize_block(header) } } impl sp_api::Metadata<Block> for Runtime { fn metadata() -> OpaqueMetadata { Runtime::metadata().into() } } impl sp_block_builder::BlockBuilder<Block> for Runtime { fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult { Executive::apply_extrinsic(extrinsic) } fn finalize_block() -> <Block as BlockT>::Header { Executive::finalize_block() } fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> { data.create_extrinsics() } fn check_inherents( block: Block, data: sp_inherents::InherentData, ) -> sp_inherents::CheckInherentsResult { data.check_extrinsics(&block) } fn random_seed() -> <Block as BlockT>::Hash { RandomnessCollectiveFlip::random_seed() } } impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime { fn validate_transaction( source: TransactionSource, tx: <Block as BlockT>::Extrinsic, ) -> TransactionValidity { Executive::validate_transaction(source, tx) } } impl sp_offchain::OffchainWorkerApi<Block> for Runtime { fn offchain_worker(header: &<Block as BlockT>::Header) { Executive::offchain_worker(header) } } // TODO ### sp_consensus_babe by Skyh, 0927 ### /// configuration /// current_epoch_start /// generate_key_ownership_proof /// submit_report_equivocation_unsigned_extrinsic impl sp_consensus_babe::BabeApi<Block> for Runtime { fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration { // The choice of `c` parameter (where `1 - c` represents the // probability of a slot being empty), is done in accordance to the // slot duration and expected target block time, for safely // resisting network delays of maximum two seconds. // <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results> sp_consensus_babe::BabeGenesisConfiguration { slot_duration: Babe::slot_duration(), epoch_length: EpochDuration::get(), c: PRIMARY_PROBABILITY, genesis_authorities: Babe::authorities(), randomness: Babe::randomness(), allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryPlainSlots, } } fn current_epoch_start() -> sp_consensus_babe::SlotNumber { Babe::current_epoch_start() } fn generate_key_ownership_proof( _slot_number: sp_consensus_babe::SlotNumber, authority_id: sp_consensus_babe::AuthorityId, ) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> { use codec::Encode; Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id)) .map(|p| p.encode()) .map(sp_consensus_babe::OpaqueKeyOwnershipProof::new) } fn submit_report_equivocation_unsigned_extrinsic( equivocation_proof: sp_consensus_babe::EquivocationProof<<Block as BlockT>::Header>, key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof, ) -> Option<()> { let key_owner_proof = key_owner_proof.decode()?; Babe::submit_unsigned_equivocation_report( equivocation_proof, key_owner_proof, ) } } impl sp_session::SessionKeys<Block> for Runtime { fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> { SessionKeys::generate(seed) } fn decode_session_keys( encoded: Vec<u8>, ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> { SessionKeys::decode_into_raw_public_keys(&encoded) } } impl fg_primitives::GrandpaApi<Block> for Runtime { fn grandpa_authorities() -> GrandpaAuthorityList { Grandpa::grandpa_authorities() }
{ (Balances::total_issuance() / u64::max_value() as Balance).max(1) }
identifier_body
lib.rs
OwnerProofSystem, Randomness, LockIdentifier, Filter}, weights::{ Weight, IdentityFee, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND}, }, }; // A few exports that help ease life for downstream crates. #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; pub use sp_runtime::{Permill, Perbill}; pub use pallet_timestamp::Call as TimestampCall; pub use pallet_balances::Call as BalancesCall; pub use pallet_staking::StakerStatus; /// Import the template pallet. pub use pallet_template; pub mod common; pub use common::*; pub use common::opaque; pub mod constants; pub use constants::{time::*, currency::*, fee::*}; pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("bandot"), impl_name: create_runtime_str!("bandot"), authoring_version: 1, spec_version: 1, impl_version: 1, apis: RUNTIME_API_VERSIONS, transaction_version: 1, }; /// The version information used to identify this runtime when compiled natively. #[cfg(feature = "std")] pub fn native_version() -> NativeVersion { NativeVersion { runtime_version: VERSION, can_author_with: Default::default(), } } impl_opaque_keys! { pub struct SessionKeys { pub babe: Babe, pub grandpa: Grandpa, pub im_online: ImOnline, pub authority_discovery: AuthorityDiscovery, //pub parachain_validator: ParachainSessionKeyPlaceholder<Runtime>, } } /// Avoid processing transactions from slots and parachain registrar. pub struct BaseFilter; impl Filter<Call> for BaseFilter { fn filter(_: &Call) -> bool { true } } parameter_types! { pub const BlockHashCount: BlockNumber = 2400; /// We allow for 2 seconds of compute with a 6 second average block time. pub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND; pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); /// Assume 10% of weight for average on_initialize calls. pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get() .saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get(); pub const MaximumBlockLength: u32 = 5 * 1024 * 1024; pub const Version: RuntimeVersion = VERSION; } /// frame_system by skyh 0927 impl frame_system::Trait for Runtime { type BaseCallFilter = BaseFilter; /// filter 0927 type AccountId = AccountId; type AccountData = pallet_balances::AccountData<Balance>; type Header = generic::Header<BlockNumber, BlakeTwo256>; type Lookup = IdentityLookup<AccountId>; type Index = Index; type Hash = Hash; type Hashing = BlakeTwo256; type BlockNumber = BlockNumber; type BlockHashCount = BlockHashCount; type BlockExecutionWeight = BlockExecutionWeight; type ExtrinsicBaseWeight = ExtrinsicBaseWeight; type MaximumBlockLength = MaximumBlockLength; type MaximumBlockWeight = MaximumBlockWeight; type MaximumExtrinsicWeight = MaximumExtrinsicWeight; type AvailableBlockRatio = AvailableBlockRatio; type DbWeight = RocksDbWeight; type PalletInfo = PalletInfo; type Version = Version; type Call = Call; type Event = Event; type Origin = Origin; type OnNewAccount = (); type OnKilledAccount = (); /// type SystemWeightInfo = (); } parameter_types! { pub const EpochDuration: u64 = EPOCH_DURATION_IN_SLOTS; pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK; } /// pallet_babe by skyh 0927 impl pallet_babe::Trait for Runtime { type EpochDuration = EpochDuration; type ExpectedBlockTime = ExpectedBlockTime; type EpochChangeTrigger = pallet_babe::ExternalTrigger; type KeyOwnerProofSystem = Historical; type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, pallet_babe::AuthorityId)>>::Proof; type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, pallet_babe::AuthorityId)>>::IdentificationTuple; type HandleEquivocation = pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, ()>; // Offences type WeightInfo = (); } /// pallet_grandpa by skyh 0927 impl pallet_grandpa::Trait for Runtime { type KeyOwnerProofSystem = Historical; type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof; type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::IdentificationTuple; type HandleEquivocation = pallet_grandpa::EquivocationHandler<Self::KeyOwnerIdentification, ()>; // Offences type WeightInfo = (); type Event = Event; type Call = Call; } parameter_types! { pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17); } /// pallet_session by skyh 0927 impl pallet_session::Trait for Runtime { type Keys = SessionKeys; type ValidatorId = <Self as frame_system::Trait>::AccountId; type ValidatorIdOf = pallet_staking::StashOf<Self>; type ShouldEndSession = Babe; type NextSessionRotation = Babe; type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, Staking>; type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders; type DisabledValidatorsThreshold = DisabledValidatorsThreshold; type WeightInfo = (); type Event = Event; } impl pallet_session::historical::Trait for Runtime { type FullIdentification = pallet_staking::Exposure<AccountId, Balance>; type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>; } /// frame_system::offchain by skyh 0927 impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime where Call: From<C>, { type Extrinsic = UncheckedExtrinsic; type OverarchingCall = Call; } pallet_staking_reward_curve::build! { const REWARD_CURVE: PiecewiseLinear<'static> = curve!( min_inflation: 0_025_000, max_inflation: 0_100_000, ideal_stake: 0_500_000, falloff: 0_050_000, max_piece_count: 40, test_precision: 0_005_000, ); } /// Struct that handles the conversion of Balance -> `u64`. This is used for /// staking's election calculation. pub struct CurrencyToVoteHandler; impl CurrencyToVoteHandler { fn factor() -> Balance { (Balances::total_issuance() / u64::max_value() as Balance).max(1) } } impl Convert<Balance, u64> for CurrencyToVoteHandler { fn
(x: Balance) -> u64 { (x / Self::factor()) as u64 } } impl Convert<u128, Balance> for CurrencyToVoteHandler { fn convert(x: u128) -> Balance { x * Self::factor() } } parameter_types! { pub const SessionsPerEra: sp_staking::SessionIndex = 3; // 3 hours pub const BondingDuration: pallet_staking::EraIndex = 4; // 12 hours pub const SlashDeferDuration: pallet_staking::EraIndex = 2; // 6 hours pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE; pub const MaxNominatorRewardedPerValidator: u32 = 64; pub const ElectionLookahead: BlockNumber = EPOCH_DURATION_IN_BLOCKS / 4; pub const StakingUnsignedPriority: TransactionPriority = TransactionPriority::max_value() / 2; pub const MaxIterations: u32 = 5; // 0.05%. The higher the value, the more strict solution acceptance becomes. pub MinSolutionScoreBump: Perbill = Perbill::from_rational_approximation(5u32, 10_000); } /// pallet_staking::offchain by skyh 0927 impl pallet_staking::Trait for Runtime { type Currency = Balances; type UnixTime = Timestamp; type CurrencyToVote = CurrencyToVoteHandler; type RewardRemainder = Treasury; type RewardCurve = RewardCurve; type Slash = Treasury; // send the slashed funds to the pallet treasury. type Reward = (); // rewards are minted from the void type SessionInterface = Self; type SessionsPerEra = SessionsPerEra; type BondingDuration = BondingDuration; type SlashDeferDuration = SlashDeferDuration; /// A super-majority of the council can cancel the slash. type SlashCancelOrigin = frame_system::EnsureRoot<Self::AccountId>; // TODO type NextNewSession = Session; type ElectionLookahead = ElectionLookahead; type UnsignedPriority = StakingUnsignedPriority; type MaxIterations = MaxIterations; type MinSolutionScoreBump = MinSolutionScoreBump; type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator; type WeightInfo = (); type Event = Event; type Call = Call; } parameter_types! { pub const CouncilMotionDuration: BlockNumber = 3 * DAYS; pub const CouncilMaxProposals: u32 = 100; pub const CouncilMaxMembers: u32 = 100; } type CouncilCollective = pallet_collective::Instance1; pub type MoreThanHalfCouncil = EnsureOneOf< AccountId, EnsureRoot<AccountId>, pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective> >; pub type SlashCancelOrigin = EnsureOneOf< AccountId, EnsureRoot<AccountId>, pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective> >; /// pallet_collective by skyh 1020 impl pallet_collective::Trait<CouncilCollective> for Runtime { type MotionDuration = CouncilMotionDuration; type MaxProposals = CouncilMaxProposals; type MaxMembers = CouncilMaxMembers; type DefaultVote = pallet_collective::PrimeDefaultVote; // type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>; type WeightInfo = (); type Origin = Origin; type Proposal = Call; type Event = Event; } parameter_types! { pub const TechnicalMotionDuration: BlockNumber = 3 * DAYS; pub const TechnicalMaxProposals: u32 = 100; pub const TechnicalMaxMembers: u32 = 100; } type TechnicalCollective = pallet_collective::Instance2; impl pallet_collective::Trait<TechnicalCollective> for Runtime { type Origin = Origin; type Proposal = Call; type Event = Event; type MotionDuration = TechnicalMotionDuration; type MaxProposals = TechnicalMaxProposals; type MaxMembers = TechnicalMaxMembers; type DefaultVote = pallet_collective::PrimeDefaultVote; // type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>; type WeightInfo = (); } parameter_types! { pub const LaunchPeriod: BlockNumber = 7 * DAYS; pub const VotingPeriod: BlockNumber = 7 * DAYS; pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS; pub const MinimumDeposit: Balance = 1 * DOLLARS; pub const EnactmentPeriod: BlockNumber = 8 * DAYS; pub const CooloffPeriod: BlockNumber = 7 * DAYS; // One cent: $10,000 / MB pub const PreimageByteDeposit: Balance = 10 * MILLICENTS; pub const InstantAllowed: bool = true; pub const MaxVotes: u32 = 100; pub const MaxProposals: u32 = 100; } /// pallet_democracy by skyh 1020 impl pallet_democracy::Trait for Runtime { type Proposal = Call; type Event = Event; type Currency = Balances; type EnactmentPeriod = EnactmentPeriod; type LaunchPeriod = LaunchPeriod; type VotingPeriod = VotingPeriod; type CooloffPeriod = CooloffPeriod; type PalletsOrigin = OriginCaller; type VetoOrigin = pallet_collective::EnsureMember<AccountId, TechnicalCollective>; type ExternalOrigin = pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>; type ExternalMajorityOrigin = pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>; type ExternalDefaultOrigin = pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, CouncilCollective>; /// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote /// be tabled immediately and with a shorter voting/enactment period. type FastTrackOrigin = pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>; type InstantOrigin = pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>; type InstantAllowed = InstantAllowed; type FastTrackVotingPeriod = FastTrackVotingPeriod; // To cancel a proposal which has been passed, 2/3 of the council must agree to it. type CancellationOrigin = EnsureOneOf< AccountId, EnsureRoot<AccountId>, pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>, >; // To cancel a proposal before it has been passed, the technical committee must be unanimous or // Root must agree. // type CancelProposalOrigin = EnsureOneOf< // AccountId, // EnsureRoot<AccountId>, // pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>, // >; // type BlacklistOrigin = EnsureRoot<AccountId>; // Any single technical committee member may veto a coming council proposal, however they can // only do it once and it lasts only for the cooloff period. type Slash = Treasury; type Scheduler = Scheduler; type MaxVotes = MaxVotes; type MinimumDeposit = MinimumDeposit; type PreimageByteDeposit = PreimageByteDeposit; type OperationalPreimageOrigin = pallet_collective::EnsureMember<AccountId, CouncilCollective>; type WeightInfo = (); // type MaxProposals = MaxProposals; } parameter_types! { pub const CandidacyBond: Balance = 1 * DOLLARS; pub const VotingBond: Balance = 5 * CENTS; /// Daily council elections. pub const TermDuration: BlockNumber = 24 * HOURS; pub const DesiredMembers: u32 = 19; pub const DesiredRunnersUp: u32 = 19; pub const ElectionsPhragmenModuleId: LockIdentifier = *b"phrelect"; } // Make sure that there are no more than MaxMembers members elected via phragmen. const_assert!(DesiredMembers::get() <= CouncilMaxMembers::get()); /// pallet_elections_phragmen by skyh 1020 impl pallet_elections_phragmen::Trait for Runtime { type Event = Event; type Currency = Balances; type ChangeMembers = Council; type InitializeMembers = Council; type CurrencyToVote = CurrencyToVoteHandler; type CandidacyBond = CandidacyBond; type VotingBond = VotingBond; type LoserCandidate = Treasury; type BadReport = Treasury; type KickedMember = Treasury; type DesiredMembers = DesiredMembers; type DesiredRunnersUp = DesiredRunnersUp; type TermDuration = TermDuration; type ModuleId = ElectionsPhragmenModuleId; // type WeightInfo = weights::pallet_elections_phragmen::WeightInfo<Runtime>; type WeightInfo = (); } /// pallet_membership by skyh 1020 impl pallet_membership::Trait<pallet_membership::Instance1> for Runtime { type Event = Event; type AddOrigin = MoreThanHalfCouncil; type RemoveOrigin = MoreThanHalfCouncil; type SwapOrigin = MoreThanHalfCouncil; type ResetOrigin = MoreThanHalfCouncil; type PrimeOrigin = MoreThanHalfCouncil; type MembershipInitialized = TechnicalCommittee; type MembershipChanged = TechnicalCommittee; } parameter_types! { pub const ProposalBond: Permill = Permill::from_percent(5); pub const ProposalBondMinimum: Balance = 20 * DOLLARS; pub const SpendPeriod: BlockNumber = 6 * DAYS; pub const Burn: Permill = Permill::from_perthousand(2); pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry"); pub const TipCountdown: BlockNumber = 1 * DAYS; pub const TipFindersFee: Percent = Percent::from_percent(20); pub const TipReportDepositBase: Balance = 1 * DOLLARS; pub const DataDepositPerByte: Balance = 1 * CENTS; pub const BountyDepositBase: Balance = 1 * DOLLARS; pub const BountyDepositPayoutDelay: BlockNumber = 4 * DAYS; pub const BountyUpdatePeriod: BlockNumber = 90 * DAYS; pub const MaximumReasonLength: u32 = 16384; pub const BountyCuratorDeposit: Permill = Permill::from_percent(50); pub const BountyValueMinimum: Balance = 2 * DOLLARS; } type ApproveOrigin = EnsureOneOf< AccountId, EnsureRoot<AccountId>, pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective> >; /// pallet_treasury by skyh 1020 impl pallet_treasury::Trait for Runtime { type ModuleId = TreasuryModuleId; type Currency = Balances; type ApproveOrigin = ApproveOrigin; type RejectOrigin = MoreThanHalfCouncil; type DataDepositPerByte = DataDepositPerByte; type Tippers = ElectionsPhragmen; type TipCountdown = TipCountdown; type TipFindersFee = TipFindersFee; type TipReportDepositBase = TipReportDepositBase; type BountyDepositBase = BountyDepositBase; type BountyDepositPayoutDelay = BountyDepositPayoutDelay; type BountyUpdatePeriod = BountyUpdatePeriod; type MaximumReasonLength = MaximumReasonLength; type BountyCuratorDeposit = BountyCuratorDeposit; type BountyValueMinimum = BountyValueMinimum; // type BurnDestination = Society; type ProposalBond = ProposalBond; type ProposalBondMinimum = ProposalBondMinimum; type SpendPeriod = SpendPeriod; type OnSlash = Treasury; type Burn = Burn; type BurnDestination = (); // type WeightInfo = weights::pallet_treasury::WeightInfo<Runtime>; type WeightInfo = (); type Event = Event; } parameter_types! { pub const MaxScheduledPerBlock: u32 = 50; } /// pallet_scheduler by skyh 1020 impl pallet_scheduler::Trait for Runtime { type PalletsOrigin = OriginCaller; type MaximumWeight = MaximumBlockWeight; type ScheduleOrigin = EnsureRoot<AccountId>; type MaxScheduledPerBlock = MaxScheduledPerBlock; type WeightInfo = (); type Origin = Origin; type Event = Event; type Call = Call; } parameter_types! { pub const SessionDuration: BlockNumber = EPOCH_DURATION_IN_BLOCKS as _; pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value(); } impl pallet_im_online::Trait for Runtime { type AuthorityId = ImOnlineId; type SessionDuration = SessionDuration; type ReportUnresponsiveness = Offences; type UnsignedPriority = ImOnlineUnsignedPriority; type WeightInfo = (); type Event = Event; } parameter_types! { pub const IndexDeposit: Balance = DOLLARS; } /// pallet_indices by skyh 1020 impl pallet_indices::Trait for Runtime { type AccountIndex = AccountIndex; type Deposit = IndexDeposit; type Currency = Balances; type WeightInfo = (); type Event = Event; } parameter_types! { pub OffencesWeightSoftLimit: Weight = Perbill::from_percent(60) * MaximumBlockWeight::get(); } /// pallet_offences by skyh 1020 impl pallet_offences::Trait for Runtime { type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>; type WeightSoftLimit = OffencesWeightSoftLimit; type OnOffenceHandler = Staking; type Event = Event; } impl pallet_utility::Trait for Runtime { type WeightInfo = (); type Event = Event; type Call = Call; } parameter_types! { pub const MinVestedTransfer: Balance = 100 * DOLLARS; } /// pallet_vesting by skyh 1020 impl pallet_vesting::Trait for Runtime { type Event = Event; type Currency = Balances; type BlockNumberToBalance = ConvertInto; type MinVestedTransfer = MinVestedTransfer; type WeightInfo = (); } impl pallet_authority_discovery::Trait for Runtime {} parameter_types! { pub const UncleGenerations: BlockNumber = 5; } /// pallet_authorship origin impl pallet_authorship::Trait for Runtime { type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>; type UncleGenerations = UncleGenerations; type FilterUncle = (); type EventHandler = (Staking, ()); // ImOnline } parameter_types! { pub const MinimumPeriod: u64 = SLOT_DURATION / 2; } /// pallet_timestamp origin impl pallet_timestamp::Trait for Runtime { /// A timestamp: milliseconds since the unix epoch. type Moment = Moment; type OnTimestampSet = Babe; type MinimumPeriod = MinimumPeriod; type WeightInfo = (); } parameter_types! { pub const ExistentialDeposit: u128 = 500; // 0 pub const MaxLocks: u32 = 50; } /// pallet_balances origin impl pallet_balances::Trait for Runtime { type Balance = Balance; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type MaxLocks = MaxLocks; type AccountStore = System; // type Event = Event; type WeightInfo = (); } parameter_types! { pub const TransactionByteFee: Balance = 1; } /// pallet_transaction_payment origin impl pallet_transaction_payment::Trait for Runtime { type Currency = Balances; type TransactionByteFee = TransactionByteFee; type WeightToFee = IdentityFee<Balance>; type OnTransactionPayment = (); // treasury type FeeMultiplierUpdate = (); // } impl pallet_sudo::Trait for Runtime { type Event = Event; type Call = Call; } /// Configure the template pallet in pallets/template. impl pallet_template::Trait for Runtime { type Event = Event; } // TODO // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( pub enum Runtime where Block = Block, NodeBlock = opaque::Block, UncheckedExtrinsic = UncheckedExtrinsic { System: frame_system::{Module, Call, Config, Storage, Event<T>}, RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage}, Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent}, Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>}, TransactionPayment: pallet_transaction_payment::{Module, Storage}, Sudo: pallet_sudo::{Module, Call, Config<T>, Storage, Event<T>}, Authorship: pallet_authorship::{Module, Call, Storage, Inherent}, Babe: pallet_babe::{Module, Call, Storage, Config, Inherent}, Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event}, Staking: pallet_staking::{Module, Call, Config<T>, Storage, Event<T>}, Session: pallet_session::{Module, Call, Storage, Event, Config<T>}, AuthorityDiscovery: pallet_authority_discovery::{Module, Call, Config}, Council: pallet_collective::<Instance1>::{Module, Call, Storage, Origin<T>, Event<T>, Config<T>}, TechnicalCommittee: pallet_collective::<Instance2>::{Module, Call, Storage, Origin<T>, Event<T>, Config<T>}, Democracy: pallet_democracy::{Module, Call, Storage, Config, Event<T>}, ElectionsPhragmen: pallet_elections_phragmen::{Module, Call, Storage, Event<T>, Config<T>}, TechnicalMembership: pallet_membership::<Instance1>::{Module, Call, Storage, Event<T>, Config<T>}, ImOnline: pallet_im_online::{Module, Call, Storage, Event<T>, ValidateUnsigned, Config<T>}, Indices: pallet_indices::{Module, Call, Storage, Config<T>, Event<T>}, Scheduler: pallet_scheduler::{Module, Call, Storage, Event<T>}, Treasury: pallet_treasury::{Module, Call, Storage, Event<T>}, Offences: pallet_offences::{Module, Call, Storage, Event}, Historical: pallet_session_historical::{Module}, Vesting: pallet_vesting::{Module, Call, Storage, Event<T>, Config<T>}, Utility: pallet_utility::{Module, Call, Event}, // Include the custom logic from the template pallet in the runtime. TemplateModule: pallet_template::{Module, Call, Storage, Event<T>}, } ); /// The address format for describing accounts. pub type Address = AccountId; /// Block header type as expected by this runtime. pub type Header = generic::Header<BlockNumber, BlakeTwo256>; /// Block type as expected by this runtime. pub type Block = generic::Block<Header, UncheckedExtrinsic>; /// A Block signed with a Justification pub type SignedBlock = generic::SignedBlock<Block>; /// BlockId type as expected by this runtime. pub type BlockId = generic::BlockId<Block>; /// The SignedExtension to the basic transaction logic. pub type SignedExtra = ( frame_system::CheckSpecVersion<Runtime>, frame_system::CheckTxVersion<Runtime>, frame_system::CheckGenesis<Runtime>, frame_system::CheckEra<Runtime>, frame_system::CheckNonce<Runtime>, frame_system::CheckWeight<Runtime>, pallet_transaction_payment::ChargeTransactionPayment<Runtime> ); /// Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>; /// Extrinsic type that has already been checked. pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>; /// Executive: handles dispatch to the various modules. pub type Executive = frame_executive::Executive< Runtime, Block, frame_system::ChainContext<Runtime>, Runtime, AllModules, >; impl_runtime_apis! { impl sp_api::Core<Block> for Runtime { fn version() -> RuntimeVersion { VERSION } fn execute_block(block: Block) { Executive::execute_block(block) } fn initialize_block(header: &<Block as BlockT>::Header) { Executive::initialize_block(header) } } impl sp_api::Metadata<Block> for Runtime { fn metadata() -> OpaqueMetadata { Runtime::metadata().into() } } impl sp_block_builder::BlockBuilder<Block> for Runtime { fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult { Executive::apply_extrinsic(extrinsic) } fn finalize_block() -> <Block as BlockT>::Header { Executive::finalize_block() } fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> { data.create_extrinsics() } fn check_inherents( block: Block, data: sp_inherents::InherentData, ) -> sp_inherents::CheckInherentsResult { data.check_extrinsics(&block) } fn random_seed() -> <Block as BlockT>::Hash { RandomnessCollectiveFlip::random_seed() } } impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime { fn validate_transaction( source: TransactionSource, tx: <Block as BlockT>::Extrinsic, ) -> TransactionValidity { Executive::validate_transaction(source, tx) } } impl sp_offchain::OffchainWorkerApi<Block> for Runtime { fn offchain_worker(header: &<Block as BlockT>::Header) { Executive::offchain_worker(header) } } // TODO ### sp_consensus_babe by Skyh, 0927 ### /// configuration /// current_epoch_start /// generate_key_ownership_proof /// submit_report_equivocation_unsigned_extrinsic impl sp_consensus_babe::BabeApi<Block> for Runtime { fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration { // The choice of `c` parameter (where `1 - c` represents the // probability of a slot being empty), is done in accordance to the // slot duration and expected target block time, for safely // resisting network delays of maximum two seconds. // <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results> sp_consensus_babe::BabeGenesisConfiguration { slot_duration: Babe::slot_duration(), epoch_length: EpochDuration::get(), c: PRIMARY_PROBABILITY, genesis_authorities: Babe::authorities(), randomness: Babe::randomness(), allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryPlainSlots, } } fn current_epoch_start() -> sp_consensus_babe::SlotNumber { Babe::current_epoch_start() } fn generate_key_ownership_proof( _slot_number: sp_consensus_babe::SlotNumber, authority_id: sp_consensus_babe::AuthorityId, ) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> { use codec::Encode; Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id)) .map(|p| p.encode()) .map(sp_consensus_babe::OpaqueKeyOwnershipProof::new) } fn submit_report_equivocation_unsigned_extrinsic( equivocation_proof: sp_consensus_babe::EquivocationProof<<Block as BlockT>::Header>, key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof, ) -> Option<()> { let key_owner_proof = key_owner_proof.decode()?; Babe::submit_unsigned_equivocation_report( equivocation_proof, key_owner_proof, ) } } impl sp_session::SessionKeys<Block> for Runtime { fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> { SessionKeys::generate(seed) } fn decode_session_keys( encoded: Vec<u8>, ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> { SessionKeys::decode_into_raw_public_keys(&encoded) } } impl fg_primitives::GrandpaApi<Block> for Runtime { fn grandpa_authorities() -> GrandpaAuthorityList { Grandpa::grandpa_authorities() }
convert
identifier_name
lib.rs
::{KeyOwnerProofSystem, Randomness, LockIdentifier, Filter}, weights::{ Weight, IdentityFee, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND}, }, }; // A few exports that help ease life for downstream crates. #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; pub use sp_runtime::{Permill, Perbill}; pub use pallet_timestamp::Call as TimestampCall; pub use pallet_balances::Call as BalancesCall; pub use pallet_staking::StakerStatus; /// Import the template pallet. pub use pallet_template; pub mod common; pub use common::*; pub use common::opaque; pub mod constants; pub use constants::{time::*, currency::*, fee::*}; pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("bandot"), impl_name: create_runtime_str!("bandot"), authoring_version: 1, spec_version: 1, impl_version: 1, apis: RUNTIME_API_VERSIONS, transaction_version: 1, }; /// The version information used to identify this runtime when compiled natively. #[cfg(feature = "std")] pub fn native_version() -> NativeVersion { NativeVersion { runtime_version: VERSION, can_author_with: Default::default(), } } impl_opaque_keys! { pub struct SessionKeys { pub babe: Babe, pub grandpa: Grandpa, pub im_online: ImOnline, pub authority_discovery: AuthorityDiscovery, //pub parachain_validator: ParachainSessionKeyPlaceholder<Runtime>, } } /// Avoid processing transactions from slots and parachain registrar. pub struct BaseFilter; impl Filter<Call> for BaseFilter { fn filter(_: &Call) -> bool { true } } parameter_types! { pub const BlockHashCount: BlockNumber = 2400; /// We allow for 2 seconds of compute with a 6 second average block time. pub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND; pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); /// Assume 10% of weight for average on_initialize calls. pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get() .saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get(); pub const MaximumBlockLength: u32 = 5 * 1024 * 1024; pub const Version: RuntimeVersion = VERSION; } /// frame_system by skyh 0927 impl frame_system::Trait for Runtime { type BaseCallFilter = BaseFilter; /// filter 0927 type AccountId = AccountId; type AccountData = pallet_balances::AccountData<Balance>; type Header = generic::Header<BlockNumber, BlakeTwo256>; type Lookup = IdentityLookup<AccountId>; type Index = Index; type Hash = Hash; type Hashing = BlakeTwo256; type BlockNumber = BlockNumber; type BlockHashCount = BlockHashCount; type BlockExecutionWeight = BlockExecutionWeight; type ExtrinsicBaseWeight = ExtrinsicBaseWeight; type MaximumBlockLength = MaximumBlockLength; type MaximumBlockWeight = MaximumBlockWeight; type MaximumExtrinsicWeight = MaximumExtrinsicWeight; type AvailableBlockRatio = AvailableBlockRatio; type DbWeight = RocksDbWeight; type PalletInfo = PalletInfo; type Version = Version; type Call = Call; type Event = Event; type Origin = Origin; type OnNewAccount = (); type OnKilledAccount = (); /// type SystemWeightInfo = (); } parameter_types! { pub const EpochDuration: u64 = EPOCH_DURATION_IN_SLOTS; pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK; } /// pallet_babe by skyh 0927 impl pallet_babe::Trait for Runtime { type EpochDuration = EpochDuration; type ExpectedBlockTime = ExpectedBlockTime; type EpochChangeTrigger = pallet_babe::ExternalTrigger; type KeyOwnerProofSystem = Historical; type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, pallet_babe::AuthorityId)>>::Proof; type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, pallet_babe::AuthorityId)>>::IdentificationTuple; type HandleEquivocation = pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, ()>; // Offences type WeightInfo = (); } /// pallet_grandpa by skyh 0927 impl pallet_grandpa::Trait for Runtime { type KeyOwnerProofSystem = Historical; type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof; type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::IdentificationTuple; type HandleEquivocation = pallet_grandpa::EquivocationHandler<Self::KeyOwnerIdentification, ()>; // Offences type WeightInfo = (); type Event = Event; type Call = Call; } parameter_types! { pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17); } /// pallet_session by skyh 0927 impl pallet_session::Trait for Runtime { type Keys = SessionKeys; type ValidatorId = <Self as frame_system::Trait>::AccountId; type ValidatorIdOf = pallet_staking::StashOf<Self>; type ShouldEndSession = Babe; type NextSessionRotation = Babe; type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, Staking>; type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders; type DisabledValidatorsThreshold = DisabledValidatorsThreshold; type WeightInfo = (); type Event = Event; } impl pallet_session::historical::Trait for Runtime { type FullIdentification = pallet_staking::Exposure<AccountId, Balance>; type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>; } /// frame_system::offchain by skyh 0927 impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime where Call: From<C>, { type Extrinsic = UncheckedExtrinsic; type OverarchingCall = Call; } pallet_staking_reward_curve::build! { const REWARD_CURVE: PiecewiseLinear<'static> = curve!( min_inflation: 0_025_000, max_inflation: 0_100_000, ideal_stake: 0_500_000, falloff: 0_050_000, max_piece_count: 40, test_precision: 0_005_000, ); } /// Struct that handles the conversion of Balance -> `u64`. This is used for /// staking's election calculation. pub struct CurrencyToVoteHandler; impl CurrencyToVoteHandler { fn factor() -> Balance { (Balances::total_issuance() / u64::max_value() as Balance).max(1) } } impl Convert<Balance, u64> for CurrencyToVoteHandler { fn convert(x: Balance) -> u64 { (x / Self::factor()) as u64 } } impl Convert<u128, Balance> for CurrencyToVoteHandler { fn convert(x: u128) -> Balance { x * Self::factor() } } parameter_types! { pub const SessionsPerEra: sp_staking::SessionIndex = 3; // 3 hours pub const BondingDuration: pallet_staking::EraIndex = 4; // 12 hours pub const SlashDeferDuration: pallet_staking::EraIndex = 2; // 6 hours pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE; pub const MaxNominatorRewardedPerValidator: u32 = 64; pub const ElectionLookahead: BlockNumber = EPOCH_DURATION_IN_BLOCKS / 4; pub const StakingUnsignedPriority: TransactionPriority = TransactionPriority::max_value() / 2; pub const MaxIterations: u32 = 5; // 0.05%. The higher the value, the more strict solution acceptance becomes. pub MinSolutionScoreBump: Perbill = Perbill::from_rational_approximation(5u32, 10_000); } /// pallet_staking::offchain by skyh 0927 impl pallet_staking::Trait for Runtime { type Currency = Balances; type UnixTime = Timestamp; type CurrencyToVote = CurrencyToVoteHandler; type RewardRemainder = Treasury; type RewardCurve = RewardCurve; type Slash = Treasury; // send the slashed funds to the pallet treasury. type Reward = (); // rewards are minted from the void type SessionInterface = Self; type SessionsPerEra = SessionsPerEra; type BondingDuration = BondingDuration; type SlashDeferDuration = SlashDeferDuration; /// A super-majority of the council can cancel the slash. type SlashCancelOrigin = frame_system::EnsureRoot<Self::AccountId>; // TODO type NextNewSession = Session; type ElectionLookahead = ElectionLookahead; type UnsignedPriority = StakingUnsignedPriority; type MaxIterations = MaxIterations; type MinSolutionScoreBump = MinSolutionScoreBump; type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator; type WeightInfo = (); type Event = Event; type Call = Call; } parameter_types! { pub const CouncilMotionDuration: BlockNumber = 3 * DAYS; pub const CouncilMaxProposals: u32 = 100; pub const CouncilMaxMembers: u32 = 100; } type CouncilCollective = pallet_collective::Instance1; pub type MoreThanHalfCouncil = EnsureOneOf< AccountId, EnsureRoot<AccountId>, pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective> >; pub type SlashCancelOrigin = EnsureOneOf< AccountId, EnsureRoot<AccountId>, pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective> >; /// pallet_collective by skyh 1020 impl pallet_collective::Trait<CouncilCollective> for Runtime { type MotionDuration = CouncilMotionDuration; type MaxProposals = CouncilMaxProposals; type MaxMembers = CouncilMaxMembers; type DefaultVote = pallet_collective::PrimeDefaultVote; // type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>; type WeightInfo = (); type Origin = Origin; type Proposal = Call; type Event = Event; } parameter_types! { pub const TechnicalMotionDuration: BlockNumber = 3 * DAYS; pub const TechnicalMaxProposals: u32 = 100; pub const TechnicalMaxMembers: u32 = 100; } type TechnicalCollective = pallet_collective::Instance2; impl pallet_collective::Trait<TechnicalCollective> for Runtime { type Origin = Origin; type Proposal = Call; type Event = Event; type MotionDuration = TechnicalMotionDuration; type MaxProposals = TechnicalMaxProposals; type MaxMembers = TechnicalMaxMembers; type DefaultVote = pallet_collective::PrimeDefaultVote; // type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>; type WeightInfo = (); } parameter_types! { pub const LaunchPeriod: BlockNumber = 7 * DAYS; pub const VotingPeriod: BlockNumber = 7 * DAYS; pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS; pub const MinimumDeposit: Balance = 1 * DOLLARS; pub const EnactmentPeriod: BlockNumber = 8 * DAYS; pub const CooloffPeriod: BlockNumber = 7 * DAYS; // One cent: $10,000 / MB pub const PreimageByteDeposit: Balance = 10 * MILLICENTS; pub const InstantAllowed: bool = true; pub const MaxVotes: u32 = 100; pub const MaxProposals: u32 = 100; } /// pallet_democracy by skyh 1020 impl pallet_democracy::Trait for Runtime { type Proposal = Call; type Event = Event; type Currency = Balances; type EnactmentPeriod = EnactmentPeriod; type LaunchPeriod = LaunchPeriod; type VotingPeriod = VotingPeriod; type CooloffPeriod = CooloffPeriod; type PalletsOrigin = OriginCaller; type VetoOrigin = pallet_collective::EnsureMember<AccountId, TechnicalCollective>; type ExternalOrigin = pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>; type ExternalMajorityOrigin = pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>; type ExternalDefaultOrigin = pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, CouncilCollective>; /// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote /// be tabled immediately and with a shorter voting/enactment period. type FastTrackOrigin = pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>; type InstantOrigin = pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>; type InstantAllowed = InstantAllowed; type FastTrackVotingPeriod = FastTrackVotingPeriod; // To cancel a proposal which has been passed, 2/3 of the council must agree to it. type CancellationOrigin = EnsureOneOf< AccountId, EnsureRoot<AccountId>, pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>, >; // To cancel a proposal before it has been passed, the technical committee must be unanimous or // Root must agree. // type CancelProposalOrigin = EnsureOneOf< // AccountId, // EnsureRoot<AccountId>, // pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>, // >; // type BlacklistOrigin = EnsureRoot<AccountId>; // Any single technical committee member may veto a coming council proposal, however they can // only do it once and it lasts only for the cooloff period. type Slash = Treasury; type Scheduler = Scheduler; type MaxVotes = MaxVotes; type MinimumDeposit = MinimumDeposit; type PreimageByteDeposit = PreimageByteDeposit; type OperationalPreimageOrigin = pallet_collective::EnsureMember<AccountId, CouncilCollective>; type WeightInfo = (); // type MaxProposals = MaxProposals; } parameter_types! { pub const CandidacyBond: Balance = 1 * DOLLARS; pub const VotingBond: Balance = 5 * CENTS; /// Daily council elections. pub const TermDuration: BlockNumber = 24 * HOURS; pub const DesiredMembers: u32 = 19; pub const DesiredRunnersUp: u32 = 19; pub const ElectionsPhragmenModuleId: LockIdentifier = *b"phrelect"; } // Make sure that there are no more than MaxMembers members elected via phragmen. const_assert!(DesiredMembers::get() <= CouncilMaxMembers::get()); /// pallet_elections_phragmen by skyh 1020 impl pallet_elections_phragmen::Trait for Runtime { type Event = Event; type Currency = Balances; type ChangeMembers = Council; type InitializeMembers = Council; type CurrencyToVote = CurrencyToVoteHandler; type CandidacyBond = CandidacyBond; type VotingBond = VotingBond; type LoserCandidate = Treasury; type BadReport = Treasury; type KickedMember = Treasury; type DesiredMembers = DesiredMembers; type DesiredRunnersUp = DesiredRunnersUp; type TermDuration = TermDuration; type ModuleId = ElectionsPhragmenModuleId; // type WeightInfo = weights::pallet_elections_phragmen::WeightInfo<Runtime>; type WeightInfo = (); } /// pallet_membership by skyh 1020 impl pallet_membership::Trait<pallet_membership::Instance1> for Runtime { type Event = Event; type AddOrigin = MoreThanHalfCouncil; type RemoveOrigin = MoreThanHalfCouncil; type SwapOrigin = MoreThanHalfCouncil; type ResetOrigin = MoreThanHalfCouncil; type PrimeOrigin = MoreThanHalfCouncil; type MembershipInitialized = TechnicalCommittee; type MembershipChanged = TechnicalCommittee; } parameter_types! { pub const ProposalBond: Permill = Permill::from_percent(5); pub const ProposalBondMinimum: Balance = 20 * DOLLARS; pub const SpendPeriod: BlockNumber = 6 * DAYS; pub const Burn: Permill = Permill::from_perthousand(2); pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry"); pub const TipCountdown: BlockNumber = 1 * DAYS; pub const TipFindersFee: Percent = Percent::from_percent(20); pub const TipReportDepositBase: Balance = 1 * DOLLARS; pub const DataDepositPerByte: Balance = 1 * CENTS; pub const BountyDepositBase: Balance = 1 * DOLLARS; pub const BountyDepositPayoutDelay: BlockNumber = 4 * DAYS; pub const BountyUpdatePeriod: BlockNumber = 90 * DAYS; pub const MaximumReasonLength: u32 = 16384; pub const BountyCuratorDeposit: Permill = Permill::from_percent(50); pub const BountyValueMinimum: Balance = 2 * DOLLARS; } type ApproveOrigin = EnsureOneOf< AccountId, EnsureRoot<AccountId>, pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective> >; /// pallet_treasury by skyh 1020 impl pallet_treasury::Trait for Runtime { type ModuleId = TreasuryModuleId; type Currency = Balances; type ApproveOrigin = ApproveOrigin; type RejectOrigin = MoreThanHalfCouncil; type DataDepositPerByte = DataDepositPerByte; type Tippers = ElectionsPhragmen; type TipCountdown = TipCountdown; type TipFindersFee = TipFindersFee; type TipReportDepositBase = TipReportDepositBase; type BountyDepositBase = BountyDepositBase; type BountyDepositPayoutDelay = BountyDepositPayoutDelay; type BountyUpdatePeriod = BountyUpdatePeriod; type MaximumReasonLength = MaximumReasonLength; type BountyCuratorDeposit = BountyCuratorDeposit; type BountyValueMinimum = BountyValueMinimum; // type BurnDestination = Society; type ProposalBond = ProposalBond; type ProposalBondMinimum = ProposalBondMinimum; type SpendPeriod = SpendPeriod; type OnSlash = Treasury; type Burn = Burn; type BurnDestination = (); // type WeightInfo = weights::pallet_treasury::WeightInfo<Runtime>; type WeightInfo = (); type Event = Event; } parameter_types! { pub const MaxScheduledPerBlock: u32 = 50; } /// pallet_scheduler by skyh 1020 impl pallet_scheduler::Trait for Runtime { type PalletsOrigin = OriginCaller; type MaximumWeight = MaximumBlockWeight; type ScheduleOrigin = EnsureRoot<AccountId>; type MaxScheduledPerBlock = MaxScheduledPerBlock; type WeightInfo = (); type Origin = Origin; type Event = Event; type Call = Call; } parameter_types! { pub const SessionDuration: BlockNumber = EPOCH_DURATION_IN_BLOCKS as _; pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value(); } impl pallet_im_online::Trait for Runtime { type AuthorityId = ImOnlineId; type SessionDuration = SessionDuration; type ReportUnresponsiveness = Offences; type UnsignedPriority = ImOnlineUnsignedPriority; type WeightInfo = (); type Event = Event; } parameter_types! { pub const IndexDeposit: Balance = DOLLARS; } /// pallet_indices by skyh 1020 impl pallet_indices::Trait for Runtime { type AccountIndex = AccountIndex; type Deposit = IndexDeposit; type Currency = Balances; type WeightInfo = (); type Event = Event; } parameter_types! { pub OffencesWeightSoftLimit: Weight = Perbill::from_percent(60) * MaximumBlockWeight::get(); } /// pallet_offences by skyh 1020 impl pallet_offences::Trait for Runtime { type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>; type WeightSoftLimit = OffencesWeightSoftLimit; type OnOffenceHandler = Staking; type Event = Event; } impl pallet_utility::Trait for Runtime { type WeightInfo = (); type Event = Event; type Call = Call; } parameter_types! { pub const MinVestedTransfer: Balance = 100 * DOLLARS; } /// pallet_vesting by skyh 1020 impl pallet_vesting::Trait for Runtime { type Event = Event; type Currency = Balances; type BlockNumberToBalance = ConvertInto; type MinVestedTransfer = MinVestedTransfer; type WeightInfo = (); } impl pallet_authority_discovery::Trait for Runtime {} parameter_types! { pub const UncleGenerations: BlockNumber = 5; } /// pallet_authorship origin impl pallet_authorship::Trait for Runtime { type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>; type UncleGenerations = UncleGenerations; type FilterUncle = (); type EventHandler = (Staking, ()); // ImOnline } parameter_types! { pub const MinimumPeriod: u64 = SLOT_DURATION / 2; } /// pallet_timestamp origin impl pallet_timestamp::Trait for Runtime { /// A timestamp: milliseconds since the unix epoch. type Moment = Moment; type OnTimestampSet = Babe; type MinimumPeriod = MinimumPeriod; type WeightInfo = (); } parameter_types! { pub const ExistentialDeposit: u128 = 500; // 0 pub const MaxLocks: u32 = 50; } /// pallet_balances origin impl pallet_balances::Trait for Runtime { type Balance = Balance; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type MaxLocks = MaxLocks;
type WeightInfo = (); } parameter_types! { pub const TransactionByteFee: Balance = 1; } /// pallet_transaction_payment origin impl pallet_transaction_payment::Trait for Runtime { type Currency = Balances; type TransactionByteFee = TransactionByteFee; type WeightToFee = IdentityFee<Balance>; type OnTransactionPayment = (); // treasury type FeeMultiplierUpdate = (); // } impl pallet_sudo::Trait for Runtime { type Event = Event; type Call = Call; } /// Configure the template pallet in pallets/template. impl pallet_template::Trait for Runtime { type Event = Event; } // TODO // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( pub enum Runtime where Block = Block, NodeBlock = opaque::Block, UncheckedExtrinsic = UncheckedExtrinsic { System: frame_system::{Module, Call, Config, Storage, Event<T>}, RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage}, Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent}, Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>}, TransactionPayment: pallet_transaction_payment::{Module, Storage}, Sudo: pallet_sudo::{Module, Call, Config<T>, Storage, Event<T>}, Authorship: pallet_authorship::{Module, Call, Storage, Inherent}, Babe: pallet_babe::{Module, Call, Storage, Config, Inherent}, Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event}, Staking: pallet_staking::{Module, Call, Config<T>, Storage, Event<T>}, Session: pallet_session::{Module, Call, Storage, Event, Config<T>}, AuthorityDiscovery: pallet_authority_discovery::{Module, Call, Config}, Council: pallet_collective::<Instance1>::{Module, Call, Storage, Origin<T>, Event<T>, Config<T>}, TechnicalCommittee: pallet_collective::<Instance2>::{Module, Call, Storage, Origin<T>, Event<T>, Config<T>}, Democracy: pallet_democracy::{Module, Call, Storage, Config, Event<T>}, ElectionsPhragmen: pallet_elections_phragmen::{Module, Call, Storage, Event<T>, Config<T>}, TechnicalMembership: pallet_membership::<Instance1>::{Module, Call, Storage, Event<T>, Config<T>}, ImOnline: pallet_im_online::{Module, Call, Storage, Event<T>, ValidateUnsigned, Config<T>}, Indices: pallet_indices::{Module, Call, Storage, Config<T>, Event<T>}, Scheduler: pallet_scheduler::{Module, Call, Storage, Event<T>}, Treasury: pallet_treasury::{Module, Call, Storage, Event<T>}, Offences: pallet_offences::{Module, Call, Storage, Event}, Historical: pallet_session_historical::{Module}, Vesting: pallet_vesting::{Module, Call, Storage, Event<T>, Config<T>}, Utility: pallet_utility::{Module, Call, Event}, // Include the custom logic from the template pallet in the runtime. TemplateModule: pallet_template::{Module, Call, Storage, Event<T>}, } ); /// The address format for describing accounts. pub type Address = AccountId; /// Block header type as expected by this runtime. pub type Header = generic::Header<BlockNumber, BlakeTwo256>; /// Block type as expected by this runtime. pub type Block = generic::Block<Header, UncheckedExtrinsic>; /// A Block signed with a Justification pub type SignedBlock = generic::SignedBlock<Block>; /// BlockId type as expected by this runtime. pub type BlockId = generic::BlockId<Block>; /// The SignedExtension to the basic transaction logic. pub type SignedExtra = ( frame_system::CheckSpecVersion<Runtime>, frame_system::CheckTxVersion<Runtime>, frame_system::CheckGenesis<Runtime>, frame_system::CheckEra<Runtime>, frame_system::CheckNonce<Runtime>, frame_system::CheckWeight<Runtime>, pallet_transaction_payment::ChargeTransactionPayment<Runtime> ); /// Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>; /// Extrinsic type that has already been checked. pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>; /// Executive: handles dispatch to the various modules. pub type Executive = frame_executive::Executive< Runtime, Block, frame_system::ChainContext<Runtime>, Runtime, AllModules, >; impl_runtime_apis! { impl sp_api::Core<Block> for Runtime { fn version() -> RuntimeVersion { VERSION } fn execute_block(block: Block) { Executive::execute_block(block) } fn initialize_block(header: &<Block as BlockT>::Header) { Executive::initialize_block(header) } } impl sp_api::Metadata<Block> for Runtime { fn metadata() -> OpaqueMetadata { Runtime::metadata().into() } } impl sp_block_builder::BlockBuilder<Block> for Runtime { fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult { Executive::apply_extrinsic(extrinsic) } fn finalize_block() -> <Block as BlockT>::Header { Executive::finalize_block() } fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> { data.create_extrinsics() } fn check_inherents( block: Block, data: sp_inherents::InherentData, ) -> sp_inherents::CheckInherentsResult { data.check_extrinsics(&block) } fn random_seed() -> <Block as BlockT>::Hash { RandomnessCollectiveFlip::random_seed() } } impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime { fn validate_transaction( source: TransactionSource, tx: <Block as BlockT>::Extrinsic, ) -> TransactionValidity { Executive::validate_transaction(source, tx) } } impl sp_offchain::OffchainWorkerApi<Block> for Runtime { fn offchain_worker(header: &<Block as BlockT>::Header) { Executive::offchain_worker(header) } } // TODO ### sp_consensus_babe by Skyh, 0927 ### /// configuration /// current_epoch_start /// generate_key_ownership_proof /// submit_report_equivocation_unsigned_extrinsic impl sp_consensus_babe::BabeApi<Block> for Runtime { fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration { // The choice of `c` parameter (where `1 - c` represents the // probability of a slot being empty), is done in accordance to the // slot duration and expected target block time, for safely // resisting network delays of maximum two seconds. // <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results> sp_consensus_babe::BabeGenesisConfiguration { slot_duration: Babe::slot_duration(), epoch_length: EpochDuration::get(), c: PRIMARY_PROBABILITY, genesis_authorities: Babe::authorities(), randomness: Babe::randomness(), allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryPlainSlots, } } fn current_epoch_start() -> sp_consensus_babe::SlotNumber { Babe::current_epoch_start() } fn generate_key_ownership_proof( _slot_number: sp_consensus_babe::SlotNumber, authority_id: sp_consensus_babe::AuthorityId, ) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> { use codec::Encode; Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id)) .map(|p| p.encode()) .map(sp_consensus_babe::OpaqueKeyOwnershipProof::new) } fn submit_report_equivocation_unsigned_extrinsic( equivocation_proof: sp_consensus_babe::EquivocationProof<<Block as BlockT>::Header>, key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof, ) -> Option<()> { let key_owner_proof = key_owner_proof.decode()?; Babe::submit_unsigned_equivocation_report( equivocation_proof, key_owner_proof, ) } } impl sp_session::SessionKeys<Block> for Runtime { fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> { SessionKeys::generate(seed) } fn decode_session_keys( encoded: Vec<u8>, ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> { SessionKeys::decode_into_raw_public_keys(&encoded) } } impl fg_primitives::GrandpaApi<Block> for Runtime { fn grandpa_authorities() -> GrandpaAuthorityList { Grandpa::grandpa_authorities() }
type AccountStore = System; // type Event = Event;
random_line_split
event.rs
use crate::mappings::Mappings; use crate::scheduler::TaskMessage; use crate::system::{SystemCtx, SystemDataOutput, SYSTEM_ID_MAPPINGS}; use crate::{resource_id_for_component, MacroData, ResourceId, Resources, SystemData, SystemId}; use hashbrown::HashSet; use lazy_static::lazy_static; use legion::storage::ComponentTypeId; use legion::world::World; use parking_lot::Mutex; use std::alloc::Layout; use std::any::TypeId; use std::ptr; /// ID of an event type, allocated consecutively. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)] pub struct EventId(pub usize); impl From<usize> for EventId { fn from(x: usize) -> Self { Self(x) } } lazy_static! { pub static ref EVENT_ID_MAPPINGS: Mutex<Mappings<TypeId, EventId>> = Mutex::new(Mappings::new()); } /// Returns the event ID for the given type. pub fn event_id_for<E>() -> EventId where E: Event, { EVENT_ID_MAPPINGS.lock().get_or_alloc(TypeId::of::<E>()) } /// Marker trait for types which can be triggered as events. pub trait Event: Send + Sync +'static {} impl<T> Event for T where T: Send + Sync +'static {} /// Strategy used to handle an event. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum HandleStrategy { /*/// The handler will be invoked in the call to `trigger` so that /// the system triggering it will observe any side effects from /// handling the event. /// /// This is the default strategy. Immediate,*/ /// The handler will be run at the end of the system which triggered the event. EndOfSystem, /// The handle will be scheduled for running at the end of tick. /// /// This is the default strategy. EndOfTick, } impl Default for HandleStrategy { fn default() -> Self { HandleStrategy::EndOfTick } } /// A raw event handler. /// /// # Safety /// * The event type returned by `event_id()` must be the exact /// type which is handled by `handle_raw`. `handle_raw` must /// interpret any events as the same type. pub unsafe trait RawEventHandler: Send + Sync +'static { /// Returns the unique ID of this event handler, as allocated by `system_id_for::<T>()`. fn id(&self) -> SystemId; /// Returns the name of this event handler. fn name(&self) -> &'static str; /// Returns the ID of the event which is handled by this handler. fn event_id(&self) -> EventId; /// Returns the strategy that should be used to invoke this handler. fn strategy(&self) -> HandleStrategy; /// Returns the resources read by this event handler. fn resource_reads(&self) -> &[ResourceId]; /// Returns the resources written by this event handler. fn resource_writes(&self) -> &[ResourceId]; fn init(&mut self, resources: &mut Resources, ctx: SystemCtx, world: &World); /// Handles a slice of events, accessing any needed resources. /// /// # Safety /// * The handler must not access any resources not indicated by `resource_reads()` and `resource_writes()`. /// * The given slice __must__ be transmuted to a slice of the event type returned by `event_id`. unsafe fn handle_raw_batch( &mut self, events: *const (), events_len: usize, resources: &Resources, ctx: SystemCtx, world: &World, ); } // High-level event handlers. /// An event handler. This type should be used by users, not `RawEventHandler`. pub trait EventHandler<E: Event>: Send + Sync +'static { /// The resources accessed by this event handler. type HandlerData: for<'a> SystemData<'a>; /// Handles a single event. Users may implement `handle_batch` /// instead which handles multiple events at once. fn handle(&mut self, event: &E, data: &mut <Self::HandlerData as SystemData>::Output); /// Handles a slice of events. This function may be called instead of `handle` /// when multiple events are concerned. /// /// The default implementation for this function simply calls `handle` on each /// event in the slice. fn handle_batch(&mut self, events: &[E], mut data: <Self::HandlerData as SystemData>::Output) { events .iter() .for_each(|event| self.handle(event, &mut data)); } /// Returns the strategy that should be used to invoke this handler. /// The default implementation of this function returns `HandleStrategy::default()`. fn strategy(&self) -> HandleStrategy { HandleStrategy::default() } } pub struct CachedEventHandler<H, E> where H: EventHandler<E>, E: Event, { inner: H, /// Cached system ID. id: SystemId, /// Cached event ID. event_id: EventId, /// Cached resource reads. resource_reads: Vec<ResourceId>, /// Cached resource writes. resource_writes: Vec<ResourceId>, /// Cached component reads. component_reads: Vec<ComponentTypeId>, /// Cached component writes. component_writes: Vec<ComponentTypeId>, /// Cached handler data, or `None` if it has not yet been accessed. data: Option<H::HandlerData>, name: &'static str, } impl<H, E> CachedEventHandler<H, E> where H: EventHandler<E>, E: Event, { /// Creates a new `CachedEventHandler` caching the given event handler. pub fn new(inner: H, name: &'static str) -> Self { let component_writes = H::HandlerData::component_writes() .into_iter() .collect::<HashSet<_>>(); let mut resource_reads = H::HandlerData::resource_reads(); resource_reads.extend( H::HandlerData::component_reads() .into_iter() .filter(|comp|!component_writes.contains(comp)) .map(|comp| resource_id_for_component(comp)), ); let mut resource_writes = H::HandlerData::resource_writes(); resource_writes.extend( H::HandlerData::component_writes() .into_iter() .map(|comp| resource_id_for_component(comp)), ); Self { id: SYSTEM_ID_MAPPINGS.lock().alloc(), event_id: event_id_for::<E>(), resource_reads, resource_writes, component_reads: H::HandlerData::component_reads(), component_writes: H::HandlerData::component_writes(), data: None, inner, name, } } } unsafe impl<H, E> RawEventHandler for CachedEventHandler<H, E> where H: EventHandler<E>, E: Event, { fn id(&self) -> SystemId { self.id } fn name(&self) -> &'static str { self.name } fn event_id(&self) -> EventId { self.event_id } fn strategy(&self) -> HandleStrategy { self.inner.strategy() } fn resource_reads(&self) -> &[ResourceId] { &self.resource_reads } fn resource_writes(&self) -> &[ResourceId] { &self.resource_writes } fn init(&mut self, resources: &mut Resources, ctx: SystemCtx, world: &World) { let mut data = unsafe { H::HandlerData::load_from_resources(resources, ctx, world) }; data.init(resources, &self.component_reads, &self.component_writes); self.data = Some(data); } unsafe fn handle_raw_batch( &mut self, events: *const (), events_len: usize, _resources: &Resources, _ctx: SystemCtx, _world: &World, ) { // https://github.com/nvzqz/static-assertions-rs/issues/21 /*assert_eq_size!(*const [()], *const [H::Event]); assert_eq_align!(*const [()], *const [H::Event]);*/ let events = std::slice::from_raw_parts(events as *const E, events_len); let data = self.data.as_mut().unwrap(); self.inner.handle_batch(events, data.before_execution()); data.after_execution(); } } /// System data which allows you to trigger events of a given type. pub struct Trigger<E> where E: Event, { ctx: SystemCtx, queued: Vec<E>, id: EventId, } impl<'a, E> SystemData<'a> for Trigger<E> where E: Event, { type Output = &'a mut Self; unsafe fn load_from_resources( _resources: &mut Resources, ctx: SystemCtx, _world: &World, ) -> Self { Self { ctx, queued: vec![], id: event_id_for::<E>(), } } fn resource_reads() -> Vec<ResourceId> { vec![] } fn resource_writes() -> Vec<ResourceId> { vec![] } fn component_reads() -> Vec<ComponentTypeId> { vec![] } fn component_writes() -> Vec<ComponentTypeId> { vec![] } fn before_execution(&'a mut self) -> Self::Output { self } fn after_execution(&mut self) { // TODO: end-of-system handlers // Move events to bump-allocated slice and send to scheduler. let len = self.queued.len(); if len == 0
let ptr: *mut E = self .ctx .bump .get_or_default() .alloc_layout(Layout::for_value(self.queued.as_slice())) .cast::<E>() .as_ptr(); self.queued .drain(..) .enumerate() .for_each(|(index, event)| unsafe { ptr::write(ptr.offset(index as isize), event); }); self.ctx .sender .send(TaskMessage::TriggerEvents { id: self.id, ptr: ptr as *const (), len, }) .unwrap(); } } impl<E> Trigger<E> where E: Send + Sync +'static, { pub fn trigger(&mut self, event: E) { self.queued.push(event); } pub fn trigger_batched(&mut self, events: impl IntoIterator<Item = E>) { self.queued.extend(events); } } impl<'a, E> SystemDataOutput<'a> for &'a mut Trigger<E> where E: Send + Sync +'static, { type SystemData = Trigger<E>; } impl<E> MacroData for &'static mut Trigger<E> where E: Event, { type SystemData = Trigger<E>; } #[cfg(test)] mod tests { #[test] fn check_event_slice_size_and_align() { // temp fix for https://github.com/nvzqz/static-assertions-rs/issues/21 assert_eq_size!(*const [()], *const [i32]); assert_eq_align!(*const [()], *const [i32]); } }
{ return; // Nothing to do }
conditional_block
event.rs
use crate::mappings::Mappings; use crate::scheduler::TaskMessage; use crate::system::{SystemCtx, SystemDataOutput, SYSTEM_ID_MAPPINGS}; use crate::{resource_id_for_component, MacroData, ResourceId, Resources, SystemData, SystemId}; use hashbrown::HashSet; use lazy_static::lazy_static; use legion::storage::ComponentTypeId; use legion::world::World; use parking_lot::Mutex; use std::alloc::Layout; use std::any::TypeId; use std::ptr; /// ID of an event type, allocated consecutively. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)] pub struct EventId(pub usize); impl From<usize> for EventId { fn from(x: usize) -> Self { Self(x) } } lazy_static! { pub static ref EVENT_ID_MAPPINGS: Mutex<Mappings<TypeId, EventId>> = Mutex::new(Mappings::new()); } /// Returns the event ID for the given type. pub fn event_id_for<E>() -> EventId where E: Event, { EVENT_ID_MAPPINGS.lock().get_or_alloc(TypeId::of::<E>()) } /// Marker trait for types which can be triggered as events. pub trait Event: Send + Sync +'static {} impl<T> Event for T where T: Send + Sync +'static {} /// Strategy used to handle an event. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum HandleStrategy { /*/// The handler will be invoked in the call to `trigger` so that /// the system triggering it will observe any side effects from /// handling the event. /// /// This is the default strategy. Immediate,*/ /// The handler will be run at the end of the system which triggered the event. EndOfSystem, /// The handle will be scheduled for running at the end of tick. /// /// This is the default strategy. EndOfTick, } impl Default for HandleStrategy { fn default() -> Self { HandleStrategy::EndOfTick } } /// A raw event handler. /// /// # Safety /// * The event type returned by `event_id()` must be the exact /// type which is handled by `handle_raw`. `handle_raw` must /// interpret any events as the same type. pub unsafe trait RawEventHandler: Send + Sync +'static { /// Returns the unique ID of this event handler, as allocated by `system_id_for::<T>()`. fn id(&self) -> SystemId; /// Returns the name of this event handler. fn name(&self) -> &'static str; /// Returns the ID of the event which is handled by this handler. fn event_id(&self) -> EventId; /// Returns the strategy that should be used to invoke this handler. fn strategy(&self) -> HandleStrategy; /// Returns the resources read by this event handler. fn resource_reads(&self) -> &[ResourceId]; /// Returns the resources written by this event handler. fn resource_writes(&self) -> &[ResourceId]; fn init(&mut self, resources: &mut Resources, ctx: SystemCtx, world: &World); /// Handles a slice of events, accessing any needed resources. /// /// # Safety /// * The handler must not access any resources not indicated by `resource_reads()` and `resource_writes()`. /// * The given slice __must__ be transmuted to a slice of the event type returned by `event_id`. unsafe fn handle_raw_batch( &mut self, events: *const (), events_len: usize, resources: &Resources, ctx: SystemCtx, world: &World, ); } // High-level event handlers. /// An event handler. This type should be used by users, not `RawEventHandler`. pub trait EventHandler<E: Event>: Send + Sync +'static { /// The resources accessed by this event handler. type HandlerData: for<'a> SystemData<'a>; /// Handles a single event. Users may implement `handle_batch` /// instead which handles multiple events at once. fn handle(&mut self, event: &E, data: &mut <Self::HandlerData as SystemData>::Output); /// Handles a slice of events. This function may be called instead of `handle` /// when multiple events are concerned. /// /// The default implementation for this function simply calls `handle` on each /// event in the slice. fn handle_batch(&mut self, events: &[E], mut data: <Self::HandlerData as SystemData>::Output) { events .iter() .for_each(|event| self.handle(event, &mut data)); } /// Returns the strategy that should be used to invoke this handler. /// The default implementation of this function returns `HandleStrategy::default()`. fn strategy(&self) -> HandleStrategy { HandleStrategy::default() } } pub struct CachedEventHandler<H, E> where H: EventHandler<E>, E: Event, { inner: H, /// Cached system ID. id: SystemId, /// Cached event ID. event_id: EventId, /// Cached resource reads. resource_reads: Vec<ResourceId>, /// Cached resource writes. resource_writes: Vec<ResourceId>, /// Cached component reads. component_reads: Vec<ComponentTypeId>, /// Cached component writes. component_writes: Vec<ComponentTypeId>, /// Cached handler data, or `None` if it has not yet been accessed. data: Option<H::HandlerData>, name: &'static str, } impl<H, E> CachedEventHandler<H, E> where H: EventHandler<E>, E: Event, { /// Creates a new `CachedEventHandler` caching the given event handler. pub fn new(inner: H, name: &'static str) -> Self { let component_writes = H::HandlerData::component_writes() .into_iter() .collect::<HashSet<_>>(); let mut resource_reads = H::HandlerData::resource_reads(); resource_reads.extend( H::HandlerData::component_reads() .into_iter() .filter(|comp|!component_writes.contains(comp)) .map(|comp| resource_id_for_component(comp)), ); let mut resource_writes = H::HandlerData::resource_writes(); resource_writes.extend( H::HandlerData::component_writes() .into_iter() .map(|comp| resource_id_for_component(comp)), ); Self { id: SYSTEM_ID_MAPPINGS.lock().alloc(), event_id: event_id_for::<E>(), resource_reads, resource_writes, component_reads: H::HandlerData::component_reads(), component_writes: H::HandlerData::component_writes(), data: None, inner, name, } } } unsafe impl<H, E> RawEventHandler for CachedEventHandler<H, E> where H: EventHandler<E>, E: Event, { fn id(&self) -> SystemId { self.id } fn name(&self) -> &'static str { self.name } fn event_id(&self) -> EventId { self.event_id } fn strategy(&self) -> HandleStrategy { self.inner.strategy() } fn resource_reads(&self) -> &[ResourceId] { &self.resource_reads } fn resource_writes(&self) -> &[ResourceId] { &self.resource_writes } fn init(&mut self, resources: &mut Resources, ctx: SystemCtx, world: &World) { let mut data = unsafe { H::HandlerData::load_from_resources(resources, ctx, world) }; data.init(resources, &self.component_reads, &self.component_writes); self.data = Some(data); } unsafe fn handle_raw_batch( &mut self, events: *const (), events_len: usize, _resources: &Resources, _ctx: SystemCtx, _world: &World, ) { // https://github.com/nvzqz/static-assertions-rs/issues/21 /*assert_eq_size!(*const [()], *const [H::Event]); assert_eq_align!(*const [()], *const [H::Event]);*/ let events = std::slice::from_raw_parts(events as *const E, events_len); let data = self.data.as_mut().unwrap(); self.inner.handle_batch(events, data.before_execution()); data.after_execution(); } } /// System data which allows you to trigger events of a given type. pub struct Trigger<E> where E: Event, { ctx: SystemCtx, queued: Vec<E>, id: EventId, } impl<'a, E> SystemData<'a> for Trigger<E> where E: Event, { type Output = &'a mut Self; unsafe fn load_from_resources( _resources: &mut Resources, ctx: SystemCtx, _world: &World, ) -> Self { Self { ctx, queued: vec![], id: event_id_for::<E>(), } } fn resource_reads() -> Vec<ResourceId> { vec![] } fn resource_writes() -> Vec<ResourceId> { vec![] } fn component_reads() -> Vec<ComponentTypeId> { vec![] } fn component_writes() -> Vec<ComponentTypeId> { vec![] } fn before_execution(&'a mut self) -> Self::Output { self } fn after_execution(&mut self) { // TODO: end-of-system handlers // Move events to bump-allocated slice and send to scheduler. let len = self.queued.len(); if len == 0 { return; // Nothing to do } let ptr: *mut E = self .ctx .bump .get_or_default() .alloc_layout(Layout::for_value(self.queued.as_slice())) .cast::<E>() .as_ptr(); self.queued .drain(..) .enumerate() .for_each(|(index, event)| unsafe { ptr::write(ptr.offset(index as isize), event); }); self.ctx .sender .send(TaskMessage::TriggerEvents { id: self.id, ptr: ptr as *const (), len, }) .unwrap(); } } impl<E> Trigger<E> where E: Send + Sync +'static, { pub fn
(&mut self, event: E) { self.queued.push(event); } pub fn trigger_batched(&mut self, events: impl IntoIterator<Item = E>) { self.queued.extend(events); } } impl<'a, E> SystemDataOutput<'a> for &'a mut Trigger<E> where E: Send + Sync +'static, { type SystemData = Trigger<E>; } impl<E> MacroData for &'static mut Trigger<E> where E: Event, { type SystemData = Trigger<E>; } #[cfg(test)] mod tests { #[test] fn check_event_slice_size_and_align() { // temp fix for https://github.com/nvzqz/static-assertions-rs/issues/21 assert_eq_size!(*const [()], *const [i32]); assert_eq_align!(*const [()], *const [i32]); } }
trigger
identifier_name
event.rs
use crate::mappings::Mappings; use crate::scheduler::TaskMessage; use crate::system::{SystemCtx, SystemDataOutput, SYSTEM_ID_MAPPINGS}; use crate::{resource_id_for_component, MacroData, ResourceId, Resources, SystemData, SystemId}; use hashbrown::HashSet; use lazy_static::lazy_static; use legion::storage::ComponentTypeId; use legion::world::World; use parking_lot::Mutex; use std::alloc::Layout; use std::any::TypeId; use std::ptr; /// ID of an event type, allocated consecutively. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)] pub struct EventId(pub usize); impl From<usize> for EventId { fn from(x: usize) -> Self { Self(x) } } lazy_static! { pub static ref EVENT_ID_MAPPINGS: Mutex<Mappings<TypeId, EventId>> = Mutex::new(Mappings::new()); } /// Returns the event ID for the given type. pub fn event_id_for<E>() -> EventId where E: Event, { EVENT_ID_MAPPINGS.lock().get_or_alloc(TypeId::of::<E>()) } /// Marker trait for types which can be triggered as events. pub trait Event: Send + Sync +'static {} impl<T> Event for T where T: Send + Sync +'static {} /// Strategy used to handle an event. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum HandleStrategy { /*/// The handler will be invoked in the call to `trigger` so that /// the system triggering it will observe any side effects from /// handling the event. /// /// This is the default strategy. Immediate,*/ /// The handler will be run at the end of the system which triggered the event. EndOfSystem, /// The handle will be scheduled for running at the end of tick. /// /// This is the default strategy. EndOfTick, } impl Default for HandleStrategy { fn default() -> Self { HandleStrategy::EndOfTick } } /// A raw event handler. /// /// # Safety /// * The event type returned by `event_id()` must be the exact /// type which is handled by `handle_raw`. `handle_raw` must /// interpret any events as the same type.
/// Returns the unique ID of this event handler, as allocated by `system_id_for::<T>()`. fn id(&self) -> SystemId; /// Returns the name of this event handler. fn name(&self) -> &'static str; /// Returns the ID of the event which is handled by this handler. fn event_id(&self) -> EventId; /// Returns the strategy that should be used to invoke this handler. fn strategy(&self) -> HandleStrategy; /// Returns the resources read by this event handler. fn resource_reads(&self) -> &[ResourceId]; /// Returns the resources written by this event handler. fn resource_writes(&self) -> &[ResourceId]; fn init(&mut self, resources: &mut Resources, ctx: SystemCtx, world: &World); /// Handles a slice of events, accessing any needed resources. /// /// # Safety /// * The handler must not access any resources not indicated by `resource_reads()` and `resource_writes()`. /// * The given slice __must__ be transmuted to a slice of the event type returned by `event_id`. unsafe fn handle_raw_batch( &mut self, events: *const (), events_len: usize, resources: &Resources, ctx: SystemCtx, world: &World, ); } // High-level event handlers. /// An event handler. This type should be used by users, not `RawEventHandler`. pub trait EventHandler<E: Event>: Send + Sync +'static { /// The resources accessed by this event handler. type HandlerData: for<'a> SystemData<'a>; /// Handles a single event. Users may implement `handle_batch` /// instead which handles multiple events at once. fn handle(&mut self, event: &E, data: &mut <Self::HandlerData as SystemData>::Output); /// Handles a slice of events. This function may be called instead of `handle` /// when multiple events are concerned. /// /// The default implementation for this function simply calls `handle` on each /// event in the slice. fn handle_batch(&mut self, events: &[E], mut data: <Self::HandlerData as SystemData>::Output) { events .iter() .for_each(|event| self.handle(event, &mut data)); } /// Returns the strategy that should be used to invoke this handler. /// The default implementation of this function returns `HandleStrategy::default()`. fn strategy(&self) -> HandleStrategy { HandleStrategy::default() } } pub struct CachedEventHandler<H, E> where H: EventHandler<E>, E: Event, { inner: H, /// Cached system ID. id: SystemId, /// Cached event ID. event_id: EventId, /// Cached resource reads. resource_reads: Vec<ResourceId>, /// Cached resource writes. resource_writes: Vec<ResourceId>, /// Cached component reads. component_reads: Vec<ComponentTypeId>, /// Cached component writes. component_writes: Vec<ComponentTypeId>, /// Cached handler data, or `None` if it has not yet been accessed. data: Option<H::HandlerData>, name: &'static str, } impl<H, E> CachedEventHandler<H, E> where H: EventHandler<E>, E: Event, { /// Creates a new `CachedEventHandler` caching the given event handler. pub fn new(inner: H, name: &'static str) -> Self { let component_writes = H::HandlerData::component_writes() .into_iter() .collect::<HashSet<_>>(); let mut resource_reads = H::HandlerData::resource_reads(); resource_reads.extend( H::HandlerData::component_reads() .into_iter() .filter(|comp|!component_writes.contains(comp)) .map(|comp| resource_id_for_component(comp)), ); let mut resource_writes = H::HandlerData::resource_writes(); resource_writes.extend( H::HandlerData::component_writes() .into_iter() .map(|comp| resource_id_for_component(comp)), ); Self { id: SYSTEM_ID_MAPPINGS.lock().alloc(), event_id: event_id_for::<E>(), resource_reads, resource_writes, component_reads: H::HandlerData::component_reads(), component_writes: H::HandlerData::component_writes(), data: None, inner, name, } } } unsafe impl<H, E> RawEventHandler for CachedEventHandler<H, E> where H: EventHandler<E>, E: Event, { fn id(&self) -> SystemId { self.id } fn name(&self) -> &'static str { self.name } fn event_id(&self) -> EventId { self.event_id } fn strategy(&self) -> HandleStrategy { self.inner.strategy() } fn resource_reads(&self) -> &[ResourceId] { &self.resource_reads } fn resource_writes(&self) -> &[ResourceId] { &self.resource_writes } fn init(&mut self, resources: &mut Resources, ctx: SystemCtx, world: &World) { let mut data = unsafe { H::HandlerData::load_from_resources(resources, ctx, world) }; data.init(resources, &self.component_reads, &self.component_writes); self.data = Some(data); } unsafe fn handle_raw_batch( &mut self, events: *const (), events_len: usize, _resources: &Resources, _ctx: SystemCtx, _world: &World, ) { // https://github.com/nvzqz/static-assertions-rs/issues/21 /*assert_eq_size!(*const [()], *const [H::Event]); assert_eq_align!(*const [()], *const [H::Event]);*/ let events = std::slice::from_raw_parts(events as *const E, events_len); let data = self.data.as_mut().unwrap(); self.inner.handle_batch(events, data.before_execution()); data.after_execution(); } } /// System data which allows you to trigger events of a given type. pub struct Trigger<E> where E: Event, { ctx: SystemCtx, queued: Vec<E>, id: EventId, } impl<'a, E> SystemData<'a> for Trigger<E> where E: Event, { type Output = &'a mut Self; unsafe fn load_from_resources( _resources: &mut Resources, ctx: SystemCtx, _world: &World, ) -> Self { Self { ctx, queued: vec![], id: event_id_for::<E>(), } } fn resource_reads() -> Vec<ResourceId> { vec![] } fn resource_writes() -> Vec<ResourceId> { vec![] } fn component_reads() -> Vec<ComponentTypeId> { vec![] } fn component_writes() -> Vec<ComponentTypeId> { vec![] } fn before_execution(&'a mut self) -> Self::Output { self } fn after_execution(&mut self) { // TODO: end-of-system handlers // Move events to bump-allocated slice and send to scheduler. let len = self.queued.len(); if len == 0 { return; // Nothing to do } let ptr: *mut E = self .ctx .bump .get_or_default() .alloc_layout(Layout::for_value(self.queued.as_slice())) .cast::<E>() .as_ptr(); self.queued .drain(..) .enumerate() .for_each(|(index, event)| unsafe { ptr::write(ptr.offset(index as isize), event); }); self.ctx .sender .send(TaskMessage::TriggerEvents { id: self.id, ptr: ptr as *const (), len, }) .unwrap(); } } impl<E> Trigger<E> where E: Send + Sync +'static, { pub fn trigger(&mut self, event: E) { self.queued.push(event); } pub fn trigger_batched(&mut self, events: impl IntoIterator<Item = E>) { self.queued.extend(events); } } impl<'a, E> SystemDataOutput<'a> for &'a mut Trigger<E> where E: Send + Sync +'static, { type SystemData = Trigger<E>; } impl<E> MacroData for &'static mut Trigger<E> where E: Event, { type SystemData = Trigger<E>; } #[cfg(test)] mod tests { #[test] fn check_event_slice_size_and_align() { // temp fix for https://github.com/nvzqz/static-assertions-rs/issues/21 assert_eq_size!(*const [()], *const [i32]); assert_eq_align!(*const [()], *const [i32]); } }
pub unsafe trait RawEventHandler: Send + Sync + 'static {
random_line_split
mod.rs
pub mod build; pub mod config; pub mod dev; pub mod generate; pub mod init; pub mod kv; pub mod login; pub mod logout; pub mod preview; pub mod publish; pub mod r2; pub mod route; pub mod secret; pub mod subdomain; pub mod tail; pub mod whoami; pub mod exec { pub use super::build::build; pub use super::config::configure; pub use super::dev::dev; pub use super::generate::generate; pub use super::init::init; pub use super::kv::kv_bulk; pub use super::kv::kv_key; pub use super::kv::kv_namespace; pub use super::login::login; pub use super::logout::logout; pub use super::preview::preview; pub use super::publish::publish; pub use super::r2::r2_bucket; pub use super::route::route; pub use super::secret::secret; pub use super::subdomain::subdomain; pub use super::tail::tail; pub use super::whoami::whoami; } use std::net::IpAddr; use std::path::PathBuf; use std::str::FromStr; use crate::commands::dev::Protocol; use crate::commands::tail::websocket::TailFormat; use crate::preview::HttpMethod; use crate::settings::toml::migrations::{ DurableObjectsMigration, Migration, MigrationTag, Migrations, RenameClass, TransferClass, }; use crate::settings::toml::TargetType; use clap::AppSettings; use structopt::StructOpt; use url::Url; #[derive(Debug, Clone, StructOpt)] #[structopt( name = "wrangler", author = "The Wrangler Team <[email protected]>", setting = AppSettings::ArgRequiredElseHelp, setting = AppSettings::DeriveDisplayOrder, setting = AppSettings::VersionlessSubcommands, )] pub struct Cli { /// Toggle verbose output (when applicable) #[structopt(long, global = true)] pub verbose: bool, /// Path to configuration file. #[structopt(long, short = "c", default_value = "wrangler.toml", global = true)] pub config: PathBuf, /// Environment to perform a command on. #[structopt(name = "env", long, short = "e", global = true)] pub environment: Option<String>, #[structopt(subcommand)] pub command: Command, } #[derive(Debug, Clone, StructOpt)] pub enum
{ /// Interact with your Workers KV Namespaces #[structopt(name = "kv:namespace", setting = AppSettings::SubcommandRequiredElseHelp)] KvNamespace(kv::KvNamespace), /// Individually manage Workers KV key-value pairs #[structopt(name = "kv:key", setting = AppSettings::SubcommandRequiredElseHelp)] KvKey(kv::KvKey), /// Interact with multiple Workers KV key-value pairs at once #[structopt(name = "kv:bulk", setting = AppSettings::SubcommandRequiredElseHelp)] KvBulk(kv::KvBulk), /// Interact with your Workers R2 Buckets #[structopt(setting = AppSettings::SubcommandRequiredElseHelp)] R2(r2::R2), /// List or delete worker routes. #[structopt(name = "route", setting = AppSettings::SubcommandRequiredElseHelp)] Route(route::Route), /// Generate a secret that can be referenced in the worker script #[structopt(name = "secret", setting = AppSettings::SubcommandRequiredElseHelp)] Secret(secret::Secret), /// Generate a new worker project Generate { /// The name of your worker! #[structopt(index = 1, default_value = "worker")] name: String, /// A link to a GitHub template! Defaults to https://github.com/cloudflare/worker-template #[structopt(index = 2)] template: Option<String>, /// The type of project you want generated #[structopt(name = "type", long, short = "t")] target_type: Option<TargetType>, /// Initializes a Workers Sites project. Overrides 'type' and 'template' #[structopt(long, short = "s")] site: bool, }, /// Create a wrangler.toml for an existing project Init { /// The name of your worker! #[structopt(index = 1)] name: Option<String>, /// The type of project you want generated #[structopt(name = "type", long, short = "t")] target_type: Option<TargetType>, /// Initializes a Workers Sites project. Overrides `type` and `template` #[structopt(long, short = "s")] site: bool, }, /// Build your worker Build, /// Preview your code temporarily on cloudflareworkers.com Preview { /// Type of request to preview your worker with (get, post) #[structopt(index = 1, default_value = "get")] method: HttpMethod, /// URL to open in the worker preview #[structopt(short = "u", long, default_value = "https://example.com")] url: Url, /// Body string to post to your preview worker request #[structopt(index = 2)] body: Option<String>, /// Watch your project for changes and update the preview automagically #[structopt(long)] watch: bool, /// Don't open the browser on preview #[structopt(long)] headless: bool, }, /// Start a local server for developing your worker Dev { /// Host to forward requests to, defaults to the zone of project or to /// tutorial.cloudflareworkers.com if unauthenticated. #[structopt(long, short = "h")] host: Option<String>, /// IP to listen on. Defaults to 127.0.0.1 #[structopt(long, short = "i")] ip: Option<IpAddr>, /// Port to listen on. Defaults to 8787 #[structopt(long, short = "p")] port: Option<u16>, /// Sets the protocol on which the wrangler dev listens, by default this is http /// but can be set to https #[structopt(name = "local-protocol")] local_protocol: Option<Protocol>, /// Sets the protocol on which requests are sent to the host, by default this is https /// but can be set to http #[structopt(name = "upstream-protocol")] upstream_protocol: Option<Protocol>, /// Inspect the worker using Chrome DevTools #[structopt(long)] inspect: bool, /// Run wrangler dev unauthenticated #[structopt(long)] unauthenticated: bool, }, /// Publish your worker to the orange cloud #[structopt(name = "publish")] Publish { /// [deprecated] alias of wrangler publish #[structopt(long, hidden = true)] release: bool, #[structopt(possible_value = "json")] output: Option<String>, #[structopt(flatten)] migration: AdhocMigration, }, /// Authenticate Wrangler with a Cloudflare API Token or Global API Key #[structopt(name = "config")] Config { /// Use an email and global API key for authentication. /// This is not recommended; use API tokens (the default) if possible #[structopt(name = "api-key", long)] api_key: bool, /// Do not verify provided credentials before writing out Wrangler config file #[structopt(name = "no-verify", long)] no_verify: bool, }, /// Configure your workers.dev subdomain #[structopt(name = "subdomain")] Subdomain { /// The subdomain on workers.dev you'd like to reserve #[structopt(name = "name", index = 1)] name: Option<String>, }, /// Retrieve your user info and test your auth config #[structopt(name = "whoami")] Whoami, /// View a stream of logs from a published worker #[structopt(name = "tail")] Tail { /// Name of the worker to tail #[structopt(index = 1)] name: Option<String>, /// Output format for log messages #[structopt(long, short = "f", default_value = "json", possible_values = &["json", "pretty"])] format: TailFormat, /// Stops the tail after receiving the first log (useful for testing) #[structopt(long)] once: bool, /// Adds a sampling rate (0.01 for 1%) #[structopt(long = "sampling-rate", default_value = "1")] sampling_rate: f64, /// Filter by invocation status #[structopt(long, possible_values = &["ok", "error", "canceled"])] status: Vec<String>, /// Filter by HTTP method #[structopt(long)] method: Vec<String>, /// Filter by HTTP header #[structopt(long)] header: Vec<String>, /// Filter by IP address ("self" to filter your own IP address) #[structopt(long = "ip-address", parse(try_from_str = parse_ip_address))] ip_address: Vec<String>, /// Filter by a text match in console.log messages #[structopt(long)] search: Option<String>, /// Set the URL to forward log messages #[structopt(hidden = true)] url: Option<Url>, /// Deprecated, no longer used. #[structopt(hidden = true, long = "port", short = "p")] tunnel_port: Option<u16>, /// Deprecated, no longer used. #[structopt(hidden = true, long = "metrics")] metrics_port: Option<u16>, }, /// Authenticate wrangler with your Cloudflare username and password #[structopt(name = "login")] Login { /// Allows to choose set of scopes #[structopt(name = "scopes", long, possible_values = login::SCOPES_LIST.as_ref())] scopes: Vec<String>, /// List all scopes #[structopt(name = "scopes-list", long)] scopes_list: bool, }, /// Logout from your current authentication method and remove any configuration files. /// It does not logout if you have authenticated wrangler through environment variables. #[structopt(name = "logout")] Logout, } #[derive(Debug, Clone, StructOpt)] pub struct AdhocMigration { /// Allow durable objects to be created from a class in your script #[structopt(name = "new-class", long, number_of_values = 1)] new_class: Vec<String>, /// Delete all durable objects associated with a class in your script #[structopt(name = "delete-class", long, number_of_values = 1)] delete_class: Vec<String>, /// Rename a durable object class #[structopt(name = "rename-class", long, number_of_values = 2, value_names(&["from class", "to class"]))] rename_class: Vec<String>, /// Transfer all durable objects associated with a class in another script to a class in /// this script #[structopt(name = "transfer-class", long, number_of_values = 3, value_names(&["from script", "from class", "to class"]))] transfer_class: Vec<String>, /// Specify the existing migration tag for the script. #[structopt(name = "old-tag", long)] old_tag: Option<String>, /// Specify the new migration tag for the script #[structopt(name = "new-tag", long)] new_tag: Option<String>, } impl AdhocMigration { pub fn into_migrations(self) -> Option<Migrations> { let migration = DurableObjectsMigration { new_classes: self.new_class, deleted_classes: self.delete_class, renamed_classes: self .rename_class .chunks_exact(2) .map(|chunk| { let (from, to) = if let [from, to] = chunk { (from.clone(), to.clone()) } else { unreachable!("Chunks exact returned a slice with a length not equal to 2") }; RenameClass { from, to } }) .collect(), transferred_classes: self .transfer_class .chunks_exact(3) .map(|chunk| { let (from_script, from, to) = if let [from_script, from, to] = chunk { (from_script.clone(), from.clone(), to.clone()) } else { unreachable!("Chunks exact returned a slice with a length not equal to 3") }; TransferClass { from, from_script, to, } }) .collect(), }; let is_migration_empty = migration.new_classes.is_empty() && migration.deleted_classes.is_empty() && migration.renamed_classes.is_empty() && migration.transferred_classes.is_empty(); if!is_migration_empty || self.old_tag.is_some() || self.new_tag.is_some() { let migration = if!is_migration_empty { Some(Migration { durable_objects: migration, }) } else { None }; Some(Migrations::Adhoc { script_tag: MigrationTag::Unknown, provided_old_tag: self.old_tag, new_tag: self.new_tag, migration, }) } else { None } } } fn parse_ip_address(input: &str) -> Result<String, anyhow::Error> { match input { "self" => Ok(String::from("self")), address => match IpAddr::from_str(address) { Ok(_) => Ok(address.to_owned()), Err(err) => anyhow::bail!("{}: {}", err, input), }, } } #[cfg(test)] mod tests { use super::*; fn rename_class(tag: &str) -> RenameClass { RenameClass { from: format!("renameFrom{}", tag), to: format!("renameTo{}", tag), } } fn transfer_class(tag: &str) -> TransferClass { TransferClass { from: format!("transferFromClass{}", tag), from_script: format!("transferFromScript{}", tag), to: format!("transferToClass{}", tag), } } #[test] fn adhoc_migration_parsing() { let command = Cli::from_iter(&[ "wrangler", "publish", "--old-tag", "oldTag", "--new-tag", "newTag", "--new-class", "newA", "--new-class", "newB", "--delete-class", "deleteA", "--delete-class", "deleteB", "--rename-class", "renameFromA", "renameToA", "--rename-class", "renameFromB", "renameToB", "--transfer-class", "transferFromScriptA", "transferFromClassA", "transferToClassA", "--transfer-class", "transferFromScriptB", "transferFromClassB", "transferToClassB", ]) .command; if let Command::Publish { migration,.. } = command { assert_eq!( migration.into_migrations(), Some(Migrations::Adhoc { script_tag: MigrationTag::Unknown, provided_old_tag: Some(String::from("oldTag")), new_tag: Some(String::from("newTag")), migration: Some(Migration { durable_objects: DurableObjectsMigration { new_classes: vec![String::from("newA"), String::from("newB")], deleted_classes: vec![String::from("deleteA"), String::from("deleteB")], renamed_classes: vec![rename_class("A"), rename_class("B")], transferred_classes: vec![transfer_class("A"), transfer_class("B")], } }) }) ); } else { assert!(false, "Unkown command {:?}", command) } } }
Command
identifier_name
mod.rs
pub mod build; pub mod config; pub mod dev; pub mod generate; pub mod init; pub mod kv; pub mod login; pub mod logout; pub mod preview; pub mod publish; pub mod r2; pub mod route; pub mod secret; pub mod subdomain; pub mod tail; pub mod whoami; pub mod exec { pub use super::build::build; pub use super::config::configure; pub use super::dev::dev; pub use super::generate::generate; pub use super::init::init; pub use super::kv::kv_bulk; pub use super::kv::kv_key; pub use super::kv::kv_namespace; pub use super::login::login; pub use super::logout::logout; pub use super::preview::preview; pub use super::publish::publish; pub use super::r2::r2_bucket; pub use super::route::route; pub use super::secret::secret; pub use super::subdomain::subdomain; pub use super::tail::tail; pub use super::whoami::whoami; } use std::net::IpAddr; use std::path::PathBuf; use std::str::FromStr; use crate::commands::dev::Protocol; use crate::commands::tail::websocket::TailFormat; use crate::preview::HttpMethod; use crate::settings::toml::migrations::{ DurableObjectsMigration, Migration, MigrationTag, Migrations, RenameClass, TransferClass, }; use crate::settings::toml::TargetType; use clap::AppSettings; use structopt::StructOpt; use url::Url; #[derive(Debug, Clone, StructOpt)] #[structopt( name = "wrangler", author = "The Wrangler Team <[email protected]>", setting = AppSettings::ArgRequiredElseHelp, setting = AppSettings::DeriveDisplayOrder, setting = AppSettings::VersionlessSubcommands, )] pub struct Cli { /// Toggle verbose output (when applicable) #[structopt(long, global = true)] pub verbose: bool, /// Path to configuration file. #[structopt(long, short = "c", default_value = "wrangler.toml", global = true)] pub config: PathBuf, /// Environment to perform a command on. #[structopt(name = "env", long, short = "e", global = true)] pub environment: Option<String>, #[structopt(subcommand)] pub command: Command, } #[derive(Debug, Clone, StructOpt)] pub enum Command { /// Interact with your Workers KV Namespaces #[structopt(name = "kv:namespace", setting = AppSettings::SubcommandRequiredElseHelp)] KvNamespace(kv::KvNamespace), /// Individually manage Workers KV key-value pairs #[structopt(name = "kv:key", setting = AppSettings::SubcommandRequiredElseHelp)] KvKey(kv::KvKey), /// Interact with multiple Workers KV key-value pairs at once #[structopt(name = "kv:bulk", setting = AppSettings::SubcommandRequiredElseHelp)] KvBulk(kv::KvBulk), /// Interact with your Workers R2 Buckets #[structopt(setting = AppSettings::SubcommandRequiredElseHelp)] R2(r2::R2), /// List or delete worker routes. #[structopt(name = "route", setting = AppSettings::SubcommandRequiredElseHelp)] Route(route::Route), /// Generate a secret that can be referenced in the worker script #[structopt(name = "secret", setting = AppSettings::SubcommandRequiredElseHelp)] Secret(secret::Secret), /// Generate a new worker project Generate { /// The name of your worker! #[structopt(index = 1, default_value = "worker")] name: String, /// A link to a GitHub template! Defaults to https://github.com/cloudflare/worker-template #[structopt(index = 2)] template: Option<String>, /// The type of project you want generated #[structopt(name = "type", long, short = "t")] target_type: Option<TargetType>, /// Initializes a Workers Sites project. Overrides 'type' and 'template' #[structopt(long, short = "s")] site: bool, }, /// Create a wrangler.toml for an existing project Init { /// The name of your worker! #[structopt(index = 1)] name: Option<String>, /// The type of project you want generated #[structopt(name = "type", long, short = "t")] target_type: Option<TargetType>, /// Initializes a Workers Sites project. Overrides `type` and `template` #[structopt(long, short = "s")] site: bool, }, /// Build your worker Build, /// Preview your code temporarily on cloudflareworkers.com Preview { /// Type of request to preview your worker with (get, post) #[structopt(index = 1, default_value = "get")] method: HttpMethod, /// URL to open in the worker preview #[structopt(short = "u", long, default_value = "https://example.com")] url: Url, /// Body string to post to your preview worker request #[structopt(index = 2)] body: Option<String>, /// Watch your project for changes and update the preview automagically #[structopt(long)] watch: bool, /// Don't open the browser on preview #[structopt(long)] headless: bool, }, /// Start a local server for developing your worker Dev { /// Host to forward requests to, defaults to the zone of project or to /// tutorial.cloudflareworkers.com if unauthenticated. #[structopt(long, short = "h")] host: Option<String>, /// IP to listen on. Defaults to 127.0.0.1 #[structopt(long, short = "i")] ip: Option<IpAddr>, /// Port to listen on. Defaults to 8787 #[structopt(long, short = "p")] port: Option<u16>, /// Sets the protocol on which the wrangler dev listens, by default this is http /// but can be set to https #[structopt(name = "local-protocol")] local_protocol: Option<Protocol>, /// Sets the protocol on which requests are sent to the host, by default this is https /// but can be set to http #[structopt(name = "upstream-protocol")] upstream_protocol: Option<Protocol>, /// Inspect the worker using Chrome DevTools #[structopt(long)] inspect: bool, /// Run wrangler dev unauthenticated #[structopt(long)] unauthenticated: bool, }, /// Publish your worker to the orange cloud #[structopt(name = "publish")] Publish { /// [deprecated] alias of wrangler publish #[structopt(long, hidden = true)] release: bool, #[structopt(possible_value = "json")] output: Option<String>, #[structopt(flatten)] migration: AdhocMigration, }, /// Authenticate Wrangler with a Cloudflare API Token or Global API Key #[structopt(name = "config")] Config { /// Use an email and global API key for authentication. /// This is not recommended; use API tokens (the default) if possible #[structopt(name = "api-key", long)] api_key: bool, /// Do not verify provided credentials before writing out Wrangler config file #[structopt(name = "no-verify", long)] no_verify: bool, }, /// Configure your workers.dev subdomain #[structopt(name = "subdomain")] Subdomain { /// The subdomain on workers.dev you'd like to reserve #[structopt(name = "name", index = 1)] name: Option<String>, }, /// Retrieve your user info and test your auth config #[structopt(name = "whoami")] Whoami, /// View a stream of logs from a published worker #[structopt(name = "tail")] Tail { /// Name of the worker to tail #[structopt(index = 1)] name: Option<String>, /// Output format for log messages #[structopt(long, short = "f", default_value = "json", possible_values = &["json", "pretty"])] format: TailFormat, /// Stops the tail after receiving the first log (useful for testing) #[structopt(long)] once: bool, /// Adds a sampling rate (0.01 for 1%) #[structopt(long = "sampling-rate", default_value = "1")] sampling_rate: f64, /// Filter by invocation status #[structopt(long, possible_values = &["ok", "error", "canceled"])] status: Vec<String>, /// Filter by HTTP method #[structopt(long)] method: Vec<String>, /// Filter by HTTP header #[structopt(long)] header: Vec<String>, /// Filter by IP address ("self" to filter your own IP address) #[structopt(long = "ip-address", parse(try_from_str = parse_ip_address))] ip_address: Vec<String>, /// Filter by a text match in console.log messages #[structopt(long)] search: Option<String>, /// Set the URL to forward log messages #[structopt(hidden = true)] url: Option<Url>, /// Deprecated, no longer used. #[structopt(hidden = true, long = "port", short = "p")] tunnel_port: Option<u16>, /// Deprecated, no longer used. #[structopt(hidden = true, long = "metrics")] metrics_port: Option<u16>, }, /// Authenticate wrangler with your Cloudflare username and password #[structopt(name = "login")] Login { /// Allows to choose set of scopes #[structopt(name = "scopes", long, possible_values = login::SCOPES_LIST.as_ref())] scopes: Vec<String>, /// List all scopes #[structopt(name = "scopes-list", long)] scopes_list: bool, }, /// Logout from your current authentication method and remove any configuration files. /// It does not logout if you have authenticated wrangler through environment variables. #[structopt(name = "logout")] Logout, } #[derive(Debug, Clone, StructOpt)] pub struct AdhocMigration { /// Allow durable objects to be created from a class in your script #[structopt(name = "new-class", long, number_of_values = 1)] new_class: Vec<String>, /// Delete all durable objects associated with a class in your script #[structopt(name = "delete-class", long, number_of_values = 1)] delete_class: Vec<String>, /// Rename a durable object class #[structopt(name = "rename-class", long, number_of_values = 2, value_names(&["from class", "to class"]))] rename_class: Vec<String>, /// Transfer all durable objects associated with a class in another script to a class in /// this script #[structopt(name = "transfer-class", long, number_of_values = 3, value_names(&["from script", "from class", "to class"]))] transfer_class: Vec<String>, /// Specify the existing migration tag for the script. #[structopt(name = "old-tag", long)] old_tag: Option<String>, /// Specify the new migration tag for the script #[structopt(name = "new-tag", long)] new_tag: Option<String>, } impl AdhocMigration { pub fn into_migrations(self) -> Option<Migrations> { let migration = DurableObjectsMigration { new_classes: self.new_class, deleted_classes: self.delete_class, renamed_classes: self .rename_class .chunks_exact(2) .map(|chunk| { let (from, to) = if let [from, to] = chunk { (from.clone(), to.clone()) } else { unreachable!("Chunks exact returned a slice with a length not equal to 2") }; RenameClass { from, to } }) .collect(), transferred_classes: self .transfer_class .chunks_exact(3) .map(|chunk| { let (from_script, from, to) = if let [from_script, from, to] = chunk { (from_script.clone(), from.clone(), to.clone()) } else { unreachable!("Chunks exact returned a slice with a length not equal to 3") }; TransferClass { from, from_script, to, } }) .collect(), }; let is_migration_empty = migration.new_classes.is_empty() && migration.deleted_classes.is_empty() && migration.renamed_classes.is_empty() && migration.transferred_classes.is_empty(); if!is_migration_empty || self.old_tag.is_some() || self.new_tag.is_some() { let migration = if!is_migration_empty { Some(Migration { durable_objects: migration, }) } else { None }; Some(Migrations::Adhoc { script_tag: MigrationTag::Unknown, provided_old_tag: self.old_tag, new_tag: self.new_tag, migration, }) } else { None } } } fn parse_ip_address(input: &str) -> Result<String, anyhow::Error>
#[cfg(test)] mod tests { use super::*; fn rename_class(tag: &str) -> RenameClass { RenameClass { from: format!("renameFrom{}", tag), to: format!("renameTo{}", tag), } } fn transfer_class(tag: &str) -> TransferClass { TransferClass { from: format!("transferFromClass{}", tag), from_script: format!("transferFromScript{}", tag), to: format!("transferToClass{}", tag), } } #[test] fn adhoc_migration_parsing() { let command = Cli::from_iter(&[ "wrangler", "publish", "--old-tag", "oldTag", "--new-tag", "newTag", "--new-class", "newA", "--new-class", "newB", "--delete-class", "deleteA", "--delete-class", "deleteB", "--rename-class", "renameFromA", "renameToA", "--rename-class", "renameFromB", "renameToB", "--transfer-class", "transferFromScriptA", "transferFromClassA", "transferToClassA", "--transfer-class", "transferFromScriptB", "transferFromClassB", "transferToClassB", ]) .command; if let Command::Publish { migration,.. } = command { assert_eq!( migration.into_migrations(), Some(Migrations::Adhoc { script_tag: MigrationTag::Unknown, provided_old_tag: Some(String::from("oldTag")), new_tag: Some(String::from("newTag")), migration: Some(Migration { durable_objects: DurableObjectsMigration { new_classes: vec![String::from("newA"), String::from("newB")], deleted_classes: vec![String::from("deleteA"), String::from("deleteB")], renamed_classes: vec![rename_class("A"), rename_class("B")], transferred_classes: vec![transfer_class("A"), transfer_class("B")], } }) }) ); } else { assert!(false, "Unkown command {:?}", command) } } }
{ match input { "self" => Ok(String::from("self")), address => match IpAddr::from_str(address) { Ok(_) => Ok(address.to_owned()), Err(err) => anyhow::bail!("{}: {}", err, input), }, } }
identifier_body
mod.rs
pub mod build; pub mod config; pub mod dev; pub mod generate; pub mod init; pub mod kv; pub mod login; pub mod logout; pub mod preview; pub mod publish; pub mod r2; pub mod route; pub mod secret;
pub mod exec { pub use super::build::build; pub use super::config::configure; pub use super::dev::dev; pub use super::generate::generate; pub use super::init::init; pub use super::kv::kv_bulk; pub use super::kv::kv_key; pub use super::kv::kv_namespace; pub use super::login::login; pub use super::logout::logout; pub use super::preview::preview; pub use super::publish::publish; pub use super::r2::r2_bucket; pub use super::route::route; pub use super::secret::secret; pub use super::subdomain::subdomain; pub use super::tail::tail; pub use super::whoami::whoami; } use std::net::IpAddr; use std::path::PathBuf; use std::str::FromStr; use crate::commands::dev::Protocol; use crate::commands::tail::websocket::TailFormat; use crate::preview::HttpMethod; use crate::settings::toml::migrations::{ DurableObjectsMigration, Migration, MigrationTag, Migrations, RenameClass, TransferClass, }; use crate::settings::toml::TargetType; use clap::AppSettings; use structopt::StructOpt; use url::Url; #[derive(Debug, Clone, StructOpt)] #[structopt( name = "wrangler", author = "The Wrangler Team <[email protected]>", setting = AppSettings::ArgRequiredElseHelp, setting = AppSettings::DeriveDisplayOrder, setting = AppSettings::VersionlessSubcommands, )] pub struct Cli { /// Toggle verbose output (when applicable) #[structopt(long, global = true)] pub verbose: bool, /// Path to configuration file. #[structopt(long, short = "c", default_value = "wrangler.toml", global = true)] pub config: PathBuf, /// Environment to perform a command on. #[structopt(name = "env", long, short = "e", global = true)] pub environment: Option<String>, #[structopt(subcommand)] pub command: Command, } #[derive(Debug, Clone, StructOpt)] pub enum Command { /// Interact with your Workers KV Namespaces #[structopt(name = "kv:namespace", setting = AppSettings::SubcommandRequiredElseHelp)] KvNamespace(kv::KvNamespace), /// Individually manage Workers KV key-value pairs #[structopt(name = "kv:key", setting = AppSettings::SubcommandRequiredElseHelp)] KvKey(kv::KvKey), /// Interact with multiple Workers KV key-value pairs at once #[structopt(name = "kv:bulk", setting = AppSettings::SubcommandRequiredElseHelp)] KvBulk(kv::KvBulk), /// Interact with your Workers R2 Buckets #[structopt(setting = AppSettings::SubcommandRequiredElseHelp)] R2(r2::R2), /// List or delete worker routes. #[structopt(name = "route", setting = AppSettings::SubcommandRequiredElseHelp)] Route(route::Route), /// Generate a secret that can be referenced in the worker script #[structopt(name = "secret", setting = AppSettings::SubcommandRequiredElseHelp)] Secret(secret::Secret), /// Generate a new worker project Generate { /// The name of your worker! #[structopt(index = 1, default_value = "worker")] name: String, /// A link to a GitHub template! Defaults to https://github.com/cloudflare/worker-template #[structopt(index = 2)] template: Option<String>, /// The type of project you want generated #[structopt(name = "type", long, short = "t")] target_type: Option<TargetType>, /// Initializes a Workers Sites project. Overrides 'type' and 'template' #[structopt(long, short = "s")] site: bool, }, /// Create a wrangler.toml for an existing project Init { /// The name of your worker! #[structopt(index = 1)] name: Option<String>, /// The type of project you want generated #[structopt(name = "type", long, short = "t")] target_type: Option<TargetType>, /// Initializes a Workers Sites project. Overrides `type` and `template` #[structopt(long, short = "s")] site: bool, }, /// Build your worker Build, /// Preview your code temporarily on cloudflareworkers.com Preview { /// Type of request to preview your worker with (get, post) #[structopt(index = 1, default_value = "get")] method: HttpMethod, /// URL to open in the worker preview #[structopt(short = "u", long, default_value = "https://example.com")] url: Url, /// Body string to post to your preview worker request #[structopt(index = 2)] body: Option<String>, /// Watch your project for changes and update the preview automagically #[structopt(long)] watch: bool, /// Don't open the browser on preview #[structopt(long)] headless: bool, }, /// Start a local server for developing your worker Dev { /// Host to forward requests to, defaults to the zone of project or to /// tutorial.cloudflareworkers.com if unauthenticated. #[structopt(long, short = "h")] host: Option<String>, /// IP to listen on. Defaults to 127.0.0.1 #[structopt(long, short = "i")] ip: Option<IpAddr>, /// Port to listen on. Defaults to 8787 #[structopt(long, short = "p")] port: Option<u16>, /// Sets the protocol on which the wrangler dev listens, by default this is http /// but can be set to https #[structopt(name = "local-protocol")] local_protocol: Option<Protocol>, /// Sets the protocol on which requests are sent to the host, by default this is https /// but can be set to http #[structopt(name = "upstream-protocol")] upstream_protocol: Option<Protocol>, /// Inspect the worker using Chrome DevTools #[structopt(long)] inspect: bool, /// Run wrangler dev unauthenticated #[structopt(long)] unauthenticated: bool, }, /// Publish your worker to the orange cloud #[structopt(name = "publish")] Publish { /// [deprecated] alias of wrangler publish #[structopt(long, hidden = true)] release: bool, #[structopt(possible_value = "json")] output: Option<String>, #[structopt(flatten)] migration: AdhocMigration, }, /// Authenticate Wrangler with a Cloudflare API Token or Global API Key #[structopt(name = "config")] Config { /// Use an email and global API key for authentication. /// This is not recommended; use API tokens (the default) if possible #[structopt(name = "api-key", long)] api_key: bool, /// Do not verify provided credentials before writing out Wrangler config file #[structopt(name = "no-verify", long)] no_verify: bool, }, /// Configure your workers.dev subdomain #[structopt(name = "subdomain")] Subdomain { /// The subdomain on workers.dev you'd like to reserve #[structopt(name = "name", index = 1)] name: Option<String>, }, /// Retrieve your user info and test your auth config #[structopt(name = "whoami")] Whoami, /// View a stream of logs from a published worker #[structopt(name = "tail")] Tail { /// Name of the worker to tail #[structopt(index = 1)] name: Option<String>, /// Output format for log messages #[structopt(long, short = "f", default_value = "json", possible_values = &["json", "pretty"])] format: TailFormat, /// Stops the tail after receiving the first log (useful for testing) #[structopt(long)] once: bool, /// Adds a sampling rate (0.01 for 1%) #[structopt(long = "sampling-rate", default_value = "1")] sampling_rate: f64, /// Filter by invocation status #[structopt(long, possible_values = &["ok", "error", "canceled"])] status: Vec<String>, /// Filter by HTTP method #[structopt(long)] method: Vec<String>, /// Filter by HTTP header #[structopt(long)] header: Vec<String>, /// Filter by IP address ("self" to filter your own IP address) #[structopt(long = "ip-address", parse(try_from_str = parse_ip_address))] ip_address: Vec<String>, /// Filter by a text match in console.log messages #[structopt(long)] search: Option<String>, /// Set the URL to forward log messages #[structopt(hidden = true)] url: Option<Url>, /// Deprecated, no longer used. #[structopt(hidden = true, long = "port", short = "p")] tunnel_port: Option<u16>, /// Deprecated, no longer used. #[structopt(hidden = true, long = "metrics")] metrics_port: Option<u16>, }, /// Authenticate wrangler with your Cloudflare username and password #[structopt(name = "login")] Login { /// Allows to choose set of scopes #[structopt(name = "scopes", long, possible_values = login::SCOPES_LIST.as_ref())] scopes: Vec<String>, /// List all scopes #[structopt(name = "scopes-list", long)] scopes_list: bool, }, /// Logout from your current authentication method and remove any configuration files. /// It does not logout if you have authenticated wrangler through environment variables. #[structopt(name = "logout")] Logout, } #[derive(Debug, Clone, StructOpt)] pub struct AdhocMigration { /// Allow durable objects to be created from a class in your script #[structopt(name = "new-class", long, number_of_values = 1)] new_class: Vec<String>, /// Delete all durable objects associated with a class in your script #[structopt(name = "delete-class", long, number_of_values = 1)] delete_class: Vec<String>, /// Rename a durable object class #[structopt(name = "rename-class", long, number_of_values = 2, value_names(&["from class", "to class"]))] rename_class: Vec<String>, /// Transfer all durable objects associated with a class in another script to a class in /// this script #[structopt(name = "transfer-class", long, number_of_values = 3, value_names(&["from script", "from class", "to class"]))] transfer_class: Vec<String>, /// Specify the existing migration tag for the script. #[structopt(name = "old-tag", long)] old_tag: Option<String>, /// Specify the new migration tag for the script #[structopt(name = "new-tag", long)] new_tag: Option<String>, } impl AdhocMigration { pub fn into_migrations(self) -> Option<Migrations> { let migration = DurableObjectsMigration { new_classes: self.new_class, deleted_classes: self.delete_class, renamed_classes: self .rename_class .chunks_exact(2) .map(|chunk| { let (from, to) = if let [from, to] = chunk { (from.clone(), to.clone()) } else { unreachable!("Chunks exact returned a slice with a length not equal to 2") }; RenameClass { from, to } }) .collect(), transferred_classes: self .transfer_class .chunks_exact(3) .map(|chunk| { let (from_script, from, to) = if let [from_script, from, to] = chunk { (from_script.clone(), from.clone(), to.clone()) } else { unreachable!("Chunks exact returned a slice with a length not equal to 3") }; TransferClass { from, from_script, to, } }) .collect(), }; let is_migration_empty = migration.new_classes.is_empty() && migration.deleted_classes.is_empty() && migration.renamed_classes.is_empty() && migration.transferred_classes.is_empty(); if!is_migration_empty || self.old_tag.is_some() || self.new_tag.is_some() { let migration = if!is_migration_empty { Some(Migration { durable_objects: migration, }) } else { None }; Some(Migrations::Adhoc { script_tag: MigrationTag::Unknown, provided_old_tag: self.old_tag, new_tag: self.new_tag, migration, }) } else { None } } } fn parse_ip_address(input: &str) -> Result<String, anyhow::Error> { match input { "self" => Ok(String::from("self")), address => match IpAddr::from_str(address) { Ok(_) => Ok(address.to_owned()), Err(err) => anyhow::bail!("{}: {}", err, input), }, } } #[cfg(test)] mod tests { use super::*; fn rename_class(tag: &str) -> RenameClass { RenameClass { from: format!("renameFrom{}", tag), to: format!("renameTo{}", tag), } } fn transfer_class(tag: &str) -> TransferClass { TransferClass { from: format!("transferFromClass{}", tag), from_script: format!("transferFromScript{}", tag), to: format!("transferToClass{}", tag), } } #[test] fn adhoc_migration_parsing() { let command = Cli::from_iter(&[ "wrangler", "publish", "--old-tag", "oldTag", "--new-tag", "newTag", "--new-class", "newA", "--new-class", "newB", "--delete-class", "deleteA", "--delete-class", "deleteB", "--rename-class", "renameFromA", "renameToA", "--rename-class", "renameFromB", "renameToB", "--transfer-class", "transferFromScriptA", "transferFromClassA", "transferToClassA", "--transfer-class", "transferFromScriptB", "transferFromClassB", "transferToClassB", ]) .command; if let Command::Publish { migration,.. } = command { assert_eq!( migration.into_migrations(), Some(Migrations::Adhoc { script_tag: MigrationTag::Unknown, provided_old_tag: Some(String::from("oldTag")), new_tag: Some(String::from("newTag")), migration: Some(Migration { durable_objects: DurableObjectsMigration { new_classes: vec![String::from("newA"), String::from("newB")], deleted_classes: vec![String::from("deleteA"), String::from("deleteB")], renamed_classes: vec![rename_class("A"), rename_class("B")], transferred_classes: vec![transfer_class("A"), transfer_class("B")], } }) }) ); } else { assert!(false, "Unkown command {:?}", command) } } }
pub mod subdomain; pub mod tail; pub mod whoami;
random_line_split
test.rs
// Utilities for creating test cases. use core::marker::PhantomData; use std::time::{Duration, Instant}; use std::vec::Vec; use common::errors::*; use crate::random::Rng; /* To verify no timing leaks: - Run any many different input sizes. - Verify compiler optimizations aren't making looping over many iterations too fast - Speed is linear w.r.t. num iterations. - We can even experimentally determine if algorithms are linear, quadratic, etc. - Compare average time between trials and make sure variance is lower than some constant. TODO: Add test cases to verify that this can fail sometimes. */ #[derive(Default)] pub struct TimingLeakTestCase<T> { pub data: T, pub size: usize, } /// Creates new test cases for the timing test. pub trait TimingLeakTestCaseGenerator { type Data; /// Should generate a new test case and write it into 'out'. /// - If any heap memory is involved, the new test case should re-use as /// much of the memory buffers already in 'out' as possible to avoid any /// memory location/cache related noise. /// /// Returns true if a new test case was generated or false if we ran out of /// test cases. fn next_test_case(&mut self, out: &mut TimingLeakTestCase<Self::Data>) -> bool; } /// Function which runs some code being profiled once in the calling thread. /// /// To avoid computations being pruned, this function should return the final ///'result' of the computation or some value that can only be determined after /// the computation is done. pub trait TimingLeakTestCaseRunner<T, R> = Fn(&T) -> Result<R>; /// Test wrapper for executing some caller provided code to ensure that it /// 'probably' executes in constant time regardless of which values are passed /// to it. /// /// We expect that the code should vary in execution time with the size of the /// input data (number of bytes processed) but not with the contents of those /// bytes. /// /// This performs testing purely through black box methods so we can't necessary /// fully gurantee that cache misses or branch mispredictions won't compromise /// the security of the function. /// /// The caller provides two things: /// 1. A TimingLeakTestCaseGenerator which should create a wide range of inputs /// to the code under test. There should be sufficient test cases to attempt to /// make the code under test perform very quickly or slowly. /// /// 2. A TimingLeakTestCaseRunner which takes a test case as input and runs the /// code being profiled. /// /// NOTE: This can not track any work performed on other threads. pub struct TimingLeakTest<R, Gen, Runner> { test_case_generator: Gen, test_case_runner: Runner, options: TimingLeakTestOptions, r: PhantomData<R>, } pub struct TimingLeakTestOptions { /// Number of separate sets of iterations we will run run the test case /// runner for a single test case. /// /// This must be a value that is at least 1. Setting a value > 1 will ///'measure' a single test case multiple times and will discard rounds that /// are outliers (currently only the fasest round is considered). pub num_rounds: usize, /// Number of times the test case runner will be executed in a single round. /// /// The total number of times it will be run is 'num_test_cases * num_rounds /// * num_iterations'. /// /// TODO: Automatically figure this out based on a target run time. pub num_iterations: usize, } impl TimingLeakTest<(), (), ()> { pub fn new_generator() -> TimingLeakTestBinaryGenericTestCaseGenerator { TimingLeakTestBinaryGenericTestCaseGenerator::default() } } impl<R, Gen: TimingLeakTestCaseGenerator, Runner: TimingLeakTestCaseRunner<Gen::Data, R>> TimingLeakTest<R, Gen, Runner> where Gen::Data: Default, { pub fn new( test_case_generator: Gen, test_case_runner: Runner, options: TimingLeakTestOptions, ) -> Self { Self { test_case_generator, test_case_runner, options, r: PhantomData, } } #[must_use] pub fn run(&mut self) -> Result<()> { let mut cycle_tracker = perf::CPUCycleTracker::create()?; // Check how long it takes for us to just get the number of cycles executed. let cycles_noise_floor = { let mut floor = 0; let mut last_cycles = cycle_tracker.total_cycles()?; for _ in 0..10 { let next_cycles = cycle_tracker.total_cycles()?; floor = core::cmp::max(floor, (next_cycles - last_cycles)); last_cycles = next_cycles; } floor }; let mut test_case_index = 0; let mut time_stats = StatisticsTracker::new(); let mut cycle_stats = StatisticsTracker::new(); let mut test_case = TimingLeakTestCase::default(); while self.test_case_generator.next_test_case(&mut test_case) { let mut case_time_stats = StatisticsTracker::new(); let mut case_cycle_stats = StatisticsTracker::new(); for _ in 0..self.options.num_rounds { let start = Instant::now(); let start_cycles = cycle_tracker.total_cycles()?; for _ in 0..self.options.num_iterations { self.runner_wrap(&test_case.data); } let end_cycles = cycle_tracker.total_cycles()?; let end = Instant::now(); let duration = end.duration_since(start); let cycle_duration = end_cycles - start_cycles; case_time_stats.update(duration); case_cycle_stats.update(cycle_duration); if cycle_duration < 100 * cycles_noise_floor { return Err(format_err!( "Cycle duration of {} too small relative to noise floor {}", cycle_duration, cycles_noise_floor )); } // If this is true, then most likely the test code was optimized out by the // compiler. if duration < Duration::from_millis(2) { return Err(format_err!( "Extremely short round execution time: {:?}", duration )); } // println!( // "Test case {}: {:?} : {}", // test_case_index, duration, cycle_duration // ); } time_stats.update(case_time_stats.min.unwrap()); cycle_stats.update(case_cycle_stats.min.unwrap()); test_case_index += 1; } // TODO: Check that the min cycles time is much larger than the let cycle_range = { ((cycle_stats.max.unwrap() - cycle_stats.min.unwrap()) as f64) / (cycle_stats.min.unwrap() as f64) * 100.0 }; let time_range = { let min = time_stats.min.unwrap().as_secs_f64(); let max = time_stats.max.unwrap().as_secs_f64(); (max - min) / min * 100.0 }; println!( "- Fastest round: {:?} ({} cycles)", time_stats.min.unwrap(), cycle_stats.min.unwrap() ); println!( "- Fastest iteration: {:?}", time_stats.min.unwrap() / (self.options.num_iterations as u32) ); println!("- Cycles range: {:0.2}%", cycle_range); println!("- Time range: {:0.2}%", time_range); // Must have < 1% deviation across different test inputs. if cycle_range > 1.0 { return Err(format_err!( "Cycle range between test cases too large: {:0.2}% > 1%", cycle_range )); } Ok(()) } /// Wrapper around the runner which can't be inlined to prevent /// optimizations. #[inline(never)] fn runner_wrap(&self, test_case: &Gen::Data) -> Result<R> { (self.test_case_runner)(test_case) } } #[derive(Default)] pub struct TimingLeakTestGenericTestCase { inputs: Vec<Vec<u8>>, } impl TimingLeakTestGenericTestCase { pub fn get_input(&self, idx: usize) -> &[u8] { &self.inputs[idx] } } #[derive(Default)] pub struct TimingLeakTestBinaryGenericTestCaseGenerator { inputs: Vec<Vec<Vec<u8>>>, last_position: Option<Vec<usize>>, } impl TimingLeakTestBinaryGenericTestCaseGenerator { pub fn add_input(&mut self, values: Vec<Vec<u8>>) -> usize { let idx = self.inputs.len(); self.inputs.push(values); idx } fn next_position(&self) -> Option<Vec<usize>> { for i in &self.inputs { assert!(i.len() > 0); } let mut cur = match self.last_position.clone() { Some(v) => v, None => return Some(vec![0; self.inputs.len()]), }; for i in (0..cur.len()).rev() { cur[i] += 1; if cur[i] == self.inputs[i].len() { cur[i] = 0; } else { return Some(cur); } } None } } impl TimingLeakTestCaseGenerator for TimingLeakTestBinaryGenericTestCaseGenerator { type Data = TimingLeakTestGenericTestCase; fn next_test_case( &mut self, out: &mut TimingLeakTestCase<TimingLeakTestGenericTestCase>, ) -> bool { let pos = match self.next_position() { Some(v) => v, None => return false, }; out.data.inputs.resize(pos.len(), vec![]); for i in 0..pos.len() { out.data.inputs[i].clear(); out.data.inputs[i].extend_from_slice(&self.inputs[i][pos[i]]); } self.last_position = Some(pos); true } } /// Generates synthetic data buffers whichare likely to trigger different edge /// cases and time complexities in code that is sensitive (in terms of # of bits /// set, magnitude,...) to the value of the data passed it. pub fn typical_boundary_buffers(length: usize) -> Vec<Vec<u8>>
}); if length > 1 { // Last byte set to value #1 out.push({ let mut v = vec![0u8; length]; *v.last_mut().unwrap() = 0x20; v }); // Last byte set to value #2 out.push({ let mut v = vec![0u8; length]; *v.last_mut().unwrap() = 0x03; v }); } if length > 2 { // Even bytes set. out.push({ let mut v = vec![0u8; length]; for i in (0..v.len()).step_by(2) { v[i] = i as u8 } v }); // Odd bytes set out.push({ let mut v = vec![0u8; length]; for i in (1..v.len()).step_by(2) { v[i] = i as u8 } v }); let mid_idx = length / 2; // First half set out.push({ let mut v = vec![0u8; length]; for i in 0..mid_idx { v[i] = i as u8 } v }); // Second half set out.push({ let mut v = vec![0u8; length]; for i in mid_idx..length { v[i] = i as u8 } v }); } let mut rng = crate::random::MersenneTwisterRng::mt19937(); rng.seed_u32(1234); // A few random buffers. for _ in 0..3 { out.push({ let mut v = vec![0u8; length]; rng.generate_bytes(&mut v); v }); } out } pub struct StatisticsTracker<T> { min: Option<T>, max: Option<T>, } impl<T: Ord + Copy> StatisticsTracker<T> { pub fn new() -> Self { Self { min: None, max: None, } } pub fn update(&mut self, value: T) { self.min = Some(match self.min { Some(v) => core::cmp::min(v, value), None => value, }); self.max = Some(match self.max { Some(v) => core::cmp::max(v, value), None => value, }); } } pub struct RollingMean { sum: u64, n: usize, }
{ let mut out = vec![]; // All zeros. out.push(vec![0u8; length]); // All 0xFF. out.push(vec![0xFFu8; length]); // First byte set to value #1 out.push({ let mut v = vec![0u8; length]; v[0] = 0xAB; v }); // First byte set to value #2 out.push({ let mut v = vec![0u8; length]; v[0] = 0xCD; v
identifier_body
test.rs
// Utilities for creating test cases. use core::marker::PhantomData; use std::time::{Duration, Instant}; use std::vec::Vec; use common::errors::*; use crate::random::Rng; /* To verify no timing leaks: - Run any many different input sizes. - Verify compiler optimizations aren't making looping over many iterations too fast - Speed is linear w.r.t. num iterations. - We can even experimentally determine if algorithms are linear, quadratic, etc. - Compare average time between trials and make sure variance is lower than some constant. TODO: Add test cases to verify that this can fail sometimes. */ #[derive(Default)] pub struct TimingLeakTestCase<T> { pub data: T, pub size: usize, } /// Creates new test cases for the timing test. pub trait TimingLeakTestCaseGenerator { type Data; /// Should generate a new test case and write it into 'out'. /// - If any heap memory is involved, the new test case should re-use as /// much of the memory buffers already in 'out' as possible to avoid any /// memory location/cache related noise. /// /// Returns true if a new test case was generated or false if we ran out of /// test cases. fn next_test_case(&mut self, out: &mut TimingLeakTestCase<Self::Data>) -> bool; } /// Function which runs some code being profiled once in the calling thread. /// /// To avoid computations being pruned, this function should return the final ///'result' of the computation or some value that can only be determined after /// the computation is done. pub trait TimingLeakTestCaseRunner<T, R> = Fn(&T) -> Result<R>; /// Test wrapper for executing some caller provided code to ensure that it /// 'probably' executes in constant time regardless of which values are passed /// to it. /// /// We expect that the code should vary in execution time with the size of the /// input data (number of bytes processed) but not with the contents of those /// bytes. /// /// This performs testing purely through black box methods so we can't necessary /// fully gurantee that cache misses or branch mispredictions won't compromise /// the security of the function. /// /// The caller provides two things: /// 1. A TimingLeakTestCaseGenerator which should create a wide range of inputs /// to the code under test. There should be sufficient test cases to attempt to /// make the code under test perform very quickly or slowly. ///
/// code being profiled. /// /// NOTE: This can not track any work performed on other threads. pub struct TimingLeakTest<R, Gen, Runner> { test_case_generator: Gen, test_case_runner: Runner, options: TimingLeakTestOptions, r: PhantomData<R>, } pub struct TimingLeakTestOptions { /// Number of separate sets of iterations we will run run the test case /// runner for a single test case. /// /// This must be a value that is at least 1. Setting a value > 1 will ///'measure' a single test case multiple times and will discard rounds that /// are outliers (currently only the fasest round is considered). pub num_rounds: usize, /// Number of times the test case runner will be executed in a single round. /// /// The total number of times it will be run is 'num_test_cases * num_rounds /// * num_iterations'. /// /// TODO: Automatically figure this out based on a target run time. pub num_iterations: usize, } impl TimingLeakTest<(), (), ()> { pub fn new_generator() -> TimingLeakTestBinaryGenericTestCaseGenerator { TimingLeakTestBinaryGenericTestCaseGenerator::default() } } impl<R, Gen: TimingLeakTestCaseGenerator, Runner: TimingLeakTestCaseRunner<Gen::Data, R>> TimingLeakTest<R, Gen, Runner> where Gen::Data: Default, { pub fn new( test_case_generator: Gen, test_case_runner: Runner, options: TimingLeakTestOptions, ) -> Self { Self { test_case_generator, test_case_runner, options, r: PhantomData, } } #[must_use] pub fn run(&mut self) -> Result<()> { let mut cycle_tracker = perf::CPUCycleTracker::create()?; // Check how long it takes for us to just get the number of cycles executed. let cycles_noise_floor = { let mut floor = 0; let mut last_cycles = cycle_tracker.total_cycles()?; for _ in 0..10 { let next_cycles = cycle_tracker.total_cycles()?; floor = core::cmp::max(floor, (next_cycles - last_cycles)); last_cycles = next_cycles; } floor }; let mut test_case_index = 0; let mut time_stats = StatisticsTracker::new(); let mut cycle_stats = StatisticsTracker::new(); let mut test_case = TimingLeakTestCase::default(); while self.test_case_generator.next_test_case(&mut test_case) { let mut case_time_stats = StatisticsTracker::new(); let mut case_cycle_stats = StatisticsTracker::new(); for _ in 0..self.options.num_rounds { let start = Instant::now(); let start_cycles = cycle_tracker.total_cycles()?; for _ in 0..self.options.num_iterations { self.runner_wrap(&test_case.data); } let end_cycles = cycle_tracker.total_cycles()?; let end = Instant::now(); let duration = end.duration_since(start); let cycle_duration = end_cycles - start_cycles; case_time_stats.update(duration); case_cycle_stats.update(cycle_duration); if cycle_duration < 100 * cycles_noise_floor { return Err(format_err!( "Cycle duration of {} too small relative to noise floor {}", cycle_duration, cycles_noise_floor )); } // If this is true, then most likely the test code was optimized out by the // compiler. if duration < Duration::from_millis(2) { return Err(format_err!( "Extremely short round execution time: {:?}", duration )); } // println!( // "Test case {}: {:?} : {}", // test_case_index, duration, cycle_duration // ); } time_stats.update(case_time_stats.min.unwrap()); cycle_stats.update(case_cycle_stats.min.unwrap()); test_case_index += 1; } // TODO: Check that the min cycles time is much larger than the let cycle_range = { ((cycle_stats.max.unwrap() - cycle_stats.min.unwrap()) as f64) / (cycle_stats.min.unwrap() as f64) * 100.0 }; let time_range = { let min = time_stats.min.unwrap().as_secs_f64(); let max = time_stats.max.unwrap().as_secs_f64(); (max - min) / min * 100.0 }; println!( "- Fastest round: {:?} ({} cycles)", time_stats.min.unwrap(), cycle_stats.min.unwrap() ); println!( "- Fastest iteration: {:?}", time_stats.min.unwrap() / (self.options.num_iterations as u32) ); println!("- Cycles range: {:0.2}%", cycle_range); println!("- Time range: {:0.2}%", time_range); // Must have < 1% deviation across different test inputs. if cycle_range > 1.0 { return Err(format_err!( "Cycle range between test cases too large: {:0.2}% > 1%", cycle_range )); } Ok(()) } /// Wrapper around the runner which can't be inlined to prevent /// optimizations. #[inline(never)] fn runner_wrap(&self, test_case: &Gen::Data) -> Result<R> { (self.test_case_runner)(test_case) } } #[derive(Default)] pub struct TimingLeakTestGenericTestCase { inputs: Vec<Vec<u8>>, } impl TimingLeakTestGenericTestCase { pub fn get_input(&self, idx: usize) -> &[u8] { &self.inputs[idx] } } #[derive(Default)] pub struct TimingLeakTestBinaryGenericTestCaseGenerator { inputs: Vec<Vec<Vec<u8>>>, last_position: Option<Vec<usize>>, } impl TimingLeakTestBinaryGenericTestCaseGenerator { pub fn add_input(&mut self, values: Vec<Vec<u8>>) -> usize { let idx = self.inputs.len(); self.inputs.push(values); idx } fn next_position(&self) -> Option<Vec<usize>> { for i in &self.inputs { assert!(i.len() > 0); } let mut cur = match self.last_position.clone() { Some(v) => v, None => return Some(vec![0; self.inputs.len()]), }; for i in (0..cur.len()).rev() { cur[i] += 1; if cur[i] == self.inputs[i].len() { cur[i] = 0; } else { return Some(cur); } } None } } impl TimingLeakTestCaseGenerator for TimingLeakTestBinaryGenericTestCaseGenerator { type Data = TimingLeakTestGenericTestCase; fn next_test_case( &mut self, out: &mut TimingLeakTestCase<TimingLeakTestGenericTestCase>, ) -> bool { let pos = match self.next_position() { Some(v) => v, None => return false, }; out.data.inputs.resize(pos.len(), vec![]); for i in 0..pos.len() { out.data.inputs[i].clear(); out.data.inputs[i].extend_from_slice(&self.inputs[i][pos[i]]); } self.last_position = Some(pos); true } } /// Generates synthetic data buffers whichare likely to trigger different edge /// cases and time complexities in code that is sensitive (in terms of # of bits /// set, magnitude,...) to the value of the data passed it. pub fn typical_boundary_buffers(length: usize) -> Vec<Vec<u8>> { let mut out = vec![]; // All zeros. out.push(vec![0u8; length]); // All 0xFF. out.push(vec![0xFFu8; length]); // First byte set to value #1 out.push({ let mut v = vec![0u8; length]; v[0] = 0xAB; v }); // First byte set to value #2 out.push({ let mut v = vec![0u8; length]; v[0] = 0xCD; v }); if length > 1 { // Last byte set to value #1 out.push({ let mut v = vec![0u8; length]; *v.last_mut().unwrap() = 0x20; v }); // Last byte set to value #2 out.push({ let mut v = vec![0u8; length]; *v.last_mut().unwrap() = 0x03; v }); } if length > 2 { // Even bytes set. out.push({ let mut v = vec![0u8; length]; for i in (0..v.len()).step_by(2) { v[i] = i as u8 } v }); // Odd bytes set out.push({ let mut v = vec![0u8; length]; for i in (1..v.len()).step_by(2) { v[i] = i as u8 } v }); let mid_idx = length / 2; // First half set out.push({ let mut v = vec![0u8; length]; for i in 0..mid_idx { v[i] = i as u8 } v }); // Second half set out.push({ let mut v = vec![0u8; length]; for i in mid_idx..length { v[i] = i as u8 } v }); } let mut rng = crate::random::MersenneTwisterRng::mt19937(); rng.seed_u32(1234); // A few random buffers. for _ in 0..3 { out.push({ let mut v = vec![0u8; length]; rng.generate_bytes(&mut v); v }); } out } pub struct StatisticsTracker<T> { min: Option<T>, max: Option<T>, } impl<T: Ord + Copy> StatisticsTracker<T> { pub fn new() -> Self { Self { min: None, max: None, } } pub fn update(&mut self, value: T) { self.min = Some(match self.min { Some(v) => core::cmp::min(v, value), None => value, }); self.max = Some(match self.max { Some(v) => core::cmp::max(v, value), None => value, }); } } pub struct RollingMean { sum: u64, n: usize, }
/// 2. A TimingLeakTestCaseRunner which takes a test case as input and runs the
random_line_split
test.rs
// Utilities for creating test cases. use core::marker::PhantomData; use std::time::{Duration, Instant}; use std::vec::Vec; use common::errors::*; use crate::random::Rng; /* To verify no timing leaks: - Run any many different input sizes. - Verify compiler optimizations aren't making looping over many iterations too fast - Speed is linear w.r.t. num iterations. - We can even experimentally determine if algorithms are linear, quadratic, etc. - Compare average time between trials and make sure variance is lower than some constant. TODO: Add test cases to verify that this can fail sometimes. */ #[derive(Default)] pub struct TimingLeakTestCase<T> { pub data: T, pub size: usize, } /// Creates new test cases for the timing test. pub trait TimingLeakTestCaseGenerator { type Data; /// Should generate a new test case and write it into 'out'. /// - If any heap memory is involved, the new test case should re-use as /// much of the memory buffers already in 'out' as possible to avoid any /// memory location/cache related noise. /// /// Returns true if a new test case was generated or false if we ran out of /// test cases. fn next_test_case(&mut self, out: &mut TimingLeakTestCase<Self::Data>) -> bool; } /// Function which runs some code being profiled once in the calling thread. /// /// To avoid computations being pruned, this function should return the final ///'result' of the computation or some value that can only be determined after /// the computation is done. pub trait TimingLeakTestCaseRunner<T, R> = Fn(&T) -> Result<R>; /// Test wrapper for executing some caller provided code to ensure that it /// 'probably' executes in constant time regardless of which values are passed /// to it. /// /// We expect that the code should vary in execution time with the size of the /// input data (number of bytes processed) but not with the contents of those /// bytes. /// /// This performs testing purely through black box methods so we can't necessary /// fully gurantee that cache misses or branch mispredictions won't compromise /// the security of the function. /// /// The caller provides two things: /// 1. A TimingLeakTestCaseGenerator which should create a wide range of inputs /// to the code under test. There should be sufficient test cases to attempt to /// make the code under test perform very quickly or slowly. /// /// 2. A TimingLeakTestCaseRunner which takes a test case as input and runs the /// code being profiled. /// /// NOTE: This can not track any work performed on other threads. pub struct TimingLeakTest<R, Gen, Runner> { test_case_generator: Gen, test_case_runner: Runner, options: TimingLeakTestOptions, r: PhantomData<R>, } pub struct TimingLeakTestOptions { /// Number of separate sets of iterations we will run run the test case /// runner for a single test case. /// /// This must be a value that is at least 1. Setting a value > 1 will ///'measure' a single test case multiple times and will discard rounds that /// are outliers (currently only the fasest round is considered). pub num_rounds: usize, /// Number of times the test case runner will be executed in a single round. /// /// The total number of times it will be run is 'num_test_cases * num_rounds /// * num_iterations'. /// /// TODO: Automatically figure this out based on a target run time. pub num_iterations: usize, } impl TimingLeakTest<(), (), ()> { pub fn new_generator() -> TimingLeakTestBinaryGenericTestCaseGenerator { TimingLeakTestBinaryGenericTestCaseGenerator::default() } } impl<R, Gen: TimingLeakTestCaseGenerator, Runner: TimingLeakTestCaseRunner<Gen::Data, R>> TimingLeakTest<R, Gen, Runner> where Gen::Data: Default, { pub fn new( test_case_generator: Gen, test_case_runner: Runner, options: TimingLeakTestOptions, ) -> Self { Self { test_case_generator, test_case_runner, options, r: PhantomData, } } #[must_use] pub fn run(&mut self) -> Result<()> { let mut cycle_tracker = perf::CPUCycleTracker::create()?; // Check how long it takes for us to just get the number of cycles executed. let cycles_noise_floor = { let mut floor = 0; let mut last_cycles = cycle_tracker.total_cycles()?; for _ in 0..10 { let next_cycles = cycle_tracker.total_cycles()?; floor = core::cmp::max(floor, (next_cycles - last_cycles)); last_cycles = next_cycles; } floor }; let mut test_case_index = 0; let mut time_stats = StatisticsTracker::new(); let mut cycle_stats = StatisticsTracker::new(); let mut test_case = TimingLeakTestCase::default(); while self.test_case_generator.next_test_case(&mut test_case) { let mut case_time_stats = StatisticsTracker::new(); let mut case_cycle_stats = StatisticsTracker::new(); for _ in 0..self.options.num_rounds { let start = Instant::now(); let start_cycles = cycle_tracker.total_cycles()?; for _ in 0..self.options.num_iterations { self.runner_wrap(&test_case.data); } let end_cycles = cycle_tracker.total_cycles()?; let end = Instant::now(); let duration = end.duration_since(start); let cycle_duration = end_cycles - start_cycles; case_time_stats.update(duration); case_cycle_stats.update(cycle_duration); if cycle_duration < 100 * cycles_noise_floor { return Err(format_err!( "Cycle duration of {} too small relative to noise floor {}", cycle_duration, cycles_noise_floor )); } // If this is true, then most likely the test code was optimized out by the // compiler. if duration < Duration::from_millis(2) { return Err(format_err!( "Extremely short round execution time: {:?}", duration )); } // println!( // "Test case {}: {:?} : {}", // test_case_index, duration, cycle_duration // ); } time_stats.update(case_time_stats.min.unwrap()); cycle_stats.update(case_cycle_stats.min.unwrap()); test_case_index += 1; } // TODO: Check that the min cycles time is much larger than the let cycle_range = { ((cycle_stats.max.unwrap() - cycle_stats.min.unwrap()) as f64) / (cycle_stats.min.unwrap() as f64) * 100.0 }; let time_range = { let min = time_stats.min.unwrap().as_secs_f64(); let max = time_stats.max.unwrap().as_secs_f64(); (max - min) / min * 100.0 }; println!( "- Fastest round: {:?} ({} cycles)", time_stats.min.unwrap(), cycle_stats.min.unwrap() ); println!( "- Fastest iteration: {:?}", time_stats.min.unwrap() / (self.options.num_iterations as u32) ); println!("- Cycles range: {:0.2}%", cycle_range); println!("- Time range: {:0.2}%", time_range); // Must have < 1% deviation across different test inputs. if cycle_range > 1.0 { return Err(format_err!( "Cycle range between test cases too large: {:0.2}% > 1%", cycle_range )); } Ok(()) } /// Wrapper around the runner which can't be inlined to prevent /// optimizations. #[inline(never)] fn runner_wrap(&self, test_case: &Gen::Data) -> Result<R> { (self.test_case_runner)(test_case) } } #[derive(Default)] pub struct TimingLeakTestGenericTestCase { inputs: Vec<Vec<u8>>, } impl TimingLeakTestGenericTestCase { pub fn get_input(&self, idx: usize) -> &[u8] { &self.inputs[idx] } } #[derive(Default)] pub struct TimingLeakTestBinaryGenericTestCaseGenerator { inputs: Vec<Vec<Vec<u8>>>, last_position: Option<Vec<usize>>, } impl TimingLeakTestBinaryGenericTestCaseGenerator { pub fn add_input(&mut self, values: Vec<Vec<u8>>) -> usize { let idx = self.inputs.len(); self.inputs.push(values); idx } fn next_position(&self) -> Option<Vec<usize>> { for i in &self.inputs { assert!(i.len() > 0); } let mut cur = match self.last_position.clone() { Some(v) => v, None => return Some(vec![0; self.inputs.len()]), }; for i in (0..cur.len()).rev() { cur[i] += 1; if cur[i] == self.inputs[i].len() { cur[i] = 0; } else { return Some(cur); } } None } } impl TimingLeakTestCaseGenerator for TimingLeakTestBinaryGenericTestCaseGenerator { type Data = TimingLeakTestGenericTestCase; fn next_test_case( &mut self, out: &mut TimingLeakTestCase<TimingLeakTestGenericTestCase>, ) -> bool { let pos = match self.next_position() { Some(v) => v, None => return false, }; out.data.inputs.resize(pos.len(), vec![]); for i in 0..pos.len() { out.data.inputs[i].clear(); out.data.inputs[i].extend_from_slice(&self.inputs[i][pos[i]]); } self.last_position = Some(pos); true } } /// Generates synthetic data buffers whichare likely to trigger different edge /// cases and time complexities in code that is sensitive (in terms of # of bits /// set, magnitude,...) to the value of the data passed it. pub fn typical_boundary_buffers(length: usize) -> Vec<Vec<u8>> { let mut out = vec![]; // All zeros. out.push(vec![0u8; length]); // All 0xFF. out.push(vec![0xFFu8; length]); // First byte set to value #1 out.push({ let mut v = vec![0u8; length]; v[0] = 0xAB; v }); // First byte set to value #2 out.push({ let mut v = vec![0u8; length]; v[0] = 0xCD; v }); if length > 1 { // Last byte set to value #1 out.push({ let mut v = vec![0u8; length]; *v.last_mut().unwrap() = 0x20; v }); // Last byte set to value #2 out.push({ let mut v = vec![0u8; length]; *v.last_mut().unwrap() = 0x03; v }); } if length > 2 { // Even bytes set. out.push({ let mut v = vec![0u8; length]; for i in (0..v.len()).step_by(2) { v[i] = i as u8 } v }); // Odd bytes set out.push({ let mut v = vec![0u8; length]; for i in (1..v.len()).step_by(2) { v[i] = i as u8 } v }); let mid_idx = length / 2; // First half set out.push({ let mut v = vec![0u8; length]; for i in 0..mid_idx { v[i] = i as u8 } v }); // Second half set out.push({ let mut v = vec![0u8; length]; for i in mid_idx..length { v[i] = i as u8 } v }); } let mut rng = crate::random::MersenneTwisterRng::mt19937(); rng.seed_u32(1234); // A few random buffers. for _ in 0..3 { out.push({ let mut v = vec![0u8; length]; rng.generate_bytes(&mut v); v }); } out } pub struct StatisticsTracker<T> { min: Option<T>, max: Option<T>, } impl<T: Ord + Copy> StatisticsTracker<T> { pub fn new() -> Self { Self { min: None, max: None, } } pub fn update(&mut self, value: T) { self.min = Some(match self.min { Some(v) => core::cmp::min(v, value), None => value, }); self.max = Some(match self.max { Some(v) => core::cmp::max(v, value), None => value, }); } } pub struct
{ sum: u64, n: usize, }
RollingMean
identifier_name
tags.rs
use std::fs::{File, OpenOptions}; use std::io::{Read, Write}; use std::process::Command; use std::collections::HashSet; use std::path::{PathBuf, Path}; use app_result::{AppResult, app_err_msg, app_err_missing_src}; use types::{Tags, TagsKind, SourceKind}; use path_ext::PathExt; use config::Config; use dirs::{ rusty_tags_cache_dir, cargo_git_src_dir, cargo_crates_io_src_dir, glob_path }; /// Checks if there's already a tags file for `source` /// and if not it's creating a new tags file and returning it. pub fn update_tags(config: &Config, source: &SourceKind) -> AppResult<Tags> { let src_tags = try!(cached_tags_file(&config.tags_kind, source)); let src_dir = try!(find_src_dir(source)); if src_tags.as_path().is_file() &&! config.force_recreate { return Ok(Tags::new(&src_dir, &src_tags, true)); } try!(create_tags(config, &[&src_dir], &src_tags)); Ok(Tags::new(&src_dir, &src_tags, false)) } /// Does the same thing as `update_tags`, but also checks if the `lib.rs` /// file of the library has public reexports of external crates. If /// that's the case, then the tags of the public reexported external /// crates are merged into the tags of the library. pub fn
(config: &Config, source: &SourceKind, dependencies: &Vec<SourceKind>) -> AppResult<Tags> { let lib_tags = try!(update_tags(config, source)); if lib_tags.is_up_to_date(&config.tags_kind) &&! config.force_recreate { return Ok(lib_tags); } let reexp_crates = try!(find_reexported_crates(&lib_tags.src_dir)); if reexp_crates.is_empty() { return Ok(lib_tags); } if config.verbose { println!("Found public reexports in '{}' of:", source.get_lib_name()); for rcrate in reexp_crates.iter() { println!(" {}", rcrate); } println!(""); } let mut crate_tags = Vec::<PathBuf>::new(); for rcrate in reexp_crates.iter() { if let Some(crate_dep) = dependencies.iter().find(|d| d.get_lib_name() == *rcrate) { crate_tags.push(try!(update_tags(config, crate_dep)).tags_file.clone()); } } if crate_tags.is_empty() { return Ok(lib_tags); } crate_tags.push(lib_tags.tags_file.clone()); try!(merge_tags(config, &crate_tags, &lib_tags.tags_file)); Ok(lib_tags) } /// merges `tag_files` into `into_tag_file` pub fn merge_tags(config: &Config, tag_files: &Vec<PathBuf>, into_tag_file: &Path) -> AppResult<()> { if config.verbose { println!("Merging...\n tags:"); for file in tag_files.iter() { println!(" {}", file.display()); } println!("\n into:\n {}\n", into_tag_file.display()); } match config.tags_kind { TagsKind::Vi => { let mut file_contents: Vec<String> = Vec::new(); for file in tag_files.iter() { let mut file = try!(File::open(file)); let mut contents = String::new(); try!(file.read_to_string(&mut contents)); file_contents.push(contents); } let mut merged_lines: Vec<&str> = Vec::with_capacity(100_000); for content in file_contents.iter() { for line in content.lines() { if let Some(chr) = line.chars().nth(0) { if chr!= '!' { merged_lines.push(line); } } } } merged_lines.sort(); merged_lines.dedup(); let mut tag_file = try!( OpenOptions::new() .create(true) .truncate(true) .read(true) .write(true) .open(into_tag_file) ); try!(tag_file.write_fmt(format_args!("{}\n", "!_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;\" to lines/"))); try!(tag_file.write_fmt(format_args!("{}\n", "!_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/"))); for line in merged_lines.iter() { try!(tag_file.write_fmt(format_args!("{}\n", *line))); } }, TagsKind::Emacs => { let mut tag_file = try!( OpenOptions::new() .create(true) .append(true) .read(true) .write(true) .open(into_tag_file) ); for file in tag_files.iter() { if file.as_path()!= into_tag_file { try!(tag_file.write_fmt(format_args!("{},include\n", file.display()))); } } } } Ok(()) } /// creates tags recursive for the directory hierarchy starting at `src_dirs` /// and writes them to `tags_file` pub fn create_tags<P: AsRef<Path>>(config: &Config, src_dirs: &[P], tags_file: P) -> AppResult<()> { let mut cmd = Command::new("ctags"); config.tags_kind.ctags_option().map(|opt| { cmd.arg(opt); () }); cmd.arg("--recurse") .arg("--languages=Rust") .arg("--langdef=Rust") .arg("--langmap=Rust:.rs") .arg("--regex-Rust=/^[ \\t]*(#\\[[^\\]]\\][ \\t]*)*(pub[ \\t]+)?(extern[ \\t]+)?(\"[^\"]+\"[ \\t]+)?(unsafe[ \\t]+)?fn[ \\t]+([a-zA-Z0-9_]+)/\\6/f,functions,function definitions/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?type[ \\t]+([a-zA-Z0-9_]+)/\\2/T,types,type definitions/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?enum[ \\t]+([a-zA-Z0-9_]+)/\\2/g,enum,enumeration names/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?struct[ \\t]+([a-zA-Z0-9_]+)/\\2/s,structure names/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?mod[ \\t]+([a-zA-Z0-9_]+)\\s*\\{/\\2/m,modules,module names/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?(static|const)[ \\t]+([a-zA-Z0-9_]+)/\\3/c,consts,static constants/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?trait[ \\t]+([a-zA-Z0-9_]+)/\\2/t,traits,traits/") .arg("--regex-Rust=/^[ \\t]*macro_rules![ \\t]+([a-zA-Z0-9_]+)/\\1/d,macros,macro definitions/") .arg("-o") .arg(tags_file.as_ref()); for dir in src_dirs { cmd.arg(dir.as_ref()); } if config.verbose { println!("Creating tags...\n for source:"); for dir in src_dirs { println!(" {}", dir.as_ref().display()); } println!("\n cached at:\n {}\n", tags_file.as_ref().display()); } try!(cmd.output()); Ok(()) } /// find the source directory of `source`, for git sources the directories /// in `~/.cargo/git/checkouts` are considered and for crates.io sources /// the directories in `~/.cargo/registry/src/github.com-*` are considered fn find_src_dir(source: &SourceKind) -> AppResult<PathBuf> { match *source { SourceKind::Git { ref lib_name, ref commit_hash } => { let mut lib_src = lib_name.clone(); lib_src.push_str("-*"); let mut src_dir = try!(cargo_git_src_dir().map(Path::to_path_buf)); src_dir.push(&lib_src); src_dir.push("master"); let src_paths = try!(glob_path(&format!("{}", src_dir.display()))); for src_path in src_paths { if let Ok(path) = src_path { let src_commit_hash = try!(get_commit_hash(&path)); if *commit_hash == src_commit_hash { return Ok(path); } } } // the git repository name hasn't to match the name of the library, // so here we're just going through all git directories and searching // for the one with a matching commit hash let mut src_dir = try!(cargo_git_src_dir().map(Path::to_path_buf)); src_dir.push("*"); src_dir.push("master"); let src_paths = try!(glob_path(&format!("{}", src_dir.display()))); for src_path in src_paths { if let Ok(path) = src_path { let src_commit_hash = try!(get_commit_hash(&path)); if *commit_hash == src_commit_hash { return Ok(path); } } } Err(app_err_missing_src(source)) }, SourceKind::CratesIo { ref lib_name, ref version } => { let mut lib_src = lib_name.clone(); lib_src.push('-'); lib_src.push_str(&**version); let mut src_dir = try!(cargo_crates_io_src_dir().map(Path::to_path_buf)); src_dir.push(&lib_src); if! src_dir.is_dir() { return Err(app_err_missing_src(source)); } Ok(src_dir) }, SourceKind::Path { ref path,.. } => { if! path.is_dir() { return Err(app_err_missing_src(source)); } Ok(path.clone()) } } } /// returns the position and name of the cached tags file of `source` fn cached_tags_file(tags_kind: &TagsKind, source: &SourceKind) -> AppResult<PathBuf> { match *source { SourceKind::Git {.. } | SourceKind::CratesIo {.. } => { let mut tags_file = try!(rusty_tags_cache_dir().map(Path::to_path_buf)); tags_file.push(&source.tags_file_name(tags_kind)); Ok(tags_file) }, SourceKind::Path { ref path,.. } => { let mut tags_file = path.clone(); tags_file.push(&source.tags_file_name(tags_kind)); Ok(tags_file) } } } type CrateName = String; /// searches in the file `<src_dir>/src/lib.rs` for external crates /// that are reexpored and returns their names fn find_reexported_crates(src_dir: &Path) -> AppResult<Vec<CrateName>> { let mut lib_file = src_dir.to_path_buf(); lib_file.push("src"); lib_file.push("lib.rs"); if! lib_file.is_file() { return Ok(Vec::new()); } let contents = { let mut file = try!(File::open(&lib_file)); let mut contents = String::new(); try!(file.read_to_string(&mut contents)); contents }; let lines = contents.lines(); type ModuleName = String; let mut pub_uses = HashSet::<ModuleName>::new(); #[derive(Eq, PartialEq, Hash)] struct ExternCrate<'a> { name: &'a str, as_name: &'a str } let mut extern_crates = HashSet::<ExternCrate>::new(); for line in lines { let items = line.trim_matches(';').split(' ').collect::<Vec<&str>>(); if items.len() < 3 { continue; } if items[0] == "pub" && items[1] == "use" { let mods = items[2].split("::").collect::<Vec<&str>>(); if mods.len() >= 1 { pub_uses.insert(mods[0].to_string()); } } if items[0] == "extern" && items[1] == "crate" { if items.len() == 3 { extern_crates.insert(ExternCrate { name: items[2].trim_matches('"'), as_name: items[2] }); } else if items.len() == 5 && items[3] == "as" { extern_crates.insert(ExternCrate { name: items[2].trim_matches('"'), as_name: items[4] }); } } } let mut reexp_crates = Vec::<CrateName>::new(); for extern_crate in extern_crates.iter() { if pub_uses.contains(extern_crate.as_name) { reexp_crates.push(extern_crate.name.to_string()); } } Ok(reexp_crates) } /// get the commit hash of the current `HEAD` of the git repository located at `git_dir` fn get_commit_hash(git_dir: &Path) -> AppResult<String> { let mut cmd = Command::new("git"); cmd.current_dir(git_dir) .arg("rev-parse") .arg("HEAD"); let out = try!(cmd.output()); String::from_utf8(out.stdout) .map(|s| s.trim().to_string()) .map_err(|_| app_err_msg("Couldn't convert 'git rev-parse HEAD' output to utf8!".to_string())) }
update_tags_and_check_for_reexports
identifier_name
tags.rs
use std::fs::{File, OpenOptions}; use std::io::{Read, Write}; use std::process::Command; use std::collections::HashSet; use std::path::{PathBuf, Path}; use app_result::{AppResult, app_err_msg, app_err_missing_src}; use types::{Tags, TagsKind, SourceKind}; use path_ext::PathExt; use config::Config; use dirs::{ rusty_tags_cache_dir, cargo_git_src_dir, cargo_crates_io_src_dir, glob_path }; /// Checks if there's already a tags file for `source` /// and if not it's creating a new tags file and returning it. pub fn update_tags(config: &Config, source: &SourceKind) -> AppResult<Tags> { let src_tags = try!(cached_tags_file(&config.tags_kind, source)); let src_dir = try!(find_src_dir(source)); if src_tags.as_path().is_file() &&! config.force_recreate { return Ok(Tags::new(&src_dir, &src_tags, true)); } try!(create_tags(config, &[&src_dir], &src_tags)); Ok(Tags::new(&src_dir, &src_tags, false)) } /// Does the same thing as `update_tags`, but also checks if the `lib.rs` /// file of the library has public reexports of external crates. If /// that's the case, then the tags of the public reexported external /// crates are merged into the tags of the library. pub fn update_tags_and_check_for_reexports(config: &Config, source: &SourceKind, dependencies: &Vec<SourceKind>) -> AppResult<Tags> { let lib_tags = try!(update_tags(config, source)); if lib_tags.is_up_to_date(&config.tags_kind) &&! config.force_recreate { return Ok(lib_tags); } let reexp_crates = try!(find_reexported_crates(&lib_tags.src_dir)); if reexp_crates.is_empty() { return Ok(lib_tags); } if config.verbose { println!("Found public reexports in '{}' of:", source.get_lib_name()); for rcrate in reexp_crates.iter() { println!(" {}", rcrate); } println!(""); } let mut crate_tags = Vec::<PathBuf>::new(); for rcrate in reexp_crates.iter() { if let Some(crate_dep) = dependencies.iter().find(|d| d.get_lib_name() == *rcrate) { crate_tags.push(try!(update_tags(config, crate_dep)).tags_file.clone()); } } if crate_tags.is_empty() { return Ok(lib_tags); } crate_tags.push(lib_tags.tags_file.clone()); try!(merge_tags(config, &crate_tags, &lib_tags.tags_file)); Ok(lib_tags) } /// merges `tag_files` into `into_tag_file` pub fn merge_tags(config: &Config, tag_files: &Vec<PathBuf>, into_tag_file: &Path) -> AppResult<()> { if config.verbose { println!("Merging...\n tags:"); for file in tag_files.iter() { println!(" {}", file.display()); } println!("\n into:\n {}\n", into_tag_file.display()); } match config.tags_kind { TagsKind::Vi => { let mut file_contents: Vec<String> = Vec::new(); for file in tag_files.iter() { let mut file = try!(File::open(file)); let mut contents = String::new(); try!(file.read_to_string(&mut contents)); file_contents.push(contents); } let mut merged_lines: Vec<&str> = Vec::with_capacity(100_000); for content in file_contents.iter() { for line in content.lines() { if let Some(chr) = line.chars().nth(0) { if chr!= '!' { merged_lines.push(line); } } } } merged_lines.sort(); merged_lines.dedup(); let mut tag_file = try!( OpenOptions::new() .create(true) .truncate(true) .read(true) .write(true) .open(into_tag_file) ); try!(tag_file.write_fmt(format_args!("{}\n", "!_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;\" to lines/"))); try!(tag_file.write_fmt(format_args!("{}\n", "!_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/"))); for line in merged_lines.iter() { try!(tag_file.write_fmt(format_args!("{}\n", *line))); } }, TagsKind::Emacs => { let mut tag_file = try!( OpenOptions::new() .create(true) .append(true) .read(true) .write(true) .open(into_tag_file) ); for file in tag_files.iter() { if file.as_path()!= into_tag_file { try!(tag_file.write_fmt(format_args!("{},include\n", file.display()))); } } } } Ok(()) } /// creates tags recursive for the directory hierarchy starting at `src_dirs` /// and writes them to `tags_file` pub fn create_tags<P: AsRef<Path>>(config: &Config, src_dirs: &[P], tags_file: P) -> AppResult<()> { let mut cmd = Command::new("ctags"); config.tags_kind.ctags_option().map(|opt| { cmd.arg(opt); () }); cmd.arg("--recurse") .arg("--languages=Rust") .arg("--langdef=Rust") .arg("--langmap=Rust:.rs") .arg("--regex-Rust=/^[ \\t]*(#\\[[^\\]]\\][ \\t]*)*(pub[ \\t]+)?(extern[ \\t]+)?(\"[^\"]+\"[ \\t]+)?(unsafe[ \\t]+)?fn[ \\t]+([a-zA-Z0-9_]+)/\\6/f,functions,function definitions/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?type[ \\t]+([a-zA-Z0-9_]+)/\\2/T,types,type definitions/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?enum[ \\t]+([a-zA-Z0-9_]+)/\\2/g,enum,enumeration names/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?struct[ \\t]+([a-zA-Z0-9_]+)/\\2/s,structure names/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?mod[ \\t]+([a-zA-Z0-9_]+)\\s*\\{/\\2/m,modules,module names/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?(static|const)[ \\t]+([a-zA-Z0-9_]+)/\\3/c,consts,static constants/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?trait[ \\t]+([a-zA-Z0-9_]+)/\\2/t,traits,traits/") .arg("--regex-Rust=/^[ \\t]*macro_rules![ \\t]+([a-zA-Z0-9_]+)/\\1/d,macros,macro definitions/") .arg("-o") .arg(tags_file.as_ref()); for dir in src_dirs { cmd.arg(dir.as_ref()); } if config.verbose { println!("Creating tags...\n for source:"); for dir in src_dirs { println!(" {}", dir.as_ref().display()); } println!("\n cached at:\n {}\n", tags_file.as_ref().display()); } try!(cmd.output()); Ok(()) } /// find the source directory of `source`, for git sources the directories /// in `~/.cargo/git/checkouts` are considered and for crates.io sources /// the directories in `~/.cargo/registry/src/github.com-*` are considered fn find_src_dir(source: &SourceKind) -> AppResult<PathBuf> { match *source { SourceKind::Git { ref lib_name, ref commit_hash } => { let mut lib_src = lib_name.clone(); lib_src.push_str("-*"); let mut src_dir = try!(cargo_git_src_dir().map(Path::to_path_buf)); src_dir.push(&lib_src); src_dir.push("master"); let src_paths = try!(glob_path(&format!("{}", src_dir.display()))); for src_path in src_paths { if let Ok(path) = src_path { let src_commit_hash = try!(get_commit_hash(&path)); if *commit_hash == src_commit_hash { return Ok(path); } } } // the git repository name hasn't to match the name of the library, // so here we're just going through all git directories and searching // for the one with a matching commit hash let mut src_dir = try!(cargo_git_src_dir().map(Path::to_path_buf)); src_dir.push("*"); src_dir.push("master"); let src_paths = try!(glob_path(&format!("{}", src_dir.display()))); for src_path in src_paths { if let Ok(path) = src_path { let src_commit_hash = try!(get_commit_hash(&path)); if *commit_hash == src_commit_hash { return Ok(path); } } } Err(app_err_missing_src(source)) }, SourceKind::CratesIo { ref lib_name, ref version } => { let mut lib_src = lib_name.clone(); lib_src.push('-'); lib_src.push_str(&**version); let mut src_dir = try!(cargo_crates_io_src_dir().map(Path::to_path_buf)); src_dir.push(&lib_src); if! src_dir.is_dir() { return Err(app_err_missing_src(source)); } Ok(src_dir) }, SourceKind::Path { ref path,.. } => { if! path.is_dir() { return Err(app_err_missing_src(source)); } Ok(path.clone()) } } } /// returns the position and name of the cached tags file of `source` fn cached_tags_file(tags_kind: &TagsKind, source: &SourceKind) -> AppResult<PathBuf> { match *source { SourceKind::Git {.. } | SourceKind::CratesIo {.. } => { let mut tags_file = try!(rusty_tags_cache_dir().map(Path::to_path_buf)); tags_file.push(&source.tags_file_name(tags_kind)); Ok(tags_file) }, SourceKind::Path { ref path,.. } => { let mut tags_file = path.clone(); tags_file.push(&source.tags_file_name(tags_kind)); Ok(tags_file) } } } type CrateName = String; /// searches in the file `<src_dir>/src/lib.rs` for external crates /// that are reexpored and returns their names fn find_reexported_crates(src_dir: &Path) -> AppResult<Vec<CrateName>>
#[derive(Eq, PartialEq, Hash)] struct ExternCrate<'a> { name: &'a str, as_name: &'a str } let mut extern_crates = HashSet::<ExternCrate>::new(); for line in lines { let items = line.trim_matches(';').split(' ').collect::<Vec<&str>>(); if items.len() < 3 { continue; } if items[0] == "pub" && items[1] == "use" { let mods = items[2].split("::").collect::<Vec<&str>>(); if mods.len() >= 1 { pub_uses.insert(mods[0].to_string()); } } if items[0] == "extern" && items[1] == "crate" { if items.len() == 3 { extern_crates.insert(ExternCrate { name: items[2].trim_matches('"'), as_name: items[2] }); } else if items.len() == 5 && items[3] == "as" { extern_crates.insert(ExternCrate { name: items[2].trim_matches('"'), as_name: items[4] }); } } } let mut reexp_crates = Vec::<CrateName>::new(); for extern_crate in extern_crates.iter() { if pub_uses.contains(extern_crate.as_name) { reexp_crates.push(extern_crate.name.to_string()); } } Ok(reexp_crates) } /// get the commit hash of the current `HEAD` of the git repository located at `git_dir` fn get_commit_hash(git_dir: &Path) -> AppResult<String> { let mut cmd = Command::new("git"); cmd.current_dir(git_dir) .arg("rev-parse") .arg("HEAD"); let out = try!(cmd.output()); String::from_utf8(out.stdout) .map(|s| s.trim().to_string()) .map_err(|_| app_err_msg("Couldn't convert 'git rev-parse HEAD' output to utf8!".to_string())) }
{ let mut lib_file = src_dir.to_path_buf(); lib_file.push("src"); lib_file.push("lib.rs"); if ! lib_file.is_file() { return Ok(Vec::new()); } let contents = { let mut file = try!(File::open(&lib_file)); let mut contents = String::new(); try!(file.read_to_string(&mut contents)); contents }; let lines = contents.lines(); type ModuleName = String; let mut pub_uses = HashSet::<ModuleName>::new();
identifier_body
tags.rs
use std::fs::{File, OpenOptions}; use std::io::{Read, Write}; use std::process::Command; use std::collections::HashSet; use std::path::{PathBuf, Path}; use app_result::{AppResult, app_err_msg, app_err_missing_src}; use types::{Tags, TagsKind, SourceKind}; use path_ext::PathExt; use config::Config; use dirs::{ rusty_tags_cache_dir, cargo_git_src_dir, cargo_crates_io_src_dir, glob_path }; /// Checks if there's already a tags file for `source` /// and if not it's creating a new tags file and returning it. pub fn update_tags(config: &Config, source: &SourceKind) -> AppResult<Tags> { let src_tags = try!(cached_tags_file(&config.tags_kind, source)); let src_dir = try!(find_src_dir(source)); if src_tags.as_path().is_file() &&! config.force_recreate { return Ok(Tags::new(&src_dir, &src_tags, true)); } try!(create_tags(config, &[&src_dir], &src_tags)); Ok(Tags::new(&src_dir, &src_tags, false)) } /// Does the same thing as `update_tags`, but also checks if the `lib.rs` /// file of the library has public reexports of external crates. If /// that's the case, then the tags of the public reexported external /// crates are merged into the tags of the library. pub fn update_tags_and_check_for_reexports(config: &Config, source: &SourceKind, dependencies: &Vec<SourceKind>) -> AppResult<Tags> { let lib_tags = try!(update_tags(config, source)); if lib_tags.is_up_to_date(&config.tags_kind) &&! config.force_recreate { return Ok(lib_tags); } let reexp_crates = try!(find_reexported_crates(&lib_tags.src_dir)); if reexp_crates.is_empty() { return Ok(lib_tags); } if config.verbose { println!("Found public reexports in '{}' of:", source.get_lib_name()); for rcrate in reexp_crates.iter() { println!(" {}", rcrate); } println!(""); } let mut crate_tags = Vec::<PathBuf>::new(); for rcrate in reexp_crates.iter() { if let Some(crate_dep) = dependencies.iter().find(|d| d.get_lib_name() == *rcrate) { crate_tags.push(try!(update_tags(config, crate_dep)).tags_file.clone()); } } if crate_tags.is_empty() { return Ok(lib_tags); } crate_tags.push(lib_tags.tags_file.clone()); try!(merge_tags(config, &crate_tags, &lib_tags.tags_file)); Ok(lib_tags) } /// merges `tag_files` into `into_tag_file` pub fn merge_tags(config: &Config, tag_files: &Vec<PathBuf>, into_tag_file: &Path) -> AppResult<()> { if config.verbose { println!("Merging...\n tags:"); for file in tag_files.iter() { println!(" {}", file.display()); } println!("\n into:\n {}\n", into_tag_file.display()); } match config.tags_kind { TagsKind::Vi =>
merged_lines.sort(); merged_lines.dedup(); let mut tag_file = try!( OpenOptions::new() .create(true) .truncate(true) .read(true) .write(true) .open(into_tag_file) ); try!(tag_file.write_fmt(format_args!("{}\n", "!_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;\" to lines/"))); try!(tag_file.write_fmt(format_args!("{}\n", "!_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/"))); for line in merged_lines.iter() { try!(tag_file.write_fmt(format_args!("{}\n", *line))); } } , TagsKind::Emacs => { let mut tag_file = try!( OpenOptions::new() .create(true) .append(true) .read(true) .write(true) .open(into_tag_file) ); for file in tag_files.iter() { if file.as_path()!= into_tag_file { try!(tag_file.write_fmt(format_args!("{},include\n", file.display()))); } } } } Ok(()) } /// creates tags recursive for the directory hierarchy starting at `src_dirs` /// and writes them to `tags_file` pub fn create_tags<P: AsRef<Path>>(config: &Config, src_dirs: &[P], tags_file: P) -> AppResult<()> { let mut cmd = Command::new("ctags"); config.tags_kind.ctags_option().map(|opt| { cmd.arg(opt); () }); cmd.arg("--recurse") .arg("--languages=Rust") .arg("--langdef=Rust") .arg("--langmap=Rust:.rs") .arg("--regex-Rust=/^[ \\t]*(#\\[[^\\]]\\][ \\t]*)*(pub[ \\t]+)?(extern[ \\t]+)?(\"[^\"]+\"[ \\t]+)?(unsafe[ \\t]+)?fn[ \\t]+([a-zA-Z0-9_]+)/\\6/f,functions,function definitions/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?type[ \\t]+([a-zA-Z0-9_]+)/\\2/T,types,type definitions/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?enum[ \\t]+([a-zA-Z0-9_]+)/\\2/g,enum,enumeration names/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?struct[ \\t]+([a-zA-Z0-9_]+)/\\2/s,structure names/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?mod[ \\t]+([a-zA-Z0-9_]+)\\s*\\{/\\2/m,modules,module names/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?(static|const)[ \\t]+([a-zA-Z0-9_]+)/\\3/c,consts,static constants/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?trait[ \\t]+([a-zA-Z0-9_]+)/\\2/t,traits,traits/") .arg("--regex-Rust=/^[ \\t]*macro_rules![ \\t]+([a-zA-Z0-9_]+)/\\1/d,macros,macro definitions/") .arg("-o") .arg(tags_file.as_ref()); for dir in src_dirs { cmd.arg(dir.as_ref()); } if config.verbose { println!("Creating tags...\n for source:"); for dir in src_dirs { println!(" {}", dir.as_ref().display()); } println!("\n cached at:\n {}\n", tags_file.as_ref().display()); } try!(cmd.output()); Ok(()) } /// find the source directory of `source`, for git sources the directories /// in `~/.cargo/git/checkouts` are considered and for crates.io sources /// the directories in `~/.cargo/registry/src/github.com-*` are considered fn find_src_dir(source: &SourceKind) -> AppResult<PathBuf> { match *source { SourceKind::Git { ref lib_name, ref commit_hash } => { let mut lib_src = lib_name.clone(); lib_src.push_str("-*"); let mut src_dir = try!(cargo_git_src_dir().map(Path::to_path_buf)); src_dir.push(&lib_src); src_dir.push("master"); let src_paths = try!(glob_path(&format!("{}", src_dir.display()))); for src_path in src_paths { if let Ok(path) = src_path { let src_commit_hash = try!(get_commit_hash(&path)); if *commit_hash == src_commit_hash { return Ok(path); } } } // the git repository name hasn't to match the name of the library, // so here we're just going through all git directories and searching // for the one with a matching commit hash let mut src_dir = try!(cargo_git_src_dir().map(Path::to_path_buf)); src_dir.push("*"); src_dir.push("master"); let src_paths = try!(glob_path(&format!("{}", src_dir.display()))); for src_path in src_paths { if let Ok(path) = src_path { let src_commit_hash = try!(get_commit_hash(&path)); if *commit_hash == src_commit_hash { return Ok(path); } } } Err(app_err_missing_src(source)) }, SourceKind::CratesIo { ref lib_name, ref version } => { let mut lib_src = lib_name.clone(); lib_src.push('-'); lib_src.push_str(&**version); let mut src_dir = try!(cargo_crates_io_src_dir().map(Path::to_path_buf)); src_dir.push(&lib_src); if! src_dir.is_dir() { return Err(app_err_missing_src(source)); } Ok(src_dir) }, SourceKind::Path { ref path,.. } => { if! path.is_dir() { return Err(app_err_missing_src(source)); } Ok(path.clone()) } } } /// returns the position and name of the cached tags file of `source` fn cached_tags_file(tags_kind: &TagsKind, source: &SourceKind) -> AppResult<PathBuf> { match *source { SourceKind::Git {.. } | SourceKind::CratesIo {.. } => { let mut tags_file = try!(rusty_tags_cache_dir().map(Path::to_path_buf)); tags_file.push(&source.tags_file_name(tags_kind)); Ok(tags_file) }, SourceKind::Path { ref path,.. } => { let mut tags_file = path.clone(); tags_file.push(&source.tags_file_name(tags_kind)); Ok(tags_file) } } } type CrateName = String; /// searches in the file `<src_dir>/src/lib.rs` for external crates /// that are reexpored and returns their names fn find_reexported_crates(src_dir: &Path) -> AppResult<Vec<CrateName>> { let mut lib_file = src_dir.to_path_buf(); lib_file.push("src"); lib_file.push("lib.rs"); if! lib_file.is_file() { return Ok(Vec::new()); } let contents = { let mut file = try!(File::open(&lib_file)); let mut contents = String::new(); try!(file.read_to_string(&mut contents)); contents }; let lines = contents.lines(); type ModuleName = String; let mut pub_uses = HashSet::<ModuleName>::new(); #[derive(Eq, PartialEq, Hash)] struct ExternCrate<'a> { name: &'a str, as_name: &'a str } let mut extern_crates = HashSet::<ExternCrate>::new(); for line in lines { let items = line.trim_matches(';').split(' ').collect::<Vec<&str>>(); if items.len() < 3 { continue; } if items[0] == "pub" && items[1] == "use" { let mods = items[2].split("::").collect::<Vec<&str>>(); if mods.len() >= 1 { pub_uses.insert(mods[0].to_string()); } } if items[0] == "extern" && items[1] == "crate" { if items.len() == 3 { extern_crates.insert(ExternCrate { name: items[2].trim_matches('"'), as_name: items[2] }); } else if items.len() == 5 && items[3] == "as" { extern_crates.insert(ExternCrate { name: items[2].trim_matches('"'), as_name: items[4] }); } } } let mut reexp_crates = Vec::<CrateName>::new(); for extern_crate in extern_crates.iter() { if pub_uses.contains(extern_crate.as_name) { reexp_crates.push(extern_crate.name.to_string()); } } Ok(reexp_crates) } /// get the commit hash of the current `HEAD` of the git repository located at `git_dir` fn get_commit_hash(git_dir: &Path) -> AppResult<String> { let mut cmd = Command::new("git"); cmd.current_dir(git_dir) .arg("rev-parse") .arg("HEAD"); let out = try!(cmd.output()); String::from_utf8(out.stdout) .map(|s| s.trim().to_string()) .map_err(|_| app_err_msg("Couldn't convert 'git rev-parse HEAD' output to utf8!".to_string())) }
{ let mut file_contents: Vec<String> = Vec::new(); for file in tag_files.iter() { let mut file = try!(File::open(file)); let mut contents = String::new(); try!(file.read_to_string(&mut contents)); file_contents.push(contents); } let mut merged_lines: Vec<&str> = Vec::with_capacity(100_000); for content in file_contents.iter() { for line in content.lines() { if let Some(chr) = line.chars().nth(0) { if chr != '!' { merged_lines.push(line); } } } }
conditional_block
tags.rs
use std::fs::{File, OpenOptions}; use std::io::{Read, Write}; use std::process::Command; use std::collections::HashSet; use std::path::{PathBuf, Path}; use app_result::{AppResult, app_err_msg, app_err_missing_src}; use types::{Tags, TagsKind, SourceKind}; use path_ext::PathExt; use config::Config; use dirs::{ rusty_tags_cache_dir, cargo_git_src_dir, cargo_crates_io_src_dir, glob_path }; /// Checks if there's already a tags file for `source` /// and if not it's creating a new tags file and returning it. pub fn update_tags(config: &Config, source: &SourceKind) -> AppResult<Tags> { let src_tags = try!(cached_tags_file(&config.tags_kind, source)); let src_dir = try!(find_src_dir(source)); if src_tags.as_path().is_file() &&! config.force_recreate { return Ok(Tags::new(&src_dir, &src_tags, true)); } try!(create_tags(config, &[&src_dir], &src_tags)); Ok(Tags::new(&src_dir, &src_tags, false)) } /// Does the same thing as `update_tags`, but also checks if the `lib.rs` /// file of the library has public reexports of external crates. If /// that's the case, then the tags of the public reexported external /// crates are merged into the tags of the library. pub fn update_tags_and_check_for_reexports(config: &Config, source: &SourceKind, dependencies: &Vec<SourceKind>) -> AppResult<Tags> { let lib_tags = try!(update_tags(config, source)); if lib_tags.is_up_to_date(&config.tags_kind) &&! config.force_recreate { return Ok(lib_tags); } let reexp_crates = try!(find_reexported_crates(&lib_tags.src_dir)); if reexp_crates.is_empty() { return Ok(lib_tags); } if config.verbose { println!("Found public reexports in '{}' of:", source.get_lib_name()); for rcrate in reexp_crates.iter() { println!(" {}", rcrate); } println!(""); } let mut crate_tags = Vec::<PathBuf>::new(); for rcrate in reexp_crates.iter() { if let Some(crate_dep) = dependencies.iter().find(|d| d.get_lib_name() == *rcrate) { crate_tags.push(try!(update_tags(config, crate_dep)).tags_file.clone()); } } if crate_tags.is_empty() { return Ok(lib_tags); } crate_tags.push(lib_tags.tags_file.clone()); try!(merge_tags(config, &crate_tags, &lib_tags.tags_file)); Ok(lib_tags) } /// merges `tag_files` into `into_tag_file` pub fn merge_tags(config: &Config, tag_files: &Vec<PathBuf>, into_tag_file: &Path) -> AppResult<()> { if config.verbose { println!("Merging...\n tags:"); for file in tag_files.iter() { println!(" {}", file.display()); } println!("\n into:\n {}\n", into_tag_file.display()); } match config.tags_kind { TagsKind::Vi => { let mut file_contents: Vec<String> = Vec::new(); for file in tag_files.iter() { let mut file = try!(File::open(file)); let mut contents = String::new(); try!(file.read_to_string(&mut contents)); file_contents.push(contents); } let mut merged_lines: Vec<&str> = Vec::with_capacity(100_000); for content in file_contents.iter() { for line in content.lines() { if let Some(chr) = line.chars().nth(0) { if chr!= '!' { merged_lines.push(line); } } } } merged_lines.sort(); merged_lines.dedup(); let mut tag_file = try!( OpenOptions::new() .create(true) .truncate(true) .read(true) .write(true) .open(into_tag_file) ); try!(tag_file.write_fmt(format_args!("{}\n", "!_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;\" to lines/"))); try!(tag_file.write_fmt(format_args!("{}\n", "!_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/"))); for line in merged_lines.iter() { try!(tag_file.write_fmt(format_args!("{}\n", *line))); } }, TagsKind::Emacs => { let mut tag_file = try!( OpenOptions::new() .create(true) .append(true) .read(true) .write(true) .open(into_tag_file) ); for file in tag_files.iter() { if file.as_path()!= into_tag_file { try!(tag_file.write_fmt(format_args!("{},include\n", file.display()))); } } } } Ok(()) } /// creates tags recursive for the directory hierarchy starting at `src_dirs` /// and writes them to `tags_file` pub fn create_tags<P: AsRef<Path>>(config: &Config, src_dirs: &[P], tags_file: P) -> AppResult<()> { let mut cmd = Command::new("ctags"); config.tags_kind.ctags_option().map(|opt| { cmd.arg(opt); () }); cmd.arg("--recurse") .arg("--languages=Rust") .arg("--langdef=Rust") .arg("--langmap=Rust:.rs") .arg("--regex-Rust=/^[ \\t]*(#\\[[^\\]]\\][ \\t]*)*(pub[ \\t]+)?(extern[ \\t]+)?(\"[^\"]+\"[ \\t]+)?(unsafe[ \\t]+)?fn[ \\t]+([a-zA-Z0-9_]+)/\\6/f,functions,function definitions/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?type[ \\t]+([a-zA-Z0-9_]+)/\\2/T,types,type definitions/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?enum[ \\t]+([a-zA-Z0-9_]+)/\\2/g,enum,enumeration names/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?struct[ \\t]+([a-zA-Z0-9_]+)/\\2/s,structure names/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?mod[ \\t]+([a-zA-Z0-9_]+)\\s*\\{/\\2/m,modules,module names/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?(static|const)[ \\t]+([a-zA-Z0-9_]+)/\\3/c,consts,static constants/") .arg("--regex-Rust=/^[ \\t]*(pub[ \\t]+)?trait[ \\t]+([a-zA-Z0-9_]+)/\\2/t,traits,traits/") .arg("--regex-Rust=/^[ \\t]*macro_rules![ \\t]+([a-zA-Z0-9_]+)/\\1/d,macros,macro definitions/") .arg("-o") .arg(tags_file.as_ref()); for dir in src_dirs { cmd.arg(dir.as_ref()); } if config.verbose { println!("Creating tags...\n for source:"); for dir in src_dirs { println!(" {}", dir.as_ref().display()); } println!("\n cached at:\n {}\n", tags_file.as_ref().display()); } try!(cmd.output()); Ok(()) } /// find the source directory of `source`, for git sources the directories /// in `~/.cargo/git/checkouts` are considered and for crates.io sources /// the directories in `~/.cargo/registry/src/github.com-*` are considered fn find_src_dir(source: &SourceKind) -> AppResult<PathBuf> { match *source { SourceKind::Git { ref lib_name, ref commit_hash } => { let mut lib_src = lib_name.clone(); lib_src.push_str("-*"); let mut src_dir = try!(cargo_git_src_dir().map(Path::to_path_buf)); src_dir.push(&lib_src); src_dir.push("master"); let src_paths = try!(glob_path(&format!("{}", src_dir.display()))); for src_path in src_paths { if let Ok(path) = src_path { let src_commit_hash = try!(get_commit_hash(&path)); if *commit_hash == src_commit_hash { return Ok(path); } } } // the git repository name hasn't to match the name of the library, // so here we're just going through all git directories and searching // for the one with a matching commit hash let mut src_dir = try!(cargo_git_src_dir().map(Path::to_path_buf)); src_dir.push("*"); src_dir.push("master"); let src_paths = try!(glob_path(&format!("{}", src_dir.display()))); for src_path in src_paths { if let Ok(path) = src_path { let src_commit_hash = try!(get_commit_hash(&path)); if *commit_hash == src_commit_hash { return Ok(path); } } } Err(app_err_missing_src(source)) }, SourceKind::CratesIo { ref lib_name, ref version } => { let mut lib_src = lib_name.clone(); lib_src.push('-'); lib_src.push_str(&**version); let mut src_dir = try!(cargo_crates_io_src_dir().map(Path::to_path_buf)); src_dir.push(&lib_src); if! src_dir.is_dir() { return Err(app_err_missing_src(source)); } Ok(src_dir) }, SourceKind::Path { ref path,.. } => { if! path.is_dir() { return Err(app_err_missing_src(source)); } Ok(path.clone()) } } } /// returns the position and name of the cached tags file of `source` fn cached_tags_file(tags_kind: &TagsKind, source: &SourceKind) -> AppResult<PathBuf> { match *source { SourceKind::Git {.. } | SourceKind::CratesIo {.. } => { let mut tags_file = try!(rusty_tags_cache_dir().map(Path::to_path_buf)); tags_file.push(&source.tags_file_name(tags_kind)); Ok(tags_file) }, SourceKind::Path { ref path,.. } => { let mut tags_file = path.clone(); tags_file.push(&source.tags_file_name(tags_kind)); Ok(tags_file) } } } type CrateName = String; /// searches in the file `<src_dir>/src/lib.rs` for external crates /// that are reexpored and returns their names fn find_reexported_crates(src_dir: &Path) -> AppResult<Vec<CrateName>> { let mut lib_file = src_dir.to_path_buf(); lib_file.push("src"); lib_file.push("lib.rs"); if! lib_file.is_file() { return Ok(Vec::new()); } let contents = { let mut file = try!(File::open(&lib_file)); let mut contents = String::new(); try!(file.read_to_string(&mut contents)); contents }; let lines = contents.lines(); type ModuleName = String; let mut pub_uses = HashSet::<ModuleName>::new(); #[derive(Eq, PartialEq, Hash)] struct ExternCrate<'a> { name: &'a str, as_name: &'a str } let mut extern_crates = HashSet::<ExternCrate>::new(); for line in lines { let items = line.trim_matches(';').split(' ').collect::<Vec<&str>>(); if items.len() < 3 { continue; } if items[0] == "pub" && items[1] == "use" { let mods = items[2].split("::").collect::<Vec<&str>>(); if mods.len() >= 1 { pub_uses.insert(mods[0].to_string()); } } if items[0] == "extern" && items[1] == "crate" { if items.len() == 3 { extern_crates.insert(ExternCrate { name: items[2].trim_matches('"'), as_name: items[2] }); } else if items.len() == 5 && items[3] == "as" { extern_crates.insert(ExternCrate { name: items[2].trim_matches('"'), as_name: items[4] }); } } } let mut reexp_crates = Vec::<CrateName>::new(); for extern_crate in extern_crates.iter() { if pub_uses.contains(extern_crate.as_name) { reexp_crates.push(extern_crate.name.to_string()); } } Ok(reexp_crates) }
let mut cmd = Command::new("git"); cmd.current_dir(git_dir) .arg("rev-parse") .arg("HEAD"); let out = try!(cmd.output()); String::from_utf8(out.stdout) .map(|s| s.trim().to_string()) .map_err(|_| app_err_msg("Couldn't convert 'git rev-parse HEAD' output to utf8!".to_string())) }
/// get the commit hash of the current `HEAD` of the git repository located at `git_dir` fn get_commit_hash(git_dir: &Path) -> AppResult<String> {
random_line_split
cubicbez.rs
Mul, Range}; //// ////use std::ops::{Mul, Range}; use introsort; //// use crate::MAX_EXTREMA; use arrayvec::ArrayVec; use crate::common::solve_quadratic; use crate::common::GAUSS_LEGENDRE_COEFFS_9; use crate::{ Affine, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveCurvature, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, Point, QuadBez, }; /// A single cubic Bézier segment. #[derive(Clone, Copy, Debug, PartialEq)] pub struct CubicBez { pub p0: Point, pub p1: Point, pub p2: Point, pub p3: Point, } /// An iterator which produces quadratic Bézier segments. struct ToQuads { c: CubicBez, max_hypot2: f64, t: f64, } impl CubicBez { /// Create a new cubic Bézier segment. #[inline] pub fn new<P: Into<Point>>(p0: P, p1: P, p2: P, p3: P) -> CubicBez { CubicBez { p0: p0.into(), p1: p1.into(), p2: p2.into(), p3: p3.into(), } } /// Convert to quadratic Béziers. /// /// The iterator returns the start and end parameter in the cubic of each quadratic /// segment, along with the quadratic. /// /// Note that the resulting quadratic Béziers are not in general G1 continuous; /// they are optimized for minimizing distance error. #[inline] pub fn to_quads(&self, accuracy: f64) -> impl Iterator<Item = (f64, f64, QuadBez)> { // This magic number is the square of 36 / sqrt(3). // See: http://caffeineowl.com/graphics/2d/vectorial/cubic2quad01.html let max_hypot2 = 432.0 * accuracy * accuracy; ToQuads { c: *self, max_hypot2, t: 0.0, } } } impl ParamCurve for CubicBez { #[inline] fn eval(&self, t: f64) -> Point { let mt = 1.0 - t; let v = self.p0.to_vec2() * (mt * mt * mt) + (self.p1.to_vec2() * (mt * mt * 3.0) + (self.p2.to_vec2() * (mt * 3.0) + self.p3.to_vec2() * t) * t) * t; v.to_point() } #[inline] fn start(&self) -> Point { self.p0 } #[inline] fn end(&self) -> Point { self.p3 } fn subsegment(&self, range: Range<f64>) -> CubicBez { let (t0, t1) = (range.start, range.end); let p0 = self.eval(t0); let p3 = self.eval(t1); let d = self.deriv(); let scale = (t1 - t0) * (1.0 / 3.0); let p1 = p0 + scale * d.eval(t0).to_vec2(); let p2 = p3 - scale * d.eval(t1).to_vec2(); CubicBez { p0, p1, p2, p3 } } /// Subdivide into halves, using de Casteljau. #[inline] fn subdivide(&self) -> (CubicBez, CubicBez) { let pm = self.eval(0.5); ( CubicBez::new( self.p0, self.p0.midpoint(self.p1), ((self.p0.to_vec2() + self.p1.to_vec2() * 2.0 + self.p2.to_vec2()) * 0.25) .to_point(), pm, ), CubicBez::new( pm, ((self.p1.to_vec2() + self.p2.to_vec2() * 2.0 + self.p3.to_vec2()) * 0.25) .to_point(), self.p2.midpoint(self.p3), self.p3, ), ) } } impl ParamCurveDeriv for CubicBez { type DerivResult = QuadBez; #[inline] fn deriv(&self) -> QuadBez { QuadBez::new( (3.0 * (self.p1 - self.p0)).to_point(), (3.0 * (self.p2 - self.p1)).to_point(), (3.0 * (self.p3 - self.p2)).to_point(), ) } } impl ParamCurveArclen for CubicBez { /// Arclength of a cubic Bézier segment. /// /// This is an adaptive subdivision approach using Legendre-Gauss quadrature /// in the base case, and an error estimate to decide when to subdivide. fn arclen(&self, accuracy: f64) -> f64 { // Squared L2 norm of the second derivative of the cubic. fn cubic_errnorm(c: &CubicBez) -> f64 { let d = c.deriv().deriv(); let dd = d.end() - d.start(); d.start().to_vec2().hypot2() + d.start().to_vec2().dot(dd) + dd.hypot2() * (1.0 / 3.0) } fn est_gauss9_error(c: &CubicBez) -> f64 { let lc = (c.p3 - c.p0).hypot(); let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); 2.56e-8 * libm::pow(cubic_errnorm(c) / (lc * lc), 8 as f64) * lp //// ////2.56e-8 * (cubic_errnorm(c) / (lc * lc)).powi(8) * lp } const MAX_DEPTH: usize = 16; fn rec(c: &CubicBez, accuracy: f64, depth: usize) -> f64 { if depth == MAX_DEPTH || est_gauss9_error(c) < accuracy { c.gauss_arclen(GAUSS_LEGENDRE_COEFFS_9) } else { let (c0, c1) = c.subdivide(); rec(&c0, accuracy * 0.5, depth + 1) + rec(&c1, accuracy * 0.5, depth + 1) } } rec(self, accuracy, 0) } } impl ParamCurveArea for CubicBez { #[inline] fn signed_area(&self) -> f64 { (self.p0.x * (6.0 * self.p1.y + 3.0 * self.p2.y + self.p3.y) + 3.0 * (self.p1.x * (-2.0 * self.p0.y + self.p2.y + self.p3.y) - self.p2.x * (self.p0.y + self.p1.y - 2.0 * self.p3.y)) - self.p3.x * (self.p0.y + 3.0 * self.p1.y + 6.0 * self.p2.y)) * (1.0 / 20.0) } } impl ParamCurveNearest for CubicBez { /// Find nearest point, using subdivision. fn nearest(&self, p: Point, accuracy: f64) -> (f64, f64) { let mut best_r = None; let mut best_t = 0.0; for (t0, t1, q) in self.to_quads(accuracy) { let (t, r) = q.nearest(p, accuracy); if best_r.map(|best_r| r < best_r).unwrap_or(true) { best_t = t0 + t * (t1 - t0); best_r = Some(r); } } (best_t, best_r.unwrap()) } } impl ParamCurveCurvature for CubicBez {} impl ParamCurveExtrema for CubicBez { fn extrema(&self) -> ArrayVec<[f64; MAX_EXTREMA]> { fn one_coord(result: &mut ArrayVec<[f64; MAX_EXTREMA]>, d0: f64, d1: f64, d2: f64) { let a = d0 - 2.0 * d1 + d2; let b = 2.0 * (d1 - d0); let c = d0; let roots = solve_quadratic(c, b, a); for &t in &roots { if t > 0.0 && t < 1.0 { result.push(t); } } } let mut result = ArrayVec::<[f64; MAX_EXTREMA]>::new(); //// ////let mut result = ArrayVec::new(); let d0 = self.p1 - self.p0; let d1 = self.p2 - self.p1; let d2 = self.p3 - self.p2; one_coord(&mut result, d0.x, d1.x, d2.x); one_coord(&mut result, d0.y, d1.y, d2.y); introsort::sort_by(&mut result, &|a, b| a.partial_cmp(b).unwrap()); //// ////result.sort_by(|a, b| a.partial_cmp(b).unwrap()); result } } impl Mul<CubicBez> for Affine { type Output = CubicBez; #[inline] fn mul(self, c: CubicBez) -> CubicBez { CubicBez { p0: self * c.p0, p1: self * c.p1, p2: self * c.p2, p3: self * c.p3, } } } impl Iterator for ToQuads { type Item = (f64, f64, QuadBez); fn next(&mut self) -> Option<(f64, f64, QuadBez)> { let t0 = self.t; let mut t1 = 1.0; if t0 == t1 { return None; } loop { let seg = self.c.subsegment(t0..t1); // Compute error for candidate quadratic. let p1x2 = 3.0 * seg.p1.to_vec2() - seg.p0.to_vec2(); let p2x2 = 3.0 * seg.p2.to_vec2() - seg.p3.to_vec2(); let err = (p2x2 - p1x2).hypot2(); //println!("{:?} {} {}", t0..t1, err, if err < self.max_hypot2 { "ok" } else { "" }); if err < self.max_hypot2 { let result = QuadBez::new(seg.p0, ((p1x2 + p2x2) / 4.0).to_point(), seg.p3); self.t = t1; return Some((t0, t1, result)); } else { let shrink = if t1 == 1.0 && err < 64.0 * self.max_hypot2 { 0.5 } else { 0.999_999 * libm::pow(self.max_hypot2 / err, 1. / 6.0) //// ////0.999_999 * (self.max_hypot2 / err).powf(1. / 6.0) }; t1 = t0 + shrink * (t1 - t0); } } } } #[cfg(test)] mod tests { use crate::{ Affine, CubicBez, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, Point, }; #[test] fn cubicbez_deriv() { // y = x^2 let c = CubicBez::new( (0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0, 1.0), ); let deriv = c.deriv(); let n = 10; for i in 0..=n { let t = (i as f64) * (n as f64).recip(); let delta = 1e-6; let p = c.eval(t); let p1 = c.eval(t + delta); let d_approx = (p1 - p) * delta.recip(); let d = deriv.eval(t).to_vec2(); assert!((d - d_approx).hypot() < delta * 2.0); } } #[test] fn cubicbe
// y = x^2 let c = CubicBez::new( (0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0, 1.0), ); let true_arclen = 0.5 * libm::sqrt(5.0f64) + 0.25 * (2.0 + libm::sqrt(5.0f64)).ln(); for i in 0..12 { let accuracy = 0.1f64.powi(i); let error = c.arclen(accuracy) - true_arclen; //println!("{:e}: {:e}", accuracy, error); assert!(error.abs() < accuracy); } } #[test] fn cubicbez_inv_arclen() { // y = x^2 let c = CubicBez::new( (0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0, 1.0), ); let true_arclen = 0.5 * libm::sqrt(5.0f64) + 0.25 * (2.0 + libm::sqrt(5.0f64)).ln(); for i in 0..12 { let accuracy = 0.1f64.powi(i); let n = 10; for j in 0..=n { let arc = (j as f64) * ((n as f64).recip() * true_arclen); let t = c.inv_arclen(arc, accuracy * 0.5); let actual_arc = c.subsegment(0.0..t).arclen(accuracy * 0.5); assert!( (arc - actual_arc).abs() < accuracy, "at accuracy {:e}, wanted {} got {}", accuracy, actual_arc, arc ); } } } #[test] fn cubicbez_signed_area_linear() { // y = 1 - x let c = CubicBez::new( (1.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0 / 3.0, 2.0 / 3.0), (0.0, 1.0), ); let epsilon = 1e-12; assert_eq!((Affine::rotate(0.5) * c).signed_area(), 0.5); assert!(((Affine::rotate(0.5) * c).signed_area() - 0.5).abs() < epsilon); assert!(((Affine::translate((0.0, 1.0)) * c).signed_area() - 1.0).abs() < epsilon); assert!(((Affine::translate((1.0, 0.0)) * c).signed_area() - 1.0).abs() < epsilon); } #[test] fn cubicbez_signed_area() { // y = 1 - x^3 let c = CubicBez::new((1.0, 0.0), (2.0 / 3.0, 1.0), (1.0 / 3.0, 1.0), (0.0, 1.0)); let epsilon = 1e-12; assert!((c.signed_area() - 0.75).abs() < epsilon); assert!(((Affine::rotate(0.5) * c).signed_area() - 0.75).abs() < epsilon); assert!(((Affine::translate((0.0, 1.0)) * c).signed_area() - 1.25).abs() < epsilon); assert!(((Affine::translate((1.0, 0.0)) * c).signed_area() - 1.25).abs() < epsilon); } #[test] fn cubicbez_nearest() { fn verify(result: (f64, f64), expected: f64) { assert!( (result.0 - expected).abs() < 1e-6, "got {:?} expected {}", result, expected ); } // y = x^3 let c = CubicBez::new((0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 0.0), (1.0, 1.0)); verify(c.nearest((0.1, 0.001).into(), 1e-6), 0.1); verify(c.nearest((0.2, 0.008).into(), 1e-6), 0.2); verify(c.nearest((0.3, 0.027).into(), 1e-6), 0.3); verify(c.nearest((0.4, 0.064).into(), 1e-6), 0.4); verify(c.nearest((0.5, 0.125).into(), 1e-6), 0.5); verify(c.nearest((0.6, 0.216).into(), 1e-6), 0.6); verify(c.nearest((0.7, 0.343).into(), 1e-6), 0.7); verify(c.nearest((0.8, 0.512).into(), 1e-6), 0.8); verify(c.nearest((0.9, 0.729).into(), 1e-6), 0.9); verify(c.nearest((1.0, 1.0).into(), 1e-6), 1.0); verify(c.nearest((1.1, 1.1).into(), 1e-6), 1.0); verify(c.nearest((-0.1, 0.0).into(), 1e-6), 0.0); let a = Affine::rotate(0.5); verify((a * c).nearest(a * Point::new(0.1, 0.001), 1e-6), 0.1); } #[test] fn cubicbez_extrema() { // y = x^2 let q = CubicBez::new((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)); let extrema = q.extrema(); assert_eq!(extrema.len(), 1); assert!((extrema[0] - 0.5).abs() < 1e-6); let q = CubicBez::new((0.4, 0.5), (0.0, 1.0), (1.0, 0.0), (0.5, 0.4)); let extrema = q.extrema(); assert_eq!(extrema.len(), 4); } #[test] fn cubicbez_toquads() { // y = x^3 let c = CubicBez::new((0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 0.0), (1.0, 1.0)); for i in 0..10 { let accuracy = 0.1f64.powi(i); let mut _count = 0; let mut worst: f64 = 0.0; for (t0, t1, q) in c.to_quads(accuracy) { _count += 1; let epsilon = 1e-12; assert!((q.start() - c.eval(t0)).hypot() < epsilon); assert!((q.end() - c.eval(t1)).hypot() < epsilon); let n = 4; for j in 0..=n { let t = (j as f64) * (n as f64).recip(); let p = q.eval(t); let err = (p.y - p.x.powi(3)).abs(); worst = worst.max(err); assert!(err < accuracy, "got {} wanted {}", err, accuracy); } }
z_arclen() {
identifier_name
cubicbez.rs
::{Mul, Range}; //// ////use std::ops::{Mul, Range}; use introsort; //// use crate::MAX_EXTREMA; use arrayvec::ArrayVec; use crate::common::solve_quadratic; use crate::common::GAUSS_LEGENDRE_COEFFS_9; use crate::{ Affine, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveCurvature, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, Point, QuadBez, }; /// A single cubic Bézier segment. #[derive(Clone, Copy, Debug, PartialEq)] pub struct CubicBez { pub p0: Point, pub p1: Point, pub p2: Point, pub p3: Point, } /// An iterator which produces quadratic Bézier segments. struct ToQuads { c: CubicBez, max_hypot2: f64, t: f64, } impl CubicBez { /// Create a new cubic Bézier segment. #[inline] pub fn new<P: Into<Point>>(p0: P, p1: P, p2: P, p3: P) -> CubicBez { CubicBez { p0: p0.into(), p1: p1.into(), p2: p2.into(), p3: p3.into(), } } /// Convert to quadratic Béziers. /// /// The iterator returns the start and end parameter in the cubic of each quadratic /// segment, along with the quadratic. /// /// Note that the resulting quadratic Béziers are not in general G1 continuous; /// they are optimized for minimizing distance error. #[inline] pub fn to_quads(&self, accuracy: f64) -> impl Iterator<Item = (f64, f64, QuadBez)> { // This magic number is the square of 36 / sqrt(3). // See: http://caffeineowl.com/graphics/2d/vectorial/cubic2quad01.html let max_hypot2 = 432.0 * accuracy * accuracy; ToQuads { c: *self, max_hypot2, t: 0.0, } } } impl ParamCurve for CubicBez { #[inline] fn eval(&self, t: f64) -> Point { let mt = 1.0 - t; let v = self.p0.to_vec2() * (mt * mt * mt) + (self.p1.to_vec2() * (mt * mt * 3.0) + (self.p2.to_vec2() * (mt * 3.0) + self.p3.to_vec2() * t) * t) * t; v.to_point() } #[inline] fn start(&self) -> Point { self.p0 } #[inline] fn end(&self) -> Point { self.p3 }
let p0 = self.eval(t0); let p3 = self.eval(t1); let d = self.deriv(); let scale = (t1 - t0) * (1.0 / 3.0); let p1 = p0 + scale * d.eval(t0).to_vec2(); let p2 = p3 - scale * d.eval(t1).to_vec2(); CubicBez { p0, p1, p2, p3 } } /// Subdivide into halves, using de Casteljau. #[inline] fn subdivide(&self) -> (CubicBez, CubicBez) { let pm = self.eval(0.5); ( CubicBez::new( self.p0, self.p0.midpoint(self.p1), ((self.p0.to_vec2() + self.p1.to_vec2() * 2.0 + self.p2.to_vec2()) * 0.25) .to_point(), pm, ), CubicBez::new( pm, ((self.p1.to_vec2() + self.p2.to_vec2() * 2.0 + self.p3.to_vec2()) * 0.25) .to_point(), self.p2.midpoint(self.p3), self.p3, ), ) } } impl ParamCurveDeriv for CubicBez { type DerivResult = QuadBez; #[inline] fn deriv(&self) -> QuadBez { QuadBez::new( (3.0 * (self.p1 - self.p0)).to_point(), (3.0 * (self.p2 - self.p1)).to_point(), (3.0 * (self.p3 - self.p2)).to_point(), ) } } impl ParamCurveArclen for CubicBez { /// Arclength of a cubic Bézier segment. /// /// This is an adaptive subdivision approach using Legendre-Gauss quadrature /// in the base case, and an error estimate to decide when to subdivide. fn arclen(&self, accuracy: f64) -> f64 { // Squared L2 norm of the second derivative of the cubic. fn cubic_errnorm(c: &CubicBez) -> f64 { let d = c.deriv().deriv(); let dd = d.end() - d.start(); d.start().to_vec2().hypot2() + d.start().to_vec2().dot(dd) + dd.hypot2() * (1.0 / 3.0) } fn est_gauss9_error(c: &CubicBez) -> f64 { let lc = (c.p3 - c.p0).hypot(); let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); 2.56e-8 * libm::pow(cubic_errnorm(c) / (lc * lc), 8 as f64) * lp //// ////2.56e-8 * (cubic_errnorm(c) / (lc * lc)).powi(8) * lp } const MAX_DEPTH: usize = 16; fn rec(c: &CubicBez, accuracy: f64, depth: usize) -> f64 { if depth == MAX_DEPTH || est_gauss9_error(c) < accuracy { c.gauss_arclen(GAUSS_LEGENDRE_COEFFS_9) } else { let (c0, c1) = c.subdivide(); rec(&c0, accuracy * 0.5, depth + 1) + rec(&c1, accuracy * 0.5, depth + 1) } } rec(self, accuracy, 0) } } impl ParamCurveArea for CubicBez { #[inline] fn signed_area(&self) -> f64 { (self.p0.x * (6.0 * self.p1.y + 3.0 * self.p2.y + self.p3.y) + 3.0 * (self.p1.x * (-2.0 * self.p0.y + self.p2.y + self.p3.y) - self.p2.x * (self.p0.y + self.p1.y - 2.0 * self.p3.y)) - self.p3.x * (self.p0.y + 3.0 * self.p1.y + 6.0 * self.p2.y)) * (1.0 / 20.0) } } impl ParamCurveNearest for CubicBez { /// Find nearest point, using subdivision. fn nearest(&self, p: Point, accuracy: f64) -> (f64, f64) { let mut best_r = None; let mut best_t = 0.0; for (t0, t1, q) in self.to_quads(accuracy) { let (t, r) = q.nearest(p, accuracy); if best_r.map(|best_r| r < best_r).unwrap_or(true) { best_t = t0 + t * (t1 - t0); best_r = Some(r); } } (best_t, best_r.unwrap()) } } impl ParamCurveCurvature for CubicBez {} impl ParamCurveExtrema for CubicBez { fn extrema(&self) -> ArrayVec<[f64; MAX_EXTREMA]> { fn one_coord(result: &mut ArrayVec<[f64; MAX_EXTREMA]>, d0: f64, d1: f64, d2: f64) { let a = d0 - 2.0 * d1 + d2; let b = 2.0 * (d1 - d0); let c = d0; let roots = solve_quadratic(c, b, a); for &t in &roots { if t > 0.0 && t < 1.0 { result.push(t); } } } let mut result = ArrayVec::<[f64; MAX_EXTREMA]>::new(); //// ////let mut result = ArrayVec::new(); let d0 = self.p1 - self.p0; let d1 = self.p2 - self.p1; let d2 = self.p3 - self.p2; one_coord(&mut result, d0.x, d1.x, d2.x); one_coord(&mut result, d0.y, d1.y, d2.y); introsort::sort_by(&mut result, &|a, b| a.partial_cmp(b).unwrap()); //// ////result.sort_by(|a, b| a.partial_cmp(b).unwrap()); result } } impl Mul<CubicBez> for Affine { type Output = CubicBez; #[inline] fn mul(self, c: CubicBez) -> CubicBez { CubicBez { p0: self * c.p0, p1: self * c.p1, p2: self * c.p2, p3: self * c.p3, } } } impl Iterator for ToQuads { type Item = (f64, f64, QuadBez); fn next(&mut self) -> Option<(f64, f64, QuadBez)> { let t0 = self.t; let mut t1 = 1.0; if t0 == t1 { return None; } loop { let seg = self.c.subsegment(t0..t1); // Compute error for candidate quadratic. let p1x2 = 3.0 * seg.p1.to_vec2() - seg.p0.to_vec2(); let p2x2 = 3.0 * seg.p2.to_vec2() - seg.p3.to_vec2(); let err = (p2x2 - p1x2).hypot2(); //println!("{:?} {} {}", t0..t1, err, if err < self.max_hypot2 { "ok" } else { "" }); if err < self.max_hypot2 { let result = QuadBez::new(seg.p0, ((p1x2 + p2x2) / 4.0).to_point(), seg.p3); self.t = t1; return Some((t0, t1, result)); } else { let shrink = if t1 == 1.0 && err < 64.0 * self.max_hypot2 { 0.5 } else { 0.999_999 * libm::pow(self.max_hypot2 / err, 1. / 6.0) //// ////0.999_999 * (self.max_hypot2 / err).powf(1. / 6.0) }; t1 = t0 + shrink * (t1 - t0); } } } } #[cfg(test)] mod tests { use crate::{ Affine, CubicBez, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, Point, }; #[test] fn cubicbez_deriv() { // y = x^2 let c = CubicBez::new( (0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0, 1.0), ); let deriv = c.deriv(); let n = 10; for i in 0..=n { let t = (i as f64) * (n as f64).recip(); let delta = 1e-6; let p = c.eval(t); let p1 = c.eval(t + delta); let d_approx = (p1 - p) * delta.recip(); let d = deriv.eval(t).to_vec2(); assert!((d - d_approx).hypot() < delta * 2.0); } } #[test] fn cubicbez_arclen() { // y = x^2 let c = CubicBez::new( (0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0, 1.0), ); let true_arclen = 0.5 * libm::sqrt(5.0f64) + 0.25 * (2.0 + libm::sqrt(5.0f64)).ln(); for i in 0..12 { let accuracy = 0.1f64.powi(i); let error = c.arclen(accuracy) - true_arclen; //println!("{:e}: {:e}", accuracy, error); assert!(error.abs() < accuracy); } } #[test] fn cubicbez_inv_arclen() { // y = x^2 let c = CubicBez::new( (0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0, 1.0), ); let true_arclen = 0.5 * libm::sqrt(5.0f64) + 0.25 * (2.0 + libm::sqrt(5.0f64)).ln(); for i in 0..12 { let accuracy = 0.1f64.powi(i); let n = 10; for j in 0..=n { let arc = (j as f64) * ((n as f64).recip() * true_arclen); let t = c.inv_arclen(arc, accuracy * 0.5); let actual_arc = c.subsegment(0.0..t).arclen(accuracy * 0.5); assert!( (arc - actual_arc).abs() < accuracy, "at accuracy {:e}, wanted {} got {}", accuracy, actual_arc, arc ); } } } #[test] fn cubicbez_signed_area_linear() { // y = 1 - x let c = CubicBez::new( (1.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0 / 3.0, 2.0 / 3.0), (0.0, 1.0), ); let epsilon = 1e-12; assert_eq!((Affine::rotate(0.5) * c).signed_area(), 0.5); assert!(((Affine::rotate(0.5) * c).signed_area() - 0.5).abs() < epsilon); assert!(((Affine::translate((0.0, 1.0)) * c).signed_area() - 1.0).abs() < epsilon); assert!(((Affine::translate((1.0, 0.0)) * c).signed_area() - 1.0).abs() < epsilon); } #[test] fn cubicbez_signed_area() { // y = 1 - x^3 let c = CubicBez::new((1.0, 0.0), (2.0 / 3.0, 1.0), (1.0 / 3.0, 1.0), (0.0, 1.0)); let epsilon = 1e-12; assert!((c.signed_area() - 0.75).abs() < epsilon); assert!(((Affine::rotate(0.5) * c).signed_area() - 0.75).abs() < epsilon); assert!(((Affine::translate((0.0, 1.0)) * c).signed_area() - 1.25).abs() < epsilon); assert!(((Affine::translate((1.0, 0.0)) * c).signed_area() - 1.25).abs() < epsilon); } #[test] fn cubicbez_nearest() { fn verify(result: (f64, f64), expected: f64) { assert!( (result.0 - expected).abs() < 1e-6, "got {:?} expected {}", result, expected ); } // y = x^3 let c = CubicBez::new((0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 0.0), (1.0, 1.0)); verify(c.nearest((0.1, 0.001).into(), 1e-6), 0.1); verify(c.nearest((0.2, 0.008).into(), 1e-6), 0.2); verify(c.nearest((0.3, 0.027).into(), 1e-6), 0.3); verify(c.nearest((0.4, 0.064).into(), 1e-6), 0.4); verify(c.nearest((0.5, 0.125).into(), 1e-6), 0.5); verify(c.nearest((0.6, 0.216).into(), 1e-6), 0.6); verify(c.nearest((0.7, 0.343).into(), 1e-6), 0.7); verify(c.nearest((0.8, 0.512).into(), 1e-6), 0.8); verify(c.nearest((0.9, 0.729).into(), 1e-6), 0.9); verify(c.nearest((1.0, 1.0).into(), 1e-6), 1.0); verify(c.nearest((1.1, 1.1).into(), 1e-6), 1.0); verify(c.nearest((-0.1, 0.0).into(), 1e-6), 0.0); let a = Affine::rotate(0.5); verify((a * c).nearest(a * Point::new(0.1, 0.001), 1e-6), 0.1); } #[test] fn cubicbez_extrema() { // y = x^2 let q = CubicBez::new((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)); let extrema = q.extrema(); assert_eq!(extrema.len(), 1); assert!((extrema[0] - 0.5).abs() < 1e-6); let q = CubicBez::new((0.4, 0.5), (0.0, 1.0), (1.0, 0.0), (0.5, 0.4)); let extrema = q.extrema(); assert_eq!(extrema.len(), 4); } #[test] fn cubicbez_toquads() { // y = x^3 let c = CubicBez::new((0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 0.0), (1.0, 1.0)); for i in 0..10 { let accuracy = 0.1f64.powi(i); let mut _count = 0; let mut worst: f64 = 0.0; for (t0, t1, q) in c.to_quads(accuracy) { _count += 1; let epsilon = 1e-12; assert!((q.start() - c.eval(t0)).hypot() < epsilon); assert!((q.end() - c.eval(t1)).hypot() < epsilon); let n = 4; for j in 0..=n { let t = (j as f64) * (n as f64).recip(); let p = q.eval(t); let err = (p.y - p.x.powi(3)).abs(); worst = worst.max(err); assert!(err < accuracy, "got {} wanted {}", err, accuracy); } }
fn subsegment(&self, range: Range<f64>) -> CubicBez { let (t0, t1) = (range.start, range.end);
random_line_split
cubicbez.rs
Mul, Range}; //// ////use std::ops::{Mul, Range}; use introsort; //// use crate::MAX_EXTREMA; use arrayvec::ArrayVec; use crate::common::solve_quadratic; use crate::common::GAUSS_LEGENDRE_COEFFS_9; use crate::{ Affine, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveCurvature, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, Point, QuadBez, }; /// A single cubic Bézier segment. #[derive(Clone, Copy, Debug, PartialEq)] pub struct CubicBez { pub p0: Point, pub p1: Point, pub p2: Point, pub p3: Point, } /// An iterator which produces quadratic Bézier segments. struct ToQuads { c: CubicBez, max_hypot2: f64, t: f64, } impl CubicBez { /// Create a new cubic Bézier segment. #[inline] pub fn new<P: Into<Point>>(p0: P, p1: P, p2: P, p3: P) -> CubicBez { CubicBez { p0: p0.into(), p1: p1.into(), p2: p2.into(), p3: p3.into(), } } /// Convert to quadratic Béziers. /// /// The iterator returns the start and end parameter in the cubic of each quadratic /// segment, along with the quadratic. /// /// Note that the resulting quadratic Béziers are not in general G1 continuous; /// they are optimized for minimizing distance error. #[inline] pub fn to_quads(&self, accuracy: f64) -> impl Iterator<Item = (f64, f64, QuadBez)> { // This magic number is the square of 36 / sqrt(3). // See: http://caffeineowl.com/graphics/2d/vectorial/cubic2quad01.html let max_hypot2 = 432.0 * accuracy * accuracy; ToQuads { c: *self, max_hypot2, t: 0.0, } } } impl ParamCurve for CubicBez { #[inline] fn eval(&self, t: f64) -> Point { let mt = 1.0 - t; let v = self.p0.to_vec2() * (mt * mt * mt) + (self.p1.to_vec2() * (mt * mt * 3.0) + (self.p2.to_vec2() * (mt * 3.0) + self.p3.to_vec2() * t) * t) * t; v.to_point() } #[inline] fn start(&self) -> Point { self.p0 } #[inline] fn end(&self) -> Point { self.p3 } fn subsegment(&self, range: Range<f64>) -> CubicBez { let (t0, t1) = (range.start, range.end); let p0 = self.eval(t0); let p3 = self.eval(t1); let d = self.deriv(); let scale = (t1 - t0) * (1.0 / 3.0); let p1 = p0 + scale * d.eval(t0).to_vec2(); let p2 = p3 - scale * d.eval(t1).to_vec2(); CubicBez { p0, p1, p2, p3 } } /// Subdivide into halves, using de Casteljau. #[inline] fn subdivide(&self) -> (CubicBez, CubicBez) { let pm = self.eval(0.5); ( CubicBez::new( self.p0, self.p0.midpoint(self.p1), ((self.p0.to_vec2() + self.p1.to_vec2() * 2.0 + self.p2.to_vec2()) * 0.25) .to_point(), pm, ), CubicBez::new( pm, ((self.p1.to_vec2() + self.p2.to_vec2() * 2.0 + self.p3.to_vec2()) * 0.25) .to_point(), self.p2.midpoint(self.p3), self.p3, ), ) } } impl ParamCurveDeriv for CubicBez { type DerivResult = QuadBez; #[inline] fn deriv(&self) -> QuadBez { QuadBez::new( (3.0 * (self.p1 - self.p0)).to_point(), (3.0 * (self.p2 - self.p1)).to_point(), (3.0 * (self.p3 - self.p2)).to_point(), ) } } impl ParamCurveArclen for CubicBez { /// Arclength of a cubic Bézier segment. /// /// This is an adaptive subdivision approach using Legendre-Gauss quadrature /// in the base case, and an error estimate to decide when to subdivide. fn arclen(&self, accuracy: f64) -> f64 { // Squared L2 norm of the second derivative of the cubic. fn cubic_errnorm(c: &CubicBez) -> f64 { let d = c.deriv().deriv(); let dd = d.end() - d.start(); d.start().to_vec2().hypot2() + d.start().to_vec2().dot(dd) + dd.hypot2() * (1.0 / 3.0) } fn est_gauss9_error(c: &CubicBez) -> f64 { let lc = (c.p3 - c.p0).hypot(); let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); 2.56e-8 * libm::pow(cubic_errnorm(c) / (lc * lc), 8 as f64) * lp //// ////2.56e-8 * (cubic_errnorm(c) / (lc * lc)).powi(8) * lp } const MAX_DEPTH: usize = 16; fn rec(c: &CubicBez, accuracy: f64, depth: usize) -> f64 { if depth == MAX_DEPTH || est_gauss9_error(c) < accuracy { c.gauss_arclen(GAUSS_LEGENDRE_COEFFS_9) } else { let (c0, c1) = c.subdivide(); rec(&c0, accuracy * 0.5, depth + 1) + rec(&c1, accuracy * 0.5, depth + 1) } } rec(self, accuracy, 0) } } impl ParamCurveArea for CubicBez { #[inline] fn signed_area(&self) -> f64 { (self.p0.x * (6.0 * self.p1.y + 3.0 * self.p2.y + self.p3.y) + 3.0 * (self.p1.x * (-2.0 * self.p0.y + self.p2.y + self.p3.y) - self.p2.x * (self.p0.y + self.p1.y - 2.0 * self.p3.y)) - self.p3.x * (self.p0.y + 3.0 * self.p1.y + 6.0 * self.p2.y)) * (1.0 / 20.0) } } impl ParamCurveNearest for CubicBez { /// Find nearest point, using subdivision. fn nearest(&self, p: Point, accuracy: f64) -> (f64, f64) { let mut best_r = None; let mut best_t = 0.0; for (t0, t1, q) in self.to_quads(accuracy) { let (t, r) = q.nearest(p, accuracy); if best_r.map(|best_r| r < best_r).unwrap_or(true) { best_t = t0 + t * (t1 - t0); best_r = Some(r); } } (best_t, best_r.unwrap()) } } impl ParamCurveCurvature for CubicBez {} impl ParamCurveExtrema for CubicBez { fn extrema(&self) -> ArrayVec<[f64; MAX_EXTREMA]> { fn one_coord(result: &mut ArrayVec<[f64; MAX_EXTREMA]>, d0: f64, d1: f64, d2: f64) { let a = d0 - 2.0 * d1 + d2; let b = 2.0 * (d1 - d0); let c = d0; let roots = solve_quadratic(c, b, a); for &t in &roots { if t > 0.0 && t < 1.0 { result.push(t); } } } let mut result = ArrayVec::<[f64; MAX_EXTREMA]>::new(); //// ////let mut result = ArrayVec::new(); let d0 = self.p1 - self.p0; let d1 = self.p2 - self.p1; let d2 = self.p3 - self.p2; one_coord(&mut result, d0.x, d1.x, d2.x); one_coord(&mut result, d0.y, d1.y, d2.y); introsort::sort_by(&mut result, &|a, b| a.partial_cmp(b).unwrap()); //// ////result.sort_by(|a, b| a.partial_cmp(b).unwrap()); result } } impl Mul<CubicBez> for Affine { type Output = CubicBez; #[inline] fn mul(self, c: CubicBez) -> CubicBez { CubicBez { p0: self * c.p0, p1: self * c.p1, p2: self * c.p2, p3: self * c.p3, } } } impl Iterator for ToQuads { type Item = (f64, f64, QuadBez); fn next(&mut self) -> Option<(f64, f64, QuadBez)> { let t0 = self.t; let mut t1 = 1.0; if t0 == t1 { return None; } loop { let seg = self.c.subsegment(t0..t1); // Compute error for candidate quadratic. let p1x2 = 3.0 * seg.p1.to_vec2() - seg.p0.to_vec2(); let p2x2 = 3.0 * seg.p2.to_vec2() - seg.p3.to_vec2(); let err = (p2x2 - p1x2).hypot2(); //println!("{:?} {} {}", t0..t1, err, if err < self.max_hypot2 { "ok" } else { "" }); if err < self.max_hypot2 { let result = QuadBez::new(seg.p0, ((p1x2 + p2x2) / 4.0).to_point(), seg.p3); self.t = t1; return Some((t0, t1, result)); } else { let shrink = if t1 == 1.0 && err < 64.0 * self.max_hypot2 {
0.999_999 * libm::pow(self.max_hypot2 / err, 1. / 6.0) //// ////0.999_999 * (self.max_hypot2 / err).powf(1. / 6.0) }; t1 = t0 + shrink * (t1 - t0); } } } } #[cfg(test)] mod tests { use crate::{ Affine, CubicBez, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, Point, }; #[test] fn cubicbez_deriv() { // y = x^2 let c = CubicBez::new( (0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0, 1.0), ); let deriv = c.deriv(); let n = 10; for i in 0..=n { let t = (i as f64) * (n as f64).recip(); let delta = 1e-6; let p = c.eval(t); let p1 = c.eval(t + delta); let d_approx = (p1 - p) * delta.recip(); let d = deriv.eval(t).to_vec2(); assert!((d - d_approx).hypot() < delta * 2.0); } } #[test] fn cubicbez_arclen() { // y = x^2 let c = CubicBez::new( (0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0, 1.0), ); let true_arclen = 0.5 * libm::sqrt(5.0f64) + 0.25 * (2.0 + libm::sqrt(5.0f64)).ln(); for i in 0..12 { let accuracy = 0.1f64.powi(i); let error = c.arclen(accuracy) - true_arclen; //println!("{:e}: {:e}", accuracy, error); assert!(error.abs() < accuracy); } } #[test] fn cubicbez_inv_arclen() { // y = x^2 let c = CubicBez::new( (0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0, 1.0), ); let true_arclen = 0.5 * libm::sqrt(5.0f64) + 0.25 * (2.0 + libm::sqrt(5.0f64)).ln(); for i in 0..12 { let accuracy = 0.1f64.powi(i); let n = 10; for j in 0..=n { let arc = (j as f64) * ((n as f64).recip() * true_arclen); let t = c.inv_arclen(arc, accuracy * 0.5); let actual_arc = c.subsegment(0.0..t).arclen(accuracy * 0.5); assert!( (arc - actual_arc).abs() < accuracy, "at accuracy {:e}, wanted {} got {}", accuracy, actual_arc, arc ); } } } #[test] fn cubicbez_signed_area_linear() { // y = 1 - x let c = CubicBez::new( (1.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0 / 3.0, 2.0 / 3.0), (0.0, 1.0), ); let epsilon = 1e-12; assert_eq!((Affine::rotate(0.5) * c).signed_area(), 0.5); assert!(((Affine::rotate(0.5) * c).signed_area() - 0.5).abs() < epsilon); assert!(((Affine::translate((0.0, 1.0)) * c).signed_area() - 1.0).abs() < epsilon); assert!(((Affine::translate((1.0, 0.0)) * c).signed_area() - 1.0).abs() < epsilon); } #[test] fn cubicbez_signed_area() { // y = 1 - x^3 let c = CubicBez::new((1.0, 0.0), (2.0 / 3.0, 1.0), (1.0 / 3.0, 1.0), (0.0, 1.0)); let epsilon = 1e-12; assert!((c.signed_area() - 0.75).abs() < epsilon); assert!(((Affine::rotate(0.5) * c).signed_area() - 0.75).abs() < epsilon); assert!(((Affine::translate((0.0, 1.0)) * c).signed_area() - 1.25).abs() < epsilon); assert!(((Affine::translate((1.0, 0.0)) * c).signed_area() - 1.25).abs() < epsilon); } #[test] fn cubicbez_nearest() { fn verify(result: (f64, f64), expected: f64) { assert!( (result.0 - expected).abs() < 1e-6, "got {:?} expected {}", result, expected ); } // y = x^3 let c = CubicBez::new((0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 0.0), (1.0, 1.0)); verify(c.nearest((0.1, 0.001).into(), 1e-6), 0.1); verify(c.nearest((0.2, 0.008).into(), 1e-6), 0.2); verify(c.nearest((0.3, 0.027).into(), 1e-6), 0.3); verify(c.nearest((0.4, 0.064).into(), 1e-6), 0.4); verify(c.nearest((0.5, 0.125).into(), 1e-6), 0.5); verify(c.nearest((0.6, 0.216).into(), 1e-6), 0.6); verify(c.nearest((0.7, 0.343).into(), 1e-6), 0.7); verify(c.nearest((0.8, 0.512).into(), 1e-6), 0.8); verify(c.nearest((0.9, 0.729).into(), 1e-6), 0.9); verify(c.nearest((1.0, 1.0).into(), 1e-6), 1.0); verify(c.nearest((1.1, 1.1).into(), 1e-6), 1.0); verify(c.nearest((-0.1, 0.0).into(), 1e-6), 0.0); let a = Affine::rotate(0.5); verify((a * c).nearest(a * Point::new(0.1, 0.001), 1e-6), 0.1); } #[test] fn cubicbez_extrema() { // y = x^2 let q = CubicBez::new((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)); let extrema = q.extrema(); assert_eq!(extrema.len(), 1); assert!((extrema[0] - 0.5).abs() < 1e-6); let q = CubicBez::new((0.4, 0.5), (0.0, 1.0), (1.0, 0.0), (0.5, 0.4)); let extrema = q.extrema(); assert_eq!(extrema.len(), 4); } #[test] fn cubicbez_toquads() { // y = x^3 let c = CubicBez::new((0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 0.0), (1.0, 1.0)); for i in 0..10 { let accuracy = 0.1f64.powi(i); let mut _count = 0; let mut worst: f64 = 0.0; for (t0, t1, q) in c.to_quads(accuracy) { _count += 1; let epsilon = 1e-12; assert!((q.start() - c.eval(t0)).hypot() < epsilon); assert!((q.end() - c.eval(t1)).hypot() < epsilon); let n = 4; for j in 0..=n { let t = (j as f64) * (n as f64).recip(); let p = q.eval(t); let err = (p.y - p.x.powi(3)).abs(); worst = worst.max(err); assert!(err < accuracy, "got {} wanted {}", err, accuracy); } }
0.5 } else {
conditional_block
cubicbez.rs
Mul, Range}; //// ////use std::ops::{Mul, Range}; use introsort; //// use crate::MAX_EXTREMA; use arrayvec::ArrayVec; use crate::common::solve_quadratic; use crate::common::GAUSS_LEGENDRE_COEFFS_9; use crate::{ Affine, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveCurvature, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, Point, QuadBez, }; /// A single cubic Bézier segment. #[derive(Clone, Copy, Debug, PartialEq)] pub struct CubicBez { pub p0: Point, pub p1: Point, pub p2: Point, pub p3: Point, } /// An iterator which produces quadratic Bézier segments. struct ToQuads { c: CubicBez, max_hypot2: f64, t: f64, } impl CubicBez { /// Create a new cubic Bézier segment. #[inline] pub fn new<P: Into<Point>>(p0: P, p1: P, p2: P, p3: P) -> CubicBez { CubicBez { p0: p0.into(), p1: p1.into(), p2: p2.into(), p3: p3.into(), } } /// Convert to quadratic Béziers. /// /// The iterator returns the start and end parameter in the cubic of each quadratic /// segment, along with the quadratic. /// /// Note that the resulting quadratic Béziers are not in general G1 continuous; /// they are optimized for minimizing distance error. #[inline] pub fn to_quads(&self, accuracy: f64) -> impl Iterator<Item = (f64, f64, QuadBez)> { // This magic number is the square of 36 / sqrt(3). // See: http://caffeineowl.com/graphics/2d/vectorial/cubic2quad01.html let max_hypot2 = 432.0 * accuracy * accuracy; ToQuads { c: *self, max_hypot2, t: 0.0, } } } impl ParamCurve for CubicBez { #[inline] fn eval(&self, t: f64) -> Point { let mt = 1.0 - t; let v = self.p0.to_vec2() * (mt * mt * mt) + (self.p1.to_vec2() * (mt * mt * 3.0) + (self.p2.to_vec2() * (mt * 3.0) + self.p3.to_vec2() * t) * t) * t; v.to_point() } #[inline] fn start(&self) -> Point { self.p0 } #[inline] fn end(&self) -> Point { self.p3 } fn subsegment(&self, range: Range<f64>) -> CubicBez { let (t0, t1) = (range.start, range.end); let p0 = self.eval(t0); let p3 = self.eval(t1); let d = self.deriv(); let scale = (t1 - t0) * (1.0 / 3.0); let p1 = p0 + scale * d.eval(t0).to_vec2(); let p2 = p3 - scale * d.eval(t1).to_vec2(); CubicBez { p0, p1, p2, p3 } } /// Subdivide into halves, using de Casteljau. #[inline] fn subdivide(&self) -> (CubicBez, CubicBez) { let pm = self.eval(0.5); ( CubicBez::new( self.p0, self.p0.midpoint(self.p1), ((self.p0.to_vec2() + self.p1.to_vec2() * 2.0 + self.p2.to_vec2()) * 0.25) .to_point(), pm, ), CubicBez::new( pm, ((self.p1.to_vec2() + self.p2.to_vec2() * 2.0 + self.p3.to_vec2()) * 0.25) .to_point(), self.p2.midpoint(self.p3), self.p3, ), ) } } impl ParamCurveDeriv for CubicBez { type DerivResult = QuadBez; #[inline] fn deriv(&self) -> QuadBez { QuadBez::new( (3.0 * (self.p1 - self.p0)).to_point(), (3.0 * (self.p2 - self.p1)).to_point(), (3.0 * (self.p3 - self.p2)).to_point(), ) } } impl ParamCurveArclen for CubicBez { /// Arclength of a cubic Bézier segment. /// /// This is an adaptive subdivision approach using Legendre-Gauss quadrature /// in the base case, and an error estimate to decide when to subdivide. fn arclen(&self, accuracy: f64) -> f64 { // Squared L2 norm of the second derivative of the cubic. fn cubic_errnorm(c: &CubicBez) -> f64 { let d = c.deriv().deriv(); let dd = d.end() - d.start(); d.start().to_vec2().hypot2() + d.start().to_vec2().dot(dd) + dd.hypot2() * (1.0 / 3.0) } fn est_gauss9_error(c: &CubicBez) -> f64 { let lc = (c.p3 - c.p0).hypot(); let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); 2.56e-8 * libm::pow(cubic_errnorm(c) / (lc * lc), 8 as f64) * lp //// ////2.56e-8 * (cubic_errnorm(c) / (lc * lc)).powi(8) * lp } const MAX_DEPTH: usize = 16; fn rec(c: &CubicBez, accuracy: f64, depth: usize) -> f64 { if depth == MAX_DEPTH || est_gauss9_error(c) < accuracy { c.gauss_arclen(GAUSS_LEGENDRE_COEFFS_9) } else { let (c0, c1) = c.subdivide(); rec(&c0, accuracy * 0.5, depth + 1) + rec(&c1, accuracy * 0.5, depth + 1) } } rec(self, accuracy, 0) } } impl ParamCurveArea for CubicBez { #[inline] fn signed_area(&self) -> f64 {
l ParamCurveNearest for CubicBez { /// Find nearest point, using subdivision. fn nearest(&self, p: Point, accuracy: f64) -> (f64, f64) { let mut best_r = None; let mut best_t = 0.0; for (t0, t1, q) in self.to_quads(accuracy) { let (t, r) = q.nearest(p, accuracy); if best_r.map(|best_r| r < best_r).unwrap_or(true) { best_t = t0 + t * (t1 - t0); best_r = Some(r); } } (best_t, best_r.unwrap()) } } impl ParamCurveCurvature for CubicBez {} impl ParamCurveExtrema for CubicBez { fn extrema(&self) -> ArrayVec<[f64; MAX_EXTREMA]> { fn one_coord(result: &mut ArrayVec<[f64; MAX_EXTREMA]>, d0: f64, d1: f64, d2: f64) { let a = d0 - 2.0 * d1 + d2; let b = 2.0 * (d1 - d0); let c = d0; let roots = solve_quadratic(c, b, a); for &t in &roots { if t > 0.0 && t < 1.0 { result.push(t); } } } let mut result = ArrayVec::<[f64; MAX_EXTREMA]>::new(); //// ////let mut result = ArrayVec::new(); let d0 = self.p1 - self.p0; let d1 = self.p2 - self.p1; let d2 = self.p3 - self.p2; one_coord(&mut result, d0.x, d1.x, d2.x); one_coord(&mut result, d0.y, d1.y, d2.y); introsort::sort_by(&mut result, &|a, b| a.partial_cmp(b).unwrap()); //// ////result.sort_by(|a, b| a.partial_cmp(b).unwrap()); result } } impl Mul<CubicBez> for Affine { type Output = CubicBez; #[inline] fn mul(self, c: CubicBez) -> CubicBez { CubicBez { p0: self * c.p0, p1: self * c.p1, p2: self * c.p2, p3: self * c.p3, } } } impl Iterator for ToQuads { type Item = (f64, f64, QuadBez); fn next(&mut self) -> Option<(f64, f64, QuadBez)> { let t0 = self.t; let mut t1 = 1.0; if t0 == t1 { return None; } loop { let seg = self.c.subsegment(t0..t1); // Compute error for candidate quadratic. let p1x2 = 3.0 * seg.p1.to_vec2() - seg.p0.to_vec2(); let p2x2 = 3.0 * seg.p2.to_vec2() - seg.p3.to_vec2(); let err = (p2x2 - p1x2).hypot2(); //println!("{:?} {} {}", t0..t1, err, if err < self.max_hypot2 { "ok" } else { "" }); if err < self.max_hypot2 { let result = QuadBez::new(seg.p0, ((p1x2 + p2x2) / 4.0).to_point(), seg.p3); self.t = t1; return Some((t0, t1, result)); } else { let shrink = if t1 == 1.0 && err < 64.0 * self.max_hypot2 { 0.5 } else { 0.999_999 * libm::pow(self.max_hypot2 / err, 1. / 6.0) //// ////0.999_999 * (self.max_hypot2 / err).powf(1. / 6.0) }; t1 = t0 + shrink * (t1 - t0); } } } } #[cfg(test)] mod tests { use crate::{ Affine, CubicBez, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, Point, }; #[test] fn cubicbez_deriv() { // y = x^2 let c = CubicBez::new( (0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0, 1.0), ); let deriv = c.deriv(); let n = 10; for i in 0..=n { let t = (i as f64) * (n as f64).recip(); let delta = 1e-6; let p = c.eval(t); let p1 = c.eval(t + delta); let d_approx = (p1 - p) * delta.recip(); let d = deriv.eval(t).to_vec2(); assert!((d - d_approx).hypot() < delta * 2.0); } } #[test] fn cubicbez_arclen() { // y = x^2 let c = CubicBez::new( (0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0, 1.0), ); let true_arclen = 0.5 * libm::sqrt(5.0f64) + 0.25 * (2.0 + libm::sqrt(5.0f64)).ln(); for i in 0..12 { let accuracy = 0.1f64.powi(i); let error = c.arclen(accuracy) - true_arclen; //println!("{:e}: {:e}", accuracy, error); assert!(error.abs() < accuracy); } } #[test] fn cubicbez_inv_arclen() { // y = x^2 let c = CubicBez::new( (0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0, 1.0), ); let true_arclen = 0.5 * libm::sqrt(5.0f64) + 0.25 * (2.0 + libm::sqrt(5.0f64)).ln(); for i in 0..12 { let accuracy = 0.1f64.powi(i); let n = 10; for j in 0..=n { let arc = (j as f64) * ((n as f64).recip() * true_arclen); let t = c.inv_arclen(arc, accuracy * 0.5); let actual_arc = c.subsegment(0.0..t).arclen(accuracy * 0.5); assert!( (arc - actual_arc).abs() < accuracy, "at accuracy {:e}, wanted {} got {}", accuracy, actual_arc, arc ); } } } #[test] fn cubicbez_signed_area_linear() { // y = 1 - x let c = CubicBez::new( (1.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0 / 3.0, 2.0 / 3.0), (0.0, 1.0), ); let epsilon = 1e-12; assert_eq!((Affine::rotate(0.5) * c).signed_area(), 0.5); assert!(((Affine::rotate(0.5) * c).signed_area() - 0.5).abs() < epsilon); assert!(((Affine::translate((0.0, 1.0)) * c).signed_area() - 1.0).abs() < epsilon); assert!(((Affine::translate((1.0, 0.0)) * c).signed_area() - 1.0).abs() < epsilon); } #[test] fn cubicbez_signed_area() { // y = 1 - x^3 let c = CubicBez::new((1.0, 0.0), (2.0 / 3.0, 1.0), (1.0 / 3.0, 1.0), (0.0, 1.0)); let epsilon = 1e-12; assert!((c.signed_area() - 0.75).abs() < epsilon); assert!(((Affine::rotate(0.5) * c).signed_area() - 0.75).abs() < epsilon); assert!(((Affine::translate((0.0, 1.0)) * c).signed_area() - 1.25).abs() < epsilon); assert!(((Affine::translate((1.0, 0.0)) * c).signed_area() - 1.25).abs() < epsilon); } #[test] fn cubicbez_nearest() { fn verify(result: (f64, f64), expected: f64) { assert!( (result.0 - expected).abs() < 1e-6, "got {:?} expected {}", result, expected ); } // y = x^3 let c = CubicBez::new((0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 0.0), (1.0, 1.0)); verify(c.nearest((0.1, 0.001).into(), 1e-6), 0.1); verify(c.nearest((0.2, 0.008).into(), 1e-6), 0.2); verify(c.nearest((0.3, 0.027).into(), 1e-6), 0.3); verify(c.nearest((0.4, 0.064).into(), 1e-6), 0.4); verify(c.nearest((0.5, 0.125).into(), 1e-6), 0.5); verify(c.nearest((0.6, 0.216).into(), 1e-6), 0.6); verify(c.nearest((0.7, 0.343).into(), 1e-6), 0.7); verify(c.nearest((0.8, 0.512).into(), 1e-6), 0.8); verify(c.nearest((0.9, 0.729).into(), 1e-6), 0.9); verify(c.nearest((1.0, 1.0).into(), 1e-6), 1.0); verify(c.nearest((1.1, 1.1).into(), 1e-6), 1.0); verify(c.nearest((-0.1, 0.0).into(), 1e-6), 0.0); let a = Affine::rotate(0.5); verify((a * c).nearest(a * Point::new(0.1, 0.001), 1e-6), 0.1); } #[test] fn cubicbez_extrema() { // y = x^2 let q = CubicBez::new((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)); let extrema = q.extrema(); assert_eq!(extrema.len(), 1); assert!((extrema[0] - 0.5).abs() < 1e-6); let q = CubicBez::new((0.4, 0.5), (0.0, 1.0), (1.0, 0.0), (0.5, 0.4)); let extrema = q.extrema(); assert_eq!(extrema.len(), 4); } #[test] fn cubicbez_toquads() { // y = x^3 let c = CubicBez::new((0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 0.0), (1.0, 1.0)); for i in 0..10 { let accuracy = 0.1f64.powi(i); let mut _count = 0; let mut worst: f64 = 0.0; for (t0, t1, q) in c.to_quads(accuracy) { _count += 1; let epsilon = 1e-12; assert!((q.start() - c.eval(t0)).hypot() < epsilon); assert!((q.end() - c.eval(t1)).hypot() < epsilon); let n = 4; for j in 0..=n { let t = (j as f64) * (n as f64).recip(); let p = q.eval(t); let err = (p.y - p.x.powi(3)).abs(); worst = worst.max(err); assert!(err < accuracy, "got {} wanted {}", err, accuracy); } }
(self.p0.x * (6.0 * self.p1.y + 3.0 * self.p2.y + self.p3.y) + 3.0 * (self.p1.x * (-2.0 * self.p0.y + self.p2.y + self.p3.y) - self.p2.x * (self.p0.y + self.p1.y - 2.0 * self.p3.y)) - self.p3.x * (self.p0.y + 3.0 * self.p1.y + 6.0 * self.p2.y)) * (1.0 / 20.0) } } imp
identifier_body
controller.rs
mod cli; mod collect; mod detector; mod init; mod reconcile_queue; mod reconciler; mod supervisor; mod validate_api_server; pub use self::{ collect::Collect, reconciler::{ReconcileContext, ReconcileStatus}, }; use self::collect::ControllerDescriptionCollector; use crate::controller::reconcile_queue::QueueConfig; use anyhow::Context as _; use async_trait::async_trait; use futures::future::FutureExt; use k8s_openapi::{ apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition, apimachinery::pkg::apis::meta::v1::OwnerReference, }; use kube::api::{Api, ApiResource, DynamicObject, Resource, ResourceExt}; use serde::de::DeserializeOwned; use std::{sync::Arc, time::Duration}; /// Type, wrapping several controllers and providing all /// required infrastructure for them to work. pub struct ControllerManager { controllers: Vec<DynController>, } impl ControllerManager { pub fn new() -> Self { ControllerManager { controllers: Vec::new(), } } /// Adds a controller /// # Panics /// Panics if `<C as Controller>::describe` is incorrect pub fn add<C: Controller>(&mut self) { let collector = ControllerDescriptionCollector::new(); C::describe(&collector); let meta = collector.finalize(); let vtable = ControllerVtable::of::<C>(); let dc = DynController { meta, vtable }; dc.validate(); self.controllers.push(dc); } /// Controller manger entry point. /// /// This function parses command line arguments, /// launches web server and serves to completion #[tracing::instrument(skip(self))] pub async fn main(self) -> anyhow::Result<()> { let args: cli::Args = clap::Clap::parse(); tracing::info!(args =?args, "parsed command-line arguments"); match args { cli::Args::List => self.print_list(), cli::Args::Run(args) => self.run(args).await?, cli::Args::PrintCustomResources => self.crd_print(), cli::Args::ApplyCustomResources => self.crd_apply().await?, } Ok(()) } fn print_list(self) { println!("Supported controllers:"); for c in &self.controllers { let crd_info = if let Some(crd) = c.meta.crd.as_ref() { format!( "(Custom Resource: {}/{})", crd.name(), (c.vtable.api_resource)().version ) } else { "".to_string() }; println!("\t{}{}", c.meta.name, crd_info); } } fn crd_print(self) { for c in &self.controllers { if let Some(crd) = c.meta.crd.as_ref() { let crd = serde_yaml::to_string(&crd).expect("failed to serialize CRD"); print!("{}", crd); } } } async fn crd_apply(self) -> anyhow::Result<()> { let k = kube::Client::try_default() .await .context("failed to connect to cluster")?; let crd_api = Api::<CustomResourceDefinition>::all(k); for c in &self.controllers { if let Some(crd) = c.meta.crd.as_ref() { println!("Reconciling crd {}", crd.name()); match crd_api.get(&crd.name()).await { Ok(existing) => { let report = crate::crds::is_subset_of(&existing, &crd, false); report .into_result() .context("Error: can not safely replace existing crd")?; println!("Updating crd {}", crd.name()); let mut crd = crd.clone(); crd.meta_mut().resource_version = existing.resource_version(); crd_api .replace(&crd.name(), &Default::default(), &crd) .await?; } Err(err) if crate::errors::classify_kube(&err) == crate::errors::ErrorClass::NotFound => { println!("Creating crd {}", crd.name()); crd_api.create(&Default::default(), &crd).await?; } Err(err) => { return Err(err).context("failed to get existing CRD"); } } } } Ok(()) } #[tracing::instrument(skip(self, args))] async fn run(self, args: cli::Run) -> anyhow::Result<()> { let enabled_controllers = { let controllers = self .controllers .iter() .map(|c| c.meta.name.clone()) .collect::<Vec<_>>(); init::process_controller_filters(&controllers, &args.controllers)? }; tracing::info!(enabled_controllers =?enabled_controllers, "Selected controllers to run"); tracing::info!("Connecting to Kubernetes"); let client = kube::Client::try_default() .await .context("Failed to connect to kubernetes API")?; tracing::info!("Starting version skew checker"); let version_skew_check_fut = { let client = client.clone(); async move { loop { let sleep_timeout = match validate_api_server::check_api_server_version(&client).await { Ok(_) => 3600, Err(e) =>
}; tokio::time::sleep(Duration::from_secs(sleep_timeout)).await; } } }; tokio::task::spawn(version_skew_check_fut); //tracing::info!("Discovering cluster APIs"); //let discovery = Arc::new(Discovery::new(&client).await?); let watcher_set = crate::multiwatch::WatcherSet::new(client.clone()); let watcher_set = Arc::new(watcher_set); let mut supervised = Vec::new(); for controller in enabled_controllers { let dc = self .controllers .iter() .find(|c| c.meta.name == controller) .unwrap() .clone(); let cfg = QueueConfig { throttle: Duration::from_secs(3), }; let ctl = supervisor::supervise(dc, watcher_set.clone(), client.clone(), cfg); supervised.push(ctl); } { let mut cancel = Vec::new(); for ctl in &supervised { cancel.push(ctl.get_cancellation_token()); } tokio::task::spawn(async move { tracing::info!("Waiting for termination signal"); match tokio::signal::ctrl_c().await { Ok(_) => { tracing::info!("Got termination signal"); for c in cancel { c.cancel(); } } Err(e) => { tracing::warn!("Failed to wait for termination signal: {:#}", e); } } }); } tracing::info!("Waiting for supervisors exit"); for ctl in supervised { ctl.wait().await; } Ok(()) } } /// Description of a controller #[derive(Clone)] struct ControllerDescription { name: String, crd: Option<CustomResourceDefinition>, watches: Vec<ApiResource>, } #[derive(Clone)] pub(crate) struct DynController { meta: ControllerDescription, vtable: ControllerVtable, } impl DynController { fn validate(&self) { if let Some(crd) = self.meta.crd.as_ref() { let res = (self.vtable.api_resource)(); assert_eq!(crd.spec.names.plural, res.plural); assert_eq!(crd.spec.names.kind, res.kind); assert_eq!(crd.spec.group, res.group); let has_version = crd.spec.versions.iter().any(|ver| ver.name == res.version); assert!(has_version); } } } #[derive(Clone)] struct ControllerVtable { api_resource: fn() -> ApiResource, reconcile: fn( DynamicObject, cx: &mut ReconcileContext, ) -> futures::future::BoxFuture<'_, anyhow::Result<ReconcileStatus>>, } impl ControllerVtable { fn of<C: Controller>() -> Self { ControllerVtable { api_resource: || ApiResource::erase::<C::Resource>(&C::resource_dynamic_type()), reconcile: |obj, cx| { async move { // TODO: debug this let obj = serde_json::to_string(&obj).unwrap(); let obj = serde_json::from_str(&obj).context("failed to parse DynamicObject")?; C::reconcile(cx, obj).await } .boxed() }, } } } pub fn make_owner_reference<Owner: Resource>( owner: &Owner, dt: &Owner::DynamicType, ) -> OwnerReference { OwnerReference { api_version: Owner::api_version(dt).to_string(), block_owner_deletion: None, controller: Some(true), kind: Owner::kind(dt).to_string(), name: owner.name(), uid: owner.uid().expect("missing uid on persisted object"), } } pub fn downcast_dynamic_object<K: Resource<DynamicType = ()> + DeserializeOwned>( obj: &DynamicObject, ) -> anyhow::Result<K> { let obj = serde_json::to_value(obj)?; let obj = serde_json::from_value(obj)?; Ok(obj) } /// Trait, implemented by a controller #[async_trait] pub trait Controller { /// Resource which manages the controller behavior /// (e.g. Deployment for deployment controller) type Resource: Resource + DeserializeOwned + Send; /// Additional data for dynamic types fn resource_dynamic_type() -> <Self::Resource as Resource>::DynamicType; /// Reports some information to given collector fn describe<C: Collect>(collector: &C); /// Reconciles single object async fn reconcile( cx: &mut ReconcileContext, resource: Self::Resource, ) -> anyhow::Result<ReconcileStatus>; }
{ tracing::warn!("Failed to validate api server version: {:#}", e); 10 }
conditional_block
controller.rs
mod cli; mod collect; mod detector; mod init; mod reconcile_queue; mod reconciler; mod supervisor; mod validate_api_server; pub use self::{ collect::Collect, reconciler::{ReconcileContext, ReconcileStatus}, }; use self::collect::ControllerDescriptionCollector; use crate::controller::reconcile_queue::QueueConfig; use anyhow::Context as _; use async_trait::async_trait; use futures::future::FutureExt; use k8s_openapi::{ apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition, apimachinery::pkg::apis::meta::v1::OwnerReference, }; use kube::api::{Api, ApiResource, DynamicObject, Resource, ResourceExt}; use serde::de::DeserializeOwned; use std::{sync::Arc, time::Duration}; /// Type, wrapping several controllers and providing all /// required infrastructure for them to work. pub struct ControllerManager { controllers: Vec<DynController>, } impl ControllerManager { pub fn new() -> Self { ControllerManager { controllers: Vec::new(), } } /// Adds a controller /// # Panics /// Panics if `<C as Controller>::describe` is incorrect pub fn add<C: Controller>(&mut self) { let collector = ControllerDescriptionCollector::new(); C::describe(&collector); let meta = collector.finalize(); let vtable = ControllerVtable::of::<C>(); let dc = DynController { meta, vtable }; dc.validate(); self.controllers.push(dc); } /// Controller manger entry point. /// /// This function parses command line arguments, /// launches web server and serves to completion #[tracing::instrument(skip(self))] pub async fn main(self) -> anyhow::Result<()> { let args: cli::Args = clap::Clap::parse(); tracing::info!(args =?args, "parsed command-line arguments"); match args { cli::Args::List => self.print_list(), cli::Args::Run(args) => self.run(args).await?, cli::Args::PrintCustomResources => self.crd_print(), cli::Args::ApplyCustomResources => self.crd_apply().await?, } Ok(()) } fn print_list(self) { println!("Supported controllers:"); for c in &self.controllers { let crd_info = if let Some(crd) = c.meta.crd.as_ref() { format!( "(Custom Resource: {}/{})", crd.name(), (c.vtable.api_resource)().version ) } else { "".to_string() }; println!("\t{}{}", c.meta.name, crd_info); } } fn crd_print(self) { for c in &self.controllers { if let Some(crd) = c.meta.crd.as_ref() { let crd = serde_yaml::to_string(&crd).expect("failed to serialize CRD"); print!("{}", crd); } } } async fn crd_apply(self) -> anyhow::Result<()> { let k = kube::Client::try_default() .await .context("failed to connect to cluster")?; let crd_api = Api::<CustomResourceDefinition>::all(k); for c in &self.controllers { if let Some(crd) = c.meta.crd.as_ref() { println!("Reconciling crd {}", crd.name()); match crd_api.get(&crd.name()).await { Ok(existing) => { let report = crate::crds::is_subset_of(&existing, &crd, false); report .into_result() .context("Error: can not safely replace existing crd")?; println!("Updating crd {}", crd.name()); let mut crd = crd.clone(); crd.meta_mut().resource_version = existing.resource_version(); crd_api .replace(&crd.name(), &Default::default(), &crd) .await?; } Err(err) if crate::errors::classify_kube(&err) == crate::errors::ErrorClass::NotFound => { println!("Creating crd {}", crd.name()); crd_api.create(&Default::default(), &crd).await?; } Err(err) => { return Err(err).context("failed to get existing CRD"); } } } } Ok(()) } #[tracing::instrument(skip(self, args))] async fn run(self, args: cli::Run) -> anyhow::Result<()> { let enabled_controllers = { let controllers = self .controllers .iter() .map(|c| c.meta.name.clone()) .collect::<Vec<_>>(); init::process_controller_filters(&controllers, &args.controllers)? }; tracing::info!(enabled_controllers =?enabled_controllers, "Selected controllers to run"); tracing::info!("Connecting to Kubernetes"); let client = kube::Client::try_default() .await .context("Failed to connect to kubernetes API")?; tracing::info!("Starting version skew checker"); let version_skew_check_fut = { let client = client.clone(); async move { loop { let sleep_timeout = match validate_api_server::check_api_server_version(&client).await { Ok(_) => 3600, Err(e) => { tracing::warn!("Failed to validate api server version: {:#}", e); 10 } }; tokio::time::sleep(Duration::from_secs(sleep_timeout)).await; } } }; tokio::task::spawn(version_skew_check_fut); //tracing::info!("Discovering cluster APIs"); //let discovery = Arc::new(Discovery::new(&client).await?); let watcher_set = crate::multiwatch::WatcherSet::new(client.clone()); let watcher_set = Arc::new(watcher_set); let mut supervised = Vec::new(); for controller in enabled_controllers { let dc = self .controllers .iter() .find(|c| c.meta.name == controller) .unwrap() .clone(); let cfg = QueueConfig { throttle: Duration::from_secs(3), }; let ctl = supervisor::supervise(dc, watcher_set.clone(), client.clone(), cfg); supervised.push(ctl); } { let mut cancel = Vec::new(); for ctl in &supervised { cancel.push(ctl.get_cancellation_token()); } tokio::task::spawn(async move { tracing::info!("Waiting for termination signal"); match tokio::signal::ctrl_c().await { Ok(_) => { tracing::info!("Got termination signal"); for c in cancel { c.cancel(); } } Err(e) => { tracing::warn!("Failed to wait for termination signal: {:#}", e); } } }); } tracing::info!("Waiting for supervisors exit"); for ctl in supervised { ctl.wait().await; } Ok(()) } } /// Description of a controller #[derive(Clone)] struct ControllerDescription { name: String, crd: Option<CustomResourceDefinition>, watches: Vec<ApiResource>, } #[derive(Clone)] pub(crate) struct DynController { meta: ControllerDescription, vtable: ControllerVtable, } impl DynController { fn
(&self) { if let Some(crd) = self.meta.crd.as_ref() { let res = (self.vtable.api_resource)(); assert_eq!(crd.spec.names.plural, res.plural); assert_eq!(crd.spec.names.kind, res.kind); assert_eq!(crd.spec.group, res.group); let has_version = crd.spec.versions.iter().any(|ver| ver.name == res.version); assert!(has_version); } } } #[derive(Clone)] struct ControllerVtable { api_resource: fn() -> ApiResource, reconcile: fn( DynamicObject, cx: &mut ReconcileContext, ) -> futures::future::BoxFuture<'_, anyhow::Result<ReconcileStatus>>, } impl ControllerVtable { fn of<C: Controller>() -> Self { ControllerVtable { api_resource: || ApiResource::erase::<C::Resource>(&C::resource_dynamic_type()), reconcile: |obj, cx| { async move { // TODO: debug this let obj = serde_json::to_string(&obj).unwrap(); let obj = serde_json::from_str(&obj).context("failed to parse DynamicObject")?; C::reconcile(cx, obj).await } .boxed() }, } } } pub fn make_owner_reference<Owner: Resource>( owner: &Owner, dt: &Owner::DynamicType, ) -> OwnerReference { OwnerReference { api_version: Owner::api_version(dt).to_string(), block_owner_deletion: None, controller: Some(true), kind: Owner::kind(dt).to_string(), name: owner.name(), uid: owner.uid().expect("missing uid on persisted object"), } } pub fn downcast_dynamic_object<K: Resource<DynamicType = ()> + DeserializeOwned>( obj: &DynamicObject, ) -> anyhow::Result<K> { let obj = serde_json::to_value(obj)?; let obj = serde_json::from_value(obj)?; Ok(obj) } /// Trait, implemented by a controller #[async_trait] pub trait Controller { /// Resource which manages the controller behavior /// (e.g. Deployment for deployment controller) type Resource: Resource + DeserializeOwned + Send; /// Additional data for dynamic types fn resource_dynamic_type() -> <Self::Resource as Resource>::DynamicType; /// Reports some information to given collector fn describe<C: Collect>(collector: &C); /// Reconciles single object async fn reconcile( cx: &mut ReconcileContext, resource: Self::Resource, ) -> anyhow::Result<ReconcileStatus>; }
validate
identifier_name
controller.rs
mod cli; mod collect; mod detector; mod init; mod reconcile_queue; mod reconciler; mod supervisor; mod validate_api_server; pub use self::{ collect::Collect, reconciler::{ReconcileContext, ReconcileStatus}, }; use self::collect::ControllerDescriptionCollector; use crate::controller::reconcile_queue::QueueConfig; use anyhow::Context as _; use async_trait::async_trait; use futures::future::FutureExt; use k8s_openapi::{ apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition, apimachinery::pkg::apis::meta::v1::OwnerReference, }; use kube::api::{Api, ApiResource, DynamicObject, Resource, ResourceExt}; use serde::de::DeserializeOwned; use std::{sync::Arc, time::Duration}; /// Type, wrapping several controllers and providing all /// required infrastructure for them to work. pub struct ControllerManager { controllers: Vec<DynController>, } impl ControllerManager { pub fn new() -> Self { ControllerManager { controllers: Vec::new(), } } /// Adds a controller /// # Panics /// Panics if `<C as Controller>::describe` is incorrect pub fn add<C: Controller>(&mut self) { let collector = ControllerDescriptionCollector::new(); C::describe(&collector); let meta = collector.finalize(); let vtable = ControllerVtable::of::<C>(); let dc = DynController { meta, vtable }; dc.validate(); self.controllers.push(dc); } /// Controller manger entry point. /// /// This function parses command line arguments, /// launches web server and serves to completion #[tracing::instrument(skip(self))] pub async fn main(self) -> anyhow::Result<()> { let args: cli::Args = clap::Clap::parse(); tracing::info!(args =?args, "parsed command-line arguments"); match args { cli::Args::List => self.print_list(), cli::Args::Run(args) => self.run(args).await?, cli::Args::PrintCustomResources => self.crd_print(), cli::Args::ApplyCustomResources => self.crd_apply().await?, } Ok(()) } fn print_list(self) { println!("Supported controllers:"); for c in &self.controllers { let crd_info = if let Some(crd) = c.meta.crd.as_ref() { format!( "(Custom Resource: {}/{})", crd.name(), (c.vtable.api_resource)().version ) } else { "".to_string() }; println!("\t{}{}", c.meta.name, crd_info); } } fn crd_print(self) { for c in &self.controllers { if let Some(crd) = c.meta.crd.as_ref() { let crd = serde_yaml::to_string(&crd).expect("failed to serialize CRD"); print!("{}", crd); } } } async fn crd_apply(self) -> anyhow::Result<()> { let k = kube::Client::try_default() .await .context("failed to connect to cluster")?; let crd_api = Api::<CustomResourceDefinition>::all(k); for c in &self.controllers { if let Some(crd) = c.meta.crd.as_ref() { println!("Reconciling crd {}", crd.name()); match crd_api.get(&crd.name()).await { Ok(existing) => { let report = crate::crds::is_subset_of(&existing, &crd, false); report .into_result() .context("Error: can not safely replace existing crd")?; println!("Updating crd {}", crd.name()); let mut crd = crd.clone(); crd.meta_mut().resource_version = existing.resource_version(); crd_api .replace(&crd.name(), &Default::default(), &crd) .await?; } Err(err) if crate::errors::classify_kube(&err) == crate::errors::ErrorClass::NotFound => { println!("Creating crd {}", crd.name()); crd_api.create(&Default::default(), &crd).await?; } Err(err) => { return Err(err).context("failed to get existing CRD"); } } } } Ok(()) } #[tracing::instrument(skip(self, args))] async fn run(self, args: cli::Run) -> anyhow::Result<()> { let enabled_controllers = { let controllers = self .controllers .iter() .map(|c| c.meta.name.clone()) .collect::<Vec<_>>(); init::process_controller_filters(&controllers, &args.controllers)? }; tracing::info!(enabled_controllers =?enabled_controllers, "Selected controllers to run"); tracing::info!("Connecting to Kubernetes"); let client = kube::Client::try_default() .await .context("Failed to connect to kubernetes API")?; tracing::info!("Starting version skew checker"); let version_skew_check_fut = { let client = client.clone(); async move { loop { let sleep_timeout = match validate_api_server::check_api_server_version(&client).await { Ok(_) => 3600, Err(e) => { tracing::warn!("Failed to validate api server version: {:#}", e); 10 } }; tokio::time::sleep(Duration::from_secs(sleep_timeout)).await; } } }; tokio::task::spawn(version_skew_check_fut); //tracing::info!("Discovering cluster APIs"); //let discovery = Arc::new(Discovery::new(&client).await?); let watcher_set = crate::multiwatch::WatcherSet::new(client.clone()); let watcher_set = Arc::new(watcher_set); let mut supervised = Vec::new(); for controller in enabled_controllers { let dc = self .controllers .iter() .find(|c| c.meta.name == controller) .unwrap() .clone(); let cfg = QueueConfig { throttle: Duration::from_secs(3), }; let ctl = supervisor::supervise(dc, watcher_set.clone(), client.clone(), cfg); supervised.push(ctl); } { let mut cancel = Vec::new(); for ctl in &supervised { cancel.push(ctl.get_cancellation_token()); } tokio::task::spawn(async move { tracing::info!("Waiting for termination signal"); match tokio::signal::ctrl_c().await { Ok(_) => { tracing::info!("Got termination signal"); for c in cancel { c.cancel(); } } Err(e) => { tracing::warn!("Failed to wait for termination signal: {:#}", e); } } }); } tracing::info!("Waiting for supervisors exit"); for ctl in supervised { ctl.wait().await;
} Ok(()) } } /// Description of a controller #[derive(Clone)] struct ControllerDescription { name: String, crd: Option<CustomResourceDefinition>, watches: Vec<ApiResource>, } #[derive(Clone)] pub(crate) struct DynController { meta: ControllerDescription, vtable: ControllerVtable, } impl DynController { fn validate(&self) { if let Some(crd) = self.meta.crd.as_ref() { let res = (self.vtable.api_resource)(); assert_eq!(crd.spec.names.plural, res.plural); assert_eq!(crd.spec.names.kind, res.kind); assert_eq!(crd.spec.group, res.group); let has_version = crd.spec.versions.iter().any(|ver| ver.name == res.version); assert!(has_version); } } } #[derive(Clone)] struct ControllerVtable { api_resource: fn() -> ApiResource, reconcile: fn( DynamicObject, cx: &mut ReconcileContext, ) -> futures::future::BoxFuture<'_, anyhow::Result<ReconcileStatus>>, } impl ControllerVtable { fn of<C: Controller>() -> Self { ControllerVtable { api_resource: || ApiResource::erase::<C::Resource>(&C::resource_dynamic_type()), reconcile: |obj, cx| { async move { // TODO: debug this let obj = serde_json::to_string(&obj).unwrap(); let obj = serde_json::from_str(&obj).context("failed to parse DynamicObject")?; C::reconcile(cx, obj).await } .boxed() }, } } } pub fn make_owner_reference<Owner: Resource>( owner: &Owner, dt: &Owner::DynamicType, ) -> OwnerReference { OwnerReference { api_version: Owner::api_version(dt).to_string(), block_owner_deletion: None, controller: Some(true), kind: Owner::kind(dt).to_string(), name: owner.name(), uid: owner.uid().expect("missing uid on persisted object"), } } pub fn downcast_dynamic_object<K: Resource<DynamicType = ()> + DeserializeOwned>( obj: &DynamicObject, ) -> anyhow::Result<K> { let obj = serde_json::to_value(obj)?; let obj = serde_json::from_value(obj)?; Ok(obj) } /// Trait, implemented by a controller #[async_trait] pub trait Controller { /// Resource which manages the controller behavior /// (e.g. Deployment for deployment controller) type Resource: Resource + DeserializeOwned + Send; /// Additional data for dynamic types fn resource_dynamic_type() -> <Self::Resource as Resource>::DynamicType; /// Reports some information to given collector fn describe<C: Collect>(collector: &C); /// Reconciles single object async fn reconcile( cx: &mut ReconcileContext, resource: Self::Resource, ) -> anyhow::Result<ReconcileStatus>; }
random_line_split
flex.rs
// Copyright 2020 The Druid Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Demonstrates alignment of children in the flex container. //! This example showcases the full set of functionality of flex, giving you //! knobs to change all the parameters. 99% of the time you will want to //! hard-code these parameters, which will simplify your code considerably. use druid::text::format::ParseFormatter; use druid::widget::prelude::*; use druid::widget::{ Button, Checkbox, CrossAxisAlignment, Flex, Label, MainAxisAlignment, ProgressBar, RadioGroup, SizedBox, Slider, Stepper, Switch, TextBox, WidgetExt, }; use druid::{AppLauncher, Color, Data, Lens, WidgetId, WindowDesc}; const DEFAULT_SPACER_SIZE: f64 = 8.; const SPACER_OPTIONS: [(&str, Spacers); 4] = [ ("None", Spacers::None), ("Default", Spacers::Default), ("Flex", Spacers::Flex), ("Fixed:", Spacers::Fixed), ]; const MAIN_AXIS_ALIGNMENT_OPTIONS: [(&str, MainAxisAlignment); 6] = [ ("Start", MainAxisAlignment::Start), ("Center", MainAxisAlignment::Center), ("End", MainAxisAlignment::End), ("Between", MainAxisAlignment::SpaceBetween), ("Evenly", MainAxisAlignment::SpaceEvenly), ("Around", MainAxisAlignment::SpaceAround), ]; const CROSS_AXIS_ALIGNMENT_OPTIONS: [(&str, CrossAxisAlignment); 4] = [ ("Start", CrossAxisAlignment::Start), ("Center", CrossAxisAlignment::Center), ("End", CrossAxisAlignment::End), ("Baseline", CrossAxisAlignment::Baseline), ]; const FLEX_TYPE_OPTIONS: [(&str, FlexType); 2] = [("Row", FlexType::Row), ("Column", FlexType::Column)]; #[derive(Clone, Data, Lens)] struct AppState { demo_state: DemoState, params: Params, } #[derive(Clone, Data, Lens)] struct DemoState { pub input_text: String, pub enabled: bool, volume: f64, } #[derive(Clone, Data, Lens)] struct Params { axis: FlexType, cross_alignment: CrossAxisAlignment, main_alignment: MainAxisAlignment, fill_major_axis: bool, debug_layout: bool, fix_minor_axis: bool, fix_major_axis: bool, spacers: Spacers, spacer_size: f64, } #[derive(Clone, Copy, PartialEq, Data)] enum Spacers { None, Default, Flex, Fixed, } #[derive(Clone, Copy, PartialEq, Data)] enum FlexType { Row, Column, } /// builds a child Flex widget from some paramaters. struct Rebuilder { inner: Box<dyn Widget<AppState>>, } impl Rebuilder { fn new() -> Rebuilder { Rebuilder { inner: SizedBox::empty().boxed(), } } fn rebuild_inner(&mut self, data: &AppState) { self.inner = build_widget(&data.params); } } impl Widget<AppState> for Rebuilder { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut AppState, env: &Env) { self.inner.event(ctx, event, data, env) } fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &AppState, env: &Env) { if let LifeCycle::WidgetAdded = event { self.rebuild_inner(data); } self.inner.lifecycle(ctx, event, data, env) } fn update(&mut self, ctx: &mut UpdateCtx, old_data: &AppState, data: &AppState, env: &Env) { if!old_data.params.same(&data.params) { self.rebuild_inner(data); ctx.children_changed(); } else
} fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &AppState, env: &Env, ) -> Size { self.inner.layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &AppState, env: &Env) { self.inner.paint(ctx, data, env) } fn id(&self) -> Option<WidgetId> { self.inner.id() } } fn make_control_row() -> impl Widget<AppState> { Flex::row() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child( Flex::column() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child(Label::new("Type:")) .with_default_spacer() .with_child(RadioGroup::new(FLEX_TYPE_OPTIONS.to_vec()).lens(Params::axis)), ) .with_default_spacer() .with_child( Flex::column() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child(Label::new("CrossAxis:")) .with_default_spacer() .with_child( RadioGroup::new(CROSS_AXIS_ALIGNMENT_OPTIONS.to_vec()) .lens(Params::cross_alignment), ), ) .with_default_spacer() .with_child( Flex::column() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child(Label::new("MainAxis:")) .with_default_spacer() .with_child( RadioGroup::new(MAIN_AXIS_ALIGNMENT_OPTIONS.to_vec()) .lens(Params::main_alignment), ), ) .with_default_spacer() .with_child(make_spacer_select()) .with_default_spacer() .with_child( Flex::column() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child(Label::new("Misc:")) .with_default_spacer() .with_child(Checkbox::new("Debug layout").lens(Params::debug_layout)) .with_default_spacer() .with_child(Checkbox::new("Fill main axis").lens(Params::fill_major_axis)) .with_default_spacer() .with_child(Checkbox::new("Fix minor axis size").lens(Params::fix_minor_axis)) .with_default_spacer() .with_child(Checkbox::new("Fix major axis size").lens(Params::fix_major_axis)), ) .padding(10.0) .border(Color::grey(0.6), 2.0) .rounded(5.0) .lens(AppState::params) } fn make_spacer_select() -> impl Widget<Params> { Flex::column() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child(Label::new("Insert Spacers:")) .with_default_spacer() .with_child(RadioGroup::new(SPACER_OPTIONS.to_vec()).lens(Params::spacers)) .with_default_spacer() .with_child( Flex::row() .with_child( TextBox::new() .with_formatter(ParseFormatter::new()) .lens(Params::spacer_size) .fix_width(60.0), ) .with_spacer(druid::theme::WIDGET_CONTROL_COMPONENT_PADDING) .with_child( Stepper::new() .with_range(2.0, 50.0) .with_step(2.0) .lens(Params::spacer_size), ), ) } fn space_if_needed<T: Data>(flex: &mut Flex<T>, params: &Params) { match params.spacers { Spacers::None => (), Spacers::Default => flex.add_default_spacer(), Spacers::Fixed => flex.add_spacer(params.spacer_size), Spacers::Flex => flex.add_flex_spacer(1.0), } } fn build_widget(state: &Params) -> Box<dyn Widget<AppState>> { let mut flex = match state.axis { FlexType::Column => Flex::column(), FlexType::Row => Flex::row(), } .cross_axis_alignment(state.cross_alignment) .main_axis_alignment(state.main_alignment) .must_fill_main_axis(state.fill_major_axis); flex.add_child( TextBox::new() .with_placeholder("Sample text") .lens(DemoState::input_text), ); space_if_needed(&mut flex, state); flex.add_child( Button::new("Clear").on_click(|_ctx, data: &mut DemoState, _env| { data.input_text.clear(); data.enabled = false; data.volume = 0.0; }), ); space_if_needed(&mut flex, state); flex.add_child( Label::new(|data: &DemoState, _: &Env| data.input_text.clone()).with_text_size(32.0), ); space_if_needed(&mut flex, state); flex.add_child(Checkbox::new("Demo").lens(DemoState::enabled)); space_if_needed(&mut flex, state); flex.add_child(Switch::new().lens(DemoState::enabled)); space_if_needed(&mut flex, state); flex.add_child(Slider::new().lens(DemoState::volume)); space_if_needed(&mut flex, state); flex.add_child(ProgressBar::new().lens(DemoState::volume)); space_if_needed(&mut flex, state); flex.add_child( Stepper::new() .with_range(0.0, 1.0) .with_step(0.1) .with_wraparound(true) .lens(DemoState::volume), ); let mut flex = SizedBox::new(flex); if state.fix_minor_axis { match state.axis { FlexType::Row => flex = flex.height(200.), FlexType::Column => flex = flex.width(200.), } } if state.fix_major_axis { match state.axis { FlexType::Row => flex = flex.width(600.), FlexType::Column => flex = flex.height(300.), } } let flex = flex .padding(8.0) .border(Color::grey(0.6), 2.0) .rounded(5.0) .lens(AppState::demo_state); if state.debug_layout { flex.debug_paint_layout().boxed() } else { flex.boxed() } } fn make_ui() -> impl Widget<AppState> { Flex::column() .must_fill_main_axis(true) .with_child(make_control_row()) .with_default_spacer() .with_flex_child(Rebuilder::new().center(), 1.0) .padding(10.0) } pub fn main() { let main_window = WindowDesc::new(make_ui) .window_size((720., 600.)) .with_min_size((620., 300.)) .title("Flex Container Options"); let demo_state = DemoState { input_text: "hello".into(), enabled: false, volume: 0.0, }; let params = Params { axis: FlexType::Row, cross_alignment: CrossAxisAlignment::Center, main_alignment: MainAxisAlignment::Start, debug_layout: false, fix_minor_axis: false, fix_major_axis: false, spacers: Spacers::None, spacer_size: DEFAULT_SPACER_SIZE, fill_major_axis: false, }; AppLauncher::with_window(main_window) .use_simple_logger() .launch(AppState { demo_state, params }) .expect("Failed to launch application"); }
{ self.inner.update(ctx, old_data, data, env); }
conditional_block
flex.rs
// Copyright 2020 The Druid Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Demonstrates alignment of children in the flex container. //! This example showcases the full set of functionality of flex, giving you //! knobs to change all the parameters. 99% of the time you will want to //! hard-code these parameters, which will simplify your code considerably. use druid::text::format::ParseFormatter; use druid::widget::prelude::*; use druid::widget::{ Button, Checkbox, CrossAxisAlignment, Flex, Label, MainAxisAlignment, ProgressBar, RadioGroup, SizedBox, Slider, Stepper, Switch, TextBox, WidgetExt, }; use druid::{AppLauncher, Color, Data, Lens, WidgetId, WindowDesc}; const DEFAULT_SPACER_SIZE: f64 = 8.; const SPACER_OPTIONS: [(&str, Spacers); 4] = [ ("None", Spacers::None), ("Default", Spacers::Default), ("Flex", Spacers::Flex), ("Fixed:", Spacers::Fixed), ]; const MAIN_AXIS_ALIGNMENT_OPTIONS: [(&str, MainAxisAlignment); 6] = [ ("Start", MainAxisAlignment::Start), ("Center", MainAxisAlignment::Center), ("End", MainAxisAlignment::End), ("Between", MainAxisAlignment::SpaceBetween), ("Evenly", MainAxisAlignment::SpaceEvenly), ("Around", MainAxisAlignment::SpaceAround), ]; const CROSS_AXIS_ALIGNMENT_OPTIONS: [(&str, CrossAxisAlignment); 4] = [ ("Start", CrossAxisAlignment::Start), ("Center", CrossAxisAlignment::Center), ("End", CrossAxisAlignment::End), ("Baseline", CrossAxisAlignment::Baseline), ]; const FLEX_TYPE_OPTIONS: [(&str, FlexType); 2] = [("Row", FlexType::Row), ("Column", FlexType::Column)]; #[derive(Clone, Data, Lens)] struct AppState { demo_state: DemoState, params: Params, } #[derive(Clone, Data, Lens)] struct DemoState { pub input_text: String, pub enabled: bool, volume: f64, } #[derive(Clone, Data, Lens)] struct Params { axis: FlexType, cross_alignment: CrossAxisAlignment, main_alignment: MainAxisAlignment, fill_major_axis: bool, debug_layout: bool, fix_minor_axis: bool, fix_major_axis: bool, spacers: Spacers, spacer_size: f64, } #[derive(Clone, Copy, PartialEq, Data)] enum Spacers { None, Default, Flex, Fixed, } #[derive(Clone, Copy, PartialEq, Data)] enum FlexType { Row, Column, } /// builds a child Flex widget from some paramaters. struct Rebuilder { inner: Box<dyn Widget<AppState>>, } impl Rebuilder { fn new() -> Rebuilder { Rebuilder { inner: SizedBox::empty().boxed(), } } fn rebuild_inner(&mut self, data: &AppState) { self.inner = build_widget(&data.params); } } impl Widget<AppState> for Rebuilder { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut AppState, env: &Env) { self.inner.event(ctx, event, data, env) } fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &AppState, env: &Env) { if let LifeCycle::WidgetAdded = event { self.rebuild_inner(data); } self.inner.lifecycle(ctx, event, data, env) } fn update(&mut self, ctx: &mut UpdateCtx, old_data: &AppState, data: &AppState, env: &Env) { if!old_data.params.same(&data.params) { self.rebuild_inner(data); ctx.children_changed(); } else { self.inner.update(ctx, old_data, data, env); } } fn
( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &AppState, env: &Env, ) -> Size { self.inner.layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &AppState, env: &Env) { self.inner.paint(ctx, data, env) } fn id(&self) -> Option<WidgetId> { self.inner.id() } } fn make_control_row() -> impl Widget<AppState> { Flex::row() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child( Flex::column() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child(Label::new("Type:")) .with_default_spacer() .with_child(RadioGroup::new(FLEX_TYPE_OPTIONS.to_vec()).lens(Params::axis)), ) .with_default_spacer() .with_child( Flex::column() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child(Label::new("CrossAxis:")) .with_default_spacer() .with_child( RadioGroup::new(CROSS_AXIS_ALIGNMENT_OPTIONS.to_vec()) .lens(Params::cross_alignment), ), ) .with_default_spacer() .with_child( Flex::column() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child(Label::new("MainAxis:")) .with_default_spacer() .with_child( RadioGroup::new(MAIN_AXIS_ALIGNMENT_OPTIONS.to_vec()) .lens(Params::main_alignment), ), ) .with_default_spacer() .with_child(make_spacer_select()) .with_default_spacer() .with_child( Flex::column() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child(Label::new("Misc:")) .with_default_spacer() .with_child(Checkbox::new("Debug layout").lens(Params::debug_layout)) .with_default_spacer() .with_child(Checkbox::new("Fill main axis").lens(Params::fill_major_axis)) .with_default_spacer() .with_child(Checkbox::new("Fix minor axis size").lens(Params::fix_minor_axis)) .with_default_spacer() .with_child(Checkbox::new("Fix major axis size").lens(Params::fix_major_axis)), ) .padding(10.0) .border(Color::grey(0.6), 2.0) .rounded(5.0) .lens(AppState::params) } fn make_spacer_select() -> impl Widget<Params> { Flex::column() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child(Label::new("Insert Spacers:")) .with_default_spacer() .with_child(RadioGroup::new(SPACER_OPTIONS.to_vec()).lens(Params::spacers)) .with_default_spacer() .with_child( Flex::row() .with_child( TextBox::new() .with_formatter(ParseFormatter::new()) .lens(Params::spacer_size) .fix_width(60.0), ) .with_spacer(druid::theme::WIDGET_CONTROL_COMPONENT_PADDING) .with_child( Stepper::new() .with_range(2.0, 50.0) .with_step(2.0) .lens(Params::spacer_size), ), ) } fn space_if_needed<T: Data>(flex: &mut Flex<T>, params: &Params) { match params.spacers { Spacers::None => (), Spacers::Default => flex.add_default_spacer(), Spacers::Fixed => flex.add_spacer(params.spacer_size), Spacers::Flex => flex.add_flex_spacer(1.0), } } fn build_widget(state: &Params) -> Box<dyn Widget<AppState>> { let mut flex = match state.axis { FlexType::Column => Flex::column(), FlexType::Row => Flex::row(), } .cross_axis_alignment(state.cross_alignment) .main_axis_alignment(state.main_alignment) .must_fill_main_axis(state.fill_major_axis); flex.add_child( TextBox::new() .with_placeholder("Sample text") .lens(DemoState::input_text), ); space_if_needed(&mut flex, state); flex.add_child( Button::new("Clear").on_click(|_ctx, data: &mut DemoState, _env| { data.input_text.clear(); data.enabled = false; data.volume = 0.0; }), ); space_if_needed(&mut flex, state); flex.add_child( Label::new(|data: &DemoState, _: &Env| data.input_text.clone()).with_text_size(32.0), ); space_if_needed(&mut flex, state); flex.add_child(Checkbox::new("Demo").lens(DemoState::enabled)); space_if_needed(&mut flex, state); flex.add_child(Switch::new().lens(DemoState::enabled)); space_if_needed(&mut flex, state); flex.add_child(Slider::new().lens(DemoState::volume)); space_if_needed(&mut flex, state); flex.add_child(ProgressBar::new().lens(DemoState::volume)); space_if_needed(&mut flex, state); flex.add_child( Stepper::new() .with_range(0.0, 1.0) .with_step(0.1) .with_wraparound(true) .lens(DemoState::volume), ); let mut flex = SizedBox::new(flex); if state.fix_minor_axis { match state.axis { FlexType::Row => flex = flex.height(200.), FlexType::Column => flex = flex.width(200.), } } if state.fix_major_axis { match state.axis { FlexType::Row => flex = flex.width(600.), FlexType::Column => flex = flex.height(300.), } } let flex = flex .padding(8.0) .border(Color::grey(0.6), 2.0) .rounded(5.0) .lens(AppState::demo_state); if state.debug_layout { flex.debug_paint_layout().boxed() } else { flex.boxed() } } fn make_ui() -> impl Widget<AppState> { Flex::column() .must_fill_main_axis(true) .with_child(make_control_row()) .with_default_spacer() .with_flex_child(Rebuilder::new().center(), 1.0) .padding(10.0) } pub fn main() { let main_window = WindowDesc::new(make_ui) .window_size((720., 600.)) .with_min_size((620., 300.)) .title("Flex Container Options"); let demo_state = DemoState { input_text: "hello".into(), enabled: false, volume: 0.0, }; let params = Params { axis: FlexType::Row, cross_alignment: CrossAxisAlignment::Center, main_alignment: MainAxisAlignment::Start, debug_layout: false, fix_minor_axis: false, fix_major_axis: false, spacers: Spacers::None, spacer_size: DEFAULT_SPACER_SIZE, fill_major_axis: false, }; AppLauncher::with_window(main_window) .use_simple_logger() .launch(AppState { demo_state, params }) .expect("Failed to launch application"); }
layout
identifier_name
flex.rs
// Copyright 2020 The Druid Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Demonstrates alignment of children in the flex container. //! This example showcases the full set of functionality of flex, giving you //! knobs to change all the parameters. 99% of the time you will want to //! hard-code these parameters, which will simplify your code considerably. use druid::text::format::ParseFormatter; use druid::widget::prelude::*; use druid::widget::{ Button, Checkbox, CrossAxisAlignment, Flex, Label, MainAxisAlignment, ProgressBar, RadioGroup, SizedBox, Slider, Stepper, Switch, TextBox, WidgetExt, }; use druid::{AppLauncher, Color, Data, Lens, WidgetId, WindowDesc}; const DEFAULT_SPACER_SIZE: f64 = 8.; const SPACER_OPTIONS: [(&str, Spacers); 4] = [ ("None", Spacers::None), ("Default", Spacers::Default), ("Flex", Spacers::Flex),
const MAIN_AXIS_ALIGNMENT_OPTIONS: [(&str, MainAxisAlignment); 6] = [ ("Start", MainAxisAlignment::Start), ("Center", MainAxisAlignment::Center), ("End", MainAxisAlignment::End), ("Between", MainAxisAlignment::SpaceBetween), ("Evenly", MainAxisAlignment::SpaceEvenly), ("Around", MainAxisAlignment::SpaceAround), ]; const CROSS_AXIS_ALIGNMENT_OPTIONS: [(&str, CrossAxisAlignment); 4] = [ ("Start", CrossAxisAlignment::Start), ("Center", CrossAxisAlignment::Center), ("End", CrossAxisAlignment::End), ("Baseline", CrossAxisAlignment::Baseline), ]; const FLEX_TYPE_OPTIONS: [(&str, FlexType); 2] = [("Row", FlexType::Row), ("Column", FlexType::Column)]; #[derive(Clone, Data, Lens)] struct AppState { demo_state: DemoState, params: Params, } #[derive(Clone, Data, Lens)] struct DemoState { pub input_text: String, pub enabled: bool, volume: f64, } #[derive(Clone, Data, Lens)] struct Params { axis: FlexType, cross_alignment: CrossAxisAlignment, main_alignment: MainAxisAlignment, fill_major_axis: bool, debug_layout: bool, fix_minor_axis: bool, fix_major_axis: bool, spacers: Spacers, spacer_size: f64, } #[derive(Clone, Copy, PartialEq, Data)] enum Spacers { None, Default, Flex, Fixed, } #[derive(Clone, Copy, PartialEq, Data)] enum FlexType { Row, Column, } /// builds a child Flex widget from some paramaters. struct Rebuilder { inner: Box<dyn Widget<AppState>>, } impl Rebuilder { fn new() -> Rebuilder { Rebuilder { inner: SizedBox::empty().boxed(), } } fn rebuild_inner(&mut self, data: &AppState) { self.inner = build_widget(&data.params); } } impl Widget<AppState> for Rebuilder { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut AppState, env: &Env) { self.inner.event(ctx, event, data, env) } fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &AppState, env: &Env) { if let LifeCycle::WidgetAdded = event { self.rebuild_inner(data); } self.inner.lifecycle(ctx, event, data, env) } fn update(&mut self, ctx: &mut UpdateCtx, old_data: &AppState, data: &AppState, env: &Env) { if!old_data.params.same(&data.params) { self.rebuild_inner(data); ctx.children_changed(); } else { self.inner.update(ctx, old_data, data, env); } } fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &AppState, env: &Env, ) -> Size { self.inner.layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &AppState, env: &Env) { self.inner.paint(ctx, data, env) } fn id(&self) -> Option<WidgetId> { self.inner.id() } } fn make_control_row() -> impl Widget<AppState> { Flex::row() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child( Flex::column() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child(Label::new("Type:")) .with_default_spacer() .with_child(RadioGroup::new(FLEX_TYPE_OPTIONS.to_vec()).lens(Params::axis)), ) .with_default_spacer() .with_child( Flex::column() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child(Label::new("CrossAxis:")) .with_default_spacer() .with_child( RadioGroup::new(CROSS_AXIS_ALIGNMENT_OPTIONS.to_vec()) .lens(Params::cross_alignment), ), ) .with_default_spacer() .with_child( Flex::column() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child(Label::new("MainAxis:")) .with_default_spacer() .with_child( RadioGroup::new(MAIN_AXIS_ALIGNMENT_OPTIONS.to_vec()) .lens(Params::main_alignment), ), ) .with_default_spacer() .with_child(make_spacer_select()) .with_default_spacer() .with_child( Flex::column() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child(Label::new("Misc:")) .with_default_spacer() .with_child(Checkbox::new("Debug layout").lens(Params::debug_layout)) .with_default_spacer() .with_child(Checkbox::new("Fill main axis").lens(Params::fill_major_axis)) .with_default_spacer() .with_child(Checkbox::new("Fix minor axis size").lens(Params::fix_minor_axis)) .with_default_spacer() .with_child(Checkbox::new("Fix major axis size").lens(Params::fix_major_axis)), ) .padding(10.0) .border(Color::grey(0.6), 2.0) .rounded(5.0) .lens(AppState::params) } fn make_spacer_select() -> impl Widget<Params> { Flex::column() .cross_axis_alignment(CrossAxisAlignment::Start) .with_child(Label::new("Insert Spacers:")) .with_default_spacer() .with_child(RadioGroup::new(SPACER_OPTIONS.to_vec()).lens(Params::spacers)) .with_default_spacer() .with_child( Flex::row() .with_child( TextBox::new() .with_formatter(ParseFormatter::new()) .lens(Params::spacer_size) .fix_width(60.0), ) .with_spacer(druid::theme::WIDGET_CONTROL_COMPONENT_PADDING) .with_child( Stepper::new() .with_range(2.0, 50.0) .with_step(2.0) .lens(Params::spacer_size), ), ) } fn space_if_needed<T: Data>(flex: &mut Flex<T>, params: &Params) { match params.spacers { Spacers::None => (), Spacers::Default => flex.add_default_spacer(), Spacers::Fixed => flex.add_spacer(params.spacer_size), Spacers::Flex => flex.add_flex_spacer(1.0), } } fn build_widget(state: &Params) -> Box<dyn Widget<AppState>> { let mut flex = match state.axis { FlexType::Column => Flex::column(), FlexType::Row => Flex::row(), } .cross_axis_alignment(state.cross_alignment) .main_axis_alignment(state.main_alignment) .must_fill_main_axis(state.fill_major_axis); flex.add_child( TextBox::new() .with_placeholder("Sample text") .lens(DemoState::input_text), ); space_if_needed(&mut flex, state); flex.add_child( Button::new("Clear").on_click(|_ctx, data: &mut DemoState, _env| { data.input_text.clear(); data.enabled = false; data.volume = 0.0; }), ); space_if_needed(&mut flex, state); flex.add_child( Label::new(|data: &DemoState, _: &Env| data.input_text.clone()).with_text_size(32.0), ); space_if_needed(&mut flex, state); flex.add_child(Checkbox::new("Demo").lens(DemoState::enabled)); space_if_needed(&mut flex, state); flex.add_child(Switch::new().lens(DemoState::enabled)); space_if_needed(&mut flex, state); flex.add_child(Slider::new().lens(DemoState::volume)); space_if_needed(&mut flex, state); flex.add_child(ProgressBar::new().lens(DemoState::volume)); space_if_needed(&mut flex, state); flex.add_child( Stepper::new() .with_range(0.0, 1.0) .with_step(0.1) .with_wraparound(true) .lens(DemoState::volume), ); let mut flex = SizedBox::new(flex); if state.fix_minor_axis { match state.axis { FlexType::Row => flex = flex.height(200.), FlexType::Column => flex = flex.width(200.), } } if state.fix_major_axis { match state.axis { FlexType::Row => flex = flex.width(600.), FlexType::Column => flex = flex.height(300.), } } let flex = flex .padding(8.0) .border(Color::grey(0.6), 2.0) .rounded(5.0) .lens(AppState::demo_state); if state.debug_layout { flex.debug_paint_layout().boxed() } else { flex.boxed() } } fn make_ui() -> impl Widget<AppState> { Flex::column() .must_fill_main_axis(true) .with_child(make_control_row()) .with_default_spacer() .with_flex_child(Rebuilder::new().center(), 1.0) .padding(10.0) } pub fn main() { let main_window = WindowDesc::new(make_ui) .window_size((720., 600.)) .with_min_size((620., 300.)) .title("Flex Container Options"); let demo_state = DemoState { input_text: "hello".into(), enabled: false, volume: 0.0, }; let params = Params { axis: FlexType::Row, cross_alignment: CrossAxisAlignment::Center, main_alignment: MainAxisAlignment::Start, debug_layout: false, fix_minor_axis: false, fix_major_axis: false, spacers: Spacers::None, spacer_size: DEFAULT_SPACER_SIZE, fill_major_axis: false, }; AppLauncher::with_window(main_window) .use_simple_logger() .launch(AppState { demo_state, params }) .expect("Failed to launch application"); }
("Fixed:", Spacers::Fixed), ];
random_line_split
web.rs
use std::path::PathBuf; use std::rc::Rc; use std::cell::RefCell; use std::collections::BTreeMap; use std::fs::File; use std::io::prelude::*; use std::ffi::OsStr; use std::sync::Arc; use std::time::{Duration as SDuration, Instant}; use crate::utils::{print_error_and_causes, FutureExt as _, ResultExt as ResultExt2}; use crate::HeaterControlMode; use failure::{Error, ResultExt, bail};
use crate::Shared; use crate::DataLogEntry; use crate::TSDataLogEntry; use file_db::{create_intervall_filtermap, TimestampedMethods}; use hyper::StatusCode; use hyper::server::{Http, NewService, Request, Response, Server, Service}; use hyper::header; use futures::future::{FutureExt as _, TryFutureExt}; // for conversion use futures01::future::{self, Future}; use futures01; use futures01::Stream; use handlebars::Handlebars; use tokio_inotify::AsyncINotify; use rmp_serde::{Deserializer, Serializer}; use serde::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize}; use chrono::NaiveDate; use chrono::NaiveDateTime; use chrono::{Duration, Timelike}; pub fn make_web_server(shared: &Shared) -> Result<Server<HelloWorldSpawner, ::hyper::Body>, Error> { let assets_folder: PathBuf = ::std::fs::canonicalize(std::env::var("WEBASSETS_FOLDER") .context("Environment variable WEBASSETS_FOLDER must be set.")?)?; if!assets_folder.is_dir() { bail!( "WEBASSETS_FOLDER not found ({})", assets_folder.to_string_lossy() ); } let index_html = assets_folder.join("index.html"); if!index_html.is_file() { bail!("Missing index.html in WEBASSETS_FOLDER."); } let template_registry = Rc::new(RefCell::new(Handlebars::new())); let addr = "0.0.0.0:12345".parse().unwrap(); let server = Http::new() .bind( &addr, HelloWorldSpawner { shared: shared.clone(), template_registry: template_registry.clone(), assets_folder: Rc::new(assets_folder.clone()), }, ) .unwrap(); // handlebars template template_registry .borrow_mut() .register_template_file("index.html", &index_html) .with_context(|_e| { format!("Cannot compile {}", &index_html.to_string_lossy()) })?; // todo find all other.html files in the folder // React live on asset changes let path_notify = AsyncINotify::init(&server.handle())?; const IN_CLOSE_WRITE: u32 = 8; path_notify .add_watch(&assets_folder, IN_CLOSE_WRITE) .context("Web server can not watch the webassets folder for changes.")?; let template_registry1 = Rc::clone(&template_registry); let webassets_updater = path_notify.for_each(move |_event| { if _event.name.extension().unwrap_or(OsStr::new("")) == "html" { template_registry1 .try_borrow_mut() .map(|mut registry| { registry .register_template_file( &_event.name.to_string_lossy(), assets_folder.join(&_event.name), ) .with_context(|_e| { format!("Cannot compile {}", &_event.name.to_string_lossy()) }) .print_error_and_causes(); }) .print_error_and_causes(); } future::ok(()) }); server .handle() .spawn(webassets_updater.map_err(|e| print_error_and_causes(e) )); Ok(server) } pub struct HelloWorldSpawner { shared: Shared, template_registry: Rc<RefCell<Handlebars>>, assets_folder: Rc<PathBuf>, } impl NewService for HelloWorldSpawner { type Request = Request; type Response = Response; type Error = ::hyper::Error; type Instance = HelloWorld; fn new_service(&self) -> Result<Self::Instance, ::std::io::Error> { Ok(HelloWorld { shared: async_std::sync::Arc::clone(&self.shared), template_registry: Rc::clone(&self.template_registry), assets_folder: Rc::clone(&self.assets_folder), }) } } pub struct HelloWorld { shared: Shared, template_registry: Rc<RefCell<Handlebars>>, assets_folder: Rc<PathBuf>, } type HandlerResult = Box<dyn Future<Item = Response, Error = ::hyper::Error>>; impl Service for HelloWorld { // boilerplate hooking up hyper's server types type Request = Request; type Response = Response; type Error = ::hyper::Error; // The future representing the eventual Response your call will // resolve to. This can change to whatever Future you need. type Future = HandlerResult; fn call(&self, _req: Request) -> Self::Future { let mut path_segments = _req.path().split("/").skip(1); let response_body = match path_segments.next() { Some("") | Some("index.html") => self.indexhtml(), Some("assets") => self.serve_asset(path_segments), Some("history") => self.serve_history(path_segments.next()), Some("dates") => self.serve_available_dates(), Some("current") => self.serve_current_temperatures(), Some("set_heater_control_strategy") if _req.query().is_some() => { self.set_heater_control_strategy(_req.query().unwrap()) } _ => make404(), }; response_body } } impl HelloWorld { fn indexhtml(&self) -> HandlerResult { let template_registry = Rc::clone(&self.template_registry); box_and_convert_error(future::lazy(move || { let data: BTreeMap<String, String> = BTreeMap::new(); let resp = template_registry .borrow() .render("index.html", &data) .map_err(|err| ::failure::Context::new(format!("{}", err)))?; Ok(resp).map(str_to_response) })) } fn serve_asset<'a, I: Iterator<Item = &'a str>>(&self, mut path_segments: I) -> HandlerResult { match path_segments.next() { Some(filename) => { let path = self.assets_folder.join(filename); box_and_convert_error(future::lazy(move || { if path.is_file() { let mut f = File::open(path).unwrap(); let mut buffer = String::new(); f.read_to_string(&mut buffer).unwrap(); Ok(buffer).map(str_to_response) } else { Err(::failure::err_msg("Unknown asset")) } })) } None => make404(), } } fn serve_history<'a>(&self, date: Option<&'a str>) -> HandlerResult { match NaiveDate::parse_from_str(date.unwrap_or("nodate"), "%Y-%m-%d") { Ok(date) => { let shared = self.shared.clone(); let every_3_minutes = create_intervall_filtermap( Duration::minutes(3), |data: &TSDataLogEntry| JsData::from(data), 0.25, ); use file_db::Key; struct CachedAndFilteredMarker; impl Key for CachedAndFilteredMarker { type Value = Vec<u8>; } let fut = async move { let serialized = shared .db .custom_cached_by_chunk_key_async::<CachedAndFilteredMarker>( date.into(), Box::new(move |data: &[::file_db::Timestamped<DataLogEntry>]| { let as_vec: Vec<_> = every_3_minutes(data); let mut buf = Vec::with_capacity(0); as_vec .serialize(&mut Serializer::new(&mut buf)) .print_error_and_causes(); buf }), ).await?; let resp = Response::new() .with_header(header::ContentLength(serialized.len() as u64)) .with_header(header::ContentType(::hyper::mime::APPLICATION_MSGPACK)) // TODO: Performance by using stream and without copy .with_body((*serialized).clone()); Ok(resp) }; box_and_convert_error(fut.boxed().compat()) } Err(_err) => make404(), } } fn serve_available_dates(&self) -> HandlerResult { let shared = async_std::sync::Arc::clone(&self.shared); let fut = async move { let datesvec = shared.db.get_non_empty_chunk_keys_async().await?; let json_str = serde_json::to_string(&datesvec)?; let resp = Response::new() .with_header(header::ContentLength(json_str.len() as u64)) .with_header(header::ContentType(::hyper::mime::APPLICATION_JSON)) .with_body(json_str); Ok(resp) }; box_and_convert_error(fut.boxed().compat()) } fn serve_current_temperatures(&self) -> HandlerResult { let shared = async_std::sync::Arc::clone(&self.shared); let fut = async move { let data = DataLogEntry::new_from_current(&shared).await; #[derive(Serialize)] struct Current { block : JsData, control_strategy : String, } let data = Current { block : (&data).into(), // do better control_strategy : format!("{:?}", shared.control_strategy.load()), }; let json_str = serde_json::to_string(&data)?; let resp = Response::new() .with_header(header::ContentLength(json_str.len() as u64)) .with_header(header::ContentType(::hyper::mime::APPLICATION_JSON)) .with_body(json_str); Ok(resp) }; box_and_convert_error(fut.boxed().compat()) } fn set_heater_control_strategy(&self, query: &str) -> HandlerResult { let shared = async_std::sync::Arc::clone(&self.shared); let mut action = None; for k_v in query.split('&') { if!k_v.contains("=") { continue; } let mut k_v = k_v.split("="); if k_v.next() == Some("action") { action = k_v.next(); } } let answer = match action { Some("on") => { shared.control_strategy.store(HeaterControlMode::ForceOn{ until: Instant::now() + SDuration::from_secs(3600 * 12) }); "set: on" } Some("off") => { shared.control_strategy.store(HeaterControlMode::ForceOff{ until: Instant::now() + SDuration::from_secs(3600 * 12) }); "set: off" } Some("auto") => { shared.control_strategy.store(HeaterControlMode::Auto); "set: auto" } _ => { "do nothing" } }; box_and_convert_error(future::lazy(move || Ok(answer.to_string()).map(str_to_response))) } } fn str_to_response(body: String) -> Response { Response::new() .with_header(header::ContentLength(body.len() as u64)) .with_body(body) } fn box_and_convert_error<F>(result: F) -> HandlerResult where F: Future<Item = Response, Error = Error> + Sized +'static, { Box::new(result.then(|result| { let f = match result { Ok(response) => response, Err(err) => { use std::fmt::Write; let mut buf = String::with_capacity(1000); for (i, cause) in err.iter_chain().enumerate() { if i == 0 { write!(buf, "<p>{}</p>", cause).unwrap(); } else { write!(buf, "<p> &gt; caused by: {} </p>", cause).unwrap(); } } write!(buf, "<pre>{}</pre>", err.backtrace()).unwrap(); let body = format!( r#"<!doctype html> <html lang="en"><head> <meta charset="utf-8"> <title>505 Internal Server Error</title> </head> <body> <h1>505 Internal Server Error</h1> {} </body></html>"#, buf ); print_error_and_causes(err); Response::new() .with_status(StatusCode::InternalServerError) .with_header(header::ContentLength(body.len() as u64)) .with_body(body) } }; Ok(f) })) } fn make404() -> HandlerResult { Box::new(future::lazy(|| { let body = format!( r#"<!doctype html> <html lang="en"><head> <meta charset="utf-8"> <title>404 Not Found</title> </head> <body> <h1>404 Not Found</h1> </body></html>"# ); Ok( Response::new() .with_status(StatusCode::NotFound) .with_header(header::ContentLength(body.len() as u64)) .with_body(body), ) })) } #[derive(Serialize, Deserialize, Clone)] pub struct JsData { pub time: String, pub high: f64, pub highmid: f64, pub mid: f64, pub midlow: f64, pub low: f64, pub outside: f64, pub heater_state: u8, pub reference: f64, } impl<'a> From<&'a TSDataLogEntry> for JsData { fn from(d: &TSDataLogEntry) -> JsData { JsData { time: d.time().format("%Y-%m-%dT%H:%M:%S+0000").to_string(), high: d.celsius[0] as f64 / 100.0, highmid: d.celsius[1] as f64 / 100.0, mid: d.celsius[2] as f64 / 100.0, midlow: d.celsius[3] as f64 / 100.0, low: d.celsius[4] as f64 / 100.0, outside: d.celsius[5] as f64 / 100.0, heater_state: if d.heater_state { 1 } else { 0 }, reference: d.reference_celsius.unwrap_or(0) as f64 / 100.0, } } }
random_line_split
web.rs
use std::path::PathBuf; use std::rc::Rc; use std::cell::RefCell; use std::collections::BTreeMap; use std::fs::File; use std::io::prelude::*; use std::ffi::OsStr; use std::sync::Arc; use std::time::{Duration as SDuration, Instant}; use crate::utils::{print_error_and_causes, FutureExt as _, ResultExt as ResultExt2}; use crate::HeaterControlMode; use failure::{Error, ResultExt, bail}; use crate::Shared; use crate::DataLogEntry; use crate::TSDataLogEntry; use file_db::{create_intervall_filtermap, TimestampedMethods}; use hyper::StatusCode; use hyper::server::{Http, NewService, Request, Response, Server, Service}; use hyper::header; use futures::future::{FutureExt as _, TryFutureExt}; // for conversion use futures01::future::{self, Future}; use futures01; use futures01::Stream; use handlebars::Handlebars; use tokio_inotify::AsyncINotify; use rmp_serde::{Deserializer, Serializer}; use serde::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize}; use chrono::NaiveDate; use chrono::NaiveDateTime; use chrono::{Duration, Timelike}; pub fn make_web_server(shared: &Shared) -> Result<Server<HelloWorldSpawner, ::hyper::Body>, Error> { let assets_folder: PathBuf = ::std::fs::canonicalize(std::env::var("WEBASSETS_FOLDER") .context("Environment variable WEBASSETS_FOLDER must be set.")?)?; if!assets_folder.is_dir() { bail!( "WEBASSETS_FOLDER not found ({})", assets_folder.to_string_lossy() ); } let index_html = assets_folder.join("index.html"); if!index_html.is_file() { bail!("Missing index.html in WEBASSETS_FOLDER."); } let template_registry = Rc::new(RefCell::new(Handlebars::new())); let addr = "0.0.0.0:12345".parse().unwrap(); let server = Http::new() .bind( &addr, HelloWorldSpawner { shared: shared.clone(), template_registry: template_registry.clone(), assets_folder: Rc::new(assets_folder.clone()), }, ) .unwrap(); // handlebars template template_registry .borrow_mut() .register_template_file("index.html", &index_html) .with_context(|_e| { format!("Cannot compile {}", &index_html.to_string_lossy()) })?; // todo find all other.html files in the folder // React live on asset changes let path_notify = AsyncINotify::init(&server.handle())?; const IN_CLOSE_WRITE: u32 = 8; path_notify .add_watch(&assets_folder, IN_CLOSE_WRITE) .context("Web server can not watch the webassets folder for changes.")?; let template_registry1 = Rc::clone(&template_registry); let webassets_updater = path_notify.for_each(move |_event| { if _event.name.extension().unwrap_or(OsStr::new("")) == "html" { template_registry1 .try_borrow_mut() .map(|mut registry| { registry .register_template_file( &_event.name.to_string_lossy(), assets_folder.join(&_event.name), ) .with_context(|_e| { format!("Cannot compile {}", &_event.name.to_string_lossy()) }) .print_error_and_causes(); }) .print_error_and_causes(); } future::ok(()) }); server .handle() .spawn(webassets_updater.map_err(|e| print_error_and_causes(e) )); Ok(server) } pub struct HelloWorldSpawner { shared: Shared, template_registry: Rc<RefCell<Handlebars>>, assets_folder: Rc<PathBuf>, } impl NewService for HelloWorldSpawner { type Request = Request; type Response = Response; type Error = ::hyper::Error; type Instance = HelloWorld; fn new_service(&self) -> Result<Self::Instance, ::std::io::Error> { Ok(HelloWorld { shared: async_std::sync::Arc::clone(&self.shared), template_registry: Rc::clone(&self.template_registry), assets_folder: Rc::clone(&self.assets_folder), }) } } pub struct HelloWorld { shared: Shared, template_registry: Rc<RefCell<Handlebars>>, assets_folder: Rc<PathBuf>, } type HandlerResult = Box<dyn Future<Item = Response, Error = ::hyper::Error>>; impl Service for HelloWorld { // boilerplate hooking up hyper's server types type Request = Request; type Response = Response; type Error = ::hyper::Error; // The future representing the eventual Response your call will // resolve to. This can change to whatever Future you need. type Future = HandlerResult; fn call(&self, _req: Request) -> Self::Future { let mut path_segments = _req.path().split("/").skip(1); let response_body = match path_segments.next() { Some("") | Some("index.html") => self.indexhtml(), Some("assets") => self.serve_asset(path_segments), Some("history") => self.serve_history(path_segments.next()), Some("dates") => self.serve_available_dates(), Some("current") => self.serve_current_temperatures(), Some("set_heater_control_strategy") if _req.query().is_some() => { self.set_heater_control_strategy(_req.query().unwrap()) } _ => make404(), }; response_body } } impl HelloWorld { fn indexhtml(&self) -> HandlerResult { let template_registry = Rc::clone(&self.template_registry); box_and_convert_error(future::lazy(move || { let data: BTreeMap<String, String> = BTreeMap::new(); let resp = template_registry .borrow() .render("index.html", &data) .map_err(|err| ::failure::Context::new(format!("{}", err)))?; Ok(resp).map(str_to_response) })) } fn serve_asset<'a, I: Iterator<Item = &'a str>>(&self, mut path_segments: I) -> HandlerResult { match path_segments.next() { Some(filename) => { let path = self.assets_folder.join(filename); box_and_convert_error(future::lazy(move || { if path.is_file() { let mut f = File::open(path).unwrap(); let mut buffer = String::new(); f.read_to_string(&mut buffer).unwrap(); Ok(buffer).map(str_to_response) } else { Err(::failure::err_msg("Unknown asset")) } })) } None => make404(), } } fn serve_history<'a>(&self, date: Option<&'a str>) -> HandlerResult { match NaiveDate::parse_from_str(date.unwrap_or("nodate"), "%Y-%m-%d") { Ok(date) => { let shared = self.shared.clone(); let every_3_minutes = create_intervall_filtermap( Duration::minutes(3), |data: &TSDataLogEntry| JsData::from(data), 0.25, ); use file_db::Key; struct CachedAndFilteredMarker; impl Key for CachedAndFilteredMarker { type Value = Vec<u8>; } let fut = async move { let serialized = shared .db .custom_cached_by_chunk_key_async::<CachedAndFilteredMarker>( date.into(), Box::new(move |data: &[::file_db::Timestamped<DataLogEntry>]| { let as_vec: Vec<_> = every_3_minutes(data); let mut buf = Vec::with_capacity(0); as_vec .serialize(&mut Serializer::new(&mut buf)) .print_error_and_causes(); buf }), ).await?; let resp = Response::new() .with_header(header::ContentLength(serialized.len() as u64)) .with_header(header::ContentType(::hyper::mime::APPLICATION_MSGPACK)) // TODO: Performance by using stream and without copy .with_body((*serialized).clone()); Ok(resp) }; box_and_convert_error(fut.boxed().compat()) } Err(_err) => make404(), } } fn serve_available_dates(&self) -> HandlerResult { let shared = async_std::sync::Arc::clone(&self.shared); let fut = async move { let datesvec = shared.db.get_non_empty_chunk_keys_async().await?; let json_str = serde_json::to_string(&datesvec)?; let resp = Response::new() .with_header(header::ContentLength(json_str.len() as u64)) .with_header(header::ContentType(::hyper::mime::APPLICATION_JSON)) .with_body(json_str); Ok(resp) }; box_and_convert_error(fut.boxed().compat()) } fn serve_current_temperatures(&self) -> HandlerResult { let shared = async_std::sync::Arc::clone(&self.shared); let fut = async move { let data = DataLogEntry::new_from_current(&shared).await; #[derive(Serialize)] struct Current { block : JsData, control_strategy : String, } let data = Current { block : (&data).into(), // do better control_strategy : format!("{:?}", shared.control_strategy.load()), }; let json_str = serde_json::to_string(&data)?; let resp = Response::new() .with_header(header::ContentLength(json_str.len() as u64)) .with_header(header::ContentType(::hyper::mime::APPLICATION_JSON)) .with_body(json_str); Ok(resp) }; box_and_convert_error(fut.boxed().compat()) } fn set_heater_control_strategy(&self, query: &str) -> HandlerResult { let shared = async_std::sync::Arc::clone(&self.shared); let mut action = None; for k_v in query.split('&') { if!k_v.contains("=") { continue; } let mut k_v = k_v.split("="); if k_v.next() == Some("action") { action = k_v.next(); } } let answer = match action { Some("on") => { shared.control_strategy.store(HeaterControlMode::ForceOn{ until: Instant::now() + SDuration::from_secs(3600 * 12) }); "set: on" } Some("off") => { shared.control_strategy.store(HeaterControlMode::ForceOff{ until: Instant::now() + SDuration::from_secs(3600 * 12) }); "set: off" } Some("auto") => { shared.control_strategy.store(HeaterControlMode::Auto); "set: auto" } _ => { "do nothing" } }; box_and_convert_error(future::lazy(move || Ok(answer.to_string()).map(str_to_response))) } } fn str_to_response(body: String) -> Response { Response::new() .with_header(header::ContentLength(body.len() as u64)) .with_body(body) } fn
<F>(result: F) -> HandlerResult where F: Future<Item = Response, Error = Error> + Sized +'static, { Box::new(result.then(|result| { let f = match result { Ok(response) => response, Err(err) => { use std::fmt::Write; let mut buf = String::with_capacity(1000); for (i, cause) in err.iter_chain().enumerate() { if i == 0 { write!(buf, "<p>{}</p>", cause).unwrap(); } else { write!(buf, "<p> &gt; caused by: {} </p>", cause).unwrap(); } } write!(buf, "<pre>{}</pre>", err.backtrace()).unwrap(); let body = format!( r#"<!doctype html> <html lang="en"><head> <meta charset="utf-8"> <title>505 Internal Server Error</title> </head> <body> <h1>505 Internal Server Error</h1> {} </body></html>"#, buf ); print_error_and_causes(err); Response::new() .with_status(StatusCode::InternalServerError) .with_header(header::ContentLength(body.len() as u64)) .with_body(body) } }; Ok(f) })) } fn make404() -> HandlerResult { Box::new(future::lazy(|| { let body = format!( r#"<!doctype html> <html lang="en"><head> <meta charset="utf-8"> <title>404 Not Found</title> </head> <body> <h1>404 Not Found</h1> </body></html>"# ); Ok( Response::new() .with_status(StatusCode::NotFound) .with_header(header::ContentLength(body.len() as u64)) .with_body(body), ) })) } #[derive(Serialize, Deserialize, Clone)] pub struct JsData { pub time: String, pub high: f64, pub highmid: f64, pub mid: f64, pub midlow: f64, pub low: f64, pub outside: f64, pub heater_state: u8, pub reference: f64, } impl<'a> From<&'a TSDataLogEntry> for JsData { fn from(d: &TSDataLogEntry) -> JsData { JsData { time: d.time().format("%Y-%m-%dT%H:%M:%S+0000").to_string(), high: d.celsius[0] as f64 / 100.0, highmid: d.celsius[1] as f64 / 100.0, mid: d.celsius[2] as f64 / 100.0, midlow: d.celsius[3] as f64 / 100.0, low: d.celsius[4] as f64 / 100.0, outside: d.celsius[5] as f64 / 100.0, heater_state: if d.heater_state { 1 } else { 0 }, reference: d.reference_celsius.unwrap_or(0) as f64 / 100.0, } } }
box_and_convert_error
identifier_name