lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/pagetree.rs
manuel-rhdt/lemon_pdf
e85d52d391a6dbc34fe4b33e437d788e62fd12a0
use std::collections::HashMap; use std::f64::consts::SQRT_2; use std::io::Result; use crate as lemon_pdf; use lemon_pdf_derive::PdfFormat; use crate::array::Array; use crate::content::PageContext; use crate::document::DocumentContext; use crate::font::Font; use crate::object::{IndirectReference, Object, Value}; use crate::stream::{Stream, StreamEncoder, StreamFilter}; use crate::Pt; #[derive(Debug, Clone, PdfFormat)] pub struct Pages { count: i64, #[skip_if("Option::is_none")] parent: Option<IndirectReference<Pages>>, kids: Vec<Object<PageTreeNode>>, } impl Default for Pages { fn default() -> Self { Pages { kids: Vec::new(), parent: None, count: -1, } } } #[derive(Clone, Debug, PdfFormat)] enum PageTreeNode { Tree(Pages), Page(Page), } impl Pages { pub fn new() -> Self { Default::default() } #[allow(unused)] pub fn add_pagetree(&mut self, tree: Pages) { self.kids.push(Object::Direct(PageTreeNode::Tree(tree))) } pub fn add_page(&mut self, page: Page) { self.kids.push(Object::Direct(PageTreeNode::Page(page))) } pub fn write_to_context( mut self, context: &mut DocumentContext, ) -> Result<IndirectReference<Pages>> { context.write_object_fn(|context, self_reference| { let mut array = Vec::new(); for child in self.kids { match child { Object::Direct(PageTreeNode::Tree(mut tree)) => { tree.parent = Some(self_reference); let tree_obj = tree.write_to_context(context)?; array.push(tree_obj.convert().into()) } Object::Direct(PageTreeNode::Page(mut page)) => { page.set_parent(self_reference); let page_obj = context.write_object(page)?; array.push(page_obj.convert().into()); } _ => unreachable!(), } } self.kids = array; self.count = self.kids.len() as i64; Ok(self) }) } } #[derive(Clone, Debug, Default, PartialEq, PdfFormat)] #[omit_type(true)] pub struct ResourceDictionary { pub font: HashMap<String, IndirectReference<Font>>, } #[derive(Clone, Debug, PdfFormat)] pub struct Page { pub resources: Option<ResourceDictionary>, pub media_box: [Pt; 4], #[skip_if("Option::is_none")] pub parent: Option<IndirectReference<Pages>>, pub contents: Vec<IndirectReference<Stream>>, } impl Page { pub fn new() -> Self { Page { resources: None, media_box: MediaBox::paper_din_a(4).as_array(), parent: None, contents: Vec::new(), } } pub fn set_media_box(&mut self, media_box: MediaBox) { self.media_box = media_box.as_array() } fn get_context<'context, 'borrow>( &mut self, context: &'borrow mut DocumentContext<'context>, stream_filter: Option<StreamFilter>, ) -> PageContext<'_, 'context, 'borrow> { PageContext { fonts: HashMap::new(), page: self, content_stream: StreamEncoder::new(stream_filter), pdf_context: context, } } pub fn add_content<'context, 'borrow>( &mut self, context: &mut DocumentContext<'context>, stream_filter: Option<StreamFilter>, content_f: impl FnOnce(&mut PageContext<'_, 'context, '_>) -> Result<()>, ) -> Result<()> { let mut page_context = self.get_context(context, stream_filter); content_f(&mut page_context)?; page_context.finish()?; Ok(()) } pub(crate) fn set_parent(&mut self, parent: IndirectReference<Pages>) { self.parent = Some(parent) } } #[derive(Debug, Copy, Clone, PartialEq)] pub struct MediaBox { pub xmin: Pt, pub ymin: Pt, pub xmax: Pt, pub ymax: Pt, } impl MediaBox { pub fn new(xmin: Pt, ymin: Pt, xmax: Pt, ymax: Pt) -> Self { MediaBox { xmin, ymin, xmax, ymax, } } pub fn paper_din_a(num: i32) -> Self { const A_AREA: f64 = 1.0; const M_TO_PT: f64 = 2834.65; let height = M_TO_PT * (A_AREA * SQRT_2).sqrt() / SQRT_2.powi(num); MediaBox::new(Pt(0.0), Pt(0.0), Pt(height / SQRT_2), Pt(height)) } pub fn as_array(self) -> [Pt; 4] { [self.xmin, self.ymin, self.xmax, self.ymax] } } impl Default for Page { fn default() -> Self { Page::new() } } impl From<MediaBox> for Object<Value> { fn from(mediabox: MediaBox) -> Object<Value> { let mut array = Array::new(); array.push(Object::Direct(mediabox.xmin.0.into())); array.push(Object::Direct(mediabox.ymin.0.into())); array.push(Object::Direct(mediabox.xmax.0.into())); array.push(Object::Direct(mediabox.ymax.0.into())); Object::Direct(array.into()) } }
use std::collections::HashMap; use std::f64::consts::SQRT_2; use std::io::Result; use crate as lemon_pdf; use lemon_pdf_derive::PdfFormat; use crate::array::Array; use crate::content::PageContext; use crate::document::DocumentContext; use crate::font::Font; use crate::object::{IndirectReference, Object, Value}; use crate::stream::{Stream, StreamEncoder, StreamFilter}; use crate::Pt; #[derive(Debug, Clone, PdfFormat)] pub struct Pages { count: i64, #[skip_if("Option::is_none")] parent: Option<IndirectReference<Pages>>, kids: Vec<Object<PageTreeNode>>, } impl Default for Pages { fn default() -> Self { Pages { kids: Vec::new(), parent: None, count: -1, } } } #[derive(Clone, Debug, PdfFormat)] enum PageTreeNode { Tree(Pages), Page(Page), } impl Pages { pub fn new() -> Self { Default::default() } #[allow(unused)] pub fn add_pagetree(&mut self, tree: Pages) { self.kids.push(Object::Direct(PageTreeNode::Tree(tree))) } pub fn add_page(&mut self, page: Page) { self.kids.push(Object::Direct(PageTreeNode::Page(page))) } pub fn write_to_context( mut self, context: &mut DocumentContext, ) -> Result<IndirectReference<Pages>> { context.write_object_fn(|context, self_reference| { let mut array = Vec::new(); for child in self.kids { match child { Object::Direct(PageTreeNode::Tree(mut tree)) => { tree.parent = Some(self_reference); let tree_obj = tree.write_to_context(context)?; array.push(tree_obj.convert().into()) } Object::Direct(PageTreeNode::Page(mut page)) => { page.set_parent(self_reference); let page_obj = context.write_object(page)?; array.push(page_obj.convert().into()); } _ => unreachable!(), } } self.kids = array; self.count = self.kids.len() as i64; Ok(self) }) } } #[derive(Clone, Debug, Default, PartialEq, PdfFormat)] #[omit_type(true)] pub struct ResourceDictionary { pub font: HashMap<String, IndirectReference<Font>>, } #[derive(Clone, Debug, PdfFormat)] pub struct Page { pub resources: Option<ResourceDictionary>, pub media_box: [Pt; 4], #[skip_if("Option::is_none")] pub parent: Option<IndirectReference<Pages>>, pub contents: Vec<IndirectReference<Stream>>, } impl Page {
pub fn set_media_box(&mut self, media_box: MediaBox) { self.media_box = media_box.as_array() } fn get_context<'context, 'borrow>( &mut self, context: &'borrow mut DocumentContext<'context>, stream_filter: Option<StreamFilter>, ) -> PageContext<'_, 'context, 'borrow> { PageContext { fonts: HashMap::new(), page: self, content_stream: StreamEncoder::new(stream_filter), pdf_context: context, } } pub fn add_content<'context, 'borrow>( &mut self, context: &mut DocumentContext<'context>, stream_filter: Option<StreamFilter>, content_f: impl FnOnce(&mut PageContext<'_, 'context, '_>) -> Result<()>, ) -> Result<()> { let mut page_context = self.get_context(context, stream_filter); content_f(&mut page_context)?; page_context.finish()?; Ok(()) } pub(crate) fn set_parent(&mut self, parent: IndirectReference<Pages>) { self.parent = Some(parent) } } #[derive(Debug, Copy, Clone, PartialEq)] pub struct MediaBox { pub xmin: Pt, pub ymin: Pt, pub xmax: Pt, pub ymax: Pt, } impl MediaBox { pub fn new(xmin: Pt, ymin: Pt, xmax: Pt, ymax: Pt) -> Self { MediaBox { xmin, ymin, xmax, ymax, } } pub fn paper_din_a(num: i32) -> Self { const A_AREA: f64 = 1.0; const M_TO_PT: f64 = 2834.65; let height = M_TO_PT * (A_AREA * SQRT_2).sqrt() / SQRT_2.powi(num); MediaBox::new(Pt(0.0), Pt(0.0), Pt(height / SQRT_2), Pt(height)) } pub fn as_array(self) -> [Pt; 4] { [self.xmin, self.ymin, self.xmax, self.ymax] } } impl Default for Page { fn default() -> Self { Page::new() } } impl From<MediaBox> for Object<Value> { fn from(mediabox: MediaBox) -> Object<Value> { let mut array = Array::new(); array.push(Object::Direct(mediabox.xmin.0.into())); array.push(Object::Direct(mediabox.ymin.0.into())); array.push(Object::Direct(mediabox.xmax.0.into())); array.push(Object::Direct(mediabox.ymax.0.into())); Object::Direct(array.into()) } }
pub fn new() -> Self { Page { resources: None, media_box: MediaBox::paper_din_a(4).as_array(), parent: None, contents: Vec::new(), } }
function_block-full_function
[ { "content": "pub trait PdfFormat: std::fmt::Debug {\n\n fn write(&self, output: &mut Formatter) -> Result<()>;\n\n}\n\n\n\nimpl<'a> PdfFormat for &'a str {\n\n fn write(&self, output: &mut Formatter) -> Result<()> {\n\n // TODO: proper escaping\n\n write!(output, \"/{}\", self)\n\n }\n\n}\n\n\n\nimpl<'a, T> PdfFormat for &'a T\n\nwhere\n\n T: PdfFormat,\n\n{\n\n fn write(&self, output: &mut Formatter) -> Result<()> {\n\n (*self).write(output)\n\n }\n\n}\n\n\n", "file_path": "src/object.rs", "rank": 0, "score": 114323.28334117998 }, { "content": "fn is_default<T: Default + PartialEq>(val: &T) -> bool {\n\n val == &T::default()\n\n}\n\n\n\n#[derive(Debug, Clone, Default, PartialEq, PdfFormat)]\n\npub struct FontDescriptor {\n\n pub font_name: String,\n\n #[skip_if(\"Vec::is_empty\")]\n\n pub font_family: Vec<u8>,\n\n #[skip_if(\"Option::is_none\")]\n\n pub font_stretch: Option<FontStretch>,\n\n #[skip_if(\"Option::is_none\")]\n\n pub font_weight: Option<u32>,\n\n pub flags: FontFlags,\n\n pub font_b_box: [FontUnit; 4],\n\n pub italic_angle: f64,\n\n pub ascent: FontUnit,\n\n pub descent: FontUnit,\n\n #[skip_if(\"is_default\")]\n\n pub leading: FontUnit,\n", "file_path": "src/font/descriptor.rs", "rank": 1, "score": 105924.6160353221 }, { "content": "fn parse_indirect_reference(i: &[u8]) -> IResult<&[u8], (i64, i64)> {\n\n let (i, (num, _, gen, ..)) = tuple((\n\n int_num,\n\n multispace1,\n\n int_num,\n\n multispace1,\n\n tag(b\"R\"),\n\n multispace1,\n\n ))(i)?;\n\n Ok((i, (num, gen)))\n\n}\n\n\n", "file_path": "src/deserializer.rs", "rank": 3, "score": 81091.62811669525 }, { "content": "pub trait WriteEscaped {\n\n fn write_escaped(&mut self, bytes: &[u8]) -> std::io::Result<()>;\n\n fn write_hex_escaped(&mut self, bytes: &[u8]) -> std::io::Result<()>;\n\n}\n\n\n\nimpl<W: Write> WriteEscaped for W {\n\n fn write_escaped(&mut self, bytes: &[u8]) -> std::io::Result<()> {\n\n for &byte in bytes {\n\n match byte {\n\n 0x0c /* Form Feed */ => self.write_all(b\"\\\\f\")?,\n\n 0x08 /* Backspace */ => self.write_all(b\"\\\\b\")?,\n\n b'\\t' => self.write_all(b\"\\\\t\")?,\n\n b'\\r' => self.write_all(b\"\\\\r\")?,\n\n b'\\n' => self.write_all(b\"\\\\n\")?,\n\n b')' => self.write_all(b\"\\\\)\")?,\n\n b'(' => self.write_all(b\"\\\\(\")?,\n\n non_graphic if !byte.is_ascii_graphic() => write!(self, \"\\\\d{:03o}\", non_graphic)?,\n\n other => self.write_all(&[other])?\n\n }\n\n }\n", "file_path": "src/object.rs", "rank": 4, "score": 73238.17103161538 }, { "content": "fn int_num(i: &[u8]) -> IResult<&[u8], i64> {\n\n map_res(recognize(pair(opt(tag(b\"-\")), digit1)), |s: &[u8]| {\n\n std::str::from_utf8(s).unwrap().parse::<i64>()\n\n })(i)\n\n}\n\n\n", "file_path": "src/deserializer.rs", "rank": 5, "score": 71440.69443420495 }, { "content": "#[proc_macro_derive(PdfFormat, attributes(rename, skip_if, omit_type))]\n\npub fn pdf_format_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n\n let input = proc_macro2::TokenStream::from(input);\n\n\n\n // Construct a representation of Rust code as a syntax tree\n\n // that we can manipulate\n\n let ast = syn::parse2(input).unwrap();\n\n\n\n // Build the trait implementation\n\n let result = impl_pdf_format_derive(&ast);\n\n\n\n result.into()\n\n}\n\n\n", "file_path": "lemon_pdf_derive/src/lib.rs", "rank": 6, "score": 55245.921382013505 }, { "content": "fn parse_attributes(attribute: &[Attribute]) -> StructAttr {\n\n attribute\n\n .iter()\n\n .map(Attribute::parse_meta)\n\n .filter_map(|meta| {\n\n meta.ok().and_then(|meta| match meta {\n\n Meta::List(MetaList { ident, nested, .. }) => {\n\n if ident == \"rename\" {\n\n match nested.iter().next() {\n\n Some(NestedMeta::Literal(Lit::Str(str_lit))) => {\n\n Some(StructAttr::rename(str_lit.value()))\n\n }\n\n _ => None,\n\n }\n\n } else if ident == \"skip_if\" {\n\n match nested.iter().next() {\n\n Some(NestedMeta::Literal(Lit::Str(str_lit))) => {\n\n Some(StructAttr::skip_if(str_lit.parse().unwrap()))\n\n }\n\n _ => None,\n", "file_path": "lemon_pdf_derive/src/lib.rs", "rank": 7, "score": 54955.38758242627 }, { "content": "#[derive(Default)]\n\nstruct StructAttr {\n\n omit_type: bool,\n\n rename: Option<String>,\n\n skip_if: Option<Path>,\n\n}\n\n\n\nimpl StructAttr {\n\n fn rename(val: String) -> Self {\n\n StructAttr {\n\n rename: Some(val),\n\n ..Default::default()\n\n }\n\n }\n\n\n\n fn skip_if(val: Path) -> Self {\n\n StructAttr {\n\n skip_if: Some(val),\n\n ..Default::default()\n\n }\n\n }\n", "file_path": "lemon_pdf_derive/src/lib.rs", "rank": 8, "score": 54396.52966109675 }, { "content": "#[derive(Debug)]\n\nenum State {\n\n Both(i64, i64),\n\n One(i64),\n\n None,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct PdfDeserializer<'bytes> {\n\n pub input: &'bytes [u8],\n\n state: Option<State>,\n\n}\n\n\n\nimpl<'bytes> PdfDeserializer<'bytes> {\n\n fn take(&mut self, n: usize) -> &'bytes [u8] {\n\n let result = &self.input[..n];\n\n self.input = &self.input[n..];\n\n result\n\n }\n\n\n\n fn take_ws(&mut self) -> &'bytes [u8] {\n", "file_path": "src/deserializer.rs", "rank": 9, "score": 49610.190617529704 }, { "content": "# AGL & AGLFN\n\n\n\nThis open source project is intended to be coupled with the [AGL Specification](https://github.com/adobe-type-tools/agl-specification), and provides the resources that it references.\n\n\n\n## Contents\n\n\n\nThis project includes the following resources:\n\n\n\n*glyphlist.txt*: AGL \n\n*aglfn.txt*: AGLFN \n\n*zapfdingbats.txt*: ITC Zapf Dingbats Glyph List\n\n\n\n## Overview\n\n\n\nAGL (*Adobe Glyph List*) simply provides mappings from glyph names to Unicode scalar values.\n\n\n\nAGLFN (*Adobe Glyph List For New Fonts*) provides a list of base glyph names that are recommended for new fonts, which are compatible with the [AGL (*Adobe Glyph List*) Specification](https://github.com/adobe-type-tools/agl-specification), and which should be used as described in Section 6 of that document. AGLFN comprises the set of glyph names from AGL that map via the AGL Specification rules to the semantically correct UV (*Unicode Value*). For example, \"Asmall\" is omitted because AGL maps this glyph name to the PUA (*Private Use Area*) value U+F761, rather than to the UV that maps from the glyph name \"A.\" Also omitted is \"ffi,\" because AGL maps this to the Alphabetic Presentation Forms value U+FB03, rather than decomposing it into the following sequence of three UVs: U+0066, U+0066, and U+0069. The name \"arrowvertex\" has been omitted because this glyph now has a real UV, and AGL is now incorrect in mapping it to the PUA value U+F8E6. If you do not find an appropriate name for your glyph in this list, then please refer to Section 6 of the AGL Specification.\n\n\n\nThe *ITC Zapf Dingbats Glyph List* is similar to AGL in that it simply provides mappings from glyph names to Unicode scalar values, but only for glyphs in the ITC Zapf Dingbats font.\n\n\n", "file_path": "resources/font/adobe_glyph_list/README.md", "rank": 10, "score": 48985.92950950212 }, { "content": "## Format\n\n\n\nEach record in AGL (*glyphlist.txt*) and the *ITC Zapf Dingbats Glyph List* (*zapfdingbats.txt*) is comprised of two semicolon-delimited fields, described as follows:\n\n\n\n* Glyph name—*upper/lowercase letters and digits*\n\n* Unicode scalar value—*four uppercase hexadecimal digits*\n\n\n\nThe AGL and *ITC Zapf Dingbats Glyph List* records are sorted by glyph name in increasing ASCII order, lines starting with \"#\" are comments, and blank lines should be ignored.\n\n\n\nEach record in AGLFN (*aglfn.txt*) is comprised of three semicolon-delimited fields, described as follows:\n\n\n\n* Standard UV or CUS (*Corporate Use Subarea*) UV—*four uppercase hexadecimal digits*\n\n* Glyph name—*upper/lowercase letters and digits*\n\n* Character names: Unicode character names for standard UVs, and descriptive names for CUS UVs—*uppercase letters, hyphen, and space*\n\n\n\nThe AGLFN records are sorted by glyph name in increasing ASCII order, entries with the same glyph name are sorted in decreasing priority order, the UVs and Unicode character names are provided for convenience, lines starting with \"#\" are comments, and blank lines should be ignored.\n\n\n\n## More Information\n\n\n\nImportant details about glyph naming and interpreting glyph names can be found in the [AGL Specification](https://github.com/adobe-type-tools/agl-specification), which is an open specification.\n\n\n\nThe tools and documentation that comprise [AFDKO (*Adobe Font Development Kit for OpenType*)](http://www.adobe.com/devnet/opentype/afdko.html) are helpful for those who develop OpenType fonts. For general and format-related questions about OpenType fonts, the [OpenType Specification](http://www.microsoft.com/typography/otspec/) is the single best source.\n\n\n\n## Getting Involved\n\n\n\nSend suggestions for changes to the AGL & AGLFN project maintainer, [Dr. Ken Lunde](mailto:lunde@adobe.com?subject=[GitHub]%20AGL%20&%20AGLFN), for consideration.\n", "file_path": "resources/font/adobe_glyph_list/README.md", "rank": 11, "score": 48979.04600742585 }, { "content": "#[derive(Copy, Clone, Debug)]\n\nenum IndirectReferenceDe {\n\n Both(i64, i64),\n\n One(i64),\n\n}\n\n\n", "file_path": "src/deserializer.rs", "rank": 12, "score": 46604.802437980616 }, { "content": "#[derive(Debug)]\n\nenum StreamEncoderType {\n\n Identity(Cursor<Vec<u8>>),\n\n Deflate(ZlibEncoder<Cursor<Vec<u8>>>),\n\n}\n\n\n\n/// A convenience type to create PDF streams.\n\n#[derive(Debug)]\n\npub struct StreamEncoder {\n\n enc_type: StreamEncoderType,\n\n}\n\n\n\nimpl StreamEncoder {\n\n pub fn new(filter: Option<StreamFilter>) -> Self {\n\n let enc_type = match filter {\n\n None => StreamEncoderType::Identity(Cursor::new(Vec::new())),\n\n Some(StreamFilter::Deflate) => StreamEncoderType::Deflate(ZlibEncoder::new(\n\n Cursor::new(Vec::new()),\n\n Compression::default(),\n\n )),\n\n };\n", "file_path": "src/stream.rs", "rank": 13, "score": 46601.16427358087 }, { "content": "#[derive(Debug)]\n\nenum Token<'bytes> {\n\n Name(&'bytes [u8]),\n\n StartDict,\n\n EndDict,\n\n StartArray,\n\n EndArray,\n\n IndirectReference(i64, i64),\n\n PartialIndirectReference(i64),\n\n}\n\n\n", "file_path": "src/deserializer.rs", "rank": 14, "score": 46246.66294395825 }, { "content": "#[derive(Debug, Clone)]\n\nstruct HexString(String);\n\n\n\nimpl PdfFormat for HexString {\n\n fn write(&self, output: &mut Formatter) -> Result<()> {\n\n write!(output, \"<{}>\", self.0)\n\n }\n\n}\n\n\n", "file_path": "src/trailer.rs", "rank": 15, "score": 45614.31785715083 }, { "content": "fn impl_pdf_format_derive(ast: &syn::DeriveInput) -> proc_macro2::TokenStream {\n\n let name = &ast.ident;\n\n let attr = parse_attributes(&ast.attrs);\n\n\n\n let generics: &Vec<_> = &ast\n\n .generics\n\n .params\n\n .iter()\n\n .filter_map(|param| match param {\n\n GenericParam::Type(TypeParam { ident, .. }) => Some(ident),\n\n _ => None,\n\n })\n\n .collect();\n\n let impl_line = if generics.is_empty() {\n\n quote! { impl lemon_pdf::PdfFormat for #name }\n\n } else {\n\n quote! { impl<#(#generics: lemon_pdf::PdfFormat),*> lemon_pdf::PdfFormat for #name<#(#generics),*> }\n\n };\n\n\n\n match &ast.data {\n", "file_path": "lemon_pdf_derive/src/lib.rs", "rank": 16, "score": 45405.664326769394 }, { "content": "fn build_unicode_mapping(\n\n ident: &Ident,\n\n names: &[String],\n\n glyph_list: &[(String, Vec<char>)],\n\n) -> Result<proc_macro2::TokenStream, Box<dyn Error>> {\n\n let mut match_clauses = vec![];\n\n for (glyph_name, unicode_values) in glyph_list {\n\n if let Some(index) = names.iter().position(|name| name == glyph_name) {\n\n let index = std::iter::repeat(index);\n\n match_clauses.push(quote! { #(#unicode_values => Some(#index)),* });\n\n }\n\n }\n\n\n\n Ok(quote! {\n\n fn #ident(unicode: char) -> Option<usize> {\n\n match unicode {\n\n #(#match_clauses),*,\n\n _ => None\n\n }\n\n }\n\n })\n\n}\n\n\n", "file_path": "build.rs", "rank": 17, "score": 44438.20436309872 }, { "content": "fn is_space(chr: u8) -> bool {\n\n match chr {\n\n 0 | 9 | 10 | 12 | 13 | 32 => true,\n\n _ => false,\n\n }\n\n}\n\n\n", "file_path": "src/deserializer.rs", "rank": 18, "score": 38074.71183869596 }, { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n let out_dir = env::var(\"OUT_DIR\")?;\n\n let dest_path = Path::new(&out_dir).join(\"base_14_fonts.rs\");\n\n let mut f = fs::File::create(&dest_path)?;\n\n\n\n let parser = afm::afm();\n\n\n\n let mut tokens = vec![];\n\n let mut font_names = vec![];\n\n println!(\"cargo:rerun-if-changed=resources/font/base_14_fonts\");\n\n println!(\"cargo:rerun-if-changed={}\", GLYPH_LIST);\n\n println!(\"cargo:rerun-if-changed={}\", GLYPH_LIST_ZAPF_DINGBATS);\n\n\n\n let mut glyph_list = build_glyph_list(GLYPH_LIST)?;\n\n let glyph_list_zapf_dingbats = build_glyph_list(GLYPH_LIST_ZAPF_DINGBATS)?;\n\n glyph_list.extend_from_slice(&glyph_list_zapf_dingbats);\n\n\n\n for entry in glob(\"resources/font/base_14_fonts/*.afm\")\n\n .expect(\"Could not find font metrics specifications for base 14 fonts.\")\n\n {\n", "file_path": "build.rs", "rank": 19, "score": 37221.39154974483 }, { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n let mut file = BufWriter::new(File::create(\"testpdf.pdf\")?);\n\n\n\n let mut context = DocumentContext::with_writer(&mut file, Version::Pdf1_7)?;\n\n\n\n let mut page = Page::new();\n\n page.add_content(&mut context, None, |page_context| {\n\n let mut font = BuiltInFont::TimesItalic.font(&mut page_context.pdf_context)?;\n\n font.encoding = Some(EncodingEntry::Predefined(\n\n PredefinedEncoding::WinAnsiEncoding,\n\n ));\n\n let font_ref = page_context.pdf_context.write_object(Font::Simple(font))?;\n\n let font_key = page_context.add_font(font_ref);\n\n\n\n page_context.begin_text()?;\n\n page_context.set_font(&font_key, Pt(48.0))?;\n\n page_context.set_position(Pt(20.0), Pt(20.0))?;\n\n page_context.draw_simple_glyphs(&WINDOWS_1252.encode(\"Hello World!\").0)?;\n\n page_context.end_text()?;\n\n Ok(())\n", "file_path": "examples/empty_pdf.rs", "rank": 20, "score": 34970.90125407673 }, { "content": "fn get_digest(file_len: u64) -> HexString {\n\n let mut md5 = Md5::new();\n\n let time = SystemTime::now();\n\n let time = format!(\"{:?}\", time);\n\n md5.input_str(&time);\n\n md5.input_str(&format!(\"{}\", file_len));\n\n HexString(md5.result_str())\n\n}\n\n\n\npub struct Trailer {\n\n pub crossref_offset: u32,\n\n pub(crate) document_catalog: IndirectReference<DocumentCatalog>,\n\n pub(crate) document_info: Option<IndirectReference<DocumentInfo>>,\n\n}\n\n\n\nimpl Trailer {\n\n pub(crate) fn write(&mut self, context: &mut DocumentContext) -> Result<()> {\n\n writeln!(context.output, \"trailer\")?;\n\n let digest = get_digest(context.current_offset());\n\n\n", "file_path": "src/trailer.rs", "rank": 21, "score": 34835.52299740288 }, { "content": "fn multispace0(input: &[u8]) -> IResult<&[u8], &[u8]> {\n\n input.split_at_position_complete(|item| !is_space(item))\n\n}\n\n\n", "file_path": "src/deserializer.rs", "rank": 22, "score": 34236.61200357198 }, { "content": "fn multispace1(input: &[u8]) -> IResult<&[u8], &[u8]> {\n\n input.split_at_position1_complete(|item| !is_space(item), ErrorKind::MultiSpace)\n\n}\n\n\n", "file_path": "src/deserializer.rs", "rank": 23, "score": 34236.61200357198 }, { "content": "// Copyright 2018 Manuel Reinhardt\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse std::io::Result;\n\n\n\nuse crate::object::{Formatter, PdfFormat, Value, Object};\n\n\n\n/// An Array of `PdfObject`s.\n\npub type Array = Vec<Object<Value>>;\n", "file_path": "src/array.rs", "rank": 24, "score": 32974.9820959607 }, { "content": "\n\nmacro_rules! impl_array {\n\n ($num:expr) => {\n\n impl<T: PdfFormat> PdfFormat for [T; $num] {\n\n fn write(&self, f: &mut Formatter) -> Result<()> {\n\n let mut array_formatter = f.format_array();\n\n for obj in self.iter() {\n\n array_formatter = array_formatter.value(obj);\n\n }\n\n array_formatter.finish()\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl_array!(0);\n\nimpl_array!(1);\n\nimpl_array!(2);\n\nimpl_array!(3);\n\nimpl_array!(4);\n", "file_path": "src/array.rs", "rank": 25, "score": 32974.27353144849 }, { "content": "\n\nimpl<T: PdfFormat> PdfFormat for Vec<T> {\n\n fn write(&self, f: &mut Formatter) -> Result<()> {\n\n let mut array_formatter = f.format_array();\n\n for obj in self.iter() {\n\n array_formatter = array_formatter.value(obj);\n\n }\n\n array_formatter.finish()\n\n }\n\n}\n\n\n\nimpl<T: PdfFormat> PdfFormat for &[T] {\n\n fn write(&self, f: &mut Formatter) -> Result<()> {\n\n let mut array_formatter = f.format_array();\n\n for obj in self.iter() {\n\n array_formatter = array_formatter.value(obj);\n\n }\n\n array_formatter.finish()\n\n }\n\n}\n", "file_path": "src/array.rs", "rank": 26, "score": 32973.87921572246 }, { "content": "impl_array!(5);\n\nimpl_array!(6);\n\nimpl_array!(7);\n\nimpl_array!(8);\n\nimpl_array!(9);\n\nimpl_array!(10);\n\nimpl_array!(11);\n\nimpl_array!(12);\n\nimpl_array!(13);\n\nimpl_array!(14);\n\nimpl_array!(15);\n\nimpl_array!(16);\n", "file_path": "src/array.rs", "rank": 27, "score": 32969.86971651462 }, { "content": "use crate::font::Font;\n\nuse crate::object::{Formatter, IndirectReference, PdfFormat, WriteEscaped};\n\nuse crate::pagetree::{Page, ResourceDictionary};\n\nuse crate::stream::StreamEncoder;\n\nuse crate::DocumentContext;\n\n\n\n#[derive(Debug, Default, Copy, Clone, PartialEq, PdfFormat)]\n\npub struct Pt(pub f64);\n\n\n\n#[derive(Debug)]\n\npub struct PageContext<'page, 'context, 'context_borrow> {\n\n pub(crate) fonts: HashMap<IndirectReference<Font>, String>,\n\n pub(crate) content_stream: StreamEncoder,\n\n pub(crate) page: &'page mut Page,\n\n pub pdf_context: &'context_borrow mut DocumentContext<'context>,\n\n}\n\n\n\nimpl<'page, 'context, 'context_borrow> PageContext<'page, 'context, 'context_borrow> {\n\n pub fn add_font(&mut self, font: IndirectReference<Font>) -> String {\n\n let num_fonts = self.fonts.len();\n", "file_path": "src/content.rs", "rank": 28, "score": 32827.436874943574 }, { "content": " for (font_ref, font_key) in self.fonts {\n\n font_dict.insert(font_key, font_ref);\n\n }\n\n let resources = ResourceDictionary { font: font_dict };\n\n self.page.resources = Some(resources);\n\n\n\n let content_stream = self.content_stream.into_stream();\n\n let content_stream_ref = self.pdf_context.write_object(content_stream)?;\n\n let mut array = Vec::new();\n\n array.push(content_stream_ref);\n\n self.page.contents = array;\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/content.rs", "rank": 29, "score": 32819.09598489671 }, { "content": "\n\n pub fn set_position(&mut self, x: Pt, y: Pt) -> Result<()> {\n\n self.write_operation2(x, y, \"Td\")\n\n }\n\n\n\n pub fn draw_simple_glyphs(&mut self, characters: &[u8]) -> Result<()> {\n\n self.write_operation1(characters, \"Tj\")\n\n }\n\n\n\n pub fn draw_cid_glyphs(&mut self, glyphs: impl IntoIterator<Item = u16>) -> Result<()> {\n\n write!(self.content_stream, \"<\")?;\n\n for glyph in glyphs {\n\n self.content_stream.write_hex_escaped(&glyph.to_be_bytes())?;\n\n }\n\n write!(self.content_stream, \"> Tj \")?;\n\n Ok(())\n\n }\n\n\n\n pub(crate) fn finish(self) -> Result<()> {\n\n let mut font_dict = HashMap::new();\n", "file_path": "src/content.rs", "rank": 30, "score": 32811.98336874831 }, { "content": " let key = self\n\n .fonts\n\n .entry(font)\n\n .or_insert_with(|| format!(\"F{}\", num_fonts));\n\n key.clone()\n\n }\n\n\n\n pub fn push_operand(&mut self, operand: impl PdfFormat) -> Result<()> {\n\n let mut formatter = Formatter {\n\n writer: &mut self.content_stream,\n\n };\n\n operand.write(&mut formatter)?;\n\n write!(self.content_stream, \" \")\n\n }\n\n\n\n pub fn apply_operator(&mut self, operator: &str) -> Result<()> {\n\n write!(self.content_stream, \"{} \", operator)\n\n }\n\n\n\n pub fn write_operation1(&mut self, arg1: impl PdfFormat, operator: &str) -> Result<()> {\n", "file_path": "src/content.rs", "rank": 31, "score": 32810.05322926467 }, { "content": "\n\n pub fn close_and_stroke_path(&mut self) -> Result<()> {\n\n self.apply_operator(\"s\")\n\n }\n\n\n\n pub fn fill_path(&mut self) -> Result<()> {\n\n self.apply_operator(\"f\")\n\n }\n\n\n\n pub fn begin_text(&mut self) -> Result<()> {\n\n self.apply_operator(\"BT\")\n\n }\n\n\n\n pub fn end_text(&mut self) -> Result<()> {\n\n self.apply_operator(\"ET\")\n\n }\n\n\n\n pub fn set_font(&mut self, font_key: &str, size: Pt) -> Result<()> {\n\n self.write_operation2(font_key, size, \"Tf\")\n\n }\n", "file_path": "src/content.rs", "rank": 32, "score": 32805.00077411524 }, { "content": "\n\n pub fn move_to(&mut self, x: Pt, y: Pt) -> Result<()> {\n\n self.write_operation2(x, y, \"m\")\n\n }\n\n\n\n pub fn line_to(&mut self, x: Pt, y: Pt) -> Result<()> {\n\n self.write_operation2(x, y, \"l\")\n\n }\n\n\n\n pub fn rect(&mut self, x: Pt, y: Pt, width: Pt, height: Pt) -> Result<()> {\n\n self.write_operation4(x, y, width, height, \"re\")\n\n }\n\n\n\n pub fn close_path(&mut self) -> Result<()> {\n\n self.apply_operator(\"h\")\n\n }\n\n\n\n pub fn stroke_path(&mut self) -> Result<()> {\n\n self.apply_operator(\"S\")\n\n }\n", "file_path": "src/content.rs", "rank": 33, "score": 32803.834920585236 }, { "content": " self.apply_operator(operator)\n\n }\n\n\n\n pub fn save_graphics_state(&mut self) -> Result<()> {\n\n self.apply_operator(\"q\")\n\n }\n\n\n\n pub fn restore_graphics_state(&mut self) -> Result<()> {\n\n self.apply_operator(\"Q\")\n\n }\n\n\n\n pub fn concatenate_matrix(\n\n &mut self,\n\n a: f64,\n\n b: f64,\n\n c: f64,\n\n d: f64,\n\n e: Pt,\n\n f: Pt,\n\n ) -> Result<()> {\n", "file_path": "src/content.rs", "rank": 34, "score": 32802.36689522718 }, { "content": " self.push_operand(arg1)?;\n\n self.apply_operator(operator)\n\n }\n\n\n\n pub fn write_operation2(\n\n &mut self,\n\n arg1: impl PdfFormat,\n\n arg2: impl PdfFormat,\n\n operator: &str,\n\n ) -> Result<()> {\n\n self.push_operand(arg1)?;\n\n self.push_operand(arg2)?;\n\n self.apply_operator(operator)\n\n }\n\n\n\n pub fn write_operation3(\n\n &mut self,\n\n arg1: impl PdfFormat,\n\n arg2: impl PdfFormat,\n\n arg3: impl PdfFormat,\n", "file_path": "src/content.rs", "rank": 35, "score": 32801.21774775266 }, { "content": " self.push_operand(a)?;\n\n self.push_operand(b)?;\n\n self.push_operand(c)?;\n\n self.push_operand(d)?;\n\n self.push_operand(e)?;\n\n self.push_operand(f)?;\n\n self.apply_operator(\"cm\")\n\n }\n\n\n\n pub fn line_width(&mut self, width: Pt) -> Result<()> {\n\n self.write_operation1(width, \"w\")\n\n }\n\n\n\n pub fn device_rgb_fill_color(&mut self, red: f64, green: f64, blue: f64) -> Result<()> {\n\n self.write_operation3(red, green, blue, \"rg\")\n\n }\n\n\n\n pub fn device_rgb_stroke_color(&mut self, red: f64, green: f64, blue: f64) -> Result<()> {\n\n self.write_operation3(red, green, blue, \"RG\")\n\n }\n", "file_path": "src/content.rs", "rank": 36, "score": 32799.48006453549 }, { "content": " operator: &str,\n\n ) -> Result<()> {\n\n self.push_operand(arg1)?;\n\n self.push_operand(arg2)?;\n\n self.push_operand(arg3)?;\n\n self.apply_operator(operator)\n\n }\n\n\n\n pub fn write_operation4(\n\n &mut self,\n\n arg1: impl PdfFormat,\n\n arg2: impl PdfFormat,\n\n arg3: impl PdfFormat,\n\n arg4: impl PdfFormat,\n\n operator: &str,\n\n ) -> Result<()> {\n\n self.push_operand(arg1)?;\n\n self.push_operand(arg2)?;\n\n self.push_operand(arg3)?;\n\n self.push_operand(arg4)?;\n", "file_path": "src/content.rs", "rank": 37, "score": 32799.02869052729 }, { "content": "// Copyright 2018 Manuel Reinhardt\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse std::collections::HashMap;\n\nuse std::io::{Result, Write};\n\n\n\nuse lemon_pdf_derive::PdfFormat;\n\nuse crate as lemon_pdf;\n\n\n", "file_path": "src/content.rs", "rank": 38, "score": 32796.85812052703 }, { "content": "use crate::array::Array;\n\nuse crate::dictionary::Dictionary;\n\nuse crate::stream::Stream;\n\nuse serde::Serialize;\n\n\n\n#[allow(missing_debug_implementations)]\n\npub struct Formatter<'a> {\n\n pub(crate) writer: &'a mut dyn Write,\n\n}\n\n\n\nimpl<'a> Formatter<'a> {\n\n pub fn format_dictionary<'b>(&'b mut self) -> DictionaryFormatter<'a, 'b>\n\n where\n\n 'a: 'b,\n\n {\n\n DictionaryFormatter::new(self)\n\n }\n\n\n\n pub fn format_array<'b>(&'b mut self) -> ArrayFormatter<'a, 'b>\n\n where\n", "file_path": "src/object.rs", "rank": 39, "score": 32619.516311336687 }, { "content": "\n\nimpl<T> Default for IndirectReference<T> {\n\n fn default() -> Self {\n\n IndirectReference::new(0, 0)\n\n }\n\n}\n\n\n\nimpl<T> Copy for IndirectReference<T> {}\n\n\n\nimpl<T> Clone for IndirectReference<T> {\n\n fn clone(&self) -> Self {\n\n *self\n\n }\n\n}\n\n\n\nimpl<T> IndirectReference<T> {\n\n pub(crate) fn new(number: i64, generation: i64) -> Self {\n\n IndirectReference {\n\n raw: RawIndirectReference(number, generation),\n\n _marker: PhantomData,\n", "file_path": "src/object.rs", "rank": 40, "score": 32616.37178939403 }, { "content": " }\n\n\n\n pub fn finish(mut self) -> Result<()> {\n\n let formatter = &mut self.formatter;\n\n self.result = self.result.and_then(|()| write!(formatter, \">>\"));\n\n self.result\n\n }\n\n}\n\n\n\n#[allow(missing_debug_implementations)]\n\n#[must_use]\n\npub struct ArrayFormatter<'a, 'b> {\n\n formatter: &'b mut Formatter<'a>,\n\n result: Result<()>,\n\n}\n\n\n\nimpl<'a, 'b> ArrayFormatter<'a, 'b> {\n\n fn new(formatter: &'b mut Formatter<'a>) -> Self {\n\n let mut result = Ok(());\n\n result = result.and_then(|_| write!(formatter, \"[ \"));\n", "file_path": "src/object.rs", "rank": 41, "score": 32615.47556170917 }, { "content": "#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize)]\n\n#[serde(rename = \"R\")]\n\npub struct RawIndirectReference(pub i64, pub i64);\n\n\n\nimpl<T> From<IndirectReference<T>> for RawIndirectReference {\n\n fn from(other: IndirectReference<T>) -> Self {\n\n RawIndirectReference(other.number(), other.generation())\n\n }\n\n}\n\n\n\n/// A reference to an indirect object.\n\n///\n\n/// Indirect references to objects can be obtained using `write_object` or\n\n/// `write_object_fn` on the `Context`.\n\n#[derive(Serialize)]\n\n#[serde(into = \"RawIndirectReference\")]\n\npub struct IndirectReference<T> {\n\n raw: RawIndirectReference,\n\n _marker: PhantomData<T>,\n\n}\n", "file_path": "src/object.rs", "rank": 42, "score": 32614.87448221936 }, { "content": " }\n\n}\n\n\n\nimpl<T> PdfFormat for IndirectReference<T> {\n\n fn write(&self, output: &mut Formatter) -> Result<()> {\n\n write!(output, \"{} {} R\", self.number(), self.generation())\n\n }\n\n}\n\n\n\nimpl<T: PdfFormat> PdfFormat for Option<T> {\n\n fn write(&self, f: &mut Formatter) -> Result<()> {\n\n match self {\n\n Some(val) => val.write(f),\n\n None => write!(f, \"null\"),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, PdfFormat)]\n\npub enum Object<T> {\n", "file_path": "src/object.rs", "rank": 43, "score": 32612.740546120916 }, { "content": " 'a: 'b,\n\n {\n\n ArrayFormatter::new(self)\n\n }\n\n}\n\n\n\nimpl<'a> Write for Formatter<'a> {\n\n fn write(&mut self, bytes: &[u8]) -> Result<usize> {\n\n self.writer.write(bytes)\n\n }\n\n\n\n fn flush(&mut self) -> Result<()> {\n\n self.writer.flush()\n\n }\n\n}\n\n\n\n#[allow(missing_debug_implementations)]\n\n#[must_use]\n\npub struct DictionaryFormatter<'a, 'b> {\n\n formatter: &'b mut Formatter<'a>,\n", "file_path": "src/object.rs", "rank": 44, "score": 32612.6286990414 }, { "content": " }\n\n}\n\n\n\nimpl PdfFormat for usize {\n\n fn write(&self, output: &mut Formatter) -> Result<()> {\n\n write!(output, \"{}\", self)\n\n }\n\n}\n\n\n\nimpl PdfFormat for i64 {\n\n fn write(&self, output: &mut Formatter) -> Result<()> {\n\n write!(output, \"{}\", self)\n\n }\n\n}\n\n\n\n#[derive(Debug, From, PdfFormat)]\n\npub enum Value {\n\n Null,\n\n Boolean(bool),\n\n Integer(i64),\n", "file_path": "src/object.rs", "rank": 45, "score": 32611.273760557007 }, { "content": " result: Result<()>,\n\n}\n\n\n\nimpl<'a, 'b> DictionaryFormatter<'a, 'b> {\n\n fn new(formatter: &'b mut Formatter<'a>) -> Self {\n\n let mut result = Ok(());\n\n result = result.and_then(|_| write!(formatter, \"<< \"));\n\n DictionaryFormatter { formatter, result }\n\n }\n\n\n\n pub fn key_value(mut self, key: &dyn PdfFormat, value: &dyn PdfFormat) -> Self {\n\n let formatter = &mut self.formatter;\n\n self.result = self.result.and_then(|()| {\n\n key.write(formatter)?;\n\n write!(formatter, \" \")?;\n\n value.write(formatter)?;\n\n writeln!(formatter)?;\n\n Ok(())\n\n });\n\n self\n", "file_path": "src/object.rs", "rank": 46, "score": 32610.115869016867 }, { "content": " Direct(T),\n\n Indirect(IndirectReference<T>),\n\n}\n\n\n\nimpl<T: Default> Default for Object<T> {\n\n fn default() -> Self {\n\n Object::Direct(Default::default())\n\n }\n\n}\n\n\n\nimpl<T> From<IndirectReference<T>> for Object<T> {\n\n fn from(reference: IndirectReference<T>) -> Self {\n\n Object::Indirect(reference)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_hex_escape() {\n\n let mut outp = vec![];\n\n outp.write_hex_escaped(b\"\\nabc\").unwrap();\n\n assert_eq!(\"0A616263\", std::str::from_utf8(&outp).unwrap());\n\n }\n\n}\n", "file_path": "src/object.rs", "rank": 47, "score": 32610.109154751863 }, { "content": " ArrayFormatter { formatter, result }\n\n }\n\n\n\n pub fn value(mut self, value: &dyn PdfFormat) -> Self {\n\n let formatter = &mut self.formatter;\n\n self.result = self.result.and_then(|()| {\n\n value.write(formatter)?;\n\n write!(formatter, \" \")?;\n\n Ok(())\n\n });\n\n self\n\n }\n\n\n\n pub fn finish(mut self) -> Result<()> {\n\n let formatter = &mut self.formatter;\n\n self.result = self.result.and_then(|()| write!(formatter, \"]\"));\n\n self.result\n\n }\n\n}\n\n\n", "file_path": "src/object.rs", "rank": 48, "score": 32609.763369680375 }, { "content": " }\n\n }\n\n\n\n pub fn number(&self) -> i64 {\n\n self.raw.0\n\n }\n\n\n\n pub fn generation(&self) -> i64 {\n\n self.raw.1\n\n }\n\n\n\n /// Converts an indirect reference to point to an object of type `U`.\n\n ///\n\n /// This function is to be used with care, else invalid PDF documents may be created.\n\n pub fn convert<U>(self) -> IndirectReference<U> {\n\n IndirectReference::new(self.number(), self.generation())\n\n }\n\n\n\n pub fn raw(self) -> RawIndirectReference {\n\n self.raw\n", "file_path": "src/object.rs", "rank": 49, "score": 32605.889720905216 }, { "content": "impl PdfFormat for bool {\n\n fn write(&self, output: &mut Formatter) -> Result<()> {\n\n match self {\n\n true => write!(output, \"true\"),\n\n false => write!(output, \"false\"),\n\n }\n\n }\n\n}\n\n\n\nimpl PdfFormat for String {\n\n fn write(&self, output: &mut Formatter) -> Result<()> {\n\n <Self as AsRef<str>>::as_ref(self).write(output)\n\n }\n\n}\n\n\n", "file_path": "src/object.rs", "rank": 50, "score": 32605.528602172704 }, { "content": " Real(f64),\n\n String(Vec<u8>),\n\n Name(String),\n\n Array(Array),\n\n Dictionary(Dictionary),\n\n Stream(Stream),\n\n}\n\n\n\nimpl<'a> From<&'a str> for Value {\n\n fn from(from: &'a str) -> Value {\n\n Value::Name(from.to_string())\n\n }\n\n}\n\n\n\nimpl From<f32> for Value {\n\n fn from(from: f32) -> Value {\n\n Value::Real(f64::from(from))\n\n }\n\n}\n\n\n", "file_path": "src/object.rs", "rank": 51, "score": 32605.480124505186 }, { "content": "\n\nimpl<T> PartialEq for IndirectReference<T> {\n\n fn eq(&self, other: &Self) -> bool {\n\n self.raw() == other.raw()\n\n }\n\n}\n\n\n\nimpl<T> Eq for IndirectReference<T> {}\n\n\n\nimpl<T> Hash for IndirectReference<T> {\n\n fn hash<H: std::hash::Hasher>(&self, state: &mut H) {\n\n self.raw.hash(state)\n\n }\n\n}\n\n\n\nimpl<T> Debug for IndirectReference<T> {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n self.raw().fmt(f)\n\n }\n\n}\n", "file_path": "src/object.rs", "rank": 52, "score": 32604.589686508738 }, { "content": " fn write(&self, output: &mut Formatter) -> Result<()> {\n\n <Self as AsRef<[u8]>>::as_ref(self).write(output)\n\n }\n\n}\n\n\n\nimpl PdfFormat for f32 {\n\n fn write(&self, output: &mut Formatter) -> Result<()> {\n\n write!(output, \"{:.2}\", self)\n\n }\n\n}\n\n\n\nimpl PdfFormat for f64 {\n\n fn write(&self, output: &mut Formatter) -> Result<()> {\n\n write!(output, \"{:.2}\", self)\n\n }\n\n}\n\n\n\nimpl PdfFormat for u32 {\n\n fn write(&self, output: &mut Formatter) -> Result<()> {\n\n write!(output, \"{}\", self)\n", "file_path": "src/object.rs", "rank": 53, "score": 32603.484835709307 }, { "content": "// Copyright 2018 Manuel Reinhardt\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse std::io::{Result, Write};\n\nuse std::{fmt::Debug, hash::Hash, marker::PhantomData};\n\n\n\nuse crate as lemon_pdf;\n\nuse lemon_pdf_derive::PdfFormat;\n\n\n", "file_path": "src/object.rs", "rank": 54, "score": 32601.059241143677 }, { "content": " Ok(())\n\n }\n\n\n\n fn write_hex_escaped(&mut self, bytes: &[u8]) -> std::io::Result<()> {\n\n for &byte in bytes {\n\n write!(self, \"{:02X}\", byte)?;\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<'a> PdfFormat for &'a [u8] {\n\n fn write(&self, output: &mut Formatter) -> Result<()> {\n\n write!(output, \"(\")?;\n\n output.write_escaped(self)?;\n\n write!(output, \")\")\n\n }\n\n}\n\n\n\nimpl PdfFormat for Vec<u8> {\n", "file_path": "src/object.rs", "rank": 55, "score": 32600.406144815013 }, { "content": "use crate as lemon_pdf;\n\n\n\nuse crate::{Page, object::{Object, IndirectReference}};\n\n\n\nuse lemon_pdf_derive::PdfFormat;\n\n\n\n#[derive(Debug, Clone, PdfFormat)]\n\npub struct StructTreeRoot {\n\n pub k: Vec<Object<StructElem>>\n\n}\n\n\n\n#[derive(Debug, Clone, PdfFormat)]\n\npub enum StandardStructureType {\n\n Document,\n\n Part,\n\n Art,\n\n Sect,\n\n Div,\n\n BlockQuote,\n\n Caption,\n", "file_path": "src/structure_tree.rs", "rank": 56, "score": 31225.916551568065 }, { "content": " TD,\n\n THead,\n\n TBody,\n\n TFoot,\n\n}\n\n\n\n#[derive(Debug, Clone, PdfFormat)]\n\npub enum StructureParent {\n\n Root(IndirectReference<StructTreeRoot>),\n\n Elem(IndirectReference<StructElem>)\n\n}\n\n\n\n#[derive(Debug, Clone, PdfFormat)]\n\npub struct StructElem {\n\n pub s: StandardStructureType,\n\n pub p: StructureParent,\n\n #[rename(\"ID\")]\n\n #[skip_if(Vec::is_empty)]\n\n pub id: Vec<u8>,\n\n pub pg: Option<IndirectReference<Page>>,\n\n /// the children\n\n pub k: Vec<Object<StructElem>>\n\n}", "file_path": "src/structure_tree.rs", "rank": 57, "score": 31220.990709156755 }, { "content": " TOC,\n\n TOCI,\n\n Index,\n\n NonStruct,\n\n Private,\n\n P,\n\n H,\n\n H1,\n\n H2,\n\n H3,\n\n H4,\n\n H5,\n\n H6,\n\n L,\n\n LI,\n\n Lbl,\n\n LBody,\n\n Table,\n\n TR,\n\n TH,\n", "file_path": "src/structure_tree.rs", "rank": 58, "score": 31202.479622524334 }, { "content": "impl std::ops::Sub for FontUnit {\n\n type Output = FontUnit;\n\n\n\n fn sub(self, other: FontUnit) -> FontUnit {\n\n FontUnit(self.0 - other.0)\n\n }\n\n}\n\n\n\n#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PdfFormat)]\n\npub enum FontType {\n\n Type0,\n\n Type1,\n\n TrueType,\n\n}\n\n\n\nimpl Default for FontType {\n\n fn default() -> Self {\n\n FontType::Type1\n\n }\n\n}\n", "file_path": "src/font.rs", "rank": 59, "score": 29980.579314765924 }, { "content": "pub mod type0;\n\n\n\n#[derive(Debug, Clone, PartialEq, PdfFormat)]\n\npub enum Font {\n\n Simple(builtin::SimpleFont),\n\n Composite(type0::CompositeFont),\n\n}\n\n\n\n/// A postscript font unit (1/1000 of an EM)\n\n#[derive(Debug, Default, Copy, Clone, PartialEq, PartialOrd, PdfFormat)]\n\npub struct FontUnit(pub f64);\n\n\n\nimpl std::ops::Add for FontUnit {\n\n type Output = FontUnit;\n\n\n\n fn add(self, other: FontUnit) -> FontUnit {\n\n FontUnit(self.0 + other.0)\n\n }\n\n}\n\n\n", "file_path": "src/font.rs", "rank": 60, "score": 29979.73696099921 }, { "content": "// Copyright 2018 Manuel Reinhardt\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse crate as lemon_pdf;\n\nuse lemon_pdf_derive::PdfFormat;\n\n\n\npub mod builtin;\n\npub mod descriptor;\n\npub mod encoding;\n", "file_path": "src/font.rs", "rank": 61, "score": 29969.871479066067 }, { "content": "use super::{descriptor::FontDescriptor, FontType, FontUnit};\n\n\n\nuse crate as lemon_pdf;\n\nuse crate::object::{IndirectReference, Object};\n\nuse crate::stream::Stream;\n\nuse lemon_pdf_derive::PdfFormat;\n\n\n\n#[derive(Debug, Clone, PartialEq, Default, PdfFormat)]\n\n#[rename(\"Font\")]\n\npub struct CompositeFont {\n\n pub subtype: FontType,\n\n pub base_font: String,\n\n pub encoding: String,\n\n pub descendant_fonts: [IndirectReference<CIDFont>; 1],\n\n #[skip_if(\"Option::is_none\")]\n\n pub to_unicode: Option<IndirectReference<Stream>>,\n\n}\n\n\n\n#[derive(Debug, Copy, Clone, PartialEq, PdfFormat)]\n\npub enum CIDFontType {\n", "file_path": "src/font/type0.rs", "rank": 62, "score": 28385.950852146485 }, { "content": " pub encoding: Option<encoding::EncodingEntry>,\n\n}\n\n\n\nimpl SimpleFont {\n\n pub fn create_with_base_name(name: String, subtype: FontType) -> Self {\n\n SimpleFont {\n\n subtype,\n\n base_font: name,\n\n ..Default::default()\n\n }\n\n }\n\n}\n\n\n\nimpl BuiltInFont {\n\n pub fn font(self, context: &mut DocumentContext) -> Result<SimpleFont> {\n\n let metrics = self.metrics();\n\n\n\n let flags = match metrics.family_name {\n\n \"Helvetica\" => FontFlags::NONSYMBOLIC,\n\n \"Times\" => FontFlags::NONSYMBOLIC | FontFlags::SERIF,\n", "file_path": "src/font/builtin.rs", "rank": 63, "score": 28382.56596868532 }, { "content": "//! Contains the builtin PDF fonts\n\n\n\nuse std::io::Result;\n\n\n\nuse lemon_pdf_derive::PdfFormat;\n\n\n\nuse super::{\n\n descriptor::{FontDescriptor, FontFlags},\n\n encoding, FontType, FontUnit,\n\n};\n\nuse crate::document::DocumentContext;\n\nuse crate::object::{IndirectReference};\n\n\n\n#[derive(Debug, Copy, Clone)]\n\npub struct BuiltInFontMetrics {\n\n pub font_name: &'static str,\n\n pub family_name: &'static str,\n\n pub ascender: FontUnit,\n\n pub descender: FontUnit,\n\n pub cap_height: FontUnit,\n", "file_path": "src/font/builtin.rs", "rank": 64, "score": 28381.645895562116 }, { "content": "// pub fn metrics(self) -> BuiltInFontMetrics { ... }\n\n// }\n\ninclude!(concat!(env!(\"OUT_DIR\"), \"/base_14_fonts.rs\"));\n\n\n\nuse crate as lemon_pdf;\n\n\n\n#[derive(Debug, Clone, PartialEq, Default, PdfFormat)]\n\n#[rename(\"Font\")]\n\npub struct SimpleFont {\n\n pub subtype: FontType,\n\n pub base_font: String,\n\n #[skip_if(\"Option::is_none\")]\n\n pub first_char: Option<usize>,\n\n #[skip_if(\"Option::is_none\")]\n\n pub last_char: Option<usize>,\n\n #[skip_if(\"Vec::is_empty\")]\n\n pub widths: Vec<FontUnit>,\n\n #[skip_if(\"Option::is_none\")]\n\n pub font_descriptor: Option<IndirectReference<FontDescriptor>>,\n\n #[skip_if(\"Option::is_none\")]\n", "file_path": "src/font/builtin.rs", "rank": 65, "score": 28381.546366186467 }, { "content": " },\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Default, PdfFormat)]\n\n#[rename(\"Font\")]\n\npub struct CIDFont {\n\n pub subtype: CIDFontType,\n\n pub base_font: String,\n\n #[rename(\"CIDSystemInfo\")]\n\n pub cid_system_info: Object<CIDSystemInfo>,\n\n pub font_descriptor: IndirectReference<FontDescriptor>,\n\n #[rename(\"DW\")]\n\n #[skip_if(\"Option::is_none\")]\n\n pub dw: Option<FontUnit>,\n\n #[skip_if(\"Option::is_none\")]\n\n pub w: Option<Object<Vec<MetricsEntry>>>,\n\n #[rename(\"DW2\")]\n\n #[skip_if(\"Option::is_none\")]\n\n pub dw2: Option<FontUnit>,\n\n #[skip_if(\"Option::is_none\")]\n", "file_path": "src/font/type0.rs", "rank": 66, "score": 28380.873550941 }, { "content": " CIDFontType0,\n\n CIDFontType2,\n\n}\n\n\n\nimpl Default for CIDFontType {\n\n fn default() -> Self {\n\n CIDFontType::CIDFontType0\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, PdfFormat)]\n\npub enum MetricsEntry {\n\n Range {\n\n from: u32,\n\n to: u32,\n\n advance: FontUnit,\n\n },\n\n Consecutive {\n\n start: u32,\n\n advances: Vec<FontUnit>,\n", "file_path": "src/font/type0.rs", "rank": 67, "score": 28379.260610407444 }, { "content": "#[derive(Debug, Default, Clone, PartialEq, PdfFormat)]\n\npub struct Encoding {\n\n #[skip_if(\"Option::is_none\")]\n\n pub base_encoding: Option<PredefinedEncoding>,\n\n #[skip_if(\"Option::is_none\")]\n\n pub differences: Option<Object<Vec<usize>>>,\n\n}\n\n\n\npub const EXPERT_ENCODING: [&str; 256] = [\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n", "file_path": "src/font/encoding.rs", "rank": 68, "score": 28379.07865579011 }, { "content": "use crate as lemon_pdf;\n\nuse crate::object::Object;\n\nuse lemon_pdf_derive::PdfFormat;\n\n\n\nuse std::convert::TryFrom;\n\n\n\n#[derive(Debug, Copy, Clone, PartialEq, Eq, PdfFormat)]\n\npub enum PredefinedEncoding {\n\n StandardEncoding,\n\n WinAnsiEncoding,\n\n MacRomanEncoding,\n\n}\n\n\n\nimpl PredefinedEncoding {\n\n pub fn decode(self, code: u8) -> Option<&'static str> {\n\n let table = match self {\n\n PredefinedEncoding::StandardEncoding => STANDARD_ENCODING,\n\n PredefinedEncoding::WinAnsiEncoding => WIN_ANSI_ENCODING,\n\n PredefinedEncoding::MacRomanEncoding => MAC_ROMAN_ENCODING,\n\n };\n", "file_path": "src/font/encoding.rs", "rank": 69, "score": 28378.599119928185 }, { "content": "use lemon_pdf_derive::PdfFormat;\n\nuse crate as lemon_pdf;\n\n\n\nuse super::FontUnit;\n\nuse crate::object::{PdfFormat, IndirectReference};\n\nuse bitflags::bitflags;\n\n\n\nuse crate::stream::Stream;\n\n\n\n#[derive(Debug, Copy, Clone, PartialEq, Eq, PdfFormat)]\n\npub enum FontStretch {\n\n UltraCondensed,\n\n ExtraCondensed,\n\n Condensed,\n\n SemiCondensed,\n\n Normal,\n\n SemiExpanded,\n\n Expanded,\n\n ExtraExpanded,\n\n UltraExpanded,\n", "file_path": "src/font/descriptor.rs", "rank": 70, "score": 28377.88830052417 }, { "content": "#[derive(Debug, Clone, PartialEq, PdfFormat)]\n\npub enum EncodingEntry {\n\n Predefined(PredefinedEncoding),\n\n Custom(Encoding),\n\n}\n\n\n\nimpl Default for EncodingEntry {\n\n fn default() -> Self {\n\n EncodingEntry::Predefined(PredefinedEncoding::StandardEncoding)\n\n }\n\n}\n\n\n\nimpl EncodingEntry {\n\n pub fn encode(&self, char_name: &str) -> Option<u8> {\n\n match self {\n\n EncodingEntry::Predefined(encoding) => encoding.encode(char_name),\n\n _ => unimplemented!(),\n\n }\n\n }\n\n\n", "file_path": "src/font/encoding.rs", "rank": 71, "score": 28377.883780232245 }, { "content": " #[skip_if(\"is_default\")]\n\n pub cap_height: FontUnit,\n\n #[skip_if(\"is_default\")]\n\n pub x_height: FontUnit,\n\n #[skip_if(\"is_default\")]\n\n pub stem_h: FontUnit,\n\n pub stem_v: FontUnit,\n\n #[skip_if(\"is_default\")]\n\n pub avg_width: FontUnit,\n\n #[skip_if(\"is_default\")]\n\n pub max_width: FontUnit,\n\n #[skip_if(\"is_default\")]\n\n pub missing_width: FontUnit,\n\n #[skip_if(\"Option::is_none\")]\n\n pub font_file: Option<IndirectReference<Stream>>,\n\n #[skip_if(\"Option::is_none\")]\n\n pub font_file2: Option<IndirectReference<Stream>>,\n\n #[skip_if(\"Option::is_none\")]\n\n pub font_file3: Option<IndirectReference<Stream>>,\n\n #[skip_if(\"Vec::is_empty\")]\n\n pub char_set: Vec<u8>,\n\n}\n", "file_path": "src/font/descriptor.rs", "rank": 72, "score": 28376.906649744524 }, { "content": " pub w2: Option<Object<Vec<MetricsEntry>>>,\n\n #[rename(\"CIDToGIDMap\")]\n\n #[skip_if(\"String::is_empty\")]\n\n pub cid_to_gid_map: String,\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, PdfFormat)]\n\n#[omit_type(true)]\n\npub struct CIDSystemInfo {\n\n pub registry: Vec<u8>,\n\n pub ordering: Vec<u8>,\n\n pub supplement: u32,\n\n}\n\n\n\nimpl Default for CIDSystemInfo {\n\n fn default() -> Self {\n\n CIDSystemInfo {\n\n registry: b\"Adobe\".to_vec(),\n\n ordering: b\"Identity\".to_vec(),\n\n supplement: 0,\n\n }\n\n }\n\n}\n", "file_path": "src/font/type0.rs", "rank": 73, "score": 28376.54269000676 }, { "content": "}\n\n\n\nbitflags! {\n\n pub struct FontFlags: u32 {\n\n const FIXED_PITCH = 1 << 0;\n\n const SERIF = 1 << 1;\n\n const SYMBOLIC = 1 << 2;\n\n const SCRIPT = 1 << 3;\n\n // here an entry is missing from the PDF spec\n\n const NONSYMBOLIC = 1 << 5;\n\n const ITALIC = 1 << 6;\n\n\n\n const ALL_CAP = 1 << 16;\n\n const SMALL_CAP = 1 << 17;\n\n const FORCE_BOLD = 1 << 18;\n\n }\n\n}\n\n\n\nimpl Default for FontFlags {\n\n fn default() -> Self {\n", "file_path": "src/font/descriptor.rs", "rank": 74, "score": 28375.62828242251 }, { "content": " pub stem_h: FontUnit,\n\n pub stem_v: FontUnit,\n\n pub font_bbox: [FontUnit; 4],\n\n pub x_height: FontUnit,\n\n pub italic_angle: f64,\n\n pub char_metrics: &'static [CharMetric],\n\n /// A function that maps from a unicode encoded `char` to the\n\n /// corresponding index in the `char_metrics` table or None.\n\n pub unicode_mapping: fn(char) -> Option<usize>,\n\n}\n\n\n\n#[derive(Debug, Copy, Clone)]\n\npub struct CharMetric {\n\n pub name: &'static str,\n\n pub bbox: [FontUnit; 4],\n\n pub character_code: i32,\n\n pub advance_width: FontUnit,\n\n}\n\n\n\n// The following `include!` expands to\n", "file_path": "src/font/builtin.rs", "rank": 75, "score": 28375.141685795 }, { "content": " ascent: metrics.ascender,\n\n descent: metrics.descender,\n\n flags,\n\n ..Default::default()\n\n };\n\n let font_descriptor = context.write_object(font_descriptor)?;\n\n\n\n Ok(SimpleFont {\n\n subtype: FontType::Type1,\n\n base_font: metrics.font_name.to_string(),\n\n font_descriptor: Some(font_descriptor),\n\n ..Default::default()\n\n })\n\n }\n\n}\n", "file_path": "src/font/builtin.rs", "rank": 76, "score": 28374.532305681572 }, { "content": " FontFlags::NONSYMBOLIC\n\n }\n\n}\n\n\n\nimpl PdfFormat for FontFlags {\n\n fn write(&self, output: &mut crate::object::Formatter) -> std::io::Result<()> {\n\n PdfFormat::write(&self.bits(), output)\n\n }\n\n}\n\n\n", "file_path": "src/font/descriptor.rs", "rank": 77, "score": 28373.895017771156 }, { "content": "//\n\n// #[derive(Debug, Copy, Clone, PartialEq, Eq)]\n\n// pub enum BuiltInFont {\n\n// CourierBold,\n\n// CourierBoldOblique,\n\n// CourierOblique,\n\n// Courier,\n\n// HelveticaBold,\n\n// HelveticaBoldOblique,\n\n// HelveticaOblique,\n\n// Helvetica,\n\n// Symbol,\n\n// TimesBold,\n\n// TimesBoldItalic,\n\n// TimesItalic,\n\n// TimesRoman,\n\n// ZapfDingbats,\n\n// }\n\n//\n\n// impl BuiltInFont {\n", "file_path": "src/font/builtin.rs", "rank": 78, "score": 28373.654052818736 }, { "content": " pub fn decode(&self, code: u8) -> Option<&'static str> {\n\n match self {\n\n EncodingEntry::Predefined(encoding) => encoding.decode(code),\n\n _ => unimplemented!(),\n\n }\n\n }\n\n}\n\n\n\nimpl EncodingEntry {\n\n pub fn into_encoding(self) -> Encoding {\n\n match self {\n\n EncodingEntry::Predefined(encoding) => Encoding {\n\n base_encoding: Some(encoding),\n\n ..Default::default()\n\n },\n\n EncodingEntry::Custom(encoding) => encoding,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/font/encoding.rs", "rank": 79, "score": 28372.64222030002 }, { "content": " if table[code as usize].is_empty() {\n\n None\n\n } else {\n\n Some(table[code as usize])\n\n }\n\n }\n\n\n\n pub fn encode(self, char_name: &str) -> Option<u8> {\n\n let table = match self {\n\n PredefinedEncoding::StandardEncoding => STANDARD_ENCODING,\n\n PredefinedEncoding::WinAnsiEncoding => WIN_ANSI_ENCODING,\n\n PredefinedEncoding::MacRomanEncoding => MAC_ROMAN_ENCODING,\n\n };\n\n table\n\n .iter()\n\n .position(|&entry| entry == char_name)\n\n .and_then(|index| u8::try_from(index).ok())\n\n }\n\n}\n\n\n", "file_path": "src/font/encoding.rs", "rank": 80, "score": 28367.79713125823 }, { "content": " \"Courier\" => FontFlags::NONSYMBOLIC | FontFlags::FIXED_PITCH | FontFlags::SERIF,\n\n \"Symbol\" => FontFlags::SYMBOLIC,\n\n \"ZapfDingbats\" => FontFlags::SYMBOLIC,\n\n _ => FontFlags::default(),\n\n };\n\n let flags = if metrics.italic_angle != 0.0 {\n\n flags | FontFlags::ITALIC\n\n } else {\n\n flags\n\n };\n\n\n\n let font_descriptor = FontDescriptor {\n\n font_name: metrics.font_name.to_string(),\n\n font_family: metrics.family_name.as_bytes().to_owned(),\n\n font_b_box: metrics.font_bbox,\n\n cap_height: metrics.cap_height,\n\n italic_angle: metrics.italic_angle,\n\n x_height: metrics.x_height,\n\n stem_h: metrics.stem_h,\n\n stem_v: metrics.stem_v,\n", "file_path": "src/font/builtin.rs", "rank": 81, "score": 28366.289425258197 }, { "content": " \"\",\n\n \"\",\n\n];\n\n\n\npub const WIN_ANSI_ENCODING: [&str; 256] = [\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n", "file_path": "src/font/encoding.rs", "rank": 82, "score": 28365.22601972585 }, { "content": " \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n];\n\n\n\npub const MAC_ROMAN_ENCODING: [&str; 256] = [\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n", "file_path": "src/font/encoding.rs", "rank": 83, "score": 28365.22601972585 }, { "content": " \"ydieresis\",\n\n];\n\n\n\npub const SYMBOL_SET_ENCODING: [&str; 256] = [\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n", "file_path": "src/font/encoding.rs", "rank": 84, "score": 28365.163571288438 }, { "content": " \"hungarumlaut\",\n\n \"ogonek\",\n\n \"caron\",\n\n];\n\n\n\npub const STANDARD_ENCODING: [&str; 256] = [\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n", "file_path": "src/font/encoding.rs", "rank": 85, "score": 28365.103293801327 }, { "content": " \"Ucircumflexsmall\",\n\n \"Udieresissmall\",\n\n \"Yacutesmall\",\n\n \"Thornsmall\",\n\n \"Ydieresissmall\",\n\n];\n\n\n\npub const MAC_EXPERT_ENCODING: [&str; 256] = [\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n", "file_path": "src/font/encoding.rs", "rank": 86, "score": 28364.93441108826 }, { "content": "];\n\n\n\npub const ZAPF_DINGBATS_ENCODING: [&str; 256] = [\n\n \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\",\n\n \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"space\", \"a1\", \"a2\", \"a202\", \"a3\", \"a4\", \"a5\", \"a119\", \"a118\",\n\n \"a117\", \"a11\", \"a12\", \"a13\", \"a14\", \"a15\", \"a16\", \"a105\", \"a17\", \"a18\", \"a19\", \"a20\", \"a21\",\n\n \"a22\", \"a23\", \"a24\", \"a25\", \"a26\", \"a27\", \"a28\", \"a6\", \"a7\", \"a8\", \"a9\", \"a10\", \"a29\", \"a30\",\n\n \"a31\", \"a32\", \"a33\", \"a34\", \"a35\", \"a36\", \"a37\", \"a38\", \"a39\", \"a40\", \"a41\", \"a42\", \"a43\",\n\n \"a44\", \"a45\", \"a46\", \"a47\", \"a48\", \"a49\", \"a50\", \"a51\", \"a52\", \"a53\", \"a54\", \"a55\", \"a56\",\n\n \"a57\", \"a58\", \"a59\", \"a60\", \"a61\", \"a62\", \"a63\", \"a64\", \"a65\", \"a66\", \"a67\", \"a68\", \"a69\",\n\n \"a70\", \"a71\", \"a72\", \"a73\", \"a74\", \"a203\", \"a75\", \"a204\", \"a76\", \"a77\", \"a78\", \"a79\", \"a81\",\n\n \"a82\", \"a83\", \"a84\", \"a97\", \"a98\", \"a99\", \"a100\", \"\", \"a89\", \"a90\", \"a93\", \"a94\", \"a91\", \"a92\",\n\n \"a205\", \"a85\", \"a206\", \"a86\", \"a87\", \"a88\", \"a95\", \"a96\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\",\n\n \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"a101\", \"a102\", \"a103\", \"a104\", \"a106\", \"a107\", \"a108\",\n\n \"a112\", \"a111\", \"a110\", \"a109\", \"a120\", \"a121\", \"a122\", \"a123\", \"a124\", \"a125\", \"a126\", \"a127\",\n\n \"a128\", \"a129\", \"a130\", \"a131\", \"a132\", \"a133\", \"a134\", \"a135\", \"a136\", \"a137\", \"a138\", \"a139\",\n\n \"a140\", \"a141\", \"a142\", \"a143\", \"a144\", \"a145\", \"a146\", \"a147\", \"a148\", \"a149\", \"a150\", \"a151\",\n\n \"a152\", \"a153\", \"a154\", \"a155\", \"a156\", \"a157\", \"a158\", \"a159\", \"a160\", \"a161\", \"a163\", \"a164\",\n\n \"a196\", \"a165\", \"a192\", \"a166\", \"a167\", \"a168\", \"a169\", \"a170\", \"a171\", \"a172\", \"a173\", \"a162\",\n\n \"a174\", \"a175\", \"a176\", \"a177\", \"a178\", \"a179\", \"a193\", \"a180\", \"a199\", \"a181\", \"a200\", \"a182\",\n\n \"\", \"a201\", \"a183\", \"a184\", \"a197\", \"a185\", \"a194\", \"a198\", \"a186\", \"a195\", \"a187\", \"a188\",\n\n \"a189\", \"a190\", \"a191\", \"\",\n\n];\n", "file_path": "src/font/encoding.rs", "rank": 87, "score": 28362.45697535567 }, { "content": " \"Ccedillasmall\",\n\n \"Egravesmall\",\n\n \"Eacutesmall\",\n\n \"Ecircumflexsmall\",\n\n \"Edieresissmall\",\n\n \"Igravesmall\",\n\n \"Iacutesmall\",\n\n \"Icircumflexsmall\",\n\n \"Idieresissmall\",\n\n \"Ethsmall\",\n\n \"Ntildesmall\",\n\n \"Ogravesmall\",\n\n \"Oacutesmall\",\n\n \"Ocircumflexsmall\",\n\n \"Otildesmall\",\n\n \"Odieresissmall\",\n\n \"OEsmall\",\n\n \"Oslashsmall\",\n\n \"Ugravesmall\",\n\n \"Uacutesmall\",\n", "file_path": "src/font/encoding.rs", "rank": 88, "score": 28361.69574902983 }, { "content": " \"\",\n\n \"space\",\n\n \"exclamsmall\",\n\n \"Hungarumlautsmall\",\n\n \"\",\n\n \"dollaroldstyle\",\n\n \"dollarsuperior\",\n\n \"ampersandsmall\",\n\n \"Acutesmall\",\n\n \"parenleftsuperior\",\n\n \"parenrightsuperior\",\n\n \"twodotenleader\",\n\n \"onedotenleader\",\n\n \"comma\",\n\n \"hyphen\",\n\n \"period\",\n\n \"fraction\",\n\n \"zerooldstyle\",\n\n \"oneoldstyle\",\n\n \"twooldstyle\",\n", "file_path": "src/font/encoding.rs", "rank": 89, "score": 28361.69574902983 }, { "content": " \"threeoldstyle\",\n\n \"fouroldstyle\",\n\n \"fiveoldstyle\",\n\n \"sixoldstyle\",\n\n \"sevenoldstyle\",\n\n \"eightoldstyle\",\n\n \"nineoldstyle\",\n\n \"colon\",\n\n \"semicolon\",\n\n \"commasuperior\",\n\n \"threequartersemdash\",\n\n \"periodsuperior\",\n\n \"questionsmall\",\n\n \"\",\n\n \"asuperior\",\n\n \"bsuperior\",\n\n \"centsuperior\",\n\n \"dsuperior\",\n\n \"esuperior\",\n\n \"\",\n", "file_path": "src/font/encoding.rs", "rank": 90, "score": 28361.69574902983 }, { "content": " \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"exclamdownsmall\",\n\n \"centoldstyle\",\n\n \"Lslashsmall\",\n\n \"\",\n\n \"\",\n\n \"Scaronsmall\",\n\n \"Zcaronsmall\",\n\n \"Dieresissmall\",\n\n \"Brevesmall\",\n\n \"Caronsmall\",\n", "file_path": "src/font/encoding.rs", "rank": 91, "score": 28361.69574902983 }, { "content": " \"\",\n\n \"\",\n\n \"isuperior\",\n\n \"\",\n\n \"\",\n\n \"lsuperior\",\n\n \"msuperior\",\n\n \"nsuperior\",\n\n \"osuperior\",\n\n \"\",\n\n \"\",\n\n \"rsuperior\",\n\n \"ssuperior\",\n\n \"tsuperior\",\n\n \"\",\n\n \"ff\",\n\n \"fi\",\n\n \"fl\",\n\n \"ffi\",\n\n \"ffl\",\n", "file_path": "src/font/encoding.rs", "rank": 92, "score": 28361.69574902983 }, { "content": " \"parenleftinferior\",\n\n \"\",\n\n \"parenrightinferior\",\n\n \"Circumflexsmall\",\n\n \"hyphensuperior\",\n\n \"Gravesmall\",\n\n \"Asmall\",\n\n \"Bsmall\",\n\n \"Csmall\",\n\n \"Dsmall\",\n\n \"Esmall\",\n\n \"Fsmall\",\n\n \"Gsmall\",\n\n \"Hsmall\",\n\n \"Ismall\",\n\n \"Jsmall\",\n\n \"Ksmall\",\n\n \"Lsmall\",\n\n \"Msmall\",\n\n \"Nsmall\",\n", "file_path": "src/font/encoding.rs", "rank": 93, "score": 28361.69574902983 }, { "content": " \"\",\n\n \"Dotaccentsmall\",\n\n \"\",\n\n \"\",\n\n \"Macronsmall\",\n\n \"\",\n\n \"\",\n\n \"figuredash\",\n\n \"hypheninferior\",\n\n \"\",\n\n \"\",\n\n \"Ogoneksmall\",\n\n \"Ringsmall\",\n\n \"Cedillasmall\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"onequarter\",\n\n \"onehalf\",\n\n \"threequarters\",\n", "file_path": "src/font/encoding.rs", "rank": 94, "score": 28361.69574902983 }, { "content": " \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n", "file_path": "src/font/encoding.rs", "rank": 95, "score": 28361.69574902983 }, { "content": " \"Osmall\",\n\n \"Psmall\",\n\n \"Qsmall\",\n\n \"Rsmall\",\n\n \"Ssmall\",\n\n \"Tsmall\",\n\n \"Usmall\",\n\n \"Vsmall\",\n\n \"Wsmall\",\n\n \"Xsmall\",\n\n \"Ysmall\",\n\n \"Zsmall\",\n\n \"colonmonetary\",\n\n \"onefitted\",\n\n \"rupiah\",\n\n \"Tildesmall\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n", "file_path": "src/font/encoding.rs", "rank": 96, "score": 28361.69574902983 }, { "content": " \"oneinferior\",\n\n \"twoinferior\",\n\n \"threeinferior\",\n\n \"fourinferior\",\n\n \"fiveinferior\",\n\n \"sixinferior\",\n\n \"seveninferior\",\n\n \"eightinferior\",\n\n \"nineinferior\",\n\n \"centinferior\",\n\n \"dollarinferior\",\n\n \"periodinferior\",\n\n \"commainferior\",\n\n \"Agravesmall\",\n\n \"Aacutesmall\",\n\n \"Acircumflexsmall\",\n\n \"Atildesmall\",\n\n \"Adieresissmall\",\n\n \"Aringsmall\",\n\n \"AEsmall\",\n", "file_path": "src/font/encoding.rs", "rank": 97, "score": 28361.69574902983 }, { "content": " \"questiondownsmall\",\n\n \"oneeighth\",\n\n \"threeeighths\",\n\n \"fiveeighths\",\n\n \"seveneighths\",\n\n \"onethird\",\n\n \"twothirds\",\n\n \"\",\n\n \"\",\n\n \"zerosuperior\",\n\n \"onesuperior\",\n\n \"twosuperior\",\n\n \"threesuperior\",\n\n \"foursuperior\",\n\n \"fivesuperior\",\n\n \"sixsuperior\",\n\n \"sevensuperior\",\n\n \"eightsuperior\",\n\n \"ninesuperior\",\n\n \"zeroinferior\",\n", "file_path": "src/font/encoding.rs", "rank": 98, "score": 28361.69574902983 }, { "content": " \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n\n \"\",\n", "file_path": "src/font/encoding.rs", "rank": 99, "score": 28361.69574902983 } ]
Rust
src/interpreter/stdlib/special_forms/_match.rs
emirayka/nia_interpreter_core
8b212e44fdede3d49cd75eddb255091a1d67b0e5
use crate::interpreter::environment::EnvironmentId; use crate::interpreter::error::Error; use crate::interpreter::interpreter::Interpreter; use crate::interpreter::value::Value; use crate::interpreter::library; pub fn _match( interpreter: &mut Interpreter, environment_id: EnvironmentId, values: Vec<Value>, ) -> Result<Value, Error> { if values.len() < 1 { return Error::invalid_argument_count_error("").into(); } let mut values = values; let expression = values.remove(0); let clauses = values; let value_to_match = interpreter .execute_value(environment_id, expression) .map_err(|err| { Error::generic_execution_error_caused( "Cannot evaluate value in the `match' special form.", err, ) })?; let mut child_environment_id = None; let mut code_to_execute = None; for clause in clauses { let cons_id = library::read_as_cons_id(clause)?; let mut clause = interpreter.list_to_vec(cons_id)?; let pattern = clause.remove(0); let evaluated_pattern = interpreter.execute_value(environment_id, pattern)?; match library::match_value( interpreter, environment_id, evaluated_pattern, value_to_match, ) { Ok(environment_id) => { child_environment_id = Some(environment_id); let forms = clause; code_to_execute = Some(forms); break; } _ => {} } } match child_environment_id { Some(environment_id) => library::evaluate_forms_return_last( interpreter, environment_id, &code_to_execute.unwrap(), ), _ => Error::generic_execution_error("").into(), } } #[cfg(test)] mod tests { use super::*; #[allow(unused_imports)] use nia_basic_assertions::*; #[allow(unused_imports)] use crate::utils; #[test] fn executes_forms() { let mut interpreter = Interpreter::new(); let pairs = vec![ ("(match () ('()))", interpreter.intern_nil_symbol_value()), ("(match () ('() 1))", Value::Integer(1)), ("(match () ('() 1 2))", Value::Integer(2)), ("(match () ('() 1 2 3))", Value::Integer(3)), ]; utils::assert_results_are_correct(&mut interpreter, pairs); } #[test] fn able_to_destructurize_lists() { let mut interpreter = Interpreter::new(); let pairs = vec![ ("(match '() ('() nil))", "nil"), ("(match '(1) ('(a) (list:new a)))", "(list:new 1)"), ("(match '(1 2) ('(a b) (list:new a b)))", "(list:new 1 2)"), ( "(match '(1 2 3) ('(a b c) (list:new a b c)))", "(list:new 1 2 3)", ), ]; utils::assert_results_are_equal(&mut interpreter, pairs); } #[test] fn able_to_destructurize_inner_lists() { let mut interpreter = Interpreter::new(); let pairs = vec![ ("(match '(1) ('(a) (list:new a)))", "(list:new 1)"), ("(match '((1)) ('((a)) (list:new a)))", "(list:new 1)"), ("(match '(((1))) ('(((a))) (list:new a)))", "(list:new 1)"), ("(match '(1) ('(a) (list:new a)))", "(list:new 1)"), ( "(match '((1) 2) ('((a) b) (list:new a b)))", "(list:new 1 2)", ), ( "(match '(((1) 2) 3) ('(((a) b) c) (list:new a b c)))", "(list:new 1 2 3)", ), ]; utils::assert_results_are_equal(&mut interpreter, pairs); } #[test] fn able_to_use_different_patterns() { let mut interpreter = Interpreter::new(); let pairs = vec![ ( "(match '() (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "()", ), ( "(match '(1) (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "(list:new 1)", ), ( "(match '(1 2) (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "(list:new 1 2)", ), ( "(match '(1 2 3) (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "(list:new 1 2 3)", ), ]; utils::assert_results_are_equal(&mut interpreter, pairs); } #[test] fn able_to_destructurize_objects() { let mut interpreter = Interpreter::new(); let pairs = vec![ ( "(match {:a 1 :b 2 :c 3} (#{:a} (list:new a)))", "(list:new 1)", ), ( "(match {:a 1 :b 2 :c 3} (#{:a :b} (list:new a b)))", "(list:new 1 2)", ), ( "(match {:a 1 :b 2 :c 3} (#{:a :b :c} (list:new a b c)))", "(list:new 1 2 3)", ), ]; utils::assert_results_are_equal(&mut interpreter, pairs); } }
use crate::interpreter::environment::EnvironmentId; use crate::interpreter::error::Error; use crate::interpreter::interpreter::Interpreter; use crate::interpreter::value::Value; use crate::interpreter::library; pub fn _match( interpreter: &mut Interpreter, environment_id: EnvironmentId, values: Vec<Value>, ) -> Result<Value, Error> { if values.len() < 1 { return Error::invalid_argument_count_error("").into(); } let mut values = values; let expression = values.remove(0); let clauses = values; let value_to_match = interpreter .execute_value(environment_id, expression) .map_err(|err| { Error::generic_execution_error_caused( "Cannot evaluate value in the `match' special form.", err, ) })?; let mut child_environment_id = None; let mut code_to_execute = None; for clause in clauses { let cons_id = library::read_as_cons_id(clause)?; let mut clause = interpreter.list_to_vec(cons_id)?; let pattern = clause.remove(0); let evaluated_pattern = interpreter.execute_value(environment_id, pattern)?; match library::match_value( interpreter, environment_id, evaluated_pattern, value_to_match, ) { Ok(environment_id) => { child_environment_id = Some(environment_id); let forms = clause; code_to_execute = Some(forms); break; } _ => {} } } match child_environment_id { Some(environment_id) => library::evaluate_forms_return_last( interpreter, environment_id, &code_to_execute.unwrap(), ), _ => Error::generic_execution_error("").into(), } } #[cfg(test)] mod tests { use super::*; #[allow(unused_imports)] use nia_basic_assertions::*; #[allow(unused_imports)] use crate::utils; #[test] fn executes_forms() { let mut interpreter = Interpreter::new(); let pairs = vec![ ("(match () ('()))", interpreter.intern_nil_symbol_value()), ("(match () ('() 1))", Value::Integer(1)), ("(match () ('() 1 2))", Value::Integer(2)), ("(match () ('() 1 2 3))", Value::Integer(3)), ]; utils::assert_results_are_correct(&mut interpreter, pairs); } #[test] fn able_to_destructurize_lists() { let mut interpreter = Interpreter::new(); let pairs = vec![ ("(match '() ('() nil))", "nil"), ("(match '(1) ('(a) (list:new a)))", "(list:new 1)"), ("(match '(1 2) ('(a b) (list:new a b)))", "(list:new 1 2)"), ( "(match '(1 2 3) ('(a b c) (list:new a b c)))", "(list:new 1 2 3)", ), ]; utils::assert_results_are_equal(&mut interpreter, pairs); } #[test] fn able_to_destructurize_inner_lists() { let mut interpreter = Interpreter::new(); let pairs = vec![ ("(match '(1) ('(a) (list:new a)))", "(list:new 1)"), ("(match '((1)) ('((a)) (list:new a)))", "(list:new 1)"), ("(match '(((1))) ('(((a))) (list:new a)))", "(list:new 1)"), ("(match '(1) ('(a) (list:new a)))", "(list:new 1)"), ( "(match '((1) 2) ('((a) b) (list:new a b)))", "(list:new 1 2)", ), ( "(match '(((1) 2) 3) ('(((a) b) c) (list:new a b c)))", "(list:new 1 2 3)", ), ]; utils::assert_results_are_equal(&mut interpreter, pairs); } #[test] fn able_to_use_different_patterns() { let mut in
#[test] fn able_to_destructurize_objects() { let mut interpreter = Interpreter::new(); let pairs = vec![ ( "(match {:a 1 :b 2 :c 3} (#{:a} (list:new a)))", "(list:new 1)", ), ( "(match {:a 1 :b 2 :c 3} (#{:a :b} (list:new a b)))", "(list:new 1 2)", ), ( "(match {:a 1 :b 2 :c 3} (#{:a :b :c} (list:new a b c)))", "(list:new 1 2 3)", ), ]; utils::assert_results_are_equal(&mut interpreter, pairs); } }
terpreter = Interpreter::new(); let pairs = vec![ ( "(match '() (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "()", ), ( "(match '(1) (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "(list:new 1)", ), ( "(match '(1 2) (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "(list:new 1 2)", ), ( "(match '(1 2 3) (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "(list:new 1 2 3)", ), ]; utils::assert_results_are_equal(&mut interpreter, pairs); }
function_block-function_prefixed
[ { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let pairs: Vec<(&str, SpecialFormFunctionType)> = vec![\n\n (\"and\", and::and),\n\n (\"call-with-this\", call_with_this::call_with_this),\n\n (\"cond\", cond::cond),\n\n (\"quote\", quote::quote),\n\n (\"define-variable\", define_variable::define_variable),\n\n (\"define-function\", define_function::define_function),\n\n (\"doitems\", doitems::doitems),\n\n (\"dokeys\", dokeys::dokeys),\n\n (\"dolist\", dolist::dolist),\n\n (\"dotimes\", dotimes::dotimes),\n\n (\"dovalues\", dovalues::dovalues),\n\n (\"export\", export::export),\n\n (\"function\", function::function),\n\n (\"fset!\", fset::fset),\n\n (\"import\", import::import),\n\n (\"let\", _let::_let),\n\n (\"let*\", let_star::let_star),\n\n (\"flet\", flet::flet),\n", "file_path": "src/interpreter/stdlib/special_forms/mod.rs", "rank": 0, "score": 459174.002756724 }, { "content": "pub fn _super(interpreter: &Interpreter) -> Result<Value, Error> {\n\n match interpreter.get_this_object() {\n\n Some(object_id) => match interpreter.get_object_prototype(object_id)? {\n\n Some(proto_object_id) => Ok(proto_object_id.into()),\n\n None => {\n\n Error::generic_execution_error(\"Variable `super' is undefined.\")\n\n .into()\n\n },\n\n },\n\n None => {\n\n Error::generic_execution_error(\"Variable `super' is undefined.\")\n\n .into()\n\n },\n\n }\n\n}\n", "file_path": "src/interpreter/special_variables/_super.rs", "rank": 1, "score": 400734.2683581503 }, { "content": "pub fn infect_stdlib(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n special_forms::infect(interpreter)?;\n\n builtin_functions::infect(interpreter)?;\n\n builtin_objects::infect(interpreter)?;\n\n builtin_variables::infect(interpreter)?;\n\n\n\n core::infect(interpreter)?;\n\n\n\n Ok(())\n\n}\n\n\n\npub use builtin_variables::{\n\n DEFINED_ACTIONS_ROOT_VARIABLE_NAME, DEFINED_DEVICES_ROOT_VARIABLE_NAME,\n\n DEFINED_MODIFIERS_ROOT_VARIABLE_NAME, GLOBAL_MAP_ROOT_VARIABLE_NAME,\n\n PRIMITIVE_ACTIONS_VARIABLE_NAME,\n\n};\n", "file_path": "src/interpreter/stdlib/mod.rs", "rank": 3, "score": 372978.7731961109 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n lang::infect(interpreter)?;\n\n func::infect(interpreter)?;\n\n\n\n Ok(())\n\n}\n", "file_path": "src/interpreter/stdlib/core/mod.rs", "rank": 4, "score": 372978.7731961109 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let is_object_id = interpreter.make_object();\n\n\n\n let bindings: Vec<(&str, BuiltinFunctionType)> = vec![\n\n (\"int?\", int_question::int_question),\n\n (\"float?\", float_question::float_question),\n\n (\"boolean?\", boolean_question::boolean_question),\n\n (\"string?\", string_question::string_question),\n\n (\"symbol?\", symbol_question::symbol_question),\n\n (\"keyword?\", keyword_question::keyword_question),\n\n (\"cons?\", cons_question::cons_question),\n\n (\"object?\", object_question::object_question),\n\n (\"function?\", function_question::function_question),\n\n (\"false?\", false_question::false_question),\n\n (\"true?\", true_question::true_question),\n\n (\"nil?\", nil_question::nil_question),\n\n (\"number?\", number_question::number_question),\n\n (\"even?\", even_question::even_question),\n\n (\"odd?\", odd_question::odd_question),\n\n (\"negative?\", negative_question::negative_question),\n", "file_path": "src/interpreter/stdlib/builtin_objects/is/mod.rs", "rank": 5, "score": 368605.03736040374 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n define_empty_list(interpreter, DEFINED_DEVICES_ROOT_VARIABLE_NAME)?;\n\n define_empty_list(interpreter, DEFINED_MODIFIERS_ROOT_VARIABLE_NAME)?;\n\n define_empty_list(interpreter, DEFINED_ACTIONS_ROOT_VARIABLE_NAME)?;\n\n define_empty_list(interpreter, GLOBAL_MAP_ROOT_VARIABLE_NAME)?;\n\n\n\n define_empty_list(interpreter, PRIMITIVE_ACTIONS_VARIABLE_NAME)?;\n\n\n\n Ok(())\n\n}\n", "file_path": "src/interpreter/stdlib/builtin_variables/mod.rs", "rank": 6, "score": 368605.0373604038 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n alist::infect(interpreter)?;\n\n action::infect(interpreter)?;\n\n bit::infect(interpreter)?;\n\n cons::infect(interpreter)?;\n\n func::infect(interpreter)?;\n\n is::infect(interpreter)?;\n\n device::infect(interpreter)?;\n\n list::infect(interpreter)?;\n\n logic::infect(interpreter)?;\n\n math::infect(interpreter)?;\n\n object::infect(interpreter)?;\n\n rand::infect(interpreter)?;\n\n string::infect(interpreter)?;\n\n to::infect(interpreter)?;\n\n\n\n nia::infect(interpreter)?;\n\n\n\n Ok(())\n\n}\n", "file_path": "src/interpreter/stdlib/builtin_objects/mod.rs", "rank": 7, "score": 368605.03736040374 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let to_object_id = interpreter.make_object();\n\n let to_symbol_id = interpreter.intern_symbol_id(\"to\");\n\n\n\n let bindings: Vec<(&str, BuiltinFunctionType)> = vec![\n\n (\"boolean\", boolean::boolean),\n\n (\"float\", float::float),\n\n (\"int\", int::int),\n\n (\"keyword\", keyword::keyword),\n\n (\"string\", string::string),\n\n (\"symbol\", symbol::symbol),\n\n ];\n\n\n\n for (name, func) in bindings {\n\n library::infect_object_builtin_function(\n\n interpreter,\n\n to_object_id,\n\n name,\n\n func,\n\n )?;\n", "file_path": "src/interpreter/stdlib/builtin_objects/to/mod.rs", "rank": 8, "score": 368605.03736040374 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let pairs: Vec<(&str, BuiltinFunctionType)> = vec![\n\n (\"assert\", assert::assert),\n\n (\"string\", string::string),\n\n (\"flookup\", flookup::flookup),\n\n (\"gensym\", gensym::gensym),\n\n (\"intern\", intern::intern),\n\n (\"lookup\", lookup::lookup),\n\n (\"/\", div::div),\n\n (\"*\", mul::mul),\n\n (\"%\", rem::rem),\n\n (\"-\", sub::sub),\n\n (\"+\", sum::sum),\n\n (\"not\", not::not),\n\n (\"eq?\", eq_question::eq_question),\n\n (\"equal?\", equal_question::equal_question),\n\n (\"neq?\", neq_question::neq_question),\n\n (\"nequal?\", nequal_question::nequal_question),\n\n (\"=\", eq_question::eq_question),\n\n (\"==\", equal_question::equal_question),\n", "file_path": "src/interpreter/stdlib/builtin_functions/mod.rs", "rank": 9, "score": 368605.03736040374 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let string_object_id = interpreter.make_object();\n\n let string_symbol_id = interpreter.intern_symbol_id(\"string\");\n\n\n\n let bindings: Vec<(&str, BuiltinFunctionType)> = vec![\n\n (\"compare\", compare::compare),\n\n (\"concat\", concat::concat),\n\n (\"contains?\", contains::contains),\n\n (\"equal?\", equal_question::equal_question),\n\n (\"find\", find::find),\n\n (\"format\", format::format),\n\n (\"greater?\", greater_question::greater_question),\n\n (\"join\", join::join),\n\n (\"left\", left::left),\n\n (\"length\", length::length),\n\n (\"less?\", less_question::less_question),\n\n (\"lower\", lower::lower),\n\n (\"repeat\", repeat::repeat),\n\n (\"right\", right::right),\n\n (\"split\", split::split),\n", "file_path": "src/interpreter/stdlib/builtin_objects/string/mod.rs", "rank": 10, "score": 364378.11974898406 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let logic_object_id = interpreter.make_object();\n\n\n\n let bindings: Vec<(&str, BuiltinFunctionType)> = vec![\n\n (\"and\", and::and),\n\n (\"nand\", nand::nand),\n\n (\"nor\", nor::nor),\n\n (\"or\", or::or),\n\n (\"xor\", xor::xor),\n\n ];\n\n\n\n for (name, func) in bindings {\n\n library::infect_object_builtin_function(\n\n interpreter,\n\n logic_object_id,\n\n name,\n\n func,\n\n )?;\n\n }\n\n\n", "file_path": "src/interpreter/stdlib/builtin_objects/logic/mod.rs", "rank": 11, "score": 364378.11974898406 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let cons_object_id = interpreter.make_object();\n\n let cons_symbol_id = interpreter.intern_symbol_id(\"cons\");\n\n\n\n let bindings: Vec<(&str, BuiltinFunctionType)> = vec![\n\n (\"new\", new::new),\n\n (\"car\", car::car),\n\n (\"cdr\", cdr::cdr),\n\n (\"set-car!\", set_car_mark::set_car_mark),\n\n (\"set-cdr!\", set_cdr_mark::set_cdr_mark),\n\n ];\n\n\n\n for (name, func) in bindings {\n\n library::infect_object_builtin_function(\n\n interpreter,\n\n cons_object_id,\n\n name,\n\n func,\n\n )?;\n\n }\n\n\n\n interpreter.define_variable(\n\n interpreter.get_root_environment_id(),\n\n cons_symbol_id,\n\n Value::Object(cons_object_id),\n\n )?;\n\n\n\n Ok(())\n\n}\n", "file_path": "src/interpreter/stdlib/builtin_objects/cons/mod.rs", "rank": 12, "score": 364378.11974898406 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let rand_object_id = interpreter.make_object();\n\n\n\n let bindings: Vec<(&str, BuiltinFunctionType)> =\n\n vec![(\"int\", int::int), (\"float\", float::float)];\n\n\n\n for (name, func) in bindings {\n\n library::infect_object_builtin_function(\n\n interpreter,\n\n rand_object_id,\n\n name,\n\n func,\n\n )?;\n\n }\n\n\n\n let rand_symbol_id = interpreter.intern_symbol_id(\"rand\");\n\n\n\n interpreter.define_variable(\n\n interpreter.get_root_environment_id(),\n\n rand_symbol_id,\n\n Value::Object(rand_object_id),\n\n )?;\n\n\n\n Ok(())\n\n}\n", "file_path": "src/interpreter/stdlib/builtin_objects/rand/mod.rs", "rank": 13, "score": 364378.11974898406 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let alist_object_id = interpreter.make_object();\n\n let alist_symbol_id = interpreter.intern_symbol_id(\"alist\");\n\n\n\n let bindings: Vec<(&str, BuiltinFunctionType)> = vec![\n\n (\"acons\", acons::acons),\n\n (\"acons!\", acons_mark::acons_mark),\n\n (\"has-key?\", has_key_question::has_key_question),\n\n (\"has-value?\", has_value_question::has_value_question),\n\n (\"lookup\", lookup::lookup),\n\n (\"new\", new::new),\n\n ];\n\n\n\n for (name, func) in bindings {\n\n library::infect_object_builtin_function(\n\n interpreter,\n\n alist_object_id,\n\n name,\n\n func,\n\n )?;\n", "file_path": "src/interpreter/stdlib/builtin_objects/alist/mod.rs", "rank": 14, "score": 364378.11974898406 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let bit_object_id = interpreter.make_object();\n\n let bit_symbol_id = interpreter.intern_symbol_id(\"bit\");\n\n\n\n let bindings: Vec<(&str, BuiltinFunctionType)> = vec![\n\n (\"and\", and::and),\n\n (\"clear\", clear::clear),\n\n (\"flip\", flip::flip),\n\n (\"not\", not::not),\n\n (\"or\", or::or),\n\n (\"set\", set::set),\n\n (\"shift-left\", shift_left::shift_left),\n\n (\"shift-right\", shift_right::shift_right),\n\n (\"test\", test::test),\n\n (\"xor\", xor::xor),\n\n ];\n\n\n\n for (name, func) in bindings {\n\n library::infect_object_builtin_function(\n\n interpreter,\n", "file_path": "src/interpreter/stdlib/builtin_objects/bit/mod.rs", "rank": 15, "score": 364378.11974898406 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let action_object_id = interpreter.make_object();\n\n let action_symbol_id = interpreter.intern_symbol_id(\"action\");\n\n\n\n let bindings: Vec<(&str, BuiltinFunctionType)> = vec![\n\n (\"send-key-press\", send_key_press::send_key_press),\n\n (\"send-key-click\", send_key_click::send_key_click),\n\n (\"send-key-release\", send_key_release::send_key_release),\n\n (\n\n \"send-mouse-button-press\",\n\n send_mouse_button_press::send_mouse_button_press,\n\n ),\n\n (\n\n \"send-mouse-button-click\",\n\n send_mouse_button_click::send_mouse_button_click,\n\n ),\n\n (\n\n \"send-mouse-button-release\",\n\n send_mouse_button_release::send_mouse_button_release,\n\n ),\n", "file_path": "src/interpreter/stdlib/builtin_objects/action/mod.rs", "rank": 16, "score": 364378.11974898406 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let device_object_id = interpreter.make_object();\n\n\n\n let bindings: Vec<(&str, BuiltinFunctionType)> = vec![\n\n (\n\n \"define-global-mapping\",\n\n define_global_mapping::define_global_mapping,\n\n ),\n\n (\"define-modifier\", define_modifier::define_modifier),\n\n (\"define\", define::define),\n\n (\"start-listening\", start_listening::start_listening),\n\n (\"stop-listening\", stop_listening::stop_listening),\n\n (\n\n \"is-listening?\",\n\n is_listening_question::is_listening_question,\n\n ),\n\n ];\n\n\n\n for (name, func) in bindings {\n\n library::infect_object_builtin_function(\n", "file_path": "src/interpreter/stdlib/builtin_objects/device/mod.rs", "rank": 17, "score": 364378.11974898406 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let object_object_id = interpreter.make_object();\n\n\n\n let funcs: Vec<(&str, BuiltinFunctionType)> = vec![\n\n (\n\n \"define-property!\",\n\n define_property_mark::define_property_mark,\n\n ),\n\n (\n\n \"delete-property!\",\n\n delete_property_mark::delete_property_mark,\n\n ),\n\n (\"freeze!\", freeze_mark::freeze_mark),\n\n (\"make\", make::make),\n\n (\"get\", get::get),\n\n (\n\n \"get-property-descriptor\",\n\n get_property_descriptor::get_property_descriptor,\n\n ),\n\n (\"get-proto\", get_proto::get_proto),\n", "file_path": "src/interpreter/stdlib/builtin_objects/object/mod.rs", "rank": 18, "score": 364378.11974898406 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let list_object_id = interpreter.make_object();\n\n let list_symbol_id = interpreter.intern_symbol_id(\"list\");\n\n\n\n let pairs: Vec<(&str, BuiltinFunctionType)> = vec![\n\n (\"all?\", all_question::all_question),\n\n (\"any?\", any_question::any_question),\n\n (\"append\", append::append),\n\n (\"aperture\", aperture::aperture),\n\n (\"contains?\", contains_question::contains),\n\n (\"filter\", filter::filter),\n\n (\"fold\", fold::fold),\n\n (\"foldl\", foldl::foldl),\n\n (\"head\", head::head),\n\n (\"init\", init::init),\n\n (\"join\", join::join),\n\n (\"last\", last::last),\n\n (\"length\", length::length),\n\n (\"map\", map::map),\n\n (\"new\", new::new),\n", "file_path": "src/interpreter/stdlib/builtin_objects/list/mod.rs", "rank": 19, "score": 364378.11974898406 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let math_symbol_id = interpreter.intern_symbol_id(\"math\");\n\n let math_object_id = interpreter.make_object();\n\n\n\n let bindings: Vec<(&str, BuiltinFunctionType)> = vec![\n\n (\"abs\", abs::abs),\n\n (\"ceil\", ceil::ceil),\n\n (\"floor\", floor::floor),\n\n (\"max\", max::max),\n\n (\"min\", min::min),\n\n (\"pow\", pow::pow),\n\n (\"round\", round::round),\n\n ];\n\n\n\n for (name, func) in bindings {\n\n library::infect_object_builtin_function(\n\n interpreter,\n\n math_object_id,\n\n name,\n\n func,\n", "file_path": "src/interpreter/stdlib/builtin_objects/math/mod.rs", "rank": 20, "score": 364378.11974898406 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let func_object_id = interpreter.make_object();\n\n\n\n let bindings: Vec<(&str, BuiltinFunctionType)> = vec![\n\n (\"always\", always::always),\n\n (\"apply\", apply::apply),\n\n (\"call\", call::call),\n\n (\"combine\", combine::combine),\n\n (\"id\", id::id),\n\n (\"f\", f::f),\n\n (\"t\", t::t),\n\n ];\n\n\n\n for (name, func) in bindings {\n\n library::infect_object_builtin_function(\n\n interpreter,\n\n func_object_id,\n\n name,\n\n func,\n\n )?;\n", "file_path": "src/interpreter/stdlib/builtin_objects/func/mod.rs", "rank": 21, "score": 364378.11974898406 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let nia_symbol_id = interpreter.intern_symbol_id(\"nia\");\n\n let nia_object_id = interpreter.make_object();\n\n\n\n let bindings: Vec<(&str, BuiltinFunctionType)> = vec![(\"quit\", quit::quit)];\n\n\n\n for (name, func) in bindings {\n\n library::infect_object_builtin_function(\n\n interpreter,\n\n nia_object_id,\n\n name,\n\n func,\n\n )?;\n\n }\n\n\n\n interpreter.define_variable(\n\n interpreter.get_root_environment_id(),\n\n nia_symbol_id,\n\n Value::Object(nia_object_id),\n\n )?;\n\n\n\n Ok(())\n\n}\n", "file_path": "src/interpreter/stdlib/builtin_objects/nia/mod.rs", "rank": 22, "score": 364378.11974898406 }, { "content": "pub fn evaluate_special_form_invocation(\n\n interpreter: &mut Interpreter,\n\n execution_environment: EnvironmentId,\n\n special_form: &SpecialFormFunction,\n\n arguments: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n (special_form.get_func())(interpreter, execution_environment, arguments)\n\n}\n", "file_path": "src/interpreter/evaluator/evaluate_special_form_invocation.rs", "rank": 23, "score": 359738.2035209084 }, { "content": "pub fn evaluate_forms_return_last(\n\n interpreter: &mut Interpreter,\n\n execution_environment: EnvironmentId,\n\n forms: &Vec<Value>,\n\n) -> Result<Value, Error> {\n\n let mut last_result = None;\n\n\n\n for form in forms {\n\n let result = interpreter.execute_value(execution_environment, *form)?;\n\n last_result = Some(result);\n\n }\n\n\n\n match last_result {\n\n Some(value) => Ok(value),\n\n None => Ok(interpreter.intern_nil_symbol_value()),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "src/interpreter/library/evaluate/evaluate_forms_return_last.rs", "rank": 24, "score": 356999.70587084664 }, { "content": "pub fn alist_new(interpreter: &mut Interpreter) -> Result<Value, Error> {\n\n let new_alist = interpreter.intern_nil_symbol_value();\n\n\n\n Ok(new_alist)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n\n\n\n #[test]\n\n fn returns_new_alist() {\n\n let mut interpreter = Interpreter::new();\n\n\n\n let expected = interpreter.intern_nil_symbol_value();\n\n let result = alist_new(&mut interpreter).unwrap();\n\n\n\n utils::assert_deep_equal(&mut interpreter, expected, result);\n\n }\n\n}\n", "file_path": "src/interpreter/library/alist/alist_new.rs", "rank": 25, "score": 354847.60092352156 }, { "content": "pub fn _this(interpreter: &Interpreter) -> Result<Value, Error> {\n\n match interpreter.get_this_object() {\n\n Some(object_id) => Ok(object_id.into()),\n\n None => Error::generic_execution_error(\"Variable `this' is undefined.\")\n\n .into(),\n\n }\n\n}\n", "file_path": "src/interpreter/special_variables/_this.rs", "rank": 26, "score": 350219.63191702036 }, { "content": "pub fn _let(\n\n interpreter: &mut Interpreter,\n\n environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() == 0 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form let must have at least one argument.\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n\n\n let definitions = library::read_as_let_definitions(\n\n interpreter,\n\n values.remove(0),\n\n ).map_err(|_| Error::invalid_argument_error(\n\n \"The first argument of special form `let' must be a list of definitions: symbol, or 2-element lists.\"\n\n ))?;\n", "file_path": "src/interpreter/stdlib/special_forms/_let.rs", "rank": 27, "score": 348030.67328059283 }, { "content": "pub fn assert_is_nil(interpreter: &mut Interpreter, param: Value) {\n\n nia_assert(match param {\n\n Value::Symbol(symbol_id) => {\n\n interpreter.symbol_is_nil(symbol_id).unwrap()\n\n }\n\n _ => false,\n\n });\n\n}\n\n\n", "file_path": "src/utils/assertion.rs", "rank": 28, "score": 343962.1164246523 }, { "content": "pub fn let_star(\n\n interpreter: &mut Interpreter,\n\n environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() == 0 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `let*' must have at least one argument.\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n\n\n let definitions =\n\n library::read_as_let_definitions(interpreter, values.remove(0))\n\n .map_err(|_| {\n\n Error::invalid_argument_error(\"Invalid `let*' definitions.\")\n\n })?;\n\n\n", "file_path": "src/interpreter/stdlib/special_forms/let_star.rs", "rank": 29, "score": 338247.4774950959 }, { "content": "pub fn set_definitions(\n\n interpreter: &mut Interpreter,\n\n definition_value_execution_environment: EnvironmentId,\n\n definition_setting_environment: EnvironmentId,\n\n definitions: Vec<Value>,\n\n) -> Result<(), Error> {\n\n for definition in definitions {\n\n set_definition(\n\n interpreter,\n\n definition_value_execution_environment,\n\n definition_setting_environment,\n\n definition,\n\n )?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/interpreter/stdlib/special_forms/_let.rs", "rank": 30, "score": 330978.38410402904 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let functions: Vec<fn(&mut Interpreter) -> Result<(), Error>> = vec![\n\n defv::infect,\n\n defc::infect,\n\n defn::infect,\n\n defm::infect,\n\n defon::infect,\n\n _fn::infect,\n\n _if::infect,\n\n when::infect,\n\n unless::infect,\n\n inc_mark::infect,\n\n dec_mark::infect,\n\n // cr::infect,\n\n empty::infect,\n\n ];\n\n\n\n for function in functions {\n\n function(interpreter)?;\n\n }\n", "file_path": "src/interpreter/stdlib/core/lang.rs", "rank": 31, "score": 326259.6156743701 }, { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let functions: Vec<fn(&mut Interpreter) -> Result<(), Error>> = vec![\n\n func__bind::infect,\n\n func__curry::infect,\n\n func__curry_star::infect,\n\n ];\n\n\n\n for function in functions {\n\n function(interpreter)?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\n#[allow(non_snake_case)]\n\nmod func__bind {\n\n use super::*;\n\n\n\n pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n interpreter.execute_in_root_environment(\n", "file_path": "src/interpreter/stdlib/core/func.rs", "rank": 32, "score": 326259.61567437014 }, { "content": "pub fn collect_garbage(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let gc = GarbageCollector::new(interpreter);\n\n\n\n gc.collect(interpreter)?;\n\n\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n use std::convert::TryInto;\n\n\n\n use crate::interpreter::environment::EnvironmentId;\n\n use crate::interpreter::value::BuiltinFunction;\n\n use crate::interpreter::value::Function;\n", "file_path": "src/interpreter/garbage_collector/garbage_collector.rs", "rank": 33, "score": 319278.6742812614 }, { "content": "pub fn evaluate_s_expression(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n s_expression: ConsId,\n\n) -> Result<Value, Error> {\n\n if interpreter.is_overflow() {\n\n return Error::stack_overflow_error().into();\n\n }\n\n\n\n // 1) evaluate first symbol\n\n let car = interpreter.get_car(s_expression)?;\n\n\n\n match car {\n\n Value::Symbol(function_symbol_id) => {\n\n let function_value = match interpreter.lookup_function(\n\n environment_id,\n\n function_symbol_id,\n\n )? {\n\n Some(function_value) => function_value,\n\n None => {\n", "file_path": "src/interpreter/evaluator/evaluate_s_expression.rs", "rank": 34, "score": 316351.8622267059 }, { "content": "pub fn evaluate_value(\n\n interpreter: &mut Interpreter,\n\n environment: EnvironmentId,\n\n value: Value,\n\n) -> Result<Value, Error> {\n\n match value {\n\n Value::Symbol(symbol_name) => {\n\n evaluate_symbol(interpreter, environment, symbol_name)\n\n },\n\n Value::Cons(cons) => {\n\n evaluate_s_expression(interpreter, environment, cons)\n\n },\n\n _ => Ok(value),\n\n }\n\n}\n", "file_path": "src/interpreter/evaluator/evaluate_value.rs", "rank": 35, "score": 315263.66502318415 }, { "content": "pub fn evaluate_values(\n\n interpreter: &mut Interpreter,\n\n execution_environment: EnvironmentId,\n\n code: &Vec<Value>,\n\n) -> Result<Option<Value>, Error> {\n\n let mut last_result = None;\n\n\n\n for value in code {\n\n last_result =\n\n evaluate_value(interpreter, execution_environment, *value)\n\n .map(|v| Some(v))?;\n\n }\n\n\n\n Ok(last_result)\n\n}\n", "file_path": "src/interpreter/evaluator/evaluate_values.rs", "rank": 36, "score": 315263.66502318415 }, { "content": "pub fn evaluate_forms(\n\n interpreter: &mut Interpreter,\n\n execution_environment: EnvironmentId,\n\n forms: Vec<Value>,\n\n) -> Result<Vec<Value>, Error> {\n\n let mut results = Vec::new();\n\n\n\n for form in forms {\n\n let result = interpreter.execute_value(execution_environment, form)?;\n\n\n\n results.push(result);\n\n }\n\n\n\n Ok(results)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n", "file_path": "src/interpreter/library/evaluate/evaluate_forms.rs", "rank": 37, "score": 311548.06830346276 }, { "content": "pub fn match_value(\n\n interpreter: &mut Interpreter,\n\n parent_environment: EnvironmentId,\n\n binding: Value,\n\n value: Value,\n\n) -> Result<EnvironmentId, Error> {\n\n let environment_id = interpreter.make_environment(parent_environment)?;\n\n\n\n let result =\n\n match_value_recursive(interpreter, environment_id, binding, value);\n\n\n\n match result {\n\n Ok(_) => Ok(environment_id),\n\n Err(err) => {\n\n interpreter.remove_environment(environment_id)?;\n\n Err(err)\n\n },\n\n }\n\n}\n\n\n", "file_path": "src/interpreter/library/general/match_value.rs", "rank": 38, "score": 306282.8137931683 }, { "content": "pub fn evaluate_s_expression_keyword(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n keyword_id: KeywordId,\n\n cons_id: ConsId,\n\n) -> Result<Value, Error> {\n\n let keyword_name = interpreter\n\n .get_keyword(keyword_id)\n\n .map(|keyword| keyword.get_name().clone())?;\n\n\n\n let property_symbol_id = interpreter.intern_symbol_id(&keyword_name);\n\n let arguments = extract_arguments(interpreter, cons_id)?;\n\n\n\n match arguments.len() {\n\n 1 => evaluate_s_expression_keyword_get(\n\n interpreter,\n\n environment_id,\n\n property_symbol_id,\n\n arguments,\n\n ),\n", "file_path": "src/interpreter/evaluator/evaluate_s_expression_keyword_invocation.rs", "rank": 39, "score": 305671.409238458 }, { "content": "fn evaluate_values(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Vec<Value>, Error> {\n\n let values = values;\n\n let mut evaluated_values = Vec::new();\n\n\n\n for value in values {\n\n let evaluated_value = match value {\n\n // todo: make sure that there is no evaluation of s-expression\n\n // it should be parsing of `object:make' invocation\n\n Value::Cons(_) => {\n\n let evaluated_value = interpreter.execute_value(environment_id, value)?;\n\n\n\n if let Value::Object(_) = evaluated_value {\n\n evaluated_value\n\n } else {\n\n return Error::invalid_argument_error(\n\n \"Special form `export' takes as arguments only s-expressions that evaluates to objects, symbols and strings.\"\n", "file_path": "src/interpreter/stdlib/special_forms/export.rs", "rank": 40, "score": 304395.5268972068 }, { "content": "fn evaluate_values(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Vec<Value>, Error> {\n\n let values = values;\n\n let mut evaluated_values = Vec::new();\n\n\n\n for value in values {\n\n let evaluated_value = match value {\n\n // todo: make sure that there is no evaluation of s-expression\n\n // it should be parsing of `object:make' invocation\n\n Value::Cons(_) => {\n\n let evaluated_value = interpreter.execute_value(environment_id, value)?;\n\n\n\n if let Value::Object(_) = evaluated_value {\n\n evaluated_value\n\n } else {\n\n return Error::invalid_argument_error(\n\n \"Special form `import' takes as arguments only s-expressions that evaluates to objects, symbols and strings.\"\n", "file_path": "src/interpreter/stdlib/special_forms/import.rs", "rank": 41, "score": 304395.5268972067 }, { "content": "pub fn match_value_recursive(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n binding: Value,\n\n value: Value,\n\n) -> Result<(), Error> {\n\n match binding {\n\n Value::Symbol(symbol_id) => {\n\n match library::check_symbol_is_assignable(interpreter, symbol_id) {\n\n Ok(_) => {},\n\n Err(err) => {\n\n if library::deep_equal(interpreter, binding, value)? {\n\n return Ok(());\n\n } else {\n\n return Err(err);\n\n }\n\n },\n\n };\n\n\n\n interpreter.define_variable(environment_id, symbol_id, value)\n", "file_path": "src/interpreter/library/general/match_value.rs", "rank": 42, "score": 302586.2974704265 }, { "content": "pub fn evaluate_s_expression_function_invocation(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n function_symbol_id: SymbolId,\n\n function_id: FunctionId,\n\n cons_id: ConsId,\n\n) -> Result<Value, Error> {\n\n let function = interpreter\n\n .get_function(function_id)\n\n .map(|function| function.clone())?;\n\n\n\n match function {\n\n Function::Builtin(builtin_function) => {\n\n // 2) evaluate arguments\n\n let arguments = extract_arguments(interpreter, cons_id)?;\n\n\n\n let evaluated_arguments = crate::library::evaluate_forms(\n\n interpreter,\n\n environment_id,\n\n arguments,\n", "file_path": "src/interpreter/evaluator/evaluate_s_expression_function_invocation.rs", "rank": 43, "score": 302326.20071359776 }, { "content": "pub fn check_value_is_integer(value: Value) -> Result<(), Error> {\n\n match value {\n\n Value::Integer(_) => Ok(()),\n\n _ => Error::invalid_argument_error(\"Expected cons\").into(),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n\n\n\n use crate::Interpreter;\n\n #[test]\n\n fn returns_nothing_when_an_integer_was_passed() {\n", "file_path": "src/interpreter/library/check/check_value_is_integer.rs", "rank": 44, "score": 301735.2716262264 }, { "content": "pub fn check_value_is_function(value: Value) -> Result<(), Error> {\n\n match value {\n\n Value::Function(_) => Ok(()),\n\n _ => Error::invalid_argument_error(\"Expected function.\").into(),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n\n\n\n use crate::FunctionId;\n\n use crate::Interpreter;\n\n\n", "file_path": "src/interpreter/library/check/check_value_is_function.rs", "rank": 45, "score": 301735.2716262264 }, { "content": "pub fn check_value_is_object(value: Value) -> Result<(), Error> {\n\n match value {\n\n Value::Object(_) => Ok(()),\n\n _ => Error::invalid_argument_error(\"Expected object\").into(),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n\n\n\n use crate::Interpreter;\n\n\n\n #[test]\n", "file_path": "src/interpreter/library/check/check_value_is_object.rs", "rank": 46, "score": 301735.2716262264 }, { "content": "pub fn check_value_is_string(value: Value) -> Result<(), Error> {\n\n match value {\n\n Value::String(_) => Ok(()),\n\n _ => Error::invalid_argument_error(\"Expected string\").into(),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n\n\n\n use crate::Interpreter;\n\n use crate::StringId;\n\n\n", "file_path": "src/interpreter/library/check/check_value_is_string.rs", "rank": 47, "score": 301735.2716262264 }, { "content": "pub fn check_value_is_symbol(value: Value) -> Result<(), Error> {\n\n match value {\n\n Value::Symbol(_) => Ok(()),\n\n _ => Error::invalid_argument_error(\"Expected symbol\").into(),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n\n\n\n use crate::Interpreter;\n\n use crate::StringId;\n\n\n", "file_path": "src/interpreter/library/check/check_value_is_symbol.rs", "rank": 48, "score": 301735.2716262264 }, { "content": "pub fn check_value_is_cons(value: Value) -> Result<(), Error> {\n\n match value {\n\n Value::Cons(_) => Ok(()),\n\n _ => Error::invalid_argument_error(\"Expected cons\").into(),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n\n\n\n use crate::ConsId;\n\n use crate::Interpreter;\n\n\n", "file_path": "src/interpreter/library/check/check_value_is_cons.rs", "rank": 49, "score": 301735.2716262264 }, { "content": "fn set_variable_to_nil(\n\n interpreter: &mut Interpreter,\n\n definition_setting_environment: EnvironmentId,\n\n symbol_id: SymbolId,\n\n) -> Result<(), Error> {\n\n library::check_symbol_is_assignable(interpreter, symbol_id)?;\n\n\n\n let nil = interpreter.intern_nil_symbol_value();\n\n\n\n interpreter.define_variable(definition_setting_environment, symbol_id, nil)\n\n}\n\n\n", "file_path": "src/interpreter/stdlib/special_forms/_let.rs", "rank": 50, "score": 300171.20805939374 }, { "content": "pub fn infect_special_form(\n\n interpreter: &mut Interpreter,\n\n name: &str,\n\n func: SpecialFormFunctionType,\n\n) -> Result<(), Error> {\n\n let name = interpreter.intern_symbol_id(name);\n\n\n\n let function = Function::SpecialForm(SpecialFormFunction::new(func));\n\n let function_id = interpreter.register_function(function);\n\n let function_value = Value::Function(function_id);\n\n\n\n let result = interpreter.define_function(\n\n interpreter.get_root_environment_id(),\n\n name,\n\n function_value,\n\n );\n\n\n\n match result {\n\n Ok(()) => Ok(()),\n\n Err(error) => Err(error),\n", "file_path": "src/interpreter/library/infect/infect_special_form.rs", "rank": 51, "score": 297812.69314909575 }, { "content": "pub fn _while(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() < 1 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `while' takes one argument at least.\",\n\n )\n\n .into();\n\n }\n\n\n\n let while_environment_id =\n\n make_while_environment(interpreter, environment_id)?;\n\n\n\n let mut values = values;\n\n let condition = values.remove(0);\n\n let code = values;\n\n\n\n let mut condition_result =\n", "file_path": "src/interpreter/stdlib/special_forms/_while.rs", "rank": 52, "score": 294594.3221359108 }, { "content": "pub fn or(\n\n interpreter: &mut Interpreter,\n\n environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n let values = values;\n\n let mut last_result = Value::Boolean(false);\n\n\n\n for value in values {\n\n let result = interpreter.execute_value(environment, value)?;\n\n\n\n if library::is_truthy(interpreter, result)? {\n\n return Ok(result);\n\n }\n\n\n\n last_result = result;\n\n }\n\n\n\n Ok(last_result)\n\n}\n", "file_path": "src/interpreter/stdlib/special_forms/or.rs", "rank": 53, "score": 294594.3221359108 }, { "content": "pub fn and(\n\n interpreter: &mut Interpreter,\n\n environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n let values = values;\n\n let mut last_result = Value::Boolean(true);\n\n\n\n for value in values {\n\n let result = interpreter.execute_value(environment, value)?;\n\n\n\n if library::is_falsy(interpreter, result)? {\n\n return Ok(result);\n\n }\n\n\n\n last_result = result;\n\n }\n\n\n\n Ok(last_result)\n\n}\n", "file_path": "src/interpreter/stdlib/special_forms/and.rs", "rank": 54, "score": 294594.3221359108 }, { "content": "pub fn with_this(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() == 0 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `with-this' takes one argument at least.\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n\n\n let first_value = values.remove(0);\n\n let first_value_evaluated =\n\n interpreter.execute_value(environment_id, first_value)?;\n\n\n\n let object_id = library::read_as_object_id(first_value_evaluated)?;\n\n\n", "file_path": "src/interpreter/stdlib/special_forms/with_this.rs", "rank": 55, "score": 294594.3221359108 }, { "content": "pub fn check_value_is_string_or_nil(\n\n interpreter: &mut Interpreter,\n\n value: Value,\n\n) -> Result<(), Error> {\n\n match value {\n\n Value::Symbol(symbol_id) => {\n\n if interpreter.symbol_is_not_nil(symbol_id)? {\n\n return Error::invalid_argument_error(\"Expected string or nil\")\n\n .into();\n\n }\n\n\n\n Ok(())\n\n }\n\n Value::String(_) => Ok(()),\n\n _ => Error::invalid_argument_error(\"Expected string or nil\").into(),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "src/interpreter/library/check/check_value_is_string_or_nil.rs", "rank": 56, "score": 292196.9684328815 }, { "content": "pub fn read_as_f64(value: Value) -> Result<f64, Error> {\n\n match value {\n\n Value::Float(float) => Ok(float),\n\n _ => Error::invalid_argument_error(\"Expected int.\").into(),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n\n\n\n use crate::Interpreter;\n\n\n\n #[test]\n", "file_path": "src/interpreter/library/read/read_as_f64.rs", "rank": 57, "score": 291436.3628286648 }, { "content": "pub fn read_as_i64(value: Value) -> Result<i64, Error> {\n\n match value {\n\n Value::Integer(int) => Ok(int),\n\n _ => Error::invalid_argument_error(\"Expected int.\").into(),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n\n\n\n use crate::Interpreter;\n\n\n\n #[test]\n", "file_path": "src/interpreter/library/read/read_as_i64.rs", "rank": 58, "score": 291436.3628286648 }, { "content": "pub fn read_as_bool(value: Value) -> Result<bool, Error> {\n\n match value {\n\n Value::Boolean(bool) => Ok(bool),\n\n _ => Error::invalid_argument_error(\"Expected boolean.\").into(),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n #[allow(unused_imports)]\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n\n\n\n use crate::Interpreter;\n\n\n", "file_path": "src/interpreter/library/read/read_as_bool.rs", "rank": 59, "score": 291436.3628286648 }, { "content": "fn remove_value_from_vector<T>(vector: &mut Vec<T>, value: T)\n\nwhere\n\n T: Copy + PartialEq + Eq,\n\n{\n\n let mut i = 0;\n\n let length = vector.len();\n\n\n\n while i < length {\n\n if vector[i] == value {\n\n break;\n\n }\n\n i += 1;\n\n }\n\n\n\n if i < length {\n\n vector.remove(i);\n\n }\n\n}\n\n\n\nimpl GarbageCollector {\n", "file_path": "src/interpreter/garbage_collector/garbage_collector.rs", "rank": 60, "score": 287238.9288865586 }, { "content": "pub fn test(\n\n _interpreter: &mut Interpreter,\n\n _environment_id: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() != 2 {\n\n return Error::invalid_argument_count_error(\n\n \"Built-in function `bit:test' takes two arguments exactly.\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n\n\n let index = library::read_as_i64(values.remove(0))?;\n\n\n\n if index < 0 || index > 63 {\n\n return Error::invalid_argument_error(\n\n \"Built-in function `bit:test' takes value between [0; 64) as bit index.\",\n\n )\n", "file_path": "src/interpreter/stdlib/builtin_objects/bit/test.rs", "rank": 61, "score": 285904.79493366915 }, { "content": "pub fn set(\n\n interpreter: &mut Interpreter,\n\n environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() != 2 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `set!' must be used with exactly two arguments\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n\n\n let variable_symbol_id =\n\n match values.remove(0) {\n\n Value::Symbol(symbol) => symbol,\n\n _ => return Error::invalid_argument_error(\n\n \"The first argument of special form `set!' must be a symbol.\",\n\n )\n", "file_path": "src/interpreter/stdlib/special_forms/set.rs", "rank": 62, "score": 285596.8559292028 }, { "content": "pub fn mlet(\n\n interpreter: &mut Interpreter,\n\n special_form_calling_environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() == 0 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form mlet must have at least one argument.\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n\n\n let definitions =\n\n library::read_as_flet_definitions(interpreter, values.remove(0))\n\n .map_err(|_| {\n\n Error::invalid_argument_error(\"Invalid `mlet' definitions.\")\n\n })?;\n\n\n", "file_path": "src/interpreter/stdlib/special_forms/mlet.rs", "rank": 63, "score": 285596.8559292028 }, { "content": "pub fn doitems(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() < 1 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `doitems' takes one argument at least.\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n let binding = library::read_as_vector(interpreter, values.remove(0))?;\n\n\n\n if binding.len() != 3 {\n\n return Error::invalid_argument_error(\n\n \"Special form `doitems' takes 3 item list as its first argument.\",\n\n )\n\n .into();\n", "file_path": "src/interpreter/stdlib/special_forms/doitems.rs", "rank": 64, "score": 285596.85592920275 }, { "content": "pub fn import(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n let evaluated_values =\n\n evaluate_values(interpreter, environment_id, values)?;\n\n\n\n let import_type =\n\n read_import_type::read_import_type(interpreter, evaluated_values)?;\n\n\n\n // todo: resolve relative module path\n\n eval_import::eval_import(interpreter, environment_id, import_type)?;\n\n\n\n Ok(Value::Boolean(true))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n", "file_path": "src/interpreter/stdlib/special_forms/import.rs", "rank": 65, "score": 285596.8559292028 }, { "content": "pub fn progn(\n\n interpreter: &mut Interpreter,\n\n environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n library::evaluate_forms_return_last(interpreter, environment, &values)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n\n\n\n #[test]\n\n fn returns_the_result_of_execution_of_the_last_form() {\n", "file_path": "src/interpreter/stdlib/special_forms/progn.rs", "rank": 66, "score": 285596.8559292028 }, { "content": "pub fn dokeys(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() < 1 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `dokeys' takes one argument at least.\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n let binding = library::read_as_vector(interpreter, values.remove(0))?;\n\n\n\n if binding.len() != 2 {\n\n return Error::invalid_argument_error(\n\n \"Special form `dokeys' takes 2 item list as its first argument.\",\n\n )\n\n .into();\n", "file_path": "src/interpreter/stdlib/special_forms/dokeys.rs", "rank": 67, "score": 285596.8559292028 }, { "content": "pub fn dovalues(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() < 1 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `dovalues' takes one argument at least.\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n let binding = library::read_as_vector(interpreter, values.remove(0))?;\n\n\n\n if binding.len() != 2 {\n\n return Error::invalid_argument_error(\n\n \"Special form `dovalues' takes 2 item list as its first argument.\",\n\n )\n\n .into();\n", "file_path": "src/interpreter/stdlib/special_forms/dovalues.rs", "rank": 68, "score": 285596.85592920275 }, { "content": "pub fn fset(\n\n interpreter: &mut Interpreter,\n\n environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() != 2 {\n\n return Error::invalid_argument_count_error(\n\n \"Built-in function `fset!' must be used with exactly two arguments\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n\n\n let function_symbol_id = match values.remove(0) {\n\n Value::Symbol(symbol) => symbol,\n\n _ => return Error::invalid_argument_error(\n\n \"The first argument of built-in function `fset!' must be a symbol.\",\n\n )\n\n .into(),\n", "file_path": "src/interpreter/stdlib/special_forms/fset.rs", "rank": 69, "score": 285596.8559292028 }, { "content": "pub fn call_with_this(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() < 2 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `call-with-this' takes two arguments at least.\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n\n\n let context_evaluated =\n\n interpreter.execute_value(environment_id, values.remove(0))?;\n\n let context_object_id = library::read_as_object_id(context_evaluated)?;\n\n\n\n let function_evaluated =\n\n interpreter.execute_value(environment_id, values.remove(0))?;\n", "file_path": "src/interpreter/stdlib/special_forms/call_with_this.rs", "rank": 70, "score": 285596.8559292028 }, { "content": "pub fn flet(\n\n interpreter: &mut Interpreter,\n\n special_form_calling_environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() == 0 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form flet must have at least one argument.\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n\n\n let definitions =\n\n library::read_as_flet_definitions(interpreter, values.remove(0))\n\n .map_err(|_| {\n\n Error::invalid_argument_error(\"Invalid `flet' definitions.\")\n\n })?;\n\n\n", "file_path": "src/interpreter/stdlib/special_forms/flet.rs", "rank": 71, "score": 285596.8559292028 }, { "content": "pub fn _try(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() < 2 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `try' must take at least two arguments\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n\n\n let try_code = values.remove(0);\n\n let clauses = values;\n\n\n\n let catch_clauses = read_catch_clauses(interpreter, clauses)?;\n\n let try_result = interpreter.execute_value(environment_id, try_code);\n\n\n", "file_path": "src/interpreter/stdlib/special_forms/_try.rs", "rank": 72, "score": 285596.8559292028 }, { "content": "pub fn cond(\n\n interpreter: &mut Interpreter,\n\n environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n let mut result = Ok(interpreter.intern_nil_symbol_value());\n\n\n\n for value in values {\n\n if let Value::Cons(part) = value {\n\n match execute_part(interpreter, environment, part) {\n\n Ok(Some(value)) => {\n\n result = Ok(value);\n\n break;\n\n },\n\n Err(error) => {\n\n result = Error::generic_execution_error_caused(\n\n \"Cannot execute special form `cond' clause.\",\n\n error,\n\n )\n\n .into();\n", "file_path": "src/interpreter/stdlib/special_forms/cond.rs", "rank": 73, "score": 285596.8559292028 }, { "content": "pub fn dotimes(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() < 1 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form dotimes`' takes one argument at least.\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n let mut binding = library::read_as_vector(interpreter, values.remove(0))?;\n\n\n\n if binding.len() != 2 {\n\n return Error::invalid_argument_error(\n\n \"Special form `dotimes' takes 2 item list as its first argument.\",\n\n )\n\n .into();\n", "file_path": "src/interpreter/stdlib/special_forms/dotimes.rs", "rank": 74, "score": 285596.8559292028 }, { "content": "pub fn throw(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() > 2 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `throw' must be called with no more than two arguments\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n\n\n let evaluated_first_argument = if values.len() > 0 {\n\n interpreter.execute_value(environment_id, values.remove(0))?\n\n } else {\n\n interpreter.intern_symbol_value(\"generic-error\")\n\n };\n\n\n", "file_path": "src/interpreter/stdlib/special_forms/throw.rs", "rank": 75, "score": 285596.8559292028 }, { "content": "pub fn block(\n\n interpreter: &mut Interpreter,\n\n execution_environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n let results = crate::library::evaluate_forms(\n\n interpreter,\n\n execution_environment,\n\n values,\n\n )?;\n\n\n\n Ok(interpreter.vec_to_list(results))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n", "file_path": "src/interpreter/stdlib/special_forms/block.rs", "rank": 76, "score": 285596.8559292028 }, { "content": "pub fn export(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n let evaluated_values =\n\n evaluate_values(interpreter, environment_id, values)?;\n\n\n\n let export_type =\n\n read_export_type::read_export_type(interpreter, evaluated_values)?;\n\n\n\n // todo: resolve relative module path\n\n eval_export::eval_export(interpreter, environment_id, export_type)?;\n\n\n\n Ok(Value::Boolean(true))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n", "file_path": "src/interpreter/stdlib/special_forms/export.rs", "rank": 77, "score": 285596.8559292028 }, { "content": "pub fn quote(\n\n _interpreter: &mut Interpreter,\n\n _environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n let mut values = values;\n\n\n\n if values.len() != 1 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `quote' must be called with exactly one argument.\",\n\n )\n\n .into();\n\n }\n\n\n\n let first_argument = values.remove(0);\n\n\n\n Ok(first_argument)\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/interpreter/stdlib/special_forms/quote.rs", "rank": 78, "score": 285596.8559292028 }, { "content": "pub fn dolist(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() < 1 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `dolist' takes one argument at least.\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n let mut binding = library::read_as_vector(interpreter, values.remove(0))?;\n\n\n\n if binding.len() != 2 {\n\n return Error::invalid_argument_error(\n\n \"Special form `dolist' takes 2 item list as its first argument.\",\n\n )\n\n .into();\n", "file_path": "src/interpreter/stdlib/special_forms/dolist.rs", "rank": 79, "score": 285596.8559292028 }, { "content": "pub fn function(\n\n interpreter: &mut Interpreter,\n\n environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n let mut values = values;\n\n\n\n if values.len() != 1 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `function' must be called with exactly one argument.\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = match values.remove(0) {\n\n Value::Cons(cons_id) => interpreter.list_to_vec(cons_id),\n\n _ => {\n\n return Error::invalid_argument_error(\n\n ERROR_MESSAGE_INCORRECT_ARGUMENT,\n\n )\n", "file_path": "src/interpreter/stdlib/special_forms/function.rs", "rank": 80, "score": 285596.8559292028 }, { "content": "fn make_none(_: Vec<char>) -> Result<Option<Element>, ParseError> {\n\n Ok(None)\n\n}\n\n\n", "file_path": "src/interpreter/parser/code.rs", "rank": 81, "score": 285519.39356520365 }, { "content": "pub fn read_as_positive_i64(value: Value) -> Result<i64, Error> {\n\n match value {\n\n Value::Integer(int) if int > 0 => Ok(int),\n\n _ => Error::invalid_argument_error(\"Expected positive int.\").into(),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n\n\n\n use crate::interpreter::interpreter::Interpreter;\n\n\n\n #[test]\n", "file_path": "src/interpreter/library/read/read_as_positive_i64.rs", "rank": 82, "score": 284943.6218195225 }, { "content": "pub fn read_as_object_id(value: Value) -> Result<ObjectId, Error> {\n\n let object_id = match value {\n\n Value::Object(object_id) => object_id,\n\n _ => {\n\n return Error::invalid_argument_error(\"Expected an object.\").into();\n\n }\n\n };\n\n\n\n Ok(object_id)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n", "file_path": "src/interpreter/library/read/read_as_object_id.rs", "rank": 83, "score": 281847.0650076614 }, { "content": "pub fn read_as_symbol_id(value: Value) -> Result<SymbolId, Error> {\n\n let symbol_id = match value {\n\n Value::Symbol(symbol_id) => symbol_id,\n\n _ => return Error::invalid_argument_error(\"Expected symbol.\").into(),\n\n };\n\n\n\n Ok(symbol_id)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n\n\n\n use crate::Interpreter;\n", "file_path": "src/interpreter/library/read/read_as_symbol_id.rs", "rank": 84, "score": 281847.0650076614 }, { "content": "pub fn read_as_keyword_id(value: Value) -> Result<KeywordId, Error> {\n\n let symbol_id = match value {\n\n Value::Keyword(keyword_id) => keyword_id,\n\n _ => return Error::invalid_argument_error(\"Expected keyword.\").into(),\n\n };\n\n\n\n Ok(symbol_id)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n\n\n\n use crate::Interpreter;\n", "file_path": "src/interpreter/library/read/read_as_keyword_id.rs", "rank": 85, "score": 281847.0650076614 }, { "content": "pub fn read_as_string_id(value: Value) -> Result<StringId, Error> {\n\n let string_id = match value {\n\n Value::String(string_id) => string_id,\n\n _ => return Error::invalid_argument_error(\"Expected string.\").into(),\n\n };\n\n\n\n Ok(string_id)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n\n\n\n use crate::Interpreter;\n", "file_path": "src/interpreter/library/read/read_as_string_id.rs", "rank": 86, "score": 281847.0650076614 }, { "content": "pub fn read_as_cons_id(value: Value) -> Result<ConsId, Error> {\n\n let cons_id = match value {\n\n Value::Cons(cons_id) => cons_id,\n\n _ => {\n\n return Error::invalid_argument_error(\"Expected cons cell.\").into();\n\n }\n\n };\n\n\n\n Ok(cons_id)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n", "file_path": "src/interpreter/library/read/read_as_cons_id.rs", "rank": 87, "score": 281847.0650076614 }, { "content": "pub fn read_as_function_id(value: Value) -> Result<FunctionId, Error> {\n\n let function_id = match value {\n\n Value::Function(function_id) => function_id,\n\n _ => {\n\n return Error::invalid_argument_error(\"Expected a function.\")\n\n .into();\n\n }\n\n };\n\n\n\n Ok(function_id)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n", "file_path": "src/interpreter/library/read/read_as_function_id.rs", "rank": 88, "score": 281847.0650076614 }, { "content": "pub fn set_definitions(\n\n interpreter: &mut Interpreter,\n\n special_form_calling_environment: EnvironmentId,\n\n function_definition_environment: EnvironmentId,\n\n definitions: Vec<(Value, FunctionArguments, Vec<Value>)>,\n\n) -> Result<(), Error> {\n\n for definition in definitions {\n\n set_definition(\n\n interpreter,\n\n special_form_calling_environment,\n\n function_definition_environment,\n\n definition,\n\n )?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/interpreter/stdlib/special_forms/flet.rs", "rank": 89, "score": 281354.27491773124 }, { "content": "pub fn set_definitions(\n\n interpreter: &mut Interpreter,\n\n special_form_calling_environment: EnvironmentId,\n\n macro_definition_environment: EnvironmentId,\n\n definitions: Vec<(Value, FunctionArguments, Vec<Value>)>,\n\n) -> Result<(), Error> {\n\n for definition in definitions {\n\n set_macro_definition(\n\n interpreter,\n\n special_form_calling_environment,\n\n macro_definition_environment,\n\n definition,\n\n )?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/interpreter/stdlib/special_forms/mlet.rs", "rank": 90, "score": 281354.27491773124 }, { "content": "pub fn run() -> Result<(), std::io::Error> {\n\n let interpreter = Interpreter::with_default_config();\n\n let history_file = get_history_file_path();\n\n\n\n let event_loop_handle = EventLoop::run_event_loop(interpreter);\n\n\n\n let mut rl = Editor::<()>::new();\n\n\n\n if let Some(history) = &history_file {\n\n rl.load_history(history)\n\n .expect(\"Failure reading history file.\");\n\n } else {\n\n println!(\"History file can't be constructed.\");\n\n }\n\n\n\n loop {\n\n let readline = rl.readline(\">> \");\n\n\n\n match readline {\n\n Ok(line) => {\n", "file_path": "src/repl/mod.rs", "rank": 91, "score": 278115.05822817964 }, { "content": "pub fn define_function(\n\n interpreter: &mut Interpreter,\n\n environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n let mut values = values;\n\n\n\n if values.len() < 1 || values.len() > 3 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `define-function' must be used with one or two or three forms.\",\n\n )\n\n .into();\n\n }\n\n\n\n let first_argument = values.remove(0);\n\n let second_argument = if values.len() > 0 {\n\n Some(values.remove(0))\n\n } else {\n\n None\n\n };\n", "file_path": "src/interpreter/stdlib/special_forms/define_function.rs", "rank": 92, "score": 277269.73902440805 }, { "content": "pub fn mlet_star(\n\n interpreter: &mut Interpreter,\n\n special_form_calling_environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() == 0 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `mlet*' must have at least one argument.\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n\n\n let definitions =\n\n library::read_as_flet_definitions(interpreter, values.remove(0))\n\n .map_err(|_| {\n\n Error::invalid_argument_error(\"Invalid `mlet*' definitions.\")\n\n })?;\n\n\n", "file_path": "src/interpreter/stdlib/special_forms/mlet_star.rs", "rank": 93, "score": 277269.73902440805 }, { "content": "pub fn flet_star(\n\n interpreter: &mut Interpreter,\n\n special_form_calling_environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n if values.len() == 0 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `flet*' must have at least one argument.\",\n\n )\n\n .into();\n\n }\n\n\n\n let mut values = values;\n\n\n\n let definitions =\n\n library::read_as_flet_definitions(interpreter, values.remove(0))\n\n .map_err(|_| {\n\n Error::invalid_argument_error(\"Invalid `flet*' definitions.\")\n\n })?;\n\n\n", "file_path": "src/interpreter/stdlib/special_forms/flet_star.rs", "rank": 94, "score": 277269.73902440805 }, { "content": "pub fn define_variable(\n\n interpreter: &mut Interpreter,\n\n environment: EnvironmentId,\n\n values: Vec<Value>,\n\n) -> Result<Value, Error> {\n\n let mut values = values;\n\n\n\n if values.len() < 1 || values.len() > 3 {\n\n return Error::invalid_argument_count_error(\n\n \"Special form `define-variable' must be used with one or two forms.\",\n\n )\n\n .into();\n\n }\n\n\n\n let first_argument = values.remove(0);\n\n let second_argument = if values.len() > 0 {\n\n Some(values.remove(0))\n\n } else {\n\n None\n\n };\n", "file_path": "src/interpreter/stdlib/special_forms/define_variable.rs", "rank": 95, "score": 277269.73902440805 }, { "content": "pub fn key_to_list(interpreter: &mut Interpreter, key: Key) -> Value {\n\n match key {\n\n Key::LoneKey(lone_key) => Value::Integer(lone_key.get_key_id() as i64),\n\n Key::DeviceKey(device_key) => interpreter.vec_to_list(vec![\n\n Value::Integer(device_key.get_device_id() as i64),\n\n Value::Integer(device_key.get_key_id() as i64),\n\n ]),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(unused_imports)]\n\n use nia_basic_assertions::*;\n\n\n\n #[allow(unused_imports)]\n\n use crate::utils;\n\n\n", "file_path": "src/interpreter/library/keys/key_chord/key_to_list.rs", "rank": 96, "score": 275144.532745023 }, { "content": "pub fn read_float_element(float_element: FloatElement) -> Result<Value, Error> {\n\n Ok(Value::Float(float_element.get_value()))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use nia_basic_assertions::nia_assert_equal;\n\n\n\n #[test]\n\n fn reads_float_elements_correctly() {\n\n let specs = vec![\n\n (Value::Float(0.0), FloatElement::new(0.0)),\n\n (Value::Float(1.1), FloatElement::new(1.1)),\n\n (Value::Float(-11.1), FloatElement::new(-11.1)),\n\n ];\n\n\n\n for (expected, float_element) in specs {\n\n let result = read_float_element(float_element);\n\n\n\n nia_assert_equal(Ok(expected), result);\n\n }\n\n }\n\n}\n", "file_path": "src/interpreter/reader/read_float_element.rs", "rank": 97, "score": 268783.066168388 }, { "content": "fn set_definition(\n\n interpreter: &mut Interpreter,\n\n definition_value_execution_environment: EnvironmentId,\n\n definition_setting_environment: EnvironmentId,\n\n definition: Value,\n\n) -> Result<(), Error> {\n\n match definition {\n\n Value::Cons(cons_id) => set_variable_via_cons(\n\n interpreter,\n\n definition_value_execution_environment,\n\n definition_setting_environment,\n\n cons_id,\n\n ),\n\n Value::Symbol(symbol_id) => {\n\n if interpreter.symbol_is_nil(symbol_id)? {\n\n return Error::invalid_argument_error(\n\n \"It's not possible to redefine `nil' via special form `let'.\",\n\n )\n\n .into();\n\n } else {\n", "file_path": "src/interpreter/stdlib/special_forms/_let.rs", "rank": 98, "score": 254745.1004595082 }, { "content": "pub fn evaluate_symbol(\n\n interpreter: &mut Interpreter,\n\n environment_id: EnvironmentId,\n\n symbol_id: SymbolId,\n\n) -> Result<Value, Error> {\n\n if interpreter.check_if_symbol_special(symbol_id)? {\n\n return Error::generic_execution_error(\n\n \"Cannot evaluate special symbols.\",\n\n )\n\n .into();\n\n }\n\n\n\n let evaluation_result = match interpreter\n\n .lookup_variable(environment_id, symbol_id)?\n\n {\n\n Some(result) => result,\n\n None => match interpreter.get_special_variable(symbol_id) {\n\n Some(func) => return func(interpreter),\n\n None => {\n\n let variable_name = interpreter.get_symbol_name(symbol_id)?;\n", "file_path": "src/interpreter/evaluator/evaluate_symbol.rs", "rank": 99, "score": 253907.03207714314 } ]
Rust
krapao/src/state.rs
shigedangao/jiemi
beffe848cb5606a4bee02647f8a6743e09301e45
use std::sync::{Arc, Mutex}; use std::fs; use std::collections::HashMap; use dirs::home_dir; use serde::{Serialize, Deserialize}; use crate::repo::config::GitConfig; use crate::err::Error; use crate::helper; const REPO_FILE_PATH: &str = "list.json"; const REPO_PATH: &str = "workspace/repo"; pub type State = Arc<Mutex<HashMap<String, GitConfig>>>; #[derive(Debug, Serialize, Deserialize, Default)] struct List { repositories: Option<HashMap<String, GitConfig>> } impl List { fn read_persistent_state() -> Result<List, Error> { let mut file_path = home_dir().unwrap_or_default(); file_path.push(REPO_PATH); file_path.push(REPO_FILE_PATH); let saved_state = fs::read(&file_path)?; let list: List = serde_json::from_slice(&saved_state)?; Ok(list) } fn create_new_empty_state() -> Result<List, Error> { let default = List::default(); default.save_list_to_persistent_state()?; Ok(default) } fn save_list_to_persistent_state(&self) -> Result<(), Error> { let mut file_path = home_dir().unwrap_or_default(); file_path.push(REPO_PATH); file_path.push(REPO_FILE_PATH); let json = serde_json::to_string_pretty(&self)?; fs::write(file_path, json)?; Ok(()) } } pub fn create_state() -> Result<State, Error> { let mut workspace_dir = home_dir().unwrap_or_default(); workspace_dir.push(REPO_PATH); helper::create_path(&workspace_dir)?; let saved_state = match List::read_persistent_state() { Ok(res) => res, Err(_) => { List::create_new_empty_state()? } }; if let Some(existing_state) = saved_state.repositories { return Ok(Arc::new(Mutex::new(existing_state))); } Ok(Arc::new(Mutex::new(HashMap::new()))) } pub fn save_new_repo_in_persistent_state(config: GitConfig) -> Result<(), Error> { let mut list: List = List::read_persistent_state()?; if let Some(existing_state) = list.repositories.as_mut() { existing_state.insert(config.repo_uri.clone(), config); } else { let mut map = HashMap::new(); map.insert(config.repo_uri.clone(), config); list.repositories = Some(map); } list.save_list_to_persistent_state() } pub fn remove_repo_from_persistent_state(key: &str) -> Result<(), Error> { let mut list: List = List::read_persistent_state()?; if let Some(existing_state) = list.repositories.as_mut() { existing_state.remove(key); } list.save_list_to_persistent_state() } #[cfg(test)] mod tests { use std::path::PathBuf; use crate::repo::config::Credentials; use super::*; #[test] fn expect_to_create_state() { let state = create_state(); assert!(state.is_ok()); let list = List::read_persistent_state(); assert!(list.is_ok()); } #[test] fn expect_to_save_new_config() { let repo_uri = "https://github.com/shigedangao/maskiedoc.git"; let credentials = Credentials::Empty; let config = GitConfig::new( credentials, repo_uri, PathBuf::new() ).unwrap(); let res = save_new_repo_in_persistent_state(config); assert!(res.is_ok()); let list = List::read_persistent_state().unwrap(); let repos = list.repositories.unwrap(); let maskiedoc = repos.get(repo_uri); assert!(maskiedoc.is_some()); let res = remove_repo_from_persistent_state(repo_uri); assert!(res.is_ok()); } }
use std::sync::{Arc, Mutex}; use std::fs; use std::collections::HashMap; use dirs::home_dir; use serde::{Serialize, Deserialize}; use crate::repo::config::GitConfig; use crate::err::Error; use crate::helper; const REPO_FILE_PATH: &str = "list.json"; const REPO_PATH: &str = "workspace/repo"; pub type State = Arc<Mutex<HashMap<String, GitConfig>>>; #[derive(Debug, Serialize, Deserialize, Default)] struct List { repositories: Option<HashMap<String, GitConfig>> } impl List { fn read_persistent_state() -> Result<List, Error> { let mut file_path = home_dir().unwrap_or_default(); file_path.push(REPO_PATH); file_path.push(REPO_FILE_PATH); let saved_state = fs::read(&file_path)?; let list: List = serde_json::from_slice(&saved_state)?; Ok(list) } fn create_new_empty_state() -> Result<List, Error> { let default = List::default(); default.save_list_to_persistent_state()?; Ok(default) }
} pub fn create_state() -> Result<State, Error> { let mut workspace_dir = home_dir().unwrap_or_default(); workspace_dir.push(REPO_PATH); helper::create_path(&workspace_dir)?; let saved_state = match List::read_persistent_state() { Ok(res) => res, Err(_) => { List::create_new_empty_state()? } }; if let Some(existing_state) = saved_state.repositories { return Ok(Arc::new(Mutex::new(existing_state))); } Ok(Arc::new(Mutex::new(HashMap::new()))) } pub fn save_new_repo_in_persistent_state(config: GitConfig) -> Result<(), Error> { let mut list: List = List::read_persistent_state()?; if let Some(existing_state) = list.repositories.as_mut() { existing_state.insert(config.repo_uri.clone(), config); } else { let mut map = HashMap::new(); map.insert(config.repo_uri.clone(), config); list.repositories = Some(map); } list.save_list_to_persistent_state() } pub fn remove_repo_from_persistent_state(key: &str) -> Result<(), Error> { let mut list: List = List::read_persistent_state()?; if let Some(existing_state) = list.repositories.as_mut() { existing_state.remove(key); } list.save_list_to_persistent_state() } #[cfg(test)] mod tests { use std::path::PathBuf; use crate::repo::config::Credentials; use super::*; #[test] fn expect_to_create_state() { let state = create_state(); assert!(state.is_ok()); let list = List::read_persistent_state(); assert!(list.is_ok()); } #[test] fn expect_to_save_new_config() { let repo_uri = "https://github.com/shigedangao/maskiedoc.git"; let credentials = Credentials::Empty; let config = GitConfig::new( credentials, repo_uri, PathBuf::new() ).unwrap(); let res = save_new_repo_in_persistent_state(config); assert!(res.is_ok()); let list = List::read_persistent_state().unwrap(); let repos = list.repositories.unwrap(); let maskiedoc = repos.get(repo_uri); assert!(maskiedoc.is_some()); let res = remove_repo_from_persistent_state(repo_uri); assert!(res.is_ok()); } }
fn save_list_to_persistent_state(&self) -> Result<(), Error> { let mut file_path = home_dir().unwrap_or_default(); file_path.push(REPO_PATH); file_path.push(REPO_FILE_PATH); let json = serde_json::to_string_pretty(&self)?; fs::write(file_path, json)?; Ok(()) }
function_block-full_function
[ { "content": "/// Delete an item in the state. This case is used when a CRD is delete. w/o removing the item, when a crd containing the sma\n\n/// name is applied. The crd might not take into account the update\n\n/// \n\n/// # Arguments\n\n/// * `state` - State\n\n/// * `key` - &str\n\npub fn delete_item_in_state(state: State, key: &str) -> Result<(), Error> {\n\n let mut state = state.lock()\n\n .map_err(|_| Error::Watch(LOCK_ERR_MSG.to_owned()))?;\n\n\n\n state.remove(key);\n\n\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn expect_to_add_new_element_in_state() {\n\n let state = generate_new_state();\n\n let res = upsert_state(state, \"foo\", 1).unwrap();\n\n \n\n assert_eq!(res, false);\n\n }\n", "file_path": "miwen/src/state.rs", "rank": 0, "score": 177596.1225835763 }, { "content": "/// Check if the CRD is registered in the state\n\n/// This is gonna be used to trigger a grpc call to pull the repository if a new CRD is founded\n\n/// Why ? If a new CRD is pushed we want to clone it's associated repository only once.\n\n/// \n\n/// # Arguments\n\n/// * `state` - State\n\n/// * `key` - &str\n\npub fn is_registered(state: State, key: &str) -> Result<bool, Error> {\n\n let state = state.lock()\n\n .map_err(|_| Error::Watch(LOCK_ERR_MSG.to_owned()))?;\n\n\n\n if state.contains_key(key) {\n\n return Ok(true);\n\n }\n\n\n\n Ok(false)\n\n}\n\n\n", "file_path": "miwen/src/state.rs", "rank": 1, "score": 175043.81123708622 }, { "content": "/// Check whenever the generation id exist in the state\n\n/// If it does not exist / different, then adding / updating the value in the state\n\n/// \n\n/// # Arguments\n\n/// * `state` - State\n\n/// * `key` - &str\n\n/// * `value` - i64\n\npub fn upsert_state(state: State, key: &str, value: i64) -> Result<bool, Error> {\n\n let mut state = state\n\n .lock()\n\n .map_err(|_| Error::Watch(LOCK_ERR_MSG.to_owned()))?;\n\n \n\n if let Some(inner) = state.get(key) {\n\n if inner == &value {\n\n return Ok(true)\n\n }\n\n }\n\n\n\n // otherwise update the state...\n\n state.insert(String::from(key), value);\n\n\n\n Ok(false)\n\n}\n\n\n", "file_path": "miwen/src/state.rs", "rank": 2, "score": 164011.55795861213 }, { "content": "/// Authenticate\n\n/// \n\n/// # Arguments\n\n/// * `access_key` - String\n\n/// * `secret_key` - String\n\n/// * `region` - String\n\npub fn authenticate(access_key: &str, secret_key: &str, region: &str) -> Result<(), Error> {\n\n if access_key.is_empty() || secret_key.is_empty() || region.is_empty() {\n\n return Err(Error::Sops(\"AWS configuration missing either the key_id, access_key or the region\".to_owned()));\n\n }\n\n\n\n // Create credentials\n\n AwsConfig::new(\n\n Some((access_key.to_owned(), secret_key.to_owned())), \n\n None\n\n ).create_credentials()?;\n\n \n\n // Create config\n\n AwsConfig::new(None, Some(region.to_owned()))\n\n .create_config()?;\n\n\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "krapao/src/auth/aws.rs", "rank": 6, "score": 133457.84958982875 }, { "content": "/// Create / Overwrite the SSH key\n\n/// \n\n/// # Arguments\n\n/// * `key` - &str\n\npub fn set_ssh_key(key: &str) -> Result<(), Error> {\n\n fs::write(SSH_KEYPATH, key)?;\n\n\n\n let mut perm = fs::metadata(SSH_KEYPATH)?.permissions();\n\n perm.set_mode(0o600);\n\n fs::set_permissions(SSH_KEYPATH, perm)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "krapao/src/helper.rs", "rank": 7, "score": 133101.24085794957 }, { "content": "/// Authenticate with pgp by creating the private.rsa key and then \n\n/// importing the key with the gpg command\n\n/// \n\n/// # Arguments\n\n/// * `key` - &str\n\npub fn authenticate_with_pgp(key: &str) -> Result<(), Error> {\n\n // write the private.rsa file\n\n fs::write(KEY_FILE_PATH, key)?;\n\n\n\n let status = Command::new(\"gpg\")\n\n .arg(\"--import\")\n\n .arg(KEY_FILE_PATH)\n\n .status()?;\n\n\n\n if !status.success() {\n\n return Err(Error::ProviderAuth(GPG_AUTH_ERR.to_owned()));\n\n }\n\n\n\n info!(\"🔑 PGP key registered\");\n\n\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "krapao/src/auth/pgp.rs", "rank": 8, "score": 133100.94083820045 }, { "content": "/// Generate a new State\n\n/// \n\n/// The state is used to stored the list of CRD that has been registered when a user used the command\n\n/// kubectl apply -f <crd>\n\n/// As we're also updating the CRD. Using a state ensure us that this won't create an infinite loop of update\n\npub fn generate_new_state() -> State {\n\n Arc::new(Mutex::new(HashMap::new()))\n\n}\n\n\n", "file_path": "miwen/src/state.rs", "rank": 10, "score": 128080.92663036258 }, { "content": "/// Decrypt SOPS file and return the output to the caller\n\n/// \n\n/// # Arguments\n\n/// * `config` - &GitConfig\n\n/// * `target_file_path` - &str\n\n/// * `sops_file_path` - &str\n\npub fn decrypt_file(config: &GitConfig, target_file_path: &str, sops_file_path: &str) -> Result<String, Error> {\n\n let mut t_file_path = config.target.clone();\n\n t_file_path.push(target_file_path);\n\n\n\n let mut s_file_path = config.target.clone();\n\n s_file_path.push(sops_file_path);\n\n\n\n info!(\"Trying to decrypt {target_file_path}...\");\n\n let cmd = Command::new(\"sops\")\n\n .arg(\"-d\")\n\n .arg(t_file_path)\n\n .arg(\"--config\")\n\n .arg(s_file_path)\n\n .output()?;\n\n\n\n let status = cmd.status;\n\n if status.success() {\n\n let stdout = String::from_utf8(cmd.stdout)\n\n .map_err(|_| Error::Sops(\"Unable to parse SOPS stdout\".to_owned()))?;\n\n \n", "file_path": "krapao/src/sops.rs", "rank": 11, "score": 126745.55194110537 }, { "content": "/// Process the delete CRD\n\n/// \n\n/// # Arguments\n\n/// * `crd` - Decryptor\n\n/// * `state` - State\n\nfn deleted_crd(crd: Decryptor, state: state::State) -> Result<(), Error> {\n\n let (name, _, _) = crd.get_metadata_info()?;\n\n state::delete_item_in_state(state, &name)?;\n\n info!(\"🗑️ {name} has been removed\");\n\n\n\n Ok(())\n\n}\n\n\n\n/// Create a watcher which will watch the Decryptor resources.\n\n/// For each Decryptor resource that has been:\n\n/// - created\n\n/// - updated\n\n/// \n\n/// The watcher will update the resource and add a status about the Decryptor\n\n/// \n\n/// # Why use a State ?\n\n/// By default, any changes on the Kubernetes object will trigger a new event.\n\n/// This is something we want to avoid as this would create an infinite loop.\n\n/// By using a state we're storing the generation id of the resource in a HashMap\n\n/// Hence, when a new event happened. We'll check first the generation to see if it's the same\n", "file_path": "miwen/src/watcher/mod.rs", "rank": 12, "score": 113690.60514985287 }, { "content": "/// Initialize the git repository handler\n\n/// \n\n/// # Arguments\n\n/// * `env` - &GitCredentials\n\npub fn initialize_git(env: &GitCredentials) -> Result<GitConfig, Error> {\n\n // retrieve the environment variable for git credentials\n\n let credentials = Credentials::new(env);\n\n\n\n let config = GitConfig::new(credentials, &env.repository, env.target.to_owned())?;\n\n config.init_repository()?;\n\n\n\n Ok(config)\n\n}\n", "file_path": "krapao/src/repo/mod.rs", "rank": 13, "score": 103274.2702133533 }, { "content": "/// Create path if the path does not exist\n\n/// \n\n/// # Arguments\n\n/// * `path` - &Path\n\npub fn create_path(path: &Path) -> Result<(), Error> {\n\n if let Err(err) = fs::create_dir_all(path) {\n\n if err.kind() == ErrorKind::AlreadyExists {\n\n info!(\"🔍 Path already exist\");\n\n return Ok(())\n\n }\n\n\n\n return Err(Error::from(err))\n\n }\n\n\n\n info!(\"📜 Credentials path has been created\");\n\n Ok(())\n\n}", "file_path": "krapao/src/helper.rs", "rank": 14, "score": 99760.08505671585 }, { "content": "/// Generate a CRD which is used to be applied in a Kubernetes cluster\n\n/// The final example of how the crd looks can be founded on the example folder\n\npub fn generate_crd() -> Result<String, Box<dyn std::error::Error>> {\n\n let res = serde_yaml::to_string(&Decryptor::crd())?;\n\n\n\n Ok(res)\n\n}\n\n\n\nimpl Provider {\n\n /// Get the credentials value from the provider section\n\n /// \n\n /// # Arguments\n\n /// * `&self` - &Self\n\n /// * `ns` - &str\n\n pub async fn get_credentials(&self, ns: &str) -> Result<provider::ProviderList, Error> {\n\n let client = Client::try_default().await?;\n\n if let Some(gcp) = self.gcp.clone() {\n\n let list = gcp.convert(client, ns).await?;\n\n return Ok(list);\n\n }\n\n\n\n if let Some(aws) = self.aws.clone() {\n", "file_path": "gen/src/crd/mod.rs", "rank": 15, "score": 99628.839099956 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n tonic_build::configure()\n\n .build_client(true)\n\n .build_server(false)\n\n .compile(&[\n\n \"../proto/repository.proto\",\n\n \"../proto/crd.proto\"\n\n ], \n\n &[\"../proto\"]\n\n )?;\n\n\n\n Ok(())\n\n}", "file_path": "miwen/build.rs", "rank": 16, "score": 78932.43713893638 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n tonic_build::configure()\n\n .build_server(true)\n\n .build_client(false)\n\n .compile(&[\n\n \"../proto/repository.proto\",\n\n \"../proto/crd.proto\"\n\n ], \n\n &[\"../proto\"]\n\n )?;\n\n\n\n Ok(())\n\n}", "file_path": "krapao/build.rs", "rank": 17, "score": 78932.43713893638 }, { "content": "/// Export the ssh key to the environment variable of the os\n\npub fn export_ssh_key_to_env() {\n\n let arg = format!(\"ssh -i {} -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no\", SSH_KEYPATH);\n\n env::set_var(SSH_GIT_ENV, arg);\n\n}\n\n\n", "file_path": "krapao/src/helper.rs", "rank": 18, "score": 75584.49718516326 }, { "content": "#[derive(Serialize, Default)]\n\nstruct AwsConfig {\n\n #[serde(rename(serialize = \"default\"))]\n\n credentials: Option<AwsCredentials>,\n\n #[serde(rename(serialize = \"default\"))]\n\n config: Option<AwsRegion>\n\n}\n\n\n", "file_path": "krapao/src/auth/aws.rs", "rank": 19, "score": 47088.64266480302 }, { "content": "#[derive(Serialize)]\n\nstruct AwsCredentials {\n\n aws_access_key_id: String,\n\n aws_secret_access_key: String\n\n}\n\n\n", "file_path": "krapao/src/auth/aws.rs", "rank": 20, "score": 47085.10474662596 }, { "content": "#[derive(Serialize)]\n\nstruct AwsRegion {\n\n region: String,\n\n output: String\n\n}\n\n\n\nimpl AwsConfig {\n\n /// Create a new AwsConfig based on the input parameter\n\n /// \n\n /// # Arguments\n\n /// * `creds` - Option<(String, String)>\n\n /// * `conf` - Option<String>\n\n fn new(creds: Option<(String, String)>, conf: Option<String>) -> AwsConfig {\n\n let mut config = AwsConfig::default();\n\n if let Some((key, access_key)) = creds {\n\n config.credentials = Some(AwsCredentials {\n\n aws_access_key_id: key,\n\n aws_secret_access_key: access_key\n\n });\n\n }\n\n\n", "file_path": "krapao/src/auth/aws.rs", "rank": 21, "score": 47085.10474662596 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct GvkWrapper {\n\n #[serde(rename = \"apiVersion\")]\n\n api_version: String,\n\n kind: String,\n\n metadata: ObjectMeta\n\n}\n\n\n\nimpl GvkWrapper {\n\n /// Retrieve the GVK from the wrapper\n\n /// \n\n /// # Arguments\n\n /// * `&self` - &Self\n\n fn get_gkv(&self) -> GroupVersionKind {\n\n // version is defined like so v1/deployment\n\n // if we have no slash, then we use group as \"\". \"\" represent the core api\n\n // version -> group\n\n let splitted_group = self.api_version.split_once(API_GROUP_SPLIT);\n\n match splitted_group {\n\n Some((group, version)) => GroupVersionKind {\n\n group: group.to_owned(),\n", "file_path": "miwen/src/watcher/apply.rs", "rank": 22, "score": 47085.04853783827 }, { "content": "/// Setup different logging & debugging services\n\nfn setup() -> Result<()> {\n\n if std::env::var(\"RUST_BACKTRACE\").is_err() {\n\n std::env::set_var(\"RUST_BACKTRACE\", \"full\");\n\n }\n\n\n\n color_eyre::install()\n\n}\n\n\n", "file_path": "gen/src/main.rs", "rank": 23, "score": 38574.44345484679 }, { "content": "/// Setup different logging & debugging services\n\nfn setup() -> Result<()> {\n\n if std::env::var(\"RUST_LOG\").is_err() {\n\n std::env::set_var(\"RUST_LOG\", \"krapao=debug\");\n\n }\n\n\n\n if std::env::var(\"RUST_BACKTRACE\").is_err() {\n\n std::env::set_var(\"RUST_BACKTRACE\", \"full\");\n\n }\n\n\n\n // init the env loggger\n\n env_logger::init();\n\n color_eyre::install()\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> Result<()> {\n\n setup()?;\n\n // create the state\n\n let state = state::create_state()?;\n\n\n", "file_path": "krapao/src/main.rs", "rank": 24, "score": 38574.44345484679 }, { "content": "fn main() -> Result<()> {\n\n setup()?;\n\n \n\n // retrieve a filename path if given\n\n // not using clap as we're only focusing on a single arg...\n\n let path = env::args().nth(1).unwrap_or_else(|| \".\".to_owned());\n\n let full_path = format!(\"{path}/crd.yaml\");\n\n\n\n let spec = crd::generate_crd().expect(\"Expect to generate CRD\");\n\n fs::write(&full_path, spec)?;\n\n println!(\"✅ CRD has been generated at the path {full_path}\");\n\n\n\n Ok(())\n\n}\n", "file_path": "gen/src/main.rs", "rank": 25, "score": 38574.44345484679 }, { "content": "/// Setup different logging & debugging services\n\nfn setup() -> color_eyre::Result<()> {\n\n if std::env::var(\"RUST_LOG\").is_err() {\n\n std::env::set_var(\"RUST_LOG\", \"miwen=info\");\n\n }\n\n\n\n if std::env::var(\"RUST_BACKTRACE\").is_err() {\n\n std::env::set_var(\"RUST_BACKTRACE\", \"full\");\n\n }\n\n\n\n // init the env loggger\n\n env_logger::init();\n\n color_eyre::install()\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n setup()?;\n\n\n\n let state = state::generate_new_state();\n\n tokio::try_join!(\n\n // Start the watcher which will react to any changes on the crd\n\n watcher::boostrap_watcher(state),\n\n // Start a sync loop which will sync the repo with the cluster\n\n sync::bootstrap_repo_sync()\n\n )?;\n\n\n\n Ok(())\n\n}\n", "file_path": "miwen/src/main.rs", "rank": 26, "score": 35564.77167594045 }, { "content": "/// Get the gRPC http address\n\nfn get_rpc_addr() -> String {\n\n if let Some(mode) = std::env::var_os(\"MODE\") {\n\n if mode == \"release\" {\n\n return \"http://repository-svc:50208\".to_owned()\n\n }\n\n }\n\n\n\n // use on local dev\n\n \"http://127.0.0.1:50208\".to_owned()\n\n}", "file_path": "miwen/src/client/mod.rs", "rank": 27, "score": 35452.41267169096 }, { "content": "use std::sync::{Arc, Mutex};\n\nuse std::collections::HashMap;\n\nuse crate::err::Error;\n\n\n\n// Constant\n\nconst LOCK_ERR_MSG: &str = \"Unable to acquired lock\";\n\n\n\npub type State = Arc<Mutex<HashMap<String, i64>>>;\n\n\n\n/// Generate a new State\n\n/// \n\n/// The state is used to stored the list of CRD that has been registered when a user used the command\n\n/// kubectl apply -f <crd>\n\n/// As we're also updating the CRD. Using a state ensure us that this won't create an infinite loop of update\n", "file_path": "miwen/src/state.rs", "rank": 29, "score": 29999.9522537778 }, { "content": "\n\n #[test]\n\n fn expect_upsert_to_return_false() {\n\n let state = generate_new_state();\n\n\n\n let res = upsert_state(state.clone(), \"foo\", 1).unwrap();\n\n assert_eq!(res, false);\n\n\n\n let res = upsert_state(state, \"foo\", 1).unwrap();\n\n assert_eq!(res, true);\n\n }\n\n\n\n #[test]\n\n fn expect_to_update_existing_element_in_state() {\n\n let state = generate_new_state();\n\n upsert_state(state.clone(), \"foo\", 1).unwrap();\n\n upsert_state(state.clone(), \"foo\", 2).unwrap();\n\n\n\n // get the value and check it\n\n let map = state.lock().unwrap();\n", "file_path": "miwen/src/state.rs", "rank": 33, "score": 29987.16968600869 }, { "content": " }\n\n\n\n #[test]\n\n fn expect_to_delete_item_in_state() {\n\n let state = generate_new_state();\n\n upsert_state(state.clone(), \"foo\", 1).unwrap();\n\n\n\n let res = delete_item_in_state(state.clone(), \"foo\");\n\n assert!(res.is_ok());\n\n\n\n let map = state.lock().unwrap();\n\n let item = map.get(\"foo\");\n\n assert!(item.is_none());\n\n }\n\n}", "file_path": "miwen/src/state.rs", "rank": 34, "score": 29987.08151999543 }, { "content": " let item = map.get(\"foo\");\n\n\n\n assert_eq!(item.unwrap().to_owned(), 2);\n\n }\n\n\n\n #[test]\n\n fn expect_state_to_be_registered() {\n\n let state = generate_new_state();\n\n upsert_state(state.clone(), \"foo\", 1).unwrap();\n\n \n\n let res = is_registered(state, \"foo\").unwrap();\n\n assert_eq!(res, true);\n\n }\n\n\n\n #[test]\n\n fn expect_state_to_not_be_registered() {\n\n let state = generate_new_state();\n\n let res = is_registered(state, \"foo\").unwrap();\n\n \n\n assert_eq!(res, false);\n", "file_path": "miwen/src/state.rs", "rank": 35, "score": 29987.073871851408 }, { "content": "use kube::Client;\n\nuse schemars::JsonSchema;\n\nuse serde::{Serialize, Deserialize};\n\nuse crate::err::Error;\n\nuse super::secret::GenericConfig;\n\n\n\n// Constant\n\nconst TOKEN_MSG_ERR: &str = \"Unable to retrieve username / token for secret\";\n\nconst SSH_MSG_ERR: &str = \"SSH could not be founded\";\n\n\n\n#[derive(Debug, JsonSchema, Clone, Serialize, Deserialize)]\n\npub struct Repository {\n\n pub url: String,\n\n pub credentials: Option<RepositoryCredentials>\n\n}\n\n\n\n#[derive(Debug, JsonSchema, Clone, Serialize, Deserialize)]\n\npub struct RepositoryCredentials {\n\n pub username: Option<GenericConfig>,\n\n pub token: Option<GenericConfig>,\n", "file_path": "gen/src/crd/repo.rs", "rank": 36, "score": 19.851645679460457 }, { "content": "use serde::{Deserialize, Serialize};\n\nuse schemars::JsonSchema;\n\nuse kube::{Client, Api};\n\nuse k8s_openapi::api::core::v1::Secret;\n\nuse crate::util;\n\nuse crate::err::Error;\n\n\n\n// Constant\n\nconst MISSING_SECRET_MSG_ERR: &str = \"Secret has not been specified\";\n\n\n\n#[derive(Debug, Serialize, Deserialize, Clone, JsonSchema, Default)]\n\npub struct GenericConfig {\n\n #[serde(rename = \"secretName\")]\n\n pub secret_name: Option<String>,\n\n pub key: Option<String>,\n\n pub literal: Option<String>\n\n}\n\n\n\nimpl GenericConfig {\n\n /// Get the value from a secret or a literal value\n", "file_path": "gen/src/crd/secret.rs", "rank": 37, "score": 18.480901149427268 }, { "content": "use std::fs;\n\nuse std::path::{Path, PathBuf};\n\nuse std::process::Command;\n\nuse serde::{Serialize, Deserialize};\n\nuse crate::err::Error;\n\nuse crate::helper;\n\nuse crate::env::GitCredentials;\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum Credentials {\n\n Token(String, String),\n\n Ssh(String),\n\n Empty\n\n}\n\n\n\nimpl Default for Credentials {\n\n fn default() -> Self {\n\n Credentials::Empty\n\n }\n\n}\n", "file_path": "krapao/src/repo/config.rs", "rank": 38, "score": 17.60239676399837 }, { "content": "/// List of previous statuses...\n\n#[derive(Debug, Serialize, Deserialize, Clone, JsonSchema, Default)]\n\npub struct DecryptorStatus {\n\n pub current: Status,\n\n pub history: Option<VecDeque<Status>>,\n\n}\n\n\n\n#[derive(Debug, JsonSchema, Clone, Serialize, Deserialize, PartialEq)]\n\npub enum SyncStatus {\n\n Sync,\n\n NotSync\n\n}\n\n\n\nimpl Default for SyncStatus {\n\n fn default() -> Self {\n\n SyncStatus::Sync\n\n }\n\n}\n\n\n\n#[derive(Debug, JsonSchema, Clone, Serialize, Deserialize, PartialEq, Default)]\n", "file_path": "gen/src/crd/status.rs", "rank": 39, "score": 17.014503496860268 }, { "content": "use std::path::PathBuf;\n\n\n\nuse dirs::home_dir;\n\nuse serde::Deserialize;\n\nuse rand::Rng;\n\nuse crate::server::service::repo::proto::Payload;\n\n\n\n// Constant\n\nconst REPOSITORY_PATH: &str = \"workspace/repo\";\n\n\n\n#[derive(Debug, Default, Deserialize)]\n\npub struct GitCredentials {\n\n pub username: Option<String>,\n\n pub token: Option<String>,\n\n pub repository: String,\n\n pub target: PathBuf,\n\n pub ssh: Option<String>,\n\n pub sync_interval: Option<u64>\n\n}\n\n\n", "file_path": "krapao/src/env.rs", "rank": 40, "score": 16.459852610111717 }, { "content": "use tonic::{async_trait, Response, Status, Request};\n\nuse self::proto::{\n\n repo_service_server::RepoService,\n\n Payload,\n\n Response as ProtoResponse,\n\n};\n\nuse crate::repo;\n\nuse crate::env::GitCredentials;\n\nuse crate::state;\n\nuse crate::err::Error;\n\n\n\npub mod proto {\n\n tonic::include_proto!(\"repository\");\n\n}\n\n\n\n#[derive(Debug, Default, Clone)]\n\npub struct RepoHandler {\n\n pub state: state::State\n\n}\n\n\n", "file_path": "krapao/src/server/service/repo.rs", "rank": 41, "score": 16.278352947664807 }, { "content": "use tokio::time::{sleep, Duration};\n\nuse crate::err::Error;\n\nuse crate::state::State;\n\n\n\n// constant\n\nconst THREAD_SLEEP: u64 = 180;\n\n\n\n/// Synchronize the list of repository which is stored in the State\n\n/// Synchronization happened every 3min.\n\n/// Each repo is updated in it's own thread. Sync is also done at the startup of krapao.\n\n/// This is useful in case if the statefulset is restarting\n\n/// \n\n/// # Arguments\n\n/// * `state` - State\n\npub async fn synchronize_repository(state: State) -> Result<(), Error> {\n\n loop {\n\n let guard = state.lock()\n\n .map_err(|err| Error::Sync(err.to_string()))?;\n\n\n\n for (_, config) in guard.clone().into_iter() {\n", "file_path": "krapao/src/sync/mod.rs", "rank": 42, "score": 16.100030628567072 }, { "content": "use tonic::{async_trait, Response, Status, Request};\n\nuse self::proto::{\n\n crd_service_server::CrdService,\n\n Response as ProtoResponse,\n\n Payload,\n\n};\n\nuse crate::state;\n\nuse crate::err::Error;\n\nuse crate::sops;\n\nuse crate::auth::Provider;\n\n\n\n// Constant\n\nconst REPO_NOT_EXIST_ERR_MSG: &str = \"Repository does not exist\";\n\n\n\npub mod proto {\n\n tonic::include_proto!(\"crd\");\n\n}\n\n\n\n#[derive(Debug, Default, Clone)]\n\npub struct CrdHandler {\n", "file_path": "krapao/src/server/service/crd.rs", "rank": 43, "score": 15.693708181778964 }, { "content": "use kube::Client;\n\nuse schemars::JsonSchema;\n\nuse serde::{Serialize, Deserialize};\n\nuse async_trait::async_trait;\n\nuse super::secret::GenericConfig;\n\nuse crate::err::Error;\n\n\n\n#[derive(Debug, PartialEq)]\n\npub enum ProviderList {\n\n Gcp(String),\n\n Aws(String, String, String),\n\n Pgp(String),\n\n Vault(String),\n\n None\n\n}\n\n\n\n#[derive(Debug, JsonSchema, Serialize, Deserialize, Clone)]\n\npub struct GcpCredentials {\n\n #[serde(rename = \"serviceAccount\")]\n\n pub service_account: GenericConfig\n", "file_path": "gen/src/crd/provider.rs", "rank": 44, "score": 15.496776639013403 }, { "content": "#[derive(Default, Debug, Clone, Serialize, Deserialize)]\n\npub struct GitConfig {\n\n auth_method: Credentials,\n\n pub repo_uri: String,\n\n pub target: PathBuf\n\n}\n\n\n\nimpl GitConfig {\n\n /// Create a new GitConfig handler\n\n /// \n\n /// # Arguments\n\n /// * `auth_method` - Credentials\n\n /// * `repo_uri` - &str\n\n /// * `target` - PathBuf\n\n pub fn new(auth_method: Credentials, repo_uri: &str, target: PathBuf) -> Result<Self, Error> {\n\n if repo_uri.is_empty() {\n\n return Err(Error::EmptyRepoURI);\n\n }\n\n \n\n Ok(GitConfig {\n", "file_path": "krapao/src/repo/config.rs", "rank": 45, "score": 15.486818113505013 }, { "content": "/// or not. If the id is similar we'll skip the update of the status\n\n/// \n\n/// # Why watching the Decryptor resource ?\n\n/// Using a watcher enabled to process the Decryptor object. This allows us to then\n\n/// - Retrieve the Decryptor struct\n\n/// - Clone the repository specified\n\n/// - Decrypt the file specified in the spec\n\n/// - Apply the file in the Cluster \n\n/// \n\n/// # Arguments\n\n/// * `state` - State\n\npub async fn boostrap_watcher(state: state::State) -> Result<(), Error> {\n\n info!(\"Starting up the controller...\");\n\n info!(\"Initializing client\");\n\n let client = Client::try_default().await?;\n\n \n\n // Watch the Decryptor ressources\n\n let api: Api<Decryptor> = Api::all(client.clone());\n\n let mut watcher = watcher(api, ListParams::default()).boxed();\n\n\n", "file_path": "miwen/src/watcher/mod.rs", "rank": 46, "score": 15.290514277050379 }, { "content": "use std::fs;\n\nuse serde::Serialize;\n\nuse crate::err::Error;\n\nuse crate::helper;\n\n\n\n// Constant\n\nconst AWS_CONFIG_FOLDER: &str = \".aws\";\n\nconst AWS_CREDENTIALS_PATH: &str = \"credentials\";\n\nconst AWS_REGION_PATH: &str = \"config\";\n\nconst AWS_OUTPUT: &str = \"json\";\n\n\n\n#[derive(Serialize, Default)]\n", "file_path": "krapao/src/auth/aws.rs", "rank": 47, "score": 15.106677545236108 }, { "content": "use core::fmt;\n\nuse kube::Error as KubeError;\n\nuse gen::err::Error as GenError;\n\n\n\n#[derive(Debug)]\n\npub enum Error {\n\n KubeAuthentication,\n\n KubeRuntime(String),\n\n Generator(String),\n\n Watch(String),\n\n Serialize,\n\n Rpc(String),\n\n Apply(String)\n\n}\n\n\n\nimpl fmt::Display for Error {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match self {\n\n Error::KubeAuthentication => write!(f, \"Unable to authenticate with Kubernetes\"),\n\n Error::KubeRuntime(msg) => write!(f, \"Unexpected error with the controller: {msg}\"),\n", "file_path": "miwen/src/err.rs", "rank": 48, "score": 14.1729607928104 }, { "content": "} \n\n\n\n#[async_trait]\n\npub(crate) trait AsyncTryFrom {\n\n type Error;\n\n type Output;\n\n\n\n /// Convert a Credential to a ProviderList. Because async method can't be used on trait. We have to implement a From\n\n /// method with async_trait crate\n\n /// \n\n /// # Arguments\n\n /// * `&self` - &Self\n\n /// * `client` - Client\n\n /// * `ns` - &str\n\n async fn convert(&self, client: Client, ns: &str) -> Result<Self::Output, Self::Error>;\n\n}\n\n\n\n#[async_trait]\n\nimpl AsyncTryFrom for GcpCredentials {\n\n type Error = Error;\n", "file_path": "gen/src/crd/provider.rs", "rank": 49, "score": 14.0863352470407 }, { "content": "use std::collections::VecDeque;\n\n\n\nuse schemars::JsonSchema;\n\nuse serde::{Serialize, Deserialize};\n\nuse kube::{\n\n CustomResource,\n\n CustomResourceExt,\n\n Client,\n\n Api,\n\n api::{Patch, PatchParams},\n\n};\n\nuse status::DecryptorStatus;\n\nuse crate::err::Error;\n\nuse provider::AsyncTryFrom;\n\nuse self::status::Status;\n\n\n\npub mod status;\n\npub mod repo;\n\npub mod provider;\n\npub mod secret;\n", "file_path": "gen/src/crd/mod.rs", "rank": 50, "score": 13.168790079272508 }, { "content": "use tonic::transport::Server;\n\nuse crate::err::Error;\n\nuse crate::state::State;\n\nuse self::service::repo::{\n\n proto::repo_service_server::RepoServiceServer,\n\n RepoHandler\n\n};\n\nuse self::service::crd::{\n\n proto::crd_service_server::CrdServiceServer,\n\n CrdHandler\n\n};\n\n\n\npub mod service;\n\n\n\n/// Initialize the gRPC server\n\n/// The server is used to communicate with the controller\n\n/// \n\n/// # Arguments\n\n/// * `state` - State\n\npub async fn bootstrap_server(state: State) -> Result<(), Error> {\n", "file_path": "krapao/src/server/mod.rs", "rank": 51, "score": 12.698859009618332 }, { "content": " vault: Option<provider::VaultCredentials>\n\n}\n\n\n\n\n\n#[derive(Debug, JsonSchema, Clone, Serialize, Deserialize)]\n\npub struct Source {\n\n pub repository: repo::Repository,\n\n #[serde(rename = \"fileToDecrypt\")]\n\n pub file_to_decrypt: String,\n\n #[serde(rename = \"sopsPath\")]\n\n pub sops_path: String\n\n}\n\n\n\n/// Generate a CRD which is used to be applied in a Kubernetes cluster\n\n/// The final example of how the crd looks can be founded on the example folder\n", "file_path": "gen/src/crd/mod.rs", "rank": 52, "score": 12.477615338075749 }, { "content": "\n\nimpl Payload {\n\n /// Create a new Payload\n\n /// \n\n /// # Arguments\n\n /// * `spec` - &DecryptorSpec\n\n /// * `ns` - &str\n\n async fn new(spec: &DecryptorSpec, ns: &str) -> Result<Self, Error> {\n\n let repository = spec.source.repository.url.to_owned();\n\n let file_to_decrypt = spec.source.file_to_decrypt.to_owned();\n\n let sops_file_path = spec.source.sops_path.to_owned();\n\n \n\n // get the auth provider from the crd\n\n let provider = spec.provider.to_owned();\n\n let credentials = provider.get_credentials(ns).await?;\n\n let mut payload = Payload {\n\n file_to_decrypt,\n\n sops_file_path,\n\n repository,\n\n ..Default::default()\n", "file_path": "miwen/src/client/crd.rs", "rank": 53, "score": 12.239127703297507 }, { "content": "use kube::{\n\n Api,\n\n Client,\n\n api::ListParams\n\n};\n\nuse kube::runtime::{\n\n watcher,\n\n watcher::Event\n\n};\n\nuse gen::crd::{\n\n Decryptor,\n\n status::{SyncStatus, DecryptorStatus}\n\n};\n\nuse futures::{TryStreamExt, StreamExt};\n\nuse crate::err::Error;\n\nuse crate::state;\n\nuse crate::client::{server, crd};\n\n\n\npub mod apply;\n\n\n", "file_path": "miwen/src/watcher/mod.rs", "rank": 54, "score": 12.191528198034725 }, { "content": "#[async_trait]\n\nimpl RepoService for RepoHandler {\n\n /// Configure a new repository in the krapao project.\n\n /// We're:\n\n /// - Add the repository in the list of repos to listen\n\n /// - Store the repository in a persistent state & tempo state\n\n /// - Clone the repository\n\n /// - Store the state which can be used by an async task run in parallel with the gRPC server\n\n /// \n\n /// # Arguments\n\n /// * `&self` - Self\n\n /// * `request` - Request<Payload>\n\n async fn set_repository(\n\n &self,\n\n request: Request<Payload>\n\n ) -> Result<Response<ProtoResponse>, Status> {\n\n let input = request.into_inner();\n\n // retrieve the env from the request\n\n let env = GitCredentials::from(input);\n\n // retrieve the state\n", "file_path": "krapao/src/server/service/repo.rs", "rank": 55, "score": 12.18433211441853 }, { "content": " // in this case we're going to trigger the creation of a new repo\n\n }\n\n\n\n /// Delete a repository from the list of repository\n\n /// - Remove the repo from the list of repo\n\n /// - Remove the repo from the persistent state\n\n /// - Delete the repository\n\n /// \n\n /// # Arguments\n\n /// * `self` - Self\n\n /// * `request` - Request<Payload>\n\n async fn delete_repository(\n\n &self,\n\n request: Request<Payload>\n\n ) -> Result<Response<ProtoResponse>, Status> {\n\n let input = request.into_inner();\n\n // convert the input as an Env\n\n let env = GitCredentials::from(input);\n\n // get the state\n\n let mut state = self.state.lock()\n", "file_path": "krapao/src/server/service/repo.rs", "rank": 56, "score": 11.813857571732955 }, { "content": " }\n\n}\n\n\n\n#[async_trait]\n\nimpl AsyncTryFrom for PgpCredentials {\n\n type Error = Error;\n\n type Output = ProviderList;\n\n\n\n async fn convert(&self, client: Client, ns: &str) -> Result<Self::Output, Self::Error> {\n\n let key = self.private_key.get_value(&client, ns).await?;\n\n\n\n Ok(ProviderList::Pgp(key))\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl AsyncTryFrom for VaultCredentials {\n\n type Error = Error;\n\n type Output = ProviderList;\n\n\n\n async fn convert(&self, client: Client, ns: &str) -> Result<Self::Output, Self::Error> {\n\n let token = self.token.get_value(&client, ns).await?;\n\n\n\n Ok(ProviderList::Vault(token))\n\n }\n\n}", "file_path": "gen/src/crd/provider.rs", "rank": 57, "score": 11.752252555207194 }, { "content": " pub state: state::State\n\n}\n\n\n\n#[async_trait]\n\nimpl CrdService for CrdHandler {\n\n async fn render(\n\n &self,\n\n request: Request<Payload>\n\n ) -> Result<Response<ProtoResponse>, Status> {\n\n let input = request.into_inner();\n\n // get a lock and retrieve the state\n\n let guard = self.state.lock()\n\n .map_err(|err| Error::Server(err.to_string()))?;\n\n\n\n let config = guard.get(&input.repository)\n\n .ok_or_else(|| Error::Server(REPO_NOT_EXIST_ERR_MSG.to_owned()))?;\n\n\n\n let provider = Provider::new(&input);\n\n provider.authenticate()?;\n\n\n", "file_path": "krapao/src/server/service/crd.rs", "rank": 58, "score": 11.62488752727838 }, { "content": "/// Parse the decryptor struct which we're going to use to add the Status structure\n\n/// \n\n/// # Arguments\n\n/// * `mut decryptor` - Decryptor\n\n/// * `client` - Client\n\n/// * `state` - State \n\nasync fn parse_update_of_crd(mut decryptor: Decryptor, client: Client, state: state::State) -> Result<(), Error> {\n\n let (name, generation_id, ns) = decryptor.get_metadata_info()?;\n\n info!(\"ℹ️ Change has been detected on {name}\");\n\n\n\n // If the resource is not registered in the state, then this mean that the repository\n\n // might not be pulled. In that case we call the rpc server to pull the repository\n\n if !state::is_registered(state.clone(), &name)? {\n\n // proceed to call the grpc api to pull the repo\n\n server::dispatch_clone_repository(&decryptor.spec, &client, &ns).await?;\n\n }\n\n\n\n // In order to not create an infinite loop of update...\n\n // we're checking the generation_id\n\n let generation_exist = state::upsert_state(state, &name, generation_id)?;\n", "file_path": "miwen/src/watcher/mod.rs", "rank": 59, "score": 11.518170778893102 }, { "content": "\n\n// Constant\n\nconst DEFAULT_NAMESPACE: &str = \"default\";\n\n\n\n// The implementation is based on\n\n//\n\n// - https://github.com/kube-rs/kube-rs/blob/bf3b248f0c96b229863e0bff510fdf118efd2381/examples/crd_apply.rs\n\n#[derive(Debug, CustomResource, Serialize, Deserialize, Clone, JsonSchema)]\n\n#[kube(status = \"DecryptorStatus\")]\n\n#[kube(group = \"jiemi.cr\", version = \"v1alpha1\", kind = \"Decryptor\", namespaced)]\n\npub struct DecryptorSpec {\n\n pub provider: Provider,\n\n pub source: Source\n\n}\n\n\n\n#[derive(Debug, JsonSchema, Clone, Serialize, Deserialize)]\n\npub struct Provider {\n\n gcp: Option<provider::GcpCredentials>,\n\n aws: Option<provider::AwsCredentials>,\n\n pgp: Option<provider::PgpCredentials>,\n", "file_path": "gen/src/crd/mod.rs", "rank": 60, "score": 11.357926585276864 }, { "content": "use kube::{\n\n Api,\n\n Client,\n\n core::{\n\n DynamicObject,\n\n GroupVersionKind,\n\n ApiResource, ObjectMeta,\n\n },\n\n api::{\n\n PatchParams,\n\n Patch,\n\n PostParams\n\n },\n\n};\n\nuse serde::Deserialize;\n\nuse crate::err::Error;\n\n\n\n// Constant\n\nconst API_GROUP_SPLIT: &str = \"/\";\n\nconst MISSING_NAME_ERR: &str = \"❌ Provided resource does not have a name\";\n\n\n\n#[derive(Deserialize, Debug)]\n", "file_path": "miwen/src/watcher/apply.rs", "rank": 61, "score": 11.262980513363036 }, { "content": " pub ssh: Option<GenericConfig>\n\n}\n\n\n\nimpl RepositoryCredentials {\n\n /// Retrieve the GIT credentials for the field:\n\n /// - username\n\n /// - token\n\n /// \n\n /// \n\n /// # Arguments\n\n /// * `&self` - Self\n\n /// * `client` - &Client\n\n /// * `ns` - &str\n\n pub async fn get_token_creds(&self, client: &Client, ns: &str) -> Result<(String, String), Error> {\n\n let creds = self.username.as_ref().zip(self.token.as_ref());\n\n if let Some((u, t)) = creds {\n\n let username = match u.get_value(client, ns).await {\n\n Ok(u) => u,\n\n Err(err) => return Err(err)\n\n };\n", "file_path": "gen/src/crd/repo.rs", "rank": 62, "score": 11.192660253258337 }, { "content": "use crate::err::Error;\n\nuse crate::env::GitCredentials;\n\nuse self::config::{Credentials, GitConfig};\n\n\n\npub mod config;\n\n\n\n/// Initialize the git repository handler\n\n/// \n\n/// # Arguments\n\n/// * `env` - &GitCredentials\n", "file_path": "krapao/src/repo/mod.rs", "rank": 63, "score": 11.138280980273752 }, { "content": "use std::time::Duration;\n\nuse gen::crd::{DecryptorSpec, repo::RepositoryCredentials};\n\nuse kube::Client;\n\nuse tonic::Request;\n\nuse crate::err::Error;\n\nuse self::proto::{\n\n repo_service_client::RepoServiceClient,\n\n Payload,\n\n Credentials\n\n};\n\nuse super::REQUEST_TIMEOUT;\n\n\n\nmod proto {\n\n tonic::include_proto!(\"repository\");\n\n}\n\n\n\nimpl Credentials {\n\n /// Build the credentials needed to clone the repository\n\n /// \n\n /// # Arguments\n", "file_path": "miwen/src/client/server.rs", "rank": 64, "score": 10.974225688760832 }, { "content": "\n\n/// Dispatch to krapao rpc server the repository to clone\n\n/// - Build credentials needed for krapao to clone the repository if needed\n\n/// \n\n/// # Arguments\n\n/// * `spec` - &DecryptorSpec\n\n/// * `kube_client` - &Client\n\n/// * `ns` - &str\n\npub async fn dispatch_clone_repository(spec: &DecryptorSpec, kube_client: &Client, ns: &str) -> Result<(), Error> {\n\n info!(\"Rpc call to clone the target repository...\");\n\n let mut client = RepoServiceClient::connect(super::get_rpc_addr()).await?;\n\n // request to grpc server\n\n // build credentials\n\n let spec_creds = spec.source.repository.credentials.clone();\n\n let cred = match spec_creds {\n\n Some(res) => Some(Credentials::build(res, kube_client, ns).await?),\n\n None => None\n\n };\n\n\n\n let mut req = Request::new(Payload {\n", "file_path": "miwen/src/client/server.rs", "rank": 65, "score": 10.730912499386466 }, { "content": "// This mod is used to pull changes from the repository\n\n// from time to time and check whenever we need to update the resoruces\n\nuse kube::{Api, Client};\n\nuse kube::api::ListParams;\n\nuse gen::crd::status::{DecryptorStatus, SyncStatus};\n\nuse gen::crd::Decryptor;\n\nuse tokio::time::sleep;\n\nuse std::time::Duration;\n\nuse futures::future::try_join_all;\n\nuse crate::err::Error;\n\nuse crate::client::crd;\n\nuse crate::watcher::apply;\n\n\n\n// constant\n\nconst THREAD_SLEEP: u64 = 180;\n\n\n\n/// Bootstrap the repo sync process\n\n/// It runs every 180s / 3min\n\npub async fn bootstrap_repo_sync() -> Result<(), Error> {\n\n info!(\"Starting up sync process\");\n", "file_path": "miwen/src/sync/mod.rs", "rank": 66, "score": 10.72603369045012 }, { "content": "use std::{env, fs};\n\nuse crate::err::Error;\n\n\n\n// Constant\n\nconst ENV_NAME: &str = \"GOOGLE_APPLICATION_CREDENTIALS\";\n\nconst FILENAME: &str = \"../credentials.json\";\n\n\n\n/// Set the authentication file for Google Cloud Project\n\n/// This is going to be used by sops in order to decrypt the file\n\n/// \n\n/// # Arguments\n\n/// * `credentials` - &str\n\npub(crate) fn set_authentication_file_for_gcp(credentials: &str) -> Result<(), Error> {\n\n // writing the configuration file\n\n fs::write(\"../credentials.json\", credentials)\n\n .map_err(|err| Error::ProviderAuth(err.to_string()))?;\n\n \n\n env::set_var(ENV_NAME, FILENAME);\n\n\n\n Ok(())\n\n}", "file_path": "krapao/src/auth/gcp.rs", "rank": 67, "score": 10.691150481786906 }, { "content": "use crate::err::Error;\n\n\n\n// Constant\n\nconst VAULT_TOKEN_VAR: &str = \"VAULT_TOKEN\";\n\n\n\n/// Set the vault token in order to authenticate with vault\n\n/// \n\n/// # Arguments\n\n/// * `token` - &str\n\npub(crate) fn set_vault_token(token: &str) -> Result<(), Error> {\n\n std::env::set_var(VAULT_TOKEN_VAR, token);\n\n \n\n Ok(())\n\n}", "file_path": "krapao/src/auth/vault.rs", "rank": 68, "score": 10.681732724751278 }, { "content": "use crate::err::Error;\n\nuse crate::server::service::crd::proto::Payload;\n\n\n\npub mod gcp;\n\npub mod aws;\n\npub mod pgp;\n\npub mod vault;\n\n\n\n// Constant\n\nconst MISSING_PROVIDER_ERR: &str = \"Missing provider\";\n\n\n\n#[derive(Debug)]\n\npub enum Provider {\n\n Gcp(String),\n\n Aws(String, String, String),\n\n Pgp(String),\n\n Vault(String),\n\n None\n\n}\n\n\n", "file_path": "krapao/src/auth/mod.rs", "rank": 69, "score": 10.597738945940325 }, { "content": " let mut state = self.state.lock()\n\n .map_err(|err| Error::Server(err.to_string()))?;\n\n\n\n // if the state is already contain the repository then we don't need to clone it again\n\n if state.contains_key(&env.repository) {\n\n return Ok(Response::new(ProtoResponse {\n\n done: true\n\n }))\n\n }\n\n\n\n // maybe do this async ?\n\n let config = repo::initialize_git(&env)?;\n\n \n\n // add the new git config in the state\n\n state.insert(env.repository, config.clone());\n\n state::save_new_repo_in_persistent_state(config)?;\n\n\n\n Ok(Response::new(ProtoResponse {\n\n done: true\n\n }))\n", "file_path": "krapao/src/server/service/repo.rs", "rank": 70, "score": 10.572923771526042 }, { "content": "impl From<Payload> for GitCredentials {\n\n fn from(p: Payload) -> Self {\n\n let mut rng = rand::thread_rng();\n\n\n\n let mut dir = home_dir().unwrap_or_default();\n\n dir.push(REPOSITORY_PATH);\n\n dir.push(rng.gen::<u32>().to_string());\n\n\n\n let mut env = GitCredentials {\n\n repository: p.url,\n\n target: dir,\n\n sync_interval: Some(1800),\n\n ..Default::default()\n\n };\n\n\n\n // compute the username\n\n if let Some(creds) = p.cred {\n\n env.username = creds.username;\n\n env.token = creds.token;\n\n env.ssh = creds.ssh;\n\n }\n\n\n\n env\n\n }\n\n}", "file_path": "krapao/src/env.rs", "rank": 71, "score": 10.54994038018058 }, { "content": " pub fn add_current_to_history(&mut self) {\n\n if let Some(queue) = self.history.as_mut() {\n\n if queue.len() > MAX_QUEUE_SIZE {\n\n queue.pop_front();\n\n }\n\n\n\n queue.push_back(self.current.clone());\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use kube::core::ObjectMeta;\n\n use kube::{Client, Api};\n\n use crate::crd::{DecryptorSpec, Provider, Source};\n\n use crate::crd::repo::Repository;\n\n use super::super::Decryptor;\n\n use super::*;\n\n\n", "file_path": "gen/src/crd/status.rs", "rank": 72, "score": 10.442228078547942 }, { "content": "}\n\n\n\n#[derive(Debug, JsonSchema, Serialize, Deserialize, Clone)]\n\npub struct AwsCredentials {\n\n #[serde(rename = \"keyId\")]\n\n pub key_id: GenericConfig,\n\n #[serde(rename = \"accessKey\")]\n\n pub access_key: GenericConfig,\n\n pub region: GenericConfig\n\n}\n\n\n\n#[derive(Debug, JsonSchema, Serialize, Deserialize, Clone)]\n\npub struct PgpCredentials {\n\n #[serde(rename = \"privateKey\")]\n\n pub private_key: GenericConfig\n\n}\n\n\n\n#[derive(Debug, JsonSchema, Serialize, Deserialize, Clone)]\n\npub(crate) struct VaultCredentials {\n\n pub token: GenericConfig\n", "file_path": "gen/src/crd/provider.rs", "rank": 73, "score": 10.25642790672288 }, { "content": " /// * `rep` - RepositoryCredentials\n\n /// * `client` - &Client\n\n /// * `ns` - &str\n\n async fn build(rep: RepositoryCredentials, client: &Client, ns: &str) -> Result<Self, Error> {\n\n if rep.ssh.is_some() {\n\n let res = rep.get_ssh(client, ns).await?;\n\n return Ok(Credentials {\n\n ssh: Some(res),\n\n ..Default::default()\n\n });\n\n }\n\n\n\n let (username, token) = rep.get_token_creds(client, ns).await?;\n\n Ok(Credentials {\n\n username: Some(username),\n\n token: Some(token),\n\n ..Default::default()\n\n })\n\n }\n\n}\n", "file_path": "miwen/src/client/server.rs", "rank": 74, "score": 10.173055116532591 }, { "content": " type Output = ProviderList;\n\n\n\n async fn convert(&self, client: Client, ns: &str) -> Result<Self::Output, Self::Error> {\n\n let value = self.service_account.get_value(&client, ns).await?;\n\n\n\n Ok(ProviderList::Gcp(value))\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl AsyncTryFrom for AwsCredentials {\n\n type Error = Error;\n\n type Output = ProviderList;\n\n\n\n async fn convert(&self, client: Client, ns: &str) -> Result<Self::Output, Self::Error> {\n\n let id = self.key_id.get_value(&client, ns).await?;\n\n let key = self.access_key.get_value(&client, ns).await?;\n\n let region = self.region.get_value(&client, ns).await?;\n\n\n\n Ok(ProviderList::Aws(id, key, region))\n", "file_path": "gen/src/crd/provider.rs", "rank": 75, "score": 10.031028665217837 }, { "content": "}\n\n\n\nimpl std::fmt::Display for Error {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n match &self {\n\n Error::Auth(msg) => write!(f, \"Unable to authenticate reasons: {msg}\"),\n\n Error::EmptyRepoURI => write!(f, \"Unable to clone repository. Url is empty\"),\n\n Error::MalformattedURI => write!(f, \"Repository URL is malformatted\"),\n\n Error::Clone(msg) => write!(f, \"Error while cloning repository {msg}\"),\n\n Error::Config(msg) => write!(f, \"Unable to parse the configuration spec to bootstrap service {msg}\"),\n\n Error::Pull(msg) => write!(f, \"Unable to pull repository changes {msg}\"),\n\n Error::RefreshDuration => write!(f, \"Refresh interval is inferior to 180 seconds / 3 min\"),\n\n Error::MaxPullRetry => write!(f, \"Failed to refresh repository after retrying 20 times\"),\n\n Error::Server(msg) => write!(f, \"gRPC server error: {msg}\"),\n\n Error::Bootstrap(msg) => write!(f, \"Initialization problem. State can't be recovered {msg}\"),\n\n Error::Sync(msg) => write!(f, \"Issue while syncing repositories {msg}\"),\n\n Error::Sops(msg) => write!(f, \"Error with SOPS: {msg}\"),\n\n Error::Encoding(msg) => write!(f, \"Error while encoding data: {msg}\"),\n\n Error::Io(msg) => write!(f, \"Error while processing doing I/O: {msg}\"),\n\n Error::ProviderAuth(msg) => write!(f, \"Error while authenticating with provider to decrypt SOPS file: {msg}\")\n", "file_path": "krapao/src/err.rs", "rank": 76, "score": 9.884868964721537 }, { "content": " }\n\n }\n\n\n\n info!(\"No change detected for {filename}\");\n\n\n\n Ok(())\n\n}\n\n\n\n/// Get a list of Crd. The list is used to get the file to apply on the cluster\n\n/// We're assuming that the repo is being already pulled...\n\n/// \n\n/// # Arguments\n\n/// * `client` - Client\n\nasync fn list_crd(client: Client) -> Result<Vec<Decryptor>, Error> {\n\n let api: Api<Decryptor> = Api::all(client);\n\n let mut list = Vec::new();\n\n\n\n for crd in api.list(&ListParams::default()).await? {\n\n list.push(crd);\n\n }\n", "file_path": "miwen/src/sync/mod.rs", "rank": 77, "score": 9.842208820367535 }, { "content": "use std::{fs, env};\n\nuse std::os::unix::fs::PermissionsExt;\n\nuse std::path::Path;\n\nuse std::io::ErrorKind;\n\nuse super::err::Error;\n\n\n\n// Constant\n\nconst SSH_KEYPATH: &str = \"../../id_rsa\";\n\nconst SSH_GIT_ENV: &str = \"GIT_SSH_COMMAND\";\n\n\n\n/// Create / Overwrite the SSH key\n\n/// \n\n/// # Arguments\n\n/// * `key` - &str\n", "file_path": "krapao/src/helper.rs", "rank": 78, "score": 9.838013169685 }, { "content": "impl From<GenError> for Error {\n\n fn from(err: GenError) -> Self {\n\n Error::Generator(err.to_string())\n\n }\n\n}\n\n\n\nimpl From<kube::runtime::watcher::Error> for Error {\n\n fn from(err: kube::runtime::watcher::Error) -> Self {\n\n Error::Watch(err.to_string())\n\n }\n\n}\n\n\n\nimpl From<serde_json::Error> for Error {\n\n fn from(_: serde_json::Error) -> Self {\n\n Error::Serialize\n\n }\n\n}\n\n\n\nimpl From<tonic::transport::Error> for Error {\n\n fn from(err: tonic::transport::Error) -> Self {\n", "file_path": "miwen/src/err.rs", "rank": 79, "score": 9.808689271166271 }, { "content": " .map_err(|err| Error::Server(err.to_string()))?;\n\n\n\n if state.contains_key(&env.repository) {\n\n let config = state.remove(&env.repository);\n\n if let Some(git) = config {\n\n // remove the value from the persistent state\n\n state::remove_repo_from_persistent_state(&env.repository)?;\n\n git.delete_repository()?;\n\n }\n\n } else {\n\n info!(\"No repository to delete\");\n\n }\n\n\n\n Ok(Response::new(ProtoResponse {\n\n done: true,\n\n }))\n\n }\n\n}\n", "file_path": "krapao/src/server/service/repo.rs", "rank": 80, "score": 9.6749377307022 }, { "content": "#[derive(Debug)]\n\npub enum Error {\n\n MissingMetadata(String),\n\n Kube(String),\n\n DecodedBytes(String),\n\n Encoding(String)\n\n}\n\n\n\nimpl std::fmt::Display for Error {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n match self {\n\n Error::MissingMetadata(key) => write!(f, \"Key: {key} is not present within the metadata\"),\n\n Error::Kube(msg) => write!(f, \"Error while looking for kube resource {msg}\"),\n\n Error::DecodedBytes(msg) => write!(f, \"Unable to decoded bytes for reasons: {msg}\"),\n\n Error::Encoding(msg) => write!(f, \"Unable to encoded value to json: {msg}\")\n\n }\n\n }\n\n}\n\n\n\nimpl std::error::Error for Error {}\n", "file_path": "gen/src/err.rs", "rank": 81, "score": 9.550273092267465 }, { "content": " Error::Rpc(err.to_string())\n\n }\n\n}\n\n\n\nimpl From<serde_yaml::Error> for Error {\n\n fn from(_: serde_yaml::Error) -> Self {\n\n Error::Apply(\"Unable to decrypt the resource from the repository\".to_owned())\n\n }\n\n}\n", "file_path": "miwen/src/err.rs", "rank": 82, "score": 9.43509609843381 }, { "content": "use std::collections::VecDeque;\n\nuse schemars::JsonSchema;\n\nuse serde::{Serialize, Deserialize};\n\nuse chrono::Utc;\n\n\n\n// constant\n\nconst MAX_QUEUE_SIZE: usize = 10;\n\n\n\n/// Status field of the CRD. It represent the Sync status of the CRD. See below to see how it looks\n\n/// \n\n/// # Example\n\n/// Status:\n\n/// Current:\n\n/// deployed_at: 2022-03-03T20:37:59.024362965+00:00\n\n/// error_message: <nil>\n\n/// file_to_decrypt: pgp/secret.enc.yaml\n\n/// Id: 1\n\n/// Revision: a888f02e1111beb2c543d729faa5d516ecaa9e12\n\n/// Status: Sync\n\n/// History:\n", "file_path": "gen/src/crd/status.rs", "rank": 83, "score": 9.264411259139308 }, { "content": "pub struct Status {\n\n deployed_at: String,\n\n pub id: u64,\n\n pub revision: String,\n\n pub file_to_decrypt: String,\n\n status: SyncStatus,\n\n error_message: Option<String>\n\n}\n\n\n\nimpl DecryptorStatus {\n\n /// Create a new Decryptor Status struct. This status is used by the Controller to update the k8s status\n\n /// \n\n /// # Arguments\n\n /// * `status` - SyncStatus\n\n /// * `err` - Option<String>\n\n /// * `revision` - String\n\n pub fn new(\n\n status: SyncStatus,\n\n err: Option<String>,\n\n revision: Option<String>,\n", "file_path": "gen/src/crd/status.rs", "rank": 84, "score": 9.189113197870682 }, { "content": " Error::Generator(msg) => write!(f, \"Error encountered while processing the Decryptor spec: {msg}\"),\n\n Error::Watch(msg) => write!(f, \"Error while watching the decryptor resource {msg}\"),\n\n Error::Serialize => write!(f, \"Error while serializing the Status\"),\n\n Error::Rpc(msg) => write!(f, \"Error while communicating with rpc server {msg}\"),\n\n Error::Apply(msg) => write!(f, \"Error while applying rendered resource from repo: {msg}\")\n\n }\n\n }\n\n}\n\n\n\nimpl std::error::Error for Error {}\n\n\n\nimpl From<KubeError> for Error {\n\n fn from(err: KubeError) -> Self {\n\n match err {\n\n KubeError::Auth(_) => Error::KubeAuthentication,\n\n _ => Error::KubeRuntime(err.to_string())\n\n }\n\n }\n\n}\n\n\n", "file_path": "miwen/src/err.rs", "rank": 85, "score": 9.14511312552849 }, { "content": " let res = conf.get_value(client, ns).await?;\n\n return Ok(res);\n\n }\n\n\n\n Err(Error::Kube(SSH_MSG_ERR.to_owned()))\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n fn get_credentials() -> RepositoryCredentials {\n\n RepositoryCredentials {\n\n username: Some(GenericConfig {\n\n literal: Some(\"username\".to_owned()),\n\n ..Default::default()\n\n }),\n\n token: Some(GenericConfig {\n\n literal: Some(\"token\".to_owned()),\n", "file_path": "gen/src/crd/repo.rs", "rank": 86, "score": 9.100948215621997 }, { "content": " loop {\n\n sleep(Duration::from_secs(THREAD_SLEEP)).await;\n\n\n\n tokio::spawn(async move {\n\n info!(\"Sync process is running...\");\n\n if let Err(err) = sync_encrypted_file_with_git().await {\n\n error!(\"Error while syncing repository with cluster: {}\", err.to_string());\n\n }\n\n });\n\n }\n\n} \n\n\n\n/// Synchronize encrypted file specified in the CRD with the associated repository\n\n/// Basically, we're comparing the commit hash of the last sync with the current hash in the\n\n/// repository.\n\n/// If the hash is different, then we may synchronize the file with the cluster\n\nasync fn sync_encrypted_file_with_git() -> Result<(), Error> {\n\n let client = Client::try_default().await?;\n\n let crds = list_crd(client.clone()).await?;\n\n\n", "file_path": "miwen/src/sync/mod.rs", "rank": 87, "score": 9.037859934121142 }, { "content": "use std::process::Command;\n\nuse std::fs;\n\nuse crate::err::Error;\n\n\n\n// Constant\n\nconst KEY_FILE_PATH: &str = \"../private.rsa\";\n\nconst GPG_AUTH_ERR: &str = \"Unable to verify the imported private key\";\n\n\n\n/// Authenticate with pgp by creating the private.rsa key and then \n\n/// importing the key with the gpg command\n\n/// \n\n/// # Arguments\n\n/// * `key` - &str\n", "file_path": "krapao/src/auth/pgp.rs", "rank": 88, "score": 9.018804566705558 }, { "content": "use std::process::Command;\n\nuse crate::repo::config::GitConfig;\n\nuse crate::err::Error;\n\n\n\n/// Decrypt SOPS file and return the output to the caller\n\n/// \n\n/// # Arguments\n\n/// * `config` - &GitConfig\n\n/// * `target_file_path` - &str\n\n/// * `sops_file_path` - &str\n", "file_path": "krapao/src/sops.rs", "rank": 89, "score": 8.989853110766097 }, { "content": " }\n\n\n\n // clone repository\n\n let status = Command::new(\"git\")\n\n .arg(\"clone\")\n\n .arg(uri)\n\n .arg(&self.target)\n\n .status()?;\n\n \n\n if !status.success() {\n\n return Err(Error::Clone(status.to_string()))\n\n }\n\n\n\n info!(\"Repository has been clone in the path {}\", self.repo_uri);\n\n\n\n Ok(())\n\n }\n\n\n\n /// Delete repository that was clone\n\n pub fn delete_repository(&self) -> Result<(), Error> {\n", "file_path": "krapao/src/repo/config.rs", "rank": 90, "score": 8.908381072061754 }, { "content": " // bootstrap the server\n\n let res = tokio::try_join!(\n\n server::bootstrap_server(state.clone()),\n\n sync::synchronize_repository(state.clone())\n\n );\n\n\n\n match res {\n\n Ok(_) => error!(\"Expect server / watcher to not stop\"),\n\n Err(err) => error!(\"{}\", err.to_string())\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "krapao/src/main.rs", "rank": 91, "score": 8.740678241269705 }, { "content": "\n\n Ok(list)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n \n\n #[tokio::test]\n\n async fn expect_list_crd_to_not_fail() {\n\n let client = Client::try_default().await.unwrap();\n\n let res = list_crd(client).await;\n\n\n\n assert!(res.is_ok());\n\n }\n\n}", "file_path": "miwen/src/sync/mod.rs", "rank": 92, "score": 8.70817926899037 }, { "content": " username: String,\n\n #[serde(rename(deserialize = \"GIT_TOKEN\"))]\n\n token: String,\n\n #[serde(rename(deserialize = \"GIT_SSH_KEY\"))]\n\n ssh: String\n\n }\n\n\n\n /// Load environment variable from the Env.toml file\n\n /// This is only used in the dev environment. this method is only used for local test purposes\n\n /// \n\n /// # Arguments\n\n /// * `&self` - &Env\n\n fn load_local_env() -> Result<TestRepoConfig, Error> {\n\n info!(\"Loading local environment variable\");\n\n let mut settings = Config::default();\n\n settings.merge(File::with_name(\"Env\"))?;\n\n\n\n let env = settings.try_into::<TestRepoConfig>()?;\n\n \n\n Ok(env)\n", "file_path": "krapao/src/repo/config.rs", "rank": 93, "score": 8.629585520347572 }, { "content": " };\n\n\n\n Ok(payload)\n\n }\n\n}\n\n\n\n/// Get the decrypted Kubernetes object from the RPC server\n\n/// \n\n/// # Arguments\n\n/// * `spec` - &DecryptorSpec\n\n/// * `ns` - &str\n\npub async fn get_decrypted_kubernetes_object(spec: &DecryptorSpec, ns: &str) -> Result<(String, String), Error> {\n\n info!(\"Rpc call to retrieve the decrypted kubernetes file...\");\n\n let mut client = CrdServiceClient::connect(super::get_rpc_addr()).await?;\n\n\n\n // create the payload\n\n let payload = Payload::new(spec, ns).await?;\n\n\n\n // create a request and call the rpc server\n\n let mut req = Request::new(payload);\n", "file_path": "miwen/src/client/crd.rs", "rank": 94, "score": 8.519026276417446 }, { "content": " /// \n\n /// # Arguments\n\n /// * `&self` - &Self\n\n pub fn get_metadata_info(&self) -> Result<(String, i64, String), Error> {\n\n let metadata = self.metadata.clone();\n\n\n\n let name = metadata.name\n\n .ok_or_else(|| Error::MissingMetadata(\"name\".to_owned()))?;\n\n let generation_id = metadata.generation\n\n .ok_or_else(|| Error::MissingMetadata(\"generation_id\".to_owned()))?;\n\n let ns = metadata.namespace\n\n .unwrap_or_else(|| DEFAULT_NAMESPACE.to_owned());\n\n\n\n Ok((name, generation_id, ns))\n\n }\n\n\n\n /// Set the status in the current Decryptor crd\n\n /// \n\n /// # Arguments\n\n /// * `&mut self` - &Self\n", "file_path": "gen/src/crd/mod.rs", "rank": 95, "score": 8.456004316229018 }, { "content": " /// * `status` - DecryptorStatus\n\n pub fn set_status(&mut self, mut status: DecryptorStatus) {\n\n // get a new history of the status\n\n let (history, current_status_id) = self.create_new_status_history();\n\n status.history = history;\n\n // set other field which come from the decryptor\n\n status.current.id = current_status_id + 1;\n\n status.current.file_to_decrypt = self.spec.source.file_to_decrypt.to_owned();\n\n \n\n self.status = Some(status);\n\n }\n\n\n\n /// Update the status of the Decrytpro\n\n /// \n\n /// # Arguments\n\n /// * `&self` - &Self\n\n pub async fn update_status(&mut self) -> Result<(), Error> {\n\n let (name, _, ns) = self.get_metadata_info()?;\n\n let client = Client::try_default().await?;\n\n let api = Api::<Decryptor>::namespaced(client.clone(), &ns);\n", "file_path": "gen/src/crd/mod.rs", "rank": 96, "score": 8.385466371624105 }, { "content": "use k8s_openapi::ByteString;\n\nuse crate::err::Error;\n\n\n\n/// Decode a Base64 to a string\n\n///\n\n/// # Arguments\n\n/// * `base` - &ByteString\n\npub(crate) fn decode_byte(base: &ByteString) -> Result<String, Error> {\n\n let value = String::from_utf8(base.0.clone())\n\n .map_err(|err| Error::DecodedBytes(err.to_string()))?;\n\n\n\n Ok(value)\n\n}\n", "file_path": "gen/src/util.rs", "rank": 97, "score": 8.17007335968717 }, { "content": " auth_method,\n\n repo_uri: repo_uri.to_owned(),\n\n target\n\n })\n\n }\n\n\n\n /// Init the repository. Create if the repo exist or just skip it\n\n /// \n\n /// # Arguments\n\n /// * `&self` - &GitConfig\n\n pub fn init_repository(&self) -> Result<(), Error> {\n\n if Path::new(&self.target).is_dir() {\n\n info!(\"Repository exist\");\n\n return Ok(());\n\n }\n\n\n\n // clone the repo\n\n self.clone_repository()\n\n }\n\n\n", "file_path": "krapao/src/repo/config.rs", "rank": 98, "score": 8.14921743408728 }, { "content": "\n\n if !status.success() {\n\n error!(\"Fail to pull repository\");\n\n return Err(Error::Pull(status.to_string()));\n\n }\n\n\n\n info!(\"Local repository cache has been updated\");\n\n Ok(())\n\n }\n\n\n\n /// Get the commit hash from the repository\n\n /// \n\n /// # Arguments\n\n /// * `&self` - &Self\n\n pub fn get_commit_hash(&self) -> Option<String> {\n\n let output = Command::new(\"git\")\n\n .arg(\"-C\")\n\n .arg(self.target.clone())\n\n .arg(\"rev-parse\")\n\n .arg(\"HEAD\")\n", "file_path": "krapao/src/repo/config.rs", "rank": 99, "score": 8.144020555517162 } ]
Rust
src/windows.rs
chadbrewbaker/filebuffer
38193fc0c9cb54363a8dcf59c303a6605e2ba8c5
use std::fs; use std::io; use std::mem; use std::os::windows::io::AsRawHandle; use std::ptr; extern crate winapi; #[derive(Debug)] pub struct PlatformData { #[allow(dead_code)] file: fs::File, mapping_handle: winapi::um::winnt::HANDLE, } impl Drop for PlatformData { fn drop (&mut self) { if self.mapping_handle != ptr::null_mut() { let success = unsafe { winapi::um::handleapi::CloseHandle(self.mapping_handle) }; assert!(success != 0); } } } pub fn map_file(file: fs::File) -> io::Result<(*const u8, usize, PlatformData)> { let file_handle = file.as_raw_handle(); let length = try!(file.metadata()).len(); if length > usize::max_value() as u64 { return Err(io::Error::new(io::ErrorKind::Other, "file is larger than address space")); } let mut platform_data = PlatformData { file: file, mapping_handle: ptr::null_mut(), }; if length == 0 { return Ok((ptr::null(), 0, platform_data)); } platform_data.mapping_handle = unsafe { winapi::um::memoryapi::CreateFileMappingW( file_handle as *mut winapi::ctypes::c_void, ptr::null_mut(), winapi::um::winnt::PAGE_READONLY, 0, 0, ptr::null_mut() ) }; if platform_data.mapping_handle == ptr::null_mut() { return Err(io::Error::last_os_error()); } let result = unsafe { winapi::um::memoryapi::MapViewOfFile( platform_data.mapping_handle, winapi::um::memoryapi::FILE_MAP_READ, 0, 0, length as winapi::shared::basetsd::SIZE_T ) }; if result == ptr::null_mut() { Err(io::Error::last_os_error()) } else { Ok((result as *const u8, length as usize, platform_data)) } } pub fn unmap_file(buffer: *const u8, _length: usize) { let success = unsafe { winapi::um::memoryapi::UnmapViewOfFile(buffer as *mut winapi::ctypes::c_void) }; assert!(success != 0); } pub fn get_resident(_buffer: *const u8, _length: usize, residency: &mut [bool]) { for x in residency { *x = true; } } pub fn prefetch(buffer: *const u8, length: usize) { let mut entry = winapi::um::memoryapi::WIN32_MEMORY_RANGE_ENTRY { VirtualAddress: buffer as *mut winapi::ctypes::c_void, NumberOfBytes: length as winapi::shared::basetsd::SIZE_T, }; unsafe { let current_process_handle = winapi::um::processthreadsapi::GetCurrentProcess(); winapi::um::memoryapi::PrefetchVirtualMemory( current_process_handle, 1, &mut entry, 0 ); } } pub fn get_page_size() -> usize { let mut sysinfo: winapi::um::sysinfoapi::SYSTEM_INFO = unsafe { mem::zeroed() }; unsafe { winapi::um::sysinfoapi::GetSystemInfo(&mut sysinfo); } sysinfo.dwPageSize as usize }
use std::fs; use std::io; use std::mem; use std::os::windows::io::AsRawHandle; use std::ptr; extern crate winapi; #[derive(Debug)] pub struct PlatformData { #[allow(dead_code)] file: fs::File, mapping_handle: winapi::um::winnt::HANDLE, } impl Drop for PlatformData { fn drop (&mut self) { if self.mapping_handle != ptr::null_mut() { let success = unsafe { winapi::um::handleapi::CloseHandle(self.mapping_handle) }; assert!(success != 0); } } } pub fn map_file(file: fs::File) -> io::Result<(*const u8, usize, PlatformData)> { let file_handle = file.as_raw_handle(); let length = try!(file.metadata()).len(); if length > usize::max_value() as u64 { return Err(io::Error::new(io::ErrorKind::Other, "file is larger than address space")); } let mut platform_data = PlatformData { file: file, mapping_handle: ptr::null_mut(), }; if length == 0 { return Ok((ptr::null(), 0, platform_data)); } platform_data.mapping_handle = unsafe { winapi::um::memoryapi::CreateFileMappingW( file_handle as *mut winapi::ctypes::c_void, ptr::null_mut(), winapi::um::winnt::PAGE_READONLY, 0, 0, ptr::null_mut() ) }; if platform_data.mapping_handle == ptr::null_mut() { return Err(io::Error::last_os_error()); } let result = unsafe { winapi::um::memoryapi::MapViewOfFile( platform_data.mapping_handle, winapi::um::memoryapi::FILE_MAP_READ, 0, 0, length as winapi::shared::basetsd::SIZE_T ) }; if result == ptr::null_mut() { Err(io::Error::last_os_error()) } else { Ok((result as *const u8, length as usize, platform_data)) } } pub fn unmap_file(buffer: *const u8, _length: usize) { let success = unsafe { winapi::um::memoryapi::UnmapViewOfFile(buffer as *mut winapi::ctypes::c_void) }; assert!(success != 0); } pub fn get_resident(_buffer: *const u8, _length: usize, residency: &mut [bool]) { for x in residency { *x = true; } } pub fn prefetch(buffer: *const u8, length: usize) { let mut entry = winapi::um::memoryapi::WIN32_MEMORY_RANGE_ENTRY { VirtualAddress: buffer as *mut winapi::ctypes::c_void, NumberOfBytes: length as winapi::shared::basetsd::SIZE_T, }; unsafe { let current_process_handle = winapi::um::processthreadsapi::GetCurrentProcess(); winapi::um::memoryapi::PrefetchVirtualMemory( current_process_handle, 1, &mut entry, 0 ); } } pub fn get_page_size() -> usiz
e { let mut sysinfo: winapi::um::sysinfoapi::SYSTEM_INFO = unsafe { mem::zeroed() }; unsafe { winapi::um::sysinfoapi::GetSystemInfo(&mut sysinfo); } sysinfo.dwPageSize as usize }
function_block-function_prefixed
[ { "content": "/// Writes whether the pages in the range starting at `buffer` with a length of `length` bytes\n\n/// are resident in physical memory into `residency`. The size of `residency` must be at least\n\n/// `length / page_size`. Both `buffer` and `length` must be a multiple of the page size.\n\npub fn get_resident(buffer: *const u8, length: usize, residency: &mut [bool]) {\n\n use std::thread;\n\n\n\n let result = unsafe {\n\n // Note: the libc on BSD descendants uses a signed char for residency_char while\n\n // glibc uses an unsigned one, which is why we use an type-inferred cast here.\n\n let residency_char = residency.as_mut_ptr() as *mut _;\n\n assert_eq!(1, mem::size_of_val(&*residency_char));\n\n libc::mincore(buffer as *mut libc::c_void, length, residency_char)\n\n };\n\n\n\n // Any error code except EAGAIN indicates a programming error.\n\n assert!(result == libc::EAGAIN || result == 0);\n\n\n\n // In the rare occasion that the kernel is busy, yield so we don't spam the kernel with\n\n // `mincore` calls, then try again.\n\n if result == libc::EAGAIN {\n\n thread::yield_now();\n\n get_resident(buffer, length, residency)\n\n }\n\n}\n\n\n", "file_path": "src/unix.rs", "rank": 0, "score": 242884.91114529915 }, { "content": "pub fn unmap_file(buffer: *const u8, length: usize) {\n\n let result = unsafe { libc::munmap(buffer as *mut libc::c_void, length) };\n\n\n\n // `munmap` only fails due to incorrect usage, which is a program error, not a runtime failure.\n\n assert!(result == 0);\n\n}\n\n\n", "file_path": "src/unix.rs", "rank": 3, "score": 203421.35840151235 }, { "content": "/// Requests the kernel to make the specified range of bytes resident in physical memory. `buffer`\n\n/// must be page-aligned.\n\npub fn prefetch(buffer: *const u8, length: usize) {\n\n let result = unsafe { libc::madvise(buffer as *mut libc::c_void, length, libc::MADV_WILLNEED) };\n\n\n\n // Any returned error code indicates a programming error, not a runtime error.\n\n assert_eq!(0, result);\n\n}\n\n\n", "file_path": "src/unix.rs", "rank": 4, "score": 191030.13640305106 }, { "content": "pub fn map_file(file: fs::File) -> io::Result<(*const u8, usize, PlatformData)> {\n\n let fd = file.as_raw_fd();\n\n let length = (file.metadata()?).len();\n\n\n\n if length > usize::max_value() as u64 {\n\n return Err(io::Error::new(\n\n io::ErrorKind::Other,\n\n \"file is larger than address space\",\n\n ));\n\n }\n\n\n\n // Don't try to map anything if the file is empty.\n\n if length == 0 {\n\n return Ok((ptr::null(), 0, PlatformData));\n\n }\n\n\n\n let result = unsafe {\n\n libc::mmap(\n\n ptr::null_mut(),\n\n length as usize,\n", "file_path": "src/unix.rs", "rank": 6, "score": 183808.5109430703 }, { "content": "pub fn get_page_size() -> usize {\n\n let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize };\n\n\n\n // Assert that the page size is a power of two, which is assumed when the page size is used.\n\n assert!(page_size != 0);\n\n assert_eq!(0, page_size & (page_size - 1));\n\n\n\n page_size\n\n}\n", "file_path": "src/unix.rs", "rank": 8, "score": 76059.70124110783 }, { "content": "#[test]\n\nfn empty_file_has_zero_resident_len() {\n\n let fbuffer = FileBuffer::open(\"src/empty_file_for_testing.rs\").unwrap();\n\n assert_eq!(fbuffer.resident_len(0, 0), 0);\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 10, "score": 61439.23334520523 }, { "content": "#[test]\n\nfn drop_after_leak() {\n\n let mut bytes = &[0u8][..];\n\n assert_eq!(bytes[0], 0);\n\n {\n\n let fbuffer = FileBuffer::open(\"src/lib.rs\").unwrap();\n\n bytes = fbuffer.leak();\n\n }\n\n assert_eq!(&bytes[3..13], &b\"Filebuffer\"[..]);\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 11, "score": 47942.235972086266 }, { "content": "#[test]\n\nfn make_resident() {\n\n let fbuffer = FileBuffer::open(\"src/lib.rs\").unwrap();\n\n\n\n // Touch the first page to make it resident.\n\n assert_eq!(&fbuffer[3..13], &b\"Filebuffer\"[..]);\n\n\n\n // Now at least that part should be resident.\n\n assert_eq!(fbuffer.resident_len(3, 10), 10);\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 12, "score": 47607.9891276385 }, { "content": "/// Rounds `size` down to the nearest multiple of `power_of_two`.\n\nfn round_down_to(size: usize, power_of_two: usize) -> usize {\n\n size & !(power_of_two - 1)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 13, "score": 46974.21926804831 }, { "content": "/// Rounds `size` up to the nearest multiple of `power_of_two`.\n\nfn round_up_to(size: usize, power_of_two: usize) -> usize {\n\n (size + (power_of_two - 1)) & !(power_of_two - 1)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 14, "score": 46974.21926804831 }, { "content": "#[test]\n\nfn open_file() {\n\n let fbuffer = FileBuffer::open(\"src/lib.rs\");\n\n assert!(fbuffer.is_ok());\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 15, "score": 46918.840752261414 }, { "content": "#[test]\n\nfn open_empty_file_is_fine() {\n\n FileBuffer::open(\"src/empty_file_for_testing.rs\").unwrap();\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 16, "score": 43559.69788150874 }, { "content": "#[test]\n\nfn empty_file_prefetch_is_fine() {\n\n let fbuffer = FileBuffer::open(\"src/empty_file_for_testing.rs\").unwrap();\n\n fbuffer.prefetch(0, 0);\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 17, "score": 43559.69788150874 }, { "content": "#[test]\n\nfn empty_file_deref_is_fine() {\n\n let fbuffer = FileBuffer::open(\"src/empty_file_for_testing.rs\").unwrap();\n\n assert_eq!(fbuffer.iter().any(|_| true), false);\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 18, "score": 43559.69788150874 }, { "content": "fn main() {\n\n for fname in env::args().skip(1) {\n\n println!(\"==> {} <==\", &fname);\n\n let fbuffer = FileBuffer::open(&fname).expect(\"failed to open file\");\n\n let lines = str::from_utf8(&fbuffer).expect(\"not valid UTF-8\").lines();\n\n for line in lines.take(10) {\n\n println!(\"{}\", line);\n\n }\n\n }\n\n}\n", "file_path": "examples/head.rs", "rank": 19, "score": 26478.081298853467 }, { "content": "#[test]\n\nfn prefetch_is_not_harmful() {\n\n let fbuffer = FileBuffer::open(\"src/lib.rs\").unwrap();\n\n\n\n // It is impossible to test that this actually works without root access to instruct the kernel\n\n // to drop its caches, but at least we can verify that calling `prefetch` is not harmful.\n\n fbuffer.prefetch(0, fbuffer.len());\n\n\n\n // Reading from the file should still work as normal.\n\n assert_eq!(&fbuffer[3..13], &b\"Filebuffer\"[..]);\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 20, "score": 25583.598090813655 }, { "content": "#[test]\n\nfn verify_round_up_to() {\n\n assert_eq!(1024, round_up_to(23, 1024));\n\n assert_eq!(1024, round_up_to(1024, 1024));\n\n assert_eq!(2048, round_up_to(1025, 1024));\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 21, "score": 25583.598090813655 }, { "content": "fn main() {\n\n for fname in env::args().skip(1) {\n\n let fbuffer = FileBuffer::open(&fname).expect(\"failed to open file\");\n\n let mut hasher = Sha256::new();\n\n hasher.input(&fbuffer);\n\n\n\n // Match the output format of `sha256sum`, which has two spaces between the hash and name.\n\n println!(\"{} {}\", hasher.result_str(), fname);\n\n }\n\n}\n", "file_path": "examples/sha256sum_filebuffer.rs", "rank": 22, "score": 25583.598090813655 }, { "content": "#[test]\n\nfn verify_round_down_to() {\n\n assert_eq!(0, round_down_to(23, 1024));\n\n assert_eq!(1024, round_down_to(1024, 1024));\n\n assert_eq!(1024, round_down_to(1025, 1024));\n\n}\n\n\n\nimpl FileBuffer {\n\n /// Maps the file at `path` into memory.\n\n pub fn open<P: AsRef<Path>>(path: P) -> io::Result<FileBuffer> {\n\n // Open the `fs::File` so we get all of std's error handling for free, then use it to\n\n // extract the file descriptor. The file is closed again when `map_file` returns on\n\n // Unix-ish platforms, but `mmap` only requires the descriptor to be open for the `mmap`\n\n // call, so this is fine. On Windows, the file must be kept open for the lifetime of the\n\n // mapping, so `map_file` moves the file into the platform data.\n\n let mut open_opts = fs::OpenOptions::new();\n\n open_opts.read(true);\n\n\n\n // TODO: On Windows, set `share_mode()` to read-only. This requires the\n\n // `open_options_ext` feature that is currently unstable, but it is\n\n // required to ensure that a different process does not suddenly modify\n", "file_path": "src/lib.rs", "rank": 23, "score": 25583.598090813655 }, { "content": "fn main() {\n\n for fname in env::args().skip(1) {\n\n let file = fs::File::open(&fname).expect(\"failed to open file\");\n\n let mut reader = io::BufReader::new(file);\n\n let mut hasher = Sha256::new();\n\n\n\n loop {\n\n let consumed_len = {\n\n let buffer = reader.fill_buf().expect(\"failed to read from file\");\n\n if buffer.len() == 0 {\n\n // End of file.\n\n break;\n\n }\n\n hasher.input(buffer);\n\n buffer.len()\n\n };\n\n reader.consume(consumed_len);\n\n }\n\n\n\n // Match the output format of `sha256sum`, which has two spaces between the hash and name.\n\n println!(\"{} {}\", hasher.result_str(), fname);\n\n }\n\n}\n", "file_path": "examples/sha256sum_naive.rs", "rank": 24, "score": 25583.598090813655 }, { "content": "#[test]\n\nfn page_size_at_least_4096() {\n\n // There is no reason why the page size cannot be smaller, it is just that in practice there\n\n // is no platform with a smaller page size, so this tests that `get_page_size()` returns\n\n // a plausible value.\n\n assert!(get_page_size() >= 4096);\n\n}\n", "file_path": "src/lib.rs", "rank": 25, "score": 24767.72459213553 }, { "content": "#[test]\n\nfn fbuffer_can_be_moved_into_thread() {\n\n use std::thread;\n\n\n\n let fbuffer = FileBuffer::open(\"src/lib.rs\").unwrap();\n\n thread::spawn(move || {\n\n assert_eq!(&fbuffer[3..13], &b\"Filebuffer\"[..]);\n\n });\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 26, "score": 24020.534321662457 }, { "content": "#[test]\n\nfn fbuffer_can_be_shared_among_threads() {\n\n use std::sync;\n\n use std::thread;\n\n\n\n let fbuffer = FileBuffer::open(\"src/lib.rs\").unwrap();\n\n let buffer1 = sync::Arc::new(fbuffer);\n\n let buffer2 = buffer1.clone();\n\n thread::spawn(move || {\n\n assert_eq!(&buffer2[3..13], &b\"Filebuffer\"[..]);\n\n });\n\n assert_eq!(&buffer1[17..45], &b\"Fast and simple file reading\"[..]);\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 27, "score": 23333.704587114986 }, { "content": "", "file_path": "src/empty_file_for_testing.rs", "rank": 28, "score": 21335.24266144775 }, { "content": " buffer\n\n }\n\n}\n\n\n\n// There is no possibility of data races when passing `&FileBuffer` across threads,\n\n// because the buffer is read-only. `&FileBuffer` has no interior mutability.\n\nunsafe impl Sync for FileBuffer {}\n\n\n\n// It is safe to move a `FileBuffer` into a different thread.\n\nunsafe impl Send for FileBuffer {}\n\n\n\nimpl Drop for FileBuffer {\n\n fn drop(&mut self) {\n\n if self.buffer != ptr::null() {\n\n unmap_file(self.buffer, self.length);\n\n }\n\n }\n\n}\n\n\n\nimpl Deref for FileBuffer {\n", "file_path": "src/lib.rs", "rank": 29, "score": 15.707632602872703 }, { "content": " type Target = [u8];\n\n\n\n fn deref(&self) -> &[u8] {\n\n unsafe { slice::from_raw_parts(self.buffer, self.length) }\n\n }\n\n}\n\n\n\nimpl AsRef<[u8]> for FileBuffer {\n\n fn as_ref(&self) -> &[u8] {\n\n self.deref()\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 31, "score": 13.785984970705515 }, { "content": "Filebuffer\n\n==========\n\nFast and simple file reading for Rust.\n\n\n\n[![Build Status][tr-img]][tr]\n\n[![Build Status][av-img]][av]\n\n[![Crates.io version][crate-img]][crate]\n\n[![Changelog][changelog-img]][changelog]\n\n[![Documentation][docs-img]][docs]\n\n\n\nFilebuffer can map files into memory. This is often faster than using the\n\nprimitives in `std::io`, and also more convenient. Furthermore this crate\n\noffers prefetching and checking whether file data is resident in physical\n\nmemory (so access will not incur a page fault). This enables non-blocking\n\nfile reading.\n\n\n\nExample\n\n-------\n\nBelow is an implementation of the `sha256sum` program that is both faster and\n\nsimpler than the naive `std::io` equivalent. (See `sha256sum_filebuffer` and\n\n`sha256sum_naive` in the examples directory.)\n\n\n\n```rust\n\nuse std::env;\n\nuse crypto::digest::Digest;\n\nuse crypto::sha2::Sha256;\n\nuse filebuffer::FileBuffer;\n\n\n\nextern crate crypto;\n\nextern crate filebuffer;\n\n\n\nfn main() {\n\n for fname in env::args().skip(1) {\n\n let fbuffer = FileBuffer::open(&fname).expect(\"failed to open file\");\n\n let mut hasher = Sha256::new();\n\n hasher.input(&fbuffer);\n\n println!(\"{} {}\", hasher.result_str(), fname);\n\n }\n\n}\n\n```\n\n\n", "file_path": "readme.md", "rank": 32, "score": 13.445099750071789 }, { "content": " ///\n\n /// To check whether the slice is resident at a later time, use `resident_len()`.\n\n ///\n\n /// # Panics\n\n ///\n\n /// Panics if the specified range lies outside of the buffer.\n\n pub fn prefetch(&self, offset: usize, length: usize) {\n\n // TODO: This function should use `collections::range::RangeArgument` once stabilized.\n\n // The specified offset and length must lie within the buffer.\n\n assert!(offset + length <= self.length);\n\n\n\n // This is a no-op for empty files.\n\n if self.buffer == ptr::null() {\n\n return;\n\n }\n\n\n\n let aligned_offset = round_down_to(offset, self.page_size);\n\n let aligned_length = round_up_to(length + (offset - aligned_offset), self.page_size);\n\n\n\n let buffer = unsafe { self.buffer.offset(aligned_offset as isize) };\n", "file_path": "src/lib.rs", "rank": 33, "score": 12.605917614051112 }, { "content": "use unix::get_resident;\n\n\n\n#[cfg(windows)]\n\nuse windows::{get_page_size, get_resident, map_file, prefetch, unmap_file, PlatformData};\n\n\n\n/// A memory-mapped file.\n\n///\n\n/// # Safety\n\n///\n\n/// **On Unix-ish platforms, external modifications to the file made after the file buffer was\n\n/// opened can show up in this file buffer.** In particular, if a file is truncated after opening,\n\n/// accessing the removed part causes undefined behavior. On Windows it is possible to prevent this\n\n/// by opening the file in exclusive mode, but that functionality is not available in stable Rust\n\n/// currently. (Filebuffer will be updated after stabilization.)\n\n///\n\n/// It is recommended to ensure that other applications do not write to the file when it is mapped,\n\n/// possibly by marking the file read-only. (Though even this is no guarantee.)\n\n#[derive(Debug)]\n\npub struct FileBuffer {\n\n page_size: usize,\n\n buffer: *const u8,\n\n length: usize,\n\n\n\n #[allow(dead_code)] // This field is not dead, it might have an effectful destructor.\n\n platform_data: PlatformData,\n\n}\n\n\n\n/// Rounds `size` up to the nearest multiple of `power_of_two`.\n", "file_path": "src/lib.rs", "rank": 34, "score": 11.419624554088132 }, { "content": " // the length of the buffer, because it is rounded up to the page size.\n\n cmp::min(length, resident_length)\n\n }\n\n\n\n /// Returns the system page size.\n\n ///\n\n /// When the kernel makes the file resident in physical memory, it does so with page\n\n /// granularity. (In practice this happens in larger chunks, but still in multiples of\n\n /// the page size.) Therefore, when processing the file in chunks, this is a good chunk\n\n /// length.\n\n pub fn chunk_len_hint(&self) -> usize {\n\n self.page_size\n\n }\n\n\n\n /// Advises the kernel to make a slice of the file resident in physical memory.\n\n ///\n\n /// This method does not block, meaning that when the function returns, the slice is not\n\n /// necessarily resident. After this function returns, the kernel may read the requested slice\n\n /// from disk and make it resident. Note that this is only an advice, the kernel need not honor\n\n /// it.\n", "file_path": "src/lib.rs", "rank": 37, "score": 10.480108965993956 }, { "content": " ///\n\n /// # Panics\n\n ///\n\n /// Panics if the specified range lies outside of the buffer.\n\n ///\n\n /// # Remarks\n\n ///\n\n /// Windows does not expose a mechanism to query which pages are resident in physical\n\n /// memory. Therefore this function optimistically claims that the entire range is resident\n\n /// on Windows.\n\n pub fn resident_len(&self, offset: usize, length: usize) -> usize {\n\n // The specified offset and length must lie within the buffer.\n\n assert!(offset + length <= self.length);\n\n\n\n // This is a no-op for empty files.\n\n if self.buffer == ptr::null() {\n\n return 0;\n\n }\n\n\n\n let aligned_offset = round_down_to(offset, self.page_size);\n", "file_path": "src/lib.rs", "rank": 38, "score": 10.478069797813074 }, { "content": " prefetch(buffer, aligned_length);\n\n }\n\n\n\n /// Leaks the file buffer as a byte slice.\n\n ///\n\n /// This prevents the buffer from being unmapped, keeping the file mapped until the program\n\n /// ends. This is not as bad as it sounds, because the kernel is free to evict pages from\n\n /// physical memory in case of memory pressure. Because the file is mapped read-only, it can\n\n /// always be read from disk again.\n\n ///\n\n /// If the file buffer is going to be open for the entire duration of the program anyway, this\n\n /// method can avoid some lifetime issues. Still, it is good practice to close the file buffer\n\n /// if possible. This method should be a last resort.\n\n pub fn leak(mut self) -> &'static [u8] {\n\n let buffer = unsafe { slice::from_raw_parts(self.buffer, self.length) };\n\n\n\n // Prevent `drop()` from freeing the buffer.\n\n self.buffer = ptr::null();\n\n self.length = 0;\n\n\n", "file_path": "src/lib.rs", "rank": 39, "score": 10.251775786566506 }, { "content": " // the contents of the file. See also Rust issue 27720.\n\n\n\n let file = open_opts.open(path)?;\n\n let (buffer, length, platform_data) = map_file(file)?;\n\n let fbuffer = FileBuffer {\n\n page_size: get_page_size(),\n\n buffer: buffer,\n\n length: length,\n\n platform_data: platform_data,\n\n };\n\n Ok(fbuffer)\n\n }\n\n\n\n /// Returns the number of bytes resident in physical memory, starting from `offset`.\n\n ///\n\n /// The slice `[offset..offset + resident_len]` can be accessed without causing page faults or\n\n /// disk access. Note that this is only a snapshot, and the kernel might decide to evict pages\n\n /// or make them resident at any time.\n\n ///\n\n /// The returned resident length is at most `length`.\n", "file_path": "src/lib.rs", "rank": 40, "score": 9.941631441217169 }, { "content": " let aligned_length = round_up_to(length + (offset - aligned_offset), self.page_size);\n\n let num_pages = aligned_length / self.page_size;\n\n\n\n // There is a tradeoff here: to store residency information, we need an array of booleans.\n\n // The requested range can potentially be very large and it is only known at runtime. We\n\n // could allocate a vector here, but that requires a heap allocation just to get residency\n\n // information (which might in turn cause a page fault). Instead, check at most 32 pages at\n\n // once. This means more syscalls for large ranges, but it saves us the heap allocation,\n\n // and for ranges up to 32 pages (128 KiB typically) there is only one syscall.\n\n let mut residency = [false; 32];\n\n let mut pages_checked = 0;\n\n let mut pages_resident = 0;\n\n\n\n while pages_checked < num_pages {\n\n let pages_to_check = cmp::min(32, num_pages - pages_checked);\n\n let check_offset = (aligned_offset + pages_checked * self.page_size) as isize;\n\n let check_buffer = unsafe { self.buffer.offset(check_offset) };\n\n let check_length = pages_to_check * self.page_size;\n\n get_resident(check_buffer, check_length, &mut residency);\n\n\n", "file_path": "src/lib.rs", "rank": 41, "score": 8.971173710504905 }, { "content": "// Filebuffer -- Fast and simple file reading\n\n// Copyright 2016 Ruud van Asseldonk\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// A copy of the License has been included in the root of the repository.\n\n\n\n// This example implements the `sha256sum` program in Rust using the Filebuffer library. Compare\n\n// with `sha256sum_naive` which uses the IO primitives in the standard library.\n\n\n\nuse std::env;\n\nuse crypto::digest::Digest;\n\nuse crypto::sha2::Sha256;\n\nuse filebuffer::FileBuffer;\n\n\n\nextern crate crypto;\n\nextern crate filebuffer;\n\n\n", "file_path": "examples/sha256sum_filebuffer.rs", "rank": 42, "score": 8.892718030861381 }, { "content": " libc::PROT_READ,\n\n libc::MAP_PRIVATE,\n\n fd,\n\n 0,\n\n )\n\n };\n\n\n\n if result == libc::MAP_FAILED {\n\n Err(io::Error::last_os_error())\n\n } else {\n\n Ok((result as *const u8, length as usize, PlatformData))\n\n }\n\n}\n\n\n", "file_path": "src/unix.rs", "rank": 44, "score": 8.195946588714904 }, { "content": "// Filebuffer -- Fast and simple file reading\n\n// Copyright 2016 Ruud van Asseldonk\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// A copy of the License has been included in the root of the repository.\n\n\n\n// This example implements the `head` program in Rust using the Filebuffer library.\n\n// Input files are assumed to be valid UTF-8.\n\n\n\nuse std::env;\n\nuse std::str;\n\nuse filebuffer::FileBuffer;\n\n\n\nextern crate filebuffer;\n\n\n", "file_path": "examples/head.rs", "rank": 45, "score": 8.089434997311136 }, { "content": "// Filebuffer -- Fast and simple file reading\n\n// Copyright 2016 Ruud van Asseldonk\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// A copy of the License has been included in the root of the repository.\n\n\n\n//! This mod contains the platform-specific implementations of functions based on the libc crate\n\n//! that is available on Unix-ish platforms.\n\n\n\nuse std::fs;\n\nuse std::io;\n\nuse std::mem;\n\nuse std::os::unix::io::AsRawFd;\n\nuse std::ptr;\n\n\n\nextern crate libc;\n\n\n\n#[derive(Debug)]\n\npub struct PlatformData;\n\n\n", "file_path": "src/unix.rs", "rank": 46, "score": 6.9096659095932695 }, { "content": " // Count the number of resident pages.\n\n match residency[..pages_to_check]\n\n .iter()\n\n .position(|resident| !resident)\n\n {\n\n Some(non_resident) => {\n\n // The index of the non-resident page is the number of resident pages.\n\n pages_resident += non_resident;\n\n break;\n\n }\n\n None => {\n\n pages_resident += pages_to_check;\n\n pages_checked += pages_to_check;\n\n }\n\n }\n\n }\n\n\n\n let resident_length = pages_resident * self.page_size + aligned_offset - offset;\n\n\n\n // Never return more than the requested length. The resident length might be larger than\n", "file_path": "src/lib.rs", "rank": 47, "score": 6.864828361448979 }, { "content": "// Filebuffer -- Fast and simple file reading\n\n// Copyright 2016 Ruud van Asseldonk\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// A copy of the License has been included in the root of the repository.\n\n\n\n// This example implements the `sha256sum` program in Rust using the IO primitives in the\n\n// standard library. Compare with `sha256sum_filebuffer` which uses the Filebuffer library.\n\n\n\nuse std::env;\n\nuse std::fs;\n\nuse std::io;\n\nuse std::io::BufRead;\n\nuse crypto::digest::Digest;\n\nuse crypto::sha2::Sha256;\n\n\n\nextern crate crypto;\n\n\n", "file_path": "examples/sha256sum_naive.rs", "rank": 48, "score": 5.29964498826702 }, { "content": "// Filebuffer -- Fast and simple file reading\n\n// Copyright 2016 Ruud van Asseldonk\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// A copy of the License has been included in the root of the repository.\n\n\n\n//! Filebuffer, a library for fast and simple file reading.\n\n//!\n\n//! # Examples\n\n//!\n\n//! Map a file into memory and access it as a slice of bytes. This is simple and will generally\n\n//! outperform `Read::read_to_end()`.\n\n//!\n\n//! ```\n\n//! use filebuffer::FileBuffer;\n\n//! let fbuffer = FileBuffer::open(\"src/lib.rs\").unwrap();\n\n//! assert_eq!(&fbuffer[3..45], &b\"Filebuffer -- Fast and simple file reading\"[..]);\n\n//! ```\n\n\n", "file_path": "src/lib.rs", "rank": 49, "score": 5.2623281999465625 }, { "content": "#![warn(missing_docs)]\n\n\n\nuse std::cmp;\n\nuse std::fs;\n\nuse std::io;\n\nuse std::ops::Deref;\n\nuse std::path::Path;\n\nuse std::ptr;\n\nuse std::slice;\n\n\n\n#[cfg(unix)]\n\nmod unix;\n\n\n\n#[cfg(windows)]\n\nmod windows;\n\n\n\n#[cfg(unix)]\n\nuse unix::{get_page_size, map_file, prefetch, unmap_file, PlatformData};\n\n\n\n#[cfg(all(unix))]\n", "file_path": "src/lib.rs", "rank": 50, "score": 4.927824208359699 }, { "content": "Changelog\n\n=========\n\n\n\n0.4.0\n\n-----\n\n\n\nReleased 2018-04-29.\n\n\n\n * Bump `winapi` dependency to 0.3.\n\n * Ensures compatibility with Rust 1.8 through 1.25 stable.\n\n\n\n0.3.0\n\n-----\n\n\n\nReleased 2017-08-03.\n\n\n\n * Add support for Mac OS X.\n\n * Implement `AsRef<[u8]>` for `Filebuffer`.\n\n * Ensures compatibility with Rust 1.8 through 1.19 stable.\n\n\n\nThanks to Craig M. Brandenburg for contributing to this release.\n\n\n\n0.2.0\n\n-----\n\n\n\nReleased 2017-05-20.\n\n\n\n * Derive `fmt::Debug` for public types.\n\n * Depend on libc only on Unix-like environments, and on kernel32-sys only on\n\n Windows. This requires Rust 1.8 or later, so this is a breaking change.\n\n * Ensures compatibility with Rust 1.8 through 1.17 stable.\n\n\n\nThanks to Colin Wallace for contributing to this release.\n\n\n\n0.1.1\n\n-----\n\n\n\nReleased 2017-02-01.\n\n\n\n * Ensures compatibility with Rust 1.4 through 1.14 stable.\n\n * Host documentation on docs.rs (thanks, docs.rs authors!).\n\n * Update crate metadata.\n\n\n\n0.1.0\n\n-----\n\n\n\nReleased 2016-01-31.\n\n\n\nInitial release with Windows and Linux support.\n", "file_path": "changelog.md", "rank": 51, "score": 4.399932912973629 }, { "content": "License\n\n-------\n\nFilebuffer is licensed under the [Apache 2.0][apache2] license. It may be used\n\nin free software as well as closed-source applications, both for commercial and\n\nnon-commercial use under the conditions given in the license. If you want to use\n\nFilebuffer in your GPLv2-licensed software, you can add an [exception][except]\n\nto your copyright notice.\n\n\n\n[tr-img]: https://travis-ci.org/ruuda/filebuffer.svg?branch=master\n\n[tr]: https://travis-ci.org/ruuda/filebuffer\n\n[av-img]: https://ci.appveyor.com/api/projects/status/kfacq5ul22hbnd9u?svg=true\n\n[av]: https://ci.appveyor.com/project/ruuda/filebuffer\n\n[crate-img]: https://img.shields.io/crates/v/filebuffer.svg\n\n[crate]: https://crates.io/crates/filebuffer\n\n[changelog-img]: https://img.shields.io/badge/changelog-online-blue.svg\n\n[changelog]: https://github.com/ruuda/filebuffer/blob/master/changelog.md#changelog\n\n[docs-img]: https://img.shields.io/badge/docs-online-blue.svg\n\n[docs]: https://docs.rs/filebuffer\n\n[apache2]: https://www.apache.org/licenses/LICENSE-2.0\n\n[except]: https://www.gnu.org/licenses/gpl-faq.html#GPLIncompatibleLibs\n", "file_path": "readme.md", "rank": 52, "score": 4.247689375374328 } ]
Rust
src/browser/url/search.rs
AlterionX/seed
ba2d8d36c68feda991d73a961ddc630fb67df949
use crate::browser::url::Url; use serde::{Deserialize, Serialize}; use std::{borrow::Cow, collections::BTreeMap, fmt}; #[allow(clippy::module_name_repetitions)] #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct UrlSearch { search: BTreeMap<String, Vec<String>>, pub(super) invalid_components: Vec<String>, } impl UrlSearch { pub fn new() -> Self { Self { search: BTreeMap::new(), invalid_components: Vec::new(), } } pub fn contains_key(&self, key: impl AsRef<str>) -> bool { self.search.contains_key(key.as_ref()) } pub fn get(&self, key: impl AsRef<str>) -> Option<&Vec<String>> { self.search.get(key.as_ref()) } pub fn get_mut(&mut self, key: impl AsRef<str>) -> Option<&mut Vec<String>> { self.search.get_mut(key.as_ref()) } pub fn push_value<'a>(&mut self, key: impl Into<Cow<'a, str>>, value: String) { let key = key.into(); if self.search.contains_key(key.as_ref()) { self.search.get_mut(key.as_ref()).unwrap().push(value); } else { self.search.insert(key.into_owned(), vec![value]); } } pub fn insert(&mut self, key: String, values: Vec<String>) -> Option<Vec<String>> { self.search.insert(key, values) } pub fn remove(&mut self, key: impl AsRef<str>) -> Option<Vec<String>> { self.search.remove(key.as_ref()) } pub fn iter(&self) -> impl Iterator<Item = (&String, &Vec<String>)> { self.search.iter() } pub fn invalid_components(&self) -> &[String] { &self.invalid_components } pub fn invalid_components_mut(&mut self) -> &mut Vec<String> { &mut self.invalid_components } } impl fmt::Display for UrlSearch { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let params = web_sys::UrlSearchParams::new().expect("create a new UrlSearchParams"); for (key, values) in &self.search { for value in values { params.append(key, value); } } write!(fmt, "{}", String::from(params.to_string())) } } impl From<web_sys::UrlSearchParams> for UrlSearch { fn from(params: web_sys::UrlSearchParams) -> Self { let mut url_search = Self::default(); let mut invalid_components = Vec::<String>::new(); for param in js_sys::Array::from(&params).to_vec() { let key_value_pair = js_sys::Array::from(&param).to_vec(); let key = key_value_pair .get(0) .expect("get UrlSearchParams key from key-value pair") .as_string() .expect("cast UrlSearchParams key to String"); let value = key_value_pair .get(1) .expect("get UrlSearchParams value from key-value pair") .as_string() .expect("cast UrlSearchParams value to String"); let key = match Url::decode_uri_component(&key) { Ok(decoded_key) => decoded_key, Err(_) => { invalid_components.push(key.clone()); key } }; let value = match Url::decode_uri_component(&value) { Ok(decoded_value) => decoded_value, Err(_) => { invalid_components.push(value.clone()); value } }; url_search.push_value(key, value) } url_search.invalid_components = invalid_components; url_search } } impl<K, V, VS> std::iter::FromIterator<(K, VS)> for UrlSearch where K: Into<String>, V: Into<String>, VS: IntoIterator<Item = V>, { fn from_iter<I: IntoIterator<Item = (K, VS)>>(iter: I) -> Self { let search = iter .into_iter() .map(|(k, vs)| { let k = k.into(); let v: Vec<_> = vs.into_iter().map(Into::into).collect(); (k, v) }) .collect(); Self { search, invalid_components: Vec::new(), } } } impl<'iter, K, V, VS> std::iter::FromIterator<&'iter (K, VS)> for UrlSearch where K: Into<String> + Copy + 'iter, V: Into<String> + Copy + 'iter, VS: IntoIterator<Item = V> + 'iter, { fn from_iter<I: IntoIterator<Item = &'iter (K, VS)>>(iter: I) -> Self { iter.into_iter().collect() } }
use crate::browser::url::Url; use serde::{Deserialize, Serialize}; use std::{borrow::Cow, collections::BTreeMap, fmt}; #[allow(clippy::module_name_repetitions)] #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct UrlSearch { search: BTreeMap<String, Vec<String>>, pub(super) invalid_components: Vec<String>, } impl UrlSearch { pub fn new() -> Self { Self { search: BTreeMap::new(), invalid_components: Vec::new(), } } pub fn contains_key(&self, key: impl AsRef<str>) -> bool { self.search.contains_key(key.as_ref()) } pub fn get(&self, key: impl AsRef<str>) -> Option<&Vec<String>> { self.search.get(key.as_ref()) } pub fn get_mut(&mut self, key: impl AsRef<str>) -> Option<&mut Vec<String>> { self.search.get_mut(key.as_ref()) } pub fn push_value<'a>(&mut self, key: impl Into<Cow<'a, str>>, value: String) {
pub fn insert(&mut self, key: String, values: Vec<String>) -> Option<Vec<String>> { self.search.insert(key, values) } pub fn remove(&mut self, key: impl AsRef<str>) -> Option<Vec<String>> { self.search.remove(key.as_ref()) } pub fn iter(&self) -> impl Iterator<Item = (&String, &Vec<String>)> { self.search.iter() } pub fn invalid_components(&self) -> &[String] { &self.invalid_components } pub fn invalid_components_mut(&mut self) -> &mut Vec<String> { &mut self.invalid_components } } impl fmt::Display for UrlSearch { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let params = web_sys::UrlSearchParams::new().expect("create a new UrlSearchParams"); for (key, values) in &self.search { for value in values { params.append(key, value); } } write!(fmt, "{}", String::from(params.to_string())) } } impl From<web_sys::UrlSearchParams> for UrlSearch { fn from(params: web_sys::UrlSearchParams) -> Self { let mut url_search = Self::default(); let mut invalid_components = Vec::<String>::new(); for param in js_sys::Array::from(&params).to_vec() { let key_value_pair = js_sys::Array::from(&param).to_vec(); let key = key_value_pair .get(0) .expect("get UrlSearchParams key from key-value pair") .as_string() .expect("cast UrlSearchParams key to String"); let value = key_value_pair .get(1) .expect("get UrlSearchParams value from key-value pair") .as_string() .expect("cast UrlSearchParams value to String"); let key = match Url::decode_uri_component(&key) { Ok(decoded_key) => decoded_key, Err(_) => { invalid_components.push(key.clone()); key } }; let value = match Url::decode_uri_component(&value) { Ok(decoded_value) => decoded_value, Err(_) => { invalid_components.push(value.clone()); value } }; url_search.push_value(key, value) } url_search.invalid_components = invalid_components; url_search } } impl<K, V, VS> std::iter::FromIterator<(K, VS)> for UrlSearch where K: Into<String>, V: Into<String>, VS: IntoIterator<Item = V>, { fn from_iter<I: IntoIterator<Item = (K, VS)>>(iter: I) -> Self { let search = iter .into_iter() .map(|(k, vs)| { let k = k.into(); let v: Vec<_> = vs.into_iter().map(Into::into).collect(); (k, v) }) .collect(); Self { search, invalid_components: Vec::new(), } } } impl<'iter, K, V, VS> std::iter::FromIterator<&'iter (K, VS)> for UrlSearch where K: Into<String> + Copy + 'iter, V: Into<String> + Copy + 'iter, VS: IntoIterator<Item = V> + 'iter, { fn from_iter<I: IntoIterator<Item = &'iter (K, VS)>>(iter: I) -> Self { iter.into_iter().collect() } }
let key = key.into(); if self.search.contains_key(key.as_ref()) { self.search.get_mut(key.as_ref()).unwrap().push(value); } else { self.search.insert(key.into_owned(), vec![value]); } }
function_block-function_prefix_line
[ { "content": "/// Attach given `key` to the `El`.\n\n///\n\n/// The keys are used by the diffing algorithm to determine the correspondence between old and\n\n/// new elements and helps to optimize the insertion, removal and reordering of elements.\n\npub fn el_key(key: &impl ToString) -> ElKey {\n\n ElKey(key.to_string())\n\n}\n\n\n\n// ------ El ------\n\n\n\n/// A component in our virtual DOM.\n\n///\n\n/// _Note:_ `Listener`s in `El`'s `event_handler_manager` are not cloned, but recreated during VDOM patching.\n\n///\n\n/// [MDN reference](https://developer.mozilla.org/en-US/docs/Web/API/Element)\n\n/// [`web_sys` reference](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Element.html)\n\n#[derive(Debug)] // todo: Custom debug implementation where children are on new lines and indented.\n\npub struct El<Ms> {\n\n // Ms is a message type, as in part of TEA.\n\n // We call this 'El' instead of 'Element' for brevity, and to prevent\n\n // confusion with web_sys::Element.\n\n pub tag: Tag,\n\n pub attrs: Attrs,\n\n pub style: Style,\n", "file_path": "src/virtual_dom/node/el.rs", "rank": 0, "score": 274755.7318279436 }, { "content": "pub fn get_media_href(path: &str) -> String {\n\n format!(\"/public/media/{}\", path)\n\n}\n", "file_path": "examples/bunnies/src/config.rs", "rank": 1, "score": 239231.12849678996 }, { "content": "/// Simplify getting the value of input elements; required due to the need to cast\n\n/// from general nodes/elements to `HTML_Elements`.\n\n///\n\n/// # Errors\n\n///\n\n/// Will return error if it's not possible to call `get_value` for given `target`.\n\npub fn get_value(target: &web_sys::EventTarget) -> Result<String, &'static str> {\n\n #![allow(clippy::wildcard_imports)]\n\n use web_sys::*;\n\n\n\n macro_rules! get {\n\n ($element:ty) => {\n\n get!($element, |_| Ok(()))\n\n };\n\n ($element:ty, $result_callback:expr) => {\n\n if let Some(input) = target.dyn_ref::<$element>() {\n\n return $result_callback(input).map(|_| input.value().to_string());\n\n }\n\n };\n\n }\n\n // List of elements\n\n // https://docs.rs/web-sys/0.3.25/web_sys/struct.HtmlMenuItemElement.html?search=value\n\n // They should be ordered by expected frequency of use\n\n\n\n get!(HtmlInputElement, |input: &HtmlInputElement| {\n\n // https://www.w3schools.com/tags/att_input_value.asp\n", "file_path": "src/browser/util.rs", "rank": 2, "score": 233346.07522084186 }, { "content": "#[cfg(not(use_nightly))]\n\npub fn wrap_debug<T: std::fmt::Debug>(object: T) -> T {\n\n object\n\n}\n\n\n\n/// A convenience function for logging to the web browser's console. We use\n\n/// a macro to supplement the log function to allow multiple inputs.\n\n///\n\n/// NOTE: `log!` also accepts entities which don't implement `Debug` on `nightly` Rust.\n\n/// It's useful because you don't have to add `Debug` bound to many places - implementation for\n\n/// logged entity is enough.\n\n#[macro_export]\n\nmacro_rules! log {\n\n { $($expr:expr),* $(,)? } => {\n\n {\n\n let mut formatted_exprs = Vec::new();\n\n $(\n\n formatted_exprs.push(format!(\"{:#?}\", $crate::shortcuts::wrap_debug(&$expr)));\n\n )*\n\n $crate::shortcuts::log_1(\n\n &formatted_exprs\n\n .as_slice()\n\n .join(\" \")\n\n .into()\n\n );\n\n }\n\n };\n\n}\n", "file_path": "src/shortcuts.rs", "rank": 3, "score": 226003.70224642826 }, { "content": "#[allow(clippy::unit_arg)]\n\npub fn set_checked(target: &web_sys::EventTarget, value: bool) -> Result<(), &'static str> {\n\n if let Some(input) = target.dyn_ref::<web_sys::HtmlInputElement>() {\n\n // https://www.w3schools.com/tags/att_input_checked.asp\n\n return match input.type_().as_str() {\n\n \"file\" => Err(\n\n r#\"The checked attribute can be used with <input type=\"checkbox\"> and <input type=\"radio\">.\"#,\n\n ),\n\n _ => Ok(input.set_checked(value)),\n\n };\n\n }\n\n if let Some(input) = target.dyn_ref::<web_sys::HtmlMenuItemElement>() {\n\n return Ok(input.set_checked(value));\n\n }\n\n Err(\"Only `HtmlInputElement` and `HtmlMenuItemElement` can be used in function `set_checked`.\")\n\n}\n\n\n", "file_path": "src/browser/util.rs", "rank": 4, "score": 225399.69198532891 }, { "content": "#[cfg(not(use_nightly))]\n\npub fn log<T: std::fmt::Debug>(object: T) -> T {\n\n web_sys::console::log_1(&format!(\"{:#?}\", &object).into());\n\n object\n\n}\n\n\n\n/// Similar to log, but for errors.\n", "file_path": "src/browser/util.rs", "rank": 5, "score": 213882.03458517266 }, { "content": "#[cfg(not(use_nightly))]\n\npub fn error<T: std::fmt::Debug>(object: T) -> T {\n\n web_sys::console::error_1(&format!(\"{:#?}\", &object).into());\n\n object\n\n}\n", "file_path": "src/browser/util.rs", "rank": 6, "score": 213882.03458517266 }, { "content": "/// Similar to `get_value`.\n\npub fn set_value(target: &web_sys::EventTarget, value: &str) -> Result<(), &'static str> {\n\n #![allow(clippy::wildcard_imports)]\n\n use web_sys::*;\n\n\n\n macro_rules! set {\n\n ($element:ty) => {\n\n set!($element, |_| Ok(value))\n\n };\n\n ($element:ty, $value_result_callback:expr) => {\n\n if let Some(input) = target.dyn_ref::<$element>() {\n\n return $value_result_callback(input).map(|value| input.set_value(value));\n\n }\n\n };\n\n }\n\n // List of elements\n\n // https://docs.rs/web-sys/0.3.25/web_sys/struct.HtmlMenuItemElement.html?search=set_value\n\n // They should be ordered by expected frequency of use\n\n\n\n if let Some(input) = target.dyn_ref::<HtmlInputElement>() {\n\n return set_html_input_element_value(input, value);\n", "file_path": "src/browser/util.rs", "rank": 7, "score": 209105.15461184073 }, { "content": "#[allow(dead_code)]\n\npub fn get_checked(target: &web_sys::EventTarget) -> Result<bool, &'static str> {\n\n if let Some(input) = target.dyn_ref::<web_sys::HtmlInputElement>() {\n\n // https://www.w3schools.com/tags/att_input_checked.asp\n\n return match input.type_().as_str() {\n\n \"file\" => Err(\n\n r#\"The checked attribute can be used with <input type=\"checkbox\"> and <input type=\"radio\">.\"#,\n\n ),\n\n _ => Ok(input.checked()),\n\n };\n\n }\n\n if let Some(input) = target.dyn_ref::<web_sys::HtmlMenuItemElement>() {\n\n return Ok(input.checked());\n\n }\n\n Err(\"Only `HtmlInputElement` and `HtmlMenuItemElement` can be used in function `get_checked`.\")\n\n}\n\n\n\n#[allow(clippy::missing_errors_doc)]\n\n/// Similar to `set_value`.\n", "file_path": "src/browser/util.rs", "rank": 8, "score": 203288.9962409052 }, { "content": "pub fn view(model: &Model, intro: impl FnOnce(&str, &str) -> Vec<Node<Msg>>) -> Vec<Node<Msg>> {\n\n nodes![\n\n intro(TITLE, DESCRIPTION),\n\n model\n\n .fetch_result\n\n .as_ref()\n\n .map(|result| div![format!(\"{:#?}\", result)]),\n\n button![ev(Ev::Click, |_| Msg::SendRequest), \"Try to Fetch JSON\"],\n\n ]\n\n}\n", "file_path": "examples/server_integration/client/src/example_b.rs", "rank": 9, "score": 199491.06444214517 }, { "content": "pub fn view(model: &Model, intro: impl FnOnce(&str, &str) -> Vec<Node<Msg>>) -> Vec<Node<Msg>> {\n\n let btn_disabled = match model {\n\n Model::ReadyToSubmit(form) if !form.title.is_empty() => false,\n\n _ => true,\n\n };\n\n\n\n let form_id = \"A_FORM\".to_string();\n\n let form = form![\n\n style! {\n\n St::Display => \"flex\",\n\n St::FlexDirection => \"column\",\n\n },\n\n ev(Ev::Submit, move |event| {\n\n event.prevent_default();\n\n Msg::FormSubmitted(form_id)\n\n }),\n\n view_form_field(\n\n label![\"Title:\", attrs! {At::For => \"form-title\" }],\n\n input![\n\n input_ev(Ev::Input, Msg::TitleChanged),\n", "file_path": "examples/server_integration/client/src/example_e.rs", "rank": 10, "score": 199491.06444214517 }, { "content": "pub fn view(model: &Model, intro: impl FnOnce(&str, &str) -> Vec<Node<Msg>>) -> Vec<Node<Msg>> {\n\n nodes![\n\n intro(TITLE, DESCRIPTION),\n\n match &model.fetch_result {\n\n None =>\n\n IF!(matches!(model.status, Status::WaitingForResponse(_)) => div![\"Waiting for response...\"]),\n\n Some(Ok(result)) => Some(div![format!(\"Server returned: {:#?}\", result)]),\n\n Some(Err(fetch_error)) => Some(div![format!(\"{:#?}\", fetch_error)]),\n\n },\n\n view_button(&model.status),\n\n ]\n\n}\n\n\n", "file_path": "examples/server_integration/client/src/example_d.rs", "rank": 11, "score": 199491.06444214517 }, { "content": "pub fn view(model: &Model, intro: impl FnOnce(&str, &str) -> Vec<Node<Msg>>) -> Vec<Node<Msg>> {\n\n nodes![\n\n intro(TITLE, DESCRIPTION),\n\n match model.status {\n\n Status::ReadyToSendRequest => nodes![\n\n model\n\n .fetch_result\n\n .as_ref()\n\n .map(|result| div![format!(\"{:#?}\", result)]),\n\n button![ev(Ev::Click, |_| Msg::SendRequest), \"Send request\"],\n\n ],\n\n Status::WaitingForResponse => nodes![\n\n div![\"Waiting for response...\"],\n\n button![ev(Ev::Click, |_| Msg::AbortRequest), \"Abort request\"],\n\n ],\n\n Status::RequestAborted => nodes![\n\n model\n\n .fetch_result\n\n .as_ref()\n\n .map(|result| div![format!(\"{:#?}\", result)]),\n\n button![\n\n attrs! {At::Disabled => false.as_at_value()},\n\n \"Request aborted\"\n\n ],\n\n ],\n\n }\n\n ]\n\n}\n", "file_path": "examples/server_integration/client/src/example_c.rs", "rank": 12, "score": 199491.06444214517 }, { "content": "pub fn view(model: &Model, intro: impl FnOnce(&str, &str) -> Vec<Node<Msg>>) -> Vec<Node<Msg>> {\n\n nodes![\n\n intro(TITLE, DESCRIPTION),\n\n view_message(&model.response_data),\n\n input![\n\n input_ev(Ev::Input, Msg::NewMessageChanged),\n\n attrs! {\n\n At::Value => model.new_message,\n\n At::AutoFocus => AtValue::None,\n\n }\n\n ],\n\n button![ev(Ev::Click, |_| Msg::SendRequest), \"Send message\"],\n\n ]\n\n}\n\n\n", "file_path": "examples/server_integration/client/src/example_a.rs", "rank": 13, "score": 199491.06444214517 }, { "content": "pub fn _all_classes_to_attrs(all_classes: &[String]) -> Attrs {\n\n let mut attrs = Attrs::empty();\n\n if !all_classes.is_empty() {\n\n attrs.add_multiple(\n\n At::Class,\n\n &all_classes.iter().map(String::as_str).collect::<Vec<_>>(),\n\n );\n\n }\n\n attrs\n\n}\n\n\n\n/// `IF!(predicate => expression) -> Option<expression value>`\n\n/// - `expression` is evaluated only when `predicate` is `true` (lazy eval).\n\n/// - Alternative to `bool::then`.\n\n///\n\n/// # Example\n\n///\n\n/// ```rust,no_run\n\n///div![\n\n/// C![\"btn\", IF!(active => \"active\")],\n", "file_path": "src/shortcuts.rs", "rank": 14, "score": 187029.1623728247 }, { "content": "/// Create an event that passes no data, other than it occurred. Foregoes using a closure,\n\n/// in favor of pointing to a message directly.\n\npub fn simple_ev<Ms: Clone + 'static>(trigger: impl Into<Ev>, message: Ms) -> EventHandler<Ms> {\n\n let handler = || Some(message);\n\n let closure_handler = move |_| handler.clone()();\n\n EventHandler::new(trigger, closure_handler)\n\n}\n", "file_path": "src/browser/dom/event_handler.rs", "rank": 15, "score": 176869.77352676727 }, { "content": "pub fn _fill_all_classes(all_classes: &mut Vec<String>, classes: Option<Vec<String>>) {\n\n if let Some(classes) = classes {\n\n for class in classes {\n\n if !class.is_empty() {\n\n all_classes.push(class);\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/shortcuts.rs", "rank": 16, "score": 175065.00426409979 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/el_key/src/lib.rs", "rank": 17, "score": 174152.59137091035 }, { "content": "fn get_request_url() -> impl Into<Cow<'static, str>> {\n\n \"/api/send-message\"\n\n}\n\n\n\n// ------ ------\n\n// Model\n\n// ------ -----\n\n\n\n#[derive(Default)]\n\npub struct Model {\n\n pub new_message: String,\n\n pub response_data: Option<shared::SendMessageResponseBody>,\n\n}\n\n\n\n// ------ ------\n\n// Update\n\n// ------ ------\n\n\n\npub enum Msg {\n\n NewMessageChanged(String),\n\n SendRequest,\n\n Fetched(fetch::Result<shared::SendMessageResponseBody>),\n\n}\n\n\n", "file_path": "examples/server_integration/client/src/example_a.rs", "rank": 18, "score": 168030.96486768973 }, { "content": "fn get_request_url() -> impl Into<Cow<'static, str>> {\n\n \"/api/non-existent-endpoint\"\n\n}\n\n\n\n// ------ ------\n\n// Model\n\n// ------ ------\n\n\n\n#[derive(Default)]\n\npub struct Model {\n\n pub fetch_result: Option<fetch::Result<ExpectedResponseData>>,\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct ExpectedResponseData {\n\n something: String,\n\n}\n\n\n\n// ------ ------\n\n// Update\n\n// ------ ------\n\n\n\npub enum Msg {\n\n SendRequest,\n\n Fetched(fetch::Result<ExpectedResponseData>),\n\n}\n\n\n", "file_path": "examples/server_integration/client/src/example_b.rs", "rank": 19, "score": 168030.96486768973 }, { "content": "fn get_request_url() -> impl Into<Cow<'static, str>> {\n\n \"/api/form\"\n\n}\n\n\n\n// ------ ------\n\n// Model\n\n// ------ ------\n\n\n\n#[derive(Default, Debug)]\n\npub struct Form {\n\n title: String,\n\n description: String,\n\n file: Option<File>,\n\n answer: bool,\n\n}\n\n\n\nimpl Form {\n\n fn to_form_data(&self) -> Result<web_sys::FormData, JsValue> {\n\n let form_data = web_sys::FormData::new()?;\n\n form_data.append_with_str(\"title\", &self.title)?;\n", "file_path": "examples/server_integration/client/src/example_e.rs", "rank": 20, "score": 168030.96486768973 }, { "content": "fn get_request_url() -> impl Into<Cow<'static, str>> {\n\n let response_delay_ms: u32 = 2000;\n\n format!(\"/api/delayed-response/{}\", response_delay_ms)\n\n}\n\n\n\n// ------ ------\n\n// Model\n\n// ------ ------\n\n\n\n#[derive(Default)]\n\npub struct Model {\n\n pub fetch_result: Option<fetch::Result<String>>,\n\n pub request_controller: Option<fetch::RequestController>,\n\n pub status: Status,\n\n}\n\n\n\npub enum Status {\n\n ReadyToSendRequest,\n\n WaitingForResponse,\n\n RequestAborted,\n", "file_path": "examples/server_integration/client/src/example_c.rs", "rank": 21, "score": 168030.96486768973 }, { "content": "fn get_request_url() -> impl Into<Cow<'static, str>> {\n\n let response_delay_ms: u32 = 2500;\n\n format!(\"/api/delayed-response/{}\", response_delay_ms)\n\n}\n\n\n\n// ------ ------\n\n// Model\n\n// ------ ------\n\n\n\n#[derive(Default)]\n\npub struct Model {\n\n pub fetch_result: Option<fetch::Result<String>>,\n\n pub request_controller: Option<fetch::RequestController>,\n\n pub status: Status,\n\n}\n\n\n\npub enum TimeoutStatus {\n\n Enabled,\n\n Disabled,\n\n}\n", "file_path": "examples/server_integration/client/src/example_d.rs", "rank": 22, "score": 168030.96486768973 }, { "content": "pub fn view<Ms: 'static>(lang: &str, code: &str) -> Node<Ms> {\n\n custom![\n\n Tag::from(\"code-block\"),\n\n attrs! {\n\n At::from(\"lang\") => lang,\n\n At::from(\"code\") => code,\n\n }\n\n ]\n\n}\n", "file_path": "examples/custom_elements/src/code_block.rs", "rank": 23, "score": 167590.33143669367 }, { "content": "// wrapper for `log_1` because we don't want to \"leak\" `web_sys` dependency through macro\n\npub fn log_1(data_1: &JsValue) {\n\n web_sys::console::log_1(data_1);\n\n}\n\n\n\n/// Similar to log!\n\n#[macro_export]\n\nmacro_rules! error {\n\n { $($expr:expr),* $(,)? } => {\n\n {\n\n let mut formatted_exprs = Vec::new();\n\n $(\n\n formatted_exprs.push(format!(\"{:#?}\", $crate::shortcuts::wrap_debug(&$expr)));\n\n )*\n\n $crate::shortcuts::error_1(\n\n &formatted_exprs\n\n .as_slice()\n\n .join(\" \")\n\n .into()\n\n );\n\n }\n\n };\n\n}\n", "file_path": "src/shortcuts.rs", "rank": 24, "score": 165659.47348921144 }, { "content": "// wrapper for `error_1` because we don't want to \"leak\" `web_sys` dependency through macro\n\npub fn error_1(data_1: &JsValue) {\n\n web_sys::console::error_1(data_1);\n\n}\n\n\n\n/// A key-value pairs, where the keys and values must implement `ToString`.\n\n#[macro_export]\n\nmacro_rules! key_value_pairs {\n\n { $($key:expr => $value:expr),* $(,)? } => {\n\n {\n\n let mut result = IndexMap::new();\n\n $(\n\n // We can handle arguments of multiple types by using this:\n\n // Strings, &strs, bools, numbers etc.\n\n result.insert($key.to_string(), $value.to_string());\n\n )*\n\n result\n\n }\n\n };\n\n}\n", "file_path": "src/shortcuts.rs", "rank": 25, "score": 165659.47348921144 }, { "content": "/// Checks whether the old element can be updated with a new one.\n\npub fn el_can_be_patched<Ms>(el_old: &El<Ms>, el_new: &El<Ms>) -> bool {\n\n el_old.namespace == el_new.namespace && el_old.tag == el_new.tag && el_old.key == el_new.key\n\n}\n\n\n", "file_path": "src/virtual_dom/patch/patch_gen.rs", "rank": 26, "score": 164008.44426934188 }, { "content": "/// Convenience function to access the `web_sys::HtmlCanvasElement`.\n\n/// /// _Note:_ Returns `None` if there is no element with the given `id` or the element isn't `HtmlCanvasElement`.\n\npub fn canvas(id: &str) -> Option<web_sys::HtmlCanvasElement> {\n\n document()\n\n .get_element_by_id(id)\n\n .and_then(|element| element.dyn_into::<web_sys::HtmlCanvasElement>().ok())\n\n}\n\n\n", "file_path": "src/browser/util.rs", "rank": 27, "score": 162621.98240648175 }, { "content": "pub fn init(orders: &mut impl Orders<Msg>) -> Model {\n\n Model {\n\n value: 0,\n\n _sub_handle: orders.subscribe_with_handle(|_: DoReset| Msg::Reset),\n\n }\n\n}\n\n\n\n// ------ ------\n\n// Model\n\n// ------ ------\n\n\n\npub struct Model {\n\n value: i32,\n\n _sub_handle: SubHandle,\n\n}\n\n\n\n// ------ ------\n\n// Update\n\n// ------ ------\n\n\n\npub enum Msg {\n\n Increment,\n\n Decrement,\n\n Reset,\n\n}\n\n\n", "file_path": "examples/subscribe/src/counter.rs", "rank": 28, "score": 160724.7466125011 }, { "content": "fn toggle(value: &mut bool) {\n\n *value = !*value\n\n}\n\n\n\n// ------ ------\n\n// View\n\n// ------ ------\n\n\n", "file_path": "examples/server_integration/client/src/example_e.rs", "rank": 29, "score": 158058.11158514753 }, { "content": "fn column(title: &str, content: impl IntoNodes<Msg>) -> Node<Msg> {\n\n div![\n\n C![\"column\"],\n\n div![\n\n C![\"box\"],\n\n div![\n\n C![\"menu\"],\n\n p![C![\"menu-label\"], title,],\n\n ul![\n\n C![\"menu-list\", \"content\"],\n\n style! {\n\n St::MaxHeight => vh(80),\n\n St::OverflowY => \"auto\",\n\n },\n\n content.into_nodes(),\n\n ]\n\n ],\n\n ]\n\n ]\n\n}\n\n\n", "file_path": "examples/graphql/src/lib.rs", "rank": 30, "score": 156577.2563576848 }, { "content": "pub fn view<Ms: 'static>(expression: &str) -> Node<Ms> {\n\n custom![Tag::from(\"math-tex\"), expression,]\n\n}\n", "file_path": "examples/custom_elements/src/math_tex.rs", "rank": 31, "score": 156330.8627315763 }, { "content": "// `wasm-bindgen` cannot transfer struct with public closures to JS (yet) so we have to send slice.\n\npub fn start() -> Box<[JsValue]> {\n\n let app = App::start(\"app\", init, update, view);\n\n\n\n create_closures_for_js(&app)\n\n}\n\n\n", "file_path": "examples/update_from_js/src/lib.rs", "rank": 32, "score": 155369.09103409905 }, { "content": "fn send_request_to_top_secret(token: String, orders: &mut impl Orders<Msg>) {\n\n orders.perform_cmd(async {\n\n Msg::TopSecretFetched(\n\n async {\n\n Request::new(format!(\"{}/top_secret\", API_URL))\n\n .header(Header::bearer(token))\n\n .fetch()\n\n .await?\n\n .check_status()?\n\n .text()\n\n .await\n\n }\n\n .await,\n\n )\n\n });\n\n}\n\n\n\n// ------ ------\n\n// Urls\n\n// ------ ------\n", "file_path": "examples/auth/src/lib.rs", "rank": 33, "score": 155220.1663876455 }, { "content": "#[doc(hidden)]\n\npub trait ToCSSValueForToString {\n\n fn to_css_value(&self) -> CSSValue;\n\n}\n\n\n\nimpl<T: ToString> ToCSSValueForToString for T {\n\n fn to_css_value(&self) -> CSSValue {\n\n CSSValue::Some(self.to_string())\n\n }\n\n}\n\n\n\n// impl<T: ToString> ToCSSValue for Option<T>\n", "file_path": "src/virtual_dom/values.rs", "rank": 34, "score": 154819.42062679818 }, { "content": "pub fn store_data<T>(storage: &Storage, name: &str, data: &T)\n\nwhere\n\n T: serde::Serialize,\n\n{\n\n let serialized = serde_json::to_string(&data).expect(\"serialize for `LocalStorage`\");\n\n storage\n\n .set_item(name, &serialized)\n\n .expect(\"save into `LocalStorage`\");\n\n}\n\n\n\n/// Load a store, to a deserializable data structure.\n\n#[deprecated(\n\n since = \"0.7.0\",\n\n note = \"Use `LocalStorage::get` or `SessionStorage::get`.\"\n\n)]\n", "file_path": "src/browser/service/storage.rs", "rank": 35, "score": 152970.7419380299 }, { "content": "pub fn load_data<T>(storage: &Storage, name: &str) -> Option<T>\n\nwhere\n\n T: serde::de::DeserializeOwned,\n\n{\n\n storage\n\n .get_item(name)\n\n .expect(\"try to get item from `LocalStorage`\")\n\n .map(|loaded_serialized| {\n\n serde_json::from_str(&loaded_serialized).expect(\"deserialize from `LocalStorage`\")\n\n })\n\n}\n", "file_path": "src/browser/service/storage.rs", "rank": 36, "score": 152970.7419380299 }, { "content": "#[doc(hidden)]\n\npub trait ToCSSValueForOptionToString {\n\n fn to_css_value(&self) -> CSSValue;\n\n}\n\n\n\nimpl<T: ToString> ToCSSValueForOptionToString for Option<T> {\n\n fn to_css_value(&self) -> CSSValue {\n\n self.as_ref()\n\n .map_or(CSSValue::Ignored, |t| CSSValue::Some(t.to_string()))\n\n }\n\n}\n\n\n\n// ------------- AtValue -------------\n\n\n\n/// Attribute value.\n\n///\n\n/// # Example\n\n///\n\n/// ```rust,no_run\n\n///attrs! {\n\n/// At::Disabled => false.as_at_value(), // same as `=> AtValue::Ignored`\n", "file_path": "src/virtual_dom/values.rs", "rank": 37, "score": 151496.27226204157 }, { "content": "fn view_header(new_todo_title: &str) -> Node<Msg> {\n\n header![\n\n C![\"header\"],\n\n h1![\"todos\"],\n\n input![\n\n C![\"new-todo\"],\n\n attrs! {\n\n At::Placeholder => \"What needs to be done?\";\n\n At::AutoFocus => true.as_at_value();\n\n At::Value => new_todo_title;\n\n },\n\n keyboard_ev(Ev::KeyDown, |keyboard_event| {\n\n IF!(keyboard_event.key_code() == ENTER_KEY => Msg::CreateNewTodo)\n\n }),\n\n input_ev(Ev::Input, Msg::NewTodoTitleChanged),\n\n ]\n\n ]\n\n}\n\n\n\n// ------ main ------\n\n\n", "file_path": "examples/todomvc/src/lib.rs", "rank": 38, "score": 148334.62830035435 }, { "content": "fn disabled_card(card: &Card, el_key_enabled: bool) -> Node<Msg> {\n\n let card_id = card.id;\n\n div![\n\n id!(format!(\"card-table__card-{}\", card.id)),\n\n IF!(el_key_enabled => el_key(&card_id)),\n\n C![\n\n \"card-table__card\",\n\n \"card-table__card--disabled\",\n\n IF!(card.selected => \"card-table__card--selected\"),\n\n ],\n\n style! {\n\n St::Color => card.fg_color.to_string(),\n\n },\n\n ev(Ev::Click, move |_| Msg::ToggleSelected(card_id)),\n\n format!(\"{}\", card.id),\n\n ]\n\n}\n\n\n", "file_path": "examples/el_key/src/lib.rs", "rank": 39, "score": 147060.6442654775 }, { "content": "fn enabled_card(card: &Card, el_key_enabled: bool) -> Node<Msg> {\n\n div![\n\n id!(format!(\"card-table__card-{}\", card.id)),\n\n IF!(el_key_enabled => el_key(&card.id)),\n\n C![\n\n \"card-table__card\",\n\n \"card-table__card--enabled\",\n\n card.drag.map(|drag| match drag {\n\n Drag::Dragged => \"card-table__card--dragged\",\n\n Drag::Over => \"card-table__card--dragover\",\n\n }),\n\n IF!(card.selected => \"card-table__card--selected\"),\n\n ],\n\n attrs! {\n\n At::Draggable => true\n\n },\n\n enabled_card_graphics(card),\n\n enabled_card_event_handlers(card),\n\n ]\n\n}\n\n\n", "file_path": "examples/el_key/src/lib.rs", "rank": 40, "score": 147060.6442654775 }, { "content": "fn view(model: &Model) -> impl IntoNodes<Msg> {\n\n div![\n\n id![\"content\"],\n\n h1![id![\"title\"], \"Element key example\"],\n\n card_table(model),\n\n control_buttons(),\n\n options(model),\n\n readme(&model.readme),\n\n ]\n\n}\n\n\n", "file_path": "examples/el_key/src/lib.rs", "rank": 41, "score": 147029.233361011 }, { "content": "/// Attaches given `ElRef` to the DOM element.\n\n///\n\n/// See `ElRef` for more info.\n\npub fn el_ref<E: Clone>(reference: &ElRef<E>) -> ElRef<E> {\n\n reference.clone()\n\n}\n\n\n\n// ------ ElRef ------\n\n\n\n/// DOM element reference.\n\n/// You want to use it instead of DOM selectors to get raw DOM elements.\n\n///\n\n/// _Note_: Cloning is cheap, it uses only phantom data and `Rc` under the hood.\n\n///\n\n/// # Example\n\n///\n\n/// ```rust,no_run\n\n/// #[derive(Default)]\n\n/// struct Model {\n\n/// canvas: ElRef<web_sys::HtmlCanvasElement>,\n\n/// }\n\n///\n\n/// fn view(model: &Model) -> impl IntoNodes<Msg> {\n", "file_path": "src/virtual_dom/el_ref.rs", "rank": 42, "score": 146396.67758775956 }, { "content": "fn wrap_in_permanent_closure<T>(f: impl FnMut(T) + 'static) -> JsValue\n\nwhere\n\n T: wasm_bindgen::convert::FromWasmAbi + 'static,\n\n{\n\n // `Closure::new` isn't in `stable` Rust (yet) - it's a custom implementation from Seed.\n\n // If you need more flexibility, use `Closure::wrap`.\n\n let closure = Closure::new(f);\n\n let closure_as_js_value = closure.as_ref().clone();\n\n // `forget` leaks `Closure` - we should use it only when\n\n // we want to call given `Closure` more than once.\n\n closure.forget();\n\n closure_as_js_value\n\n}\n\n\n\n// ------ ------\n\n// Extern\n\n// ------ ------\n\n\n\n#[wasm_bindgen]\n\nextern \"C\" {\n\n fn enableClock();\n\n}\n", "file_path": "examples/update_from_js/src/lib.rs", "rank": 43, "score": 140854.27628233325 }, { "content": "pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {\n\n match msg {\n\n Msg::NameChanged(name) => model.form.name = name,\n\n Msg::Submit => {\n\n orders.skip(); // No need to rerender\n\n\n\n let token = \"YWxhZGRpbjpvcGVuc2VzYW1l\";\n\n // Created outside async block because of lifetime reasons\n\n // (we can't use reference to `model.form` in async function).\n\n let request = Request::new(\"/\")\n\n .method(Method::Post)\n\n .header(Header::custom(\"Accept-Language\", \"en\"))\n\n .header(Header::bearer(token))\n\n .json(&model.form)\n\n .expect(\"Serialization failed\");\n\n\n\n orders.perform_cmd(async {\n\n let response = fetch(request).await.expect(\"HTTP request failed\");\n\n\n\n if response.status().is_ok() {\n", "file_path": "examples/fetch/src/post.rs", "rank": 44, "score": 139282.8651274814 }, { "content": "pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {\n\n match msg {\n\n Msg::Fetch => {\n\n orders.skip(); // No need to rerender\n\n orders.perform_cmd(async {\n\n let response = fetch(\"user.json\").await.expect(\"HTTP request failed\");\n\n\n\n let user = response\n\n .check_status() // ensure we've got 2xx status\n\n .expect(\"status check failed\")\n\n .json::<User>()\n\n .await\n\n .expect(\"deserialization failed\");\n\n\n\n Msg::Received(user)\n\n });\n\n }\n\n Msg::Received(user) => {\n\n model.user = Some(user);\n\n }\n\n }\n\n}\n\n\n\n// ------ ------\n\n// View\n\n// ------ ------\n\n\n", "file_path": "examples/fetch/src/simple.rs", "rank": 45, "score": 139282.8651274814 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/counter/src/lib.rs", "rank": 46, "score": 138634.11520971544 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/markdown/src/lib.rs", "rank": 47, "score": 138634.11520971544 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/canvas/src/lib.rs", "rank": 48, "score": 138634.11520971544 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/fetch/src/lib.rs", "rank": 49, "score": 138634.11520971544 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/pages/src/lib.rs", "rank": 50, "score": 138634.11520971544 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/websocket/src/client.rs", "rank": 51, "score": 138634.11520971544 }, { "content": "pub fn end(\n\n mut fps_counter: UniqueViewMut<FpsCounter>,\n\n mut hud: NonSendSync<UniqueViewMut<Hud>>,\n\n positions: View<Position>,\n\n) {\n\n fps_counter.end();\n\n let fps = fps_counter.current.ceil() as u32;\n\n let len = positions.len();\n\n hud.update(len, fps);\n\n}\n", "file_path": "examples/bunnies/src/systems.rs", "rank": 52, "score": 138634.11520971544 }, { "content": "pub fn render(\n\n mut renderer: NonSendSync<UniqueViewMut<SceneRenderer>>,\n\n positions: View<Position>,\n\n stage_area: UniqueView<StageArea>,\n\n img_area: UniqueView<ImageArea>,\n\n instance_positions: UniqueView<InstancePositions>,\n\n) {\n\n renderer\n\n .render(\n\n positions.len(),\n\n &img_area.0,\n\n &stage_area.0,\n\n &instance_positions.0,\n\n )\n\n .unwrap();\n\n}\n\n\n", "file_path": "examples/bunnies/src/systems.rs", "rank": 53, "score": 138634.11520971544 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/todomvc/src/lib.rs", "rank": 54, "score": 138634.11520971544 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/url/src/lib.rs", "rank": 55, "score": 138634.11520971544 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/subscribe/src/lib.rs", "rank": 56, "score": 138634.11520971544 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/graphql/src/lib.rs", "rank": 57, "score": 138634.11520971544 }, { "content": "pub fn update(\n\n mut positions: ViewMut<Position>,\n\n mut speeds: ViewMut<Speed>,\n\n mut gravities: ViewMut<Gravity>,\n\n stage_area: UniqueView<StageArea>,\n\n img_area: UniqueView<ImageArea>,\n\n) {\n\n let stage_size = &stage_area.0;\n\n let img_size = &img_area.0;\n\n\n\n (&mut positions, &mut speeds, &mut gravities)\n\n .iter()\n\n .for_each(|(pos, speed, gravity)| {\n\n let mut pos = &mut pos.0;\n\n let mut speed = &mut speed.0;\n\n let gravity = &gravity.0;\n\n\n\n //movement is made to match https://github.com/pixijs/bunny-mark/blob/master/src/Bunny.js\n\n pos.x += speed.x;\n\n pos.y -= speed.y;\n", "file_path": "examples/bunnies/src/systems.rs", "rank": 58, "score": 138634.11520971544 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/auth/src/lib.rs", "rank": 59, "score": 138634.11520971544 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/animation/src/lib.rs", "rank": 60, "score": 138634.11520971544 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/bunnies/src/lib.rs", "rank": 61, "score": 138634.11520971544 }, { "content": "fn init(_: Url, _: &mut impl Orders<Msg>) -> Model {\n\n Model::new()\n\n}\n\n\n\n// ------ ------\n\n// Model\n\n// ------ ------\n\n\n\n// ------ Model ------\n\n\n", "file_path": "examples/el_key/src/lib.rs", "rank": 62, "score": 136815.74062034665 }, { "content": "/// Request the animation frame.\n\npub fn request_animation_frame(\n\n f: Closure<dyn FnMut(RequestAnimationFrameTime)>,\n\n) -> RequestAnimationFrameHandle {\n\n let request_id = window()\n\n .request_animation_frame(f.as_ref().unchecked_ref())\n\n .expect(\"Problem requesting animation frame\");\n\n\n\n RequestAnimationFrameHandle {\n\n request_id,\n\n _closure: f,\n\n }\n\n}\n\n\n", "file_path": "src/browser/util.rs", "rank": 63, "score": 136051.4451131953 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/tea_component/src/lib.rs", "rank": 64, "score": 136051.4451131953 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/window_events/src/lib.rs", "rank": 65, "score": 136051.4451131953 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/unsaved_changes/src/lib.rs", "rank": 66, "score": 136051.4451131953 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/user_media/src/lib.rs", "rank": 67, "score": 136051.4451131953 }, { "content": "pub fn handle_controller(\n\n mut entities: EntitiesViewMut,\n\n controller: UniqueView<Controller>,\n\n mut positions: ViewMut<Position>,\n\n mut speeds: ViewMut<Speed>,\n\n mut gravities: ViewMut<Gravity>,\n\n stage_area: UniqueView<StageArea>,\n\n img_area: UniqueView<ImageArea>,\n\n mut instance_positions: UniqueViewMut<InstancePositions>,\n\n) {\n\n if *controller == Controller::Adding {\n\n let count = positions.len();\n\n let len = count + N_BUNNIES_PER_TICK;\n\n let stage_size = &stage_area.0;\n\n let img_size = &img_area.0;\n\n\n\n positions.reserve(N_BUNNIES_PER_TICK);\n\n speeds.reserve(N_BUNNIES_PER_TICK);\n\n gravities.reserve(N_BUNNIES_PER_TICK);\n\n\n", "file_path": "examples/bunnies/src/systems.rs", "rank": 68, "score": 136051.4451131953 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/custom_elements/src/lib.rs", "rank": 69, "score": 136051.4451131953 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/component_builder/src/lib.rs", "rank": 70, "score": 136051.4451131953 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/drop_zone/src/lib.rs", "rank": 71, "score": 136051.4451131953 }, { "content": "pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {\n\n match msg {\n\n Msg::SendRequest => {\n\n orders.skip().perform_cmd(async {\n\n Msg::Fetched(\n\n async { fetch(get_request_url()).await?.check_status()?.json().await }.await,\n\n )\n\n });\n\n }\n\n\n\n Msg::Fetched(fetch_result) => {\n\n model.fetch_result = Some(fetch_result);\n\n }\n\n }\n\n}\n\n\n\n// ------ ------\n\n// View\n\n// ------ ------\n\n\n", "file_path": "examples/server_integration/client/src/example_b.rs", "rank": 72, "score": 135056.87190956622 }, { "content": "pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {\n\n match msg {\n\n Msg::TitleChanged(title) => model.form_mut().title = title,\n\n Msg::DescriptionChanged(description) => model.form_mut().description = description,\n\n Msg::FileChanged(file) => {\n\n model.form_mut().file = file;\n\n }\n\n Msg::AnswerChanged => toggle(&mut model.form_mut().answer),\n\n Msg::FormSubmitted(id) => {\n\n let form = mem::take(model.form_mut());\n\n let form_data = form.to_form_data().expect(\"create from data from form\");\n\n orders.perform_cmd(async { Msg::ServerResponded(send_request(form_data).await) });\n\n *model = Model::WaitingForResponse(form);\n\n log!(format!(\"Form {} submitted.\", id));\n\n }\n\n Msg::ServerResponded(Ok(response_data)) => {\n\n *model = Model::ReadyToSubmit(Form::default());\n\n clear_file_input();\n\n log_2(\n\n &\"%cResponse data:\".into(),\n", "file_path": "examples/server_integration/client/src/example_e.rs", "rank": 73, "score": 135056.87190956622 }, { "content": "pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {\n\n match msg {\n\n Msg::SendRequest => {\n\n let (request, controller) = Request::new(get_request_url()).controller();\n\n model.status = Status::WaitingForResponse;\n\n model.fetch_result = None;\n\n model.request_controller = Some(controller);\n\n orders.perform_cmd(async {\n\n Msg::Fetched(async { fetch(request).await?.text().await }.await)\n\n });\n\n }\n\n\n\n Msg::AbortRequest => {\n\n if let Some(controller) = &model.request_controller {\n\n controller.abort();\n\n }\n\n model.status = Status::RequestAborted;\n\n }\n\n\n\n Msg::Fetched(fetch_result) => {\n\n model.status = Status::ReadyToSendRequest;\n\n model.fetch_result = Some(fetch_result);\n\n }\n\n }\n\n}\n\n\n\n// ------ ------\n\n// View\n\n// ------ ------\n\n\n", "file_path": "examples/server_integration/client/src/example_c.rs", "rank": 74, "score": 135056.87190956622 }, { "content": "pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {\n\n match msg {\n\n Msg::NewMessageChanged(message) => {\n\n model.new_message = message;\n\n }\n\n Msg::SendRequest => {\n\n orders.skip().perform_cmd({\n\n let message = model.new_message.clone();\n\n async { Msg::Fetched(send_message(message).await) }\n\n });\n\n }\n\n\n\n Msg::Fetched(Ok(response_data)) => {\n\n model.response_data = Some(response_data);\n\n }\n\n\n\n Msg::Fetched(Err(fetch_error)) => {\n\n log!(\"Example_A error:\", fetch_error);\n\n orders.skip();\n\n }\n", "file_path": "examples/server_integration/client/src/example_a.rs", "rank": 75, "score": 135056.87190956622 }, { "content": "pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {\n\n match msg {\n\n Msg::SendRequest => {\n\n let (request, controller) = Request::new(get_request_url())\n\n .timeout(TIMEOUT)\n\n .controller();\n\n\n\n model.status = Status::WaitingForResponse(TimeoutStatus::Enabled);\n\n model.fetch_result = None;\n\n model.request_controller = Some(controller);\n\n\n\n orders.perform_cmd(async {\n\n Msg::Fetched(async { fetch(request).await?.text().await }.await)\n\n });\n\n }\n\n\n\n Msg::DisableTimeout => {\n\n if let Some(controller) = &model.request_controller {\n\n controller.disable_timeout().expect(\"disable timeout\");\n\n }\n", "file_path": "examples/server_integration/client/src/example_d.rs", "rank": 76, "score": 135056.87190956622 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/server_integration/client/src/lib.rs", "rank": 77, "score": 133636.54543171098 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/pages_keep_state/src/lib.rs", "rank": 78, "score": 133636.54543171098 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n App::start(\"app\", init, update, view);\n\n}\n", "file_path": "examples/pages_hash_routing/src/lib.rs", "rank": 79, "score": 133636.54543171098 }, { "content": "/// Stream no values on predefined time interval in milliseconds.\n\n///\n\n/// Handler has to return `Msg`, `Option<Msg>` or `()`.\n\n///\n\n/// # Example\n\n///\n\n/// ```rust,no_run\n\n///orders.stream(streams::interval(1000, || Msg::OnTick));\n\n///orders.stream_with_handle(streams::interval(1000, || log!(\"Tick!\")));\n\n/// ```\n\n///\n\n/// # Panics\n\n///\n\n/// Panics when the handler doesn't return `Msg`, `Option<Msg>` or `()`.\n\n/// (It will be changed to a compile-time error).\n\npub fn interval<MsU>(\n\n ms: u32,\n\n handler: impl FnOnce() -> MsU + Clone + 'static,\n\n) -> impl Stream<Item = MsU> {\n\n IntervalStream::new(ms).map(move |_| handler.clone()())\n\n}\n\n\n\n// ------ Backoff stream ------\n\n\n", "file_path": "src/app/streams.rs", "rank": 80, "score": 131456.02658758435 }, { "content": "/// Stream retries count in increasing intervals.\n\n///\n\n/// Algorithm - [Truncated exponential backoff](https://cloud.google.com/storage/docs/exponential-backoff)\n\n///\n\n/// # Arguments\n\n///\n\n/// * `max_seconds` - Typically `32` or `64` seconds. Default is `32`.\n\n/// * `handler` - Receives the number of retries (starting from 1); Has to return `Msg`, `Option<Msg>` or `()`.\n\n///\n\n/// # Example\n\n///\n\n/// ```rust,no_run\n\n///orders.stream(streams::backoff(None, |_retries| Msg::OnTick));\n\n///orders.stream_with_handle(streams::backoff(Some(15), |_| log!(\"Tick!\")));\n\n/// ```\n\n///\n\n/// # Panics\n\n///\n\n/// Panics when the handler doesn't return `Msg`, `Option<Msg>` or `()`.\n\n/// (It will be changed to a compile-time error).\n\npub fn backoff<MsU>(\n\n max_seconds: Option<u32>,\n\n handler: impl FnOnce(usize) -> MsU + Clone + 'static,\n\n) -> impl Stream<Item = MsU> {\n\n BackoffStream::new(max_seconds.unwrap_or(32)).map(move |retries| handler.clone()(retries))\n\n}\n\n\n\n// ------ Window Event stream ------\n\n\n", "file_path": "src/app/streams.rs", "rank": 81, "score": 131452.79887264135 }, { "content": "/// Set timeout in milliseconds.\n\n///\n\n/// Handler has to return `Msg`, `Option<Msg>` or `()`.\n\n///\n\n/// # Example\n\n///\n\n/// ```rust,no_run\n\n///orders.perform_cmd_with_handle(cmds::timeout(2000, || Msg::OnTimeout));\n\n///orders.perform_cmd(cmds::timeout(1000, || log!(\"Tick!\")));\n\n/// ```\n\n///\n\n/// # Panics\n\n///\n\n/// Panics when the command doesn't return `Msg`, `Option<Msg>` or `()`.\n\n/// (It will be changed to a compile-time error).\n\npub fn timeout<MsU>(\n\n ms: u32,\n\n handler: impl FnOnce() -> MsU + Clone + 'static,\n\n) -> impl Future<Output = MsU> {\n\n TimeoutFuture::new(ms).map(move |_| handler())\n\n}\n", "file_path": "src/app/cmds.rs", "rank": 82, "score": 131452.79887264135 }, { "content": "/// Stream `Window` `web_sys::Event`s.\n\n///\n\n/// Handler has to return `Msg`, `Option<Msg>` or `()`.\n\n///\n\n/// # Example\n\n///\n\n/// ```rust,no_run\n\n///orders.stream(streams::window_event(Ev::Resize, |_| Msg::OnResize));\n\n///orders.stream_with_handle(streams::window_event(Ev::Click, |_| log!(\"Clicked!\")));\n\n/// ```\n\n///\n\n/// # Panics\n\n///\n\n/// Panics when the handler doesn't return `Msg`, `Option<Msg>` or `()`.\n\n/// (It will be changed to a compile-time error).\n\npub fn window_event<MsU>(\n\n trigger: impl Into<Ev>,\n\n handler: impl FnOnce(Event) -> MsU + Clone + 'static,\n\n) -> impl Stream<Item = MsU> {\n\n EventStream::new(&window(), trigger.into()).map(move |event| handler.clone()(event))\n\n}\n\n\n\n// ------ Document Event stream ------\n\n\n", "file_path": "src/app/streams.rs", "rank": 83, "score": 129037.89919115702 }, { "content": "/// Stream `Document` `web_sys::Event`s.\n\n///\n\n/// Handler has to return `Msg`, `Option<Msg>` or `()`.\n\n///\n\n/// # Example\n\n///\n\n/// ```rust,no_run\n\n///orders.stream(streams::document_event(Ev::SelectionChange, |_| Msg::OnSelection));\n\n///orders.stream_with_handle(streams::document_event(Ev::SelectionChange, |_| log!(\"Selection changed!\")));\n\n/// ```\n\n///\n\n/// # Panics\n\n///\n\n/// Panics when the handler doesn't return `Msg`, `Option<Msg>` or `()`.\n\n/// (It will be changed to a compile-time error).\n\npub fn document_event<MsU>(\n\n trigger: impl Into<Ev>,\n\n handler: impl FnOnce(Event) -> MsU + Clone + 'static,\n\n) -> impl Stream<Item = MsU> {\n\n EventStream::new(&document(), trigger.into()).map(move |event| handler.clone()(event))\n\n}\n", "file_path": "src/app/streams.rs", "rank": 84, "score": 129037.89919115702 }, { "content": "pub fn view<Ms: 'static>(icon: &str, width: Option<u32>, height: Option<u32>) -> Node<Ms> {\n\n custom![\n\n Tag::from(\"feather-icon\"),\n\n attrs! {\n\n At::from(\"icon\") => icon,\n\n At::Width => if let Some(width) = width { AtValue::Some(width.to_string()) } else { AtValue::Ignored },\n\n At::Height => if let Some(height) = height { AtValue::Some(height.to_string()) } else { AtValue::Ignored },\n\n }\n\n ]\n\n}\n", "file_path": "examples/custom_elements/src/feather_icon.rs", "rank": 85, "score": 127525.83278821745 }, { "content": "/// See [`set_interval`](fn.set_interval.html)\n\n///\n\n///\n\n/// # References\n\n/// * [MDN docs](https://developer.mozilla.org/en-US/docs/Wemb/API/WindowOrWorkerGlobalScope/setTimeout)\n\npub fn set_timeout(handler: Box<dyn Fn()>, timeout: i32) {\n\n let callback = Closure::wrap(handler as Box<dyn Fn()>);\n\n util::window()\n\n .set_timeout_with_callback_and_timeout_and_arguments_0(\n\n callback.as_ref().unchecked_ref(),\n\n timeout,\n\n )\n\n .expect(\"Problem setting timeout\");\n\n callback.forget();\n\n}\n\n\n\n/// Introduce `El` and `Tag` into the global namespace for convenience (`El` will be repeated\n\n/// often in the output type of components), and `UpdateEl`, which is required\n\n/// for element-creation macros, input event constructors, and the `History` struct.\n\n/// Expose the `wasm_bindgen` prelude.\n\npub mod prelude {\n\n pub use crate::{\n\n app::{\n\n builder::init::Init, cmds, streams, subs, AfterMount, App, BeforeMount, CmdHandle,\n\n GetElement, MessageMapper, MountType, Orders, RenderInfo, StreamHandle, SubHandle,\n", "file_path": "src/lib.rs", "rank": 86, "score": 127200.94388912604 }, { "content": "/// A high-level wrapper for `web_sys::window.set_interval_with_callback_and_timeout_and_arguments_0`:\n\n///\n\n/// # References\n\n/// * [WASM bindgen closures](https://rustwasm.github.io/wasm-bindgen/examples/closures.html)\n\n/// * [`web_sys` Window](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Window.html)\n\n/// * [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval)\n\npub fn set_interval(handler: Box<dyn Fn()>, timeout: i32) {\n\n let callback = Closure::wrap(handler as Box<dyn Fn()>);\n\n util::window()\n\n .set_interval_with_callback_and_timeout_and_arguments_0(\n\n callback.as_ref().unchecked_ref(),\n\n timeout,\n\n )\n\n .expect(\"Problem setting interval\");\n\n callback.forget();\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 87, "score": 127200.02527325632 }, { "content": "#[allow(clippy::option_map_unit_fn)]\n\npub fn setup_link_listener<Ms>(\n\n update: impl Fn(Ms) + 'static,\n\n notify: impl Fn(Notification) + 'static,\n\n routes: Option<fn(Url) -> Option<Ms>>,\n\n) where\n\n Ms: 'static,\n\n{\n\n let closure = Closure::new(move |event: web_sys::Event| {\n\n event.target()\n\n .and_then(|et| et.dyn_into::<web_sys::Element>().ok())\n\n .and_then(|el| el.closest(\"[href]\").ok())\n\n .flatten()\n\n .and_then(|href_el| match href_el.tag_name().to_lowercase().as_str() {\n\n // Base, Link and Use tags use href for something other than navigation.\n\n \"base\" | \"link\" | \"use\" => None,\n\n _ => Some(href_el)\n\n })\n\n .and_then(|href_el| href_el.get_attribute(\"href\"))\n\n // The first character being / or empty href indicates a rel link, which is what\n\n // we're intercepting.\n", "file_path": "src/browser/service/routing.rs", "rank": 88, "score": 126779.71370811519 }, { "content": "/// Add a listener that handles routing for navigation events like forward and back.\n\npub fn setup_popstate_listener<Ms>(\n\n update: impl Fn(Ms) + 'static,\n\n updated_listener: impl Fn(Closure<dyn FnMut(web_sys::Event)>) + 'static,\n\n notify: impl Fn(Notification) + 'static,\n\n routes: Option<fn(Url) -> Option<Ms>>,\n\n base_path: Rc<Vec<String>>,\n\n) where\n\n Ms: 'static,\n\n{\n\n let closure = Closure::new(move |ev: web_sys::Event| {\n\n let ev = ev\n\n .dyn_ref::<web_sys::PopStateEvent>()\n\n .expect(\"Problem casting as Popstate event\");\n\n\n\n let url = match ev.state().as_string() {\n\n Some(state_str) => {\n\n serde_json::from_str(&state_str).expect(\"Problem deserializing popstate state\")\n\n }\n\n // Only update when requested for an update by the user.\n\n None => Url::current(),\n", "file_path": "src/browser/service/routing.rs", "rank": 89, "score": 126774.93662540361 }, { "content": "/// Add a listener that handles routing when the url hash is changed.\n\npub fn setup_hashchange_listener<Ms>(\n\n update: impl Fn(Ms) + 'static,\n\n updated_listener: impl Fn(Closure<dyn FnMut(web_sys::Event)>) + 'static,\n\n notify: impl Fn(Notification) + 'static,\n\n routes: Option<fn(Url) -> Option<Ms>>,\n\n base_path: Rc<Vec<String>>,\n\n) where\n\n Ms: 'static,\n\n{\n\n // todo: DRY with popstate listener\n\n let closure = Closure::new(move |ev: web_sys::Event| {\n\n let ev = ev\n\n .dyn_ref::<web_sys::HashChangeEvent>()\n\n .expect(\"Problem casting as hashchange event\");\n\n\n\n let url: Url = ev\n\n .new_url()\n\n .parse()\n\n .expect(\"cast hashchange event url to `Url`\");\n\n\n", "file_path": "src/browser/service/routing.rs", "rank": 90, "score": 126774.93662540361 }, { "content": "/// Convenience function to access the `web_sys` history.\n\npub fn history() -> web_sys::History {\n\n window().history().expect(\"Can't find history\")\n\n}\n\n\n", "file_path": "src/browser/util.rs", "rank": 91, "score": 125077.18988636552 }, { "content": "/// Convenience function to access the `web_sys` DOM document.\n\npub fn document() -> web_sys::Document {\n\n window()\n\n .document()\n\n .expect(\"Can't find the window's document\")\n\n}\n\n\n", "file_path": "src/browser/util.rs", "rank": 92, "score": 125077.18988636552 }, { "content": "/// Convenience function to avoid repeating expect logic.\n\npub fn window() -> web_sys::Window {\n\n web_sys::window().expect(\"Can't find the global Window\")\n\n}\n\n\n", "file_path": "src/browser/util.rs", "rank": 93, "score": 125077.18988636552 }, { "content": "fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {\n\n log!(\"update:\", msg);\n\n match msg {\n\n // ------ Selecting ------\n\n Msg::SelectNone => {\n\n model\n\n .cards\n\n .iter_mut()\n\n .for_each(|card| card.selected = false);\n\n }\n\n Msg::ToggleSelected(card_id) => {\n\n if let Some(card) = model.cards.iter_mut().find(|card| card.id == card_id) {\n\n card.selected = !card.selected;\n\n }\n\n }\n\n // ------- Drag and drop ------\n\n Msg::DragStart(card_id) => {\n\n if let Some(card) = model.cards.iter_mut().find(|card| card.id == card_id) {\n\n card.drag = Some(Drag::Dragged);\n\n }\n", "file_path": "examples/el_key/src/lib.rs", "rank": 94, "score": 123098.84221802569 }, { "content": "#[deprecated(since = \"0.7.0\", note = \"Use `LocalStorage` or `SessionStorage`.\")]\n\n#[allow(clippy::module_name_repetitions)]\n\npub fn get_storage() -> Option<Storage> {\n\n web_sys::window()\n\n .expect(\"get `window`\")\n\n .local_storage()\n\n .ok()\n\n .flatten()\n\n}\n\n\n\n/// Create a new store, from a serializable data structure.\n\n#[deprecated(\n\n since = \"0.7.0\",\n\n note = \"Use `LocalStorage::insert` or `SessionStorage::insert`.\"\n\n)]\n", "file_path": "src/browser/service/storage.rs", "rank": 95, "score": 122818.429714558 }, { "content": "pub fn register_workloads(world: &World) {\n\n world\n\n .add_workload(TICK)\n\n .with_system(system!(start))\n\n .with_system(system!(handle_controller))\n\n .with_system(system!(update))\n\n .with_system(system!(commit))\n\n .with_system(system!(render))\n\n .with_system(system!(end))\n\n .build();\n\n}\n\n\n", "file_path": "examples/bunnies/src/systems.rs", "rank": 96, "score": 122814.22732061209 }, { "content": "pub fn view<Ms: 'static>(\n\n model: &Model,\n\n on_click: impl FnOnce() -> Ms + Clone + 'static,\n\n to_msg: impl FnOnce(Msg) -> Ms + Clone + 'static,\n\n) -> Node<Ms> {\n\n div![\n\n ev(Ev::Click, |_| on_click()),\n\n button![\n\n ev(Ev::Click, {\n\n let to_msg = to_msg.clone();\n\n move |_| to_msg(Msg::Decrement)\n\n }),\n\n \"-\"\n\n ],\n\n div![model.value.to_string()],\n\n button![ev(Ev::Click, move |_| to_msg(Msg::Increment)), \"+\"],\n\n ]\n\n}\n", "file_path": "examples/tea_component/src/counter.rs", "rank": 97, "score": 122814.22732061209 }, { "content": "/// Convenience function to access the `web_sys` DOM body.\n\npub fn body() -> web_sys::HtmlElement {\n\n document().body().expect(\"Can't find the document's body\")\n\n}\n\n\n", "file_path": "src/browser/util.rs", "rank": 98, "score": 122814.22732061209 }, { "content": "/// Update the attributes, style, text, and events of an element. Does not\n\n/// process children, and assumes the tag is the same. Assume we've identfied\n\n/// the most-correct pairing between new and old.\n\npub fn patch_el_details<Ms>(\n\n old: &mut El<Ms>,\n\n new: &mut El<Ms>,\n\n old_el_ws: &web_sys::Node,\n\n mailbox: &Mailbox<Ms>,\n\n) {\n\n for (key, new_val) in &new.attrs.vals {\n\n match old.attrs.vals.get(key) {\n\n Some(old_val) => {\n\n // The value's different\n\n if old_val != new_val {\n\n set_attr_value(old_el_ws, key, new_val);\n\n }\n\n }\n\n None => {\n\n set_attr_value(old_el_ws, key, new_val);\n\n }\n\n }\n\n\n\n // We handle value in the vdom using attributes, but the DOM needs\n", "file_path": "src/browser/dom/virtual_dom_bridge.rs", "rank": 99, "score": 122654.87000170379 } ]
Rust
src/node.rs
pmuens/anova
c7d160b5df49bd3d6fbf9cf664025836997f12ab
use crate::{ block::Block, chain::Chain, transaction::Transaction, utils::{Keccak256, Sender}, }; use crate::{mempool::Mempool, utils::hash}; use rand::prelude::SliceRandom; pub struct Node { chain: Chain, mempool: Mempool, nonce: u64, } impl Node { pub fn new() -> Self { let chain = Chain::new(1000); let mempool = Mempool::new(); Node { chain, mempool, nonce: 1, } } pub fn create_transaction(&mut self) { let mut rng = rand::thread_rng(); let mut numbers: Vec<u8> = (1..100).collect(); numbers.shuffle(&mut rng); let sender: Sender = hash(numbers); let tx = Transaction::new(sender, self.nonce); self.add_transaction(tx); self.nonce += 1; } pub fn add_transaction(&mut self, transaction: Transaction) { let index = self.generate_transaction_index(&transaction); self.mempool.insert(index, transaction); } pub fn add_transactions(&mut self, transactions: Vec<Transaction>) { transactions .into_iter() .for_each(|tx| self.add_transaction(tx)); } pub fn propose_block(&self) -> Option<Block> { if let Some(transactions) = self.mempool.get_all_transactions() { let mut prev_block_id = None; if let Some(block) = self.chain.last() { prev_block_id = Some(block.id.clone()); } return Some(Block::new(transactions, prev_block_id)); } None } pub fn finalize_block(&mut self, block: Block) { let tx_indexes: Vec<Keccak256> = block .transactions .iter() .map(|tx| self.generate_transaction_index(tx)) .collect(); self.chain.append(block); self.mempool.remove_transactions(tx_indexes); if let Some(transactions) = self.mempool.get_all_transactions() { self.mempool.clear(); transactions.into_iter().for_each(|tx| { let index = self.generate_transaction_index(&tx); self.mempool.insert(index, tx); }); } } fn generate_transaction_index(&self, transaction: &Transaction) -> Keccak256 { let mut block_id = None; if let Some(block) = self.chain.last() { block_id = Some(block.id.clone()); } let data = bincode::serialize(&(transaction.id.clone(), block_id)).unwrap(); hash(data) } } #[cfg(test)] mod tests { use super::*; #[test] fn new_node() { let node = Node::new(); assert_eq!(node.mempool.get_all_transactions(), None); assert_eq!(node.chain.height(), None); assert_eq!(node.nonce, 1); } #[test] fn create_transaction() { let mut node = Node::new(); node.create_transaction(); assert_eq!(node.mempool.len(), 1); assert_eq!(node.nonce, 2); } #[test] fn add_transaction() { let mut node = Node::new(); let tx = Transaction::new(vec![0, 1, 2, 3, 4], 1); node.add_transaction(tx); assert_eq!(node.mempool.len(), 1); assert_eq!(node.nonce, 1); } #[test] fn add_transactions() { let mut node = Node::new(); let tx_1 = Transaction::new(vec![0, 1, 2, 3, 4], 1); let tx_2 = Transaction::new(vec![5, 6, 7, 8, 9], 1); let transactions = vec![tx_1, tx_2]; node.add_transactions(transactions); assert_eq!(node.mempool.len(), 2); assert_eq!(node.nonce, 1); } #[test] fn propose_block() { let mut node = Node::new(); let block = node.propose_block(); assert_eq!(block, None); node.create_transaction(); let block = node.propose_block(); assert!(block.is_some()); let block = block.unwrap(); assert_eq!(block.transactions.len(), 1); assert_eq!(block.get_previous_block_id(), None); } #[test] fn finalize_single_block() { let mut node = Node::new(); node.create_transaction(); let block_proposal = node.propose_block().unwrap(); node.finalize_block(block_proposal.clone()); assert_eq!(node.chain.height(), Some(0)); assert_eq!(node.chain.last(), Some(&block_proposal)); assert_eq!(node.mempool.get_all_transactions(), None); } #[test] fn finalize_multiple_blocks() { let mut node = Node::new(); node.create_transaction(); let first_block = node.propose_block().unwrap(); node.finalize_block(first_block.clone()); node.create_transaction(); let second_block = node.propose_block().unwrap(); node.finalize_block(second_block.clone()); assert_eq!(node.chain.height(), Some(1)); assert_eq!(node.chain.last(), Some(&second_block)); assert_eq!(node.mempool.len(), 0); assert_eq!(node.mempool.get_all_transactions(), None); } #[test] fn finalize_block_pending_transactions() { let mut node = Node::new(); node.create_transaction(); let block_proposal = node.propose_block().unwrap(); node.create_transaction(); node.create_transaction(); node.finalize_block(block_proposal.clone()); assert_eq!(node.chain.height(), Some(0)); assert_eq!(node.chain.last(), Some(&block_proposal)); assert_eq!(node.mempool.len(), 2); } #[test] fn lifecycle() { let mut node = Node::new(); assert_eq!(node.chain.height(), None); node.create_transaction(); let first_block = node.propose_block().unwrap(); node.finalize_block(first_block.clone()); assert_eq!(first_block.transactions.len(), 1); assert_eq!(first_block.get_previous_block_id(), None); assert_eq!(node.chain.get(0), Some(&first_block)); assert_eq!(node.chain.height(), Some(0)); assert_eq!(node.mempool.len(), 0); node.create_transaction(); node.create_transaction(); let second_block = node.propose_block().unwrap(); node.finalize_block(second_block.clone()); assert_eq!(second_block.transactions.len(), 2); assert_eq!(second_block.get_previous_block_id(), Some(&first_block.id)); assert_eq!(node.chain.get(1), Some(&second_block)); assert_eq!(node.chain.height(), Some(1)); assert_eq!(node.mempool.len(), 0); node.create_transaction(); node.create_transaction(); node.create_transaction(); let third_block = node.propose_block().unwrap(); node.create_transaction(); node.create_transaction(); node.finalize_block(third_block.clone()); assert_eq!(third_block.transactions.len(), 3); assert_eq!(third_block.get_previous_block_id(), Some(&second_block.id)); assert_eq!(node.chain.get(2), Some(&third_block)); assert_eq!(node.chain.height(), Some(2)); assert_eq!(node.mempool.len(), 2); let tx_1 = Transaction::new(vec![0, 1, 2, 3, 4], 1); let tx_2 = Transaction::new(vec![5, 6, 7, 8, 9], 1); let transactions = vec![tx_1, tx_2]; node.add_transactions(transactions); let fourth_block = node.propose_block().unwrap(); node.finalize_block(fourth_block.clone()); assert_eq!(fourth_block.transactions.len(), 4); assert_eq!(fourth_block.get_previous_block_id(), Some(&third_block.id)); assert_eq!(node.chain.get(3), Some(&fourth_block)); assert_eq!(node.chain.height(), Some(3)); assert_eq!(node.mempool.len(), 0); } #[test] fn generate_transaction_index() { let mut node = Node::new(); let tx = Transaction::new(vec![0, 1, 2, 3, 4], 1); let index = node.generate_transaction_index(&tx); assert_eq!( index, vec![ 131, 104, 201, 189, 46, 213, 139, 247, 167, 5, 96, 68, 185, 137, 240, 74, 88, 236, 236, 163, 205, 63, 31, 84, 42, 72, 102, 49, 96, 111, 237, 138 ] ); let block = Block::new(vec![tx.clone()], None); node.chain.append(block); let index = node.generate_transaction_index(&tx); assert_eq!( index, vec![ 207, 58, 24, 227, 9, 92, 25, 41, 58, 138, 229, 70, 116, 80, 222, 43, 52, 244, 40, 144, 108, 8, 75, 38, 81, 216, 33, 89, 84, 248, 102, 53 ] ) } }
use crate::{ block::Block, chain::Chain, transaction::Transaction, utils::{Keccak256, Sender}, }; use crate::{mempool::Mempool, utils::hash}; use rand::prelude::SliceRandom; pub struct Node { chain: Chain, mempool: Mempool, nonce: u64, } impl Node { pub fn new() -> Self { let chain = Chain::new(1000); let mempool = Mempool::new(); Node { chain, mempool, nonce: 1, } } pub fn create_transaction(&mut self) { let mut rng = rand::thread_rng(); let mut numbers: Vec<u8> = (1..100).collect(); numbers.shuffle(&mut rng); let sender: Sender = hash(numbers); let tx = Transaction::new(sender, self.nonce); self.add_transaction(tx); self.nonce += 1; } pub fn add_transaction(&mut self, transaction: Transaction) { let index = self.generate_transaction_index(&transaction); self.mempool.insert(index, transaction); } pub fn add_transactions(&mut self, transactions: Vec<Transaction>) { transactions .into_iter() .for_each(|tx| self.add_transaction(tx)); } pub fn propose_block(&self) -> Option<Block> { if let Some(transactions) = self.mempool.get_all_transactions() { let mut prev_block_id = None; if let Some(block) = self.chain.last() { prev_block_id = Some(block.id.clone()); } return Some(Block::new(transactions, prev_block_id)); } None } pub fn finalize_block(&mut self, block: Block) { let tx_indexes: Vec<Keccak256> = block .transactions .iter() .map(|tx| self.generate_transaction_index(tx)) .collect(); self.chain.append(block); self.mempool.remove_transactions(tx_indexes); if let Some(transactions) = self.mempool.get_all_transactions() { self.mempool.clear(); transactions.into_iter().for_each(|tx| { let index = self.generate_transaction_index(&tx); self.mempool.insert(index, tx); }); } } fn generate_transaction_index(&self, transaction: &Transaction) -> Keccak256 { let mut block_id = None; if let Some(block) = self.chain.last() { block_id = Some(block.id.clone()); } let data = bincode::serialize(&(transaction.id.clone(), block_id)).unwrap(); hash(data) } } #[cfg(test)] mod tests { use super::*; #[test] fn new_node() { let node = Node::new(); assert_eq!(node.mempool.get_all_transactions(), None); assert_eq!(node.chain.height(), None); assert_eq!(node.nonce, 1); } #[test] fn create_transaction() { let mut node = Node::new(); node.create_transaction(); assert_eq!(node.mempool.len(), 1); assert_eq!(node.nonce, 2); } #[test] fn add_transaction() { let mut node = Node::new(); let tx = Transaction::new(vec![0, 1, 2, 3, 4],
#[test] fn add_transactions() { let mut node = Node::new(); let tx_1 = Transaction::new(vec![0, 1, 2, 3, 4], 1); let tx_2 = Transaction::new(vec![5, 6, 7, 8, 9], 1); let transactions = vec![tx_1, tx_2]; node.add_transactions(transactions); assert_eq!(node.mempool.len(), 2); assert_eq!(node.nonce, 1); } #[test] fn propose_block() { let mut node = Node::new(); let block = node.propose_block(); assert_eq!(block, None); node.create_transaction(); let block = node.propose_block(); assert!(block.is_some()); let block = block.unwrap(); assert_eq!(block.transactions.len(), 1); assert_eq!(block.get_previous_block_id(), None); } #[test] fn finalize_single_block() { let mut node = Node::new(); node.create_transaction(); let block_proposal = node.propose_block().unwrap(); node.finalize_block(block_proposal.clone()); assert_eq!(node.chain.height(), Some(0)); assert_eq!(node.chain.last(), Some(&block_proposal)); assert_eq!(node.mempool.get_all_transactions(), None); } #[test] fn finalize_multiple_blocks() { let mut node = Node::new(); node.create_transaction(); let first_block = node.propose_block().unwrap(); node.finalize_block(first_block.clone()); node.create_transaction(); let second_block = node.propose_block().unwrap(); node.finalize_block(second_block.clone()); assert_eq!(node.chain.height(), Some(1)); assert_eq!(node.chain.last(), Some(&second_block)); assert_eq!(node.mempool.len(), 0); assert_eq!(node.mempool.get_all_transactions(), None); } #[test] fn finalize_block_pending_transactions() { let mut node = Node::new(); node.create_transaction(); let block_proposal = node.propose_block().unwrap(); node.create_transaction(); node.create_transaction(); node.finalize_block(block_proposal.clone()); assert_eq!(node.chain.height(), Some(0)); assert_eq!(node.chain.last(), Some(&block_proposal)); assert_eq!(node.mempool.len(), 2); } #[test] fn lifecycle() { let mut node = Node::new(); assert_eq!(node.chain.height(), None); node.create_transaction(); let first_block = node.propose_block().unwrap(); node.finalize_block(first_block.clone()); assert_eq!(first_block.transactions.len(), 1); assert_eq!(first_block.get_previous_block_id(), None); assert_eq!(node.chain.get(0), Some(&first_block)); assert_eq!(node.chain.height(), Some(0)); assert_eq!(node.mempool.len(), 0); node.create_transaction(); node.create_transaction(); let second_block = node.propose_block().unwrap(); node.finalize_block(second_block.clone()); assert_eq!(second_block.transactions.len(), 2); assert_eq!(second_block.get_previous_block_id(), Some(&first_block.id)); assert_eq!(node.chain.get(1), Some(&second_block)); assert_eq!(node.chain.height(), Some(1)); assert_eq!(node.mempool.len(), 0); node.create_transaction(); node.create_transaction(); node.create_transaction(); let third_block = node.propose_block().unwrap(); node.create_transaction(); node.create_transaction(); node.finalize_block(third_block.clone()); assert_eq!(third_block.transactions.len(), 3); assert_eq!(third_block.get_previous_block_id(), Some(&second_block.id)); assert_eq!(node.chain.get(2), Some(&third_block)); assert_eq!(node.chain.height(), Some(2)); assert_eq!(node.mempool.len(), 2); let tx_1 = Transaction::new(vec![0, 1, 2, 3, 4], 1); let tx_2 = Transaction::new(vec![5, 6, 7, 8, 9], 1); let transactions = vec![tx_1, tx_2]; node.add_transactions(transactions); let fourth_block = node.propose_block().unwrap(); node.finalize_block(fourth_block.clone()); assert_eq!(fourth_block.transactions.len(), 4); assert_eq!(fourth_block.get_previous_block_id(), Some(&third_block.id)); assert_eq!(node.chain.get(3), Some(&fourth_block)); assert_eq!(node.chain.height(), Some(3)); assert_eq!(node.mempool.len(), 0); } #[test] fn generate_transaction_index() { let mut node = Node::new(); let tx = Transaction::new(vec![0, 1, 2, 3, 4], 1); let index = node.generate_transaction_index(&tx); assert_eq!( index, vec![ 131, 104, 201, 189, 46, 213, 139, 247, 167, 5, 96, 68, 185, 137, 240, 74, 88, 236, 236, 163, 205, 63, 31, 84, 42, 72, 102, 49, 96, 111, 237, 138 ] ); let block = Block::new(vec![tx.clone()], None); node.chain.append(block); let index = node.generate_transaction_index(&tx); assert_eq!( index, vec![ 207, 58, 24, 227, 9, 92, 25, 41, 58, 138, 229, 70, 116, 80, 222, 43, 52, 244, 40, 144, 108, 8, 75, 38, 81, 216, 33, 89, 84, 248, 102, 53 ] ) } }
1); node.add_transaction(tx); assert_eq!(node.mempool.len(), 1); assert_eq!(node.nonce, 1); }
function_block-function_prefixed
[ { "content": "use bincode;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::utils;\n\nuse super::utils::{BinEncoding, Keccak256, Sender};\n\n\n\n/// A Transaction which includes a reference to its sender and a nonce.\n\n#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]\n\npub struct Transaction {\n\n /// Id which uniquely identifies the Transaction.\n\n pub id: Keccak256,\n\n /// Entity which created the Transaction.\n\n sender: Sender,\n\n /// Nonce used to mitigate replay attacks.\n\n nonce: u64,\n\n}\n\n\n\nimpl Transaction {\n\n /// Creates a new Transaction.\n\n pub fn new(sender: Sender, nonce: u64) -> Self {\n", "file_path": "src/transaction.rs", "rank": 0, "score": 21471.267735564208 }, { "content": " }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn new_transaction() {\n\n let tx = Transaction::new(vec![1, 2, 3, 4, 5], 42);\n\n let expected = Transaction {\n\n id: vec![\n\n 242, 173, 79, 62, 149, 64, 34, 43, 218, 41, 24, 9, 145, 148, 96, 195, 129, 80, 125,\n\n 126, 255, 231, 209, 59, 221, 242, 186, 41, 33, 28, 79, 50,\n\n ],\n\n sender: vec![1, 2, 3, 4, 5],\n\n nonce: 42,\n\n };\n\n\n\n assert_eq!(tx, expected);\n", "file_path": "src/transaction.rs", "rank": 1, "score": 21468.171238536826 }, { "content": " let id = Transaction::generate_id(&sender, &nonce);\n\n Transaction { id, sender, nonce }\n\n }\n\n\n\n /// Generates a unique Transaction id.\n\n pub fn generate_id(sender: &Sender, nonce: &u64) -> Keccak256 {\n\n let serialized = Transaction::serialize(&sender, &nonce);\n\n utils::hash(&serialized)\n\n }\n\n\n\n /// Serializes the Transaction data into a binary representation.\n\n pub fn serialize(sender: &Sender, nonce: &u64) -> BinEncoding<Transaction> {\n\n let values = (sender, nonce);\n\n bincode::serialize(&values).unwrap()\n\n }\n\n\n\n /// Deserializes a Transactions binary representation.\n\n pub fn deserialize(data: BinEncoding<Transaction>) -> Transaction {\n\n let (sender, nonce) = bincode::deserialize(&data[..]).unwrap();\n\n Transaction::new(sender, nonce)\n", "file_path": "src/transaction.rs", "rank": 2, "score": 21465.876115894982 }, { "content": " }\n\n\n\n #[test]\n\n fn serde() {\n\n let sender = vec![0, 1, 2, 3, 4];\n\n let nonce = 42;\n\n let tx = Transaction::new(sender.clone(), nonce);\n\n\n\n let serialized = Transaction::serialize(&sender, &nonce);\n\n assert_eq!(\n\n serialized,\n\n vec![5, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 42, 0, 0, 0, 0, 0, 0, 0]\n\n );\n\n\n\n let deserialized = Transaction::deserialize(serialized);\n\n assert_eq!(deserialized, tx);\n\n }\n\n}\n", "file_path": "src/transaction.rs", "rank": 3, "score": 21462.651813894172 }, { "content": " self.0.last()\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::transaction::Transaction;\n\n\n\n #[test]\n\n fn new_chain() {\n\n let chain = Chain::new(100);\n\n assert_eq!(chain.0.len(), 0);\n\n }\n\n\n\n #[test]\n\n fn height() {\n\n let tx = Transaction::new(vec![0, 1, 2, 3, 4], 1);\n\n let block = Block::new(vec![tx], None);\n\n\n", "file_path": "src/chain.rs", "rank": 4, "score": 21266.347191194596 }, { "content": "use std::collections::BTreeMap;\n\n\n\nuse crate::{transaction::Transaction, utils::Keccak256};\n\n\n\n/// A pool that stores pending [Transactions](crate::transaction::Transaction) in memory.\n\npub struct Mempool(BTreeMap<Keccak256, Transaction>);\n\n\n\nimpl Mempool {\n\n /// Creates a new Mempool.\n\n pub fn new() -> Self {\n\n let mempool = BTreeMap::new();\n\n Mempool(mempool)\n\n }\n\n\n\n /// Insert a new Transaction into the Mempool.\n\n pub fn insert(&mut self, index: Keccak256, transaction: Transaction) {\n\n self.0.insert(index, transaction);\n\n }\n\n\n\n /// Remove all Transactions in the Mempool.\n", "file_path": "src/mempool.rs", "rank": 5, "score": 21265.71831659052 }, { "content": "\n\n /// Return all Transactions currently available in the Mempool.\n\n pub fn get_all_transactions(&self) -> Option<Vec<Transaction>> {\n\n if self.len() != 0 {\n\n return Some(self.0.values().cloned().collect());\n\n }\n\n None\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn new_mempool() {\n\n let mempool = Mempool::new();\n\n assert_eq!(mempool.0.len(), 0);\n\n }\n\n\n", "file_path": "src/mempool.rs", "rank": 6, "score": 21264.386044120845 }, { "content": " pub fn clear(&mut self) {\n\n self.0.clear();\n\n }\n\n\n\n /// Returns the number of Transactions in the Mempool.\n\n pub fn len(&self) -> usize {\n\n self.0.len()\n\n }\n\n\n\n /// Remove Transactions based on their indexes from the Mempool. Return the\n\n /// number of removed Transactions.\n\n pub fn remove_transactions(&mut self, indexes: Vec<Keccak256>) -> usize {\n\n let mut removed = 0;\n\n for index in indexes.iter() {\n\n if let Some(_) = self.0.remove(index) {\n\n removed += 1;\n\n }\n\n }\n\n removed\n\n }\n", "file_path": "src/mempool.rs", "rank": 7, "score": 21263.283391578254 }, { "content": "use super::block::Block;\n\n\n\n/// An immutable Chain made up of multiple [Blocks](crate::block::Block).\n\npub struct Chain(Vec<Block>);\n\n\n\nimpl Chain {\n\n /// Creates a new Chain.\n\n pub fn new(init_capacity: usize) -> Self {\n\n let chain: Vec<Block> = Vec::with_capacity(init_capacity);\n\n Chain(chain)\n\n }\n\n\n\n /// Appends a new Block and returns the current height.\n\n pub fn append(&mut self, mut block: Block) -> u64 {\n\n let previous_block = self.0.last();\n\n let mut previous_block_id = None;\n\n if let Some(prev_block) = previous_block {\n\n previous_block_id = Some(prev_block.id.clone());\n\n }\n\n block.set_previous_block_id(previous_block_id);\n", "file_path": "src/chain.rs", "rank": 8, "score": 21262.003857680316 }, { "content": " let tx = Transaction::new(vec![0, 1, 2, 3, 4], 1);\n\n let block = Block::new(vec![tx], None);\n\n\n\n let mut chain = Chain::new(1);\n\n chain.append(block.clone());\n\n\n\n assert_eq!(chain.last(), Some(&block));\n\n }\n\n\n\n #[test]\n\n fn append_multiple_blocks() {\n\n let tx_1 = Transaction::new(vec![0, 1, 2, 3, 4], 1);\n\n let tx_2 = Transaction::new(vec![0, 1, 2, 3, 4], 2);\n\n let tx_3 = Transaction::new(vec![5, 6, 7, 8, 9], 1);\n\n\n\n let block_1 = Block::new(vec![tx_1.clone(), tx_2.clone()], None);\n\n let block_2 = Block::new(vec![tx_3.clone()], None);\n\n\n\n let mut chain = Chain::new(100);\n\n let mut height;\n", "file_path": "src/chain.rs", "rank": 9, "score": 21261.39370713725 }, { "content": " let mut chain = Chain::new(1);\n\n let height = chain.append(block);\n\n\n\n assert_eq!(height, 0);\n\n assert_eq!(chain.height(), Some(0));\n\n }\n\n\n\n #[test]\n\n fn get() {\n\n let tx = Transaction::new(vec![0, 1, 2, 3, 4], 1);\n\n let block = Block::new(vec![tx], None);\n\n\n\n let mut chain = Chain::new(1);\n\n chain.append(block.clone());\n\n\n\n assert_eq!(chain.get(0), Some(&block));\n\n }\n\n\n\n #[test]\n\n fn last() {\n", "file_path": "src/chain.rs", "rank": 10, "score": 21259.763741574105 }, { "content": " #[test]\n\n fn insert() {\n\n let tx = Transaction::new(vec![0, 1, 2, 3, 4], 1);\n\n let index = tx.id.clone();\n\n\n\n let mut mempool = Mempool::new();\n\n mempool.insert(index.clone(), tx.clone());\n\n\n\n assert_eq!(mempool.0.len(), 1);\n\n assert_eq!(mempool.0.get(&index), Some(&tx));\n\n }\n\n\n\n #[test]\n\n fn clear() {\n\n let tx = Transaction::new(vec![0, 1, 2, 3, 4], 1);\n\n let index = tx.id.clone();\n\n\n\n let mut mempool = Mempool::new();\n\n mempool.insert(index, tx);\n\n\n", "file_path": "src/mempool.rs", "rank": 11, "score": 21259.60309465593 }, { "content": " self.0.push(block);\n\n // We can safely unwrap here given that we just appended a Block\n\n self.height().unwrap()\n\n }\n\n\n\n /// Returns the current height.\n\n pub fn height(&self) -> Option<u64> {\n\n if self.0.is_empty() {\n\n return None;\n\n }\n\n Some((self.0.len() - 1) as u64)\n\n }\n\n\n\n /// Returns a reference to the Block at the given index.\n\n pub fn get(&self, index: usize) -> Option<&Block> {\n\n self.0.get(index)\n\n }\n\n\n\n /// Returns a reference to the last Block.\n\n pub fn last(&self) -> Option<&Block> {\n", "file_path": "src/chain.rs", "rank": 12, "score": 21257.262697984064 }, { "content": " mempool.insert(tx_3_idx.clone(), tx_3.clone());\n\n\n\n let removed = mempool.remove_transactions(vec![tx_1_idx, tx_3_idx]);\n\n\n\n assert_eq!(removed, 2);\n\n assert_eq!(mempool.0.len(), 1);\n\n assert_eq!(mempool.0.get(&tx_2_idx), Some(&tx_2));\n\n }\n\n\n\n #[test]\n\n fn get_all_transactions() {\n\n let tx_1 = Transaction::new(vec![0, 1, 2, 3, 4], 1);\n\n let tx_2 = Transaction::new(vec![5, 6, 7, 8, 9], 1);\n\n\n\n let mut mempool = Mempool::new();\n\n\n\n let transactions = mempool.get_all_transactions();\n\n assert_eq!(transactions, None);\n\n\n\n mempool.insert(tx_1.id.clone(), tx_1.clone());\n\n mempool.insert(tx_2.id.clone(), tx_2.clone());\n\n let expected = vec![tx_2, tx_1];\n\n\n\n let transactions = mempool.get_all_transactions();\n\n assert_eq!(transactions, Some(expected));\n\n }\n\n}\n", "file_path": "src/mempool.rs", "rank": 13, "score": 21256.194740793628 }, { "content": " mempool.clear();\n\n assert_eq!(mempool.0.len(), 0);\n\n }\n\n\n\n #[test]\n\n fn remove_transactions() {\n\n let tx_1 = Transaction::new(vec![0, 1, 2, 3, 4], 1);\n\n let tx_2 = Transaction::new(vec![5, 6, 7, 8, 9], 1);\n\n let tx_3 = Transaction::new(vec![0, 1, 2, 3, 4], 2);\n\n let tx_1_idx = tx_1.id.clone();\n\n let tx_2_idx = tx_2.id.clone();\n\n let tx_3_idx = tx_3.id.clone();\n\n\n\n let mut mempool = Mempool::new();\n\n\n\n let removed = mempool.remove_transactions(vec![tx_2_idx.clone()]);\n\n assert_eq!(removed, 0);\n\n\n\n mempool.insert(tx_1_idx.clone(), tx_1.clone());\n\n mempool.insert(tx_2_idx.clone(), tx_2.clone());\n", "file_path": "src/mempool.rs", "rank": 14, "score": 21255.49958054894 }, { "content": " height = chain.append(block_1);\n\n assert_eq!(height, 0);\n\n height = chain.append(block_2);\n\n assert_eq!(height, 1);\n\n\n\n let appended_block_1 = chain.get(0).unwrap();\n\n let appended_block_2 = chain.get(1).unwrap();\n\n\n\n // Ensure that the first block has a `previous_block_id` of `None`\n\n assert_eq!(appended_block_1.get_previous_block_id(), None);\n\n\n\n // Ensure that the second block refers to the first Block\n\n assert_eq!(\n\n appended_block_2.get_previous_block_id().unwrap(),\n\n &appended_block_1.id\n\n );\n\n }\n\n}\n", "file_path": "src/chain.rs", "rank": 15, "score": 21250.740533349293 }, { "content": "use super::transaction::Transaction;\n\nuse super::utils;\n\nuse super::utils::{BinEncoding, Keccak256};\n\n\n\n/// A Block that contains multiple [Transactions](crate::transaction::Transaction).\n\n#[derive(Debug, Clone, PartialEq)]\n\npub struct Block {\n\n /// Id which uniquely identifies the Block.\n\n pub id: Keccak256,\n\n /// List of transactions included in this Block.\n\n pub transactions: Vec<Transaction>,\n\n /// Id which references the preceding Block.\n\n prev_block_id: Option<Keccak256>,\n\n}\n\n\n\nimpl Block {\n\n /// Creates a new Block.\n\n pub fn new(transactions: Vec<Transaction>, prev_block_id: Option<Keccak256>) -> Self {\n\n let id = Block::generate_id(&transactions, prev_block_id.as_ref());\n\n Block {\n", "file_path": "src/block.rs", "rank": 16, "score": 21156.511306407945 }, { "content": "}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn new_block() {\n\n let tx_1 = Transaction::new(vec![0, 1, 2, 3, 4], 1);\n\n let tx_2 = Transaction::new(vec![0, 1, 2, 3, 4], 2);\n\n let tx_3 = Transaction::new(vec![5, 6, 7, 8, 9], 1);\n\n\n\n let block = Block::new(vec![tx_1.clone(), tx_2.clone(), tx_3.clone()], None);\n\n let expected = Block {\n\n id: vec![\n\n 246, 134, 115, 10, 204, 145, 13, 37, 13, 114, 184, 74, 164, 48, 50, 144, 22, 104,\n\n 204, 116, 53, 94, 84, 254, 216, 22, 97, 58, 245, 188, 45, 21,\n\n ],\n\n transactions: vec![tx_1.clone(), tx_2.clone(), tx_3.clone()],\n\n prev_block_id: None,\n", "file_path": "src/block.rs", "rank": 17, "score": 21156.344917425504 }, { "content": " ]\n\n );\n\n\n\n let deserialized = Block::deserialize(serialized);\n\n assert_eq!(deserialized, block);\n\n }\n\n\n\n #[test]\n\n fn set_previous_block_id() {\n\n let tx = Transaction::new(vec![0, 1, 2, 3, 4], 1);\n\n\n\n let mut block = Block::new(vec![tx.clone()], None);\n\n let expected_initial = Block {\n\n id: vec![\n\n 61, 76, 173, 32, 98, 204, 110, 230, 105, 241, 153, 253, 74, 212, 214, 61, 101, 52,\n\n 42, 176, 46, 29, 206, 216, 251, 40, 250, 159, 168, 103, 81, 99,\n\n ],\n\n transactions: vec![tx.clone()],\n\n prev_block_id: None,\n\n };\n", "file_path": "src/block.rs", "rank": 18, "score": 21151.88543310605 }, { "content": " prev_block_id: Option<&Keccak256>,\n\n ) -> Keccak256 {\n\n let serialized = Block::serialize(&transactions, prev_block_id);\n\n utils::hash(&serialized)\n\n }\n\n\n\n /// Serializes the Block data into a binary representation.\n\n pub fn serialize(\n\n transactions: &Vec<Transaction>,\n\n prev_block_id: Option<&Keccak256>,\n\n ) -> BinEncoding<Block> {\n\n let values = (transactions, prev_block_id);\n\n bincode::serialize(&values).unwrap()\n\n }\n\n\n\n /// Deserializes a Blocks binary representation.\n\n pub fn deserialize(data: BinEncoding<Block>) -> Block {\n\n let (transactions, prev_block_id) = bincode::deserialize(&data[..]).unwrap();\n\n Block::new(transactions, prev_block_id)\n\n }\n", "file_path": "src/block.rs", "rank": 19, "score": 21150.299198475965 }, { "content": " id,\n\n transactions,\n\n prev_block_id,\n\n }\n\n }\n\n\n\n /// Returns a reference to the previous Block id.\n\n pub fn get_previous_block_id(&self) -> Option<&Keccak256> {\n\n self.prev_block_id.as_ref()\n\n }\n\n\n\n /// Sets the previous Block id and updates the Blocks id.\n\n pub fn set_previous_block_id(&mut self, prev_block_id: Option<Keccak256>) {\n\n self.prev_block_id = prev_block_id;\n\n self.id = Block::generate_id(&self.transactions, self.prev_block_id.as_ref());\n\n }\n\n\n\n /// Generates a unique Block id.\n\n pub fn generate_id(\n\n transactions: &Vec<Transaction>,\n", "file_path": "src/block.rs", "rank": 20, "score": 21149.300962277808 }, { "content": " };\n\n\n\n assert_eq!(block, expected);\n\n }\n\n\n\n #[test]\n\n fn serde() {\n\n let tx_1 = Transaction::new(vec![0, 1, 2, 3, 4], 1);\n\n let transactions = vec![tx_1];\n\n let prev_block_id = Some(vec![5, 6, 7, 8, 9]);\n\n let block = Block::new(transactions.clone(), prev_block_id.clone());\n\n\n\n let serialized = Block::serialize(&transactions, prev_block_id.clone().as_ref());\n\n assert_eq!(\n\n serialized,\n\n vec![\n\n 1, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 196, 70, 213, 169, 141, 198, 53,\n\n 47, 112, 185, 125, 254, 146, 41, 135, 204, 30, 126, 28, 159, 0, 167, 6, 219, 32,\n\n 215, 216, 240, 151, 197, 172, 26, 5, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 1, 0, 0,\n\n 0, 0, 0, 0, 0, 1, 5, 0, 0, 0, 0, 0, 0, 0, 5, 6, 7, 8, 9\n", "file_path": "src/block.rs", "rank": 21, "score": 21148.552385178686 }, { "content": " assert_eq!(block, expected_initial);\n\n\n\n // Update the previous Block id\n\n block.set_previous_block_id(Some(vec![1, 2, 3, 4]));\n\n let expected_updated = Block {\n\n id: vec![\n\n 137, 184, 196, 140, 0, 212, 191, 29, 101, 3, 16, 175, 81, 94, 71, 5, 59, 215, 214,\n\n 187, 147, 58, 226, 21, 220, 250, 77, 67, 131, 51, 91, 60,\n\n ],\n\n transactions: vec![tx.clone()],\n\n prev_block_id: Some(vec![1, 2, 3, 4]),\n\n };\n\n assert_eq!(block, expected_updated);\n\n }\n\n}\n", "file_path": "src/block.rs", "rank": 22, "score": 21144.13132850782 }, { "content": "/// Dummy trait used to map a generic type to a u8.\n\npub trait AlwaysU8 {\n\n type Type;\n\n}\n\n\n\nimpl<T> AlwaysU8 for T {\n\n type Type = u8;\n\n}\n\n\n\n/// A types binary encoding.\n\npub(crate) type BinEncoding<T> = Vec<<T as AlwaysU8>::Type>;\n\n\n\n// A Keccak256 hash.\n\npub(crate) type Keccak256 = Vec<u8>;\n\n\n\n// A Keccak256 hash of a senders public key.\n\npub(crate) type Sender = Keccak256;\n\n\n\n/// Creates a Keccak256 hash of the given data.\n\npub(crate) fn hash<T: AsRef<[u8]>>(data: T) -> Keccak256 {\n\n let mut hasher = sha3::Keccak256::new();\n\n hasher.update(data);\n\n hasher.finalize().as_slice().to_vec()\n\n}\n", "file_path": "src/utils.rs", "rank": 23, "score": 20949.125021027794 }, { "content": "//! Anova is a distributed ledger with a focus on privacy, safety and scalability.\n\n\n\nextern crate bincode;\n\nextern crate rand;\n\nextern crate serde;\n\nextern crate sha3;\n\n\n\npub mod block;\n\npub mod chain;\n\npub mod mempool;\n\npub mod node;\n\npub mod snowball;\n\npub mod transaction;\n\n\n\nmod utils;\n", "file_path": "src/lib.rs", "rank": 40, "score": 15.873343375724026 }, { "content": " /// Number of votes required to consider a value to be *accepted*.\n\n /// Referred to as `alpha` in the whitepaper.\n\n quorum_size: u8,\n\n /// Number of consecutive votes required to consider a decision to be *stable*.\n\n /// Referred to as `beta` in the whitepaper.\n\n decision_threshold: u8,\n\n}\n\n\n\nimpl<T> Snowball<T>\n\nwhere\n\n T: Eq + Hash + Clone,\n\n{\n\n /// Creates a new Snowball.\n\n pub fn new(sample_size: u8, quorum_size: u8, decision_threshold: u8) -> Self {\n\n Snowball {\n\n value: None,\n\n done: false,\n\n counter: 0,\n\n counters: HashMap::new(),\n\n sample_size,\n", "file_path": "src/snowball.rs", "rank": 41, "score": 8.334800245738355 }, { "content": "#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[derive(Debug, PartialEq, Eq, Hash, Clone)]\n\n enum Color {\n\n Red,\n\n Green,\n\n Blue,\n\n }\n\n\n\n fn get_snowball<T: Eq + Hash + Clone>() -> Snowball<T> {\n\n let sample_size = 5;\n\n let quorum_size = 4;\n\n let decision_threshold = 3;\n\n Snowball::new(sample_size, quorum_size, decision_threshold)\n\n }\n\n\n\n #[test]\n\n fn new_snowball() {\n", "file_path": "src/snowball.rs", "rank": 42, "score": 8.281940225370295 }, { "content": " quorum_size,\n\n decision_threshold,\n\n }\n\n }\n\n\n\n /// Run one round of the Snowball algorithm.\n\n pub fn tick(&mut self, votes: HashMap<T, f64>) {\n\n // Return if we already settled on a value.\n\n if self.done {\n\n return;\n\n }\n\n\n\n // Ensure that the denominator (number of votes) can't be less than 2.\n\n let mut denom = votes.keys().len() as f64;\n\n if denom < 2.0 {\n\n denom = 2.0;\n\n }\n\n\n\n // Get item with the majority of votes and its votes.\n\n let mut favorite: Option<T> = None;\n", "file_path": "src/snowball.rs", "rank": 43, "score": 7.629365082611649 }, { "content": "use std::{collections::HashMap, hash::Hash};\n\n\n\n/// Himitsu variant of the Snowball algorithm from the family of\n\n/// [Metastable Consensus Protocols](https://arxiv.org/abs/1906.08936).\n\n#[derive(Debug, PartialEq)]\n\npub struct Snowball<T>\n\nwhere\n\n T: Eq + Hash,\n\n{\n\n /// The current value.\n\n value: Option<T>,\n\n /// Returns whether the algorithm converged.\n\n done: bool,\n\n /// Records the number of consecutive successes.\n\n counter: u8,\n\n /// Records the number of consecutive successes for each individual item.\n\n counters: HashMap<T, u8>,\n\n /// Number or queried peers. Subset of all available peers.\n\n /// Referred to as `k` in the whitepaper.\n\n sample_size: u8,\n", "file_path": "src/snowball.rs", "rank": 44, "score": 6.590260661214678 }, { "content": " let snowball: Snowball<()> = get_snowball();\n\n let expected: Snowball<()> = Snowball {\n\n value: None,\n\n done: false,\n\n counter: 0,\n\n counters: HashMap::new(),\n\n sample_size: 5,\n\n quorum_size: 4,\n\n decision_threshold: 3,\n\n };\n\n\n\n assert_eq!(snowball, expected);\n\n }\n\n\n\n #[test]\n\n fn track_successes() {\n\n let mut snowball = get_snowball();\n\n let mut votes = HashMap::new();\n\n\n\n votes.insert(Color::Red, 3.0);\n", "file_path": "src/snowball.rs", "rank": 45, "score": 6.210445686567988 }, { "content": " let mut favorite_votes: f64 = 0.0;\n\n for (item, votes) in votes.into_iter() {\n\n if votes > favorite_votes {\n\n favorite = Some(item);\n\n favorite_votes = votes;\n\n }\n\n }\n\n\n\n // Check if there's a quorum.\n\n if favorite_votes >= (self.quorum_size as f64 * 2.0 / denom) {\n\n // We have votes for favorites so we can safely unwrap.\n\n let favorite = favorite.unwrap();\n\n // Store the old value so that we can use it for comparison later.\n\n let old_value = self.value.clone();\n\n // Increment the favorites counter.\n\n *self.counters.entry(favorite.clone()).or_insert(0) += 1;\n\n // Set the current value to the favorite if its counter is higher.\n\n if self.value.is_none()\n\n || self.counters.get(&favorite) > self.counters.get(self.value.as_ref().unwrap())\n\n {\n", "file_path": "src/snowball.rs", "rank": 46, "score": 4.272220497954457 }, { "content": "# Anova\n\n\n\n## Useful Commands\n\n\n\n```sh\n\ncargo build\n\n\n\ncargo check\n\n\n\ncargo clean\n\n\n\ncargo doc [--open]\n\n\n\ncargo test [--lib]\n\n```\n", "file_path": "README.md", "rank": 47, "score": 3.9753238855375734 }, { "content": " }\n\n\n\n #[test]\n\n fn convergence() {\n\n let mut snowball = get_snowball();\n\n let mut votes = HashMap::new();\n\n\n\n votes.insert(Color::Red, 3.0);\n\n votes.insert(Color::Green, 1.0);\n\n votes.insert(Color::Blue, 1.0);\n\n\n\n // 1st round\n\n snowball.tick(votes.clone());\n\n assert_eq!(snowball.counter, 1);\n\n assert_eq!(snowball.done, false);\n\n assert_eq!(snowball.value, Some(Color::Red));\n\n\n\n // 2nd round\n\n snowball.tick(votes.clone());\n\n assert_eq!(snowball.counter, 2);\n", "file_path": "src/snowball.rs", "rank": 48, "score": 3.8543978280753364 }, { "content": " votes.insert(Color::Green, 1.0);\n\n votes.insert(Color::Blue, 1.0);\n\n\n\n snowball.tick(votes);\n\n assert_eq!(snowball.counter, 1);\n\n assert_eq!(snowball.done, false);\n\n assert_eq!(snowball.value, Some(Color::Red));\n\n }\n\n\n\n #[test]\n\n fn reset_when_no_quorum() {\n\n let mut snowball = get_snowball();\n\n let mut votes = HashMap::new();\n\n\n\n votes.insert(Color::Red, 3.0);\n\n votes.insert(Color::Green, 1.0);\n\n votes.insert(Color::Blue, 1.0);\n\n\n\n snowball.tick(votes.clone());\n\n assert_eq!(snowball.counter, 1);\n", "file_path": "src/snowball.rs", "rank": 49, "score": 3.714664023004024 }, { "content": " assert_eq!(snowball.done, false);\n\n assert_eq!(snowball.value, Some(Color::Red));\n\n\n\n votes.clear();\n\n\n\n votes.insert(Color::Red, 2.0);\n\n votes.insert(Color::Green, 2.0);\n\n votes.insert(Color::Blue, 1.0);\n\n snowball.tick(votes);\n\n assert_eq!(snowball.counter, 0);\n\n assert_eq!(snowball.done, false);\n\n assert_eq!(snowball.value, Some(Color::Red));\n\n }\n\n\n\n #[test]\n\n fn change_in_majority() {\n\n let mut snowball = get_snowball();\n\n let mut votes = HashMap::new();\n\n\n\n votes.insert(Color::Red, 3.0);\n", "file_path": "src/snowball.rs", "rank": 50, "score": 3.6813269560657926 }, { "content": "use sha3::Digest;\n\n\n\n/// Dummy trait used to map a generic type to a u8.\n", "file_path": "src/utils.rs", "rank": 51, "score": 2.8887934572390126 } ]
Rust
cli/src/command/list/list.rs
bennyboer/worklog
bce3c3954c3a14cca7c029caf2641ec1f5af4478
use std::collections::HashMap; use cmd_args::{arg, option, Group}; use colorful::Colorful; use persistence::calc::{Status, WorkItem}; use crate::command::command::Command; use std::ops::Sub; pub struct ListCommand {} impl Command for ListCommand { fn build(&self) -> Group { Group::new( Box::new(|args, options| execute(args, options)), "List work items", ) .add_option(option::Descriptor::new( "all", option::Type::Bool { default: false }, "Show all available log entries", )) .add_option(option::Descriptor::new( "filter", option::Type::Str { default: String::from("today"), }, "Filter by a date ('today' (default), 'yesterday', '2020-02-20' (yyyy-MM-dd)) or work item ID", )) } fn aliases(&self) -> Option<Vec<&str>> { Some(vec!["ls"]) } fn name(&self) -> &str { "list" } } fn execute(_args: &Vec<arg::Value>, options: &HashMap<&str, option::Value>) { let all: bool = options.get("all").map_or(false, |v| v.bool().unwrap()); let mut entries = match all { true => persistence::list_items().unwrap(), false => { let filter: &str = options.get("filter").map_or("today", |v| v.str().unwrap()); match filter.parse::<i32>() { Ok(id) => persistence::find_item_by_id(id) .unwrap() .map_or(Vec::new(), |v| vec![v]), Err(_) => { let (from_timestamp, to_timestamp) = filter_keyword_to_time_range(filter); persistence::find_items_by_timerange(from_timestamp, to_timestamp).unwrap() } } } }; let found_str: String = format!("| Found {} log entries |", entries.len()); println!(" {} ", "-".repeat(found_str.len() - 2)); println!("{}", found_str); println!(" {} ", "-".repeat(found_str.len() - 2)); entries.sort_by_key(|v| i64::max_value() - v.created_timestamp()); let mut items_per_day = Vec::new(); items_per_day.push(Vec::new()); let mut last_date_option: Option<chrono::Date<_>> = None; for item in &entries { let date_time = shared::time::get_local_date_time(item.created_timestamp()); let is_another_day = match last_date_option { Some(last_date) => date_time.date().sub(last_date).num_days().abs() >= 1, None => false, }; if is_another_day { items_per_day.push(Vec::new()); } let current_day_items = items_per_day.last_mut().unwrap(); current_day_items.push(item); last_date_option = Some(date_time.date()); } for items in items_per_day { if !items.is_empty() { print_date_header(&items); for item in items { println!(" • {}", format_item(item)); } } } println!(); } fn print_date_header(items: &[&WorkItem]) { let first = *items.first().unwrap(); let date_time = shared::time::get_local_date_time(first.created_timestamp()); println!(); println!( "{}", format!( "# {} ({})", date_time.format("%A - %d. %B %Y"), shared::time::format_duration((calculate_total_work_time(items) / 1000) as u32) ) .underlined() ); println!(); } pub(crate) fn calculate_total_work_time(items: &[&WorkItem]) -> i64 { let mut time_events: Vec<shared::calc::TimeEvent> = items .iter() .flat_map(|i| { i.events() .iter() .map(|e| shared::calc::TimeEvent::new(e.is_start(), e.timestamp())) }) .collect(); for item in items { if let Status::InProgress = item.status() { time_events.push(shared::calc::TimeEvent::new( false, chrono::Utc::now().timestamp_millis(), )); } } shared::calc::calculate_unique_total_time(&mut time_events) } fn format_item(item: &WorkItem) -> String { let id_str = format!( "#{}", item.id().expect("Work item must have an ID at this point!") ) .color(colorful::Color::DodgerBlue3); let time_str = shared::time::get_local_date_time(item.created_timestamp()) .format("%H:%M") .to_string() .color(colorful::Color::DeepPink1a); let description = item.description(); let duration_str = shared::time::format_duration((item.time_taken() / 1000) as u32) .color(colorful::Color::Orange1); let status_str = match item.status() { Status::Done => duration_str, Status::InProgress => { format!("IN PROGRESS ({})", duration_str).color(colorful::Color::GreenYellow) } Status::Paused => format!("PAUSED ({})", duration_str).color(colorful::Color::Red), }; let tags_formatted: Vec<_> = item.tags().iter().map(|s| format!("#{}", s)).collect(); let tags_str = tags_formatted .join(", ") .color(colorful::Color::DarkSlateGray1); format!( "{} [{}] {} - {} ({})", id_str, time_str, description, status_str, tags_str ) } pub(crate) fn filter_keyword_to_time_range(keyword: &str) -> (i64, i64) { match keyword { "today" => { let today = chrono::Utc::today(); let from_timestamp = today.and_hms(0, 0, 0).timestamp_millis(); let to_timestamp = today.succ().and_hms(0, 0, 0).timestamp_millis(); (from_timestamp, to_timestamp) } "yesterday" => { let yesterday = chrono::Utc::today().pred(); let from_timestamp = yesterday.and_hms(0, 0, 0).timestamp_millis(); let to_timestamp = yesterday.succ().and_hms(0, 0, 0).timestamp_millis(); (from_timestamp, to_timestamp) } str => { let date = chrono::NaiveDate::parse_from_str(str, "%Y-%m-%d") .expect("Expected date format to be in form 'YYYY-MM-dd'"); let from_timestamp = date.and_hms(0, 0, 0).timestamp_millis(); let to_timestamp = date.succ().and_hms(0, 0, 0).timestamp_millis(); (from_timestamp, to_timestamp) } } }
use std::collections::HashMap; use cmd_args::{arg, option, Group}; use colorful::Colorful; use persistence::calc::{Status, WorkItem}; use crate::command::command::Command; use std::ops::Sub; pub struct ListCommand {} impl Command for ListCommand { fn build(&self) -> Group { Group::new( Box::new(|args, options| execute(args, options)), "List work items", ) .add_option(option::Descriptor::new( "all", option::Type::Bool { default: false }, "Show all available log entries", )) .add_option(option::Descriptor::new( "filter", option::Type::Str { default: String::from("today"), }, "Filter by a date ('today' (default), 'yesterday', '2020-02-20' (yyyy-MM-dd)) or work item ID", )) } fn aliases(&self) -> Option<Vec<&str>> { Some(vec!["ls"]) } fn name(&self) -> &str { "list" } } fn execute(_args: &Vec<arg::Value>, options: &HashMap<&str, option::Value>) { let all: bool = options.get("all").map_or(false, |v| v.bool().unwrap()); let mut entries = match all { true => persistence::list_items().unwrap(), false => { let filter: &str = options.get("filter").map_or("today", |v| v.str().unwrap()); match filter.parse::<i32>() { Ok(id) => persistence::find_item_by_id(id) .unwrap() .map_or(Vec::new(), |v| vec![v]), Err(_) => { let (from_timestamp, to_timestamp) = filter_keyword_to_time_range(filter); persistence::find_items_by_timerange(from_timestamp, to_timestamp).unwrap() } } } }; let found_str: String = format!("| Found {} log entries |", entries.len()); println!(" {} ", "-".repeat(found_str.len() - 2)); println!("{}", found_str); println!(" {} ", "-".repeat(found_str.len() - 2)); entries.sort_by_key(|v| i64::max_value() - v.created_timestamp()); let mut items_per_day = Vec::new(); items_per_day.push(Vec::new()); let mut last_date_option: Option<chrono::Date<_>> = None; for item in &entries { let date_time = shared::time::get_local_date_time(item.created_timestamp()); let is_another_day = match last_date_option { Some(last_date) => date_time.date().sub(last_date).num_days().abs() >= 1, None => false, }; if is_another_day { items_per_day.push(Vec::new()); } let current_day_items = items_per_day.last_mut().unwrap(); current_day_items.push(item); last_date_option = Some(date_time.date()); } for items in items_per_day { if !items.is_empty() { print_date_header(&items); for item in items { println!(" • {}", format_item(item)); } } } println!(); } fn print_date_header(items: &[&WorkItem]) { let first = *items.first().unwrap(); let date_time = shared::time::get_local_date_time(first.created_timestamp()); println!(); println!( "{}", format!( "# {} ({})", date_time.format("%A - %d. %B %Y"), shared::time::format_duration((calculate_total_work_time(items) / 1000) as u32) ) .underlined() ); println!(); }
fn format_item(item: &WorkItem) -> String { let id_str = format!( "#{}", item.id().expect("Work item must have an ID at this point!") ) .color(colorful::Color::DodgerBlue3); let time_str = shared::time::get_local_date_time(item.created_timestamp()) .format("%H:%M") .to_string() .color(colorful::Color::DeepPink1a); let description = item.description(); let duration_str = shared::time::format_duration((item.time_taken() / 1000) as u32) .color(colorful::Color::Orange1); let status_str = match item.status() { Status::Done => duration_str, Status::InProgress => { format!("IN PROGRESS ({})", duration_str).color(colorful::Color::GreenYellow) } Status::Paused => format!("PAUSED ({})", duration_str).color(colorful::Color::Red), }; let tags_formatted: Vec<_> = item.tags().iter().map(|s| format!("#{}", s)).collect(); let tags_str = tags_formatted .join(", ") .color(colorful::Color::DarkSlateGray1); format!( "{} [{}] {} - {} ({})", id_str, time_str, description, status_str, tags_str ) } pub(crate) fn filter_keyword_to_time_range(keyword: &str) -> (i64, i64) { match keyword { "today" => { let today = chrono::Utc::today(); let from_timestamp = today.and_hms(0, 0, 0).timestamp_millis(); let to_timestamp = today.succ().and_hms(0, 0, 0).timestamp_millis(); (from_timestamp, to_timestamp) } "yesterday" => { let yesterday = chrono::Utc::today().pred(); let from_timestamp = yesterday.and_hms(0, 0, 0).timestamp_millis(); let to_timestamp = yesterday.succ().and_hms(0, 0, 0).timestamp_millis(); (from_timestamp, to_timestamp) } str => { let date = chrono::NaiveDate::parse_from_str(str, "%Y-%m-%d") .expect("Expected date format to be in form 'YYYY-MM-dd'"); let from_timestamp = date.and_hms(0, 0, 0).timestamp_millis(); let to_timestamp = date.succ().and_hms(0, 0, 0).timestamp_millis(); (from_timestamp, to_timestamp) } } }
pub(crate) fn calculate_total_work_time(items: &[&WorkItem]) -> i64 { let mut time_events: Vec<shared::calc::TimeEvent> = items .iter() .flat_map(|i| { i.events() .iter() .map(|e| shared::calc::TimeEvent::new(e.is_start(), e.timestamp())) }) .collect(); for item in items { if let Status::InProgress = item.status() { time_events.push(shared::calc::TimeEvent::new( false, chrono::Utc::now().timestamp_millis(), )); } } shared::calc::calculate_unique_total_time(&mut time_events) }
function_block-full_function
[ { "content": "/// Format a duration given in seconds in the form \"Xh Xm Xs\".\n\npub fn format_duration(mut seconds: u32) -> String {\n\n let hours = seconds / 60 / 60;\n\n seconds -= hours * 60 * 60;\n\n\n\n let minutes = seconds / 60;\n\n seconds -= minutes * 60;\n\n\n\n let mut result = Vec::new();\n\n if hours > 0 {\n\n result.push(format!(\"{}h\", hours));\n\n }\n\n if minutes > 0 {\n\n result.push(format!(\"{}m\", minutes));\n\n }\n\n if seconds > 0 {\n\n result.push(format!(\"{}s\", seconds));\n\n }\n\n\n\n result.join(\" \")\n\n}\n", "file_path": "shared/src/time/duration_parser.rs", "rank": 1, "score": 264379.82659447007 }, { "content": "fn format_event_timeline(item: &WorkItem) -> String {\n\n let mut result = Vec::new();\n\n\n\n let mut start_time = None;\n\n for event in item.events() {\n\n match event.event_type() {\n\n EventType::Started | EventType::Continued => {\n\n start_time = Some(shared::time::get_local_date_time(event.timestamp()))\n\n }\n\n EventType::Finished | EventType::Paused => result.push(format!(\n\n \"{} - {}\",\n\n start_time.unwrap().format(\"%H:%M\"),\n\n shared::time::get_local_date_time(event.timestamp()).format(\"%H:%M\")\n\n )),\n\n };\n\n }\n\n\n\n result.join(\", \")\n\n}\n\n\n", "file_path": "cli/src/command/export/export.rs", "rank": 2, "score": 259584.15474935598 }, { "content": "pub fn find_item_by_id(id: i32) -> Result<Option<WorkItem>, Box<dyn Error>> {\n\n let data_access = data_access::get_data_access()?;\n\n\n\n Ok(data_access.find_item_by_id(id)?)\n\n}\n\n\n", "file_path": "persistence/src/lib.rs", "rank": 3, "score": 248406.80020411575 }, { "content": "pub fn delete_item(id: i32) -> Result<Option<WorkItem>, Box<dyn Error>> {\n\n let mut data_access = data_access::get_data_access()?;\n\n\n\n Ok(data_access.delete_item(id)?)\n\n}\n\n\n", "file_path": "persistence/src/lib.rs", "rank": 4, "score": 242179.52426746694 }, { "content": "/// Print the work item.\n\nfn print_item(item: WorkItem) {\n\n print_header(&format!(\n\n \"Details for work item with ID {}\",\n\n item.id().unwrap()\n\n ));\n\n println!();\n\n\n\n println!(\"{}\", \"# Description\".underlined());\n\n\n\n println!(\"{}\", item.description());\n\n\n\n println!();\n\n\n\n println!(\"{}\", \"# Status\".underlined());\n\n\n\n println!(\n\n \"{}\",\n\n format!(\"{}\", item.status()).color(colorful::Color::OrangeRed1)\n\n );\n\n\n", "file_path": "cli/src/command/show/show.rs", "rank": 5, "score": 232606.99120804784 }, { "content": "/// Build a widget representing a tag.\n\nfn build_tag_widget() -> impl Widget<String> {\n\n let tag_color = rand_color(); // TODO: Use fixed color per tag instead\n\n\n\n Label::new(|text: &String, _: &Env| format!(\"#{}\", text))\n\n .with_text_color(invert_color(&tag_color))\n\n .with_text_size(11.0)\n\n .padding((3.0, 1.0))\n\n .background(tag_color)\n\n .rounded(100.0)\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 6, "score": 232262.50548016457 }, { "content": "/// Build the tags list widget.\n\nfn build_tags() -> impl Widget<im::Vector<String>> {\n\n List::new(|| build_tag_widget())\n\n .horizontal()\n\n .with_spacing(2.0)\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 8, "score": 222527.25290043975 }, { "content": "/// Export to a markdown file with the given file path.\n\nfn export_to_markdown(file_path: &str, filter: String) {\n\n let (from_timestamp, to_timestamp) = list::filter_keyword_to_time_range(&filter[..]);\n\n let items = persistence::find_items_by_timerange(from_timestamp, to_timestamp).unwrap();\n\n\n\n let first_item = items.first().unwrap();\n\n let date_time = shared::time::get_local_date_time(first_item.created_timestamp());\n\n\n\n let mut data = String::new();\n\n\n\n data.push_str(&format!(\n\n \"# Report for {} the {}\\n\\n\",\n\n date_time.format(\"%A\").to_string(),\n\n date_time.format(\"%Y-%m-%d\").to_string()\n\n ));\n\n\n\n data.push_str(\"## Statistics\\n\\n\");\n\n\n\n let total_work_time = {\n\n let item_refs: Vec<&WorkItem> = items.iter().collect();\n\n let total_work_time_ms = list::calculate_total_work_time(&item_refs);\n", "file_path": "cli/src/command/export/export.rs", "rank": 9, "score": 218798.9262542514 }, { "content": "/// Log a work calc.\n\n/// Will return the ID of the new item.\n\npub fn log_item(item: WorkItem) -> Result<i32, Box<dyn Error>> {\n\n let mut data_access = data_access::get_data_access()?;\n\n\n\n Ok(data_access.log_item(item)?)\n\n}\n\n\n", "file_path": "persistence/src/lib.rs", "rank": 10, "score": 209894.56794229578 }, { "content": "pub fn list_items() -> Result<Vec<WorkItem>, Box<dyn Error>> {\n\n let data_access = data_access::get_data_access()?;\n\n\n\n Ok(data_access.list_items()?)\n\n}\n\n\n", "file_path": "persistence/src/lib.rs", "rank": 11, "score": 191963.4531388514 }, { "content": "fn pause_work_item_by_id(id: i32) {\n\n match persistence::find_item_by_id(id).unwrap() {\n\n Some(mut item) => {\n\n if let Status::InProgress = item.status() {\n\n item.pause_working().unwrap();\n\n\n\n match persistence::update_items(vec![&item]) {\n\n Ok(_) => println!(\"Paused work item with ID {}.\", id),\n\n Err(e) => println!(\"Failed to update work item with ID {}. Error: '{}'\", id, e),\n\n };\n\n } else {\n\n println!(\n\n \"Work item with ID {} is currently not in progress and thus cannot be paused.\",\n\n id\n\n );\n\n }\n\n }\n\n None => {\n\n println!(\"Could not find work item with ID {}.\", id);\n\n }\n", "file_path": "cli/src/command/pause/pause.rs", "rank": 12, "score": 190787.47467060527 }, { "content": "/// Execute the log command.\n\nfn execute(args: &Vec<arg::Value>, _options: &HashMap<&str, option::Value>) {\n\n let description = args[0].str().unwrap();\n\n let tags_str = args[1].str().unwrap();\n\n let time_taken_str = args[2].str().unwrap();\n\n\n\n let tags: Vec<String> = tags_str.split(\",\").map(|s| s.trim().to_owned()).collect();\n\n let time_taken_ms = shared::time::parse_duration(time_taken_str).unwrap() as i64 * 1000;\n\n\n\n let current_timestamp_ms = chrono::Utc::now().timestamp_millis();\n\n let item = persistence::calc::WorkItem::new_internal(\n\n -1,\n\n description.to_owned(),\n\n Status::Done,\n\n HashSet::from_iter(tags.into_iter()),\n\n vec![\n\n Event::new(EventType::Started, current_timestamp_ms - time_taken_ms),\n\n Event::new(EventType::Finished, current_timestamp_ms),\n\n ],\n\n );\n\n\n\n let new_id = persistence::log_item(item).unwrap();\n\n\n\n println!(\n\n \"Create work item with ID {}.\",\n\n format!(\"#{}\", new_id).color(colorful::Color::DodgerBlue3)\n\n );\n\n}\n", "file_path": "cli/src/command/log/log.rs", "rank": 13, "score": 189935.4938457078 }, { "content": "/// Execute the show command.\n\nfn execute(args: &Vec<arg::Value>, _options: &HashMap<&str, option::Value>) {\n\n let id = args[0].int().unwrap();\n\n\n\n match persistence::find_item_by_id(id) {\n\n Ok(optional_item) => match optional_item {\n\n Some(item) => print_item(item),\n\n None => println!(\"Could not find work item with ID {}.\", id),\n\n },\n\n Err(e) => println!(\n\n \"Failed to show details for work item with ID {}. Error: '{}'.\",\n\n id, e\n\n ),\n\n }\n\n}\n\n\n", "file_path": "cli/src/command/show/show.rs", "rank": 14, "score": 189873.22080855217 }, { "content": "/// Build the status panel that is part of the work item list item widget.\n\nfn build_status_panel() -> impl Widget<UiWorkItem> {\n\n Painter::new(|ctx, item: &UiWorkItem, _: &_| {\n\n let size = ctx.size().to_rounded_rect(2.0);\n\n\n\n let color = match item.status {\n\n UiWorkItemStatus::InProgress => Color::rgb8(130, 200, 50),\n\n UiWorkItemStatus::Paused => Color::rgb8(216, 139, 100),\n\n UiWorkItemStatus::Finished => Color::rgb8(100, 177, 216),\n\n };\n\n\n\n ctx.fill(size, &color)\n\n })\n\n .fix_width(4.0)\n\n}\n\n\n\nimpl Widget<UiWorkItem> for WorkItemListItemWidget {\n\n fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut UiWorkItem, env: &Env) {\n\n match event {\n\n Event::Command(cmd) => {\n\n if cmd.is(ITEM_CHANGED) {\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 16, "score": 186952.63523176577 }, { "content": "fn get_item_background_color(is_hot: bool) -> Color {\n\n if is_hot {\n\n Color::rgb8(245, 245, 245)\n\n } else {\n\n Color::WHITE\n\n }\n\n}\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 17, "score": 185393.92550766031 }, { "content": "/// Print a header string to the console.\n\nfn print_header(str: &str) {\n\n println!(\" {} \", \"-\".repeat(str.len() + 2));\n\n println!(\"| {} |\", str);\n\n println!(\" {} \", \"-\".repeat(str.len() + 2));\n\n}\n", "file_path": "cli/src/command/show/show.rs", "rank": 18, "score": 184639.2021602695 }, { "content": "/// Find the earliest work item among the list of passed work item references.\n\nfn find_earliest_work_item(items: &[WorkItem]) -> &WorkItem {\n\n let mut earliest_ts: i64 = items.first().unwrap().created_timestamp();\n\n let mut earliest_item = items.first().unwrap();\n\n for item in &items[1..] {\n\n if item.created_timestamp() < earliest_ts {\n\n earliest_ts = item.created_timestamp();\n\n earliest_item = item;\n\n }\n\n }\n\n\n\n earliest_item\n\n}\n", "file_path": "cli/src/command/export/export.rs", "rank": 19, "score": 179407.80981569563 }, { "content": "/// Find the latest work item among the list of passed work item references.\n\nfn find_latest_work_item(items: &[WorkItem]) -> &WorkItem {\n\n let mut lastest_ts: i64 = items.first().unwrap().events().last().unwrap().timestamp();\n\n let mut latest_item = items.first().unwrap();\n\n for item in &items[1..] {\n\n if item.events().last().unwrap().timestamp() > lastest_ts {\n\n lastest_ts = item.events().last().unwrap().timestamp();\n\n latest_item = item;\n\n }\n\n }\n\n\n\n latest_item\n\n}\n\n\n", "file_path": "cli/src/command/export/export.rs", "rank": 20, "score": 179407.80981569563 }, { "content": "/// Parse the time taken in seconds from the given string in the format\n\n/// \"Xh Xm Xs\" where X must be a number and h, m or s are optional.\n\npub fn parse_duration(src: &str) -> Result<i32, String> {\n\n let mut hours = 0;\n\n let mut minutes = 0;\n\n let mut seconds = 0;\n\n\n\n let mut number_buffer: String = String::new();\n\n for char in src.chars() {\n\n let is_hours = char == 'h';\n\n let is_minutes = char == 'm';\n\n let is_seconds = char == 's';\n\n\n\n let consume_buffer = is_hours || is_minutes || is_seconds;\n\n if consume_buffer {\n\n // Parse number from buffer and clear it\n\n let num: i32 = match number_buffer.trim().parse() {\n\n Ok(res) => Ok(res),\n\n Err(_) => Err(format!(\n\n \"Could not parse time taken from given string '{}'\",\n\n src\n\n )),\n", "file_path": "shared/src/time/duration_parser.rs", "rank": 21, "score": 178986.9657434266 }, { "content": "/// Build the detail view of a work item (if one is selected).\n\nfn build_detail_view_wrapper() -> impl Widget<Option<Rc<RefCell<UiWorkItem>>>> {\n\n Maybe::new(\n\n || {\n\n SideBar::new(\n\n build_detail_view().lens(SelectedWorkItemLens),\n\n false,\n\n true,\n\n |ctx, _, _| {\n\n ctx.submit_command(\n\n controller::SELECT_ITEM\n\n .with(-1)\n\n .to(controller::DAY_VIEW_WIDGET_ID),\n\n );\n\n },\n\n )\n\n },\n\n || SizedBox::empty().lens(lens::Unit),\n\n )\n\n .with_id(SIDEBAR_WIDGET_ID)\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/day_view.rs", "rank": 22, "score": 166003.7576258462 }, { "content": "/// Update a bunch of work items.\n\npub fn update_items(items: Vec<&WorkItem>) -> Result<(), Box<dyn Error>> {\n\n let mut data_access = data_access::get_data_access()?;\n\n\n\n Ok(data_access.update_items(items)?)\n\n}\n\n\n", "file_path": "persistence/src/lib.rs", "rank": 23, "score": 164644.32111219186 }, { "content": "fn build_tag_widget(widget_id: WidgetId) -> impl Widget<String> {\n\n TagWidget::new(move |ctx: &mut EventCtx, data: &String| {\n\n ctx.submit_command(DELETE_TAG.with(data.to_owned()).to(widget_id));\n\n })\n\n}\n\n\n", "file_path": "ui/src/widget/tag_cloud/tag_cloud.rs", "rank": 24, "score": 163028.52205612516 }, { "content": "struct ItemHeaderWidget {\n\n left: WidgetPod<UiWorkItem, Box<dyn Widget<UiWorkItem>>>,\n\n right: WidgetPod<UiWorkItem, Box<dyn Widget<UiWorkItem>>>,\n\n hovered: bool,\n\n}\n\n\n\nimpl Widget<UiWorkItem> for ItemHeaderWidget {\n\n fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut UiWorkItem, env: &Env) {\n\n self.left.event(ctx, event, data, env);\n\n self.right.event(ctx, event, data, env);\n\n }\n\n\n\n fn lifecycle(\n\n &mut self,\n\n ctx: &mut LifeCycleCtx,\n\n event: &LifeCycle,\n\n data: &UiWorkItem,\n\n env: &Env,\n\n ) {\n\n self.left.lifecycle(ctx, event, data, env);\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 25, "score": 161693.0951438531 }, { "content": "struct ItemHeaderWidgetController;\n\n\n\nimpl Controller<UiWorkItem, ItemHeaderWidget> for ItemHeaderWidgetController {\n\n fn event(\n\n &mut self,\n\n child: &mut ItemHeaderWidget,\n\n ctx: &mut EventCtx,\n\n event: &Event,\n\n data: &mut UiWorkItem,\n\n env: &Env,\n\n ) {\n\n match event {\n\n Event::Command(cmd) => {\n\n if cmd.is(HOVER_CHANGED) {\n\n child.hovered = !child.hovered;\n\n ctx.request_paint();\n\n }\n\n }\n\n _ => child.event(ctx, event, data, env),\n\n }\n\n }\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 26, "score": 159449.0966834978 }, { "content": "fn build_work_item_widget() -> impl Widget<UiWorkItem> {\n\n WorkItemListItemWidget::new()\n\n .on_click(|ctx, item, _| {\n\n ctx.submit_command(\n\n controller::SELECT_ITEM\n\n .with(item.id)\n\n .to(controller::DAY_VIEW_WIDGET_ID),\n\n );\n\n ctx.submit_command(OPEN_SIDEBAR.to(SIDEBAR_WIDGET_ID));\n\n })\n\n .background(Color::WHITE)\n\n .rounded(2.0)\n\n .padding((10.0, 4.0))\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/day_view.rs", "rank": 27, "score": 155985.37697486393 }, { "content": "/// Execute the edit command.\n\nfn execute(args: &Vec<arg::Value>, options: &HashMap<&str, option::Value>) {\n\n let id = args[0]\n\n .int()\n\n .expect(\"Expected to have an ID supplied as first argument\");\n\n\n\n let description = options\n\n .get(\"description\")\n\n .unwrap()\n\n .str()\n\n .map(|v| {\n\n if v.is_empty() {\n\n None\n\n } else {\n\n Some(v.to_owned())\n\n }\n\n })\n\n .unwrap();\n\n\n\n let tags: Option<Vec<String>> = options\n\n .get(\"tags\")\n", "file_path": "cli/src/command/edit/edit.rs", "rank": 28, "score": 154217.5966833151 }, { "content": "/// Execute the pause command.\n\nfn execute(args: &Vec<arg::Value>, _options: &HashMap<&str, option::Value>) {\n\n let value = args[0].str().expect(\"Expected to have one argument\");\n\n\n\n match value.parse::<i32>() {\n\n Ok(id) => {\n\n pause_work_item_by_id(id);\n\n }\n\n Err(_) => {\n\n // Check if value is \"all\" to pause all work items in progress\n\n if value == \"all\" {\n\n pause_all_work_items_in_progress();\n\n\n\n println!(\"Paused all work items in progress.\");\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "cli/src/command/pause/pause.rs", "rank": 29, "score": 154217.5966833151 }, { "content": "/// Execute the start command.\n\nfn execute(args: &Vec<arg::Value>, options: &HashMap<&str, option::Value>) {\n\n let description = args[0].str().unwrap();\n\n let tags_str = args[1].str().unwrap();\n\n\n\n let tags: Vec<String> = tags_str.split(\",\").map(|s| s.trim().to_owned()).collect();\n\n\n\n let pause_work_items_in_progress = options.get(\"pause\").unwrap().bool().unwrap();\n\n let finish_work_items_in_progress = options.get(\"finish\").unwrap().bool().unwrap();\n\n\n\n // If both --pause and --finish are specified we are finishing all items!\n\n\n\n // Stopping in progress work items first\n\n if finish_work_items_in_progress || pause_work_items_in_progress {\n\n pause::pause_all_work_items_in_progress();\n\n }\n\n\n\n // When --finish specified -> Finish all paused work items\n\n if finish_work_items_in_progress {\n\n finish::finish_all_paused_work_items();\n\n }\n", "file_path": "cli/src/command/start/start.rs", "rank": 30, "score": 154217.5966833151 }, { "content": "/// Execute the export command.\n\nfn execute(args: &Vec<arg::Value>, options: &HashMap<&str, option::Value>) {\n\n let export_type = args[0].str().unwrap();\n\n\n\n if export_type.trim().to_lowercase() == \"markdown\" {\n\n export_to_markdown(\n\n options.get(\"path\").unwrap().str().unwrap(),\n\n options\n\n .get(\"filter\")\n\n .unwrap()\n\n .str()\n\n .map_or(String::from(\"today\"), |v| v.to_owned()),\n\n );\n\n } else {\n\n panic!(\"Export type '{}' currently not supported\", export_type);\n\n }\n\n}\n\n\n", "file_path": "cli/src/command/export/export.rs", "rank": 31, "score": 154217.5966833151 }, { "content": "/// Execute the clear command.\n\nfn execute(_args: &Vec<arg::Value>, options: &HashMap<&str, option::Value>) {\n\n let acknowlegement = options.get(\"ack\").unwrap().bool().unwrap();\n\n\n\n if acknowlegement {\n\n match persistence::clear() {\n\n Ok(_) => println!(\"Cleared the database (Removed all work items).\"),\n\n Err(e) => println!(\"Could not clear the database. Error: '{}'.\", e),\n\n }\n\n } else {\n\n println!(\"Do you really want to clear the database (Remove all work items)?\");\n\n println!(\"Please acknowledge the operation by re-entering the clear command followed by the --ack flag\");\n\n }\n\n}\n", "file_path": "cli/src/command/clear/clear.rs", "rank": 32, "score": 154217.5966833151 }, { "content": "/// Execute the delete command.\n\nfn execute(args: &Vec<arg::Value>, _options: &HashMap<&str, option::Value>) {\n\n let id = args[0].int().expect(\"Expected to have an ID supplied\");\n\n\n\n match persistence::delete_item(id) {\n\n Ok(item) => match item {\n\n Some(_) => println!(\"Work item with ID {} has been deleted.\", id),\n\n None => println!(\"There is no work item with ID {}.\", id),\n\n },\n\n Err(e) => println!(\n\n \"An error occurred trying to delete work item with ID {}. Error: '{}'.\",\n\n id, e\n\n ),\n\n };\n\n}\n", "file_path": "cli/src/command/delete/delete.rs", "rank": 33, "score": 154217.5966833151 }, { "content": "/// Execute the finish command.\n\nfn execute(args: &Vec<arg::Value>, _options: &HashMap<&str, option::Value>) {\n\n let id = args[0]\n\n .int()\n\n .expect(\"Expected first argument to be a work item ID\");\n\n\n\n match persistence::find_item_by_id(id).unwrap() {\n\n Some(mut item) => {\n\n if let Status::Done = item.status() {\n\n println!(\"Work item with ID {} is already finished.\", id);\n\n } else {\n\n item.finish_working(None).unwrap();\n\n\n\n match persistence::update_items(vec![&item]) {\n\n Ok(_) => println!(\"Finished work item with ID {}.\", id),\n\n Err(e) => println!(\n\n \"Failed to update work item with ID {}. Error: '{}'\",\n\n item.id().unwrap(),\n\n e\n\n ),\n\n };\n", "file_path": "cli/src/command/finish/finish.rs", "rank": 34, "score": 154217.5966833151 }, { "content": "pub fn find_items_by_status(status: Status) -> Result<Vec<WorkItem>, Box<dyn Error>> {\n\n let data_access = data_access::get_data_access()?;\n\n\n\n Ok(data_access.find_items_by_status(status)?)\n\n}\n\n\n", "file_path": "persistence/src/lib.rs", "rank": 35, "score": 153094.91984791966 }, { "content": "/// Execute the continue command.\n\nfn execute(args: &Vec<arg::Value>, _options: &HashMap<&str, option::Value>) {\n\n let id = args[0]\n\n .int()\n\n .expect(\"Expected an ID of a work item as first argument\");\n\n\n\n match persistence::find_item_by_id(id) {\n\n Ok(option) => match option {\n\n Some(mut item) => {\n\n if let Status::Paused = item.status() {\n\n item.continue_working().unwrap();\n\n\n\n match persistence::update_items(vec![&item]) {\n\n Ok(_) => println!(\"Continued work item with ID {}.\", id),\n\n Err(e) => println!(\n\n \"Failed to continue work item with ID {}. Error: '{}'\",\n\n id, e\n\n ),\n\n };\n\n } else {\n\n println!(\"Work item with ID {} is currently not paused and thus cannot be continued working on.\", id);\n", "file_path": "cli/src/command/continue_cmd/continue_cmd.rs", "rank": 36, "score": 149853.17851202367 }, { "content": "fn build_day_view_work_items() -> impl Widget<state::DayViewWorkItems> {\n\n Scroll::new(LensWrap::new(\n\n List::new(|| build_work_item_widget().lens(SelectedWorkItemLens)),\n\n state::DayViewWorkItems::items,\n\n ))\n\n .vertical()\n\n .with_id(ITEM_LIST_WIDGET_ID)\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/day_view.rs", "rank": 37, "score": 147524.0726778064 }, { "content": "fn rand_color() -> Color {\n\n Color::rgb(\n\n rand::random::<f64>(),\n\n rand::random::<f64>(),\n\n rand::random::<f64>(),\n\n )\n\n .with_alpha(0.4)\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 38, "score": 144074.54538916625 }, { "content": "/// Build the status label of the work item.\n\nfn build_status_label() -> Label<UiWorkItem> {\n\n Label::new(|item: &UiWorkItem, _env: &_| {\n\n format!(\n\n \"{}\",\n\n match item.status {\n\n UiWorkItemStatus::InProgress => \"In progress\",\n\n UiWorkItemStatus::Paused => \"Paused\",\n\n UiWorkItemStatus::Finished => \"Done\",\n\n }\n\n )\n\n })\n\n .with_text_size(12.0)\n\n .with_text_color(Color::rgb8(100, 100, 100))\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 39, "score": 142638.93500605068 }, { "content": "/// Build the work item timing label.\n\nfn build_timing_label() -> Label<UiWorkItem> {\n\n Label::new(|item: &UiWorkItem, _: &Env| {\n\n let work_item = item.work_item.as_ref().borrow();\n\n\n\n let time_str = shared::time::get_local_date_time(work_item.created_timestamp())\n\n .format(\"%H:%M\")\n\n .to_string();\n\n let duration_str = shared::time::format_duration((work_item.time_taken() / 1000) as u32);\n\n\n\n format!(\"{} ({})\", duration_str, time_str)\n\n })\n\n .with_text_size(12.0)\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 40, "score": 142638.93500605068 }, { "content": "/// Configure the druid environment.\n\npub fn configure_environment(env: &mut Env) {\n\n theme::configure_theme(env);\n\n}\n", "file_path": "ui/src/util/ui/env.rs", "rank": 41, "score": 142017.83558894263 }, { "content": "/// Configure the theme for druid.\n\npub fn configure_theme(env: &mut Env) {\n\n env.set(theme::BACKGROUND_LIGHT, Color::rgb8(245, 245, 245));\n\n env.set(theme::BORDER_LIGHT, Color::rgb8(140, 150, 160));\n\n env.set(theme::BORDER_DARK, Color::rgb8(120, 130, 140));\n\n env.set(theme::SELECTION_COLOR, Color::rgb8(51, 152, 255));\n\n env.set(theme::CURSOR_COLOR, Color::rgb8(40, 40, 40));\n\n\n\n configure_button_theme(env);\n\n configure_label_theme(env);\n\n configure_scrollbar_theme(env);\n\n}\n\n\n", "file_path": "ui/src/util/ui/theme.rs", "rank": 42, "score": 142017.83558894263 }, { "content": "/// Configure the scrollbar theme.\n\npub fn configure_scrollbar_theme(env: &mut Env) {\n\n env.set(theme::SCROLLBAR_BORDER_COLOR, Color::rgb8(40, 40, 40));\n\n env.set(theme::SCROLLBAR_COLOR, Color::rgb8(40, 40, 40));\n\n}\n", "file_path": "ui/src/util/ui/theme.rs", "rank": 43, "score": 139858.530492982 }, { "content": "/// Configure the label theme.\n\npub fn configure_label_theme(env: &mut Env) {\n\n env.set(theme::LABEL_COLOR, Color::rgb8(20, 20, 20));\n\n}\n\n\n", "file_path": "ui/src/util/ui/theme.rs", "rank": 44, "score": 139858.530492982 }, { "content": "/// Configure the button theme.\n\npub fn configure_button_theme(env: &mut Env) {\n\n env.set(theme::BUTTON_DARK, Color::rgb8(180, 190, 200));\n\n env.set(theme::BUTTON_LIGHT, Color::rgb8(190, 200, 210));\n\n}\n\n\n", "file_path": "ui/src/util/ui/theme.rs", "rank": 45, "score": 139858.530492982 }, { "content": "fn build_detail_view() -> impl Widget<UiWorkItem> {\n\n Scroll::new(Padding::new(\n\n (15.0, 10.0),\n\n Flex::column()\n\n .main_axis_alignment(MainAxisAlignment::Start)\n\n .cross_axis_alignment(CrossAxisAlignment::Start)\n\n .with_child(build_detail_view_title())\n\n .with_child(\n\n HorizontalSeparator::new(4.0, Color::rgb(0.9, 0.9, 0.9))\n\n .lens(lens::Unit)\n\n .padding((100.0, 10.0)),\n\n )\n\n .with_child(build_detail_view_status())\n\n .with_child(\n\n HorizontalSeparator::new(4.0, Color::rgb(0.9, 0.9, 0.9))\n\n .lens(lens::Unit)\n\n .padding((100.0, 10.0)),\n\n )\n\n .with_child(\n\n Label::new(\"Tags\")\n", "file_path": "ui/src/widget/day_view/day_view.rs", "rank": 46, "score": 139510.6373290299 }, { "content": "/// Update the passed work item with the given optional changes.\n\nfn update_work_item(\n\n item: &mut WorkItem,\n\n description: Option<String>,\n\n tags: Option<Vec<String>>,\n\n) -> Result<(), Box<dyn Error>> {\n\n if description.is_some() {\n\n item.set_description(description.unwrap());\n\n }\n\n\n\n if tags.is_some() {\n\n item.set_tags(HashSet::from_iter(tags.unwrap().into_iter()));\n\n }\n\n\n\n // Persist changes\n\n persistence::update_items(vec![item])\n\n}\n", "file_path": "cli/src/command/edit/edit.rs", "rank": 47, "score": 138637.68486940686 }, { "content": "fn invert_color(color: &Color) -> Color {\n\n let (red, green, blue, _) = color.as_rgba();\n\n let sum = red + green + blue;\n\n\n\n if sum < 1.5 {\n\n Color::WHITE\n\n } else {\n\n Color::BLACK\n\n }\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 48, "score": 137670.55303171396 }, { "content": "fn build_detail_view_tags() -> impl Widget<UiWorkItem> {\n\n TagCloud::new(|ctx, data| {\n\n ctx.submit_command(ITEM_CHANGED.with(data.id).to(ITEM_LIST_WIDGET_ID))\n\n })\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/day_view.rs", "rank": 49, "score": 137164.5229843377 }, { "content": "fn build_detail_view_title() -> impl Widget<UiWorkItem> {\n\n let title_edit_id = WidgetId::next();\n\n\n\n let non_editing_widget = Label::new(|data: &UiWorkItem, _: &Env| data.description.to_owned())\n\n .with_line_break_mode(LineBreaking::WordWrap)\n\n .with_text_size(20.0)\n\n .padding(2.0)\n\n .expand_width();\n\n\n\n let editing_widget = TextBox::multiline()\n\n .with_text_size(20.0)\n\n .lens(UiWorkItem::description)\n\n .expand_width();\n\n\n\n EditableFieldWidget::new(\n\n non_editing_widget,\n\n editing_widget,\n\n |ctx, data: &mut UiWorkItem, _| {\n\n // Update work item in backend\n\n let mut work_item = data.work_item.borrow_mut();\n", "file_path": "ui/src/widget/day_view/day_view.rs", "rank": 50, "score": 137164.5229843377 }, { "content": "fn build_detail_view_status() -> impl Widget<UiWorkItem> {\n\n Flex::row()\n\n .cross_axis_alignment(CrossAxisAlignment::Center)\n\n .with_child(\n\n Label::new(\"Status: \")\n\n .with_text_size(18.0)\n\n .with_text_color(Color::rgb8(120, 120, 120)),\n\n )\n\n .with_child(\n\n Label::new(|data: &UiWorkItem, _: &Env| {\n\n format!(\n\n \"{}\",\n\n match data.status {\n\n UiWorkItemStatus::InProgress => \"In progress\",\n\n UiWorkItemStatus::Paused => \"Paused\",\n\n UiWorkItemStatus::Finished => \"Done\",\n\n }\n\n )\n\n })\n\n .with_text_size(18.0),\n\n )\n\n .with_flex_spacer(1.0)\n\n .with_child(build_detail_view_status_buttons())\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/day_view.rs", "rank": 51, "score": 137164.52298433776 }, { "content": "pub fn find_items_by_timerange(\n\n from_timestamp: i64,\n\n to_timestamp: i64,\n\n) -> Result<Vec<WorkItem>, Box<dyn Error>> {\n\n let data_access = data_access::get_data_access()?;\n\n\n\n Ok(data_access.filter_items(from_timestamp, to_timestamp)?)\n\n}\n\n\n", "file_path": "persistence/src/lib.rs", "rank": 52, "score": 136151.9146778303 }, { "content": "fn build_detail_view_status_buttons() -> impl Widget<UiWorkItem> {\n\n Flex::row()\n\n .with_child(When::new(\n\n |data: &UiWorkItem| data.status == UiWorkItemStatus::InProgress,\n\n UiButton::new(Label::new(\"Pause\").padding((4.0, 2.0)))\n\n .with_color(Color::rgb8(255, 179, 102))\n\n .on_click(|ctx, data: &mut UiWorkItem, _| {\n\n // Update UI work item\n\n data.status = UiWorkItemStatus::Paused;\n\n\n\n // Update work item in backend\n\n let mut work_item = data.work_item.borrow_mut();\n\n work_item.pause_working().unwrap();\n\n persistence::update_items(vec![&work_item]).unwrap();\n\n\n\n // Notify list item that it needs to update as well\n\n ctx.submit_command(ITEM_CHANGED.with(data.id).to(ITEM_LIST_WIDGET_ID));\n\n\n\n ctx.request_update();\n\n }),\n", "file_path": "ui/src/widget/day_view/day_view.rs", "rank": 53, "score": 134922.91923147452 }, { "content": "/// Get the primary monitor from the given list of monitors.\n\npub fn get_primary_monitor(monitors: &[Monitor]) -> Option<&Monitor> {\n\n for monitor in monitors {\n\n if monitor.is_primary() {\n\n return Some(monitor);\n\n }\n\n }\n\n\n\n None\n\n}\n", "file_path": "ui/src/util/ui/ui.rs", "rank": 54, "score": 134337.40237539652 }, { "content": "/// Calculate the total work time without counting parallel work time ranges\n\n/// multiple times.\n\n/// For example when you have parallel work items, the time is only counted once!\n\npub fn calculate_unique_total_time(events: &mut [TimeEvent]) -> i64 {\n\n // Sort events by their timestamp\n\n events.sort_by_key(|v| v.timestamp);\n\n\n\n // Iterate over events and sum up the total time\n\n let mut total_time = 0;\n\n let mut in_progress_count = 0;\n\n let mut start_timestamp: Option<i64> = None;\n\n for event in events {\n\n if event.is_start {\n\n in_progress_count += 1;\n\n\n\n if in_progress_count == 1 {\n\n start_timestamp = Some(event.timestamp); // Memorize as start timestamp\n\n }\n\n } else {\n\n in_progress_count -= 1;\n\n\n\n if in_progress_count == 0 {\n\n // No time range currently in progress -> save to time taken\n", "file_path": "shared/src/calc/time_calculator.rs", "rank": 55, "score": 130907.85706239248 }, { "content": "/// Build the header of the day view.\n\nfn build_header() -> impl Widget<Rc<chrono::Date<chrono::Local>>> {\n\n let arrow_left_svg = icon::get_icon(icon::ARROW_LEFT);\n\n let arrow_right_svg = icon::get_icon(icon::ARROW_RIGHT);\n\n\n\n Flex::row()\n\n .main_axis_alignment(MainAxisAlignment::SpaceBetween)\n\n .with_spacer(10.0)\n\n .with_child(\n\n UiButton::new(Svg::new(arrow_left_svg).fix_width(18.0).padding(8.0))\n\n .with_corner_radius(100.0)\n\n .on_click(|ctx, _, _| {\n\n ctx.submit_command(controller::PREV_DAY.to(controller::DAY_VIEW_WIDGET_ID))\n\n }),\n\n )\n\n .with_flex_spacer(1.0)\n\n .with_child(build_header_date_label())\n\n .with_flex_spacer(1.0)\n\n .with_child(\n\n UiButton::new(Svg::new(arrow_right_svg).fix_width(18.0).padding(8.0))\n\n .with_corner_radius(100.0)\n\n .on_click(|ctx, _, _| {\n\n ctx.submit_command(controller::NEXT_DAY.to(controller::DAY_VIEW_WIDGET_ID))\n\n }),\n\n )\n\n .with_spacer(10.0)\n\n .padding((0.0, 10.0))\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/day_view.rs", "rank": 56, "score": 124825.146497379 }, { "content": "/// Create a tmp work item lookup from the given logs table rows.\n\nfn tmp_item_lookup_from_rows(mut rows: Rows) -> Result<HashMap<i32, TmpWorkItem>, Box<dyn Error>> {\n\n let mut item_lookup = HashMap::new();\n\n while let Some(row) = rows.next()? {\n\n let id: i32 = row.get(0)?;\n\n\n\n let description = row.get(1)?;\n\n\n\n let status_str: String = row.get(2)?;\n\n let status = Status::from_str(&status_str)\n\n .expect(\"Could not interpret Status string stored in the database\");\n\n\n\n item_lookup.insert(\n\n id,\n\n TmpWorkItem {\n\n id,\n\n description,\n\n status,\n\n },\n\n );\n\n }\n\n\n\n Ok(item_lookup)\n\n}\n\n\n", "file_path": "persistence/src/data_access/sqlite/sqlite_data_access.rs", "rank": 57, "score": 118704.71918709122 }, { "content": "/// Work item to be filled with more data.\n\nstruct TmpWorkItem {\n\n id: i32,\n\n description: String,\n\n status: Status,\n\n}\n\n\n\nimpl SQLiteDataAccess {\n\n /// Create a new SQLite data access.\n\n pub fn new() -> Result<SQLiteDataAccess, Box<dyn Error>> {\n\n let db_path = determine_database_path()?;\n\n\n\n // Create directories if they do not exist\n\n fs::create_dir_all(&db_path.parent().unwrap())?;\n\n\n\n let mut data_access = SQLiteDataAccess {\n\n connection: Connection::open(&db_path)?,\n\n };\n\n\n\n data_access.prepare_database()?;\n\n\n", "file_path": "persistence/src/data_access/sqlite/sqlite_data_access.rs", "rank": 58, "score": 114810.92386871728 }, { "content": "/// Get local date time for the passed timestamp.\n\npub fn get_local_date_time(timestamp_millis: i64) -> chrono::DateTime<chrono::Local> {\n\n let date_time: chrono::DateTime<chrono::Utc> = chrono::DateTime::from_utc(\n\n chrono::NaiveDateTime::from_timestamp(timestamp_millis / 1000, 0),\n\n chrono::Utc,\n\n );\n\n\n\n // Adjust UTC date time to the local timezone\n\n chrono::DateTime::from(date_time)\n\n}\n", "file_path": "shared/src/time/mod.rs", "rank": 59, "score": 113422.04358349845 }, { "content": "/// Insert all the given tags for the work item with the passed ID.\n\nfn insert_tags(transaction: &Transaction, id: i32, tags: &[String]) -> Result<(), Box<dyn Error>> {\n\n for tag in tags {\n\n transaction.execute(\n\n \"INSERT INTO log_tags (log_id, tag) VALUES (?1, ?2)\",\n\n params![id, tag],\n\n )?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "persistence/src/data_access/sqlite/sqlite_data_access.rs", "rank": 60, "score": 112267.40225947554 }, { "content": "/// Load work items for the given date.\n\nfn load_work_items(\n\n date: &chrono::Date<chrono::Local>,\n\n) -> Result<Option<DayViewWorkItems>, Box<dyn Error>> {\n\n let from_timestamp = date.and_hms(0, 0, 0).timestamp_millis();\n\n let to_timestamp = date.succ().and_hms(0, 0, 0).timestamp_millis();\n\n\n\n let items = persistence::find_items_by_timerange(from_timestamp, to_timestamp)?;\n\n\n\n if items.is_empty() {\n\n return Ok(None);\n\n }\n\n\n\n let mut ui_work_items = im::Vector::new();\n\n for item in items {\n\n ui_work_items.push_back(Rc::new(RefCell::new(work_item::UiWorkItem {\n\n id: item.id().unwrap(),\n\n description: item.description().to_owned(),\n\n status: match item.status() {\n\n Status::Done => work_item::UiWorkItemStatus::Finished,\n\n Status::InProgress => work_item::UiWorkItemStatus::InProgress,\n", "file_path": "ui/src/state/state.rs", "rank": 61, "score": 110869.01743053642 }, { "content": " }\n\n }\n\n\n\n /// Specify a callback to be called when the item has been clicked.\n\n pub fn on_click(\n\n self,\n\n f: impl Fn(&mut EventCtx, &mut UiWorkItem, &Env) + 'static,\n\n ) -> ControllerHost<Self, Click<UiWorkItem>> {\n\n ControllerHost::new(self, Click::new(f))\n\n }\n\n}\n\n\n\n/// Build the work item timing label.\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 62, "score": 108043.87810529918 }, { "content": "use crate::state::work_item::{UiWorkItem, UiWorkItemStatus};\n\nuse crate::Size;\n\nuse druid::widget::{\n\n Click, Controller, ControllerHost, CrossAxisAlignment, Flex, Label, LineBreaking, List,\n\n MainAxisAlignment, Painter,\n\n};\n\nuse druid::{\n\n BoxConstraints, Color, Env, Event, EventCtx, LayoutCtx, LifeCycle, LifeCycleCtx,\n\n LinearGradient, PaintCtx, Point, Rect, RenderContext, Selector, UnitPoint, UpdateCtx, Widget,\n\n WidgetExt, WidgetId, WidgetPod,\n\n};\n\n\n\nconst HOVER_CHANGED: Selector = Selector::new(\"work-item-header.hover-changed\");\n\npub(crate) const ITEM_CHANGED: Selector<i32> = Selector::new(\"work-item.item-changed\");\n\n\n\npub(crate) struct WorkItemListItemWidget {\n\n header_id: WidgetId,\n\n child: WidgetPod<UiWorkItem, Box<dyn Widget<UiWorkItem>>>,\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 63, "score": 108042.60296027508 }, { "content": "impl WorkItemListItemWidget {\n\n pub fn new() -> WorkItemListItemWidget {\n\n let header_id = WidgetId::next();\n\n let item_header = ControllerHost::new(\n\n ItemHeaderWidget {\n\n left: WidgetPod::new(\n\n Label::new(|item: &UiWorkItem, _env: &_| format!(\"{}\", item.description))\n\n .with_text_size(18.0)\n\n .with_line_break_mode(LineBreaking::Clip),\n\n )\n\n .boxed(),\n\n right: WidgetPod::new(build_timing_label().padding((10.0, 0.0, 0.0, 0.0))).boxed(),\n\n hovered: false,\n\n },\n\n ItemHeaderWidgetController,\n\n )\n\n .with_id(header_id);\n\n\n\n let child = Flex::row()\n\n .main_axis_alignment(MainAxisAlignment::Start)\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 64, "score": 108041.84051082187 }, { "content": " if let LifeCycle::HotChanged(_) = event {\n\n ctx.request_paint();\n\n ctx.submit_command(HOVER_CHANGED.to(self.header_id))\n\n }\n\n\n\n self.child.lifecycle(ctx, event, data, env);\n\n }\n\n\n\n fn update(\n\n &mut self,\n\n ctx: &mut UpdateCtx,\n\n _old_data: &UiWorkItem,\n\n data: &UiWorkItem,\n\n env: &Env,\n\n ) {\n\n self.child.update(ctx, data, env);\n\n }\n\n\n\n fn layout(\n\n &mut self,\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 65, "score": 108039.51102657306 }, { "content": " if let Some(item_id) = cmd.get(ITEM_CHANGED) {\n\n if data.id == *item_id {\n\n ctx.request_update();\n\n }\n\n }\n\n }\n\n }\n\n _ => {}\n\n }\n\n\n\n self.child.event(ctx, event, data, env);\n\n }\n\n\n\n fn lifecycle(\n\n &mut self,\n\n ctx: &mut LifeCycleCtx,\n\n event: &LifeCycle,\n\n data: &UiWorkItem,\n\n env: &Env,\n\n ) {\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 66, "score": 108039.24161337511 }, { "content": " self.right.lifecycle(ctx, event, data, env);\n\n }\n\n\n\n fn update(\n\n &mut self,\n\n ctx: &mut UpdateCtx,\n\n _old_data: &UiWorkItem,\n\n data: &UiWorkItem,\n\n env: &Env,\n\n ) {\n\n self.left.update(ctx, data, env);\n\n self.right.update(ctx, data, env);\n\n }\n\n\n\n fn layout(\n\n &mut self,\n\n ctx: &mut LayoutCtx,\n\n bc: &BoxConstraints,\n\n data: &UiWorkItem,\n\n env: &Env,\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 67, "score": 108036.50442174135 }, { "content": " .with_child(build_status_panel())\n\n .with_spacer(10.0)\n\n .with_flex_child(\n\n Flex::column()\n\n .cross_axis_alignment(CrossAxisAlignment::Start)\n\n .with_child(item_header)\n\n .with_child(\n\n Flex::row()\n\n .with_child(build_status_label())\n\n .with_flex_spacer(1.0)\n\n .with_child(build_tags().lens(UiWorkItem::tags)),\n\n ),\n\n 1.0,\n\n )\n\n .with_spacer(10.0)\n\n .fix_height(60.0);\n\n\n\n WorkItemListItemWidget {\n\n header_id,\n\n child: WidgetPod::new(child).boxed(),\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 68, "score": 108036.39555531806 }, { "content": " ctx: &mut LayoutCtx,\n\n bc: &BoxConstraints,\n\n data: &UiWorkItem,\n\n env: &Env,\n\n ) -> Size {\n\n self.child.layout(ctx, bc, data, env)\n\n }\n\n\n\n fn paint(&mut self, ctx: &mut PaintCtx, data: &UiWorkItem, env: &Env) {\n\n let is_hot = ctx.is_hot();\n\n let size = ctx.size().to_rounded_rect(2.0);\n\n\n\n ctx.fill(size, &get_item_background_color(is_hot));\n\n\n\n self.child.paint(ctx, data, env);\n\n }\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 69, "score": 108035.35486838593 }, { "content": " ) -> Size {\n\n // First layout right item\n\n let right_size = self.right.layout(ctx, bc, data, env);\n\n\n\n // Give left item all the remaining space\n\n let left_bc = BoxConstraints::new(\n\n Size::ZERO,\n\n Size::new(bc.max().width - right_size.width, bc.max().height),\n\n );\n\n let left_size = self.left.layout(ctx, &left_bc, data, env);\n\n\n\n // Translate right widget by the left widget width\n\n self.right\n\n .set_origin(ctx, data, env, Point::new(left_bc.max().width, 0.0));\n\n\n\n Size::new(bc.max().width, left_size.height.max(right_size.height))\n\n }\n\n\n\n fn paint(&mut self, ctx: &mut PaintCtx, data: &UiWorkItem, env: &Env) {\n\n self.left.paint(ctx, data, env);\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 70, "score": 108033.62067858085 }, { "content": " self.right.paint(ctx, data, env);\n\n\n\n // Draw fade gradient for left widget\n\n let right_rect = self.right.layout_rect();\n\n let fade_width = right_rect.x0.min(20.0);\n\n let fade_rect = Rect::new(\n\n right_rect.x0 - fade_width,\n\n 0.0,\n\n right_rect.x0,\n\n ctx.size().height,\n\n );\n\n\n\n let color = get_item_background_color(self.hovered);\n\n let transparent_color = get_item_background_color(self.hovered).with_alpha(0.0);\n\n\n\n ctx.fill(\n\n fade_rect,\n\n &LinearGradient::new(\n\n UnitPoint::LEFT,\n\n UnitPoint::RIGHT,\n\n (transparent_color, color),\n\n ),\n\n );\n\n }\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/work_item/work_item_list_item.rs", "rank": 71, "score": 108028.61900800407 }, { "content": "/// Create a tags lookup from the passed log_tags table rows.\n\nfn tags_lookup_from_rows(mut rows: Rows) -> Result<HashMap<i32, HashSet<String>>, Box<dyn Error>> {\n\n let mut tags_lookup: HashMap<i32, HashSet<String>> = HashMap::new();\n\n while let Some(row) = rows.next()? {\n\n let log_id: i32 = row.get(0)?;\n\n let tag: String = row.get(1)?;\n\n\n\n match tags_lookup.entry(log_id) {\n\n Entry::Occupied(mut e) => {\n\n e.get_mut().insert(tag);\n\n }\n\n Entry::Vacant(e) => {\n\n let mut set = HashSet::new();\n\n set.insert(tag);\n\n e.insert(set);\n\n }\n\n };\n\n }\n\n\n\n Ok(tags_lookup)\n\n}\n\n\n", "file_path": "persistence/src/data_access/sqlite/sqlite_data_access.rs", "rank": 72, "score": 104894.88142716864 }, { "content": "/// Get the current UTC+0 timestamp in milliseconds.\n\nfn get_current_timestamp() -> i64 {\n\n chrono::Utc::now().timestamp_millis()\n\n}\n", "file_path": "persistence/src/calc/work_item.rs", "rank": 73, "score": 104570.86485267674 }, { "content": "/// Create final work items from the passed caches.\n\nfn create_work_items(\n\n item_lookup: HashMap<i32, TmpWorkItem>,\n\n mut tags_lookup: HashMap<i32, HashSet<String>>,\n\n mut events_lookup: HashMap<i32, Vec<Event>>,\n\n) -> Vec<WorkItem> {\n\n item_lookup\n\n .into_iter()\n\n .map(|(id, tmp_item)| {\n\n // Retrieve cached tags\n\n let tags = tags_lookup.remove(&id).unwrap_or(HashSet::new());\n\n\n\n // Retrieve cached events and sort them by their timestamp\n\n let mut events = events_lookup\n\n .remove(&id)\n\n .expect(\"Found no events for a work item, which must not be possible\");\n\n events.sort_by_key(|e| e.timestamp());\n\n\n\n WorkItem::new_internal(\n\n tmp_item.id,\n\n tmp_item.description,\n\n tmp_item.status,\n\n tags,\n\n events,\n\n )\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "persistence/src/data_access/sqlite/sqlite_data_access.rs", "rank": 74, "score": 101184.84652523977 }, { "content": "/// Build placeholder for no items.\n\nfn build_placeholder() -> impl Widget<()> {\n\n Flex::column()\n\n .main_axis_alignment(MainAxisAlignment::Center)\n\n .with_child(Svg::new(icon::get_icon(icon::SLOTH)).fix_height(150.0))\n\n .with_spacer(30.0)\n\n .with_child(\n\n Label::new(\"No work items for the day!\")\n\n .with_text_size(24.0)\n\n .with_line_break_mode(LineBreaking::WordWrap)\n\n .with_text_alignment(TextAlignment::Center)\n\n .with_text_color(Color::rgb8(100, 100, 100))\n\n .fix_width(300.0),\n\n )\n\n .expand_height()\n\n}\n\n\n", "file_path": "ui/src/widget/day_view/day_view.rs", "rank": 75, "score": 95985.74243008954 }, { "content": "pub fn clear() -> Result<(), Box<dyn Error>> {\n\n let mut data_access = data_access::get_data_access()?;\n\n\n\n Ok(data_access.clear()?)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n #[test]\n\n fn it_works() {\n\n assert_eq!(2 + 2, 4);\n\n }\n\n}\n", "file_path": "persistence/src/lib.rs", "rank": 76, "score": 92121.17661339477 }, { "content": "/// Build the root widget.\n\nfn build_root_widget() -> impl Widget<state::UiState> {\n\n Flex::row()\n\n .cross_axis_alignment(CrossAxisAlignment::Start)\n\n .with_flex_child(\n\n LensWrap::new(day_view::DayViewWidget::new(), state::UiState::day),\n\n 1.0,\n\n )\n\n .background(LinearGradient::new(\n\n UnitPoint::TOP,\n\n UnitPoint::BOTTOM,\n\n (Color::rgb8(255, 255, 255), Color::rgb8(220, 230, 240)),\n\n ))\n\n .env_scope(|env, _| {\n\n util::ui::env::configure_environment(env);\n\n })\n\n}\n", "file_path": "ui/src/main.rs", "rank": 77, "score": 91432.4202347183 }, { "content": "/// Build the date label for the day view header.\n\nfn build_header_date_label() -> Label<Rc<chrono::Date<chrono::Local>>> {\n\n Label::dynamic(|date_ref: &Rc<chrono::Date<chrono::Local>>, _| {\n\n date_ref.as_ref().format(\"%A, %d. %B\").to_string()\n\n })\n\n .with_text_size(32.0)\n\n}\n\n\n\nimpl Widget<state::DayViewState> for DayViewWidget {\n\n fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut DayViewState, env: &Env) {\n\n self.child.event(ctx, event, data, env);\n\n }\n\n\n\n fn lifecycle(\n\n &mut self,\n\n ctx: &mut LifeCycleCtx,\n\n event: &LifeCycle,\n\n data: &DayViewState,\n\n env: &Env,\n\n ) {\n\n self.child.lifecycle(ctx, event, data, env);\n", "file_path": "ui/src/widget/day_view/day_view.rs", "rank": 78, "score": 90888.45182177662 }, { "content": "/// Determine the path to the logs database.\n\nfn determine_database_path() -> Result<path::PathBuf, &'static str> {\n\n Ok(match home::home_dir() {\n\n Some(path) => Ok(path),\n\n None => Err(\"Could not determine the current users HOME directory\"),\n\n }?\n\n .join(SUB_HOME_DIRECTORY)\n\n .join(FILE_NAME))\n\n}\n\n\n", "file_path": "persistence/src/data_access/sqlite/sqlite_data_access.rs", "rank": 79, "score": 81914.99272989371 }, { "content": "use druid::{Data, Lens};\n\nuse std::cell::RefCell;\n\nuse std::rc::Rc;\n\n\n\n/// Work item displayable in the UI.\n\n#[derive(Clone, Data, Lens)]\n\npub struct UiWorkItem {\n\n /// ID of the work item.\n\n pub id: i32,\n\n /// Description of the work item.\n\n pub description: String,\n\n /// Status of the work item.\n\n pub status: UiWorkItemStatus,\n\n /// Tags of the item.\n\n pub tags: im::Vector<String>,\n\n /// Reference to the original work item.\n\n pub work_item: Rc<RefCell<persistence::calc::WorkItem>>,\n\n /// Temporary string used for example to add a new tag to the tag list.\n\n pub tmp: String,\n\n}\n\n\n\n#[derive(Clone, Data, PartialEq, Debug)]\n\npub enum UiWorkItemStatus {\n\n InProgress,\n\n Paused,\n\n Finished,\n\n}\n", "file_path": "ui/src/state/work_item/work_item.rs", "rank": 80, "score": 80252.86867078066 }, { "content": "/// Delete all tags for the work item with the given ID.\n\nfn delete_tags(transaction: &Transaction, id: i32) -> Result<(), Box<dyn Error>> {\n\n transaction.execute(\"DELETE FROM log_tags WHERE log_id = ?1\", params![id])?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "persistence/src/data_access/sqlite/sqlite_data_access.rs", "rank": 81, "score": 76806.72396411409 }, { "content": "/// Delete all events for the work item with the given ID.\n\nfn delete_events(transaction: &Transaction, id: i32) -> Result<(), Box<dyn Error>> {\n\n transaction.execute(\"DELETE FROM log_events WHERE log_id = ?1\", params![id])?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "persistence/src/data_access/sqlite/sqlite_data_access.rs", "rank": 82, "score": 76806.72396411409 }, { "content": "use crate::command::command::Command;\n\nuse cmd_args::{arg, option, Group};\n\nuse colorful::Colorful;\n\nuse persistence::calc::event::{Event, EventType};\n\nuse persistence::calc::Status;\n\nuse std::collections::{HashMap, HashSet};\n\nuse std::iter::FromIterator;\n\n\n\n/// Command used to log work items directly.\n\npub struct LogCommand {}\n\n\n\nimpl Command for LogCommand {\n\n fn build(&self) -> Group {\n\n Group::new(\n\n Box::new(|args, options| execute(args, options)),\n\n \"Log an already done work item\",\n\n )\n\n .add_argument(arg::Descriptor::new(\n\n arg::Type::Str,\n\n \"Description of the work done\",\n", "file_path": "cli/src/command/log/log.rs", "rank": 83, "score": 76341.8687342844 }, { "content": " ))\n\n .add_argument(arg::Descriptor::new(arg::Type::Str, \"Tags\"))\n\n .add_argument(arg::Descriptor::new(\n\n arg::Type::Str,\n\n \"Time spent on the task (Format like '2h 3m 12s', '45m' or '1h 15m')\",\n\n ))\n\n }\n\n\n\n fn aliases(&self) -> Option<Vec<&str>> {\n\n Some(vec![\"l\"])\n\n }\n\n\n\n fn name(&self) -> &str {\n\n \"log\"\n\n }\n\n}\n\n\n\n/// Execute the log command.\n", "file_path": "cli/src/command/log/log.rs", "rank": 84, "score": 76329.63764091225 }, { "content": "use crate::command::command::Command;\n\nuse cmd_args::{arg, option, Group};\n\nuse colorful::Colorful;\n\nuse persistence::calc::WorkItem;\n\nuse std::collections::HashMap;\n\n\n\n/// Command used to show details about a work item.\n\npub struct ShowCommand {}\n\n\n\nimpl Command for ShowCommand {\n\n fn build(&self) -> Group {\n\n Group::new(\n\n Box::new(|args, options| execute(args, options)),\n\n \"Show details about a work item\",\n\n )\n\n .add_argument(arg::Descriptor::new(\n\n arg::Type::Int,\n\n \"ID of the work item to show details for\",\n\n ))\n\n }\n", "file_path": "cli/src/command/show/show.rs", "rank": 85, "score": 76269.39830462392 }, { "content": "\n\n fn aliases(&self) -> Option<Vec<&str>> {\n\n Some(vec![\"details\", \"detail\"])\n\n }\n\n\n\n fn name(&self) -> &str {\n\n \"show\"\n\n }\n\n}\n\n\n\n/// Execute the show command.\n", "file_path": "cli/src/command/show/show.rs", "rank": 86, "score": 76254.2286445539 }, { "content": " println!();\n\n\n\n println!(\"{}\", \"# Statistics\".underlined());\n\n\n\n println!(\n\n \" • Total time in progress: {}\",\n\n shared::time::format_duration((item.time_taken() / 1000) as u32)\n\n );\n\n\n\n println!();\n\n}\n\n\n", "file_path": "cli/src/command/show/show.rs", "rank": 87, "score": 76253.20341729531 }, { "content": " println!();\n\n\n\n println!(\"{}\", \"# Tags\".underlined());\n\n\n\n for tag in item.tags() {\n\n println!(\" • {}\", tag.color(colorful::Color::DeepPink2));\n\n }\n\n\n\n println!();\n\n\n\n println!(\"{}\", \"# Events\".underlined());\n\n\n\n for event in item.events() {\n\n println!(\n\n \" • [{}] at {}\",\n\n format!(\"{}\", event.event_type()).color(colorful::Color::DarkSlateGray1),\n\n shared::time::get_local_date_time(event.timestamp()).format(\"%H:%M:%S - %A, %Y-%m-%d\")\n\n );\n\n }\n\n\n", "file_path": "cli/src/command/show/show.rs", "rank": 88, "score": 76251.91222488719 }, { "content": "/// Get the data access to use.\n\npub fn get_data_access() -> Result<Box<dyn DataAccess>, Box<dyn Error>> {\n\n Ok(Box::new(SQLiteDataAccess::new()?))\n\n}\n", "file_path": "persistence/src/data_access/data_access_factory.rs", "rank": 96, "score": 74766.00557655616 }, { "content": "/// Create an events lookup from the passed log_events table rows.\n\nfn events_lookup_from_rows(mut rows: Rows) -> Result<HashMap<i32, Vec<Event>>, Box<dyn Error>> {\n\n let mut events_lookup: HashMap<i32, Vec<Event>> = HashMap::new();\n\n while let Some(row) = rows.next()? {\n\n let log_id: i32 = row.get(0)?;\n\n\n\n let timestamp: i64 = row.get(1)?;\n\n\n\n let event_str: String = row.get(2)?;\n\n let event_type =\n\n EventType::from_str(&event_str).expect(\"EventType string could not be interpreted\");\n\n\n\n match events_lookup.entry(log_id) {\n\n Entry::Occupied(mut e) => {\n\n e.get_mut().push(Event::new(event_type, timestamp));\n\n }\n\n Entry::Vacant(e) => {\n\n e.insert(vec![Event::new(event_type, timestamp)]);\n\n }\n\n };\n\n }\n\n\n\n Ok(events_lookup)\n\n}\n\n\n", "file_path": "persistence/src/data_access/sqlite/sqlite_data_access.rs", "rank": 97, "score": 68300.99405701997 }, { "content": "mod log;\n\n\n\npub use log::LogCommand;\n", "file_path": "cli/src/command/log/mod.rs", "rank": 98, "score": 67819.42780069103 }, { "content": "mod show;\n\n\n\npub use show::ShowCommand;\n", "file_path": "cli/src/command/show/mod.rs", "rank": 99, "score": 67759.04322208447 } ]
Rust
nachricht-serde/src/ser.rs
yasammez/nachricht
846d60dec1da1ddd5ffa2c1fa1ab7ec5d7386bce
use serde::ser::{self, Serialize, Impossible}; use nachricht::{EncodeError, Header, Refable}; use std::io::Write; use crate::error::{Error, Result}; pub struct Serializer<W> { symbols: Vec<(Refable, String)>, output: W, } pub fn to_bytes<T: Serialize>(value: &T) -> Result<Vec<u8>> { let buf = Vec::new(); let mut serializer = Serializer { output: buf, symbols: Vec::new() }; value.serialize(&mut serializer)?; Ok(serializer.output()) } pub fn to_writer<T: Serialize, W: Write>(writer: W, value: &T) -> Result<()> { let mut serializer = Serializer { output: writer, symbols: Vec::new() }; value.serialize(&mut serializer)?; Ok(()) } impl Serializer<Vec<u8>> { fn output(self) -> Vec<u8> { self.output } } impl<W: Write> Serializer<W> { fn serialize_refable(&mut self, key: &str, kind: Refable) -> Result<()> { match self.symbols.iter().enumerate().find(|(_, (k, v))| *k == kind && v == key) { Some((i, _)) => { Header::Ref(i).encode(&mut self.output)?; }, None => { self.symbols.push((kind, key.to_owned())); match kind { Refable::Key => Header::Key(key.len()), Refable::Sym => Header::Sym(key.len()) }.encode(&mut self.output)?; self.output.write_all(key.as_bytes()).map_err(EncodeError::from)?; } } Ok(()) } } impl<'a, W: Write> ser::Serializer for &'a mut Serializer<W> { type Ok = (); type Error = Error; type SerializeSeq = Self; type SerializeTuple = Self; type SerializeTupleStruct = Self; type SerializeTupleVariant = Self; type SerializeMap = Self; type SerializeStruct = Self; type SerializeStructVariant = Self; fn serialize_bool(self, v: bool) -> Result<()> { match v { true => Header::True, false => Header::False }.encode(&mut self.output)?; Ok(()) } fn serialize_i8(self, v: i8) -> Result<()> { self.serialize_i64(i64::from(v)) } fn serialize_i16(self, v: i16) -> Result<()> { self.serialize_i64(i64::from(v)) } fn serialize_i32(self, v: i32) -> Result<()> { self.serialize_i64(i64::from(v)) } fn serialize_i64(self, v: i64) -> Result<()> { if v < 0 { Header::Neg(v.abs() as u64) } else { Header::Pos(v as u64) }.encode(&mut self.output)?; Ok(()) } fn serialize_u8(self, v: u8) -> Result<()> { self.serialize_u64(u64::from(v)) } fn serialize_u16(self, v: u16) -> Result<()> { self.serialize_u64(u64::from(v)) } fn serialize_u32(self, v: u32) -> Result<()> { self.serialize_u64(u64::from(v)) } fn serialize_u64(self, v: u64) -> Result<()> { Header::Pos(v).encode(&mut self.output)?; Ok(()) } fn serialize_f32(self, v: f32) -> Result<()> { Header::F32.encode(&mut self.output)?; self.output.write_all(&v.to_be_bytes()).map_err(EncodeError::from)?; Ok(()) } fn serialize_f64(self, v: f64) -> Result<()> { Header::F64.encode(&mut self.output)?; self.output.write_all(&v.to_be_bytes()).map_err(EncodeError::from)?; Ok(()) } fn serialize_char(self, v: char) -> Result<()> { self.serialize_str(&v.to_string()) } fn serialize_str(self, v: &str) -> Result<()> { Header::Str(v.len()).encode(&mut self.output)?; self.output.write_all(v.as_bytes()).map_err(EncodeError::from)?; Ok(()) } fn serialize_bytes(self, v: &[u8]) -> Result<()> { Header::Bin(v.len()).encode(&mut self.output)?; self.output.write_all(v).map_err(EncodeError::from)?; Ok(()) } fn serialize_none(self) -> Result<()> { Header::Null.encode(&mut self.output)?; Ok(()) } fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<()> { value.serialize(self) } fn serialize_unit(self) -> Result<()> { Header::Null.encode(&mut self.output)?; Ok(()) } fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { self.serialize_unit() } fn serialize_unit_variant(self, _name: &'static str, _index: u32, variant: &'static str) -> Result<()> { self.serialize_refable(variant, Refable::Sym) } fn serialize_newtype_struct<T: ?Sized + Serialize>(self, _name: &'static str, value: &T) -> Result<()> { value.serialize(self) } fn serialize_newtype_variant<T: ?Sized + Serialize>(self, _name: &'static str, _index: u32, variant: &'static str, value: &T) -> Result<()> { Header::Bag(1).encode(&mut self.output)?; self.serialize_refable(variant, Refable::Key)?; value.serialize(self)?; Ok(()) } fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> { match len { Some(l) => { Header::Bag(l).encode(&mut self.output)?; Ok(self) }, None => Err(Error::Length), } } fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> { self.serialize_seq(Some(len)) } fn serialize_tuple_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeTupleStruct> { self.serialize_seq(Some(len)) } fn serialize_tuple_variant(self, _name: &'static str, _index: u32, variant: &'static str, len: usize) -> Result<Self::SerializeTupleVariant> { Header::Bag(1).encode(&mut self.output)?; self.serialize_refable(variant, Refable::Key)?; Header::Bag(len).encode(&mut self.output)?; Ok(self) } fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> { match len { Some(len) => { Header::Bag(len).encode(&mut self.output)?; Ok(self) }, None => Err(Error::Length) } } fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> { Header::Bag(len).encode(&mut self.output)?; Ok(self) } fn serialize_struct_variant(self, name: &'static str, index: u32, variant: &'static str, len: usize) -> Result<Self::SerializeStructVariant> { self.serialize_tuple_variant(name, index, variant, len) } } impl<'a, W: Write> ser::SerializeSeq for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeTuple for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeTupleStruct for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeTupleVariant for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeMap for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<()> { key.serialize(MapKeySerializer { ser: self }) } fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeStruct for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<()> { self.serialize_refable(key, Refable::Key)?; value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeStructVariant for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<()> { self.serialize_refable(key, Refable::Key)?; value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } struct MapKeySerializer<'a, W: 'a> { ser: &'a mut Serializer<W>, } impl<'a, W: Write> ser::Serializer for MapKeySerializer<'a, W> { type Ok = (); type Error = Error; type SerializeSeq = Impossible<(), Error>; type SerializeTuple = Impossible<(), Error>; type SerializeTupleStruct = Impossible<(), Error>; type SerializeTupleVariant = Impossible<(), Error>; type SerializeMap = Impossible<(), Error>; type SerializeStruct = Impossible<(), Error>; type SerializeStructVariant = Impossible<(), Error>; fn serialize_bool(self, v: bool) -> Result<()> { self.ser.serialize_refable(match v { true => "true", false => "false" }, Refable::Key) } fn serialize_i8(self, v: i8) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_i16(self, v: i16) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_i32(self, v: i32) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_i64(self, v: i64) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_u8(self, v: u8) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_u16(self, v: u16) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_u32(self, v: u32) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_u64(self, v: u64) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_f32(self, _v: f32) -> Result<()> { Err(Error::KeyType) } fn serialize_f64(self, _v: f64) -> Result<()> { Err(Error::KeyType) } fn serialize_char(self, v: char) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_str(self, v: &str) -> Result<()> { self.ser.serialize_refable(v, Refable::Key) } fn serialize_bytes(self, _v: &[u8]) -> Result<()> { Err(Error::KeyType) } fn serialize_none(self) -> Result<()> { Err(Error::KeyType) } fn serialize_some<T: ?Sized + Serialize>(self, _v: &T) -> Result<()> { Err(Error::KeyType) } fn serialize_unit(self) -> Result<()> { Err(Error::KeyType) } fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { Err(Error::KeyType) } fn serialize_unit_variant(self, _name: &'static str, _index: u32, variant: &'static str) -> Result<()> { self.ser.serialize_refable(variant, Refable::Key) } fn serialize_newtype_struct<T: ?Sized + Serialize>(self, _name: &'static str, value: &T) -> Result<()> { value.serialize(self) } fn serialize_newtype_variant<T: ?Sized + Serialize>(self, _name: &'static str, _index: u32, _variant: &'static str, _value: &T) -> Result<()> { Err(Error::KeyType) } fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> { Err(Error::KeyType) } fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { Err(Error::KeyType) } fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> { Err(Error::KeyType) } fn serialize_tuple_variant(self, _name: &'static str, _index: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeTupleVariant> { Err(Error::KeyType) } fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> { Err(Error::KeyType) } fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> { Err(Error::KeyType) } fn serialize_struct_variant(self, _name: &'static str, _index: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeStructVariant> { Err(Error::KeyType) } }
use serde::ser::{self, Serialize, Impossible}; use nachricht::{EncodeError, Header, Refable}; use std::io::Write; use crate::error::{Error, Result}; pub struct Serializer<W> { symbols: Vec<(Refable, String)>, output: W, } pub fn to_bytes<T: Serialize>(value: &T) -> Result<Vec<u8>> { let buf = Vec::new(); let mut serializer = Serializer { output: buf, symbols: Vec::new() }; value.serialize(&mut serializer)?; Ok(serializer.output()) } pub fn to_writer<T: Serialize, W: Write>(writer: W, value: &T) -> Result<()> { let mut serializer = Serializer { output: writer, symbols: Vec::new() }; value.serialize(&mut serializer)?; Ok(()) } impl Serializer<Vec<u8>> { fn output(self) -> Vec<u8> { self.output } } impl<W: Write> Serializer<W> { fn serialize_refable(&mut self, key: &str, kind: Refable) -> Result<()> { match self.symbols.iter().enumerate().find(|(_, (k, v))| *k == kind && v == key) { Some((i, _)) => { Header::Ref(i).encode(&mut self.output)?; }, None => { self.symbols.push((kind, key.to_owned())); match kind { Refable::Key => Header::Key(key.len()), Refable::Sym => Header::Sym(key.len()) }.encode(&mut self.output)?; self.output.write_all(key.as_bytes()).map_err(EncodeError::from)?; } } Ok(()) } } impl<'a, W: Write> ser::Serializer for &'a mut Serializer<W> { type Ok = (); type Error = Error; type SerializeSeq = Self; type SerializeTuple = Self; type SerializeTupleStruct = Self; type SerializeTupleVariant = Self; type SerializeMap = Self; type SerializeStruct = Self; type SerializeStructVariant = Self; fn serialize_bool(self, v: bool) -> Result<()> { match v { true => Header::True, false => Header::False }.encode(&mut self.output)?; Ok(()) } fn serialize_i8(self, v: i8) -> Result<()> { self.serialize_i64(i64::from(v)) } fn serialize_i16(self, v: i16) -> Result<()> { self.serialize_i64(i64::from(v)) } fn serialize_i32(self, v: i32) -> Result<()> { self.serialize_i64(i64::from(v)) } fn serialize_i64(self, v: i64) -> Result<()> { if v < 0 { Header::Neg(v.abs() as u64) } else { Header::Pos(v as u64) }.encode(&mut self.output)?; Ok(()) } fn serialize_u8(self, v: u8) -> Result<()> { self.serialize_u64(u64::from(v)) } fn serialize_u16(self, v: u16) -> Result<()> { self.serialize_u64(u64::from(v)) } fn serialize_u32(self, v: u32) -> Result<()> { self.serialize_u64(u64::from(v)) } fn serialize_u64(self, v: u64) -> Result<()> { Header::Pos(v).encode(&mut self.output)?; Ok(()) } fn serialize_f32(self, v: f32) -> Result<()> { Header::F32.encode(&mut self.output)?; self.output.write_all(&v.to_be_bytes()).map_err(EncodeError::from)?; Ok(()) } fn serialize_f64(self, v: f64) -> Result<()> { Header::F64.encode(&mut self.output)?; self.output.write_all(&v.to_be_bytes()).map_err(EncodeError::from)?; Ok(()) } fn serialize_char(self, v: char) -> Result<()> { self.serialize_str(&v.to_string()) } fn serialize_str(self, v: &str) -> Result<()> { Header::Str(v.len()).encode(&mut self.output)?; self.output.write_all(v.as_bytes()).map_err(EncodeError::from)?; Ok(()) } fn serialize_bytes(self, v: &[u8]) -> Result<()> { Header::Bin(v.len()).encode(&mut self.output)?; self.output.write_all(v).map_err(EncodeError::from)?; Ok(()) } fn serialize_none(self) -> Result<()> { Header::Null.encode(&mut self.output)?; Ok(()) } fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<()> { value.serialize(self) } fn serialize_unit(self) -> Result<()> { Header::Null.encode(&mut self.output)?; Ok(()) } fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { self.serialize_unit() } fn serialize_unit_variant(self, _name: &'static str, _index: u32, variant: &'static str) -> Result<()> { self.serialize_refable(variant, Refable::Sym) } fn serialize_newtype_struct<T: ?Sized + Serialize>(self, _name: &'static str, value: &T) -> Result<()> { value.serialize(self) } fn serialize_newtype_variant<T: ?Sized + Serialize>(self, _name: &'static str, _index: u32, variant: &'static str, value: &T) -> Result<()> { Header::Bag(1).encode(&mut self.output)?; self.serialize_refable(variant, Refable::Key)?; value.serialize(self)?; Ok(()) } fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> { match len { Some(l) => { Header::Bag(l).encode(&mut self.output)?; Ok(self) }, None => Err(Error::Length), } } fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> { self.serialize_seq(Some(len)) } fn serialize_tuple_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeTupleStruct> { self.serialize_seq(Some(len)) } fn serialize_tuple_variant(self, _name: &'static str, _index: u32, variant: &'static str, len: usize) -> Result<Self::SerializeTupleVariant> { Header::Bag(1).encode(&mut self.outpu
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> { match len { Some(len) => { Header::Bag(len).encode(&mut self.output)?; Ok(self) }, None => Err(Error::Length) } } fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> { Header::Bag(len).encode(&mut self.output)?; Ok(self) } fn serialize_struct_variant(self, name: &'static str, index: u32, variant: &'static str, len: usize) -> Result<Self::SerializeStructVariant> { self.serialize_tuple_variant(name, index, variant, len) } } impl<'a, W: Write> ser::SerializeSeq for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeTuple for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeTupleStruct for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeTupleVariant for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeMap for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<()> { key.serialize(MapKeySerializer { ser: self }) } fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> { value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeStruct for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<()> { self.serialize_refable(key, Refable::Key)?; value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } impl<'a, W: Write> ser::SerializeStructVariant for &'a mut Serializer<W> { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<()> { self.serialize_refable(key, Refable::Key)?; value.serialize(&mut **self) } fn end(self) -> Result<()> { Ok(()) } } struct MapKeySerializer<'a, W: 'a> { ser: &'a mut Serializer<W>, } impl<'a, W: Write> ser::Serializer for MapKeySerializer<'a, W> { type Ok = (); type Error = Error; type SerializeSeq = Impossible<(), Error>; type SerializeTuple = Impossible<(), Error>; type SerializeTupleStruct = Impossible<(), Error>; type SerializeTupleVariant = Impossible<(), Error>; type SerializeMap = Impossible<(), Error>; type SerializeStruct = Impossible<(), Error>; type SerializeStructVariant = Impossible<(), Error>; fn serialize_bool(self, v: bool) -> Result<()> { self.ser.serialize_refable(match v { true => "true", false => "false" }, Refable::Key) } fn serialize_i8(self, v: i8) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_i16(self, v: i16) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_i32(self, v: i32) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_i64(self, v: i64) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_u8(self, v: u8) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_u16(self, v: u16) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_u32(self, v: u32) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_u64(self, v: u64) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_f32(self, _v: f32) -> Result<()> { Err(Error::KeyType) } fn serialize_f64(self, _v: f64) -> Result<()> { Err(Error::KeyType) } fn serialize_char(self, v: char) -> Result<()> { self.ser.serialize_refable(&v.to_string(), Refable::Key) } fn serialize_str(self, v: &str) -> Result<()> { self.ser.serialize_refable(v, Refable::Key) } fn serialize_bytes(self, _v: &[u8]) -> Result<()> { Err(Error::KeyType) } fn serialize_none(self) -> Result<()> { Err(Error::KeyType) } fn serialize_some<T: ?Sized + Serialize>(self, _v: &T) -> Result<()> { Err(Error::KeyType) } fn serialize_unit(self) -> Result<()> { Err(Error::KeyType) } fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { Err(Error::KeyType) } fn serialize_unit_variant(self, _name: &'static str, _index: u32, variant: &'static str) -> Result<()> { self.ser.serialize_refable(variant, Refable::Key) } fn serialize_newtype_struct<T: ?Sized + Serialize>(self, _name: &'static str, value: &T) -> Result<()> { value.serialize(self) } fn serialize_newtype_variant<T: ?Sized + Serialize>(self, _name: &'static str, _index: u32, _variant: &'static str, _value: &T) -> Result<()> { Err(Error::KeyType) } fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> { Err(Error::KeyType) } fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { Err(Error::KeyType) } fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> { Err(Error::KeyType) } fn serialize_tuple_variant(self, _name: &'static str, _index: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeTupleVariant> { Err(Error::KeyType) } fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> { Err(Error::KeyType) } fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> { Err(Error::KeyType) } fn serialize_struct_variant(self, _name: &'static str, _index: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeStructVariant> { Err(Error::KeyType) } }
t)?; self.serialize_refable(variant, Refable::Key)?; Header::Bag(len).encode(&mut self.output)?; Ok(self) }
function_block-function_prefixed
[ { "content": "fn symbol(i: &str) -> IResult<&str, String> {\n\n alt((\n\n map(tuple((tag(\"#\"), identifier)), |(_,i)| String::from(i)),\n\n map(tuple((tag(\"#\"), escaped_string)), |(_,i)| i)\n\n ))(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 1, "score": 180756.81549580873 }, { "content": "fn key(i: &str) -> IResult<&str, String> {\n\n alt((\n\n map(tuple((identifier, white, tag(\"=\"))), |(i,_,_)| String::from(i)),\n\n map(tuple((escaped_string, white, tag(\"=\"))), |(i,_,_)| i)\n\n ))(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 2, "score": 180686.42554043856 }, { "content": "fn escaped_string(i: &str) -> IResult<&str, String> {\n\n delimited(\n\n tag(\"\\\"\"),\n\n alt((\n\n escaped_transform(\n\n is_not(\"\\\\\\\"\"),\n\n '\\\\',\n\n alt((\n\n value(\"\\\\\", tag(\"\\\\\")),\n\n value(\"\\n\", tag(\"n\")),\n\n value(\"\\\"\", tag(\"\\\"\")),\n\n ))\n\n ),\n\n map(tag(\"\"), String::from)\n\n )),\n\n tag(\"\\\"\"),\n\n )(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 4, "score": 147273.98597854795 }, { "content": "pub fn from_bytes<'a, T: Deserialize<'a>>(s: &'a [u8]) -> std::result::Result<T, DeserializationError> {\n\n let mut deserializer = Deserializer::from_bytes(s);\n\n let t = T::deserialize(&mut deserializer).map_err(|e| e.at(deserializer.pos))?;\n\n if deserializer.input[deserializer.pos..].is_empty() {\n\n Ok(t)\n\n } else {\n\n Err(Error::Trailing.at(deserializer.pos))\n\n }\n\n}\n\n\n\nimpl<'de> Deserializer<'de> {\n\n\n\n #[inline]\n\n fn decode_header(&mut self) -> Result<Header> {\n\n let (header, c) = Header::decode(&self.input[self.pos..])?;\n\n self.pos += c;\n\n Ok(header)\n\n }\n\n\n\n #[inline]\n", "file_path": "nachricht-serde/src/de.rs", "rank": 5, "score": 143997.54551609722 }, { "content": "pub fn parse(i: &str) -> Result<Field> {\n\n Ok(all_consuming(terminated(field, white))(i).finish().map_err(|e| anyhow!(\"{}\", e))?.1)\n\n}\n\n\n\npub enum Keyword {\n\n Null,\n\n True,\n\n False,\n\n}\n\n\n\nconst WHITESPACE: &'static str = \" \\t\\r\\n\";\n\nconst B64_CHARS: &'static str = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890+/\";\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 6, "score": 143068.90977407154 }, { "content": "fn float32(i: &str) -> IResult<&str, f32> {\n\n map_res(tuple((tag(\"$\"), float)), |(_,n)| n.parse())(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 7, "score": 142254.15634870718 }, { "content": "fn float64(i: &str) -> IResult<&str, f64> {\n\n map_res(tuple((tag(\"$$\"), float)), |(_,n)| n.parse())(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 8, "score": 142254.15634870718 }, { "content": "fn intp(i: &str) -> IResult<&str, u64> {\n\n map_res(digit1, |n: &str| n.parse())(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 9, "score": 142067.98357432787 }, { "content": "fn intn(i: &str) -> IResult<&str, u64> {\n\n map_res(tuple((tag(\"-\"), digit1)), |(_,n): (&str, &str)| n.parse())(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 10, "score": 142067.98357432787 }, { "content": "fn bytes(i: &str) -> IResult<&str, Vec<u8>> {\n\n map_res(delimited(\n\n tag(\"'\"),\n\n b64,\n\n tag(\"'\")), |c| { decode(c) }\n\n )(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 11, "score": 136456.93283308885 }, { "content": "fn nch_value(i: &str) -> IResult<&str, Value> {\n\n map(tuple((\n\n white,\n\n alt((\n\n map(container, |f| Value::Container(f)),\n\n map(symbol, |s| Value::Symbol(Cow::Owned(s))),\n\n map(escaped_string, |s| Value::Str(Cow::Owned(s))),\n\n map(bytes, |b| Value::Bytes(Cow::Owned(b))),\n\n map(intn, |i| Value::Int(Sign::Neg, i)),\n\n map(intp, |i| Value::Int(Sign::Pos, i)),\n\n map(float32, |f| Value::F32(f)),\n\n map(float64, |f| Value::F64(f)),\n\n map(keyword, |k| match k {\n\n Keyword::Null => Value::Null,\n\n Keyword::True => Value::Bool(true),\n\n Keyword::False => Value::Bool(false)\n\n })\n\n )),\n\n white\n\n )), |(_,v,_)| v)(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 12, "score": 131778.42433111364 }, { "content": "fn float(i: &str) -> IResult<&str, &str> {\n\n recognize(tuple((opt(tag(\"-\")), opt(digit1), opt(tag(\".\")), opt(digit1))))(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 14, "score": 110282.1070774315 }, { "content": "fn white(i: &str) -> IResult<&str, &str> {\n\n take_while(move |c| WHITESPACE.contains(c))(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 15, "score": 110282.1070774315 }, { "content": "fn b64(i: &str) -> IResult<&str, &str> {\n\n recognize(tuple((take_while(move |c| B64_CHARS.contains(c)), opt(tag(\"=\")), opt(tag(\"=\")))))(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 16, "score": 110282.1070774315 }, { "content": "fn identifier(i: &str) -> IResult<&str, &str> {\n\n is_not(\" \\\\$,=\\\"'()#\\n\")(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 17, "score": 110282.1070774315 }, { "content": "fn parse(buffer: &[u8]) -> Result<Field> {\n\n let string = from_utf8(&buffer).context(\"input is not utf-8\")?;\n\n parser::parse(string)\n\n}\n", "file_path": "nachricht-nq/src/main.rs", "rank": 18, "score": 110192.02160660617 }, { "content": "fn keyword(i: &str) -> IResult<&str, Keyword> {\n\n alt((\n\n map(tag(\"null\"), |_| Keyword::Null),\n\n map(tag(\"true\"), |_| Keyword::True),\n\n map(tag(\"false\"),|_| Keyword::False)\n\n ))(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 19, "score": 103386.72358422933 }, { "content": "fn field(i: &str) -> IResult<&str, Field> {\n\n alt((\n\n map(tuple((white, key, white, nch_value, white)), |(_,k,_,v,_)| Field { name: Some(Cow::Owned(k)), value: v }),\n\n map(nch_value, |v| Field { name: None, value: v }),\n\n ))(i)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\n\n use ::nachricht::*;\n\n use std::borrow::Cow;\n\n\n\n #[test]\n\n fn primitives() {\n\n assert_eq!(super::parse(\"null\").unwrap(), Field { name: None, value: Value::Null });\n\n assert_eq!(super::parse(\"true\").unwrap(), Field { name: None, value: Value::Bool(true) });\n\n assert_eq!(super::parse(\"false\").unwrap(), Field { name: None, value: Value::Bool(false) });\n\n }\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 20, "score": 103386.72358422933 }, { "content": "fn container(i: &str) -> IResult<&str, Vec<Field>> {\n\n delimited(\n\n tag(\"(\"),\n\n map(tuple((separated_list0(tag(\",\"), field), white, opt(tag(\",\")), white)), |(l,_,_,_)| l),\n\n tag(\")\"),\n\n )(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 21, "score": 99802.52935603783 }, { "content": "fn file_mode(path: PathBuf) -> Result<()> {\n\n let mut buf = Vec::new();\n\n File::open(&path)?.read_to_end(&mut buf)?;\n\n let field = Decoder::decode(&buf)?.0;\n\n let edited = edit::edit(format!(\"{}\", &field))?;\n\n let parsed = parser::parse(&edited)?;\n\n Encoder::encode(&parsed, &mut File::create(&path)?)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "nachricht-nq/src/main.rs", "rank": 22, "score": 93412.16303438481 }, { "content": "fn main() -> Result<()> {\n\n let msg = Message {\n\n version: 1,\n\n cats: vec![\n\n Cat { name: \"Jessica\", species: Species::PrionailurusViverrinus },\n\n Cat { name: \"Wantan\", species: Species::LynxLynx },\n\n Cat { name: \"Sphinx\", species: Species::FelisCatus },\n\n Cat { name: \"Chandra\", species: Species::PrionailurusViverrinus },\n\n ],\n\n };\n\n\n\n let bytes = nachricht_serde::to_bytes(&msg).context(\"Failed to serialize cats\")?;\n\n std::io::stdout().write_all(&bytes).context(\"Failed to write bytes\")?;\n\n Ok(())\n\n}\n", "file_path": "example/src/main.rs", "rank": 23, "score": 84651.67672735015 }, { "content": "fn main() -> Result<()> {\n\n let opt = Opt::from_args();\n\n match opt.file {\n\n Some(path) => file_mode(path),\n\n None => streaming_mode(opt),\n\n }\n\n}\n\n\n", "file_path": "nachricht-nq/src/main.rs", "rank": 24, "score": 82545.61215363693 }, { "content": "fn streaming_mode(opt: Opt) -> Result<()> {\n\n let mut buffer = Vec::new();\n\n io::stdin().read_to_end(&mut buffer).context(\"Failed to read stdin\")?;\n\n let field = if opt.text {\n\n parse(&buffer)?\n\n } else {\n\n Decoder::decode(&buffer)?.0\n\n };\n\n if opt.encode {\n\n Encoder::encode(&field, &mut io::stdout())?;\n\n } else {\n\n println!(\"{}\", &field);\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "nachricht-nq/src/main.rs", "rank": 25, "score": 72689.80471942973 }, { "content": "struct MapKey<'de> {\n\n key: &'de str,\n\n}\n\n\n\nimpl<'de> de::Deserializer<'de> for MapKey<'de> {\n\n type Error = Error;\n\n\n\n fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n visitor.visit_borrowed_str(self.key)\n\n }\n\n\n\n fn deserialize_bool<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n match self.key {\n\n \"true\" => visitor.visit_bool(true),\n\n \"false\" => visitor.visit_bool(false),\n\n _ => Err(Error::Key(self.key.into(), type_name::<bool>())),\n\n }\n\n }\n\n\n\n fn deserialize_i8<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n", "file_path": "nachricht-serde/src/de.rs", "rank": 26, "score": 68787.85455061728 }, { "content": "struct StructDeserializer<'a, 'de: 'a> {\n\n de: &'a mut Deserializer<'de>,\n\n remaining: usize,\n\n}\n\n\n\nimpl<'a, 'de> StructDeserializer<'a, 'de> {\n\n fn new(de: &'a mut Deserializer<'de>, remaining: usize) -> Self {\n\n Self { de, remaining }\n\n }\n\n}\n\n\n\nimpl<'de, 'a> MapAccess<'de> for StructDeserializer<'a, 'de> {\n\n type Error = Error;\n\n\n\n fn next_key_seed<K: DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>> {\n\n if self.remaining == 0 {\n\n Ok(None)\n\n } else {\n\n self.remaining -= 1;\n\n let header = self.de.decode_header()?;\n", "file_path": "nachricht-serde/src/de.rs", "rank": 27, "score": 49565.78949497383 }, { "content": "#[derive(StructOpt)]\n\n#[structopt(name = \"nq\", author = \"Liv Fischer\")]\n\nstruct Opt {\n\n /// Encode the output into the wire format instead\n\n #[structopt(short, long)]\n\n encode: bool,\n\n\n\n /// Parse the input from the textual representation instead\n\n #[structopt(short, long)]\n\n text: bool,\n\n\n\n /// Open a nachricht encoded file in the standard editor\n\n #[structopt(short, long, parse(from_os_str))]\n\n file: Option<PathBuf>,\n\n}\n\n\n", "file_path": "nachricht-nq/src/main.rs", "rank": 28, "score": 47728.89941184038 }, { "content": "#[derive(Serialize, Deserialize, PartialEq, Debug)]\n\nstruct Message<'a> {\n\n version: u32,\n\n #[serde(borrow)]\n\n cats: Vec<Cat<'a>>,\n\n}\n\n\n", "file_path": "example/src/main.rs", "rank": 29, "score": 47248.82483541284 }, { "content": "struct SeqDeserializer<'a, 'de: 'a> {\n\n de: &'a mut Deserializer<'de>,\n\n remaining: usize,\n\n}\n\n\n\nimpl<'a, 'de> SeqDeserializer<'a, 'de> {\n\n fn new(de: &'a mut Deserializer<'de>, remaining: usize) -> Self {\n\n Self { de, remaining }\n\n }\n\n}\n\n\n\nimpl<'de, 'a> SeqAccess<'de> for SeqDeserializer<'a, 'de> {\n\n type Error = Error;\n\n\n\n fn next_element_seed<T: DeserializeSeed<'de>>(&mut self, seed: T) -> Result<Option<T::Value>> {\n\n if self.remaining == 0 {\n\n Ok(None)\n\n } else {\n\n self.remaining -= 1;\n\n seed.deserialize(&mut *self.de).map(Some)\n\n }\n\n }\n\n\n\n #[inline]\n\n fn size_hint(&self) -> Option<usize> {\n\n Some(self.remaining)\n\n }\n\n\n\n}\n\n\n", "file_path": "nachricht-serde/src/de.rs", "rank": 30, "score": 41350.78852057271 }, { "content": "struct EnumDeserializer<'a, 'de: 'a> {\n\n de: &'a mut Deserializer<'de>,\n\n}\n\n\n\nimpl<'a, 'de> EnumDeserializer<'a, 'de> {\n\n fn new(de: &'a mut Deserializer<'de>) -> Self {\n\n Self { de }\n\n }\n\n}\n\n\n\nimpl<'de, 'a> EnumAccess<'de> for EnumDeserializer<'a, 'de> {\n\n type Error = Error;\n\n type Variant = Self;\n\n\n\n fn variant_seed<V: DeserializeSeed<'de>>(self, seed: V) -> Result<(V::Value, Self::Variant)> {\n\n let variant = seed.deserialize(&mut *self.de)?;\n\n Ok((variant, self))\n\n }\n\n}\n\n\n", "file_path": "nachricht-serde/src/de.rs", "rank": 31, "score": 41350.78852057271 }, { "content": "struct MapDeserializer<'a, 'de: 'a> {\n\n de: &'a mut Deserializer<'de>,\n\n remaining: usize,\n\n}\n\n\n\nimpl<'a, 'de> MapDeserializer<'a, 'de> {\n\n fn new(de: &'a mut Deserializer<'de>, remaining: usize) -> Self {\n\n Self { de, remaining }\n\n }\n\n}\n\n\n\nimpl<'de, 'a> MapAccess<'de> for MapDeserializer<'a, 'de> {\n\n type Error = Error;\n\n\n\n fn next_key_seed<K: DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>> {\n\n if self.remaining == 0 {\n\n Ok(None)\n\n } else {\n\n self.remaining -= 1;\n\n let header = self.de.decode_header()?;\n", "file_path": "nachricht-serde/src/de.rs", "rank": 32, "score": 41350.78852057271 }, { "content": " }\n\n}\n\n\n\nimpl Display for DecodeError {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {\n\n match self {\n\n DecodeError::Eof => f.write_str(\"Unexpected end of buffer while decoding\"),\n\n DecodeError::Utf8(e) => write!(f, \"String slice was not valid Utf-8: {}\", e),\n\n DecodeError::DuplicateKey(key) => write!(f, \"Key {} found in value position\", key),\n\n DecodeError::UnknownRef(value) => write!(f, \"Unknown reference {}\", value),\n\n DecodeError::Length(value) => write!(f, \"Length {} exceeds maximum {}\", value, usize::MAX),\n\n DecodeError::Allocation => f.write_str(\"An allocation failed\"),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum EncodeError {\n\n Io(std::io::Error),\n\n Length(usize),\n", "file_path": "nachricht/src/error.rs", "rank": 33, "score": 29058.037971320296 }, { "content": "impl Display for DecoderError {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {\n\n write!(f, \"{} at input position {}\", self.inner, self.at)\n\n }\n\n}\n\n\n\n#[derive(Debug, PartialEq)]\n\npub enum DecodeError {\n\n Eof,\n\n Utf8(std::str::Utf8Error),\n\n DuplicateKey(String),\n\n UnknownRef(usize),\n\n Length(u64),\n\n Allocation,\n\n}\n\n\n\nimpl DecodeError {\n\n pub fn at(self, at: usize) -> DecoderError {\n\n DecoderError { inner: self, at }\n\n }\n", "file_path": "nachricht/src/error.rs", "rank": 34, "score": 29056.854372777365 }, { "content": "}\n\n\n\nimpl From<std::io::Error> for EncodeError {\n\n fn from(e: std::io::Error) -> EncodeError {\n\n EncodeError::Io(e)\n\n }\n\n}\n\n\n\nimpl std::error::Error for EncodeError {\n\n fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n\n match self {\n\n EncodeError::Io(e) => Some(e),\n\n _ => None,\n\n }\n\n }\n\n}\n\n\n\nimpl Display for EncodeError {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {\n\n match self {\n\n EncodeError::Io(e) => write!(f, \"IO error {}\", e),\n\n EncodeError::Length(value) => write!(f, \"Length {} exceeds maximum {}\", value, u64::MAX),\n\n }\n\n }\n\n}\n", "file_path": "nachricht/src/error.rs", "rank": 35, "score": 29054.28477539884 }, { "content": "use std::fmt::{Display, Formatter, self};\n\n\n\n#[derive(Debug, PartialEq)]\n\npub struct DecoderError {\n\n inner: DecodeError,\n\n at: usize,\n\n}\n\n\n\nimpl DecoderError {\n\n pub fn into_inner(self) -> DecodeError {\n\n self.inner\n\n }\n\n}\n\n\n\nimpl std::error::Error for DecoderError {\n\n fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n\n Some(&self.inner)\n\n }\n\n}\n\n\n", "file_path": "nachricht/src/error.rs", "rank": 36, "score": 29047.229179282756 }, { "content": "}\n\n\n\nimpl From<std::str::Utf8Error> for DecodeError {\n\n fn from(e: std::str::Utf8Error) -> DecodeError {\n\n DecodeError::Utf8(e)\n\n }\n\n}\n\n\n\nimpl From<std::collections::TryReserveError> for DecodeError {\n\n fn from(_e: std::collections::TryReserveError) -> DecodeError {\n\n DecodeError::Allocation\n\n }\n\n}\n\n\n\nimpl std::error::Error for DecodeError {\n\n fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n\n match self {\n\n DecodeError::Utf8(e) => Some(e),\n\n _ => None,\n\n }\n", "file_path": "nachricht/src/error.rs", "rank": 37, "score": 29046.26956586766 }, { "content": " #[inline]\n\n fn encode_long_header<W: Write>(&self, i: u64, w: &mut W) -> Result<usize, EncodeError> {\n\n let limit = self.sz_limit();\n\n if i < limit as u64 {\n\n w.write_all(&[self.code() << 5 | i as u8 + (24 - limit)])?;\n\n Ok(1)\n\n } else {\n\n let sz = Self::size(i);\n\n let buf = i.to_be_bytes();\n\n w.write_all(&[self.code() << 5 | (sz + 23)])?;\n\n w.write_all(&buf[buf.len() - sz as usize ..])?;\n\n Ok(1 + sz as usize)\n\n }\n\n }\n\n\n\n #[inline]\n\n fn decode_u64(buf: &[u8], sz: u8) -> Result<(u64, usize), DecodeError> {\n\n if sz < 24 {\n\n Ok((sz as u64, 0))\n\n } else {\n", "file_path": "nachricht/src/header.rs", "rank": 38, "score": 28889.470492256398 }, { "content": " /// define a field and thus has to immediately followed by another header whose field will be\n\n /// named by this key.\n\n Key(usize),\n\n /// A reference into the symbol table. This could resolve to either a symbol (which itself\n\n /// resolve to a string) or a key.\n\n Ref(usize),\n\n}\n\n\n\nimpl Header {\n\n\n\n /// Returns the mnemonic of the header. This is useful for error messages.\n\n pub fn name(&self) -> &'static str {\n\n match *self {\n\n Header::Null => \"Null\",\n\n Header::True => \"True\",\n\n Header::False => \"False\",\n\n Header::F32 => \"F32\",\n\n Header::F64 => \"F64\",\n\n Header::Pos(_) => \"Pos\",\n\n Header::Neg(_) => \"Neg\",\n", "file_path": "nachricht/src/header.rs", "rank": 39, "score": 28887.035562281926 }, { "content": " Header::Bin(_) => \"Bin\",\n\n Header::Bag(_) => \"Bag\",\n\n Header::Str(_) => \"Str\",\n\n Header::Sym(_) => \"Sym\",\n\n Header::Key(_) => \"Key\",\n\n Header::Ref(_) => \"Ref\",\n\n }\n\n }\n\n\n\n /// Returns the number of written bytes\n\n pub fn encode<W: Write>(&self, w: &mut W) -> Result<usize, EncodeError> {\n\n match *self {\n\n Header::Null => { w.write_all(&[self.code() << 5 | 0])?; Ok(1) },\n\n Header::True => { w.write_all(&[self.code() << 5 | 1])?; Ok(1) },\n\n Header::False => { w.write_all(&[self.code() << 5 | 2])?; Ok(1) },\n\n Header::F32 => { w.write_all(&[self.code() << 5 | 3])?; Ok(1) },\n\n Header::F64 => { w.write_all(&[self.code() << 5 | 4])?; Ok(1) },\n\n Header::Pos(i) => self.encode_long_header(i, w),\n\n Header::Neg(0) => { w.write_all(&[1 << 5 | 0])?; Ok(1) },\n\n Header::Neg(i) => self.encode_long_header(i - 1, w),\n", "file_path": "nachricht/src/header.rs", "rank": 40, "score": 28885.54013628649 }, { "content": " Header::Bin(i)\n\n | Header::Bag(i)\n\n | Header::Str(i)\n\n | Header::Sym(i)\n\n | Header::Key(i)\n\n | Header::Ref(i) => self.encode_long_header(Self::to_u64(i)?, w)\n\n }\n\n }\n\n\n\n /// Returns the decoded header and the number of consumed bytes\n\n pub fn decode<B: ?Sized + AsRef<[u8]>>(buf: &B) -> Result<(Self, usize), DecodeError> {\n\n let buf = buf.as_ref();\n\n if buf.len() < 1 {\n\n return Err(DecodeError::Eof);\n\n }\n\n let code = buf[0] >> 5;\n\n let sz = buf[0] & 0x1f;\n\n match code {\n\n 0 => {\n\n match sz {\n", "file_path": "nachricht/src/header.rs", "rank": 41, "score": 28884.887886012675 }, { "content": " let bytes = sz as usize - 23;\n\n if buf.len() < bytes {\n\n Err(DecodeError::Eof)\n\n } else {\n\n let mut tmp = [0u8; 8];\n\n tmp[8 - bytes..].copy_from_slice(&buf[..bytes]);\n\n Ok((<u64>::from_be_bytes(tmp), bytes))\n\n }\n\n }\n\n }\n\n\n\n #[inline]\n\n fn code(&self) -> u8 {\n\n match *self {\n\n Header::Null | Header::True | Header::False | Header::F32 | Header::F64 | Header::Bin(_) => 0,\n\n Header::Pos(_) => 1,\n\n Header::Neg(_) => 2,\n\n Header::Bag(_) => 3,\n\n Header::Str(_) => 4,\n\n Header::Sym(_) => 5,\n", "file_path": "nachricht/src/header.rs", "rank": 42, "score": 28883.691993588025 }, { "content": " 0 => Ok((Header::Null, 1)),\n\n 1 => Ok((Header::True, 1)),\n\n 2 => Ok((Header::False, 1)),\n\n 3 => Ok((Header::F32, 1)),\n\n 4 => Ok((Header::F64, 1)),\n\n x if x < 24 => Ok((Header::Bin(x as usize - 5), 1)),\n\n x => Self::decode_u64(&buf[1..], x).and_then(|(i, c)| Ok((Header::Bin(Self::to_usize(i)?), c + 1))),\n\n }\n\n },\n\n 1 => Self::decode_u64(&buf[1..], sz).map(|(i, c)| (Header::Pos(i), c + 1)),\n\n 2 => Self::decode_u64(&buf[1..], sz).map(|(i, c)| (Header::Neg(i.saturating_add(1)), c + 1)),\n\n 3 => Self::decode_u64(&buf[1..], sz).and_then(|(i, c)| Ok((Header::Bag(Self::to_usize(i)?), c + 1))),\n\n 4 => Self::decode_u64(&buf[1..], sz).and_then(|(i, c)| Ok((Header::Str(Self::to_usize(i)?), c + 1))),\n\n 5 => Self::decode_u64(&buf[1..], sz).and_then(|(i, c)| Ok((Header::Sym(Self::to_usize(i)?), c + 1))),\n\n 6 => Self::decode_u64(&buf[1..], sz).and_then(|(i, c)| Ok((Header::Key(Self::to_usize(i)?), c + 1))),\n\n 7 => Self::decode_u64(&buf[1..], sz).and_then(|(i, c)| Ok((Header::Ref(Self::to_usize(i)?), c + 1))),\n\n _ => unreachable!(),\n\n }\n\n }\n\n\n", "file_path": "nachricht/src/header.rs", "rank": 43, "score": 28881.61404908777 }, { "content": " #[inline]\n\n fn to_u64(value: usize) -> Result<u64, EncodeError> {\n\n u64::try_from(value).map_err(|_| EncodeError::Length(value))\n\n }\n\n\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::Header;\n\n\n\n #[test]\n\n fn lead_bytes() {\n\n let mut src = [0u8; 9];\n\n let mut dst = Vec::with_capacity(9);\n\n for l in 0..u8::MAX {\n\n dst.clear();\n\n src[0] = l;\n\n let decoded = Header::decode(&src).unwrap().0;\n\n let _ = decoded.encode(&mut dst).unwrap();\n", "file_path": "nachricht/src/header.rs", "rank": 44, "score": 28875.46444041413 }, { "content": " let mut buf = Vec::new();\n\n assert_roundtrip(Header::Null, &mut buf);\n\n assert_roundtrip(Header::True, &mut buf);\n\n assert_roundtrip(Header::False, &mut buf);\n\n assert_roundtrip(Header::F32, &mut buf);\n\n assert_roundtrip(Header::F64, &mut buf);\n\n for i in 0..24 {\n\n if i < 19 {\n\n assert_roundtrip(Header::Bin(i), &mut buf);\n\n }\n\n assert_roundtrip(Header::Pos(i as u64), &mut buf);\n\n assert_roundtrip(Header::Neg(if i == 0 { 1 } else { i } as u64), &mut buf);\n\n assert_roundtrip(Header::Bag(i), &mut buf);\n\n assert_roundtrip(Header::Str(i), &mut buf);\n\n assert_roundtrip(Header::Sym(i), &mut buf);\n\n assert_roundtrip(Header::Key(i), &mut buf);\n\n assert_roundtrip(Header::Ref(i), &mut buf);\n\n }\n\n }\n\n\n", "file_path": "nachricht/src/header.rs", "rank": 45, "score": 28873.883186785 }, { "content": " /// The following four bytes contain an IEEE-754 32-bit floating point number\n\n F32,\n\n /// The following eight bytes contain an IEEE-754 64-bit floating point number\n\n F64,\n\n /// The value describes the length of a following byte array.\n\n /// Note that this code also contains the five fixed length values.\n\n Bin(usize),\n\n /// The value describes a postive integer fitting into an u64\n\n Pos(u64),\n\n /// The value describes a negative integer whose negative fits into an u64\n\n Neg(u64),\n\n /// The value describes the length in fields of a container. the fields follow the header\n\n /// immediately.\n\n Bag(usize),\n\n /// The value describes the length in bytes of a following unicode string\n\n Str(usize),\n\n /// A symbol has the same semantics as a string except that it gets pushed into the symbol\n\n /// table and can be referenced from there\n\n Sym(usize),\n\n /// The value describes the length in bytes of a following key value. This in itself does not\n", "file_path": "nachricht/src/header.rs", "rank": 46, "score": 28873.19077204102 }, { "content": " Header::Key(_) => 6,\n\n Header::Ref(_) => 7,\n\n }\n\n }\n\n\n\n #[inline]\n\n fn sz_limit(&self) -> u8 {\n\n match *self {\n\n Header::Bin(_) => 19,\n\n _ => 24,\n\n }\n\n }\n\n\n\n /// Returns the number of bytes needed to encode this value\n\n #[inline]\n\n fn size(value: u64) -> u8 {\n\n if value < 1 << 8 {\n\n 1\n\n } else if value < 1 << 16 {\n\n 2\n", "file_path": "nachricht/src/header.rs", "rank": 47, "score": 28872.589365891472 }, { "content": " #[test]\n\n fn roundtrip_long() {\n\n let mut buf = Vec::new();\n\n // choose large prime number to make this test terminate in acceptable time, in this case\n\n // (2^59-1)/179951\n\n for i in (0..u64::MAX).step_by(3_203_431_780_337) {\n\n assert_roundtrip(Header::Bin(i as usize), &mut buf);\n\n assert_roundtrip(Header::Pos(i), &mut buf);\n\n assert_roundtrip(Header::Neg(if i == 0 { 1 } else { i } as u64), &mut buf);\n\n assert_roundtrip(Header::Bag(i as usize), &mut buf);\n\n assert_roundtrip(Header::Str(i as usize), &mut buf);\n\n assert_roundtrip(Header::Sym(i as usize), &mut buf);\n\n assert_roundtrip(Header::Key(i as usize), &mut buf);\n\n assert_roundtrip(Header::Ref(i as usize), &mut buf);\n\n }\n\n }\n\n\n\n #[test]\n\n fn inefficient_encoding() {\n\n let buf = [0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02];\n", "file_path": "nachricht/src/header.rs", "rank": 48, "score": 28871.612110549395 }, { "content": "//! A `Nachricht` header is defined by a code and a value. The first three bits of the first byte\n\n//! define a code, while the latter five bits yield an unsigned integer, consistently named `sz`\n\n//! for size. If this integer is less than 24, its value is the value of the header. Otherwise the\n\n//! following `sz - 23` bytes (up to eight, since `sz::MAX` is `2^5-1`) contain an unsigned integer\n\n//! in network byte order which defines the value of the header. The interpretation of the value\n\n//! depends on the code: it can either define the value of the whole field or the length of the\n\n//! field's content.\n\n\n\nuse crate::error::{DecodeError, EncodeError};\n\nuse std::convert::TryFrom;\n\nuse std::io::Write;\n\n\n\n#[derive(Debug, PartialEq, Clone, Copy)]\n\npub enum Header {\n\n /// Also known as unit or nil\n\n Null,\n\n /// The boolean value true\n\n True,\n\n /// The boolean value false\n\n False,\n", "file_path": "nachricht/src/header.rs", "rank": 49, "score": 28870.28878788865 }, { "content": " assert_eq!(Header::Bag(2), Header::decode(&buf).unwrap().0);\n\n }\n\n\n\n fn assert_roundtrip(value: Header, buf: &mut Vec<u8>) {\n\n let _ = value.encode(buf);\n\n assert_eq!(value, Header::decode(buf).unwrap().0);\n\n buf.clear();\n\n }\n\n\n\n}\n", "file_path": "nachricht/src/header.rs", "rank": 50, "score": 28867.75761744717 }, { "content": " } else if value < 1 << 24 {\n\n 3\n\n } else if value < 1 << 32 {\n\n 4\n\n } else if value < 1 << 40 {\n\n 5\n\n } else if value < 1 << 48 {\n\n 6\n\n } else if value < 1 << 56 {\n\n 7\n\n } else {\n\n 8\n\n }\n\n }\n\n\n\n #[inline]\n\n fn to_usize(value: u64) -> Result<usize, DecodeError> {\n\n usize::try_from(value).map_err(|_| DecodeError::Length(value))\n\n }\n\n\n", "file_path": "nachricht/src/header.rs", "rank": 51, "score": 28867.708992536453 }, { "content": " }\n\n }\n\n\n\n #[test]\n\n fn negative_zero() {\n\n let mut buf = Vec::new();\n\n let _ = Header::Neg(0).encode(&mut buf);\n\n assert_eq!(Header::Pos(0), Header::decode(&buf).unwrap().0);\n\n }\n\n\n\n #[test]\n\n fn negative_max() {\n\n let buf = [0x5f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];\n\n assert_eq!(Header::Neg(u64::MAX), Header::decode(&buf).unwrap().0);\n\n let buf = [0x5f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe];\n\n assert_eq!(Header::Neg(u64::MAX), Header::decode(&buf).unwrap().0);\n\n }\n\n\n\n #[test]\n\n fn roundtrip_compact() {\n", "file_path": "nachricht/src/header.rs", "rank": 52, "score": 28864.541201056123 }, { "content": "impl Display for DeserializationError {\n\n fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {\n\n write!(fmt, \"{} at input position {}\", self.inner, self.at)\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum Error {\n\n // Decode\n\n Decode(DecodeError),\n\n Trailing,\n\n UnexpectedHeader(&'static [&'static str], &'static str),\n\n UnexpectedRefable(&'static str, &'static str),\n\n Int,\n\n Utf8(Utf8Error),\n\n Key(String, &'static str),\n\n // Encode\n\n Length,\n\n Encode(EncodeError),\n\n KeyType,\n", "file_path": "nachricht-serde/src/error.rs", "rank": 53, "score": 27780.822318502975 }, { "content": "}\n\n\n\nimpl Display for Error {\n\n fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {\n\n match self {\n\n Error::Message(msg) => fmt.write_str(msg),\n\n Error::Encode(e) => write!(fmt, \"Encoding error: {}\", e.to_string()),\n\n Error::Decode(e) => write!(fmt, \"Decoding error: {}\", e.to_string()),\n\n Error::KeyType => write!(fmt, \"Map key must be convertible to a string. Maybe use crate `serde_with` to transform the map into a vec of tuples\"),\n\n Error::Length => fmt.write_str(\"Length required\"),\n\n Error::Trailing => fmt.write_str(\"Trailing characters in input\"),\n\n Error::UnexpectedHeader(expected, actual) => write!(fmt, \"Unexpected header: expected one of ({}), found {}\", expected.join(\", \"), actual),\n\n Error::UnexpectedRefable(expected, actual) => write!(fmt, \"Unexpected refable: expected {}, found {}\", expected, actual),\n\n Error::Utf8(e) => write!(fmt, \"Bytes aren't valid Utf-8: {}\", e.to_string()),\n\n Error::Key(k, t) => write!(fmt, \"Key `{}` could not be parsed as {}\", k, t),\n\n Error::Int => fmt.write_str(\"Integer didn't fit into target type\"),\n\n }\n\n }\n\n}\n\n\n", "file_path": "nachricht-serde/src/error.rs", "rank": 54, "score": 27777.235795744728 }, { "content": "use std;\n\nuse std::fmt::{self, Display};\n\nuse std::str::Utf8Error;\n\nuse serde::{de, ser};\n\nuse nachricht::{EncodeError, DecodeError};\n\n\n\npub type Result<T> = std::result::Result<T, Error>;\n\n\n\n#[derive(Debug)]\n\npub struct DeserializationError {\n\n inner: Error,\n\n at: usize,\n\n}\n\n\n\nimpl std::error::Error for DeserializationError {\n\n fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n\n Some(&self.inner)\n\n }\n\n}\n\n\n", "file_path": "nachricht-serde/src/error.rs", "rank": 55, "score": 27771.315688745224 }, { "content": " // Both\n\n Message(String),\n\n}\n\n\n\nimpl Error {\n\n pub fn at(self, at: usize) -> DeserializationError {\n\n DeserializationError { inner: self, at }\n\n }\n\n}\n\n\n\nimpl ser::Error for Error {\n\n fn custom<T: Display>(msg: T) -> Self {\n\n Error::Message(msg.to_string())\n\n }\n\n}\n\n\n\nimpl de::Error for Error {\n\n fn custom<T: Display>(msg: T) -> Self {\n\n Error::Message(msg.to_string())\n\n }\n", "file_path": "nachricht-serde/src/error.rs", "rank": 56, "score": 27768.372081096386 }, { "content": "impl From<EncodeError> for Error {\n\n fn from(e: EncodeError) -> Error {\n\n Error::Encode(e)\n\n }\n\n}\n\n\n\nimpl From<DecodeError> for Error {\n\n fn from(e: DecodeError) -> Error {\n\n Error::Decode(e)\n\n }\n\n}\n\n\n\nimpl From<std::num::TryFromIntError> for Error {\n\n fn from(_e: std::num::TryFromIntError) -> Error {\n\n Error::Int\n\n }\n\n}\n\n\n\nimpl From<std::str::Utf8Error> for Error {\n\n fn from(e: std::str::Utf8Error) -> Error {\n\n Error::Utf8(e)\n\n }\n\n}\n\n\n\nimpl std::error::Error for Error {}\n", "file_path": "nachricht-serde/src/error.rs", "rank": 57, "score": 27760.541980639293 }, { "content": "}\n\n\n\nimpl<'w, W: Write> Encoder<'w, W> {\n\n\n\n /// Encode a field to the given writer. The resulting `usize` is the amount of bytes that got written.\n\n pub fn encode(field: &Field, writer: &'w mut W) -> Result<usize, EncodeError> {\n\n Self { writer, symbols: Vec::new() }.encode_inner(field)\n\n }\n\n\n\n fn encode_inner(&mut self, field: &Field) -> Result<usize, EncodeError> {\n\n let mut c = 0;\n\n if let Some(ref name) = field.name {\n\n c += self.encode_refable(name.as_ref(), Refable::Key)?;\n\n }\n\n match &field.value {\n\n Value::Null => Header::Null.encode(self.writer),\n\n Value::Bool(v) => match v { true => Header::True, false => Header::False }.encode(self.writer),\n\n Value::F32(v) => {\n\n c += Header::F32.encode(self.writer)?;\n\n self.writer.write_all(&v.to_be_bytes())?;\n", "file_path": "nachricht/src/field.rs", "rank": 61, "score": 43.51024531074012 }, { "content": " c += Header::Bag(inner.len()).encode(self.writer)?;\n\n for field in inner.iter() {\n\n c += self.encode_inner(field)?;\n\n }\n\n Ok(c)\n\n },\n\n }\n\n }\n\n\n\n fn encode_refable<'a>(&mut self, key: &'a str, kind: Refable) -> Result<usize, EncodeError> {\n\n match self.symbols.iter().enumerate().find(|(_, (k, v))| *k == kind && v == key) {\n\n Some((i, _)) => Header::Ref(i).encode(self.writer),\n\n None => {\n\n self.symbols.push((kind, key.to_owned()));\n\n match kind { Refable::Key => Header::Key(key.len()), Refable::Sym => Header::Sym(key.len()) }.encode(self.writer)?;\n\n self.writer.write_all(key.as_bytes())?;\n\n Ok(1 + key.len())\n\n }\n\n }\n\n }\n", "file_path": "nachricht/src/field.rs", "rank": 66, "score": 39.888981827842656 }, { "content": "#[repr(u8)]\n\npub enum Refable {\n\n Sym,\n\n Key,\n\n}\n\n\n\nimpl Refable {\n\n pub fn name(&self) -> &'static str {\n\n match *self {\n\n Refable::Sym => \"Sym\",\n\n Refable::Key => \"Key\",\n\n }\n\n }\n\n}\n\n\n\n/// Used to encode `nachricht` fields. This uses an internal symbol table to allow referencing keys and symbols which\n\n/// get repeated.\n\npub struct Encoder<'w, W: Write> {\n\n writer: &'w mut W,\n\n symbols: Vec<(Refable, String)>,\n", "file_path": "nachricht/src/field.rs", "rank": 68, "score": 38.41197560961709 }, { "content": " visitor.visit_u16(self.key.parse().map_err(|_| Error::Key(self.key.into(), type_name::<u16>()))?)\n\n }\n\n\n\n fn deserialize_u32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n visitor.visit_u32(self.key.parse().map_err(|_| Error::Key(self.key.into(), type_name::<u32>()))?)\n\n }\n\n\n\n fn deserialize_u64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n visitor.visit_u64(self.key.parse().map_err(|_| Error::Key(self.key.into(), type_name::<u64>()))?)\n\n }\n\n\n\n fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n visitor.visit_some(self)\n\n }\n\n\n\n fn deserialize_newtype_struct<V: Visitor<'de>>(self, _name: &'static str, visitor: V) -> Result<V::Value> {\n\n visitor.visit_newtype_struct(self)\n\n }\n\n\n\n fn deserialize_enum<V: Visitor<'de>>(self, _name: &'static str, _variants: &'static [&'static str], visitor: V) -> Result<V::Value> {\n\n visitor.visit_enum(self.key.into_deserializer())\n\n }\n\n\n\n forward_to_deserialize_any! {\n\n f32 f64 char str string unit unit_struct seq tuple tuple_struct map struct identifier ignored_any bytes byte_buf\n\n }\n\n\n\n}\n", "file_path": "nachricht-serde/src/de.rs", "rank": 71, "score": 37.029956033821 }, { "content": " Ok(c + size_of::<f32>())\n\n },\n\n Value::F64(v) => {\n\n c += Header::F64.encode(self.writer)?;\n\n self.writer.write_all(&v.to_be_bytes())?;\n\n Ok(c + size_of::<f64>())\n\n },\n\n Value::Bytes(v) => {\n\n c += Header::Bin(v.len()).encode(self.writer)?;\n\n self.writer.write_all(v)?;\n\n Ok(c + v.len())\n\n },\n\n Value::Int(s, v) => { match s { Sign::Pos => Header::Pos(*v), Sign::Neg => Header::Neg(*v) }.encode(self.writer) },\n\n Value::Str(v) => {\n\n c += Header::Str(v.len()).encode(self.writer)?;\n\n self.writer.write_all(v.as_bytes())?;\n\n Ok(c + v.len())\n\n },\n\n Value::Symbol(v) => self.encode_refable(v, Refable::Sym),\n\n Value::Container(inner) => {\n", "file_path": "nachricht/src/field.rs", "rank": 72, "score": 36.643707604521104 }, { "content": "/// The possible values according to the `nachricht` data model.\n\n#[derive(Debug, PartialEq, Clone)]\n\npub enum Value<'a> {\n\n Null,\n\n Bool(bool),\n\n F32(f32),\n\n F64(f64),\n\n Bytes(Cow<'a, [u8]>),\n\n Int(Sign, u64),\n\n Str(Cow<'a, str>),\n\n Symbol(Cow<'a, str>),\n\n Container(Vec<Field<'a>>),\n\n}\n\n\n\nimpl<'a> Value<'a> {\n\n\n\n fn b64(input: &[u8]) -> String {\n\n const CHAR_SET: &'static [char] = &['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',\n\n 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',\n\n 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n", "file_path": "nachricht/src/field.rs", "rank": 76, "score": 34.33896361666422 }, { "content": " match self.decode_header()? {\n\n Header::F32 => visitor.visit_f32(<f32>::from_be_bytes(self.decode_slice(4)?.try_into().unwrap())),\n\n o => Err(Error::UnexpectedHeader(&[\"F32\"], o.name())),\n\n }\n\n }\n\n\n\n fn deserialize_f64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n match self.decode_header()? {\n\n Header::F64 => visitor.visit_f64(<f64>::from_be_bytes(self.decode_slice(8)?.try_into().unwrap())),\n\n o => Err(Error::UnexpectedHeader(&[\"F64\"], o.name())),\n\n }\n\n }\n\n\n\n fn deserialize_char<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n let header = self.decode_header()?;\n\n match self.decode_stringy(header)? {\n\n (v, Refable::Sym) => {\n\n let mut chars = v.chars();\n\n let c = chars.next().ok_or(Error::Decode(DecodeError::Eof))?;\n\n match chars.next() {\n", "file_path": "nachricht-serde/src/de.rs", "rank": 82, "score": 31.69230817826395 }, { "content": "\n\n}\n\n/// Used to decode `nachricht` fields. This uses an internal symbol table to allow the decoding of encountered\n\n/// references.\n\npub struct Decoder<'a> {\n\n symbols: Vec<(Refable, &'a str)>,\n\n buf: &'a [u8],\n\n pos: usize,\n\n}\n\n\n\nimpl<'a> Decoder<'a> {\n\n\n\n /// Decode a single field from the given buffer. All strings, keys, symbols and byte data will be borrowed from the\n\n /// buffer instead of copied. This means that the decoded field may only live as long as the buffer does. However,\n\n /// some allocations still occur: containers need their own heap space.\n\n pub fn decode<B: ?Sized + AsRef<[u8]>>(buf: &'a B) -> Result<(Field<'a>, usize), DecoderError> {\n\n let mut decoder = Self { buf: buf.as_ref(), symbols: Vec::new(), pos: 0 };\n\n let field = decoder.decode_field().map_err(|e| e.at(decoder.pos))?;\n\n Ok((field, decoder.pos))\n\n }\n", "file_path": "nachricht/src/field.rs", "rank": 83, "score": 31.35499797977581 }, { "content": "impl<'de, 'a> VariantAccess<'de> for EnumDeserializer<'a, 'de> {\n\n type Error = Error;\n\n\n\n fn unit_variant(self) -> Result<()> {\n\n match self.de.decode_header()? {\n\n Header::Null => Ok(()),\n\n o => Err(Error::UnexpectedHeader(&[\"Null\"], o.name())),\n\n }\n\n }\n\n\n\n fn newtype_variant_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Value> {\n\n seed.deserialize(self.de)\n\n }\n\n\n\n fn tuple_variant<V: Visitor<'de>>(self, _len: usize, visitor: V) -> Result<V::Value> {\n\n de::Deserializer::deserialize_seq(self.de, visitor)\n\n }\n\n\n\n fn struct_variant<V: Visitor<'de>>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value> {\n\n de::Deserializer::deserialize_struct(self.de, \"\", fields, visitor)\n\n }\n\n\n\n}\n\n\n", "file_path": "nachricht-serde/src/de.rs", "rank": 84, "score": 31.242988109449193 }, { "content": " }\n\n\n\n}\n\n\n\nimpl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {\n\n type Error = Error;\n\n\n\n fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n let header = self.decode_header()?;\n\n match header {\n\n Header::Null => visitor.visit_unit(),\n\n Header::True => visitor.visit_bool(true),\n\n Header::False => visitor.visit_bool(false),\n\n Header::F32 => visitor.visit_f32(<f32>::from_be_bytes(self.decode_slice(4)?.try_into().unwrap())),\n\n Header::F64 => visitor.visit_f64(<f64>::from_be_bytes(self.decode_slice(8)?.try_into().unwrap())),\n\n Header::Bin(v) => visitor.visit_borrowed_bytes(self.decode_slice(v)?),\n\n Header::Pos(v) => visitor.visit_u64(v),\n\n Header::Neg(v) => visitor.visit_i64(-(v as i128).try_into()?),\n\n Header::Str(v) => visitor.visit_borrowed_str(std::str::from_utf8(self.decode_slice(v)?)?),\n\n Header::Sym(v) => {\n", "file_path": "nachricht-serde/src/de.rs", "rank": 85, "score": 31.00203433025003 }, { "content": " match self.decode_header()? {\n\n Header::True => visitor.visit_bool(true),\n\n Header::False => visitor.visit_bool(false),\n\n o => Err(Error::UnexpectedHeader(&[\"True\", \"False\"], o.name())),\n\n }\n\n }\n\n\n\n fn deserialize_i8<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n visitor.visit_i8(self.decode_int()?.try_into()?)\n\n }\n\n\n\n fn deserialize_i16<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n visitor.visit_i16(self.decode_int()?.try_into()?)\n\n }\n\n\n\n fn deserialize_i32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n visitor.visit_i32(self.decode_int()?.try_into()?)\n\n }\n\n\n\n fn deserialize_i64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n", "file_path": "nachricht-serde/src/de.rs", "rank": 86, "score": 30.418376605629668 }, { "content": "\n\n fn decode_field(&mut self) -> Result<Field<'a>, DecodeError> {\n\n let (header, c) = Header::decode(&self.buf[self.pos..])?;\n\n self.pos += c;\n\n match header {\n\n Header::Key(v) => {\n\n let key = from_utf8(&self.decode_slice(v)?)?;\n\n self.symbols.push((Refable::Key, key));\n\n Ok(Field { name: Some(Cow::Borrowed(key)), value: self.decode_value()? })\n\n },\n\n Header::Ref(v) => {\n\n match self.symbols.get(v) {\n\n Some((Refable::Sym, _)) => Ok(Field { name: None, value: self.decode_value_inner(header)? }),\n\n Some((Refable::Key, key)) => Ok(Field { name: Some(Cow::Borrowed(key)), value: self.decode_value()? }),\n\n _ => Err(DecodeError::UnknownRef(v)),\n\n }\n\n },\n\n _ => Ok(Field { name: None, value: self.decode_value_inner(header)? }),\n\n }\n\n }\n", "file_path": "nachricht/src/field.rs", "rank": 87, "score": 30.101528482527343 }, { "content": " visitor.visit_i8(self.key.parse().map_err(|_| Error::Key(self.key.into(), type_name::<i8>()))?)\n\n }\n\n\n\n fn deserialize_i16<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n visitor.visit_i16(self.key.parse().map_err(|_| Error::Key(self.key.into(), type_name::<i16>()))?)\n\n }\n\n\n\n fn deserialize_i32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n visitor.visit_i32(self.key.parse().map_err(|_| Error::Key(self.key.into(), type_name::<i32>()))?)\n\n }\n\n\n\n fn deserialize_i64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n visitor.visit_i64(self.key.parse().map_err(|_| Error::Key(self.key.into(), type_name::<i64>()))?)\n\n }\n\n\n\n fn deserialize_u8<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n visitor.visit_u8(self.key.parse().map_err(|_| Error::Key(self.key.into(), type_name::<u8>()))?)\n\n }\n\n\n\n fn deserialize_u16<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n", "file_path": "nachricht-serde/src/de.rs", "rank": 88, "score": 29.966629774066224 }, { "content": "\n\n fn decode_value(&mut self) -> Result<Value<'a>, DecodeError> {\n\n let (header, c) = Header::decode(&self.buf[self.pos..])?;\n\n self.pos += c;\n\n self.decode_value_inner(header)\n\n }\n\n\n\n fn decode_value_inner(&mut self, header: Header) -> Result<Value<'a>, DecodeError> {\n\n match header {\n\n Header::Null => Ok(Value::Null),\n\n Header::True => Ok(Value::Bool(true)),\n\n Header::False => Ok(Value::Bool(false)),\n\n Header::F32 => Ok(Value::F32(<f32>::from_be_bytes(self.decode_slice(4)?.try_into().unwrap()))),\n\n Header::F64 => Ok(Value::F64(<f64>::from_be_bytes(self.decode_slice(8)?.try_into().unwrap()))),\n\n Header::Bin(v) => Ok(Value::Bytes(Cow::Borrowed(self.decode_slice(v)?))),\n\n Header::Pos(v) => Ok(Value::Int(Sign::Pos, v)),\n\n Header::Neg(v) => Ok(Value::Int(Sign::Neg, v)),\n\n Header::Bag(v) => {\n\n let mut fields = Vec::with_capacity(0);\n\n fields.try_reserve(v)?;\n", "file_path": "nachricht/src/field.rs", "rank": 89, "score": 29.81996102647461 }, { "content": " fn deserialize_unit_struct<V: Visitor<'de>>(self, _name: &'static str, visitor: V) -> Result<V::Value> {\n\n self.deserialize_unit(visitor)\n\n }\n\n\n\n fn deserialize_newtype_struct<V: Visitor<'de>>(self, _name: &'static str, visitor: V) -> Result<V::Value> {\n\n visitor.visit_newtype_struct(self)\n\n }\n\n\n\n fn deserialize_seq<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value> {\n\n match self.decode_header()? {\n\n Header::Bag(v) => visitor.visit_seq(SeqDeserializer::new(&mut self, v)),\n\n o => Err(Error::UnexpectedHeader(&[\"Bag\"], o.name())),\n\n }\n\n }\n\n\n\n fn deserialize_tuple<V: Visitor<'de>>(self, _len: usize, visitor: V) -> Result<V::Value> {\n\n self.deserialize_seq(visitor)\n\n }\n\n\n\n fn deserialize_tuple_struct<V: Visitor<'de>>(self, _name: &'static str, _len: usize, visitor: V) -> Result<V::Value> {\n", "file_path": "nachricht-serde/src/de.rs", "rank": 90, "score": 29.72667362281837 }, { "content": " for _ in 0..v {\n\n fields.push(self.decode_field()?);\n\n }\n\n Ok(Value::Container(fields))\n\n },\n\n Header::Str(v) => Ok(Value::Str(Cow::Borrowed(from_utf8(&self.decode_slice(v)?)?))),\n\n Header::Sym(v) => {\n\n let symbol = from_utf8(&self.decode_slice(v)?)?;\n\n self.symbols.push((Refable::Sym, symbol));\n\n Ok(Value::Symbol(Cow::Borrowed(symbol)))\n\n },\n\n Header::Key(v) => {\n\n let key = from_utf8(&self.decode_slice(v)?)?;\n\n Err(DecodeError::DuplicateKey(key.to_string()))\n\n },\n\n Header::Ref(v) => {\n\n match self.symbols.get(v) {\n\n Some((Refable::Sym, symbol)) => Ok(Value::Symbol(Cow::Borrowed(symbol))),\n\n Some((Refable::Key, key)) => Err(DecodeError::DuplicateKey(key.to_string())),\n\n None => Err(DecodeError::UnknownRef(v))\n", "file_path": "nachricht/src/field.rs", "rank": 92, "score": 29.22636075925184 }, { "content": " self.deserialize_seq(visitor)\n\n }\n\n\n\n fn deserialize_map<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value> {\n\n match self.decode_header()? {\n\n Header::Bag(v) => visitor.visit_map(MapDeserializer::new(&mut self, v)),\n\n o => Err(Error::UnexpectedHeader(&[\"Bag\"], o.name())),\n\n }\n\n }\n\n\n\n fn deserialize_struct<V: Visitor<'de>>(mut self, _name: &'static str, _fields: &'static [&'static str], visitor: V) -> Result<V::Value> {\n\n match self.decode_header()? {\n\n Header::Bag(v) => visitor.visit_map(StructDeserializer::new(&mut self, v)),\n\n o => Err(Error::UnexpectedHeader(&[\"Bag\"], o.name())),\n\n }\n\n }\n\n\n\n fn deserialize_enum<V: Visitor<'de>>(self, _name: &'static str, _variants: &'static [&'static str], visitor: V) -> Result<V::Value> {\n\n match self.decode_header()? {\n\n Header::Bag(1) => visitor.visit_enum(EnumDeserializer::new(&mut *self)),\n", "file_path": "nachricht-serde/src/de.rs", "rank": 93, "score": 29.138369302299512 }, { "content": " match self {\n\n Value::Null => f.write_str(\"null\"),\n\n Value::Bool(true) => f.write_str(\"true\"),\n\n Value::Bool(false) => f.write_str(\"false\"),\n\n Value::F32(v) => write!(f, \"${}\", v),\n\n Value::F64(v) => write!(f, \"$${}\", v),\n\n Value::Bytes(v) => write!(f, \"'{}'\", Self::b64(v).as_str()),\n\n Value::Int(s, v) => write!(f, \"{}{}\", match s { Sign::Pos => \"\", Sign::Neg => \"-\" }, v),\n\n Value::Str(v) => write!(f, \"\\\"{}\\\"\", v.replace(\"\\\\\", \"\\\\\\\\\").replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\n\")),\n\n Value::Symbol(v) if v.chars().any(|c| \"\\n\\\\$ ,=\\\"'()#\".contains(c))\n\n => write!(f, \"#\\\"{}\\\"\", v.replace(\"\\\\\", \"\\\\\\\\\").replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\n\")),\n\n Value::Symbol(v) => write!(f, \"#{}\", v),\n\n Value::Container(v) => write!(f,\"(\\n{}\\n)\", v.iter()\n\n .flat_map(|f| format!(\"{},\", f).lines().map(|line| format!(\" {}\", line)).collect::<Vec<String>>())\n\n .collect::<Vec<String>>().join(\"\\n\")),\n\n }\n\n }\n\n}\n\n\n\n/// When encoding struct-like data structures, `name` should be the identifier of the current field. When encoding\n", "file_path": "nachricht/src/field.rs", "rank": 94, "score": 28.650015207501124 }, { "content": "use serde::{forward_to_deserialize_any, Deserialize};\n\nuse serde::de::{self, DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, VariantAccess, Visitor};\n\nuse nachricht::{DecodeError, Header, Refable};\n\nuse std::convert::TryInto;\n\nuse std::any::type_name;\n\n\n\nuse crate::error::{DeserializationError, Error, Result};\n\n\n\npub struct Deserializer<'de> {\n\n input: &'de [u8],\n\n pos: usize,\n\n symbols: Vec<(Refable, &'de str)>,\n\n}\n\n\n\nimpl<'de> Deserializer<'de> {\n\n pub fn from_bytes(input: &'de [u8]) -> Self {\n\n Deserializer { input, pos: 0, symbols: Vec::new() }\n\n }\n\n}\n\n\n", "file_path": "nachricht-serde/src/de.rs", "rank": 95, "score": 28.458598280164544 }, { "content": " let sym = std::str::from_utf8(self.decode_slice(v)?)?;\n\n self.symbols.push((Refable::Sym, sym));\n\n visitor.visit_borrowed_str(sym)\n\n },\n\n Header::Bag(v) => visitor.visit_seq(SeqDeserializer::new(self, v)),\n\n Header::Key(v) => {\n\n let key = std::str::from_utf8(self.decode_slice(v)?)?;\n\n self.symbols.push((Refable::Key, key));\n\n visitor.visit_borrowed_str(key)\n\n },\n\n Header::Ref(v) => {\n\n match self.symbols.get(v) {\n\n Some((_, v)) => visitor.visit_borrowed_str(v),\n\n None => Err(Error::Decode(DecodeError::UnknownRef(v))),\n\n }\n\n },\n\n }\n\n }\n\n\n\n fn deserialize_bool<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n", "file_path": "nachricht-serde/src/de.rs", "rank": 96, "score": 28.18101165444887 }, { "content": " Some(_) => Err(Error::Trailing),\n\n None => visitor.visit_char(c),\n\n }\n\n },\n\n (_, o) => Err(Error::UnexpectedRefable(Refable::Sym.name(), o.name())),\n\n }\n\n }\n\n\n\n fn deserialize_str<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n let header = self.decode_header()?;\n\n match self.decode_stringy(header)? {\n\n (v, Refable::Sym) => visitor.visit_borrowed_str(v),\n\n (_, o) => Err(Error::UnexpectedRefable(Refable::Sym.name(), o.name())),\n\n }\n\n }\n\n\n\n fn deserialize_string<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {\n\n self.deserialize_str(visitor)\n\n }\n\n\n", "file_path": "nachricht-serde/src/de.rs", "rank": 97, "score": 27.98521941597317 }, { "content": " fn decode_int(&mut self) -> Result<i128> {\n\n let header = self.decode_header()?;\n\n match header {\n\n Header::Pos(v) => Ok(v as i128),\n\n Header::Neg(v) => Ok(-(v as i128)),\n\n o => Err(Error::UnexpectedHeader(&[\"Pos\", \"Neg\"], o.name())),\n\n }\n\n }\n\n\n\n #[inline]\n\n fn decode_slice(&mut self, len: usize) -> Result<&'de [u8]> {\n\n if self.input[self.pos..].len() < len {\n\n Err(Error::Decode(DecodeError::Eof))\n\n } else {\n\n self.pos += len;\n\n Ok(&self.input[self.pos - len..self.pos])\n\n }\n\n }\n\n\n\n fn decode_stringy(&mut self, header: Header) -> Result<(&'de str, Refable)> {\n", "file_path": "nachricht-serde/src/de.rs", "rank": 98, "score": 27.63232850804431 }, { "content": " match self.de.decode_stringy(header)? {\n\n (v, Refable::Key) => seed.deserialize(MapKey { key: v }).map(Some),\n\n (_, o) => Err(Error::UnexpectedRefable(Refable::Key.name(), o.name())),\n\n }\n\n }\n\n }\n\n\n\n fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value> {\n\n seed.deserialize(&mut *self.de)\n\n }\n\n\n\n #[inline]\n\n fn size_hint(&self) -> Option<usize> {\n\n Some(self.remaining >> 1)\n\n }\n\n}\n\n\n", "file_path": "nachricht-serde/src/de.rs", "rank": 99, "score": 27.25898006553064 } ]
Rust
packages/connector/src/cf.rs
hahnlee/canter
274f0ccb55892b6b8387007f0ea24f2187da5648
use core_foundation::base::{ kCFAllocatorDefault, Boolean, CFGetTypeID, CFIndex, CFRange, ToVoid, }; use core_foundation::boolean::{kCFBooleanTrue, CFBooleanGetTypeID, CFBooleanRef}; use core_foundation::data::{ CFDataCreate, CFDataGetBytePtr, CFDataGetLength, CFDataGetTypeID, CFDataRef, }; use core_foundation::dictionary::{ kCFTypeDictionaryKeyCallBacks, kCFTypeDictionaryValueCallBacks, CFDictionaryAddValue, CFDictionaryCreateMutable, CFDictionaryGetCount, CFDictionaryGetKeysAndValues, CFDictionaryGetTypeID, CFDictionaryRef, CFMutableDictionaryRef, }; use core_foundation::number::{ kCFNumberSInt64Type, CFNumber, CFNumberGetType, CFNumberGetTypeID, CFNumberGetValue, CFNumberRef, }; use core_foundation::string::{ kCFStringEncodingUTF8, CFString, CFStringGetBytes, CFStringGetCStringPtr, CFStringGetLength, CFStringGetTypeID, CFStringRef, }; use libc::c_void; use napi::{Env, JsBoolean, JsFunction, JsNumber, JsObject, JsString, JsUnknown, ValueType}; pub fn set_cf_dict( dict_ref: CFMutableDictionaryRef, key: *const c_void, unknown: JsUnknown, env: &Env, ) { let object_type = unknown.get_type().unwrap(); if object_type == ValueType::String { let cf_string = CFString::new( unknown .coerce_to_string() .unwrap() .into_utf8() .unwrap() .as_str() .unwrap(), ); unsafe { CFDictionaryAddValue(dict_ref, key, cf_string.to_void()); } return; }; if object_type == ValueType::Object { if unknown.is_typedarray().unwrap() { let object = unknown.coerce_to_object().unwrap(); let properties = object.get_property_names().unwrap(); let length = properties.get_array_length_unchecked().unwrap(); let mut data: Vec<u8> = vec![]; for i in 0..length { let elem_value = object.get_element::<JsNumber>(i).unwrap(); let value = (elem_value.get_uint32().unwrap() & 0xff) as u8; data.push(value); } let cf_data = unsafe { CFDataCreate(kCFAllocatorDefault, data.as_mut_ptr(), data.len() as isize) }; unsafe { CFDictionaryAddValue(dict_ref, key, cf_data.to_void()); } return; } let new_dict_ref = unsafe { CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks, ) }; let object = unknown.coerce_to_object().unwrap(); let properties = object.get_property_names().unwrap(); let length = properties.get_array_length_unchecked().unwrap(); for i in 0..length { let elem_key = properties.get_element::<JsString>(i).unwrap(); let value = object .get_property::<JsString, JsUnknown>(elem_key) .unwrap(); let ns_key = CFString::new(elem_key.into_utf8().unwrap().as_str().unwrap()); set_cf_dict(new_dict_ref, ns_key.to_void(), value, env); } unsafe { CFDictionaryAddValue(dict_ref, key, new_dict_ref as *const c_void); } return; } if object_type == ValueType::Number { let value = unknown.coerce_to_number().unwrap(); let cf_number = to_cf_number(value, env); unsafe { CFDictionaryAddValue(dict_ref, key, cf_number.to_void()); } } } fn to_cf_number(value: JsNumber, env: &Env) -> CFNumber { let number_object = env .get_global() .unwrap() .get_property::<JsString, JsFunction>(env.create_string("Number").unwrap()) .unwrap() .coerce_to_object() .unwrap(); let is_integer_fn = number_object .get_property::<JsString, JsFunction>(env.create_string("isInteger").unwrap()) .unwrap(); let is_integer = unsafe { is_integer_fn .call(None, &[value]) .unwrap() .cast::<JsBoolean>() .get_value() .unwrap() }; if is_integer { CFNumber::from(value.get_int32().unwrap()) } else { CFNumber::from(value.get_double().unwrap()) } } pub fn to_cf_dictionary(object: JsObject, env: &Env) -> CFMutableDictionaryRef { let properties = object.get_property_names().unwrap(); let length = properties.get_array_length_unchecked().unwrap(); let dict_ref = unsafe { CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks, ) }; for i in 0..length { let key = properties.get_element::<JsString>(i).unwrap(); let value = object.get_property::<JsString, JsUnknown>(key).unwrap(); let ns_key = CFString::new(key.into_utf8().unwrap().as_str().unwrap()); set_cf_dict(dict_ref, ns_key.to_void(), value, env); } dict_ref } fn to_string(string_ref: CFStringRef) -> String { unsafe { let char_ptr = CFStringGetCStringPtr(string_ref, kCFStringEncodingUTF8); if !char_ptr.is_null() { let c_str = std::ffi::CStr::from_ptr(char_ptr); return String::from(c_str.to_str().unwrap()); } let char_len = CFStringGetLength(string_ref); let mut bytes_required: CFIndex = 0; CFStringGetBytes( string_ref, CFRange { location: 0, length: char_len, }, kCFStringEncodingUTF8, 0, false as Boolean, std::ptr::null_mut(), 0, &mut bytes_required, ); let mut buffer = vec![b'\x00'; bytes_required as usize]; let mut bytes_used: CFIndex = 0; CFStringGetBytes( string_ref, CFRange { location: 0, length: char_len, }, kCFStringEncodingUTF8, 0, false as Boolean, buffer.as_mut_ptr(), buffer.len() as CFIndex, &mut bytes_used, ); return String::from_utf8_unchecked(buffer); } } pub fn from_object(env: &Env, dict_ref: CFDictionaryRef) -> JsObject { let length = unsafe { CFDictionaryGetCount(dict_ref) as usize }; let (keys, values) = get_keys_and_values(dict_ref, length); let mut obj = env.create_object().unwrap(); for i in 0..length { let key = to_string(keys[i] as CFStringRef); let value = values[i]; set_obj(env, &mut obj, &key, value); } obj } fn set_obj(env: &Env, obj: &mut JsObject, key: &str, value: *const c_void) { let cf_type = unsafe { CFGetTypeID(value) }; let js_key = env.create_string(key).unwrap(); if cf_type == unsafe { CFStringGetTypeID() } { let value = to_string(value as CFStringRef); let value = env.create_string(&value).unwrap(); obj.set_property(js_key, value).unwrap(); return; } if cf_type == unsafe { CFDictionaryGetTypeID() } { let value = value as CFDictionaryRef; let length = unsafe { CFDictionaryGetCount(value) as usize }; let (keys, values) = get_keys_and_values(value, length); let mut dict = env.create_object().unwrap(); for i in 0..length { let value_key = to_string(keys[i] as CFStringRef); set_obj(env, &mut dict, &value_key, values[i]); } obj.set_property(js_key, dict).unwrap(); return; } if cf_type == unsafe { CFBooleanGetTypeID() } { let value = value as CFBooleanRef; let value = unsafe { value == kCFBooleanTrue }; let value = env.get_boolean(value).unwrap(); obj.set_property(js_key, value).unwrap(); return; } if cf_type == unsafe { CFNumberGetTypeID() } { let value = value as CFNumberRef; let number_type = unsafe { CFNumberGetType(value) }; if number_type == kCFNumberSInt64Type { let mut num: i64 = 100; let number_ptr: *mut i64 = &mut num; unsafe { CFNumberGetValue(value, kCFNumberSInt64Type, number_ptr as *mut c_void); } let number = unsafe { *number_ptr }; obj.set_property(js_key, env.create_int64(number).unwrap()) .unwrap(); return; } } if cf_type == unsafe { CFDataGetTypeID() } { let value = value as CFDataRef; let ptr = unsafe { CFDataGetBytePtr(value) }; let length = unsafe { CFDataGetLength(value) }; let slice = unsafe { std::slice::from_raw_parts(ptr, length as usize) }; obj.set_property( js_key, env.create_arraybuffer_with_data(slice.to_vec()) .unwrap() .into_raw(), ) .unwrap() } } fn get_keys_and_values( dict_ref: CFDictionaryRef, length: usize, ) -> (Vec<*const c_void>, Vec<*const c_void>) { let mut keys = Vec::with_capacity(length); let mut values = Vec::with_capacity(length); unsafe { CFDictionaryGetKeysAndValues(dict_ref, keys.as_mut_ptr(), values.as_mut_ptr()); keys.set_len(length); values.set_len(length); } (keys, values) }
use core_foundation::base::{ kCFAllocatorDefault, Boolean, CFGetTypeID, CFIndex, CFRange, ToVoid, }; use core_foundation::boolean::{kCFBooleanTrue, CFBooleanGetTypeID, CFBooleanRef}; use core_foundation::data::{ CFDataCreate, CFDataGetBytePtr, CFDataGetLength, CFDataGetTypeID, CFDataRef, }; use core_foundation::dictionary::{ kCFTypeDictionaryKeyCallBacks, kCFTypeDictionaryValueCallBacks, CFDictionaryAddValue, CFDictionaryCreateMutable, CFDictionaryGetCount, CFDictionaryGetKeysAndValues, CFDictionaryGetTypeID, CFDictionaryRef, CFMutableDictionaryRef, }; use core_foundation::number::{ kCFNumberSInt64Type, CFNumber, CFNumberGetType, CFNumberGetTypeID, CFNumberGetValue, CFNumberRef, }; use core_foundation::string::{ kCFStringEncodingUTF8, CFString, CFStringGetBytes, CFStringGetCStringPtr, CFStringGetLength, CFStringGetTypeID, CFStringRef, }; use libc::c_void; use napi::{Env, JsBoolean, JsFunction, JsNumber, JsObject, JsString, JsUnknown, ValueType}; pub fn set_cf_dict( dict_ref: CFMutableDictionaryRef, key: *const c_void, unknown: JsUnknown, env: &Env, ) { let object_type = unknown.get_type().unwrap(); if object_type == ValueType::String { let cf_string = CFString::new( unknown .coerce_to_string() .unwrap() .into_utf8() .unwrap() .as_str() .unwrap(), ); unsafe { CFDictionaryAddValue(dict_ref, key, cf_string.to_void()); } return; }; if object_type == ValueType
return; } if object_type == ValueType::Number { let value = unknown.coerce_to_number().unwrap(); let cf_number = to_cf_number(value, env); unsafe { CFDictionaryAddValue(dict_ref, key, cf_number.to_void()); } } } fn to_cf_number(value: JsNumber, env: &Env) -> CFNumber { let number_object = env .get_global() .unwrap() .get_property::<JsString, JsFunction>(env.create_string("Number").unwrap()) .unwrap() .coerce_to_object() .unwrap(); let is_integer_fn = number_object .get_property::<JsString, JsFunction>(env.create_string("isInteger").unwrap()) .unwrap(); let is_integer = unsafe { is_integer_fn .call(None, &[value]) .unwrap() .cast::<JsBoolean>() .get_value() .unwrap() }; if is_integer { CFNumber::from(value.get_int32().unwrap()) } else { CFNumber::from(value.get_double().unwrap()) } } pub fn to_cf_dictionary(object: JsObject, env: &Env) -> CFMutableDictionaryRef { let properties = object.get_property_names().unwrap(); let length = properties.get_array_length_unchecked().unwrap(); let dict_ref = unsafe { CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks, ) }; for i in 0..length { let key = properties.get_element::<JsString>(i).unwrap(); let value = object.get_property::<JsString, JsUnknown>(key).unwrap(); let ns_key = CFString::new(key.into_utf8().unwrap().as_str().unwrap()); set_cf_dict(dict_ref, ns_key.to_void(), value, env); } dict_ref } fn to_string(string_ref: CFStringRef) -> String { unsafe { let char_ptr = CFStringGetCStringPtr(string_ref, kCFStringEncodingUTF8); if !char_ptr.is_null() { let c_str = std::ffi::CStr::from_ptr(char_ptr); return String::from(c_str.to_str().unwrap()); } let char_len = CFStringGetLength(string_ref); let mut bytes_required: CFIndex = 0; CFStringGetBytes( string_ref, CFRange { location: 0, length: char_len, }, kCFStringEncodingUTF8, 0, false as Boolean, std::ptr::null_mut(), 0, &mut bytes_required, ); let mut buffer = vec![b'\x00'; bytes_required as usize]; let mut bytes_used: CFIndex = 0; CFStringGetBytes( string_ref, CFRange { location: 0, length: char_len, }, kCFStringEncodingUTF8, 0, false as Boolean, buffer.as_mut_ptr(), buffer.len() as CFIndex, &mut bytes_used, ); return String::from_utf8_unchecked(buffer); } } pub fn from_object(env: &Env, dict_ref: CFDictionaryRef) -> JsObject { let length = unsafe { CFDictionaryGetCount(dict_ref) as usize }; let (keys, values) = get_keys_and_values(dict_ref, length); let mut obj = env.create_object().unwrap(); for i in 0..length { let key = to_string(keys[i] as CFStringRef); let value = values[i]; set_obj(env, &mut obj, &key, value); } obj } fn set_obj(env: &Env, obj: &mut JsObject, key: &str, value: *const c_void) { let cf_type = unsafe { CFGetTypeID(value) }; let js_key = env.create_string(key).unwrap(); if cf_type == unsafe { CFStringGetTypeID() } { let value = to_string(value as CFStringRef); let value = env.create_string(&value).unwrap(); obj.set_property(js_key, value).unwrap(); return; } if cf_type == unsafe { CFDictionaryGetTypeID() } { let value = value as CFDictionaryRef; let length = unsafe { CFDictionaryGetCount(value) as usize }; let (keys, values) = get_keys_and_values(value, length); let mut dict = env.create_object().unwrap(); for i in 0..length { let value_key = to_string(keys[i] as CFStringRef); set_obj(env, &mut dict, &value_key, values[i]); } obj.set_property(js_key, dict).unwrap(); return; } if cf_type == unsafe { CFBooleanGetTypeID() } { let value = value as CFBooleanRef; let value = unsafe { value == kCFBooleanTrue }; let value = env.get_boolean(value).unwrap(); obj.set_property(js_key, value).unwrap(); return; } if cf_type == unsafe { CFNumberGetTypeID() } { let value = value as CFNumberRef; let number_type = unsafe { CFNumberGetType(value) }; if number_type == kCFNumberSInt64Type { let mut num: i64 = 100; let number_ptr: *mut i64 = &mut num; unsafe { CFNumberGetValue(value, kCFNumberSInt64Type, number_ptr as *mut c_void); } let number = unsafe { *number_ptr }; obj.set_property(js_key, env.create_int64(number).unwrap()) .unwrap(); return; } } if cf_type == unsafe { CFDataGetTypeID() } { let value = value as CFDataRef; let ptr = unsafe { CFDataGetBytePtr(value) }; let length = unsafe { CFDataGetLength(value) }; let slice = unsafe { std::slice::from_raw_parts(ptr, length as usize) }; obj.set_property( js_key, env.create_arraybuffer_with_data(slice.to_vec()) .unwrap() .into_raw(), ) .unwrap() } } fn get_keys_and_values( dict_ref: CFDictionaryRef, length: usize, ) -> (Vec<*const c_void>, Vec<*const c_void>) { let mut keys = Vec::with_capacity(length); let mut values = Vec::with_capacity(length); unsafe { CFDictionaryGetKeysAndValues(dict_ref, keys.as_mut_ptr(), values.as_mut_ptr()); keys.set_len(length); values.set_len(length); } (keys, values) }
::Object { if unknown.is_typedarray().unwrap() { let object = unknown.coerce_to_object().unwrap(); let properties = object.get_property_names().unwrap(); let length = properties.get_array_length_unchecked().unwrap(); let mut data: Vec<u8> = vec![]; for i in 0..length { let elem_value = object.get_element::<JsNumber>(i).unwrap(); let value = (elem_value.get_uint32().unwrap() & 0xff) as u8; data.push(value); } let cf_data = unsafe { CFDataCreate(kCFAllocatorDefault, data.as_mut_ptr(), data.len() as isize) }; unsafe { CFDictionaryAddValue(dict_ref, key, cf_data.to_void()); } return; } let new_dict_ref = unsafe { CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks, ) }; let object = unknown.coerce_to_object().unwrap(); let properties = object.get_property_names().unwrap(); let length = properties.get_array_length_unchecked().unwrap(); for i in 0..length { let elem_key = properties.get_element::<JsString>(i).unwrap(); let value = object .get_property::<JsString, JsUnknown>(elem_key) .unwrap(); let ns_key = CFString::new(elem_key.into_utf8().unwrap().as_str().unwrap()); set_cf_dict(new_dict_ref, ns_key.to_void(), value, env); } unsafe { CFDictionaryAddValue(dict_ref, key, new_dict_ref as *const c_void); }
random
[ { "content": "pub fn receive_message(\n\n connection_ref: bridge::AMDServiceConnectionRef,\n\n) -> Result<CFDictionaryRef, i32> {\n\n unsafe {\n\n let response: CFDictionaryRef = std::ptr::null_mut();\n\n let code = bridge::AMDServiceConnectionReceiveMessage(\n\n connection_ref,\n\n &response,\n\n std::ptr::null(),\n\n std::ptr::null(),\n\n std::ptr::null(),\n\n std::ptr::null(),\n\n );\n\n\n\n if code != 0 {\n\n return Err(code);\n\n }\n\n\n\n return Ok(response);\n\n }\n\n}\n", "file_path": "src/device/mod.rs", "rank": 5, "score": 80867.68232325144 }, { "content": "pub fn start_service(\n\n device: &bridge::AMDevice,\n\n service_name: &str,\n\n) -> bridge::AMDServiceConnectionRef {\n\n unsafe {\n\n let ns_service_name = CFString::new(&service_name);\n\n let ns_service_name = ns_service_name.to_void() as CFStringRef;\n\n\n\n let service_ptr: bridge::AMDServiceConnectionRef = std::ptr::null_mut();\n\n let result = bridge::AMDeviceSecureStartService(\n\n device,\n\n ns_service_name,\n\n std::ptr::null_mut(),\n\n &service_ptr,\n\n );\n\n\n\n if result != 0 {\n\n panic!(\"couldn't start service {}\", result);\n\n }\n\n\n\n service_ptr\n\n }\n\n}\n\n\n", "file_path": "src/device/mod.rs", "rank": 6, "score": 80867.68232325144 }, { "content": "pub fn disconnect(device: &bridge::AMDevice) {\n\n unsafe {\n\n bridge::AMDeviceStopSession(device);\n\n bridge::AMDeviceDisconnect(device);\n\n };\n\n}\n\n\n", "file_path": "src/device/mod.rs", "rank": 7, "score": 68287.73277875583 }, { "content": "pub fn connect(device: &bridge::AMDevice) {\n\n let result = unsafe { bridge::AMDeviceConnect(device) };\n\n if result != 0 {\n\n panic!(\"not connected\");\n\n }\n\n\n\n pair(device);\n\n\n\n let session_result = unsafe { bridge::AMDeviceStartSession(device) };\n\n if session_result != 0 {\n\n panic!(\"couldn't start session\");\n\n }\n\n}\n\n\n", "file_path": "src/device/mod.rs", "rank": 8, "score": 68287.73277875583 }, { "content": "pub fn pair(device: &bridge::AMDevice) {\n\n let is_paired = unsafe { bridge::AMDeviceIsPaired(device) };\n\n if is_paired != 1 {\n\n let pair_result = unsafe { bridge::AMDevicePair(device) };\n\n if pair_result != 0 {\n\n panic!(\"device locked\");\n\n }\n\n }\n\n\n\n let is_valid = unsafe { bridge::AMDeviceValidatePairing(device) };\n\n\n\n if is_valid != 0 {\n\n panic!(\"validation failed\");\n\n }\n\n}\n\n\n", "file_path": "src/device/mod.rs", "rank": 9, "score": 68287.73277875583 }, { "content": "pub fn send_message(connection_ref: bridge::AMDServiceConnectionRef, message: CFDictionaryRef) {\n\n let result = unsafe {\n\n bridge::AMDServiceConnectionSendMessage(\n\n connection_ref,\n\n message,\n\n kCFPropertyListBinaryFormat_v1_0,\n\n )\n\n };\n\n\n\n if result != 0 {\n\n panic!(\"couldn't send message {}\", result);\n\n }\n\n}\n\n\n", "file_path": "src/device/mod.rs", "rank": 11, "score": 64986.52874582487 }, { "content": "pub fn get_udid(device: &bridge::AMDevice) -> String {\n\n let char_ptr = unsafe {\n\n let ns_uuid = bridge::AMDeviceCopyDeviceIdentifier(device);\n\n let c_str_ptr = CFStringGetCStringPtr(ns_uuid, kCFStringEncodingUTF8);\n\n CFRelease(ns_uuid as CFTypeRef);\n\n c_str_ptr\n\n };\n\n let c_str = unsafe { std::ffi::CStr::from_ptr(char_ptr) };\n\n return String::from(c_str.to_str().unwrap());\n\n}\n\n\n", "file_path": "src/device/mod.rs", "rank": 12, "score": 63786.75263622363 }, { "content": "pub fn invalidate_connection(connection_ref: bridge::AMDServiceConnectionRef) {\n\n unsafe {\n\n bridge::AMDServiceConnectionInvalidate(connection_ref);\n\n };\n\n}\n\n\n", "file_path": "src/device/mod.rs", "rank": 13, "score": 62612.44477555777 }, { "content": "pub fn get_devices(timeout: f64) -> Vec<&'static bridge::AMDevice> {\n\n let mut devices = Vec::new();\n\n\n\n unsafe {\n\n let devices_ptr: *mut libc::c_void = &mut devices as *mut _ as *mut libc::c_void;\n\n bridge::AMDeviceNotificationSubscribe(handle_am_device_notification, 0, 0, devices_ptr);\n\n CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeout, false as Boolean);\n\n }\n\n\n\n return devices;\n\n}\n\n\n", "file_path": "src/device/mod.rs", "rank": 14, "score": 58451.446107438904 }, { "content": "fn main() {\n\n println!(\"cargo:rustc-link-search=framework=/Library/Apple/System/Library/PrivateFrameworks\");\n\n println!(\"cargo:rustc-link-lib=framework=MobileDevice\");\n\n}\n", "file_path": "build.rs", "rank": 16, "score": 45750.93847940276 }, { "content": "fn main() {\n\n napi_build::setup();\n\n}\n", "file_path": "packages/connector/build.rs", "rank": 17, "score": 44025.43112301724 }, { "content": "#[napi]\n\nfn get_devices() -> Vec<AMDevice> {\n\n let devices = canter::device::get_devices(0.25);\n\n\n\n let mut array = Vec::<AMDevice>::new();\n\n\n\n for device in devices {\n\n array.push(AMDevice::new(device));\n\n }\n\n\n\n array\n\n}\n\n\n", "file_path": "packages/connector/src/lib.rs", "rank": 18, "score": 36395.0938635581 }, { "content": "pub struct amd_service_connection {\n\n pub unknown: [u8; 16],\n\n pub socket: u32,\n\n pub unknown2: u32,\n\n pub secure_io_context: *mut c_void,\n\n pub flags: u32,\n\n pub device_connection_id: u32,\n\n pub service_name: [c_char; 128],\n\n}\n\n\n\nunsafe impl Send for amd_service_connection {}\n\nunsafe impl Sync for amd_service_connection {}\n\n\n\npub type AMDServiceConnectionRef = *const amd_service_connection;\n\n\n", "file_path": "src/device/bridge.rs", "rank": 24, "score": 4.636865558857455 }, { "content": " &kCFTypeDictionaryKeyCallBacks,\n\n &kCFTypeDictionaryValueCallBacks,\n\n )\n\n };\n\n CFDictionary { dict_ref: dict_ref }\n\n }\n\n\n\n pub fn insert(&self, key: &str, value: *const c_void) {\n\n let ns_key = CFString::new(key);\n\n let ns_key_ref = ns_key.to_void();\n\n unsafe {\n\n CFDictionaryAddValue(self.dict_ref, ns_key_ref, value);\n\n }\n\n }\n\n}\n\n\n\nunsafe impl ToVoid<*const c_void> for CFDictionary {\n\n fn to_void(&self) -> *const c_void {\n\n self.dict_ref as *const c_void\n\n }\n", "file_path": "src/cf_dictionary.rs", "rank": 25, "score": 4.3877846710257895 }, { "content": "use libc::c_void;\n\nuse std::ops::Drop;\n\n\n\nuse core_foundation::base::{kCFAllocatorDefault, CFRelease, CFTypeRef, ToVoid};\n\nuse core_foundation::dictionary::{\n\n kCFTypeDictionaryKeyCallBacks, kCFTypeDictionaryValueCallBacks, CFDictionaryAddValue,\n\n CFDictionaryCreateMutable, CFMutableDictionaryRef,\n\n};\n\nuse core_foundation::string::CFString;\n\n\n\npub struct CFDictionary {\n\n dict_ref: CFMutableDictionaryRef,\n\n}\n\n\n\nimpl CFDictionary {\n\n pub fn new() -> CFDictionary {\n\n let dict_ref = unsafe {\n\n CFDictionaryCreateMutable(\n\n kCFAllocatorDefault,\n\n 0,\n", "file_path": "src/cf_dictionary.rs", "rank": 26, "score": 4.378826172482681 }, { "content": "pub mod bridge;\n\n\n\nuse core_foundation::base::{Boolean, CFRelease, CFTypeRef, ToVoid};\n\nuse core_foundation::dictionary::CFDictionaryRef;\n\nuse core_foundation::propertylist::kCFPropertyListBinaryFormat_v1_0;\n\nuse core_foundation::runloop::{kCFRunLoopDefaultMode, CFRunLoopRunInMode};\n\nuse core_foundation::string::{\n\n kCFStringEncodingUTF8, CFString, CFStringGetCStringPtr, CFStringRef,\n\n};\n\n\n\nextern \"C\" fn handle_am_device_notification(\n\n target: *const bridge::AMDeviceNotificationCallbackInfo,\n\n args: *mut libc::c_void,\n\n) {\n\n let manager = args as *mut Vec<&bridge::AMDevice>;\n\n let device = unsafe { &*(*target).dev };\n\n unsafe {\n\n (*manager).push(device);\n\n }\n\n}\n\n\n", "file_path": "src/device/mod.rs", "rank": 28, "score": 4.081296480131874 }, { "content": "use core_foundation::dictionary::CFDictionaryRef;\n\nuse core_foundation::propertylist::CFPropertyListFormat;\n\nuse core_foundation::string::CFStringRef;\n\n\n\nuse libc::{c_char, c_uchar, c_uint, c_void};\n\n\n\n#[repr(C)]\n\npub struct AMDevice {\n\n pub unknown0: [c_uchar; 16],\n\n pub device_id: c_uint,\n\n pub product_id: c_uint,\n\n pub serial: *mut c_char,\n\n pub unknown1: c_uint,\n\n pub unknown2: c_uint,\n\n pub lockdown_conn: c_uint,\n\n pub unknown3: [c_uchar; 8],\n\n pub unknown4: c_uint,\n\n pub unknown5: [c_uchar; 24],\n\n}\n\n\n", "file_path": "src/device/bridge.rs", "rank": 29, "score": 4.072112964245541 }, { "content": " #[napi(constructor)]\n\n pub fn noop() {\n\n // NOTE: without empty constructor throws error at napi-rs\n\n }\n\n\n\n pub fn new(connection_ref: AMDServiceConnectionRef) -> Self {\n\n Self {\n\n connection_ref: connection_ref,\n\n }\n\n }\n\n\n\n #[napi]\n\n pub fn close(&mut self) {\n\n canter::device::invalidate_connection(self.connection_ref);\n\n }\n\n\n\n #[napi]\n\n pub fn send(&mut self, env: Env, message: JsObject) {\n\n canter::device::send_message(self.connection_ref, cf::to_cf_dictionary(message, &env));\n\n }\n", "file_path": "packages/connector/src/lib.rs", "rank": 30, "score": 3.5218450533816514 }, { "content": "#[macro_use]\n\nextern crate napi_derive;\n\n\n\nuse canter::device::bridge::AMDServiceConnectionRef;\n\nuse core_foundation::dictionary::CFDictionaryRef;\n\nuse napi::threadsafe_function::{\n\n ErrorStrategy, ThreadSafeCallContext, ThreadsafeFunction, ThreadsafeFunctionCallMode,\n\n};\n\nuse napi::{Env, JsFunction, JsObject};\n\nuse std::sync::Arc;\n\nuse std::thread;\n\n\n\nmod cf;\n\n\n\n#[napi]\n", "file_path": "packages/connector/src/lib.rs", "rank": 31, "score": 3.238883196416866 }, { "content": "\n\n #[napi]\n\n pub fn register_receive_listener(&mut self, callback: JsFunction) {\n\n let tsfn: ThreadsafeFunction<CFDictionaryRef, ErrorStrategy::Fatal> = callback\n\n .create_threadsafe_function(0, |ctx: ThreadSafeCallContext<CFDictionaryRef>| {\n\n Ok(vec![cf::from_object(&ctx.env, ctx.value)])\n\n })\n\n .unwrap();\n\n\n\n let ptr = unsafe { Arc::new(*self.connection_ref) };\n\n\n\n thread::spawn(move || loop {\n\n let item = Arc::clone(&ptr);\n\n let response = canter::device::receive_message(Arc::into_raw(item));\n\n match response {\n\n Ok(message) => {\n\n tsfn.call(message, ThreadsafeFunctionCallMode::Blocking);\n\n }\n\n Err(_) => {\n\n break;\n\n }\n\n }\n\n });\n\n }\n\n}\n", "file_path": "packages/connector/src/lib.rs", "rank": 32, "score": 2.9826043117295007 }, { "content": "#[derive(Copy, Clone)]\n\n#[repr(C)]\n\npub struct AMDeviceNotificationCallbackInfo {\n\n pub dev: *mut AMDevice,\n\n pub msg: c_uint,\n\n pub subscription: *mut AMDeviceNotification,\n\n}\n\n\n\n#[derive(Copy, Clone)]\n\n#[repr(C)]\n\npub struct AMDeviceNotification {\n\n pub unknown0: c_uint,\n\n pub unknown1: c_uint,\n\n pub unknown2: c_uint,\n\n pub callback: AMDeviceNotificationCallback,\n\n pub cookie: c_uint,\n\n}\n\n\n\n#[derive(Copy, Clone)]\n\n#[repr(C)]\n", "file_path": "src/device/bridge.rs", "rank": 34, "score": 2.294645308967481 }, { "content": "pub mod device;\n", "file_path": "src/lib.rs", "rank": 35, "score": 1.9773592331436673 }, { "content": "# Canter (WIP)\n\n(WIP) iOS Safari and webview testing library with [playwright](https://playwright.dev/docs/api/class-android) compatible API.\n\n\n\nWorks only on macOS.\n\n\n\n# Usage\n\n```ts\n\nimport ios from 'canter-playwright'\n\n\n\n;(async () => {\n\n const [device] = await ios.devices()\n\n const [webview] = await device.webViews()\n\n const page = await webview.page()\n\n await page.goto('https://example.com')\n\n await webview.close()\n\n})()\n\n```\n\n\n\n# Goal\n\nProvide [playwright android](https://playwright.dev/docs/api/class-android) compatible API.\n\n\n\n# Current status\n\n- Connecting to a iOS device.\n\n- Connecting to webview or iOS Safari.\n\n- Navigate webpage\n\n\n\n# Packages\n\n- `canter-core`\n\n- `canter-connector`\n\n- `canter-playwright`\n\n\n\n# License\n\n```\n\nCopyright 2021-2022 Han Lee\n\n\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\n\nyou may not use this file except in compliance with the License.\n\nYou may obtain a copy of the License at\n\n\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n\n\nUnless required by applicable law or agreed to in writing, software\n\ndistributed under the License is distributed on an \"AS IS\" BASIS,\n\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\nSee the License for the specific language governing permissions and\n\nlimitations under the License.\n\n```\n", "file_path": "README.md", "rank": 36, "score": 1.7360943973490035 }, { "content": " #[napi]\n\n pub fn disconnect(&mut self) {\n\n canter::device::disconnect(self.device);\n\n }\n\n\n\n #[napi]\n\n pub fn start_service(&mut self, service_name: String) -> AMService {\n\n let connection_ref = canter::device::start_service(self.device, &service_name);\n\n let res = AMService::new(connection_ref);\n\n res\n\n }\n\n}\n\n\n\n#[napi]\n\npub struct AMService {\n\n connection_ref: AMDServiceConnectionRef,\n\n}\n\n\n\n#[napi]\n\nimpl AMService {\n", "file_path": "packages/connector/src/lib.rs", "rank": 37, "score": 1.7278742389894528 }, { "content": "}\n\n\n\nimpl Drop for CFDictionary {\n\n fn drop(&mut self) {\n\n unsafe {\n\n CFRelease(self.dict_ref as CFTypeRef);\n\n }\n\n }\n\n}\n", "file_path": "src/cf_dictionary.rs", "rank": 38, "score": 1.556373073829209 }, { "content": " service_name: CFStringRef,\n\n options: CFDictionaryRef,\n\n service_connection: *const AMDServiceConnectionRef,\n\n ) -> i32;\n\n pub fn AMDServiceConnectionInvalidate(\n\n connection: AMDServiceConnectionRef,\n\n );\n\n pub fn AMDServiceConnectionSendMessage(\n\n connection: AMDServiceConnectionRef,\n\n message: CFDictionaryRef,\n\n format: CFPropertyListFormat,\n\n ) -> i32;\n\n pub fn AMDServiceConnectionReceiveMessage(\n\n connection: AMDServiceConnectionRef,\n\n response: *const CFDictionaryRef,\n\n format: *const CFPropertyListFormat,\n\n unknown0: *const c_void,\n\n unknown1: *const c_void,\n\n unknown2: *const c_void,\n\n ) -> i32;\n\n}\n", "file_path": "src/device/bridge.rs", "rank": 39, "score": 1.4222638293722707 }, { "content": "export class WIService {\n\n private service: AMService\n\n\n\n private connectionId: string\n\n\n\n private callbacks: Set<RpcResponseCallback<any>> = new Set()\n\n\n\n constructor(service: AMService) {\n\n this.service = service\n\n this.connectionId = v4()\n\n service.registerReceiveListener(this.receiveMessage)\n\n }\n\n\n\n private sendMessage = (name: string, params: unknown) => {\n\n this.service.send({\n\n __selector: name,\n\n __argument: params,\n\n })\n\n }\n\n\n\n private receiveMessage = (message: RpcResponse<any>) => {\n\n this.callbacks.forEach((callback) => {\n\n callback(message)\n\n })\n\n }\n\n\n\n private waitUntilResponse = <P>(matcher: RpcResponseMatcher) => {\n\n return new Promise<RpcResponse<P>>((resolve) => {\n\n const handler = (response: RpcResponse<any>) => {\n\n if (matcher(response)) {\n\n this.callbacks.delete(handler)\n\n resolve(response)\n\n }\n\n }\n\n\n\n this.callbacks.add(handler)\n\n })\n\n }\n\n\n\n reportIdentifier = async () => {\n\n this.sendMessage('_rpc_reportIdentifier:', {\n\n WIRConnectionIdentifierKey: this.connectionId,\n\n })\n\n\n\n const response = await this.waitUntilResponse<ReportIdentifierResponse>(\n\n (message) => message.__selector === '_rpc_reportCurrentState:'\n\n )\n\n\n\n return response\n\n }\n\n\n\n getConnectedApplications = async () => {\n\n this.sendMessage('_rpc_getConnectedApplications:', {\n\n WIRConnectionIdentifierKey: this.connectionId,\n\n })\n\n\n\n const response =\n\n await this.waitUntilResponse<ConnectedApplicationsResponse>(\n\n (message) =>\n\n message.__selector === '_rpc_reportConnectedApplicationList:'\n\n )\n\n\n\n return Object.values(response.__argument.WIRApplicationDictionaryKey).flat()\n\n }\n\n\n\n forwardGetListing = async (bundle: string) => {\n\n this.sendMessage('_rpc_forwardGetListing:', {\n\n WIRConnectionIdentifierKey: this.connectionId,\n\n WIRApplicationIdentifierKey: bundle,\n\n })\n\n\n\n const response = await this.waitUntilResponse<ForwardGetListingResponse>(\n\n (message) => message.__selector === '_rpc_applicationSentListing:'\n\n )\n\n\n\n return response.__argument\n\n }\n\n\n\n forwardIndicateWebView = (\n\n appId: string,\n\n pageId: number,\n\n enabled: boolean\n\n ) => {\n\n this.sendMessage('_rpc_forwardIndicateWebView:', {\n\n WIRConnectionIdentifierKey: this.connectionId,\n\n WIRApplicationIdentifierKey: appId,\n\n WIRPageIdentifierKey: pageId,\n\n WIRIndicateEnabledKey: enabled,\n\n })\n\n }\n\n\n\n forwardSocketSetup = async (\n\n appId: string,\n\n pageId: number,\n\n senderId: string\n\n ) => {\n\n this.sendMessage('_rpc_forwardSocketSetup:', {\n\n WIRConnectionIdentifierKey: this.connectionId,\n\n WIRApplicationIdentifierKey: appId,\n\n WIRPageIdentifierKey: pageId,\n\n WIRSenderKey: senderId,\n\n })\n\n\n\n const response = await this.waitUntilResponse<{\n\n WIRDestinationKey: string\n\n WIRMessageDataKey: ArrayBuffer\n\n }>((message) => {\n\n if (message.__selector !== '_rpc_applicationSentData:') {\n\n return false\n\n }\n\n\n\n return message.__argument.WIRDestinationKey === senderId\n\n })\n\n\n\n const message = bufferToObject<{\n\n method: 'Target.targetCreated'\n\n params: { targetInfo: { targetId: string; type: 'page' } }\n\n }>(response.__argument.WIRMessageDataKey)\n\n\n\n return message\n\n }\n\n\n\n forwardSocketData = (\n\n appId: string,\n\n pageId: number,\n\n senderId: string,\n\n targetId: string,\n\n id: number,\n\n message: any\n\n ) => {\n\n this.sendMessage('_rpc_forwardSocketData:', {\n\n WIRConnectionIdentifierKey: this.connectionId,\n\n WIRApplicationIdentifierKey: appId,\n\n WIRPageIdentifierKey: pageId,\n\n WIRSenderKey: senderId,\n\n WIRSocketDataKey: new TextEncoder().encode(\n\n JSON.stringify({\n\n method: 'Target.sendMessageToTarget',\n\n id,\n\n params: {\n\n targetId,\n\n message: JSON.stringify(message),\n\n },\n\n })\n\n ),\n\n })\n\n }\n\n\n\n close = async () => {\n\n this.service.close();\n\n }\n", "file_path": "packages/core/src/services/WIService.ts", "rank": 40, "score": 1.1643926445930255 }, { "content": "export class BundleService {\n\n private service: WIService\n\n private identifierKey: string\n\n\n\n constructor(service: WIService, identifierKey: string) {\n\n this.service = service\n\n this.identifierKey = identifierKey\n\n }\n\n\n\n pages = async () => {\n\n const response = await this.service.forwardGetListing(this.identifierKey)\n\n\n\n const listing = Object.values(response.WIRListingKey)\n\n\n\n return listing.map(\n\n (list) =>\n\n new PageService(\n\n this.service,\n\n this.identifierKey,\n\n list.WIRPageIdentifierKey\n\n )\n\n )\n\n }\n", "file_path": "packages/core/src/services/BundleService.ts", "rank": 41, "score": 1.130248263081978 }, { "content": "export class PageService {\n\n private service: WIService\n\n private bundleIdentifierKey: string\n\n private pageIdentifierKey: number\n\n private connectionId = v4()\n\n private initialized = false\n\n private id: number = 1\n\n private targetId: string = ''\n\n\n\n constructor(\n\n service: WIService,\n\n bundleIdentifierKey: string,\n\n pageIdentifierKey: number\n\n ) {\n\n this.service = service\n\n this.bundleIdentifierKey = bundleIdentifierKey\n\n this.pageIdentifierKey = pageIdentifierKey\n\n }\n\n\n\n private initialize = async () => {\n\n this.service.forwardIndicateWebView(\n\n this.bundleIdentifierKey,\n\n this.pageIdentifierKey,\n\n true\n\n )\n\n\n\n const response = await this.service.forwardSocketSetup(\n\n this.bundleIdentifierKey,\n\n this.pageIdentifierKey,\n\n this.connectionId\n\n )\n\n\n\n this.targetId = response.params.targetInfo.targetId\n\n\n\n this.sendMessage('Inspector.enable')\n\n this.sendMessage('Page.enable')\n\n this.initialized = true\n\n }\n\n\n\n private sendMessage = async (method: string, params?: any) => {\n\n this.service.forwardSocketData(\n\n this.bundleIdentifierKey,\n\n this.pageIdentifierKey,\n\n this.connectionId,\n\n this.targetId,\n\n this.id,\n\n {\n\n id: this.id,\n\n method,\n\n params,\n\n }\n\n )\n\n\n\n this.id = this.id + 1\n\n }\n\n\n\n goto = async (url: string) => {\n\n if (!this.initialized) {\n\n await this.initialize()\n\n }\n\n\n\n this.sendMessage('Page.navigate', {\n\n url,\n\n })\n\n }\n\n\n\n close = async () => {\n\n this.service.close();\n\n }\n", "file_path": "packages/core/src/services/PageService.ts", "rank": 42, "score": 1.0511777829344169 }, { "content": "export class IOSDevice {\n\n private device: AMDevice\n\n\n\n constructor(device: AMDevice) {\n\n this.device = device\n\n }\n\n\n\n webViews = async () => {\n\n this.device.connect()\n\n\n\n const service = this.device.startService('com.apple.webinspector')\n\n const wiService = new WIService(service)\n\n\n\n await wiService.reportIdentifier()\n\n\n\n const applications = await wiService.getConnectedApplications()\n\n\n\n const bundles = applications\n\n .filter(\n\n (app) =>\n\n app.WIRApplicationBundleIdentifierKey !== 'com.apple.mobile.lockdownd'\n\n )\n\n .flatMap((app) => new BundleService(\n\n wiService,\n\n app.WIRApplicationIdentifierKey\n\n ))\n\n\n\n const pages = await Promise.all(bundles.map(async bundle => {\n\n const pages = await bundle.pages()\n\n return pages.map((page) => new IOSWebView(page))\n\n }))\n\n\n\n return pages.flat()\n\n }\n\n\n\n close = async () => {\n\n this.device.disconnect()\n\n }\n", "file_path": "packages/playwright/src/device.ts", "rank": 43, "score": 0.5348884035454468 } ]
Rust
rootfm-core/src/envelope.rs
Kintaro/rootfm
0c535d8c108a94bae144d6d146778f93bb4626e4
use crate::{MINIMUM_LEVEL, SAMPLE_RATE}; use libm::{fmaxf, logf}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum State { Start, Delay, Attack, Hold, Decay, Sustain, Release, Off, } impl Default for State { fn default() -> State { State::Start } } impl State { fn next(&self) -> State { match self { State::Start => State::Delay, State::Delay => State::Attack, State::Attack => State::Hold, State::Hold => State::Decay, State::Decay => State::Sustain, State::Sustain => State::Release, State::Release => State::Off, State::Off => State::Off, } } } #[derive(Copy, Clone, Debug)] pub struct EnvelopeSettings { delay: f32, attack: f32, hold: f32, decay: f32, sustain: f32, release: f32, } impl EnvelopeSettings { pub const fn new( delay: f32, attack: f32, hold: f32, decay: f32, sustain: f32, release: f32, ) -> EnvelopeSettings { EnvelopeSettings { delay, attack, hold, decay, sustain, release, } } } impl EnvelopeSettings { fn value_for_state(&self, state: State) -> f32 { match state { State::Start => 0.0, State::Delay => self.delay, State::Attack => self.attack, State::Hold => self.hold, State::Decay => self.decay, State::Sustain => self.sustain, State::Release => self.release, State::Off => 0.0, } } } #[derive(Copy, Clone, Debug)] pub struct Envelope { state: State, current_level: f32, multiplier: f32, current_sample_index: f32, next_state_sample_index: f32, } impl Envelope { pub const fn new() -> Envelope { Envelope { state: State::Start, current_level: MINIMUM_LEVEL, multiplier: 1.0, current_sample_index: 0.0, next_state_sample_index: 0.0, } } pub const fn output_level(&self) -> f32 { self.current_level } pub fn is_finished(&self) -> bool { self.state == State::Off } pub fn compute(&mut self, settings: &EnvelopeSettings) -> f32 { if self.state == State::Off || self.state == State::Sustain { return self.current_level; } if self.current_sample_index >= self.next_state_sample_index { self.enter_state(settings, self.state.next()); } self.current_level *= self.multiplier; self.current_sample_index += 1.0; self.current_level } pub fn enter_state(&mut self, settings: &EnvelopeSettings, state: State) { let next_sample_index = if state == State::Off || state == State::Sustain { 0.0 } else { settings.value_for_state(state) * SAMPLE_RATE }; let (current_level, multiplier) = match state { State::Off => (0.0, 1.0), State::Start => (MINIMUM_LEVEL, 1.0), State::Delay => (MINIMUM_LEVEL, 1.0), State::Attack => ( MINIMUM_LEVEL, Envelope::multiplier(MINIMUM_LEVEL, 1.0, next_sample_index), ), State::Hold => (1.0, 1.0), State::Decay => ( 1.0, Envelope::multiplier( 1.0, fmaxf(MINIMUM_LEVEL, settings.value_for_state(State::Sustain)), next_sample_index, ), ), State::Sustain => (settings.value_for_state(State::Sustain), 1.0), State::Release => ( self.current_level, Envelope::multiplier(self.current_level, MINIMUM_LEVEL, next_sample_index), ), }; self.state = state; self.current_level = current_level; self.multiplier = multiplier; self.current_sample_index = 0.0; self.next_state_sample_index = next_sample_index; } fn multiplier(start_level: f32, end_level: f32, samples: f32) -> f32 { 1.0 + (logf(end_level) - logf(fmaxf(start_level, MINIMUM_LEVEL))) / samples } }
use crate::{MINIMUM_LEVEL, SAMPLE_RATE}; use libm::{fmaxf, logf}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum State { Start, Delay, Attack, Hold, Decay, Sustain, Release, Off, } impl Default for State { fn default() -> State { State::Start } } impl State { fn next(&self) -> State { match self { State::Start => State::Delay, State::Delay => State::Attack, State::Attack => State::Hold, State::Hold => State::Decay, State::Decay => State::Sustain, State::Sustain => State::Release, State::Release => State::Off, State::Off => State::Off, } } } #[derive(Copy, Clone, Debug)] pub struct EnvelopeSettings { delay: f32, attack: f32, hold: f32, decay: f32, sustain: f32, release: f32, } impl EnvelopeSettings {
} impl EnvelopeSettings { fn value_for_state(&self, state: State) -> f32 { match state { State::Start => 0.0, State::Delay => self.delay, State::Attack => self.attack, State::Hold => self.hold, State::Decay => self.decay, State::Sustain => self.sustain, State::Release => self.release, State::Off => 0.0, } } } #[derive(Copy, Clone, Debug)] pub struct Envelope { state: State, current_level: f32, multiplier: f32, current_sample_index: f32, next_state_sample_index: f32, } impl Envelope { pub const fn new() -> Envelope { Envelope { state: State::Start, current_level: MINIMUM_LEVEL, multiplier: 1.0, current_sample_index: 0.0, next_state_sample_index: 0.0, } } pub const fn output_level(&self) -> f32 { self.current_level } pub fn is_finished(&self) -> bool { self.state == State::Off } pub fn compute(&mut self, settings: &EnvelopeSettings) -> f32 { if self.state == State::Off || self.state == State::Sustain { return self.current_level; } if self.current_sample_index >= self.next_state_sample_index { self.enter_state(settings, self.state.next()); } self.current_level *= self.multiplier; self.current_sample_index += 1.0; self.current_level } pub fn enter_state(&mut self, settings: &EnvelopeSettings, state: State) { let next_sample_index = if state == State::Off || state == State::Sustain { 0.0 } else { settings.value_for_state(state) * SAMPLE_RATE }; let (current_level, multiplier) = match state { State::Off => (0.0, 1.0), State::Start => (MINIMUM_LEVEL, 1.0), State::Delay => (MINIMUM_LEVEL, 1.0), State::Attack => ( MINIMUM_LEVEL, Envelope::multiplier(MINIMUM_LEVEL, 1.0, next_sample_index), ), State::Hold => (1.0, 1.0), State::Decay => ( 1.0, Envelope::multiplier( 1.0, fmaxf(MINIMUM_LEVEL, settings.value_for_state(State::Sustain)), next_sample_index, ), ), State::Sustain => (settings.value_for_state(State::Sustain), 1.0), State::Release => ( self.current_level, Envelope::multiplier(self.current_level, MINIMUM_LEVEL, next_sample_index), ), }; self.state = state; self.current_level = current_level; self.multiplier = multiplier; self.current_sample_index = 0.0; self.next_state_sample_index = next_sample_index; } fn multiplier(start_level: f32, end_level: f32, samples: f32) -> f32 { 1.0 + (logf(end_level) - logf(fmaxf(start_level, MINIMUM_LEVEL))) / samples } }
pub const fn new( delay: f32, attack: f32, hold: f32, decay: f32, sustain: f32, release: f32, ) -> EnvelopeSettings { EnvelopeSettings { delay, attack, hold, decay, sustain, release, } }
function_block-full_function
[ { "content": "fn number_samples_from_ms(delay: f32) -> f32 {\n\n SAMPLE_RATE * delay * 0.001\n\n}\n\n\n\nimpl DelayLine {\n\n pub fn new(delay: f32) -> DelayLine {\n\n let samples = delay as f32 * 0.001 * SAMPLE_RATE;\n\n let fraction = floorf(number_samples_from_ms(delay) - samples);\n\n DelayLine {\n\n buffer: [0.0; MAX_BUFFER_SIZE],\n\n read_position: 0,\n\n write_position: 0,\n\n fraction,\n\n delay_ms: delay,\n\n delay_samples: floorf(number_samples_from_ms(delay)),\n\n }\n\n }\n\n\n\n #[allow(unused)]\n\n pub fn set_delay(&mut self, delay: f32) {\n", "file_path": "rootfm-core/src/reverb/delay_line.rs", "rank": 0, "score": 98200.39416465683 }, { "content": "fn cos_32s(x: f32) -> f32 {\n\n const C1: f32 = 0.99940307;\n\n const C2: f32 = -0.49558072;\n\n const C3: f32 = 0.03679168;\n\n let x2 = x * x;\n\n C1 + x2 * (C2 + C3 * x2)\n\n}\n\n\n", "file_path": "rootfm-core/src/oscillator.rs", "rank": 1, "score": 68981.84990903249 }, { "content": "fn sin(angle: f32) -> f32 {\n\n cos(HALF_PI - angle)\n\n}\n\n\n\nimpl Oscillator {\n\n pub fn with_frequency(settings: &OscillatorSettings, frequency: f32) -> Oscillator {\n\n Oscillator {\n\n phase: 0.0,\n\n phase_step: PERIOD * settings.ratio.apply(frequency) / SAMPLE_RATE,\n\n }\n\n }\n\n\n\n pub fn compute(&mut self, settings: &OscillatorSettings, modulation: f32) -> f32 {\n\n match settings.oscillator_type {\n\n OscillatorType::Sine => {\n\n let value = sin(self.phase + modulation);\n\n self.phase += self.phase_step;\n\n value\n\n }\n\n }\n\n }\n\n}\n", "file_path": "rootfm-core/src/oscillator.rs", "rank": 2, "score": 67352.04013218677 }, { "content": "fn interpolate(x1: f32, x2: f32, y1: f32, y2: f32, x: f32) -> f32 {\n\n let d = x2 - x1;\n\n if d == 0.0 {\n\n return y1;\n\n }\n\n let dx = (x - x1) / d;\n\n dx * y2 + (1.0 - dx) * y1\n\n}\n\n\n\npub use moorer::Moorer;\n", "file_path": "rootfm-core/src/reverb/mod.rs", "rank": 3, "score": 67093.55521457501 }, { "content": "fn cos(mut angle: f32) -> f32 {\n\n //clamp to the range 0..2PI\n\n angle = angle - floorf(angle * INV_TWO_PI) * TWO_PI;\n\n angle = fabsf(angle);\n\n\n\n if angle < HALF_PI {\n\n cos_32s(angle)\n\n } else if angle < PI {\n\n -cos_32s(PI - angle)\n\n } else if angle < THREE_HALF_PI {\n\n -cos_32s(angle - PI)\n\n } else {\n\n cos_32s(TWO_PI - angle)\n\n }\n\n}\n", "file_path": "rootfm-core/src/oscillator.rs", "rank": 4, "score": 64625.983614797726 }, { "content": "fn note_to_frequency(note: u32) -> f32 {\n\n 440.0 * powf(2.0, (note as f32 - 69.0) / 12.0)\n\n}\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct Voice {\n\n operators: [Operator; NUM_OPERATORS],\n\n note: u32,\n\n velocity: f32,\n\n}\n\n\n\nimpl Voice {\n\n pub fn new(preset: &Preset, note: u32, velocity: f32) -> Voice {\n\n let frequency = note_to_frequency(note);\n\n let mut operators =\n\n [Operator::with_frequency(&preset.operator_settings()[0], frequency, velocity);\n\n NUM_OPERATORS];\n\n for i in 0..NUM_OPERATORS {\n\n operators[i] =\n\n Operator::with_frequency(&preset.operator_settings()[i], frequency, velocity);\n", "file_path": "rootfm-core/src/voice.rs", "rank": 5, "score": 54761.63250701751 }, { "content": "struct Song {\n\n tracks: Vec<Track>,\n\n}\n\n\n\nimpl Song {\n\n pub fn preprocess(&mut self) -> Vec<Note> {\n\n let mut result = Vec::new();\n\n while let Some(note) = self.next_note() {\n\n result.push(note);\n\n }\n\n result\n\n }\n\n\n\n pub fn next_note(&mut self) -> Option<Note> {\n\n let mut track_index = std::usize::MAX;\n\n let mut delta = std::u32::MAX;\n\n\n\n for (track, note) in self.tracks.iter().map(|t| t.peek()).enumerate() {\n\n if let Some(n) = note {\n\n if n.delta() < delta {\n", "file_path": "rootfm-core/examples/midi.rs", "rank": 6, "score": 38155.71914247737 }, { "content": "struct Track {\n\n notes: Vec<Note>,\n\n}\n\n\n\nimpl Track {\n\n pub fn peek(&self) -> Option<Note> {\n\n if self.notes.is_empty() {\n\n None\n\n } else {\n\n Some(self.notes[0])\n\n }\n\n }\n\n\n\n pub fn update_delta(&mut self, d: u32) {\n\n if self.notes.is_empty() {\n\n return;\n\n }\n\n self.notes[0].update_delta(d);\n\n }\n\n}\n\n\n", "file_path": "rootfm-core/examples/midi.rs", "rank": 7, "score": 38155.71914247737 }, { "content": "fn main() {\n\n // Put the linker script somewhere the linker can find it\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"memory.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"memory.x\"))\n\n .unwrap();\n\n println!(\"cargo:rustc-link-search={}\", out.display());\n\n\n\n // Only re-run the build script when memory.x is changed,\n\n // instead of when any part of the source code changes.\n\n println!(\"cargo:rerun-if-changed=memory.x\");\n\n}\n", "file_path": "rootfm-firmware/build.rs", "rank": 8, "score": 33058.102148694976 }, { "content": "#[entry]\n\nfn main() -> ! {\n\n let _cp = cortex_m::Peripherals::take().unwrap();\n\n let dp = pac::Peripherals::take().unwrap();\n\n\n\n // Constrain and Freeze power\n\n let pwr = dp.PWR.constrain();\n\n let vos = pwr.freeze();\n\n\n\n // Constrain and Freeze clock\n\n let rcc = dp.RCC.constrain();\n\n let mut ccdr = rcc.sys_ck(400.mhz()).freeze(vos, &dp.SYSCFG);\n\n\n\n let gpiof = dp.GPIOF.split(&mut ccdr.ahb4);\n\n\n\n let mut synthesizer = Synthesizer::new(PRESET_1);\n\n\n\n let i2c = {\n\n let scl = gpiof.pf1.into_alternate_af4().set_open_drain();\n\n let sda = gpiof.pf0.into_alternate_af4().set_open_drain();\n\n dp.I2C2.i2c((scl, sda), 1.mhz(), &ccdr)\n", "file_path": "rootfm-firmware/src/main.rs", "rank": 9, "score": 31965.536398822136 }, { "content": "fn main() {\n\n let spec = hound::WavSpec {\n\n channels: 1,\n\n sample_rate: 44100,\n\n bits_per_sample: 32,\n\n sample_format: hound::SampleFormat::Float,\n\n };\n\n\n\n let path = path::Path::new(\"test.mid\");\n\n let contents = fs::read(path).unwrap();\n\n let smf = Smf::parse(&contents).unwrap();\n\n let mut synthesizer = Synthesizer::new(PRESET_1);\n\n let mut writer = hound::WavWriter::create(\"sine.wav\", spec).unwrap();\n\n\n\n let mut song = Song {\n\n tracks: smf\n\n .tracks\n\n .iter()\n\n .map(|track| Track {\n\n notes: track\n", "file_path": "rootfm-core/examples/midi.rs", "rank": 10, "score": 31965.536398822136 }, { "content": "use super::{interpolate, MAX_BUFFER_SIZE};\n\nuse crate::SAMPLE_RATE;\n\nuse libm::floorf;\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct DelayLine {\n\n buffer: [f32; MAX_BUFFER_SIZE],\n\n read_position: usize,\n\n write_position: usize,\n\n fraction: f32,\n\n delay_samples: f32,\n\n delay_ms: f32,\n\n}\n\n\n", "file_path": "rootfm-core/src/reverb/delay_line.rs", "rank": 11, "score": 23080.18925537769 }, { "content": " pub fn write_delay(&mut self, sample: f32) {\n\n self.buffer[self.write_position] = sample;\n\n self.write_position = (self.write_position + 1) % MAX_BUFFER_SIZE;\n\n self.read_position = (self.write_position + 1) % MAX_BUFFER_SIZE;\n\n }\n\n\n\n pub fn compute(&mut self, sample: f32) -> f32 {\n\n let val = if self.delay_samples == 0.0 {\n\n sample\n\n } else {\n\n self.read_delay()\n\n };\n\n self.write_delay(sample);\n\n val\n\n }\n\n}\n", "file_path": "rootfm-core/src/reverb/delay_line.rs", "rank": 12, "score": 23075.442985651316 }, { "content": " let delay_samples = number_samples_from_ms(delay);\n\n self.delay_samples = floorf(delay_samples);\n\n self.fraction = delay_samples - self.delay_samples;\n\n self.read_position = self.write_position - self.delay_samples as usize;\n\n if self.write_position < self.delay_samples as usize {\n\n self.write_position += MAX_BUFFER_SIZE;\n\n }\n\n }\n\n\n\n pub fn read_delay(&mut self) -> f32 {\n\n let sample = self.buffer[self.read_position];\n\n let previous_read_position = if self.read_position < 1 {\n\n MAX_BUFFER_SIZE - 1\n\n } else {\n\n self.read_position - 1\n\n };\n\n let previous_sample = self.buffer[previous_read_position];\n\n interpolate(0.0, 1.0, sample, previous_sample, self.fraction)\n\n }\n\n\n", "file_path": "rootfm-core/src/reverb/delay_line.rs", "rank": 13, "score": 23073.650945158035 }, { "content": "use super::{interpolate, MAX_BUFFER_SIZE};\n\nuse crate::SAMPLE_RATE;\n\nuse libm::floorf;\n\n\n\nconst EARLY_REFLECTION_TAPS: [f32; 18] = [\n\n 0.0043, 0.0215, 0.0225, 0.0268, 0.0270, 0.0298, 0.0458, 0.0485, 0.0572, 0.0587, 0.0595, 0.0612,\n\n 0.0707, 0.0708, 0.0726, 0.0741, 0.0753, 0.0797,\n\n];\n\n\n\nconst EARLY_REFLECTION_GAINS: [f32; 18] = [\n\n 0.841, 0.504, 0.491, 0.379, 0.380, 0.346, 0.289, 0.272, 0.192, 0.193, 0.217, 0.181, 0.180,\n\n 0.181, 0.176, 0.142, 0.167, 0.134,\n\n];\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct EarlyReflectionTapDelayLine {\n\n write_position: usize,\n\n read_position: usize,\n\n fraction: f32,\n\n buffer: [f32; MAX_BUFFER_SIZE],\n", "file_path": "rootfm-core/src/reverb/early_reflection_tap_delay_line.rs", "rank": 14, "score": 20513.238551349878 }, { "content": " delay_samples: f32,\n\n}\n\n\n\nimpl EarlyReflectionTapDelayLine {\n\n pub fn new(delay: f32) -> EarlyReflectionTapDelayLine {\n\n let delay_samples = SAMPLE_RATE * delay;\n\n EarlyReflectionTapDelayLine {\n\n write_position: 0,\n\n read_position: 0,\n\n buffer: [0.0; MAX_BUFFER_SIZE],\n\n delay_samples: floorf(delay_samples),\n\n fraction: delay_samples - floorf(delay_samples),\n\n }\n\n }\n\n\n\n fn set_delay(&mut self, delay: f32) {\n\n let delay_samples = SAMPLE_RATE * delay;\n\n self.delay_samples = floorf(delay_samples);\n\n self.read_position = if self.write_position < self.delay_samples as usize {\n\n self.write_position + MAX_BUFFER_SIZE - self.delay_samples as usize\n", "file_path": "rootfm-core/src/reverb/early_reflection_tap_delay_line.rs", "rank": 15, "score": 20510.34203746827 }, { "content": " pub fn write_delay(&mut self, sample: f32) {\n\n self.buffer[self.write_position] = sample;\n\n self.write_position = (self.write_position + 1) % MAX_BUFFER_SIZE;\n\n self.read_position = (self.read_position + 1) % MAX_BUFFER_SIZE;\n\n }\n\n\n\n pub fn compute(&mut self, sample: f32) -> f32 {\n\n let y = self.read_delay(sample);\n\n self.write_delay(sample);\n\n y\n\n }\n\n}\n", "file_path": "rootfm-core/src/reverb/early_reflection_tap_delay_line.rs", "rank": 16, "score": 20510.136273593253 }, { "content": " } else {\n\n self.write_position - self.delay_samples as usize\n\n };\n\n }\n\n\n\n pub fn read_delay(&mut self, sample: f32) -> f32 {\n\n sample\n\n + EARLY_REFLECTION_TAPS\n\n .iter()\n\n .zip(EARLY_REFLECTION_GAINS.iter())\n\n .map(|(tap, gain)| {\n\n self.set_delay(*tap);\n\n let y = self.buffer[self.read_position];\n\n let y2 = self.buffer[self.read_position - 1];\n\n let interpolation = interpolate(0.0, 1.0, y, y2, self.fraction);\n\n interpolation * gain\n\n })\n\n .sum::<f32>()\n\n }\n\n\n", "file_path": "rootfm-core/src/reverb/early_reflection_tap_delay_line.rs", "rank": 17, "score": 20509.18192232764 }, { "content": "use super::delay_line::DelayLine;\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct AllPass {\n\n gain: f32,\n\n delay: DelayLine,\n\n}\n\n\n\nimpl AllPass {\n\n pub fn new(delay: f32, gain: f32) -> AllPass {\n\n AllPass {\n\n gain,\n\n delay: DelayLine::new(delay),\n\n }\n\n }\n\n\n\n pub fn compute(&mut self, sample: f32) -> f32 {\n\n let delay = self.delay.read_delay();\n\n let filter = sample + (self.gain * delay);\n\n let out = -self.gain * filter + delay;\n\n self.delay.write_delay(filter);\n\n out\n\n }\n\n}\n", "file_path": "rootfm-core/src/reverb/all_pass.rs", "rank": 24, "score": 12.268730533863867 }, { "content": "use super::delay_line::DelayLine;\n\nuse super::low_pass::LowPass;\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct Comb {\n\n gain: f32,\n\n delay: DelayLine,\n\n low_pass: LowPass,\n\n}\n\n\n\nimpl Comb {\n\n pub fn new(delay: f32, cutoff: f32, gain: f32) -> Comb {\n\n Comb {\n\n gain,\n\n delay: DelayLine::new(delay),\n\n low_pass: LowPass::new(cutoff),\n\n }\n\n }\n\n\n\n #[allow(unused)]\n", "file_path": "rootfm-core/src/reverb/comb.rs", "rank": 25, "score": 12.059598101684886 }, { "content": "use super::all_pass::AllPass;\n\nuse super::comb::Comb;\n\nuse super::delay_line::DelayLine;\n\nuse super::early_reflection_tap_delay_line::EarlyReflectionTapDelayLine;\n\n\n\nconst NUM_COMBS: usize = 6;\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct Moorer {\n\n combs: [Comb; NUM_COMBS],\n\n all_pass: AllPass,\n\n er_generator: EarlyReflectionTapDelayLine,\n\n delay_line: DelayLine,\n\n bypass: bool,\n\n}\n\n\n\nimpl Moorer {\n\n pub fn new(late_delay: f32) -> Moorer {\n\n let gain = 0.707;\n\n Moorer {\n", "file_path": "rootfm-core/src/reverb/moorer.rs", "rank": 27, "score": 10.52358044481604 }, { "content": "impl Ratio {\n\n pub fn apply(&self, frequency: f32) -> f32 {\n\n match self {\n\n Ratio::Ratio(r) => r * frequency,\n\n Ratio::Fixed(f) => *f,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct OscillatorSettings {\n\n oscillator_type: OscillatorType,\n\n ratio: Ratio,\n\n detune: f32,\n\n}\n\n\n\nimpl OscillatorSettings {\n\n pub const fn new(\n\n oscillator_type: OscillatorType,\n\n ratio: Ratio,\n", "file_path": "rootfm-core/src/oscillator.rs", "rank": 28, "score": 10.46967080949283 }, { "content": "use crate::SAMPLE_RATE;\n\nuse libm::{cosf, sqrtf};\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct LowPass {\n\n cutoff: f32,\n\n coefficient: f32,\n\n previous: f32,\n\n}\n\n\n\nimpl LowPass {\n\n pub fn new(cutoff: f32) -> LowPass {\n\n let costh = 2.0 - cosf(2.0 * core::f32::consts::PI * cutoff / SAMPLE_RATE);\n\n LowPass {\n\n cutoff,\n\n coefficient: sqrtf(costh * costh - 1.0) - costh,\n\n previous: 0.0,\n\n }\n\n }\n\n\n", "file_path": "rootfm-core/src/reverb/low_pass.rs", "rank": 29, "score": 9.683700291957173 }, { "content": "use crate::{PERIOD, SAMPLE_RATE};\n\nuse libm::{fabsf, floorf};\n\n\n\npub const SINE_OSCILLATOR: OscillatorSettings = OscillatorSettings {\n\n oscillator_type: OscillatorType::Sine,\n\n ratio: Ratio::Ratio(1.0),\n\n detune: 0.0,\n\n};\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub enum OscillatorType {\n\n Sine,\n\n}\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub enum Ratio {\n\n Ratio(f32),\n\n Fixed(f32),\n\n}\n\n\n", "file_path": "rootfm-core/src/oscillator.rs", "rank": 30, "score": 9.644669429366754 }, { "content": "use crate::{Envelope, EnvelopeSettings, Oscillator, OscillatorSettings, State};\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct OperatorSettings {\n\n envelope_settings: EnvelopeSettings,\n\n oscillator_settings: OscillatorSettings,\n\n enabled: bool,\n\n output_level: f32,\n\n sensitivity: f32,\n\n}\n\n\n\nimpl OperatorSettings {\n\n pub const fn new(\n\n envelope_settings: EnvelopeSettings,\n\n oscillator_settings: OscillatorSettings,\n\n output_level: f32,\n\n sensitivity: f32,\n\n ) -> OperatorSettings {\n\n OperatorSettings {\n\n envelope_settings,\n", "file_path": "rootfm-core/src/operator.rs", "rank": 31, "score": 9.226225237411422 }, { "content": " ALGORITHM_9,\n\n};\n\npub use envelope::{Envelope, EnvelopeSettings, State};\n\npub use operator::{Operator, OperatorSettings};\n\npub use oscillator::{Oscillator, OscillatorSettings, OscillatorType, Ratio, SINE_OSCILLATOR};\n\npub use preset::{Preset, PRESET_1, PRESET_2, PRESET_3, PRESET_4};\n\npub use reverb::Moorer;\n\npub use synthesizer::Synthesizer;\n\npub use voice::Voice;\n\n\n\npub const MINIMUM_LEVEL: f32 = 0.01;\n\npub const NUM_VOICES: usize = 12;\n\npub const NUM_OPERATORS: usize = 6;\n\npub const PERIOD: f32 = core::f32::consts::PI * 2.0;\n\n//pub const SAMPLE_RATE: f32 = 44100.0;\n\npub const SAMPLE_RATE: f32 = 44100.0;\n\npub const VOICE_LEVEL: f32 = 0.1;\n", "file_path": "rootfm-core/src/lib.rs", "rank": 32, "score": 8.672483235930795 }, { "content": " detune: f32,\n\n ) -> OscillatorSettings {\n\n OscillatorSettings {\n\n oscillator_type,\n\n ratio,\n\n detune,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, Default)]\n\npub struct Oscillator {\n\n phase: f32,\n\n phase_step: f32,\n\n}\n\n\n\nconst PI: f32 = 3.141593;\n\nconst HALF_PI: f32 = 1.570796;\n\nconst TWO_PI: f32 = 6.283185;\n\nconst THREE_HALF_PI: f32 = 4.7123889;\n\nconst INV_TWO_PI: f32 = 0.1591549;\n\n\n", "file_path": "rootfm-core/src/oscillator.rs", "rank": 33, "score": 8.446697510125535 }, { "content": " pub fn gain(&self) -> f32 {\n\n self.gain\n\n }\n\n\n\n pub fn compute(&mut self, sample: f32) -> f32 {\n\n let delay = self.delay.read_delay();\n\n let delay_attenuation = delay * self.gain;\n\n let lowpass = self.low_pass.compute(delay_attenuation);\n\n\n\n let d = sample + lowpass;\n\n self.delay.write_delay(d);\n\n delay\n\n }\n\n}\n", "file_path": "rootfm-core/src/reverb/comb.rs", "rank": 34, "score": 7.848413249358097 }, { "content": "use crate::{\n\n Algorithm, EnvelopeSettings, OperatorSettings, OscillatorSettings, OscillatorType, Ratio,\n\n ALGORITHM_1, ALGORITHM_2, ALGORITHM_3, ALGORITHM_4, NUM_OPERATORS,\n\n};\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct Preset {\n\n operator_settings: [OperatorSettings; NUM_OPERATORS],\n\n algorithm: Algorithm,\n\n feedback: f32,\n\n}\n\n\n\nimpl Preset {\n\n pub const fn operator_settings(&self) -> &[OperatorSettings; NUM_OPERATORS] {\n\n &self.operator_settings\n\n }\n\n\n\n pub const fn algorithm(&self) -> &Algorithm {\n\n &self.algorithm\n\n }\n", "file_path": "rootfm-core/src/preset.rs", "rank": 35, "score": 7.650484279954997 }, { "content": " self.output_level\n\n }\n\n}\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct Operator {\n\n envelope: Envelope,\n\n oscillator: Oscillator,\n\n output_level: f32,\n\n}\n\n\n\nimpl Operator {\n\n pub fn with_frequency(settings: &OperatorSettings, frequency: f32, velocity: f32) -> Operator {\n\n Operator {\n\n envelope: Envelope::new(),\n\n oscillator: Oscillator::with_frequency(settings.oscillator_settings(), frequency),\n\n output_level: (1.0 + (velocity - 1.0) * (settings.sensitivity * 7.0))\n\n * settings.output_level,\n\n }\n\n }\n", "file_path": "rootfm-core/src/operator.rs", "rank": 36, "score": 7.386916950536472 }, { "content": "\n\n pub fn compute(&mut self, settings: &OperatorSettings, modulation: f32) -> f32 {\n\n self.oscillator\n\n .compute(&settings.oscillator_settings, modulation)\n\n * self.envelope.compute(&settings.envelope_settings)\n\n }\n\n\n\n pub fn note_on(&mut self, settings: &OperatorSettings) {\n\n self.envelope\n\n .enter_state(&settings.envelope_settings, State::Delay);\n\n }\n\n\n\n pub fn note_off(&mut self, settings: &OperatorSettings) {\n\n self.envelope\n\n .enter_state(&settings.envelope_settings, State::Release);\n\n }\n\n\n\n pub fn is_finished(&self) -> bool {\n\n self.envelope.is_finished()\n\n }\n\n}\n", "file_path": "rootfm-core/src/operator.rs", "rank": 37, "score": 7.303654352880207 }, { "content": " ALGORITHM_29,\n\n ALGORITHM_30,\n\n ALGORITHM_31,\n\n ALGORITHM_32,\n\n];\n\n\n\npub const NUM_ALGORITHMS: usize = 32;\n\n\n\n#[derive(Copy, Clone)]\n\npub enum Note {\n\n On(u32, u32, u32),\n\n Off(u32, u32),\n\n Tempo(u32, u32),\n\n}\n\n\n\nimpl Note {\n\n pub fn delta(&self) -> u32 {\n\n match self {\n\n &Note::On(_, _, d) => d,\n\n &Note::Off(_, d) => d,\n", "file_path": "rootfm-core/examples/midi.rs", "rank": 38, "score": 6.985763963519126 }, { "content": "use crate::{Moorer, Preset, Voice, NUM_VOICES, VOICE_LEVEL};\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct Synthesizer {\n\n preset: Preset,\n\n voices: [Voice; NUM_VOICES],\n\n active_voices: usize,\n\n reverb: Moorer,\n\n}\n\n\n\nimpl Synthesizer {\n\n pub fn new(preset: Preset) -> Synthesizer {\n\n Synthesizer {\n\n preset,\n\n voices: [Voice::new(&preset, 0, 0.0); NUM_VOICES],\n\n active_voices: 0,\n\n reverb: Moorer::new(0.1),\n\n }\n\n }\n\n\n", "file_path": "rootfm-core/src/synthesizer.rs", "rank": 41, "score": 6.452656299073073 }, { "content": " combs: [\n\n Comb::new(50.0, 1.0, gain),\n\n Comb::new(56.0, 1.0, gain),\n\n Comb::new(61.0, 1.0, gain),\n\n Comb::new(68.0, 1.0, gain),\n\n Comb::new(72.0, 1.0, gain),\n\n Comb::new(78.0, 1.0, gain),\n\n ],\n\n all_pass: AllPass::new(6.0, 0.707),\n\n bypass: false,\n\n er_generator: EarlyReflectionTapDelayLine::new(late_delay),\n\n delay_line: DelayLine::new(late_delay),\n\n }\n\n }\n\n\n\n pub fn compute(&mut self, sample: f32) -> f32 {\n\n if self.bypass {\n\n return sample;\n\n }\n\n\n", "file_path": "rootfm-core/src/reverb/moorer.rs", "rank": 42, "score": 5.43793389827235 }, { "content": "use cpal::traits::*;\n\nuse cpal::*;\n\nuse hound;\n\nuse libm::floorf;\n\nuse midly::*;\n\nuse rootfm_core::*;\n\nuse std::fs;\n\nuse std::path;\n\n\n\npub static PRESETS: &[Preset] = &[PRESET_1, PRESET_2, PRESET_3, PRESET_4];\n\npub const NUM_PRESETS: usize = 4;\n\npub static ALGORITHMS: &[Algorithm] = &[\n\n ALGORITHM_1,\n\n ALGORITHM_2,\n\n ALGORITHM_3,\n\n ALGORITHM_4,\n\n ALGORITHM_5,\n\n ALGORITHM_6,\n\n ALGORITHM_7,\n\n ALGORITHM_8,\n", "file_path": "rootfm-core/examples/midi.rs", "rank": 43, "score": 5.098820861363272 }, { "content": " #[allow(unused)]\n\n pub fn cutoff(&self) -> f32 {\n\n self.cutoff\n\n }\n\n\n\n #[allow(unused)]\n\n pub fn set_cutoff(&mut self, cutoff: f32) {\n\n self.cutoff = cutoff;\n\n let costh = 2.0 - cosf(2.0 * core::f32::consts::PI * cutoff / SAMPLE_RATE);\n\n self.coefficient = sqrtf(costh * costh - 1.0) - costh;\n\n }\n\n\n\n pub fn compute(&mut self, sample: f32) -> f32 {\n\n self.previous = sample * (1.0 + self.coefficient) - (self.previous * self.coefficient);\n\n self.previous\n\n }\n\n}\n", "file_path": "rootfm-core/src/reverb/low_pass.rs", "rank": 44, "score": 4.6215401682177975 }, { "content": "use crate::NUM_OPERATORS;\n\n\n\npub const OPERATOR_01: u8 = 1 << 00;\n\npub const OPERATOR_02: u8 = 1 << 01;\n\npub const OPERATOR_03: u8 = 1 << 02;\n\npub const OPERATOR_04: u8 = 1 << 03;\n\npub const OPERATOR_05: u8 = 1 << 04;\n\npub const OPERATOR_06: u8 = 1 << 05;\n\npub const NONE: u8 = 0;\n\n\n\npub const ALGORITHM_1: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_03,\n\n modulators: [\n\n OPERATOR_02,\n\n NONE,\n\n OPERATOR_04,\n\n OPERATOR_05,\n\n OPERATOR_06,\n\n OPERATOR_06,\n\n ],\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 45, "score": 3.956322140900208 }, { "content": " oscillator_settings,\n\n enabled: true,\n\n output_level,\n\n sensitivity,\n\n }\n\n }\n\n\n\n pub const fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n pub const fn envelope_settings(&self) -> &EnvelopeSettings {\n\n &self.envelope_settings\n\n }\n\n\n\n pub const fn oscillator_settings(&self) -> &OscillatorSettings {\n\n &self.oscillator_settings\n\n }\n\n\n\n pub const fn output_level(&self) -> f32 {\n", "file_path": "rootfm-core/src/operator.rs", "rank": 46, "score": 3.806838246090721 }, { "content": "pub struct Algorithm {\n\n carriers: u8,\n\n modulators: [u8; NUM_OPERATORS],\n\n}\n\n\n\nimpl Algorithm {\n\n pub const fn is_carrier(&self, index: u32) -> bool {\n\n self.carriers & (1 << index) != 0\n\n }\n\n\n\n pub fn is_modulator(&self, index: u32) -> bool {\n\n let bit = 1 << index;\n\n self.modulators.iter().any(|x| x & bit != 0)\n\n }\n\n\n\n pub const fn get_modulators_for(&self, index: u32) -> u8 {\n\n self.modulators[index as usize]\n\n }\n\n}\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 47, "score": 3.631183677337266 }, { "content": " }\n\n counter += 1;\n\n while current_cycle > cycles {\n\n if current_note >= notes.len() {\n\n return;\n\n }\n\n match notes[current_note] {\n\n Note::On(key, velocity, _) => {\n\n synthesizer.note_on(key, velocity as f32 / 127.0);\n\n }\n\n Note::Off(key, _) => {\n\n synthesizer.note_off(key);\n\n }\n\n Note::Tempo(tempo, _) => {\n\n us_per_beat = tempo;\n\n us_per_tick = us_per_beat as f32 / ticks_per_beat as f32;\n\n }\n\n }\n\n wait_us = us_per_tick * notes[current_note + 1].delta() as f32;\n\n cycles = (wait_us * SAMPLE_RATE as f32) / 1_000_000.0;\n", "file_path": "rootfm-core/examples/midi.rs", "rank": 48, "score": 3.5395508412815175 }, { "content": " carriers: OPERATOR_01 | OPERATOR_02 | OPERATOR_03 | OPERATOR_05,\n\n modulators: [NONE, NONE, OPERATOR_04, NONE, OPERATOR_06, OPERATOR_06],\n\n};\n\n\n\npub const ALGORITHM_30: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_02 | OPERATOR_03 | OPERATOR_05,\n\n modulators: [NONE, NONE, OPERATOR_04, OPERATOR_05, OPERATOR_05, NONE],\n\n};\n\n\n\npub const ALGORITHM_31: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_02 | OPERATOR_03 | OPERATOR_04 | OPERATOR_05,\n\n modulators: [NONE, NONE, NONE, NONE, OPERATOR_06, OPERATOR_06],\n\n};\n\n\n\npub const ALGORITHM_32: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_02 | OPERATOR_03 | OPERATOR_04 | OPERATOR_05 | OPERATOR_06,\n\n modulators: [NONE, NONE, NONE, NONE, NONE, OPERATOR_06],\n\n};\n\n\n\n#[derive(Copy, Clone, Debug)]\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 49, "score": 3.468566680720537 }, { "content": "use std::env;\n\nuse std::fs::File;\n\nuse std::io::Write;\n\nuse std::path::PathBuf;\n\n\n", "file_path": "rootfm-firmware/build.rs", "rank": 50, "score": 3.3750456752284523 }, { "content": " )),\n\n _ => None,\n\n },\n\n _ => None,\n\n })\n\n .filter(Option::is_some)\n\n .map(|x| x.unwrap())\n\n .collect(),\n\n })\n\n .collect(),\n\n };\n\n\n\n let mut us_per_beat = 500000;\n\n let ticks_per_beat = match smf.header.timing {\n\n Timing::Metrical(t) => t.as_int() as u32,\n\n _ => 0,\n\n };\n\n let mut us_per_tick = us_per_beat as f32 / ticks_per_beat as f32;\n\n\n\n let host = cpal::default_host();\n", "file_path": "rootfm-core/examples/midi.rs", "rank": 51, "score": 3.330019515817303 }, { "content": "\n\n pub const fn feedback(&self) -> f32 {\n\n self.feedback\n\n }\n\n\n\n pub fn set_algorithm(&mut self, algorithm: Algorithm) {\n\n self.algorithm = algorithm;\n\n }\n\n}\n\n\n\npub const ENVELOPE_1: EnvelopeSettings = EnvelopeSettings::new(0.0, 0.01, 0.2, 0.1, 1.0, 1.0);\n\npub const ENVELOPE_2: EnvelopeSettings = EnvelopeSettings::new(0.0, 0.01, 0.0, 0.5, 0.0, 1.0);\n\npub const ENVELOPE_3: EnvelopeSettings = EnvelopeSettings::new(0.0, 0.01, 0.0, 0.3, 0.0, 1.0);\n\n\n\npub static PRESET_1: Preset = Preset {\n\n operator_settings: [\n\n OperatorSettings::new(\n\n ENVELOPE_1,\n\n OscillatorSettings::new(OscillatorType::Sine, Ratio::Ratio(1.0), -3.0),\n\n 0.94,\n", "file_path": "rootfm-core/src/preset.rs", "rank": 52, "score": 3.314907672095506 }, { "content": " .filter(|(index, _)| preset.algorithm().is_carrier(*index as u32))\n\n .map(|(_, value)| value)\n\n .sum()\n\n }\n\n\n\n pub fn note(&self) -> u32 {\n\n self.note\n\n }\n\n\n\n pub fn velocity(&self) -> f32 {\n\n self.velocity\n\n }\n\n\n\n pub fn note_on(&mut self, preset: &Preset) {\n\n for (operator_index, operator) in self.operators.iter_mut().enumerate() {\n\n operator.note_on(&preset.operator_settings()[operator_index])\n\n }\n\n }\n\n\n\n pub fn note_off(&mut self, preset: &Preset) {\n", "file_path": "rootfm-core/src/voice.rs", "rank": 53, "score": 3.276284850838222 }, { "content": " pub fn note_on(&mut self, note: u32, velocity: f32) {\n\n let voice = Voice::new(&self.preset, note, velocity);\n\n self.add_voice(voice);\n\n }\n\n\n\n pub fn note_off(&mut self, note: u32) {\n\n for voice in self.voices.iter_mut() {\n\n if voice.note() == note {\n\n voice.note_off(&self.preset)\n\n }\n\n }\n\n }\n\n\n\n pub fn compute(&mut self) -> f32 {\n\n let mut level = 0.0;\n\n let mut remove = None;\n\n for (voice_index, voice) in self.voices.iter_mut().take(self.active_voices).enumerate() {\n\n if voice.is_finished(self.preset.algorithm()) {\n\n remove = Some(voice_index);\n\n continue;\n", "file_path": "rootfm-core/src/synthesizer.rs", "rank": 54, "score": 3.2216713034755187 }, { "content": " &Note::Tempo(_, d) => d,\n\n }\n\n }\n\n\n\n pub fn update_delta(&mut self, d: u32) {\n\n match self {\n\n Note::On(_, _, ref mut delta) => *delta -= d,\n\n Note::Off(_, ref mut delta) => *delta -= d,\n\n Note::Tempo(_, ref mut delta) => *delta -= d,\n\n }\n\n }\n\n}\n\n\n", "file_path": "rootfm-core/examples/midi.rs", "rank": 55, "score": 3.1686440157361133 }, { "content": " }\n\n\n\n Voice {\n\n operators,\n\n note,\n\n velocity,\n\n }\n\n }\n\n\n\n pub fn compute(&mut self, preset: &Preset) -> f32 {\n\n self.operators\n\n .iter_mut()\n\n .enumerate()\n\n .rev()\n\n .fold(\n\n [0.0; NUM_OPERATORS],\n\n |mut values, (operator_index, operator)| {\n\n let modulators = preset.algorithm().get_modulators_for(operator_index as u32);\n\n\n\n let modulation: f32 = (0u8..8u8)\n", "file_path": "rootfm-core/src/voice.rs", "rank": 56, "score": 3.131726641266803 }, { "content": "#![deny(warnings)]\n\n#![deny(unsafe_code)]\n\n#![no_main]\n\n#![no_std]\n\n\n\nextern crate panic_itm;\n\n\n\nuse cortex_m_rt::entry;\n\nuse embedded_graphics::{fonts::Font6x8, pixelcolor::BinaryColor, prelude::*};\n\nuse numtoa::NumToA;\n\nuse rootfm_core::{Synthesizer, PRESET_1};\n\nuse ssd1306::{mode::GraphicsMode, Builder};\n\nuse stm32h7xx_hal::{pac, prelude::*};\n\nuse xca9548a::{SlaveAddr, TCA9548A};\n\n\n\n#[entry]\n", "file_path": "rootfm-firmware/src/main.rs", "rank": 57, "score": 3.1134156347103694 }, { "content": "use crate::{Algorithm, Operator, Preset, NUM_OPERATORS};\n\nuse libm::powf;\n\n\n", "file_path": "rootfm-core/src/voice.rs", "rank": 58, "score": 3.079148407099794 }, { "content": "#![deny(warnings)]\n\n#![deny(unsafe_code)]\n\n#![no_std]\n\n#![feature(const_fn)]\n\n\n\nmod algorithm;\n\nmod envelope;\n\nmod operator;\n\nmod oscillator;\n\nmod preset;\n\nmod reverb;\n\nmod synthesizer;\n\nmod voice;\n\n\n\npub use algorithm::{\n\n Algorithm, ALGORITHM_1, ALGORITHM_10, ALGORITHM_11, ALGORITHM_12, ALGORITHM_13, ALGORITHM_14,\n\n ALGORITHM_15, ALGORITHM_16, ALGORITHM_17, ALGORITHM_18, ALGORITHM_19, ALGORITHM_2,\n\n ALGORITHM_20, ALGORITHM_21, ALGORITHM_22, ALGORITHM_23, ALGORITHM_24, ALGORITHM_25,\n\n ALGORITHM_26, ALGORITHM_27, ALGORITHM_28, ALGORITHM_29, ALGORITHM_3, ALGORITHM_30,\n\n ALGORITHM_31, ALGORITHM_32, ALGORITHM_4, ALGORITHM_5, ALGORITHM_6, ALGORITHM_7, ALGORITHM_8,\n", "file_path": "rootfm-core/src/lib.rs", "rank": 59, "score": 2.984790020665425 }, { "content": "\n\n event_loop.run(move |id, result| {\n\n let data = match result {\n\n Ok(data) => data,\n\n Err(err) => {\n\n eprintln!(\"an error occurred on stream {:?}: {}\", id, err);\n\n return;\n\n }\n\n };\n\n\n\n match data {\n\n cpal::StreamData::Output {\n\n buffer: cpal::UnknownTypeOutputBuffer::F32(mut buffer),\n\n } => {\n\n for sample in buffer.chunks_mut(format.channels as usize) {\n\n if counter > 0 && counter % (441000 / 4) == 0 {\n\n println!(\"Switching to {}\", (counter / (441000 / 4)) % NUM_ALGORITHMS);\n\n synthesizer\n\n .preset_mut()\n\n .set_algorithm(ALGORITHMS[(counter / (441000 / 4)) % NUM_ALGORITHMS]);\n", "file_path": "rootfm-core/examples/midi.rs", "rank": 60, "score": 2.7458839912502238 }, { "content": "const MAX_BUFFER_SIZE: usize = 32;\n\n\n\nmod all_pass;\n\nmod comb;\n\nmod delay_line;\n\nmod early_reflection_tap_delay_line;\n\nmod low_pass;\n\nmod moorer;\n\n\n", "file_path": "rootfm-core/src/reverb/mod.rs", "rank": 61, "score": 2.54860620428484 }, { "content": " let device = host\n\n .default_output_device()\n\n .expect(\"failed to find a default output device\");\n\n let format = cpal::Format {\n\n channels: 1,\n\n sample_rate: SampleRate(SAMPLE_RATE as u32),\n\n data_type: SampleFormat::F32,\n\n };\n\n let event_loop = host.event_loop();\n\n let stream_id = event_loop.build_output_stream(&device, &format).unwrap();\n\n event_loop.play_stream(stream_id.clone()).unwrap();\n\n\n\n println!(\"Sample rate: {}\", format.sample_rate.0 as f32);\n\n\n\n let mut wait_us = 0.0; //us_per_tick * note.delta() as f32;\n\n let mut cycles = 0.0; //(wait_us * SAMPLE_RATE) / 1_000_000.0;\n\n let mut current_cycle = 0.0;\n\n let notes = song.preprocess();\n\n let mut current_note = 0;\n\n let mut counter = 0;\n", "file_path": "rootfm-core/examples/midi.rs", "rank": 62, "score": 2.48248826057063 }, { "content": "};\n\n\n\npub static PRESET_3: Preset = Preset {\n\n algorithm: ALGORITHM_3,\n\n ..PRESET_1\n\n};\n\n\n\npub static PRESET_4: Preset = Preset {\n\n algorithm: ALGORITHM_4,\n\n ..PRESET_1\n\n};\n", "file_path": "rootfm-core/src/preset.rs", "rank": 63, "score": 2.1467637672018616 }, { "content": " .iter()\n\n .map(|event| match event.kind {\n\n EventKind::Midi { message, .. } => match message {\n\n MidiMessage::NoteOn { key, vel } if vel.as_int() == 0 => {\n\n Some(Note::Off(key.as_int() as u32, event.delta.as_int() as u32))\n\n }\n\n MidiMessage::NoteOn { key, vel } => Some(Note::On(\n\n key.as_int() as u32,\n\n vel.as_int() as u32,\n\n event.delta.as_int() as u32,\n\n )),\n\n MidiMessage::NoteOff { key, .. } => {\n\n Some(Note::Off(key.as_int() as u32, event.delta.as_int() as u32))\n\n }\n\n _ => None,\n\n },\n\n EventKind::Meta(message) => match message {\n\n MetaMessage::Tempo(tempo) => Some(Note::Tempo(\n\n tempo.as_int() as u32,\n\n event.delta.as_int() as u32,\n", "file_path": "rootfm-core/examples/midi.rs", "rank": 64, "score": 1.9370665388842414 }, { "content": " OPERATOR_03,\n\n OPERATOR_05 | OPERATOR_06,\n\n NONE,\n\n NONE,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_28: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_03 | OPERATOR_06,\n\n modulators: [\n\n OPERATOR_02,\n\n NONE,\n\n OPERATOR_04,\n\n OPERATOR_05,\n\n OPERATOR_05,\n\n NONE,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_29: Algorithm = Algorithm {\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 65, "score": 1.914757275979273 }, { "content": " OPERATOR_04,\n\n OPERATOR_05,\n\n OPERATOR_06,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_4: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_04,\n\n modulators: [\n\n OPERATOR_02,\n\n OPERATOR_03,\n\n NONE,\n\n OPERATOR_04,\n\n OPERATOR_05,\n\n OPERATOR_04,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_5: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_03 | OPERATOR_05,\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 66, "score": 1.889235436351536 }, { "content": "};\n\n\n\npub const ALGORITHM_2: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_03,\n\n modulators: [\n\n OPERATOR_02,\n\n OPERATOR_02,\n\n OPERATOR_04,\n\n OPERATOR_05,\n\n OPERATOR_06,\n\n NONE,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_3: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_04,\n\n modulators: [\n\n OPERATOR_02,\n\n OPERATOR_03,\n\n NONE,\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 67, "score": 1.889235436351536 }, { "content": " NONE,\n\n NONE,\n\n OPERATOR_06,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_14: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_03,\n\n modulators: [\n\n OPERATOR_02,\n\n NONE,\n\n OPERATOR_04,\n\n OPERATOR_05 | OPERATOR_06,\n\n NONE,\n\n OPERATOR_06,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_15: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_03,\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 68, "score": 1.889235436351536 }, { "content": " OPERATOR_04,\n\n OPERATOR_06,\n\n NONE,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_9: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_03,\n\n modulators: [\n\n OPERATOR_02,\n\n OPERATOR_02,\n\n OPERATOR_04 | OPERATOR_05,\n\n NONE,\n\n OPERATOR_06,\n\n NONE,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_10: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_04,\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 69, "score": 1.889235436351536 }, { "content": " OPERATOR_05,\n\n OPERATOR_06,\n\n NONE,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_19: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_04 | OPERATOR_05,\n\n modulators: [\n\n OPERATOR_02,\n\n OPERATOR_03,\n\n NONE,\n\n OPERATOR_06,\n\n OPERATOR_06,\n\n OPERATOR_06,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_20: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_02 | OPERATOR_04,\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 70, "score": 1.8643850097104617 }, { "content": "};\n\n\n\npub const ALGORITHM_17: Algorithm = Algorithm {\n\n carriers: OPERATOR_01,\n\n modulators: [\n\n OPERATOR_02 | OPERATOR_03 | OPERATOR_05,\n\n OPERATOR_02,\n\n OPERATOR_04,\n\n NONE,\n\n OPERATOR_06,\n\n NONE,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_18: Algorithm = Algorithm {\n\n carriers: OPERATOR_01,\n\n modulators: [\n\n OPERATOR_02 | OPERATOR_03 | OPERATOR_04,\n\n NONE,\n\n OPERATOR_03,\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 71, "score": 1.8401798453496045 }, { "content": " pub fn preset_mut(&mut self) -> &mut Preset {\n\n &mut self.preset\n\n }\n\n\n\n pub fn set_preset(&mut self, preset: Preset) {\n\n self.preset = preset;\n\n for voice in self.voices.iter_mut() {\n\n *voice = Voice::new(&preset, voice.note(), voice.velocity());\n\n }\n\n }\n\n\n\n pub fn add_voice(&mut self, voice: Voice) {\n\n if self.active_voices == NUM_VOICES {\n\n self.shift_down(0);\n\n }\n\n\n\n self.voices[self.active_voices] = voice;\n\n self.active_voices += 1;\n\n }\n\n\n", "file_path": "rootfm-core/src/synthesizer.rs", "rank": 72, "score": 1.8206779721936257 }, { "content": "};\n\n\n\npub const ALGORITHM_7: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_03 | OPERATOR_05,\n\n modulators: [\n\n OPERATOR_02,\n\n NONE,\n\n OPERATOR_04 | OPERATOR_05,\n\n NONE,\n\n OPERATOR_06,\n\n OPERATOR_06,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_8: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_03,\n\n modulators: [\n\n OPERATOR_02,\n\n NONE,\n\n OPERATOR_04 | OPERATOR_05,\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 73, "score": 1.8165951332073171 }, { "content": "};\n\n\n\npub const ALGORITHM_22: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_03 | OPERATOR_04 | OPERATOR_05,\n\n modulators: [\n\n OPERATOR_02,\n\n NONE,\n\n OPERATOR_06,\n\n OPERATOR_06,\n\n OPERATOR_06,\n\n OPERATOR_06,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_23: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_02 | OPERATOR_04 | OPERATOR_05,\n\n modulators: [\n\n NONE,\n\n OPERATOR_03,\n\n NONE,\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 74, "score": 1.7936073190418682 }, { "content": "};\n\n\n\npub const ALGORITHM_12: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_03,\n\n modulators: [\n\n OPERATOR_02,\n\n OPERATOR_02,\n\n OPERATOR_04 | OPERATOR_05 | OPERATOR_06,\n\n NONE,\n\n NONE,\n\n NONE,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_13: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_03,\n\n modulators: [\n\n OPERATOR_02,\n\n NONE,\n\n OPERATOR_04 | OPERATOR_05 | OPERATOR_06,\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 75, "score": 1.7936073190418682 }, { "content": " OPERATOR_06,\n\n OPERATOR_06,\n\n OPERATOR_06,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_24: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_02 | OPERATOR_03 | OPERATOR_04 | OPERATOR_05,\n\n modulators: [\n\n NONE,\n\n NONE,\n\n OPERATOR_06,\n\n OPERATOR_06,\n\n OPERATOR_06,\n\n OPERATOR_06,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_25: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_02 | OPERATOR_03 | OPERATOR_04 | OPERATOR_05,\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 76, "score": 1.7711940259664958 }, { "content": " let ers = self.er_generator.compute(sample);\n\n let out = self\n\n .combs\n\n .iter_mut()\n\n .map(|comb| comb.compute(ers * 0.25))\n\n .sum();\n\n let pass_out = self.all_pass.compute(out);\n\n let shift = self.delay_line.compute(pass_out);\n\n ers * 0.25 + shift\n\n }\n\n}\n", "file_path": "rootfm-core/src/reverb/moorer.rs", "rank": 77, "score": 1.7557431639911503 }, { "content": " }\n\n\n\n level += voice.compute(&self.preset);\n\n }\n\n\n\n if let Some(voice) = remove {\n\n self.shift_down(voice);\n\n }\n\n level * VOICE_LEVEL\n\n\n\n //self.reverb.compute(level * VOICE_LEVEL)\n\n }\n\n\n\n pub fn active_voices(&self) -> usize {\n\n self.active_voices\n\n }\n\n\n\n pub fn shift_down(&mut self, from: usize) {\n\n for i in from..NUM_VOICES - 1 {\n\n self.voices[i] = self.voices[i + 1];\n\n }\n\n self.active_voices -= 1;\n\n }\n\n}\n", "file_path": "rootfm-core/src/synthesizer.rs", "rank": 78, "score": 1.7280069517015901 }, { "content": " modulators: [NONE, NONE, NONE, OPERATOR_06, OPERATOR_06, OPERATOR_06],\n\n};\n\n\n\npub const ALGORITHM_26: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_02 | OPERATOR_04,\n\n modulators: [\n\n NONE,\n\n OPERATOR_03,\n\n NONE,\n\n OPERATOR_05 | OPERATOR_06,\n\n NONE,\n\n OPERATOR_06,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_27: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_02 | OPERATOR_04,\n\n modulators: [\n\n NONE,\n\n OPERATOR_03,\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 79, "score": 1.6868758108713144 }, { "content": " modulators: [\n\n OPERATOR_02,\n\n NONE,\n\n OPERATOR_04,\n\n NONE,\n\n OPERATOR_06,\n\n OPERATOR_06,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_6: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_03 | OPERATOR_05,\n\n modulators: [\n\n OPERATOR_02,\n\n NONE,\n\n OPERATOR_04,\n\n NONE,\n\n OPERATOR_06,\n\n OPERATOR_05,\n\n ],\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 80, "score": 1.409643674241517 }, { "content": " modulators: [\n\n OPERATOR_02,\n\n OPERATOR_03,\n\n OPERATOR_03,\n\n OPERATOR_05 | OPERATOR_06,\n\n NONE,\n\n NONE,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_11: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_04,\n\n modulators: [\n\n OPERATOR_02,\n\n OPERATOR_03,\n\n NONE,\n\n OPERATOR_05 | OPERATOR_06,\n\n NONE,\n\n OPERATOR_06,\n\n ],\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 81, "score": 1.3821516199192319 }, { "content": " modulators: [\n\n OPERATOR_02 | OPERATOR_06,\n\n OPERATOR_05,\n\n OPERATOR_04,\n\n OPERATOR_06,\n\n NONE,\n\n NONE,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_16: Algorithm = Algorithm {\n\n carriers: OPERATOR_01,\n\n modulators: [\n\n OPERATOR_02 | OPERATOR_03 | OPERATOR_05,\n\n NONE,\n\n OPERATOR_04,\n\n NONE,\n\n OPERATOR_06,\n\n OPERATOR_06,\n\n ],\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 82, "score": 1.3821516199192319 }, { "content": " modulators: [\n\n OPERATOR_03,\n\n OPERATOR_03,\n\n OPERATOR_03,\n\n OPERATOR_05 | OPERATOR_06,\n\n NONE,\n\n NONE,\n\n ],\n\n};\n\n\n\npub const ALGORITHM_21: Algorithm = Algorithm {\n\n carriers: OPERATOR_01 | OPERATOR_02 | OPERATOR_04 | OPERATOR_05,\n\n modulators: [\n\n OPERATOR_03,\n\n OPERATOR_03,\n\n OPERATOR_03,\n\n OPERATOR_06,\n\n OPERATOR_06,\n\n NONE,\n\n ],\n", "file_path": "rootfm-core/src/algorithm.rs", "rank": 83, "score": 1.3557113981216518 }, { "content": " for (operator_index, operator) in self.operators.iter_mut().enumerate() {\n\n operator.note_off(&preset.operator_settings()[operator_index])\n\n }\n\n }\n\n\n\n pub fn is_finished(&self, algorithm: &Algorithm) -> bool {\n\n self.operators\n\n .iter()\n\n .enumerate()\n\n .filter(|(operator_index, _)| algorithm.is_carrier(*operator_index as u32))\n\n .all(|(_, operator)| operator.is_finished())\n\n }\n\n}\n", "file_path": "rootfm-core/src/voice.rs", "rank": 84, "score": 1.1565847521054926 }, { "content": " OperatorSettings::new(\n\n ENVELOPE_2,\n\n OscillatorSettings::new(OscillatorType::Sine, Ratio::Ratio(5.05), 0.0),\n\n 0.82,\n\n 0.0,\n\n ),\n\n OperatorSettings::new(\n\n ENVELOPE_3,\n\n OscillatorSettings::new(OscillatorType::Sine, Ratio::Ratio(9.09), 0.0),\n\n 0.99,\n\n 0.0,\n\n ),\n\n ],\n\n algorithm: ALGORITHM_1,\n\n feedback: 0.0,\n\n};\n\n\n\npub static PRESET_2: Preset = Preset {\n\n algorithm: ALGORITHM_2,\n\n ..PRESET_1\n", "file_path": "rootfm-core/src/preset.rs", "rank": 85, "score": 1.1200271119917105 }, { "content": " };\n\n let manager = shared_bus::CortexMBusManager::new(i2c);\n\n\n\n let mut buffer = [0.0; 3 * 128];\n\n\n\n let address = SlaveAddr::default();\n\n let mut i2c_switch = TCA9548A::new(manager.acquire(), address.clone());\n\n\n\n i2c_switch.select_channels(0b0000_0100).unwrap();\n\n let mut disp1: GraphicsMode<_> = { Builder::new().connect_i2c(manager.acquire()).into() };\n\n disp1.init().unwrap();\n\n\n\n i2c_switch.select_channels(0b0000_1000).unwrap();\n\n let mut disp2: GraphicsMode<_> = Builder::new().connect_i2c(manager.acquire()).into();\n\n disp2.init().unwrap();\n\n\n\n i2c_switch.select_channels(0b0001_0000).unwrap();\n\n let mut disp3: GraphicsMode<_> = Builder::new().connect_i2c(manager.acquire()).into();\n\n disp3.init().unwrap();\n\n\n", "file_path": "rootfm-firmware/src/main.rs", "rank": 86, "score": 0.8399093457997915 } ]
Rust
models/src/input.rs
alsacoin/alsacoin
389ae5aef90011414f545fa8575b5137731adc55
use crate::account::Account; use crate::address::Address; use crate::error::Error; use crate::result::Result; use crate::transaction::Transaction; use crypto::ecc::ed25519::{KeyPair, PublicKey, SecretKey, Signature}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; #[derive(Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default, Serialize, Deserialize)] pub struct Input { pub account: Account, pub signatures: BTreeMap<PublicKey, Signature>, pub amount: u64, pub distance: u64, } impl Input { pub fn new(account: &Account, distance: u64, amount: u64) -> Result<Input> { account.validate()?; if account.amount < amount { let err = Error::InvalidAmount; return Err(err); } if distance == 0 { let err = Error::InvalidDistance; return Err(err); } let mut input = Input::default(); input.account = account.to_owned(); input.amount = amount; input.distance = distance; Ok(input) } pub fn address(&self) -> Address { self.account.address() } pub fn from_transaction(account: &Account, transaction: &Transaction) -> Result<Input> { account.validate()?; transaction.validate()?; if account.stage != transaction.stage { let err = Error::InvalidStage; return Err(err); } if account.time > transaction.time { let err = Error::InvalidTimestamp; return Err(err); } let output = transaction.get_output(&account.address())?; let distance = transaction.distance; let amount = output.amount; let mut account = account.clone(); account.locktime = transaction.locktime; account.amount = amount; account.transaction_id = Some(transaction.id); account.counter += 1; Input::new(&account, distance, amount) } pub fn signature_message(&self, seed: &[u8]) -> Result<Vec<u8>> { let mut clone = self.clone(); clone.signatures = BTreeMap::default(); let mut msg = Vec::new(); msg.extend_from_slice(seed); msg.extend_from_slice(&clone.to_bytes()?); Ok(msg) } pub fn calc_signature(&self, secret_key: &SecretKey, seed: &[u8]) -> Result<Signature> { let kp = KeyPair::from_secret(secret_key)?; if !self.account.signers.lookup(&kp.public_key) { let err = Error::NotFound; return Err(err); } let msg = self.signature_message(seed)?; kp.sign(&msg).map_err(|e| e.into()) } pub fn sign(&mut self, secret_key: &SecretKey, msg: &[u8]) -> Result<()> { let public_key = secret_key.to_public(); if !self.account.signers.lookup(&public_key) { let err = Error::NotFound; return Err(err); } let signature = self.calc_signature(secret_key, msg)?; self.signatures.insert(public_key, signature); Ok(()) } pub fn verify_signature(&self, public_key: &PublicKey, seed: &[u8]) -> Result<()> { if !self.account.signers.lookup(&public_key) { let err = Error::NotFound; return Err(err); } let signature = self.signatures.get(public_key).unwrap(); let msg = self.signature_message(seed)?; public_key.verify(&signature, &msg).map_err(|e| e.into()) } pub fn is_signed(&self) -> bool { let signatures_len = self.signatures.len(); let pks_len = self .signatures .keys() .filter(|pk| self.account.signers.lookup(&pk)) .count(); signatures_len != 0 && pks_len == signatures_len } pub fn is_fully_signed(&self) -> Result<bool> { let res = self.is_signed() && self.signatures_weight()? >= self.account.signers.threshold; Ok(res) } pub fn validate(&self) -> Result<()> { self.account.validate()?; if self.account.amount < self.amount { let err = Error::InvalidAmount; return Err(err); } if self.distance == 0 { let err = Error::InvalidDistance; return Err(err); } for pk in self.signatures.keys() { if !self.account.signers.lookup(&pk) { let err = Error::InvalidPublicKey; return Err(err); } } Ok(()) } pub fn verify_signatures(&self, seed: &[u8]) -> Result<()> { if !self.is_signed() { let err = Error::NotSigned; return Err(err); } for pk in self.signatures.keys() { if !self.account.signers.lookup(&pk) { let err = Error::InvalidPublicKey; return Err(err); } self.verify_signature(&pk, seed)?; } Ok(()) } pub fn verify_fully_signed(&self, seed: &[u8]) -> Result<()> { if !self.is_fully_signed()? { let err = Error::NotFullySigned; return Err(err); } self.verify_signatures(seed) } pub fn signatures_weight(&self) -> Result<u64> { self.validate()?; let mut sigs_weight = 0; for pk in self.signatures.keys() { let signer = self.account.signers.get(&pk)?; sigs_weight += signer.weight; } Ok(sigs_weight) } pub fn to_bytes(&self) -> Result<Vec<u8>> { serde_cbor::to_vec(self).map_err(|e| e.into()) } pub fn from_bytes(b: &[u8]) -> Result<Input> { serde_cbor::from_slice(b).map_err(|e| e.into()) } pub fn to_json(&self) -> Result<String> { serde_json::to_string(self).map_err(|e| e.into()) } pub fn from_json(s: &str) -> Result<Input> { serde_json::from_str(s).map_err(|e| e.into()) } } #[test] fn test_input_new() { use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); let signers = Signers::new().unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let res = Input::new(&account, distance, amount); assert!(res.is_ok()); let input = res.unwrap(); let res = input.validate(); assert!(res.is_ok()); } #[test] fn test_input_sign() { use crate::signer::Signer; use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); let secret_key_a = SecretKey::random().unwrap(); let public_key_a = secret_key_a.to_public(); let secret_key_b = SecretKey::random().unwrap(); let public_key_b = secret_key_b.to_public(); let msg_len = 1000; let msg = Random::bytes(msg_len).unwrap(); let weight = 10; let signer_a = Signer { public_key: public_key_a, weight, }; let signer_b = Signer { public_key: public_key_b, weight, }; let mut signers = Signers::new().unwrap(); signers.threshold = 20; signers.add(&signer_a).unwrap(); signers.add(&signer_b).unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let mut input = Input::new(&account, distance, amount).unwrap(); let is_signed = input.is_signed(); assert!(!is_signed); let res = input.sign(&secret_key_a, &msg); assert!(res.is_ok()); let is_signed = input.is_signed(); assert!(is_signed); let res = input.verify_signature(&public_key_a, &msg); assert!(res.is_ok()); let res = input.signatures_weight(); assert!(res.is_ok()); let sigs_weight = res.unwrap(); assert_eq!(sigs_weight, signer_a.weight); let res = input.is_fully_signed(); assert!(res.is_ok()); assert!(!res.unwrap()); let res = input.sign(&secret_key_b, &msg); assert!(res.is_ok()); let sigs_weight = input.signatures_weight().unwrap(); assert_eq!(sigs_weight, input.account.signers.threshold); let res = input.is_fully_signed(); assert!(res.is_ok()); assert!(res.unwrap()); } #[test] fn test_input_validate() { use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); let signers = Signers::new().unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let mut input = Input::new(&account, distance, amount).unwrap(); let res = input.validate(); assert!(res.is_ok()); input.distance = 0; let res = input.validate(); assert!(res.is_err()); input.distance += 1; let mut invalid_public_key = PublicKey::random().unwrap(); while input.account.signers.lookup(&invalid_public_key) { invalid_public_key = PublicKey::random().unwrap(); } let invalid_signature = Signature::default(); input .signatures .insert(invalid_public_key, invalid_signature); let res = input.validate(); assert!(res.is_err()); } #[test] fn test_input_serialize_bytes() { use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); for _ in 0..10 { let signers = Signers::new().unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let input_a = Input::new(&account, distance, amount).unwrap(); let res = input_a.to_bytes(); assert!(res.is_ok()); let cbor = res.unwrap(); let res = Input::from_bytes(&cbor); assert!(res.is_ok()); let input_b = res.unwrap(); assert_eq!(input_a, input_b) } } #[test] fn test_input_serialize_json() { use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); for _ in 0..10 { let signers = Signers::new().unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let input_a = Input::new(&account, distance, amount).unwrap(); let res = input_a.to_json(); assert!(res.is_ok()); let json = res.unwrap(); let res = Input::from_json(&json); assert!(res.is_ok()); let input_b = res.unwrap(); assert_eq!(input_a, input_b) } }
use crate::account::Account; use crate::address::Address; use crate::error::Error; use crate::result::Result; use crate::transaction::Transaction; use crypto::ecc::ed25519::{KeyPair, PublicKey, SecretKey, Signature}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; #[derive(Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default, Serialize, Deserialize)] pub struct Input { pub account: Account, pub signatures: BTreeMap<PublicKey, Signature>, pub amount: u64, pub distance: u64, } impl Input { pub fn new(account: &Account, distance: u64, amount: u64) -> Result<Input> { account.validate()?; if account.amount < amount { let err = Error::InvalidAmount; return Err(err); } if distance == 0 { let err = Error::InvalidDistance; return Err(err); } let mut input = Input::default(); input.account = account.to_owned(); input.amount = amount; input.distance = distance; Ok(input) } pub fn address(&self) -> Address { self.account.address() } pub fn from_transaction(account: &Account, transaction: &Transaction) -> Result<Input> { account.validate()?; transaction.validate()?; if account.stage != transaction.stage { let err = Error::InvalidStage; return Err(err); } if account.time > transaction.time { let err = Error::InvalidTimestamp; return Err(err); } let output = transaction.get_output(&account.address())?; let distance = transaction.distance; let amount = output.amount; let mut account = account.clone(); account.locktime = transaction.locktime; account.amount = amount; account.transaction_id = Some(transaction.id); account.counter += 1; Input::new(&account, distance, amount) } pub fn signature_message(&self, seed: &[u8]) -> Result<Vec<u8>> { let mut clone = self.clone(); clone.signatures = BTreeMap::default(); let mut msg = Vec::new(); msg.extend_from_slice(seed); msg.extend_from_slice(&clone.to_bytes()?); Ok(msg) }
pub fn sign(&mut self, secret_key: &SecretKey, msg: &[u8]) -> Result<()> { let public_key = secret_key.to_public(); if !self.account.signers.lookup(&public_key) { let err = Error::NotFound; return Err(err); } let signature = self.calc_signature(secret_key, msg)?; self.signatures.insert(public_key, signature); Ok(()) } pub fn verify_signature(&self, public_key: &PublicKey, seed: &[u8]) -> Result<()> { if !self.account.signers.lookup(&public_key) { let err = Error::NotFound; return Err(err); } let signature = self.signatures.get(public_key).unwrap(); let msg = self.signature_message(seed)?; public_key.verify(&signature, &msg).map_err(|e| e.into()) } pub fn is_signed(&self) -> bool { let signatures_len = self.signatures.len(); let pks_len = self .signatures .keys() .filter(|pk| self.account.signers.lookup(&pk)) .count(); signatures_len != 0 && pks_len == signatures_len } pub fn is_fully_signed(&self) -> Result<bool> { let res = self.is_signed() && self.signatures_weight()? >= self.account.signers.threshold; Ok(res) } pub fn validate(&self) -> Result<()> { self.account.validate()?; if self.account.amount < self.amount { let err = Error::InvalidAmount; return Err(err); } if self.distance == 0 { let err = Error::InvalidDistance; return Err(err); } for pk in self.signatures.keys() { if !self.account.signers.lookup(&pk) { let err = Error::InvalidPublicKey; return Err(err); } } Ok(()) } pub fn verify_signatures(&self, seed: &[u8]) -> Result<()> { if !self.is_signed() { let err = Error::NotSigned; return Err(err); } for pk in self.signatures.keys() { if !self.account.signers.lookup(&pk) { let err = Error::InvalidPublicKey; return Err(err); } self.verify_signature(&pk, seed)?; } Ok(()) } pub fn verify_fully_signed(&self, seed: &[u8]) -> Result<()> { if !self.is_fully_signed()? { let err = Error::NotFullySigned; return Err(err); } self.verify_signatures(seed) } pub fn signatures_weight(&self) -> Result<u64> { self.validate()?; let mut sigs_weight = 0; for pk in self.signatures.keys() { let signer = self.account.signers.get(&pk)?; sigs_weight += signer.weight; } Ok(sigs_weight) } pub fn to_bytes(&self) -> Result<Vec<u8>> { serde_cbor::to_vec(self).map_err(|e| e.into()) } pub fn from_bytes(b: &[u8]) -> Result<Input> { serde_cbor::from_slice(b).map_err(|e| e.into()) } pub fn to_json(&self) -> Result<String> { serde_json::to_string(self).map_err(|e| e.into()) } pub fn from_json(s: &str) -> Result<Input> { serde_json::from_str(s).map_err(|e| e.into()) } } #[test] fn test_input_new() { use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); let signers = Signers::new().unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let res = Input::new(&account, distance, amount); assert!(res.is_ok()); let input = res.unwrap(); let res = input.validate(); assert!(res.is_ok()); } #[test] fn test_input_sign() { use crate::signer::Signer; use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); let secret_key_a = SecretKey::random().unwrap(); let public_key_a = secret_key_a.to_public(); let secret_key_b = SecretKey::random().unwrap(); let public_key_b = secret_key_b.to_public(); let msg_len = 1000; let msg = Random::bytes(msg_len).unwrap(); let weight = 10; let signer_a = Signer { public_key: public_key_a, weight, }; let signer_b = Signer { public_key: public_key_b, weight, }; let mut signers = Signers::new().unwrap(); signers.threshold = 20; signers.add(&signer_a).unwrap(); signers.add(&signer_b).unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let mut input = Input::new(&account, distance, amount).unwrap(); let is_signed = input.is_signed(); assert!(!is_signed); let res = input.sign(&secret_key_a, &msg); assert!(res.is_ok()); let is_signed = input.is_signed(); assert!(is_signed); let res = input.verify_signature(&public_key_a, &msg); assert!(res.is_ok()); let res = input.signatures_weight(); assert!(res.is_ok()); let sigs_weight = res.unwrap(); assert_eq!(sigs_weight, signer_a.weight); let res = input.is_fully_signed(); assert!(res.is_ok()); assert!(!res.unwrap()); let res = input.sign(&secret_key_b, &msg); assert!(res.is_ok()); let sigs_weight = input.signatures_weight().unwrap(); assert_eq!(sigs_weight, input.account.signers.threshold); let res = input.is_fully_signed(); assert!(res.is_ok()); assert!(res.unwrap()); } #[test] fn test_input_validate() { use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); let signers = Signers::new().unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let mut input = Input::new(&account, distance, amount).unwrap(); let res = input.validate(); assert!(res.is_ok()); input.distance = 0; let res = input.validate(); assert!(res.is_err()); input.distance += 1; let mut invalid_public_key = PublicKey::random().unwrap(); while input.account.signers.lookup(&invalid_public_key) { invalid_public_key = PublicKey::random().unwrap(); } let invalid_signature = Signature::default(); input .signatures .insert(invalid_public_key, invalid_signature); let res = input.validate(); assert!(res.is_err()); } #[test] fn test_input_serialize_bytes() { use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); for _ in 0..10 { let signers = Signers::new().unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let input_a = Input::new(&account, distance, amount).unwrap(); let res = input_a.to_bytes(); assert!(res.is_ok()); let cbor = res.unwrap(); let res = Input::from_bytes(&cbor); assert!(res.is_ok()); let input_b = res.unwrap(); assert_eq!(input_a, input_b) } } #[test] fn test_input_serialize_json() { use crate::signers::Signers; use crate::stage::Stage; use crypto::hash::Digest; use crypto::random::Random; let stage = Stage::random().unwrap(); for _ in 0..10 { let signers = Signers::new().unwrap(); let amount = Random::u64().unwrap(); let tx_id = Digest::random().unwrap(); let account = Account::new(stage, &signers, amount, Some(tx_id)).unwrap(); let mut distance = Random::u64().unwrap(); while distance == 0 { distance = Random::u64().unwrap(); } let input_a = Input::new(&account, distance, amount).unwrap(); let res = input_a.to_json(); assert!(res.is_ok()); let json = res.unwrap(); let res = Input::from_json(&json); assert!(res.is_ok()); let input_b = res.unwrap(); assert_eq!(input_a, input_b) } }
pub fn calc_signature(&self, secret_key: &SecretKey, seed: &[u8]) -> Result<Signature> { let kp = KeyPair::from_secret(secret_key)?; if !self.account.signers.lookup(&kp.public_key) { let err = Error::NotFound; return Err(err); } let msg = self.signature_message(seed)?; kp.sign(&msg).map_err(|e| e.into()) }
function_block-full_function
[ { "content": "/// `address_to_bytes` converts a SocketAddrV4 to a vector of bytes.\n\npub fn address_to_bytes(address: &SocketAddrV4) -> Result<Vec<u8>> {\n\n let mut buf = Vec::new();\n\n\n\n for n in &address.ip().octets() {\n\n buf.write_u8(*n)?;\n\n }\n\n\n\n buf.write_u16::<BigEndian>(address.port())?;\n\n\n\n Ok(buf)\n\n}\n\n\n", "file_path": "network/src/backend/tcp.rs", "rank": 0, "score": 224937.5964145289 }, { "content": "/// `difficulty` calculates the difficulty bits given a specific distance\n\n/// from the eve transaction and a specific amount.\n\npub fn difficulty(h: u64, a: u64) -> Result<u64> {\n\n if (h == 0) || (a == 0) {\n\n let err = Error::OutOfBound;\n\n return Err(err);\n\n }\n\n\n\n let epoch = 1 + (h as f64 / 1000f64) as u64;\n\n let a = 1 + (a as f64 / 1000f64) as u64;\n\n let res = (64f64 * riemmann_zeta_2(epoch)? / riemmann_zeta_2(a)?).floor() as u64;\n\n Ok(res)\n\n}\n\n\n", "file_path": "mining/src/difficulty.rs", "rank": 1, "score": 200183.62646941832 }, { "content": "/// `address_from_bytes` returns an address from a slice of bytes.\n\npub fn address_from_bytes(buf: &[u8]) -> Result<SocketAddrV4> {\n\n let mut reader = Cursor::new(buf);\n\n\n\n let mut ip = [0u8; 4];\n\n\n\n #[allow(clippy::needless_range_loop)]\n\n for i in 0..4 {\n\n ip[i] = reader.read_u8()?;\n\n }\n\n\n\n let port = reader.read_u16::<BigEndian>()?;\n\n\n\n let ip_addr = Ipv4Addr::from(ip);\n\n let address = SocketAddrV4::new(ip_addr, port);\n\n Ok(address)\n\n}\n\n\n\n/// `TcpNetwork` is a network network using a Tcp network.\n\n#[derive(Copy, Clone, Eq, PartialEq, Debug)]\n\npub struct TcpNetwork {\n", "file_path": "network/src/backend/tcp.rs", "rank": 2, "score": 196191.6767505731 }, { "content": "/// `write_to_stderr` writes a binary message to stderr.\n\nfn write_to_stderr(msg: &[u8]) -> Result<()> {\n\n stderr().write_all(msg).map_err(|e| e.into())\n\n}\n\n\n", "file_path": "log/src/logger.rs", "rank": 3, "score": 188666.35406813724 }, { "content": "/// `write_to_stdout` writes a binary message to stdout.\n\nfn write_to_stdout(msg: &[u8]) -> Result<()> {\n\n stdout().write_all(msg).map_err(|e| e.into())\n\n}\n\n\n", "file_path": "log/src/logger.rs", "rank": 4, "score": 188666.35406813724 }, { "content": "/// `encrypt` encrypts a `Message` into a `CypherText`.\n\npub fn encrypt(msg: Message, pk: PublicKey, sk: SecretKey) -> Result<CypherText> {\n\n if sk.to_public().to_point().ct_eq(&pk.to_point()).unwrap_u8() == 1u8 {\n\n let msg = \"same secret keys\".into();\n\n let err = Error::Keys { msg };\n\n return Err(err);\n\n }\n\n\n\n if let Some(msg_point) = msg.to_point().decompress() {\n\n if let Some(shared_point) = shared(pk, sk)?.decompress() {\n\n let delta = (msg_point + shared_point).compress();\n\n let gamma = sk.to_public();\n\n\n\n let cyph = CypherText { gamma, delta };\n\n Ok(cyph)\n\n } else {\n\n let msg = \"invalid shared secret\".into();\n\n let err = Error::SharedSecret { msg };\n\n Err(err)\n\n }\n\n } else {\n\n let msg = \"same message\".into();\n\n let err = Error::Message { msg };\n\n Err(err)\n\n }\n\n}\n\n\n", "file_path": "crypto/src/ecc/elgamal.rs", "rank": 5, "score": 181047.7747813842 }, { "content": "/// `riemann_zeta_2` calculates the value of the Riemann Zeta function with s = 2\n\n/// at a specific iteration.\n\npub fn riemmann_zeta_2(n: u64) -> Result<f64> {\n\n if n == 0 {\n\n let err = Error::OutOfBound;\n\n return Err(err);\n\n }\n\n\n\n let mut res = 0f64;\n\n\n\n for i in 1..=n {\n\n let i2 = i.pow(2) as f64;\n\n res += 1f64 / i2;\n\n }\n\n\n\n Ok(res)\n\n}\n\n\n", "file_path": "mining/src/common.rs", "rank": 6, "score": 174387.80258679378 }, { "content": "/// `write_to_file` writes a binary message to a regular file.\n\n/// The file is created if missing.\n\nfn write_to_file(path: &str, msg: &[u8]) -> Result<()> {\n\n let mut file = OpenOptions::new().create(true).append(true).open(path)?;\n\n\n\n file.write_all(msg)?;\n\n file.write_all(b\"\\n\").map_err(|e| e.into())\n\n}\n\n\n\n/// `Logger` is the logger type used in Alsacoin.\n\n#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]\n\npub struct Logger {\n\n level: LogLevel,\n\n format: LogFormat,\n\n file: LogFile,\n\n color: bool,\n\n}\n\n\n\nimpl Logger {\n\n /// `new` creates a new `Logger`. The logger logs\n\n /// in json or binary or string on stderr and stdout,\n\n /// but only in json and binary on file.\n", "file_path": "log/src/logger.rs", "rank": 7, "score": 172877.2873536342 }, { "content": "/// `fetch_transactions` fetches transactions from remote.\n\npub fn fetch_transactions<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n ids: &BTreeSet<Digest>,\n\n) -> Result<BTreeSet<Transaction>> {\n\n let nodes = state.lock().unwrap().sample_nodes()?;\n\n let res_arc = Arc::new(Mutex::new(BTreeSet::new()));\n\n\n\n for node in nodes {\n\n let cons_msg =\n\n ConsensusMessage::new_fetch_transactions(&*state.lock().unwrap().address, &node, ids)?;\n\n send_message(state.clone(), network.clone(), logger.clone(), &cons_msg)?;\n\n let mut max_retries = state.lock().unwrap().config.max_retries.unwrap_or(1);\n\n\n\n while max_retries > 0 {\n", "file_path": "protocol/src/network.rs", "rank": 8, "score": 172265.1824951119 }, { "content": "/// `push_transactions` sends `Transaction`s to a remote node.\n\npub fn push_transactions<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n address: &[u8],\n\n fetch_id: u64,\n\n transactions: &BTreeSet<Transaction>,\n\n) -> Result<()> {\n\n let stage = state.lock().unwrap().stage;\n\n let node = Node::new(stage, address);\n\n\n\n let cons_msg = ConsensusMessage::new_push_transactions(\n\n &*state.lock().unwrap().address,\n\n fetch_id + 1,\n\n &node,\n\n transactions,\n\n )?;\n\n\n\n send_message(state, network, logger, &cons_msg)\n\n}\n\n\n", "file_path": "protocol/src/network.rs", "rank": 9, "score": 172265.1303211513 }, { "content": "/// `handle_transaction` elaborates an incoming `Node`.\n\n/// It is equivalent to the `OnReceiveTx` function in the Avalanche paper.\n\npub fn handle_transaction<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n transaction: &Transaction,\n\n) -> Result<()> {\n\n transaction.validate_fully_signed()?;\n\n transaction.validate_mined()?;\n\n\n\n let tx_id = transaction.id;\n\n\n\n if transaction.is_eve()? && tx_id != state.lock().unwrap().state.eve_transaction_id {\n\n let err = Error::InvalidTransaction;\n\n return Err(err);\n\n }\n\n\n", "file_path": "protocol/src/network.rs", "rank": 10, "score": 172263.92534450203 }, { "content": "/// `handle_push_transactions` handles a `PushTransactions`.\n\npub fn handle_push_transactions<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n msg: &ConsensusMessage,\n\n prev_id: u64,\n\n ids: &BTreeSet<Digest>,\n\n) -> Result<BTreeSet<Transaction>> {\n\n msg.validate()?;\n\n let expected_ids = ids;\n\n\n\n if msg.is_push_transactions()?\n\n && msg.node().address == state.lock().unwrap().address\n\n && msg.id() == prev_id + 1\n\n {\n\n match msg.to_owned() {\n", "file_path": "protocol/src/network.rs", "rank": 11, "score": 168554.10286840802 }, { "content": "/// `fetch_random_transactions` fetches random transactions from remote.\n\npub fn fetch_random_transactions<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n count: u32,\n\n) -> Result<BTreeSet<Transaction>> {\n\n let nodes = state.lock().unwrap().sample_nodes()?;\n\n let res_arc = Arc::new(Mutex::new(BTreeSet::new()));\n\n\n\n for node in nodes {\n\n let cons_msg = ConsensusMessage::new_fetch_random_transactions(\n\n &*state.lock().unwrap().address,\n\n &node,\n\n count,\n\n )?;\n\n send_message(state.clone(), network.clone(), logger.clone(), &cons_msg)?;\n", "file_path": "protocol/src/network.rs", "rank": 12, "score": 168554.0516341832 }, { "content": "/// `fetch_node_transactions` fetches transactions from a remote node.\n\npub fn fetch_node_transactions<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n address: &[u8],\n\n ids: &BTreeSet<Digest>,\n\n) -> Result<BTreeSet<Transaction>> {\n\n let node = Node::new(state.lock().unwrap().stage, address);\n\n let res_arc = Arc::new(Mutex::new(BTreeSet::new()));\n\n\n\n let cons_msg =\n\n ConsensusMessage::new_fetch_transactions(&*state.lock().unwrap().address, &node, ids)?;\n\n send_message(state.clone(), network.clone(), logger.clone(), &cons_msg)?;\n\n let mut max_retries = state.lock().unwrap().config.max_retries.unwrap_or(1);\n\n\n\n while max_retries > 0 {\n", "file_path": "protocol/src/network.rs", "rank": 13, "score": 168554.0516341832 }, { "content": "/// `handle_fetch_transactions` handles a `FetchTransactions` request.\n\npub fn handle_fetch_transactions<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n msg: &ConsensusMessage,\n\n) -> Result<()> {\n\n msg.validate()?;\n\n\n\n match msg.to_owned() {\n\n ConsensusMessage::FetchTransactions {\n\n address,\n\n id,\n\n node,\n\n ids,\n\n ..\n\n } => {\n", "file_path": "protocol/src/network.rs", "rank": 14, "score": 168554.0516341832 }, { "content": "/// `handle_push_random_transactions` handles a `PushTransactions` following a\n\n/// `FetchRandomTransactions`.\n\npub fn handle_push_random_transactions<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n msg: &ConsensusMessage,\n\n fetch_id: u64,\n\n count: u32,\n\n) -> Result<BTreeSet<Transaction>> {\n\n msg.validate()?;\n\n let expected_count = count;\n\n\n\n if msg.is_push_transactions()?\n\n && msg.node().address == state.lock().unwrap().address\n\n && msg.id() == fetch_id + 1\n\n {\n\n match msg.to_owned() {\n", "file_path": "protocol/src/network.rs", "rank": 15, "score": 165066.00301472592 }, { "content": "/// `handle_fetch_random_transactions` handles a `FetchRandomTransactions` request.\n\npub fn handle_fetch_random_transactions<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n msg: &ConsensusMessage,\n\n) -> Result<()> {\n\n msg.validate()?;\n\n\n\n match msg.to_owned() {\n\n ConsensusMessage::FetchRandomTransactions {\n\n address,\n\n id,\n\n node,\n\n count,\n\n ..\n\n } => {\n", "file_path": "protocol/src/network.rs", "rank": 16, "score": 165065.68217820086 }, { "content": "/// `fetch_node_random_transactions` fetches random transactions from a remote node.\n\npub fn fetch_node_random_transactions<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n address: &[u8],\n\n count: u32,\n\n) -> Result<BTreeSet<Transaction>> {\n\n let node = Node::new(state.lock().unwrap().stage, address);\n\n let res_arc = Arc::new(Mutex::new(BTreeSet::new()));\n\n\n\n let cons_msg = ConsensusMessage::new_fetch_random_transactions(\n\n &*state.lock().unwrap().address,\n\n &node,\n\n count,\n\n )?;\n\n\n", "file_path": "protocol/src/network.rs", "rank": 17, "score": 165065.68217820086 }, { "content": "/// `read_file` reads a file.\n\npub fn read_file(path: &str) -> Result<Vec<u8>> {\n\n let mut file = File::open(path)?;\n\n\n\n let mut buf = Vec::new();\n\n file.read_to_end(&mut buf)?;\n\n\n\n Ok(buf)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 18, "score": 164470.20875561127 }, { "content": "/// `write_file` writes a file.\n\npub fn write_file(path: &str, buf: &[u8]) -> Result<()> {\n\n let mut file = OpenOptions::new()\n\n .create(true)\n\n .write(true)\n\n .truncate(true)\n\n .open(path)?;\n\n\n\n file.write_all(buf).map_err(|e| e.into())\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 19, "score": 164470.20875561127 }, { "content": "#[test]\n\nfn test_transaction_distance() {\n\n use crate::account::Account;\n\n use crate::signer::Signer;\n\n use crate::signers::Signers;\n\n use crypto::random::Random;\n\n\n\n let stage = Stage::random().unwrap();\n\n let mut transaction = Transaction::new().unwrap();\n\n transaction.stage = stage;\n\n transaction.update_id().unwrap();\n\n\n\n let mut max_distance = transaction.distance;\n\n\n\n for _ in 0..10 {\n\n let public_key = PublicKey::random().unwrap();\n\n let weight = Random::u64().unwrap();\n\n let threshold = weight;\n\n\n\n let signer = Signer { public_key, weight };\n\n let mut signers = Signers::new().unwrap();\n", "file_path": "models/src/transaction.rs", "rank": 20, "score": 153720.72506285494 }, { "content": "#[test]\n\nfn test_transaction_outputs() {\n\n let custom_len = 10;\n\n let mut transaction = Transaction::new().unwrap();\n\n\n\n for _ in 0..10 {\n\n let mut output = Output::random(custom_len).unwrap();\n\n\n\n let found = transaction.lookup_output(&output.address);\n\n assert!(!found);\n\n\n\n let res = transaction.get_output(&output.address);\n\n assert!(res.is_err());\n\n\n\n let res = transaction.add_output(&output);\n\n assert!(res.is_ok());\n\n\n\n let res = transaction.validate_outputs();\n\n assert!(res.is_ok());\n\n\n\n let found = transaction.lookup_output(&output.address);\n", "file_path": "models/src/transaction.rs", "rank": 21, "score": 153682.48329617069 }, { "content": "#[test]\n\nfn test_transaction_inputs() {\n\n use crate::account::Account;\n\n use crate::signer::Signer;\n\n use crate::signers::Signers;\n\n use crypto::random::Random;\n\n\n\n let stage = Stage::random().unwrap();\n\n let mut transaction = Transaction::new().unwrap();\n\n transaction.stage = stage;\n\n transaction.update_id().unwrap();\n\n\n\n for _ in 0..10 {\n\n let secret_key = SecretKey::random().unwrap();\n\n let public_key = secret_key.to_public();\n\n\n\n let threshold = 10;\n\n let weight = threshold;\n\n\n\n let signer = Signer { public_key, weight };\n\n let mut signers = Signers::new().unwrap();\n", "file_path": "models/src/transaction.rs", "rank": 22, "score": 153607.70614345494 }, { "content": "#[test]\n\nfn test_output_serialize_bytes() {\n\n for _ in 0..10 {\n\n let custom_len = Random::u32_range(0, 11).unwrap();\n\n let output_a = Output::random(custom_len).unwrap();\n\n\n\n let res = output_a.to_bytes();\n\n assert!(res.is_ok());\n\n let cbor = res.unwrap();\n\n\n\n let res = Output::from_bytes(&cbor);\n\n assert!(res.is_ok());\n\n let output_b = res.unwrap();\n\n\n\n assert_eq!(output_a, output_b)\n\n }\n\n}\n\n\n", "file_path": "models/src/output.rs", "rank": 23, "score": 150542.4173686866 }, { "content": "#[test]\n\nfn test_output_serialize_json() {\n\n for _ in 0..10 {\n\n let custom_len = Random::u32_range(0, 11).unwrap();\n\n let output_a = Output::random(custom_len).unwrap();\n\n\n\n let res = output_a.to_json();\n\n assert!(res.is_ok());\n\n let json = res.unwrap();\n\n\n\n let res = Output::from_json(&json);\n\n assert!(res.is_ok());\n\n let output_b = res.unwrap();\n\n\n\n assert_eq!(output_a, output_b)\n\n }\n\n}\n", "file_path": "models/src/output.rs", "rank": 24, "score": 150542.4173686866 }, { "content": "#[test]\n\nfn test_account_serialize_json() {\n\n use crypto::random::Random;\n\n\n\n for _ in 0..10 {\n\n let stage = Stage::random().unwrap();\n\n let signers = Signers::new().unwrap();\n\n let amount = Random::u64().unwrap();\n\n let tx_id = Digest::random().unwrap();\n\n let account_a = Account::new(stage, &signers, amount, Some(tx_id)).unwrap();\n\n\n\n let res = account_a.to_json();\n\n assert!(res.is_ok());\n\n let json = res.unwrap();\n\n\n\n let res = Account::from_json(&json);\n\n assert!(res.is_ok());\n\n let account_b = res.unwrap();\n\n\n\n assert_eq!(account_a, account_b)\n\n }\n\n}\n\n\n", "file_path": "models/src/account.rs", "rank": 27, "score": 150384.529372948 }, { "content": "#[test]\n\nfn test_account_serialize_bytes() {\n\n use crypto::random::Random;\n\n\n\n for _ in 0..10 {\n\n let stage = Stage::random().unwrap();\n\n let signers = Signers::new().unwrap();\n\n let amount = Random::u64().unwrap();\n\n let tx_id = Digest::random().unwrap();\n\n let account_a = Account::new(stage, &signers, amount, Some(tx_id)).unwrap();\n\n\n\n let res = account_a.to_bytes();\n\n assert!(res.is_ok());\n\n let cbor = res.unwrap();\n\n\n\n let res = Account::from_bytes(&cbor);\n\n assert!(res.is_ok());\n\n let account_b = res.unwrap();\n\n\n\n assert_eq!(account_a, account_b)\n\n }\n\n}\n\n\n", "file_path": "models/src/account.rs", "rank": 28, "score": 150384.529372948 }, { "content": "#[test]\n\nfn test_transaction_serialize_json() {\n\n for _ in 0..10 {\n\n let transaction_a = Transaction::new().unwrap();\n\n\n\n let res = transaction_a.to_json();\n\n assert!(res.is_ok());\n\n let json = res.unwrap();\n\n\n\n let res = Transaction::from_json(&json);\n\n assert!(res.is_ok());\n\n let transaction_b = res.unwrap();\n\n\n\n assert_eq!(transaction_a, transaction_b)\n\n }\n\n}\n\n\n", "file_path": "models/src/transaction.rs", "rank": 29, "score": 149971.24560263637 }, { "content": "#[test]\n\nfn test_transaction_serialize_bytes() {\n\n for _ in 0..10 {\n\n let transaction_a = Transaction::new().unwrap();\n\n\n\n let res = transaction_a.to_bytes();\n\n assert!(res.is_ok());\n\n let cbor = res.unwrap();\n\n\n\n let res = Transaction::from_bytes(&cbor);\n\n assert!(res.is_ok());\n\n let transaction_b = res.unwrap();\n\n\n\n assert_eq!(transaction_a, transaction_b)\n\n }\n\n}\n\n\n", "file_path": "models/src/transaction.rs", "rank": 30, "score": 149971.24560263637 }, { "content": "#[test]\n\nfn test_signature_serialize() {\n\n let buf = [0u8; SIGNATURE_LEN];\n\n\n\n let res = Signature::from_slice(&buf);\n\n assert!(res.is_ok());\n\n let signature_a = res.unwrap();\n\n\n\n let hex = signature_a.to_string();\n\n\n\n let res = Signature::from_str(&hex);\n\n assert!(res.is_ok());\n\n\n\n let signature_b = res.unwrap();\n\n assert_eq!(signature_a, signature_b)\n\n}\n\n\n", "file_path": "crypto/src/ecc/ed25519.rs", "rank": 31, "score": 139266.7349669435 }, { "content": "/// `update_ancestors` updates the ancestors set of a `Transaction`.\n\npub fn update_ancestors<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n transaction: &Transaction,\n\n) -> Result<()> {\n\n let mut res = Ok(());\n\n\n\n for ancestor in\n\n fetch_missing_ancestors(state.clone(), network.clone(), logger.clone(), transaction)?\n\n {\n\n let state = state.clone();\n\n let network = network.clone();\n\n let logger = logger.clone();\n\n\n\n res = thread::spawn(move || handle_transaction(state, network, logger, &ancestor))\n", "file_path": "protocol/src/network.rs", "rank": 32, "score": 131945.20882714418 }, { "content": "/// `serve_client` serves the client `ConsensusMessage`s.\n\npub fn serve_client<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n) -> Result<()> {\n\n let timeout = state.lock().unwrap().config.timeout;\n\n\n\n network\n\n .clone()\n\n .lock()\n\n .unwrap()\n\n .serve(\n\n timeout,\n\n Box::new(move |msg| {\n\n let cons_msg = msg.to_consensus_message()?;\n\n\n\n handle(state.clone(), network.clone(), logger.clone(), &cons_msg).map_err(|e| {\n\n NetworkError::Consensus {\n\n msg: format!(\"{}\", e),\n\n }\n\n })\n\n }),\n\n )\n\n .map_err(|e| e.into())\n\n}\n\n\n", "file_path": "protocol/src/network.rs", "rank": 33, "score": 131940.3788087102 }, { "content": "/// `handle_mine` handles a `Mine` `ConsensusMessage` request.\n\npub fn handle_mine<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n msg: &ConsensusMessage,\n\n) -> Result<()> {\n\n msg.validate()?;\n\n\n\n match msg.to_owned() {\n\n ConsensusMessage::Mine {\n\n id,\n\n address,\n\n node,\n\n transactions,\n\n ..\n\n } => {\n", "file_path": "protocol/src/network.rs", "rank": 34, "score": 131940.3788087102 }, { "content": "/// `avalanche_step` is a single execution of the main Avalanche Consensus procedure.\n\npub fn avalanche_step<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n) -> Result<()> {\n\n let tx_ids: BTreeSet<Digest> = state\n\n .lock()\n\n .unwrap()\n\n .state\n\n .known_transactions\n\n .iter()\n\n .filter(|id| !state.lock().unwrap().state.lookup_queried_transaction(&id))\n\n .copied()\n\n .collect();\n\n\n\n for tx_id in tx_ids {\n", "file_path": "protocol/src/network.rs", "rank": 35, "score": 131940.3788087102 }, { "content": "/// `fetch_nodes` fetches nodes from remote.\n\npub fn fetch_nodes<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n ids: &BTreeSet<Digest>,\n\n) -> Result<BTreeSet<Node>> {\n\n let nodes = state.lock().unwrap().sample_nodes()?;\n\n let res_arc = Arc::new(Mutex::new(BTreeSet::new()));\n\n\n\n for node in nodes {\n\n let cons_msg =\n\n ConsensusMessage::new_fetch_nodes(&*state.lock().unwrap().address, &node, ids)?;\n\n send_message(state.clone(), network.clone(), logger.clone(), &cons_msg)?;\n\n\n\n let mut max_retries = state.lock().unwrap().config.max_retries.unwrap_or(1);\n\n\n", "file_path": "protocol/src/network.rs", "rank": 36, "score": 131940.3788087102 }, { "content": "/// `serve_consensus` serves the `Protocol` consensus.\n\n/// The name of the function in the Avalanche paper is \"AvalancheLoop\".\n\npub fn serve_consensus<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n) -> Result<()> {\n\n let mut res = Ok(());\n\n\n\n while res.is_ok() {\n\n let state = state.clone();\n\n let network = network.clone();\n\n let logger = logger.clone();\n\n\n\n res = thread::spawn(|| avalanche_step(state, network, logger))\n\n .join()\n\n .map_err(|e| Error::Thread {\n\n msg: format!(\"{:?}\", e),\n\n })?;\n\n\n\n if res.is_err() {\n\n return res;\n\n }\n\n }\n\n\n\n res\n\n}\n", "file_path": "protocol/src/network.rs", "rank": 37, "score": 131940.3788087102 }, { "content": "/// `send_message` sends a `ConsensusMessage` to a `Node`.\n\npub fn send_message<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n cons_msg: &ConsensusMessage,\n\n) -> Result<()> {\n\n logger.log_info(\"Sending a consensus message\")?;\n\n logger.log_debug(&format!(\n\n \"Started network send_message of message: {:?}\",\n\n cons_msg\n\n ))?;\n\n\n\n let res = cons_msg.validate().map_err(|e| e.into());\n\n handle_result(logger.clone(), res, \"Protocol network send_message error\")?;\n\n\n\n let res = handle_message(state.clone(), cons_msg);\n", "file_path": "protocol/src/network.rs", "rank": 38, "score": 131940.3788087102 }, { "content": "/// `query_node` queries a single remote node.\n\npub fn query_node<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n address: &[u8],\n\n transaction: &Transaction,\n\n) -> Result<bool> {\n\n let node = Node::new(state.lock().unwrap().stage, address);\n\n let cons_msg =\n\n ConsensusMessage::new_query(&*state.lock().unwrap().address, &node, transaction)?;\n\n send_message(state.clone(), network.clone(), logger.clone(), &cons_msg)?;\n\n\n\n let mut res = false;\n\n let mut max_retries = state.lock().unwrap().config.max_retries.unwrap_or(1);\n\n\n\n while max_retries > 0 {\n", "file_path": "protocol/src/network.rs", "rank": 39, "score": 131940.3788087102 }, { "content": "/// `push_nodes` sends `Node`s to a remote node.\n\npub fn push_nodes<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n address: &[u8],\n\n fetch_id: u64,\n\n nodes: &BTreeSet<Node>,\n\n) -> Result<()> {\n\n let node = Node::new(state.lock().unwrap().stage, address);\n\n let cons_msg = ConsensusMessage::new_push_nodes(\n\n &*state.lock().unwrap().address,\n\n fetch_id + 1,\n\n &node,\n\n nodes,\n\n )?;\n\n send_message(state, network, logger, &cons_msg)\n\n}\n\n\n", "file_path": "protocol/src/network.rs", "rank": 40, "score": 131940.3788087102 }, { "content": "/// `serve_mining` serves the mining operations.\n\npub fn serve_mining<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n) -> Result<()> {\n\n let timeout = state.lock().unwrap().config.timeout;\n\n\n\n network\n\n .clone()\n\n .lock()\n\n .unwrap()\n\n .serve(\n\n timeout,\n\n Box::new(move |msg| {\n\n let cons_msg = msg.to_consensus_message()?;\n\n\n\n handle_mine(state.clone(), network.clone(), logger.clone(), &cons_msg).map_err(\n\n |e| NetworkError::Consensus {\n\n msg: format!(\"{}\", e),\n\n },\n\n )\n\n }),\n\n )\n\n .map_err(|e| e.into())\n\n}\n\n\n", "file_path": "protocol/src/network.rs", "rank": 41, "score": 131940.3788087102 }, { "content": "/// `recv_message` receives a `ConsensusMessage` from a `Node`.\n\npub fn recv_message<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n) -> Result<ConsensusMessage> {\n\n logger.log_info(\"Receiving a consensus message\")?;\n\n logger.log_debug(\"Started network recv_message of message\")?;\n\n\n\n let res = state.lock().unwrap().validate();\n\n handle_result(logger.clone(), res, \"Protocol network recv_message error\")?;\n\n\n\n let res = network\n\n .lock()\n\n .unwrap()\n\n .recv(state.lock().unwrap().config.timeout)\n\n .map_err(|e| e.into());\n", "file_path": "protocol/src/network.rs", "rank": 42, "score": 131940.3788087102 }, { "content": "/// `fetch_missing_ancestors` fetches a `Transaction` ancestors from remote if missing.\n\npub fn fetch_missing_ancestors<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n transaction: &Transaction,\n\n) -> Result<BTreeSet<Transaction>> {\n\n transaction.validate()?;\n\n\n\n let to_fetch: BTreeSet<Digest> = transaction\n\n .ancestors()?\n\n .iter()\n\n .filter(|id| !state.lock().unwrap().state.lookup_known_transaction(&id))\n\n .copied()\n\n .collect();\n\n\n\n if to_fetch.is_empty() {\n", "file_path": "protocol/src/network.rs", "rank": 43, "score": 129481.57292511174 }, { "content": "/// `fetch_random_nodes` fetches random nodes from remote.\n\npub fn fetch_random_nodes<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n count: u32,\n\n) -> Result<BTreeSet<Node>> {\n\n let nodes = state.lock().unwrap().sample_nodes()?;\n\n let res_arc = Arc::new(Mutex::new(BTreeSet::new()));\n\n\n\n for node in nodes {\n\n let cons_msg = ConsensusMessage::new_fetch_random_nodes(\n\n &*state.lock().unwrap().address,\n\n &node,\n\n count,\n\n )?;\n\n\n", "file_path": "protocol/src/network.rs", "rank": 44, "score": 129476.8875071497 }, { "content": "/// `handle_fetch_nodes` handles a `FetchNodes` request.\n\npub fn handle_fetch_nodes<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n msg: &ConsensusMessage,\n\n) -> Result<()> {\n\n msg.validate()?;\n\n\n\n match msg.to_owned() {\n\n ConsensusMessage::FetchNodes {\n\n address,\n\n id,\n\n node,\n\n ids,\n\n ..\n\n } => {\n", "file_path": "protocol/src/network.rs", "rank": 45, "score": 129476.8875071497 }, { "content": "/// `fetch_node_nodes` fetches nodes from a remote node.\n\npub fn fetch_node_nodes<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n address: &[u8],\n\n ids: &BTreeSet<Digest>,\n\n) -> Result<BTreeSet<Node>> {\n\n let node = Node::new(state.lock().unwrap().stage, address);\n\n let cons_msg = ConsensusMessage::new_fetch_nodes(&*state.lock().unwrap().address, &node, ids)?;\n\n send_message(state.clone(), network.clone(), logger.clone(), &cons_msg)?;\n\n\n\n let res_arc = Arc::new(Mutex::new(BTreeSet::new()));\n\n let mut max_retries = state.lock().unwrap().config.max_retries.unwrap_or(1);\n\n\n\n while max_retries > 0 {\n\n let recv_cons_msg = recv_message(state.clone(), network.clone(), logger.clone())?;\n", "file_path": "protocol/src/network.rs", "rank": 46, "score": 129476.8875071497 }, { "content": "/// `reset` resets the Alsacoin CLI environment.\n\npub fn reset() -> Result<()> {\n\n reset_stores()?;\n\n reset_configs()\n\n}\n", "file_path": "cli/src/common.rs", "rank": 47, "score": 127931.08712258856 }, { "content": "/// `init` inits the Alsacoin CLI environment.\n\npub fn init() -> Result<()> {\n\n init_configs()?;\n\n init_stores()\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 48, "score": 127931.08712258856 }, { "content": "/// `destroy` destroys the Alsacoin CLI environment.\n\npub fn destroy() -> Result<()> {\n\n destroy_data_dir()\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 49, "score": 127931.08712258856 }, { "content": "/// `handle_fetch_random_nodes` handles a `FetchRandomNodes` request.\n\npub fn handle_fetch_random_nodes<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n msg: &ConsensusMessage,\n\n) -> Result<()> {\n\n msg.validate()?;\n\n\n\n match msg.to_owned() {\n\n ConsensusMessage::FetchRandomNodes {\n\n address,\n\n id,\n\n node,\n\n count,\n\n ..\n\n } => {\n", "file_path": "protocol/src/network.rs", "rank": 50, "score": 127161.26947681431 }, { "content": "/// `fetch_node_random_nodes` fetches random nodes from a remote node.\n\npub fn fetch_node_random_nodes<\n\n S: Store + Send + 'static,\n\n P: Store + Send + 'static,\n\n N: Network + Send + 'static,\n\n>(\n\n state: Arc<Mutex<ProtocolState<S, P>>>,\n\n network: Arc<Mutex<N>>,\n\n logger: Arc<Logger>,\n\n address: &[u8],\n\n count: u32,\n\n) -> Result<BTreeSet<Node>> {\n\n let node = Node::new(state.lock().unwrap().stage, &address);\n\n let cons_msg =\n\n ConsensusMessage::new_fetch_random_nodes(&*state.lock().unwrap().address, &node, count)?;\n\n send_message(state.clone(), network.clone(), logger.clone(), &cons_msg)?;\n\n\n\n let res_arc = Arc::new(Mutex::new(BTreeSet::new()));\n\n let mut max_retries = state.lock().unwrap().config.max_retries.unwrap_or(1);\n\n\n\n while max_retries > 0 {\n", "file_path": "protocol/src/network.rs", "rank": 51, "score": 127161.26947681431 }, { "content": "/// `reset_configs` resets the Alsacoin configs.\n\npub fn reset_configs() -> Result<()> {\n\n reset_config(Stage::Development)?;\n\n reset_config(Stage::Testing)?;\n\n reset_config(Stage::Production)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 52, "score": 125467.59582102807 }, { "content": "/// `destroy_stores` destroys the Alsacoin stores.\n\npub fn destroy_stores() -> Result<()> {\n\n destroy_store(Stage::Development)?;\n\n destroy_store(Stage::Testing)?;\n\n destroy_store(Stage::Production)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 53, "score": 125467.59582102807 }, { "content": "/// `reset_stores` resets the Alsacoin stores.\n\npub fn reset_stores() -> Result<()> {\n\n destroy_stores()?;\n\n init_stores()\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 54, "score": 125467.59582102807 }, { "content": "/// `init_configs` inits the Alsacoin configs.\n\npub fn init_configs() -> Result<()> {\n\n create_config_dir()?;\n\n init_config(Stage::Development)?;\n\n init_config(Stage::Testing)?;\n\n init_config(Stage::Production)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 55, "score": 125467.59582102807 }, { "content": "/// `destroy_configs` destroys the Alsacoin configs.\n\npub fn destroy_configs() -> Result<()> {\n\n destroy_config(Stage::Development)?;\n\n destroy_config(Stage::Testing)?;\n\n destroy_config(Stage::Production)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 56, "score": 125467.59582102807 }, { "content": "/// `init_stores` inits the Alsacoin stores.\n\npub fn init_stores() -> Result<()> {\n\n init_store(Stage::Development)?;\n\n init_store(Stage::Testing)?;\n\n init_store(Stage::Production)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 57, "score": 125467.59582102807 }, { "content": "/// `destroy_store_dir` destroys the Alsacoin stores directory.\n\npub fn destroy_store_dir() -> Result<()> {\n\n destroy_dir(&store_dir()?)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 58, "score": 123151.97779069268 }, { "content": "/// `create_config_dir` creates the Alsacoin configs directory if missing.\n\npub fn create_config_dir() -> Result<()> {\n\n create_dir(&config_dir()?)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 59, "score": 123151.97779069268 }, { "content": "/// `create_store_dir` creates the Alsacoin stores directory if missing.\n\npub fn create_store_dir() -> Result<()> {\n\n create_dir(&store_dir()?)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 60, "score": 123151.97779069268 }, { "content": "/// `destroy_data_dir` destroys the data directory.\n\npub fn destroy_data_dir() -> Result<()> {\n\n destroy_dir(&data_dir()?)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 61, "score": 123151.97779069268 }, { "content": "/// `destroy_config_dir` destroys the Alsacoin configs directory.\n\npub fn destroy_config_dir() -> Result<()> {\n\n destroy_dir(&config_dir()?)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 62, "score": 123151.97779069268 }, { "content": "/// `decrypt` decrypts a `CypherText` into a `Message`.\n\npub fn decrypt(cyph: CypherText, sk: SecretKey) -> Result<Message> {\n\n if sk\n\n .to_public()\n\n .to_point()\n\n .ct_eq(&cyph.gamma.to_point())\n\n .unwrap_u8()\n\n == 1u8\n\n {\n\n let msg = \"same secret keys\".into();\n\n let err = Error::Keys { msg };\n\n return Err(err);\n\n }\n\n\n\n if let Some(delta_point) = cyph.delta.decompress() {\n\n if let Some(inv_shared_point) = inverse_shared(cyph.gamma, sk)?.decompress() {\n\n let msg_point = (delta_point + inv_shared_point).compress();\n\n\n\n let msg = Message::from_point(&msg_point);\n\n Ok(msg)\n\n } else {\n", "file_path": "crypto/src/ecc/elgamal.rs", "rank": 63, "score": 120739.90725470716 }, { "content": "/// `data_dir` returns the data directory.\n\npub fn data_dir() -> Result<String> {\n\n let mut path = env::current_dir()?;\n\n path.push(\"data\");\n\n\n\n if let Some(path) = path.to_str() {\n\n Ok(path.into())\n\n } else {\n\n let err = Error::InvalidPath;\n\n Err(err)\n\n }\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 64, "score": 119718.42635707569 }, { "content": "/// `store_dir` returns the Alsacoin stores directory.\n\npub fn store_dir() -> Result<String> {\n\n let mut path = env::current_dir()?;\n\n path.push(\"data\");\n\n path.push(\"store\");\n\n\n\n if let Some(path) = path.to_str() {\n\n Ok(path.into())\n\n } else {\n\n let err = Error::InvalidPath;\n\n Err(err)\n\n }\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 65, "score": 119718.34859434131 }, { "content": "/// `config_dir` returns the Alsacoin configs directory.\n\npub fn config_dir() -> Result<String> {\n\n let mut path = env::current_dir()?;\n\n path.push(\"data\");\n\n path.push(\"config\");\n\n\n\n if let Some(path) = path.to_str() {\n\n Ok(path.into())\n\n } else {\n\n let err = Error::InvalidPath;\n\n Err(err)\n\n }\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 66, "score": 119718.34859434131 }, { "content": "struct SignatureVisitor;\n\n\n\nimpl<'de> de::Visitor<'de> for SignatureVisitor {\n\n type Value = Signature;\n\n\n\n fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n\n formatter.write_str(\"a string of length DIGEST_LEN*2\")\n\n }\n\n\n\n fn visit_str<E>(self, value: &str) -> result::Result<Self::Value, E>\n\n where\n\n E: de::Error,\n\n {\n\n Signature::from_str(value).map_err(|e| E::custom(format!(\"{}\", e)))\n\n }\n\n\n\n fn visit_string<E>(self, value: String) -> result::Result<Self::Value, E>\n\n where\n\n E: de::Error,\n\n {\n", "file_path": "crypto/src/ecc/ed25519.rs", "rank": 67, "score": 118089.97065846 }, { "content": "/// `create_dir` creates a directory.\n\npub fn create_dir(path: &str) -> Result<()> {\n\n fs::create_dir_all(path).map_err(|e| e.into())\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 68, "score": 114551.06796109058 }, { "content": "/// `destroy_store` destroys the Alsacoin store of a specific stage.\n\npub fn destroy_store(stage: Stage) -> Result<()> {\n\n let path = store_path(stage)?;\n\n destroy_file(&path)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 69, "score": 114551.06796109058 }, { "content": "/// `destroy_dir` destroys a directory.\n\npub fn destroy_dir(path: &str) -> Result<()> {\n\n fs::remove_dir_all(path).map_err(|e| e.into())\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 70, "score": 114551.06796109058 }, { "content": "/// `init_config` inits the Alsacoin config of a specific stage.\n\npub fn init_config(stage: Stage) -> Result<()> {\n\n create_config_dir()?;\n\n\n\n if read_config(stage).is_err() {\n\n create_config(stage)?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 71, "score": 114551.06796109058 }, { "content": "/// `destroy_config` destroys the Alsacoin config of a specific stage.\n\npub fn destroy_config(stage: Stage) -> Result<()> {\n\n let path = config_path(stage)?;\n\n destroy_file(&path)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 72, "score": 114551.06796109058 }, { "content": "/// `reset_store` resets the Alsacoin store of a specific stage.\n\npub fn reset_store(stage: Stage) -> Result<()> {\n\n destroy_store(stage)?;\n\n init_store(stage)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 73, "score": 114551.06796109058 }, { "content": "/// `init_store` inits the Alsacoin store of a specific stage.\n\npub fn init_store(stage: Stage) -> Result<()> {\n\n create_store_dir()?;\n\n\n\n let config = read_config(stage)?;\n\n\n\n create_store(stage, &config)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 74, "score": 114551.06796109058 }, { "content": "/// `create_config` creates a new Alsacoin config.\n\npub fn create_config(stage: Stage) -> Result<()> {\n\n let config = Config::default();\n\n write_config(stage, &config)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 75, "score": 114551.06796109058 }, { "content": "/// `destroy_file` destroys a file.\n\npub fn destroy_file(path: &str) -> Result<()> {\n\n fs::remove_file(path).map_err(|e| e.into())\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 76, "score": 114551.06796109058 }, { "content": "/// `reset_config` resets the Alsacoin config of a specific stage.\n\npub fn reset_config(stage: Stage) -> Result<()> {\n\n destroy_config(stage)?;\n\n init_config(stage)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 77, "score": 114551.06796109058 }, { "content": "#[test]\n\nfn test_output_validate() {\n\n for _ in 0..10 {\n\n let custom_len = Random::u32_range(0, 11).unwrap();\n\n let mut output = Output::random(custom_len).unwrap();\n\n\n\n let res = output.validate();\n\n assert!(res.is_ok());\n\n\n\n output.custom_len += 1;\n\n let res = output.validate();\n\n assert!(res.is_err());\n\n }\n\n}\n\n\n", "file_path": "models/src/output.rs", "rank": 78, "score": 113487.9170941863 }, { "content": "#[test]\n\nfn test_account_new() {\n\n use crate::signer::Signer;\n\n use crypto::ecc::ed25519::PublicKey;\n\n use crypto::random::Random;\n\n\n\n let stage = Stage::random().unwrap();\n\n let amount = Random::u64().unwrap();\n\n let mut valid_signers = Signers::new().unwrap();\n\n\n\n for _ in 0..10 {\n\n let public_key = PublicKey::random().unwrap();\n\n let weight = Random::u64_range(1, 11).unwrap();\n\n let signer = Signer { public_key, weight };\n\n\n\n valid_signers.add(&signer).unwrap();\n\n }\n\n\n\n let mut invalid_signers = valid_signers.clone();\n\n invalid_signers.threshold = invalid_signers.total_weight() + 1;\n\n\n\n let tx_id = Digest::random().unwrap();\n\n\n\n let res = Account::new(stage, &valid_signers, amount, Some(tx_id));\n\n assert!(res.is_ok());\n\n\n\n let res = Account::new(stage, &invalid_signers, amount, Some(tx_id));\n\n assert!(res.is_err());\n\n}\n\n\n", "file_path": "models/src/account.rs", "rank": 82, "score": 113326.8236809955 }, { "content": "#[test]\n\nfn test_account_storable() {\n\n use crate::wallet::Wallet;\n\n use store::memory::MemoryStoreFactory;\n\n\n\n let max_value_size = 1 << 10;\n\n let max_size = 1 << 30;\n\n\n\n let mut store = MemoryStoreFactory::new_unqlite(max_value_size, max_size).unwrap();\n\n\n\n let stage = Stage::random().unwrap();\n\n\n\n let wallet = Wallet::new(stage).unwrap();\n\n let weight = 1;\n\n let signer = wallet.to_signer(weight).unwrap();\n\n let mut signers = Signers::new().unwrap();\n\n signers.set_threshold(weight).unwrap();\n\n signers.add(&signer).unwrap();\n\n\n\n let mut account = Account::new_eve(stage, &signers).unwrap();\n\n let transaction = Transaction::new_eve(stage, &account.address()).unwrap();\n", "file_path": "models/src/account.rs", "rank": 83, "score": 113326.8236809955 }, { "content": "#[test]\n\nfn test_account_validate() {\n\n use crate::signer::Signer;\n\n use crypto::ecc::ed25519::PublicKey;\n\n use crypto::random::Random;\n\n\n\n let stage = Stage::random().unwrap();\n\n let amount = Random::u64().unwrap();\n\n let mut valid_signers = Signers::new().unwrap();\n\n\n\n let mut invalid_address = Address::random().unwrap();\n\n while invalid_address == valid_signers.address {\n\n invalid_address = Address::random().unwrap();\n\n }\n\n\n\n for _ in 0..10 {\n\n let public_key = PublicKey::random().unwrap();\n\n let weight = Random::u64_range(1, 11).unwrap();\n\n let signer = Signer { public_key, weight };\n\n\n\n valid_signers.add(&signer).unwrap();\n", "file_path": "models/src/account.rs", "rank": 84, "score": 113326.8236809955 }, { "content": "#[test]\n\nfn test_transaction_mine() {\n\n use crypto::random::Random;\n\n\n\n for _ in 0..10 {\n\n let mut transaction = Transaction::default();\n\n let address = Address::random().unwrap();\n\n let difficulty = Random::u64_range(1, 10).unwrap();\n\n\n\n transaction.set_coinbase(&address, difficulty).unwrap();\n\n\n\n let res = transaction.mine();\n\n assert!(res.is_ok());\n\n\n\n let res = transaction.validate_coinbase();\n\n assert!(res.is_ok());\n\n\n\n let res = transaction.validate_mined();\n\n assert!(res.is_ok());\n\n\n\n let mut coinbase = transaction.coinbase.unwrap();\n", "file_path": "models/src/transaction.rs", "rank": 85, "score": 112905.14948806891 }, { "content": "#[test]\n\nfn test_transaction_times() {\n\n let mut transaction = Transaction::new().unwrap();\n\n\n\n let res = transaction.validate_times();\n\n assert!(res.is_ok());\n\n\n\n let invalid_date = \"2012-12-12T00:00:00Z\";\n\n let invalid_timestamp = Timestamp::parse(invalid_date).unwrap();\n\n\n\n let res = transaction.set_time(invalid_timestamp);\n\n assert!(res.is_err());\n\n let res = transaction.set_locktime(invalid_timestamp);\n\n assert!(res.is_err());\n\n\n\n transaction.time = Timestamp::now();\n\n let res = transaction.validate_times();\n\n assert!(res.is_ok());\n\n\n\n let invalid_locktime_i64 = transaction.time.to_i64() - 1_000;\n\n let invalid_locktime = Timestamp::from_i64(invalid_locktime_i64).unwrap();\n\n\n\n transaction.locktime = Some(invalid_locktime);\n\n let res = transaction.validate_times();\n\n assert!(res.is_err());\n\n}\n\n\n", "file_path": "models/src/transaction.rs", "rank": 86, "score": 112905.14948806891 }, { "content": "#[test]\n\nfn test_transaction_storable() {\n\n use store::memory::MemoryStoreFactory;\n\n\n\n let max_value_size = 1 << 10;\n\n let max_size = 1 << 30;\n\n\n\n let mut store = MemoryStoreFactory::new_unqlite(max_value_size, max_size).unwrap();\n\n\n\n let stage = Stage::random().unwrap();\n\n\n\n let items: Vec<(Digest, Transaction)> = (0..10)\n\n .map(|_| {\n\n let mut transaction = Transaction::new().unwrap();\n\n transaction.stage = stage;\n\n transaction.update_id().unwrap();\n\n\n\n (transaction.id, transaction)\n\n })\n\n .collect();\n\n\n", "file_path": "models/src/transaction.rs", "rank": 87, "score": 112905.14948806891 }, { "content": "#[test]\n\nfn test_transaction_balance() {\n\n use crate::account::Account;\n\n use crate::signer::Signer;\n\n use crate::signers::Signers;\n\n use crypto::random::Random;\n\n\n\n let stage = Stage::random().unwrap();\n\n let mut transaction = Transaction::new().unwrap();\n\n transaction.stage = stage;\n\n transaction.update_id().unwrap();\n\n\n\n let mut input_balance = 0;\n\n let mut output_balance = 0;\n\n let mut expected_balance = 0i64;\n\n\n\n for _ in 0..10 {\n\n let public_key = PublicKey::random().unwrap();\n\n let weight = Random::u64().unwrap();\n\n let threshold = weight;\n\n\n", "file_path": "models/src/transaction.rs", "rank": 88, "score": 112905.14948806891 }, { "content": "#[test]\n\nfn test_transaction_id() {\n\n let mut transaction = Transaction::new().unwrap();\n\n\n\n let res = transaction.validate_id();\n\n assert!(res.is_ok());\n\n\n\n let mut invalid_id = Digest::random().unwrap();\n\n while invalid_id == transaction.id {\n\n invalid_id = Digest::random().unwrap();\n\n }\n\n\n\n transaction.id = invalid_id;\n\n\n\n let res = transaction.validate_id();\n\n assert!(res.is_err());\n\n}\n\n\n", "file_path": "models/src/transaction.rs", "rank": 89, "score": 112905.14948806891 }, { "content": "#[test]\n\nfn test_transaction_new() {\n\n let res = Transaction::new();\n\n assert!(res.is_ok());\n\n\n\n let transaction = res.unwrap();\n\n let res = transaction.validate();\n\n assert!(res.is_ok())\n\n}\n\n\n", "file_path": "models/src/transaction.rs", "rank": 90, "score": 112905.14948806891 }, { "content": "#[test]\n\nfn test_transaction_coinbase() {\n\n use crypto::random::Random;\n\n\n\n let invalid_difficulty = 0;\n\n\n\n for _ in 0..10 {\n\n let mut transaction = Transaction::default();\n\n let address = Address::random().unwrap();\n\n let valid_difficulty = Random::u64_range(1, 10).unwrap();\n\n\n\n let res = transaction.validate_coinbase();\n\n assert!(res.is_ok());\n\n\n\n let res = transaction.set_coinbase(&address, invalid_difficulty);\n\n assert!(res.is_err());\n\n\n\n let res = transaction.set_coinbase(&address, valid_difficulty);\n\n assert!(res.is_ok());\n\n\n\n let res = transaction.validate_coinbase();\n\n assert!(res.is_ok());\n\n }\n\n}\n\n\n", "file_path": "models/src/transaction.rs", "rank": 91, "score": 112905.14948806891 }, { "content": "#[test]\n\nfn test_transaction_eve() {\n\n let stage = Stage::random().unwrap();\n\n let address = Address::random().unwrap();\n\n\n\n let res = Transaction::new_eve(stage, &address);\n\n assert!(res.is_ok());\n\n\n\n let mut eve_transaction = res.unwrap();\n\n\n\n let res = eve_transaction.validate();\n\n assert!(res.is_ok());\n\n\n\n let res = eve_transaction.is_eve();\n\n assert!(res.is_ok());\n\n assert!(res.unwrap());\n\n\n\n eve_transaction.distance = 1;\n\n\n\n let res = eve_transaction.validate();\n\n assert!(res.is_err());\n\n\n\n let transaction = Transaction::new().unwrap();\n\n let res = transaction.is_eve();\n\n assert!(res.is_ok());\n\n assert!(!res.unwrap());\n\n}\n\n\n", "file_path": "models/src/transaction.rs", "rank": 92, "score": 112905.14948806891 }, { "content": "#[test]\n\nfn test_account_new_eve() {\n\n use crate::signer::Signer;\n\n use crypto::ecc::ed25519::PublicKey;\n\n use crypto::random::Random;\n\n\n\n let stage = Stage::random().unwrap();\n\n let mut valid_signers = Signers::new().unwrap();\n\n\n\n for _ in 0..10 {\n\n let public_key = PublicKey::random().unwrap();\n\n let weight = Random::u64_range(1, 11).unwrap();\n\n let signer = Signer { public_key, weight };\n\n\n\n valid_signers.add(&signer).unwrap();\n\n }\n\n\n\n let mut invalid_signers = valid_signers.clone();\n\n invalid_signers.threshold = invalid_signers.total_weight() + 1;\n\n\n\n let res = Account::new_eve(stage, &invalid_signers);\n", "file_path": "models/src/account.rs", "rank": 93, "score": 111084.27499643908 }, { "content": "/// `store_path` returns an Alsacoin store path.\n\npub fn store_path(stage: Stage) -> Result<String> {\n\n let mut path = env::current_dir()?;\n\n path.push(\"data\");\n\n path.push(\"store\");\n\n path.push(&format!(\"{}.store\", stage));\n\n\n\n if let Some(path) = path.to_str() {\n\n Ok(path.into())\n\n } else {\n\n let err = Error::InvalidPath;\n\n Err(err)\n\n }\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 94, "score": 109888.73040978287 }, { "content": "/// `config_path` returns an Alsacoin config path.\n\npub fn config_path(stage: Stage) -> Result<String> {\n\n let mut path = env::current_dir()?;\n\n path.push(\"data\");\n\n path.push(\"config\");\n\n path.push(&format!(\"{}.toml\", stage));\n\n\n\n if let Some(path) = path.to_str() {\n\n Ok(path.into())\n\n } else {\n\n let err = Error::InvalidPath;\n\n Err(err)\n\n }\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 95, "score": 109888.73040978287 }, { "content": "/// `read_config` reads an Alsacoin config.\n\npub fn read_config(stage: Stage) -> Result<Config> {\n\n let path = config_path(stage)?;\n\n let buf = read_file(&path)?;\n\n\n\n let contents = String::from_utf8(buf)?;\n\n Config::from_toml(&contents).map_err(|e| e.into())\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 96, "score": 109883.76875725621 }, { "content": "/// `create_store` creates an Alsacoin store.\n\npub fn create_store(stage: Stage, config: &Config) -> Result<()> {\n\n config.validate()?;\n\n\n\n let kind = config.store.kind.clone().unwrap();\n\n\n\n let path = if &kind == \"persistent\" {\n\n Some(store_path(stage)?)\n\n } else {\n\n None\n\n };\n\n\n\n StoreFactory::create(path, &config.store)\n\n .map(|_| ())\n\n .map_err(|e| e.into())\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 97, "score": 105635.91813638352 }, { "content": "/// `write_config` writes an Alsacoin config.\n\npub fn write_config(stage: Stage, config: &Config) -> Result<()> {\n\n config.validate()?;\n\n\n\n let path = config_path(stage)?;\n\n let buf = config.to_toml()?.into_bytes();\n\n\n\n write_file(&path, &buf)\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 98, "score": 105635.91813638352 }, { "content": "/// `open_pool` opens an Alsacoin pool.\n\npub fn open_pool(config: &Config) -> Result<UnQLiteStore> {\n\n config.validate()?;\n\n\n\n PoolFactory::create(&config.pool).map_err(|e| e.into())\n\n}\n\n\n", "file_path": "cli/src/common.rs", "rank": 99, "score": 104356.43929893486 } ]
Rust
src/test_md.rs
puru1761/kcapi-sys
ef3a7e91e6fb5e355fb41e75464322dd13b69349
/* * $Id$ * * Copyright (c) 2021, Purushottam A. Kulkarni. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and * or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE * */ #[cfg(test)] mod tests { use std::convert::TryInto; use std::ffi::CString; use crate::{ kcapi_handle, kcapi_md_digest, kcapi_md_digestsize, kcapi_md_hmac_sha1, kcapi_md_hmac_sha224, kcapi_md_hmac_sha256, kcapi_md_hmac_sha384, kcapi_md_hmac_sha512, kcapi_md_init, kcapi_md_setkey, kcapi_md_sha1, kcapi_md_sha224, kcapi_md_sha256, kcapi_md_sha384, kcapi_md_sha512, }; const SIZE_SHA1: usize = 20; const SIZE_SHA224: usize = 28; const SIZE_SHA256: usize = 32; const SIZE_SHA384: usize = 48; const SIZE_SHA512: usize = 64; #[test] fn test_md_init() { let ret: i32; let alg = CString::new("sha1").expect("Failed to convert CString"); unsafe { let mut handle = Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle; ret = kcapi_md_init(&mut handle as *mut _, alg.as_ptr(), 0); } assert_eq!(ret, 0); } #[test] fn test_md_digest() { let inp = [0x41u8; 16]; let mut out = [0u8; SIZE_SHA256]; let alg = std::ffi::CString::new("sha256").expect("Failed to convert to CString"); let out_exp = [ 0x99, 0x12, 0x4, 0xfb, 0xa2, 0xb6, 0x21, 0x6d, 0x47, 0x62, 0x82, 0xd3, 0x75, 0xab, 0x88, 0xd2, 0xe, 0x61, 0x8, 0xd1, 0x9, 0xae, 0xcd, 0xed, 0x97, 0xef, 0x42, 0x4d, 0xdd, 0x11, 0x47, 0x6, ]; let mut ret: i64; unsafe { let mut handle = Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle; ret = (kcapi_md_init(&mut handle as *mut _, alg.as_ptr(), 0)) .try_into() .expect("Failed to convert i32 to i64"); assert_eq!(ret, 0); ret = (kcapi_md_digestsize(handle)) .try_into() .expect("Failed to convert i32 into i64"); assert_eq!(ret, SIZE_SHA256 as i64); ret = kcapi_md_digest( handle, inp.as_ptr(), inp.len() as u64, out.as_mut_ptr(), out.len() as u64, ); assert_eq!(ret, SIZE_SHA256 as i64); } assert_eq!(out_exp, out); } #[test] fn test_md_keyed_digest() { let inp = [0x41u8; 16]; let mut out = [0u8; SIZE_SHA256]; let key = [0u8; 16]; let alg = std::ffi::CString::new("hmac(sha256)").expect("Failed to convert to CString"); let out_exp = [ 0x4a, 0x81, 0xd6, 0x13, 0xb0, 0xe, 0x91, 0x9e, 0x8a, 0xd9, 0x63, 0x78, 0x88, 0xe6, 0xa4, 0xfe, 0x8, 0x22, 0x4a, 0xb6, 0x48, 0x4b, 0xa, 0x37, 0x47, 0xa6, 0xa6, 0x62, 0xb6, 0xa2, 0x99, 0xd, ]; let mut ret: i64; unsafe { let mut handle = Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle; ret = (kcapi_md_init(&mut handle as *mut _, alg.as_ptr(), 0)) .try_into() .expect("Failed to convert i32 to i64"); assert_eq!(ret, 0); ret = (kcapi_md_digestsize(handle)) .try_into() .expect("Failed to convert i32 into i64"); assert_eq!(ret, SIZE_SHA256 as i64); ret = (kcapi_md_setkey(handle, key.as_ptr(), key.len() as u32)) .try_into() .expect("Failed to convert i32 to i64"); assert_eq!(ret, 0); ret = kcapi_md_digest( handle, inp.as_ptr(), inp.len() as u64, out.as_mut_ptr(), out.len() as u64, ); assert_eq!(ret, SIZE_SHA256 as i64); } assert_eq!(out_exp, out); } #[test] fn test_sha1() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA1]; let out_exp = [ 0x19, 0xb1, 0x92, 0x8d, 0x58, 0xa2, 0x3, 0xd, 0x8, 0x2, 0x3f, 0x3d, 0x70, 0x54, 0x51, 0x6d, 0xbc, 0x18, 0x6f, 0x20, ]; let ret: i64; unsafe { ret = kcapi_md_sha1( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA1 as i64); } #[test] fn test_sha224() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA224]; let out_exp = [ 0xcb, 0xa2, 0x25, 0xbd, 0x2d, 0xed, 0x28, 0xf5, 0xb9, 0xb3, 0xfa, 0xee, 0x8e, 0xca, 0xed, 0x82, 0xba, 0x8, 0xd2, 0xbb, 0x5a, 0xee, 0x2c, 0x37, 0x40, 0xe7, 0xff, 0x8a, ]; let ret: i64; unsafe { ret = kcapi_md_sha224( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA224 as i64); } #[test] fn test_sha256() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA256]; let out_exp = [ 0x99, 0x12, 0x4, 0xfb, 0xa2, 0xb6, 0x21, 0x6d, 0x47, 0x62, 0x82, 0xd3, 0x75, 0xab, 0x88, 0xd2, 0xe, 0x61, 0x8, 0xd1, 0x9, 0xae, 0xcd, 0xed, 0x97, 0xef, 0x42, 0x4d, 0xdd, 0x11, 0x47, 0x6, ]; let ret: i64; unsafe { ret = kcapi_md_sha256( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA256 as i64); } #[test] fn test_sha384() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA384]; let out_exp = [ 0x62, 0x5e, 0x92, 0x3, 0x4, 0x7c, 0x52, 0xa1, 0xe2, 0x90, 0x18, 0x9b, 0xd1, 0x5a, 0xbf, 0x17, 0xe, 0xd8, 0x86, 0xa3, 0x31, 0x90, 0x80, 0x3e, 0x4, 0x40, 0x2f, 0x4d, 0x48, 0xb1, 0xf, 0xe0, 0x5a, 0xb1, 0x21, 0x97, 0xf9, 0xca, 0xc2, 0x53, 0x74, 0x9a, 0x5f, 0xde, 0x8, 0x22, 0xc7, 0x34, ]; let ret: i64; unsafe { ret = kcapi_md_sha384( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA384 as i64); } #[test] fn test_sha512() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA512]; let out_exp = [ 0x67, 0x3a, 0x88, 0x7f, 0xe1, 0x68, 0xc, 0x26, 0xd8, 0x1d, 0x46, 0xd2, 0x76, 0xe6, 0xb, 0x4d, 0xfd, 0x9c, 0x16, 0x60, 0x34, 0xe7, 0x2f, 0x69, 0xd6, 0x8a, 0x77, 0xf4, 0xb0, 0xf7, 0x41, 0x21, 0xd4, 0x4b, 0x79, 0x68, 0xde, 0x8f, 0x55, 0xba, 0x26, 0x15, 0xf6, 0xe7, 0x20, 0xa2, 0xc7, 0x43, 0x99, 0x9c, 0xbc, 0xc0, 0x7a, 0x4, 0x36, 0x6d, 0x9f, 0x36, 0x46, 0xbc, 0xbc, 0x11, 0x98, 0xce, ]; let ret: i64; unsafe { ret = kcapi_md_sha512( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA512 as i64); } #[test] fn test_hmac_sha1() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA1]; let out_exp = [ 0x41, 0x85, 0xf6, 0xa4, 0xc3, 0xab, 0x30, 0xf9, 0xa8, 0x5, 0x96, 0x45, 0x6f, 0x5d, 0x61, 0x18, 0xd4, 0xfe, 0xe0, 0xd6, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha1( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA1 as i64); } #[test] fn test_hmac_sha224() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA224]; let out_exp = [ 0x5d, 0x8c, 0x6c, 0x1f, 0xf2, 0x97, 0xbf, 0x59, 0x3f, 0x59, 0x1c, 0xf3, 0x4d, 0x3c, 0x96, 0x36, 0xde, 0x33, 0x11, 0x5f, 0xb1, 0x3e, 0xa5, 0x75, 0x8c, 0xfc, 0xdc, 0x6, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha224( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA224 as i64); } #[test] fn test_hmac_sha256() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA256]; let out_exp = [ 0x4a, 0x81, 0xd6, 0x13, 0xb0, 0xe, 0x91, 0x9e, 0x8a, 0xd9, 0x63, 0x78, 0x88, 0xe6, 0xa4, 0xfe, 0x8, 0x22, 0x4a, 0xb6, 0x48, 0x4b, 0xa, 0x37, 0x47, 0xa6, 0xa6, 0x62, 0xb6, 0xa2, 0x99, 0xd, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha256( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA256 as i64); } #[test] fn test_hmac_sha384() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA384]; let out_exp = [ 0x1b, 0xcc, 0x5, 0x6f, 0x74, 0xc9, 0x34, 0xce, 0x5f, 0xe, 0xc4, 0xf5, 0x45, 0x3d, 0x1c, 0xef, 0x7c, 0x1b, 0x8d, 0xae, 0xa7, 0x6d, 0xe7, 0xc7, 0x9e, 0x7e, 0xe, 0x68, 0x4e, 0x95, 0x6d, 0xd8, 0x52, 0x11, 0x20, 0xd, 0x99, 0x93, 0x63, 0x89, 0x4f, 0xfd, 0x37, 0xc, 0xdd, 0x27, 0x75, 0xc8, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha384( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA384 as i64); } #[test] fn test_hmac_sha512() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA512]; let out_exp = [ 0x44, 0xdb, 0xf1, 0xae, 0x7d, 0xcd, 0xc0, 0x5f, 0xa6, 0x9b, 0x30, 0x44, 0x99, 0xfa, 0x19, 0x82, 0x40, 0xb, 0x94, 0xc0, 0xe9, 0x9, 0xcb, 0xc5, 0xf5, 0x74, 0x66, 0x84, 0x45, 0x5b, 0x31, 0xf8, 0x8e, 0x94, 0x14, 0x8c, 0xe2, 0xa4, 0x7, 0xa7, 0x58, 0xd2, 0x14, 0x11, 0x85, 0x8b, 0xa4, 0x50, 0x4c, 0xaa, 0x2e, 0xa1, 0x70, 0xa3, 0x1b, 0xec, 0x87, 0xab, 0xb6, 0x54, 0xf4, 0xe9, 0xd, 0x48, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha512( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA512 as i64); } }
/* * $Id$ * * Copyright (c) 2021, Purushottam A. Kulkarni. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and * or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE * */ #[cfg(test)] mod tests { use std::convert::TryInto; use std::ffi::CString; use crate::{ kcapi_handle, kcapi_md_digest, kcapi_md_digestsize, kcapi_md_hmac_sha1, kcapi_md_hmac_sha224, kcapi_md_hmac_sha256, kcapi_md_hmac_sha384, kcapi_md_hmac_sha512, kcapi_md_init, kcapi_md_setkey, kcapi_md_sha1, kcapi_md_sha224, kcapi_md_sha256, kcapi_md_sha384, kcapi_md_sha512, }; const SIZE_SHA1: usize = 20; const SIZE_SHA224: usize = 28; const SIZE_SHA256: usize = 32; const SIZE_SHA384: usize = 48; const SIZE_SHA512: usize = 64; #[test] fn test_md_init() { let ret: i32; let alg = CString::new("sha1").expect("Failed to convert CString"); unsafe { let mut handle = Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle; ret = kcapi_md_init(&mut handle as *mut _, alg.as_ptr(), 0); } assert_eq!(ret, 0); } #[test] fn test_md_digest() { let inp = [0x41u8; 16]; let mut out = [0u8; SIZE_SHA256]; let alg = std::ffi::CString::new("sha256").expect("Failed to convert to CString"); let out_exp = [ 0x99, 0x12, 0x4, 0xfb, 0xa2, 0xb6, 0x21, 0x6d, 0x47, 0x62, 0x82, 0xd3, 0x75, 0xab, 0x88, 0xd2, 0xe, 0x61, 0x8, 0xd1, 0x9, 0xae, 0xcd, 0xed, 0x97, 0xef, 0x42, 0x4d, 0xdd, 0x11, 0x47, 0x6, ]; let mut ret: i64; unsafe { let mut handle = Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle; ret = (kcapi_md_init(&mut handle as *mut _, alg.as_ptr(), 0)) .try_into() .expect("Failed to convert i32 to i64"); assert_eq!(ret, 0); ret = (kcapi_md_digestsize(handle)) .try_into() .expect("Failed to convert i32 into i64"); assert_eq!(ret, SIZE_SHA256 as i64); ret = kcapi_md_digest( handle, inp.as_ptr(), inp.len() as u64, out.as_mut_ptr(), out.len() as u64, ); assert_eq!(ret, SIZE_SHA256 as i64); } assert_eq!(out_exp, out); } #[test] fn test_md_keyed_digest() { let inp = [0x41u8; 16]; let mut out = [0u8; SIZE_SHA256]; let key = [0u8; 16]; let alg = std::ffi::CString::new("hmac(sha256)").expect("Failed to convert to CString"); let out_exp = [ 0x4a, 0x81, 0xd6, 0x13, 0xb0, 0xe, 0x91, 0x9e, 0x8a, 0xd9, 0x63, 0x78, 0x88, 0xe6, 0xa4, 0xfe, 0x8, 0x22, 0x4a, 0xb6, 0x48, 0x4b, 0xa, 0x37, 0x47, 0xa6, 0xa6, 0x62, 0xb6, 0xa2, 0x99, 0xd, ]; let mut ret: i64; unsafe { let mut handle = Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle; ret = (kcapi_md_init(&mut handle as *mut _, alg.as_ptr(), 0)) .try_into() .expect("Failed to convert i32 to i64"); assert_eq!(ret, 0); ret = (kcapi_md_digestsize(handle)) .try_into() .expect("Failed to convert i32 into i64"); assert_eq!(ret, SIZE_SHA256 as i64); ret = (kcapi_md_setkey(handle, key.as_ptr(), key.len() as u32)) .try_into() .expect("Failed to convert i32 to i64"); assert_eq!(ret, 0); ret = kcapi_md_digest( handle, inp.as_ptr(), inp.len() as u64, out.as_mut_ptr(), out.len() as u64, ); assert_eq!(ret, SIZE_SHA256 as i64); } assert_eq!(out_exp, out); } #[test] fn test_sha1() {
#[test] fn test_sha224() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA224]; let out_exp = [ 0xcb, 0xa2, 0x25, 0xbd, 0x2d, 0xed, 0x28, 0xf5, 0xb9, 0xb3, 0xfa, 0xee, 0x8e, 0xca, 0xed, 0x82, 0xba, 0x8, 0xd2, 0xbb, 0x5a, 0xee, 0x2c, 0x37, 0x40, 0xe7, 0xff, 0x8a, ]; let ret: i64; unsafe { ret = kcapi_md_sha224( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA224 as i64); } #[test] fn test_sha256() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA256]; let out_exp = [ 0x99, 0x12, 0x4, 0xfb, 0xa2, 0xb6, 0x21, 0x6d, 0x47, 0x62, 0x82, 0xd3, 0x75, 0xab, 0x88, 0xd2, 0xe, 0x61, 0x8, 0xd1, 0x9, 0xae, 0xcd, 0xed, 0x97, 0xef, 0x42, 0x4d, 0xdd, 0x11, 0x47, 0x6, ]; let ret: i64; unsafe { ret = kcapi_md_sha256( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA256 as i64); } #[test] fn test_sha384() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA384]; let out_exp = [ 0x62, 0x5e, 0x92, 0x3, 0x4, 0x7c, 0x52, 0xa1, 0xe2, 0x90, 0x18, 0x9b, 0xd1, 0x5a, 0xbf, 0x17, 0xe, 0xd8, 0x86, 0xa3, 0x31, 0x90, 0x80, 0x3e, 0x4, 0x40, 0x2f, 0x4d, 0x48, 0xb1, 0xf, 0xe0, 0x5a, 0xb1, 0x21, 0x97, 0xf9, 0xca, 0xc2, 0x53, 0x74, 0x9a, 0x5f, 0xde, 0x8, 0x22, 0xc7, 0x34, ]; let ret: i64; unsafe { ret = kcapi_md_sha384( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA384 as i64); } #[test] fn test_sha512() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA512]; let out_exp = [ 0x67, 0x3a, 0x88, 0x7f, 0xe1, 0x68, 0xc, 0x26, 0xd8, 0x1d, 0x46, 0xd2, 0x76, 0xe6, 0xb, 0x4d, 0xfd, 0x9c, 0x16, 0x60, 0x34, 0xe7, 0x2f, 0x69, 0xd6, 0x8a, 0x77, 0xf4, 0xb0, 0xf7, 0x41, 0x21, 0xd4, 0x4b, 0x79, 0x68, 0xde, 0x8f, 0x55, 0xba, 0x26, 0x15, 0xf6, 0xe7, 0x20, 0xa2, 0xc7, 0x43, 0x99, 0x9c, 0xbc, 0xc0, 0x7a, 0x4, 0x36, 0x6d, 0x9f, 0x36, 0x46, 0xbc, 0xbc, 0x11, 0x98, 0xce, ]; let ret: i64; unsafe { ret = kcapi_md_sha512( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA512 as i64); } #[test] fn test_hmac_sha1() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA1]; let out_exp = [ 0x41, 0x85, 0xf6, 0xa4, 0xc3, 0xab, 0x30, 0xf9, 0xa8, 0x5, 0x96, 0x45, 0x6f, 0x5d, 0x61, 0x18, 0xd4, 0xfe, 0xe0, 0xd6, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha1( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA1 as i64); } #[test] fn test_hmac_sha224() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA224]; let out_exp = [ 0x5d, 0x8c, 0x6c, 0x1f, 0xf2, 0x97, 0xbf, 0x59, 0x3f, 0x59, 0x1c, 0xf3, 0x4d, 0x3c, 0x96, 0x36, 0xde, 0x33, 0x11, 0x5f, 0xb1, 0x3e, 0xa5, 0x75, 0x8c, 0xfc, 0xdc, 0x6, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha224( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA224 as i64); } #[test] fn test_hmac_sha256() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA256]; let out_exp = [ 0x4a, 0x81, 0xd6, 0x13, 0xb0, 0xe, 0x91, 0x9e, 0x8a, 0xd9, 0x63, 0x78, 0x88, 0xe6, 0xa4, 0xfe, 0x8, 0x22, 0x4a, 0xb6, 0x48, 0x4b, 0xa, 0x37, 0x47, 0xa6, 0xa6, 0x62, 0xb6, 0xa2, 0x99, 0xd, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha256( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA256 as i64); } #[test] fn test_hmac_sha384() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA384]; let out_exp = [ 0x1b, 0xcc, 0x5, 0x6f, 0x74, 0xc9, 0x34, 0xce, 0x5f, 0xe, 0xc4, 0xf5, 0x45, 0x3d, 0x1c, 0xef, 0x7c, 0x1b, 0x8d, 0xae, 0xa7, 0x6d, 0xe7, 0xc7, 0x9e, 0x7e, 0xe, 0x68, 0x4e, 0x95, 0x6d, 0xd8, 0x52, 0x11, 0x20, 0xd, 0x99, 0x93, 0x63, 0x89, 0x4f, 0xfd, 0x37, 0xc, 0xdd, 0x27, 0x75, 0xc8, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha384( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA384 as i64); } #[test] fn test_hmac_sha512() { let inp = [0x41u8; 16]; let key = [0u8; 16]; let out = [0u8; SIZE_SHA512]; let out_exp = [ 0x44, 0xdb, 0xf1, 0xae, 0x7d, 0xcd, 0xc0, 0x5f, 0xa6, 0x9b, 0x30, 0x44, 0x99, 0xfa, 0x19, 0x82, 0x40, 0xb, 0x94, 0xc0, 0xe9, 0x9, 0xcb, 0xc5, 0xf5, 0x74, 0x66, 0x84, 0x45, 0x5b, 0x31, 0xf8, 0x8e, 0x94, 0x14, 0x8c, 0xe2, 0xa4, 0x7, 0xa7, 0x58, 0xd2, 0x14, 0x11, 0x85, 0x8b, 0xa4, 0x50, 0x4c, 0xaa, 0x2e, 0xa1, 0x70, 0xa3, 0x1b, 0xec, 0x87, 0xab, 0xb6, 0x54, 0xf4, 0xe9, 0xd, 0x48, ]; let ret: i64; unsafe { ret = kcapi_md_hmac_sha512( key.as_ptr(), key.len() as u32, inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA512 as i64); } }
let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA1]; let out_exp = [ 0x19, 0xb1, 0x92, 0x8d, 0x58, 0xa2, 0x3, 0xd, 0x8, 0x2, 0x3f, 0x3d, 0x70, 0x54, 0x51, 0x6d, 0xbc, 0x18, 0x6f, 0x20, ]; let ret: i64; unsafe { ret = kcapi_md_sha1( inp.as_ptr(), (inp.len() as u32).into(), out.as_ptr() as *mut u8, (out.len() as u32).into(), ); } assert_eq!(out_exp, out); assert_eq!(ret, SIZE_SHA1 as i64); }
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let out_path = PathBuf::from(env::var(\"OUT_DIR\").unwrap());\n\n let include_path = out_path.join(\"include\");\n\n let wrapper_h_path = include_path.join(\"wrapper.h\");\n\n let build_path = out_path.join(\"libkcapi\");\n\n\n\n /*\n\n * Copy the libkcapi sources to OUT_DIR.\n\n * We need to do this because the libkcapi sources are modified by automake,\n\n * and this causes package verification errors on running cargo publish.\n\n */\n\n let mut opts = fs_extra::dir::CopyOptions::new();\n\n opts.copy_inside = true;\n\n opts.overwrite = true;\n\n match fs_extra::dir::copy(\"libkcapi\", out_path.clone(), &opts) {\n\n Ok(_ret) => {}\n\n Err(e) => panic!(\"Failed to copy libkcapi to {}: {}\", build_path.display(), e),\n\n };\n\n\n\n let dst = autotools::Config::new(build_path)\n", "file_path": "build.rs", "rank": 0, "score": 29631.512016943172 }, { "content": " * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n * POSSIBILITY OF SUCH DAMAGE\n\n *\n\n */\n\n\n\n#[cfg(test)]\n\npub mod tests {\n\n\n\n use crate::kcapi_handle;\n\n use std::ffi::CString;\n\n\n", "file_path": "src/test_akcipher.rs", "rank": 1, "score": 11998.98246965501 }, { "content": " * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n * POSSIBILITY OF SUCH DAMAGE\n\n *\n\n */\n\n\n\n#[cfg(test)]\n\npub mod tests {\n\n use std::convert::TryInto;\n\n use std::ffi::CString;\n\n\n\n use crate::{\n", "file_path": "src/test_aead.rs", "rank": 3, "score": 11998.14118789109 }, { "content": " * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n * POSSIBILITY OF SUCH DAMAGE\n\n *\n\n */\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::ffi::CString;\n\n\n\n #[test]\n\n fn test_ctr_kdf() {\n", "file_path": "src/test_kdf.rs", "rank": 4, "score": 11996.316561464651 }, { "content": " * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n * POSSIBILITY OF SUCH DAMAGE\n\n *\n\n */\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::{convert::TryInto, ffi::CString};\n\n\n\n use crate::{\n\n kcapi_handle, kcapi_rng_destroy, kcapi_rng_generate, kcapi_rng_get_bytes, kcapi_rng_init,\n", "file_path": "src/test_rng.rs", "rank": 5, "score": 11993.20011459364 }, { "content": " * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n * POSSIBILITY OF SUCH DAMAGE\n\n *\n\n */\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::{convert::TryInto, ffi::CString};\n\n\n\n use crate::{\n\n kcapi_cipher_dec_aes_cbc, kcapi_cipher_dec_aes_ctr, kcapi_cipher_decrypt,\n", "file_path": "src/test_skcipher.rs", "rank": 6, "score": 11992.58244242841 }, { "content": "/*\n\n * $Id$\n\n *\n\n * Copyright (c) 2021, Purushottam A. Kulkarni.\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions are met:\n\n *\n\n * 1. Redistributions of source code must retain the above copyright notice,\n\n * this list of conditions and the following disclaimer.\n\n *\n\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n\n * this list of conditions and the following disclaimer in the documentation and\n\n * or other materials provided with the distribution.\n\n *\n\n * 3. Neither the name of the copyright holder nor the names of its contributors\n\n * may be used to endorse or promote products derived from this software without\n\n * specific prior written permission.\n\n *\n", "file_path": "src/test_rng.rs", "rank": 7, "score": 11988.365162717848 }, { "content": "/*\n\n * $Id$\n\n *\n\n * Copyright (c) 2021, Purushottam A. Kulkarni.\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions are met:\n\n *\n\n * 1. Redistributions of source code must retain the above copyright notice,\n\n * this list of conditions and the following disclaimer.\n\n *\n\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n\n * this list of conditions and the following disclaimer in the documentation and\n\n * or other materials provided with the distribution.\n\n *\n\n * 3. Neither the name of the copyright holder nor the names of its contributors\n\n * may be used to endorse or promote products derived from this software without\n\n * specific prior written permission.\n\n *\n", "file_path": "src/test_aead.rs", "rank": 8, "score": 11988.365162717848 }, { "content": "/*\n\n * $Id$\n\n *\n\n * Copyright (c) 2021, Purushottam A. Kulkarni.\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions are met:\n\n *\n\n * 1. Redistributions of source code must retain the above copyright notice,\n\n * this list of conditions and the following disclaimer.\n\n *\n\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n\n * this list of conditions and the following disclaimer in the documentation and\n\n * or other materials provided with the distribution.\n\n *\n\n * 3. Neither the name of the copyright holder nor the names of its contributors\n\n * may be used to endorse or promote products derived from this software without\n\n * specific prior written permission.\n\n *\n", "file_path": "src/test_kdf.rs", "rank": 9, "score": 11988.365162717848 }, { "content": "/*\n\n * $Id$\n\n *\n\n * Copyright (c) 2021, Purushottam A. Kulkarni.\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions are met:\n\n *\n\n * 1. Redistributions of source code must retain the above copyright notice,\n\n * this list of conditions and the following disclaimer.\n\n *\n\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n\n * this list of conditions and the following disclaimer in the documentation and\n\n * or other materials provided with the distribution.\n\n *\n\n * 3. Neither the name of the copyright holder nor the names of its contributors\n\n * may be used to endorse or promote products derived from this software without\n\n * specific prior written permission.\n\n *\n", "file_path": "src/test_akcipher.rs", "rank": 11, "score": 11988.365162717848 }, { "content": "/*\n\n * $Id$\n\n *\n\n * Copyright (c) 2021, Purushottam A. Kulkarni.\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions are met:\n\n *\n\n * 1. Redistributions of source code must retain the above copyright notice,\n\n * this list of conditions and the following disclaimer.\n\n *\n\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n\n * this list of conditions and the following disclaimer in the documentation and\n\n * or other materials provided with the distribution.\n\n *\n\n * 3. Neither the name of the copyright holder nor the names of its contributors\n\n * may be used to endorse or promote products derived from this software without\n\n * specific prior written permission.\n\n *\n", "file_path": "src/test_skcipher.rs", "rank": 12, "score": 11988.365162717848 }, { "content": " let alg = CString::new(\"cbc(aes)\").expect(\"Failed to convert to Cstring\");\n\n\n\n let pt_exp = [0x41u8; AES_BLOCKSIZE as usize];\n\n\n\n let mut ret: i64;\n\n unsafe {\n\n let mut handle =\n\n Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle;\n\n\n\n ret = (kcapi_cipher_init(&mut handle as *mut _, alg.as_ptr(), 0))\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n ret = (kcapi_cipher_setkey(handle, key.as_ptr(), key.len() as u32))\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n ret = kcapi_cipher_decrypt(\n", "file_path": "src/test_skcipher.rs", "rank": 13, "score": 11924.938079756323 }, { "content": " ];\n\n\n\n let mut ret: i64;\n\n unsafe {\n\n let mut handle =\n\n Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle;\n\n\n\n ret = (kcapi_cipher_init(&mut handle as *mut _, alg.as_ptr(), 0))\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n ret = (kcapi_cipher_setkey(handle, key.as_ptr(), key.len() as u32))\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n ret = kcapi_cipher_encrypt(\n\n handle,\n\n pt.as_ptr(),\n", "file_path": "src/test_skcipher.rs", "rank": 15, "score": 11919.463200473534 }, { "content": " kcapi_rng_seed, kcapi_rng_setentropy,\n\n };\n\n\n\n #[test]\n\n fn test_rng_generate() {\n\n let mut seed = [0x41u8; 16];\n\n let mut out = [0u8; 16];\n\n let alg = CString::new(\"drbg_nopr_sha1\").expect(\"Unable to create CString\");\n\n\n\n let mut ret: i64;\n\n unsafe {\n\n let mut handle =\n\n Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle;\n\n\n\n ret = (kcapi_rng_init(&mut handle as *mut _, alg.as_ptr(), 0))\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n ret = (kcapi_rng_seed(handle, seed.as_mut_ptr(), seed.len() as u32))\n", "file_path": "src/test_rng.rs", "rank": 16, "score": 11919.267767816646 }, { "content": "\n\n let mut ret: i64;\n\n unsafe {\n\n let mut handle =\n\n Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle;\n\n\n\n ret = (kcapi_aead_init(&mut handle as *mut _, alg.as_ptr(), 0))\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n ret = (kcapi_aead_settaglen(handle, taglen as u32))\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n kcapi_aead_setassoclen(handle, assoclen as u64);\n\n\n\n let mut newiv = &mut [0u8; 48] as *mut u8;\n\n let mut newivlen: u32 = 0;\n", "file_path": "src/test_aead.rs", "rank": 17, "score": 11919.25242855244 }, { "content": " ret = (kcapi_pad_iv(\n\n handle,\n\n iv.as_ptr(),\n\n iv.len() as u32,\n\n &mut newiv as *mut _,\n\n &mut newivlen as *mut u32,\n\n ))\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n let inbuflen =\n\n kcapi_aead_inbuflen_dec(handle, ct.len() as u64, assoclen as u64, taglen as u64);\n\n let outbuflen =\n\n kcapi_aead_outbuflen_dec(handle, ct.len() as u64, assoclen as u64, taglen as u64);\n\n\n\n ret = (kcapi_aead_setkey(handle, key.as_ptr(), key.len() as u32))\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n", "file_path": "src/test_aead.rs", "rank": 18, "score": 11918.569873676248 }, { "content": " assert_eq!(ret, 256);\n\n }\n\n }\n\n\n\n #[test]\n\n #[ignore]\n\n fn test_ackipher_enc() {\n\n unsafe {\n\n let mut handle =\n\n Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle;\n\n\n\n let alg = CString::new(\"rsa\").expect(\"Failed to create CString\");\n\n\n\n let mut ret = crate::kcapi_akcipher_init(&mut handle as *mut _, alg.as_ptr(), 0);\n\n assert_eq!(ret, 0);\n\n\n\n ret = crate::kcapi_akcipher_setpubkey(handle, pubkey.as_ptr(), pubkey.len() as u32);\n\n assert_eq!(ret, 256);\n\n let mut out = [0u8; ct.len()];\n\n let inp = pt.clone();\n", "file_path": "src/test_akcipher.rs", "rank": 20, "score": 11917.84383489518 }, { "content": " .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n ret = kcapi_rng_generate(handle, out.as_mut_ptr(), out.len() as u64);\n\n assert_eq!(ret, out.len() as i64);\n\n\n\n kcapi_rng_destroy(handle);\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_rng_get_bytes() {\n\n let mut out = [0u8; 16];\n\n let mut out_next = [0u8; 16];\n\n\n\n let mut ret: i64;\n\n unsafe {\n\n ret = kcapi_rng_get_bytes(out.as_mut_ptr(), out.len() as u64);\n\n assert_eq!(ret, out.len() as i64);\n", "file_path": "src/test_rng.rs", "rank": 22, "score": 11916.687238820485 }, { "content": "\n\n let alg = CString::new(\"hmac(sha256)\").expect(\"Failed to allocate CString\");\n\n unsafe {\n\n let mut handle = Box::into_raw(Box::new(crate::kcapi_handle { _unused: [0u8; 0] }))\n\n as *mut crate::kcapi_handle;\n\n let mut ret = crate::kcapi_md_init(&mut handle as *mut _, alg.as_ptr(), 0);\n\n assert_eq!(ret, 0);\n\n\n\n ret = crate::kcapi_md_setkey(handle, CTR_KDF_KEY.as_ptr(), CTR_KDF_KEY.len() as u32);\n\n assert_eq!(ret, 0);\n\n\n\n let ret = crate::kcapi_kdf_ctr(\n\n handle,\n\n CTR_KDF_MSG.as_ptr(),\n\n CTR_KDF_MSG.len() as crate::size_t,\n\n out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n\n );\n\n assert_eq!(ret, 0);\n\n assert_eq!(CTR_KDF_EXP, out);\n", "file_path": "src/test_kdf.rs", "rank": 23, "score": 11915.748735314393 }, { "content": "\n\n ret = (kcapi_rng_init(&mut handle as *mut _, alg.as_ptr(), 0))\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n ret = kcapi_rng_setentropy(handle, ent.as_mut_ptr(), ent.len() as u32)\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n ret = kcapi_rng_seed(handle, seed.as_mut_ptr(), seed.len() as u32)\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n ret = kcapi_rng_generate(handle, out.as_mut_ptr(), 16);\n\n assert_eq!(ret, 16);\n\n }\n\n }\n", "file_path": "src/test_rng.rs", "rank": 24, "score": 11915.738518196345 }, { "content": " handle,\n\n ct.as_ptr(),\n\n ct.len() as u64,\n\n iv.as_ptr(),\n\n pt.as_mut_ptr(),\n\n pt.len() as u64,\n\n KCAPI_ACCESS_HEURISTIC as i32,\n\n );\n\n assert_eq!(ret, pt.len() as i64);\n\n }\n\n assert_eq!(pt_exp, pt);\n\n }\n\n\n\n #[test]\n\n fn test_aes128_cbc_enc() {\n\n let inp = [0x41u8; AES_BLOCKSIZE as usize];\n\n let key = [0u8; AES128_KEYSIZE as usize];\n\n let iv = [0u8; AES128_KEYSIZE as usize];\n\n\n\n let out = [0u8; AES_BLOCKSIZE as usize];\n", "file_path": "src/test_skcipher.rs", "rank": 25, "score": 11915.688694046015 }, { "content": " 0x9f, 0xd7, 0x64, 0x78, 0x2d, 0x80, 0xa9, 0xad, 0x58, 0x5b, 0xc4, 0xe, 0x1d, 0x7e, 0x73,\n\n 0xf7,\n\n ];\n\n\n\n #[test]\n\n #[ignore]\n\n fn test_akcipher_init() {\n\n unsafe {\n\n let mut handle =\n\n Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle;\n\n\n\n let alg = CString::new(\"rsa\").expect(\"Failed to create CString\");\n\n\n\n let mut ret = crate::kcapi_akcipher_init(&mut handle as *mut _, alg.as_ptr(), 0);\n\n assert_eq!(ret, 0);\n\n\n\n ret = crate::kcapi_akcipher_setkey(handle, privkey.as_ptr(), privkey.len() as u32);\n\n assert_eq!(ret, 256);\n\n\n\n ret = crate::kcapi_akcipher_setpubkey(handle, pubkey.as_ptr(), pubkey.len() as u32);\n", "file_path": "src/test_akcipher.rs", "rank": 26, "score": 11915.680403201624 }, { "content": " );\n\n assert_eq!(sig, out);\n\n assert_eq!(out.len(), ret64 as usize);\n\n }\n\n }\n\n\n\n #[test]\n\n #[ignore]\n\n fn test_akcipher_verify() {\n\n unsafe {\n\n let mut handle =\n\n Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle;\n\n\n\n let alg =\n\n CString::new(\"pkcs1pad(rsa-generic,sha256)\").expect(\"Failed to create CString\");\n\n\n\n let mut ret = crate::kcapi_akcipher_init(&mut handle as *mut _, alg.as_ptr(), 0);\n\n assert_eq!(ret, 0);\n\n\n\n let mut hash = [0u8; 32];\n", "file_path": "src/test_akcipher.rs", "rank": 27, "score": 11915.587825049637 }, { "content": "\n\n ret = kcapi_rng_get_bytes(out_next.as_mut_ptr(), out_next.len() as u64);\n\n assert_eq!(ret, out_next.len() as i64);\n\n\n\n assert_ne!(out, out_next);\n\n }\n\n }\n\n\n\n #[test]\n\n #[ignore]\n\n fn test_rng_setentropy() {\n\n let mut ent = [0x41u8; 16];\n\n let mut seed = [0x41u8; 16];\n\n let mut out = [0u8; 16];\n\n let alg = CString::new(\"drbg_nopr_sha1\").expect(\"Unable to create CString\");\n\n\n\n let mut ret: i64;\n\n unsafe {\n\n let mut handle =\n\n Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle;\n", "file_path": "src/test_rng.rs", "rank": 28, "score": 11915.170598458106 }, { "content": " let ct_offset = assocdata_offset + assoclen;\n\n let tag_offset = ct_offset + taglen;\n\n\n\n outbuf[assocdata_offset..ct_offset].clone_from_slice(&assocdata);\n\n outbuf[ct_offset..tag_offset].clone_from_slice(&pt);\n\n\n\n let mut ret: i64;\n\n unsafe {\n\n let mut handle =\n\n Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle;\n\n\n\n ret = (kcapi_aead_init(&mut handle as *mut _, alg.as_ptr(), 0))\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n ret = (kcapi_aead_settaglen(handle, taglen as u32))\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n", "file_path": "src/test_aead.rs", "rank": 29, "score": 11915.093504161083 }, { "content": " let mut out = [0u8; 16];\n\n let alg = CString::new(\"hmac(sha1)\").expect(\"Failed to allocate CString\");\n\n unsafe {\n\n let ret = crate::kcapi_pbkdf(\n\n alg.as_ptr(),\n\n PBKDF_PASSWORD.as_ptr(),\n\n PBKDF_PASSWORD.len() as u32,\n\n PBKDF_SALT.as_ptr(),\n\n PBKDF_SALT.len() as crate::size_t,\n\n LOOPS,\n\n out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n\n );\n\n assert_eq!(ret, 0);\n\n assert_eq!(out, PBKDF_EXP);\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_pbkdf_200_bit_key() {\n", "file_path": "src/test_kdf.rs", "rank": 31, "score": 11914.907636867187 }, { "content": "\n\n let alg = CString::new(\"rsa\").expect(\"Failed to create CString\");\n\n\n\n let mut ret = crate::kcapi_akcipher_init(&mut handle as *mut _, alg.as_ptr(), 0);\n\n assert_eq!(ret, 0);\n\n\n\n ret = crate::kcapi_akcipher_setkey(handle, privkey.as_ptr(), privkey.len() as u32);\n\n assert_eq!(ret, 256);\n\n\n\n let mut out = [0u8; ct.len()];\n\n let inp = ct.clone();\n\n\n\n let ret64 = crate::kcapi_akcipher_decrypt(\n\n handle,\n\n inp.as_ptr(),\n\n inp.len() as crate::size_t,\n\n out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n\n crate::KCAPI_ACCESS_HEURISTIC as ::std::os::raw::c_int,\n\n );\n", "file_path": "src/test_akcipher.rs", "rank": 33, "score": 11914.752668137417 }, { "content": " let ret: i64;\n\n unsafe {\n\n ret = kcapi_cipher_enc_aes_ctr(\n\n key.as_ptr(),\n\n key.len() as u32,\n\n inp.as_ptr(),\n\n (inp.len() as u32).into(),\n\n iv.as_ptr(),\n\n out.as_ptr() as *mut u8,\n\n (out.len() as u32).into(),\n\n );\n\n }\n\n\n\n assert_eq!(inp.len() as i64, ret);\n\n assert_eq!(out_exp, out);\n\n }\n\n\n\n #[test]\n\n fn test_aes128_ctr_dec() {\n\n let inp = [\n", "file_path": "src/test_skcipher.rs", "rank": 34, "score": 11914.720413702978 }, { "content": "\n\n let ret: i64;\n\n unsafe {\n\n ret = kcapi_cipher_enc_aes_cbc(\n\n key.as_ptr(),\n\n key.len() as u32,\n\n inp.as_ptr(),\n\n (inp.len() as u32).into(),\n\n iv.as_ptr(),\n\n out.as_ptr() as *mut u8,\n\n (out.len() as u32).into(),\n\n );\n\n }\n\n\n\n assert_eq!(ret, inp.len() as i64);\n\n assert_eq!(out_exp, out);\n\n }\n\n\n\n #[test]\n\n fn test_aes256_cbc_dec() {\n", "file_path": "src/test_skcipher.rs", "rank": 35, "score": 11914.629447146051 }, { "content": " let mut pt_out = vec![0u8; pt.len()];\n\n pt_out.clone_from_slice(&out[out.len() - pt.len()..]);\n\n assert_eq!(pt_out, pt);\n\n assert_eq!(ret64, ct.len() as i64);\n\n }\n\n }\n\n\n\n #[test]\n\n #[ignore]\n\n fn test_akcipher_sign() {\n\n unsafe {\n\n let mut handle =\n\n Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle;\n\n\n\n let alg =\n\n CString::new(\"pkcs1pad(rsa-generic,sha256)\").expect(\"Failed to create CString\");\n\n\n\n let mut ret = crate::kcapi_akcipher_init(&mut handle as *mut _, alg.as_ptr(), 0);\n\n assert_eq!(ret, 0);\n\n\n", "file_path": "src/test_akcipher.rs", "rank": 36, "score": 11914.327563235782 }, { "content": " 0x8a, 0x32, 0xca,\n\n ];\n\n let key = [0u8; AES256_KEYSIZE as usize];\n\n let iv = [0u8; AES256_KEYSIZE as usize];\n\n\n\n let out = [0u8; (AES_BLOCKSIZE * 2) as usize];\n\n let out_exp = [0x41u8; (AES_BLOCKSIZE * 2) as usize];\n\n\n\n let ret: i64;\n\n unsafe {\n\n ret = kcapi_cipher_dec_aes_ctr(\n\n key.as_ptr(),\n\n key.len() as u32,\n\n inp.as_ptr(),\n\n (inp.len() as u32).into(),\n\n iv.as_ptr(),\n\n out.as_ptr() as *mut u8,\n\n (out.len() as u32).into(),\n\n );\n\n }\n\n assert_eq!(inp.len() as i64, ret);\n\n assert_eq!(out_exp, out);\n\n }\n\n}\n", "file_path": "src/test_skcipher.rs", "rank": 38, "score": 11914.207485596276 }, { "content": " out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n\n crate::KCAPI_ACCESS_HEURISTIC as ::std::os::raw::c_int,\n\n );\n\n assert_eq!(ret64, 0);\n\n }\n\n }\n\n\n\n #[test]\n\n #[ignore]\n\n fn test_akcipher_verify_sig_fail() {\n\n unsafe {\n\n let mut handle =\n\n Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle;\n\n\n\n let alg =\n\n CString::new(\"pkcs1pad(rsa-generic,sha256)\").expect(\"Failed to create CString\");\n\n\n\n let mut ret = crate::kcapi_akcipher_init(&mut handle as *mut _, alg.as_ptr(), 0);\n\n assert_eq!(ret, 0);\n", "file_path": "src/test_akcipher.rs", "rank": 39, "score": 11914.005795146777 }, { "content": " handle,\n\n inp.as_ptr(),\n\n inp.len() as crate::size_t,\n\n out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n\n crate::KCAPI_ACCESS_HEURISTIC as ::std::os::raw::c_int,\n\n );\n\n assert!(ret64 < 0);\n\n }\n\n }\n\n\n\n #[test]\n\n #[ignore]\n\n fn test_akcipher_verify_digest_fail() {\n\n unsafe {\n\n let mut handle =\n\n Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle;\n\n\n\n let alg =\n\n CString::new(\"pkcs1pad(rsa-generic,sha256)\").expect(\"Failed to create CString\");\n", "file_path": "src/test_akcipher.rs", "rank": 40, "score": 11913.948426850751 }, { "content": "\n\n kcapi_aead_setassoclen(handle, assoclen as u64);\n\n\n\n let mut newiv = &mut [0u8; 48] as *mut u8;\n\n let mut newivlen: u32 = 0;\n\n ret = (kcapi_pad_iv(\n\n handle,\n\n iv.as_ptr(),\n\n iv.len() as u32,\n\n &mut newiv as *mut _,\n\n &mut newivlen as *mut u32,\n\n ))\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n let outbuflen =\n\n kcapi_aead_outbuflen_enc(handle, pt.len() as u64, assoclen as u64, taglen as u64);\n\n let inbuflen =\n\n kcapi_aead_inbuflen_enc(handle, pt.len() as u64, assoclen as u64, taglen as u64);\n", "file_path": "src/test_aead.rs", "rank": 41, "score": 11913.898036923638 }, { "content": "\n\n let mut ret = crate::kcapi_akcipher_init(&mut handle as *mut _, alg.as_ptr(), 0);\n\n assert_eq!(ret, 0);\n\n\n\n let mut hash = [0u8; 32];\n\n let mut ret64 = crate::kcapi_md_sha256(\n\n pt.as_ptr(),\n\n pt.len() as crate::size_t,\n\n hash.as_mut_ptr(),\n\n hash.len() as crate::size_t,\n\n );\n\n assert_eq!(hash.len(), ret64 as usize);\n\n\n\n ret = crate::kcapi_akcipher_setpubkey(handle, pubkey.as_ptr(), pubkey.len() as u32);\n\n assert_eq!(ret, 256);\n\n\n\n let mut inp = Vec::new();\n\n inp.extend(sig.iter().copied());\n\n inp.extend(hash.iter().copied());\n\n let inp_len: usize = inp.len();\n", "file_path": "src/test_akcipher.rs", "rank": 42, "score": 11913.77122980074 }, { "content": " .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n ret = kcapi_rng_setentropy(handle, ent.as_mut_ptr(), ent.len() as u32)\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n ret = kcapi_rng_seed(handle, seed.as_mut_ptr(), seed.len() as u32)\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n ret = kcapi_rng_generate(handle, out.as_mut_ptr(), 16);\n\n assert_eq!(ret, 16);\n\n assert_eq!(out, out_exp);\n\n }\n\n }\n\n}\n", "file_path": "src/test_rng.rs", "rank": 43, "score": 11913.580319583512 }, { "content": " as *mut crate::kcapi_handle;\n\n let mut ret = crate::kcapi_md_init(&mut handle as *mut _, alg.as_ptr(), 0);\n\n assert_eq!(ret, 0);\n\n\n\n ret = crate::kcapi_md_setkey(handle, DPI_KDF_KEY.as_ptr(), DPI_KDF_KEY.len() as u32);\n\n assert_eq!(ret, 0);\n\n\n\n let ret = crate::kcapi_kdf_dpi(\n\n handle,\n\n DPI_KDF_MSG.as_ptr(),\n\n DPI_KDF_MSG.len() as crate::size_t,\n\n out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n\n );\n\n assert_eq!(ret, 0);\n\n assert_eq!(DPI_KDF_EXP, out);\n\n }\n\n }\n\n\n\n #[test]\n", "file_path": "src/test_kdf.rs", "rank": 44, "score": 11913.49211586801 }, { "content": " #[test]\n\n fn test_aes192_cbc_dec() {\n\n let inp = [\n\n 0x48, 0x5e, 0x40, 0x47, 0x1, 0xda, 0x67, 0x88, 0x74, 0x72, 0x4d, 0x32, 0xda, 0x51,\n\n 0xd1, 0x24,\n\n ];\n\n let key = [0u8; AES192_KEYSIZE as usize];\n\n let iv = [0u8; AES192_KEYSIZE as usize];\n\n\n\n let out = [0u8; AES_BLOCKSIZE as usize];\n\n let out_exp = [0x41u8; AES_BLOCKSIZE as usize];\n\n\n\n let ret: i64;\n\n unsafe {\n\n ret = kcapi_cipher_dec_aes_cbc(\n\n key.as_ptr(),\n\n key.len() as u32,\n\n inp.as_ptr(),\n\n (inp.len() as u32).into(),\n\n iv.as_ptr(),\n", "file_path": "src/test_skcipher.rs", "rank": 45, "score": 11913.249131350765 }, { "content": " let inp = [\n\n 0x7e, 0xe, 0x75, 0x77, 0xef, 0x9c, 0x30, 0xa6, 0xbf, 0xb, 0x25, 0xe0, 0x62, 0x1e, 0x82,\n\n 0x7e,\n\n ];\n\n let key = [0u8; AES256_KEYSIZE as usize];\n\n let iv = [0u8; AES256_KEYSIZE as usize];\n\n\n\n let out = [0u8; AES_BLOCKSIZE as usize];\n\n let out_exp = [0x41u8; AES_BLOCKSIZE as usize];\n\n\n\n let ret: i64;\n\n unsafe {\n\n ret = kcapi_cipher_dec_aes_cbc(\n\n key.as_ptr(),\n\n key.len() as u32,\n\n inp.as_ptr(),\n\n (inp.len() as u32).into(),\n\n iv.as_ptr(),\n\n out.as_ptr() as *mut u8,\n\n (out.len() as u32).into(),\n", "file_path": "src/test_skcipher.rs", "rank": 46, "score": 11912.738863389195 }, { "content": " }\n\n\n\n #[test]\n\n fn test_aes128_cbc_dec() {\n\n let inp = [\n\n 0xb4, 0x9c, 0xbf, 0x19, 0xd3, 0x57, 0xe6, 0xe1, 0xf6, 0x84, 0x5c, 0x30, 0xfd, 0x5b,\n\n 0x63, 0xe3,\n\n ];\n\n let key = [0u8; AES128_KEYSIZE as usize];\n\n let iv = [0u8; AES128_KEYSIZE as usize];\n\n\n\n let out = [0u8; AES_BLOCKSIZE as usize];\n\n let out_exp = [0x41u8; AES_BLOCKSIZE as usize];\n\n\n\n let ret: i64;\n\n unsafe {\n\n ret = kcapi_cipher_dec_aes_cbc(\n\n key.as_ptr(),\n\n key.len() as u32,\n\n inp.as_ptr(),\n", "file_path": "src/test_skcipher.rs", "rank": 47, "score": 11912.644082271807 }, { "content": "\n\n #[test]\n\n #[ignore]\n\n fn test_rng_kat() {\n\n let mut ent = [0x41u8; 16];\n\n let mut seed = [0x41u8; 16];\n\n let mut out = [0u8; 16];\n\n let out_exp = [\n\n 0xbd, 0x3a, 0xbb, 0xfe, 0x98, 0x85, 0x69, 0xbf, 0x64, 0x2f, 0xe9, 0xb3, 0x55, 0xc1,\n\n 0xc0, 0x35,\n\n ];\n\n let alg = CString::new(\"drbg_nopr_sha1\").expect(\"Unable to create CString\");\n\n\n\n let mut ret: i64;\n\n unsafe {\n\n let mut handle =\n\n Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle;\n\n\n\n ret = (kcapi_rng_init(&mut handle as *mut _, alg.as_ptr(), 0))\n\n .try_into()\n", "file_path": "src/test_rng.rs", "rank": 48, "score": 11912.566254583766 }, { "content": " unsafe {\n\n ret = kcapi_cipher_enc_aes_ctr(\n\n key.as_ptr(),\n\n key.len() as u32,\n\n inp.as_ptr(),\n\n (inp.len() as u32).into(),\n\n iv.as_ptr(),\n\n out.as_ptr() as *mut u8,\n\n (out.len() as u32).into(),\n\n );\n\n }\n\n\n\n assert_eq!(inp.len() as i64, ret);\n\n assert_eq!(out_exp, out);\n\n }\n\n\n\n #[test]\n\n fn test_aes192_ctr_dec() {\n\n let inp = [\n\n 0xeb, 0xa1, 0x28, 0xd3, 0xed, 0xfe, 0x13, 0xe2, 0xa9, 0xb5, 0xe8, 0x2f, 0x88, 0x71,\n", "file_path": "src/test_skcipher.rs", "rank": 49, "score": 11912.495054639203 }, { "content": " 0x4a, 0x96, 0x8c, 0x72, 0xf3, 0xcb, 0x86, 0x32, 0xb6, 0xa, 0xe1, 0x4f, 0x90, 0xb2,\n\n 0x53, 0x16, 0x65, 0x74,\n\n ];\n\n let key = [0u8; AES192_KEYSIZE as usize];\n\n let iv = [0u8; AES192_KEYSIZE as usize];\n\n\n\n let out = [0u8; (AES_BLOCKSIZE * 2) as usize];\n\n let out_exp = [0x41u8; (AES_BLOCKSIZE * 2) as usize];\n\n\n\n let ret: i64;\n\n unsafe {\n\n ret = kcapi_cipher_dec_aes_ctr(\n\n key.as_ptr(),\n\n key.len() as u32,\n\n inp.as_ptr(),\n\n (inp.len() as u32).into(),\n\n iv.as_ptr(),\n\n out.as_ptr() as *mut u8,\n\n (out.len() as u32).into(),\n\n );\n", "file_path": "src/test_skcipher.rs", "rank": 50, "score": 11912.268641859559 }, { "content": " inp[inp_len - 1] ^= 0x01;\n\n\n\n let mut out = [0u8; sig.len()];\n\n ret64 = crate::kcapi_akcipher_verify(\n\n handle,\n\n inp.as_ptr(),\n\n inp.len() as crate::size_t,\n\n out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n\n crate::KCAPI_ACCESS_HEURISTIC as ::std::os::raw::c_int,\n\n );\n\n assert!(ret64 < 0);\n\n }\n\n }\n\n\n\n #[test]\n\n #[ignore]\n\n fn test_akcipher_verify_key_fail() {\n\n unsafe {\n\n let mut handle =\n", "file_path": "src/test_akcipher.rs", "rank": 51, "score": 11912.260849354496 }, { "content": " const FB_KDF_EXP: [u8; 64] = [\n\n 0xbd, 0x14, 0x76, 0xf4, 0x3a, 0x4e, 0x31, 0x57, 0x47, 0xcf, 0x59, 0x18, 0xe0, 0xea,\n\n 0x5b, 0xc0, 0xd9, 0x87, 0x69, 0x45, 0x74, 0x77, 0xc3, 0xab, 0x18, 0xb7, 0x42, 0xde,\n\n 0xf0, 0xe0, 0x79, 0xa9, 0x33, 0xb7, 0x56, 0x36, 0x5a, 0xfb, 0x55, 0x41, 0xf2, 0x53,\n\n 0xfe, 0xe4, 0x3c, 0x6f, 0xd7, 0x88, 0xa4, 0x40, 0x41, 0x3, 0x85, 0x9, 0xe9, 0xee, 0xb6,\n\n 0x8f, 0x7d, 0x65, 0xff, 0xbb, 0x5f, 0x95,\n\n ];\n\n\n\n let mut out = [0u8; 64];\n\n\n\n let alg = CString::new(\"hmac(sha256)\").expect(\"Failed to allocate CString\");\n\n unsafe {\n\n let mut handle = Box::into_raw(Box::new(crate::kcapi_handle { _unused: [0u8; 0] }))\n\n as *mut crate::kcapi_handle;\n\n let mut ret = crate::kcapi_md_init(&mut handle as *mut _, alg.as_ptr(), 0);\n\n assert_eq!(ret, 0);\n\n\n\n ret = crate::kcapi_md_setkey(handle, FB_KDF_KEY.as_ptr(), FB_KDF_KEY.len() as u32);\n\n assert_eq!(ret, 0);\n\n\n", "file_path": "src/test_kdf.rs", "rank": 52, "score": 11912.22841943699 }, { "content": "\n\n ret = (kcapi_aead_setkey(handle, key.as_ptr(), key.len() as u32))\n\n .try_into()\n\n .expect(\"Failed to convert i32 to i64\");\n\n assert_eq!(ret, 0);\n\n\n\n ret = kcapi_aead_encrypt(\n\n handle,\n\n outbuf.as_ptr(),\n\n inbuflen,\n\n newiv,\n\n outbuf.as_mut_ptr(),\n\n outbuflen,\n\n KCAPI_ACCESS_HEURISTIC as i32,\n\n );\n\n assert_eq!(ret, outbuf.len() as i64);\n\n\n\n ct.clone_from_slice(&outbuf[assocdata.len()..assocdata.len() + pt.len()]);\n\n tag.clone_from_slice(&outbuf[tag_offset..]);\n\n }\n", "file_path": "src/test_aead.rs", "rank": 53, "score": 11912.217706533469 }, { "content": " 0xd1, 0x24,\n\n ];\n\n\n\n let ret: i64;\n\n unsafe {\n\n ret = kcapi_cipher_enc_aes_cbc(\n\n key.as_ptr(),\n\n key.len() as u32,\n\n inp.as_ptr(),\n\n (inp.len() as u32).into(),\n\n iv.as_ptr(),\n\n out.as_ptr() as *mut u8,\n\n (out.len() as u32).into(),\n\n );\n\n }\n\n\n\n assert_eq!(ret, inp.len() as i64);\n\n assert_eq!(out_exp, out);\n\n }\n\n\n", "file_path": "src/test_skcipher.rs", "rank": 54, "score": 11912.136775130468 }, { "content": " let alg = CString::new(\"hmac(sha256)\").expect(\"Failed to allocate CString\");\n\n unsafe {\n\n let ret = crate::kcapi_hkdf(\n\n alg.as_ptr(),\n\n HKDF_IKM.as_ptr(),\n\n HKDF_IKM.len() as crate::size_t,\n\n HKDF_SALT.as_ptr(),\n\n HKDF_SALT.len() as u32,\n\n HKDF_INFO.as_ptr(),\n\n HKDF_INFO.len() as crate::size_t,\n\n out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n\n );\n\n assert_eq!(ret, 0);\n\n assert_eq!(out, HKDF_OUT_EXP);\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_pbkdf_one_loop() {\n", "file_path": "src/test_kdf.rs", "rank": 55, "score": 11911.98444611961 }, { "content": " (inp.len() as u32).into(),\n\n iv.as_ptr(),\n\n out.as_ptr() as *mut u8,\n\n (out.len() as u32).into(),\n\n );\n\n }\n\n\n\n assert_eq!(ret, inp.len() as i64);\n\n assert_eq!(out_exp, out);\n\n }\n\n\n\n #[test]\n\n fn test_aes192_cbc_enc() {\n\n let inp = [0x41u8; AES_BLOCKSIZE as usize];\n\n let key = [0u8; AES192_KEYSIZE as usize];\n\n let iv = [0u8; AES192_KEYSIZE as usize];\n\n\n\n let out = [0u8; AES_BLOCKSIZE as usize];\n\n let out_exp = [\n\n 0x48, 0x5e, 0x40, 0x47, 0x1, 0xda, 0x67, 0x88, 0x74, 0x72, 0x4d, 0x32, 0xda, 0x51,\n", "file_path": "src/test_skcipher.rs", "rank": 57, "score": 11911.641502422652 }, { "content": "\n\n let ret64 = crate::kcapi_akcipher_encrypt(\n\n handle,\n\n inp.as_ptr(),\n\n inp.len() as crate::size_t,\n\n out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n\n crate::KCAPI_ACCESS_HEURISTIC as ::std::os::raw::c_int,\n\n );\n\n assert_eq!(out, ct);\n\n assert_eq!(ret64, ct.len() as i64);\n\n }\n\n }\n\n\n\n #[test]\n\n #[ignore]\n\n fn test_akcipher_dec() {\n\n unsafe {\n\n let mut handle =\n\n Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle;\n", "file_path": "src/test_akcipher.rs", "rank": 58, "score": 11911.50651506778 }, { "content": " 0x27, 0xa8, 0xa, 0x95, 0xae, 0xcb, 0x6d, 0x7a, 0xc9, 0xd, 0xbb, 0x18, 0x8b, 0x75, 0x6a,\n\n 0x6f, 0x19, 0xa3, 0xbd, 0x8f, 0xbb, 0x3f, 0x71, 0x20, 0x77, 0x3e, 0x5c, 0x16, 0xe5,\n\n 0xa6, 0x4, 0x1b,\n\n ];\n\n let key = [0u8; AES128_KEYSIZE as usize];\n\n let iv = [0u8; AES128_KEYSIZE as usize];\n\n\n\n let out = [0u8; (AES_BLOCKSIZE * 2) as usize];\n\n let out_exp = [0x41u8; (AES_BLOCKSIZE * 2) as usize];\n\n\n\n let ret: i64;\n\n unsafe {\n\n ret = kcapi_cipher_dec_aes_ctr(\n\n key.as_ptr(),\n\n key.len() as u32,\n\n inp.as_ptr(),\n\n (inp.len() as u32).into(),\n\n iv.as_ptr(),\n\n out.as_ptr() as *mut u8,\n\n (out.len() as u32).into(),\n", "file_path": "src/test_skcipher.rs", "rank": 59, "score": 11911.117242409531 }, { "content": " Box::into_raw(Box::new(kcapi_handle { _unused: [0u8; 0] })) as *mut kcapi_handle;\n\n\n\n let alg =\n\n CString::new(\"pkcs1pad(rsa-generic,sha256)\").expect(\"Failed to create CString\");\n\n\n\n let mut ret = crate::kcapi_akcipher_init(&mut handle as *mut _, alg.as_ptr(), 0);\n\n assert_eq!(ret, 0);\n\n\n\n let mut hash = [0u8; 32];\n\n let mut ret64 = crate::kcapi_md_sha256(\n\n pt.as_ptr(),\n\n pt.len() as crate::size_t,\n\n hash.as_mut_ptr(),\n\n hash.len() as crate::size_t,\n\n );\n\n assert_eq!(hash.len(), ret64 as usize);\n\n\n\n let mut pubkey_corrupt = pubkey.clone();\n\n pubkey_corrupt[pubkey.len() - pubkey.len() / 2] ^= 0x01;\n\n ret = crate::kcapi_akcipher_setpubkey(\n", "file_path": "src/test_akcipher.rs", "rank": 60, "score": 11911.064844988941 }, { "content": " out.as_ptr() as *mut u8,\n\n (out.len() as u32).into(),\n\n );\n\n }\n\n\n\n assert_eq!(ret, inp.len() as i64);\n\n assert_eq!(out_exp, out);\n\n }\n\n\n\n #[test]\n\n fn test_aes256_cbc_enc() {\n\n let inp = [0x41u8; AES_BLOCKSIZE as usize];\n\n let key = [0u8; AES256_KEYSIZE as usize];\n\n let iv = [0u8; AES256_KEYSIZE as usize];\n\n\n\n let out = [0u8; AES_BLOCKSIZE as usize];\n\n let out_exp = [\n\n 0x7e, 0xe, 0x75, 0x77, 0xef, 0x9c, 0x30, 0xa6, 0xbf, 0xb, 0x25, 0xe0, 0x62, 0x1e, 0x82,\n\n 0x7e,\n\n ];\n", "file_path": "src/test_skcipher.rs", "rank": 61, "score": 11910.872739655024 }, { "content": " pt.len() as u64,\n\n iv.as_ptr(),\n\n ct.as_mut_ptr(),\n\n ct.len() as u64,\n\n KCAPI_ACCESS_HEURISTIC as i32,\n\n );\n\n assert_eq!(ret, pt.len() as i64);\n\n }\n\n assert_eq!(ct_exp, ct);\n\n }\n\n\n\n #[test]\n\n fn test_kcapi_skcipher_dec() {\n\n let ct = [\n\n 0x7e, 0xe, 0x75, 0x77, 0xef, 0x9c, 0x30, 0xa6, 0xbf, 0xb, 0x25, 0xe0, 0x62, 0x1e, 0x82,\n\n 0x7e,\n\n ];\n\n let mut pt = [0u8; AES_BLOCKSIZE as usize];\n\n let key = [0u8; AES256_KEYSIZE as usize];\n\n let iv = [0u8; AES_BLOCKSIZE as usize];\n", "file_path": "src/test_skcipher.rs", "rank": 62, "score": 11910.861985232023 }, { "content": " let mut ret64 = crate::kcapi_md_sha256(\n\n pt.as_ptr(),\n\n pt.len() as crate::size_t,\n\n hash.as_mut_ptr(),\n\n hash.len() as crate::size_t,\n\n );\n\n assert_eq!(hash.len(), ret64 as usize);\n\n\n\n ret = crate::kcapi_akcipher_setpubkey(handle, pubkey.as_ptr(), pubkey.len() as u32);\n\n assert_eq!(ret, 256);\n\n\n\n let mut inp = Vec::new();\n\n inp.extend(sig.iter().copied());\n\n inp.extend(hash.iter().copied());\n\n\n\n let mut out = [0u8; sig.len()];\n\n ret64 = crate::kcapi_akcipher_verify(\n\n handle,\n\n inp.as_ptr(),\n\n inp.len() as crate::size_t,\n", "file_path": "src/test_akcipher.rs", "rank": 63, "score": 11910.815077400162 }, { "content": " let out_exp = [\n\n 0xb4, 0x9c, 0xbf, 0x19, 0xd3, 0x57, 0xe6, 0xe1, 0xf6, 0x84, 0x5c, 0x30, 0xfd, 0x5b,\n\n 0x63, 0xe3,\n\n ];\n\n\n\n let ret: i64;\n\n unsafe {\n\n ret = kcapi_cipher_enc_aes_cbc(\n\n key.as_ptr(),\n\n key.len() as u32,\n\n inp.as_ptr(),\n\n (inp.len() as u32).into(),\n\n iv.as_ptr(),\n\n out.as_ptr() as *mut u8,\n\n (out.len() as u32).into(),\n\n );\n\n }\n\n\n\n assert_eq!(ret, inp.len() as i64);\n\n assert_eq!(out_exp, out);\n", "file_path": "src/test_skcipher.rs", "rank": 64, "score": 11910.754373273141 }, { "content": " 0xd0, 0x65, 0xa4, 0x29, 0xc1,\n\n ];\n\n const LOOPS: u32 = 4096;\n\n\n\n let mut out = [0u8; 20];\n\n let alg = CString::new(\"hmac(sha1)\").expect(\"Failed to allocate CString\");\n\n unsafe {\n\n let ret = crate::kcapi_pbkdf(\n\n alg.as_ptr(),\n\n PBKDF_PASSWORD.as_ptr(),\n\n PBKDF_PASSWORD.len() as u32,\n\n PBKDF_SALT.as_ptr(),\n\n PBKDF_SALT.len() as crate::size_t,\n\n LOOPS,\n\n out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n\n );\n\n assert_eq!(ret, 0);\n\n assert_eq!(out, PBKDF_EXP);\n\n }\n", "file_path": "src/test_kdf.rs", "rank": 65, "score": 11910.753770265874 }, { "content": " kcapi_cipher_enc_aes_cbc, kcapi_cipher_enc_aes_ctr, kcapi_cipher_encrypt,\n\n kcapi_cipher_init, kcapi_cipher_setkey, kcapi_handle, KCAPI_ACCESS_HEURISTIC,\n\n };\n\n\n\n const AES_BLOCKSIZE: usize = 16;\n\n const AES128_KEYSIZE: usize = 16;\n\n const AES192_KEYSIZE: usize = 24;\n\n const AES256_KEYSIZE: usize = 32;\n\n\n\n #[test]\n\n fn test_kcapi_skcipher_enc() {\n\n let pt = [0x41u8; AES_BLOCKSIZE as usize];\n\n let mut ct = [0u8; AES_BLOCKSIZE as usize];\n\n let key = [0u8; AES256_KEYSIZE as usize];\n\n let iv = [0u8; AES_BLOCKSIZE as usize];\n\n let alg = CString::new(\"cbc(aes)\").expect(\"Failed to convert to Cstring\");\n\n\n\n let ct_exp = [\n\n 0x7e, 0xe, 0x75, 0x77, 0xef, 0x9c, 0x30, 0xa6, 0xbf, 0xb, 0x25, 0xe0, 0x62, 0x1e, 0x82,\n\n 0x7e,\n", "file_path": "src/test_skcipher.rs", "rank": 67, "score": 11910.131142340833 }, { "content": "\n\n let mut hash = [0u8; 32];\n\n let mut ret64 = crate::kcapi_md_sha256(\n\n pt.as_ptr(),\n\n pt.len() as crate::size_t,\n\n hash.as_mut_ptr(),\n\n hash.len() as crate::size_t,\n\n );\n\n assert_eq!(hash.len(), ret64 as usize);\n\n\n\n ret = crate::kcapi_akcipher_setpubkey(handle, pubkey.as_ptr(), pubkey.len() as u32);\n\n assert_eq!(ret, 256);\n\n\n\n let mut inp = Vec::new();\n\n inp.extend(sig.iter().copied());\n\n inp[sig.len() - 1] ^= 0x01;\n\n inp.extend(hash.iter().copied());\n\n\n\n let mut out = [0u8; sig.len()];\n\n ret64 = crate::kcapi_akcipher_verify(\n", "file_path": "src/test_akcipher.rs", "rank": 68, "score": 11909.934707404398 }, { "content": " ret = kcapi_cipher_enc_aes_ctr(\n\n key.as_ptr(),\n\n key.len() as u32,\n\n inp.as_ptr(),\n\n (inp.len() as u32).into(),\n\n iv.as_ptr(),\n\n out.as_ptr() as *mut u8,\n\n (out.len() as u32).into(),\n\n );\n\n }\n\n\n\n assert_eq!(inp.len() as i64, ret);\n\n assert_eq!(out_exp, out);\n\n }\n\n\n\n #[test]\n\n fn test_aes256_ctr_dec() {\n\n let inp = [\n\n 0x9d, 0xd4, 0x81, 0x39, 0xe3, 0x1, 0xc8, 0xc8, 0xec, 0x9, 0xe3, 0x55, 0xd3, 0xc5, 0x61,\n\n 0xc6, 0x12, 0x4e, 0xcb, 0xba, 0x86, 0x4, 0x77, 0xf8, 0xe8, 0x22, 0xf5, 0xb0, 0x85,\n", "file_path": "src/test_skcipher.rs", "rank": 69, "score": 11909.399433919709 }, { "content": " }\n\n assert_eq!(inp.len() as i64, ret);\n\n assert_eq!(out_exp, out);\n\n }\n\n\n\n #[test]\n\n fn test_aes256_ctr_enc() {\n\n let inp = [0x41u8; (AES_BLOCKSIZE * 2) as usize];\n\n let key = [0u8; AES256_KEYSIZE as usize];\n\n let iv = [0u8; AES256_KEYSIZE as usize];\n\n\n\n let out = [0u8; (AES_BLOCKSIZE * 2) as usize];\n\n let out_exp = [\n\n 0x9d, 0xd4, 0x81, 0x39, 0xe3, 0x1, 0xc8, 0xc8, 0xec, 0x9, 0xe3, 0x55, 0xd3, 0xc5, 0x61,\n\n 0xc6, 0x12, 0x4e, 0xcb, 0xba, 0x86, 0x4, 0x77, 0xf8, 0xe8, 0x22, 0xf5, 0xb0, 0x85,\n\n 0x8a, 0x32, 0xca,\n\n ];\n\n\n\n let ret: i64;\n\n unsafe {\n", "file_path": "src/test_skcipher.rs", "rank": 70, "score": 11909.389684931222 }, { "content": " }\n\n\n\n #[test]\n\n fn test_pbkdf_multiloop() {\n\n const PBKDF_SALT: [u8; 4] = [0x73, 0x61, 0x6c, 0x74];\n\n const PBKDF_PASSWORD: [u8; 8] = [0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64];\n\n const PBKDF_EXP: [u8; 20] = [\n\n 0xee, 0xfe, 0x3d, 0x61, 0xcd, 0x4d, 0xa4, 0xe4, 0xe9, 0x94, 0x5b, 0x3d, 0x6b, 0xa2,\n\n 0x15, 0x8c, 0x26, 0x34, 0xe9, 0x84,\n\n ];\n\n const LOOPS: u32 = 16777216;\n\n\n\n let mut out = [0u8; 20];\n\n let alg = CString::new(\"hmac(sha1)\").expect(\"Failed to allocate CString\");\n\n unsafe {\n\n let ret = crate::kcapi_pbkdf(\n\n alg.as_ptr(),\n\n PBKDF_PASSWORD.as_ptr(),\n\n PBKDF_PASSWORD.len() as u32,\n\n PBKDF_SALT.as_ptr(),\n", "file_path": "src/test_kdf.rs", "rank": 72, "score": 11908.98180246763 }, { "content": " handle,\n\n pubkey_corrupt.as_ptr(),\n\n pubkey_corrupt.len() as u32,\n\n );\n\n assert_eq!(ret, 256);\n\n\n\n let mut inp = Vec::new();\n\n inp.extend(sig.iter().copied());\n\n inp.extend(hash.iter().copied());\n\n\n\n let mut out = [0u8; sig.len()];\n\n ret64 = crate::kcapi_akcipher_verify(\n\n handle,\n\n inp.as_ptr(),\n\n inp.len() as crate::size_t,\n\n out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n\n crate::KCAPI_ACCESS_HEURISTIC as ::std::os::raw::c_int,\n\n );\n\n assert!(ret64 < 0);\n\n }\n\n }\n\n}\n", "file_path": "src/test_akcipher.rs", "rank": 74, "score": 11908.551479478896 }, { "content": " );\n\n assert_eq!(ret, 0);\n\n assert_eq!(out, PBKDF_EXP);\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_pbkdf_two_loops() {\n\n const PBKDF_SALT: [u8; 4] = [0x73, 0x61, 0x6c, 0x74];\n\n const PBKDF_PASSWORD: [u8; 8] = [0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64];\n\n const PBKDF_EXP: [u8; 20] = [\n\n 0xea, 0x6c, 0x1, 0x4d, 0xc7, 0x2d, 0x6f, 0x8c, 0xcd, 0x1e, 0xd9, 0x2a, 0xce, 0x1d,\n\n 0x41, 0xf0, 0xd8, 0xde, 0x89, 0x57,\n\n ];\n\n const LOOPS: u32 = 2;\n\n\n\n let mut out = [0u8; 20];\n\n let alg = CString::new(\"hmac(sha1)\").expect(\"Failed to allocate CString\");\n\n unsafe {\n\n let ret = crate::kcapi_pbkdf(\n", "file_path": "src/test_kdf.rs", "rank": 75, "score": 11908.49169335127 }, { "content": " const PBKDF_SALT: [u8; 4] = [0x73, 0x61, 0x6c, 0x74];\n\n const PBKDF_PASSWORD: [u8; 8] = [0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64];\n\n const PBKDF_EXP: [u8; 20] = [\n\n 0xc, 0x60, 0xc8, 0xf, 0x96, 0x1f, 0xe, 0x71, 0xf3, 0xa9, 0xb5, 0x24, 0xaf, 0x60, 0x12,\n\n 0x6, 0x2f, 0xe0, 0x37, 0xa6,\n\n ];\n\n const LOOPS: u32 = 1;\n\n\n\n let mut out = [0u8; 20];\n\n let alg = CString::new(\"hmac(sha1)\").expect(\"Failed to allocate CString\");\n\n unsafe {\n\n let ret = crate::kcapi_pbkdf(\n\n alg.as_ptr(),\n\n PBKDF_PASSWORD.as_ptr(),\n\n PBKDF_PASSWORD.len() as u32,\n\n PBKDF_SALT.as_ptr(),\n\n PBKDF_SALT.len() as crate::size_t,\n\n LOOPS,\n\n out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n", "file_path": "src/test_kdf.rs", "rank": 79, "score": 11907.940842129574 }, { "content": " );\n\n }\n\n assert_eq!(inp.len() as i64, ret);\n\n assert_eq!(out_exp, out);\n\n }\n\n\n\n #[test]\n\n fn test_aes192_ctr_enc() {\n\n let inp = [0x41u8; (AES_BLOCKSIZE * 2) as usize];\n\n let key = [0u8; AES192_KEYSIZE as usize];\n\n let iv = [0u8; AES192_KEYSIZE as usize];\n\n\n\n let out = [0u8; (AES_BLOCKSIZE * 2) as usize];\n\n let out_exp = [\n\n 0xeb, 0xa1, 0x28, 0xd3, 0xed, 0xfe, 0x13, 0xe2, 0xa9, 0xb5, 0xe8, 0x2f, 0x88, 0x71,\n\n 0x4a, 0x96, 0x8c, 0x72, 0xf3, 0xcb, 0x86, 0x32, 0xb6, 0xa, 0xe1, 0x4f, 0x90, 0xb2,\n\n 0x53, 0x16, 0x65, 0x74,\n\n ];\n\n\n\n let ret: i64;\n", "file_path": "src/test_skcipher.rs", "rank": 80, "score": 11907.65746383364 }, { "content": " let mut hash = [0u8; 32];\n\n let mut ret64 = crate::kcapi_md_sha256(\n\n pt.as_ptr(),\n\n pt.len() as crate::size_t,\n\n hash.as_mut_ptr(),\n\n hash.len() as crate::size_t,\n\n );\n\n assert_eq!(hash.len(), ret64 as usize);\n\n\n\n ret = crate::kcapi_akcipher_setkey(handle, privkey.as_ptr(), privkey.len() as u32);\n\n assert_eq!(ret, 256);\n\n\n\n let mut out = [0u8; ct.len()];\n\n ret64 = crate::kcapi_akcipher_sign(\n\n handle,\n\n hash.as_ptr(),\n\n hash.len() as crate::size_t,\n\n out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n\n crate::KCAPI_ACCESS_HEURISTIC as ::std::os::raw::c_int,\n", "file_path": "src/test_akcipher.rs", "rank": 81, "score": 11907.63667281103 }, { "content": " );\n\n }\n\n\n\n assert_eq!(ret, inp.len() as i64);\n\n assert_eq!(out_exp, out);\n\n }\n\n\n\n #[test]\n\n fn test_aes128_ctr_enc() {\n\n let inp = [0x41u8; (AES_BLOCKSIZE * 2) as usize];\n\n let key = [0u8; AES128_KEYSIZE as usize];\n\n let iv = [0u8; AES128_KEYSIZE as usize];\n\n\n\n let out = [0u8; (AES_BLOCKSIZE * 2) as usize];\n\n let out_exp = [\n\n 0x27, 0xa8, 0xa, 0x95, 0xae, 0xcb, 0x6d, 0x7a, 0xc9, 0xd, 0xbb, 0x18, 0x8b, 0x75, 0x6a,\n\n 0x6f, 0x19, 0xa3, 0xbd, 0x8f, 0xbb, 0x3f, 0x71, 0x20, 0x77, 0x3e, 0x5c, 0x16, 0xe5,\n\n 0xa6, 0x4, 0x1b,\n\n ];\n\n\n", "file_path": "src/test_skcipher.rs", "rank": 83, "score": 11906.456650011452 }, { "content": " let ret = crate::kcapi_kdf_fb(\n\n handle,\n\n FB_KDF_MSG.as_ptr(),\n\n FB_KDF_MSG.len() as crate::size_t,\n\n out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n\n );\n\n assert_eq!(ret, 0);\n\n assert_eq!(FB_KDF_EXP, out);\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_dpi_kdf() {\n\n const DPI_KDF_KEY: [u8; 32] = [\n\n 0x2, 0xd3, 0x6f, 0xa0, 0x21, 0xc2, 0xd, 0xdb, 0xde, 0xe4, 0x69, 0xf0, 0x57, 0x94, 0x68,\n\n 0xba, 0xe5, 0xcb, 0x13, 0xb5, 0x48, 0xb6, 0xc6, 0x1c, 0xdf, 0x9d, 0x3e, 0xc4, 0x19,\n\n 0x11, 0x1d, 0xe2,\n\n ];\n\n\n", "file_path": "src/test_kdf.rs", "rank": 87, "score": 11905.58252406775 }, { "content": " PBKDF_SALT.len() as crate::size_t,\n\n LOOPS,\n\n out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n\n );\n\n assert_eq!(ret, 0);\n\n assert_eq!(out, PBKDF_EXP);\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_pbkdf_128_bit_key() {\n\n const PBKDF_SALT: [u8; 5] = [0x73, 0x61, 0x00, 0x6c, 0x74];\n\n const PBKDF_PASSWORD: [u8; 9] = [0x70, 0x61, 0x73, 0x73, 0x00, 0x77, 0x6f, 0x72, 0x64];\n\n const PBKDF_EXP: [u8; 16] = [\n\n 0x56, 0xfa, 0x6a, 0xa7, 0x55, 0x48, 0x9, 0x9d, 0xcc, 0x37, 0xd7, 0xf0, 0x34, 0x25,\n\n 0xe0, 0xc3,\n\n ];\n\n const LOOPS: u32 = 4096;\n\n\n", "file_path": "src/test_kdf.rs", "rank": 89, "score": 11904.80577377884 }, { "content": " alg.as_ptr(),\n\n PBKDF_PASSWORD.as_ptr(),\n\n PBKDF_PASSWORD.len() as u32,\n\n PBKDF_SALT.as_ptr(),\n\n PBKDF_SALT.len() as crate::size_t,\n\n LOOPS,\n\n out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n\n );\n\n assert_eq!(ret, 0);\n\n assert_eq!(out, PBKDF_EXP);\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_pbkdf_4k_loops() {\n\n const PBKDF_SALT: [u8; 4] = [0x73, 0x61, 0x6c, 0x74];\n\n const PBKDF_PASSWORD: [u8; 8] = [0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64];\n\n const PBKDF_EXP: [u8; 20] = [\n\n 0x4b, 0x0, 0x79, 0x1, 0xb7, 0x65, 0x48, 0x9a, 0xbe, 0xad, 0x49, 0xd9, 0x26, 0xf7, 0x21,\n", "file_path": "src/test_kdf.rs", "rank": 90, "score": 11904.451107624973 }, { "content": "\n\n ret = kcapi_aead_decrypt(\n\n handle,\n\n outbuf.as_ptr(),\n\n inbuflen,\n\n newiv,\n\n outbuf.as_mut_ptr(),\n\n outbuflen,\n\n KCAPI_ACCESS_HEURISTIC as i32,\n\n );\n\n assert_eq!(ret, (outbuf.len() - assoclen) as i64);\n\n\n\n pt.clone_from_slice(&outbuf[assocdata.len()..assocdata.len() + ct.len()]);\n\n }\n\n assert_eq!(pt, pt_exp);\n\n }\n\n}\n", "file_path": "src/test_aead.rs", "rank": 91, "score": 11904.071041177376 }, { "content": " let mut ct = [0u8; pt.len()];\n\n const ct_exp: [u8; pt.len()] = [\n\n 0x42, 0xc9, 0x9b, 0x8f, 0x21, 0xf7, 0xe2, 0xd3, 0xb2, 0x69, 0x83, 0xf8, 0x30, 0xf3,\n\n 0xbf, 0x39,\n\n ];\n\n const taglen: usize = 16;\n\n const assoclen: usize = assocdata.len();\n\n\n\n let mut tag = [0u8; taglen];\n\n const tag_exp: [u8; taglen] = [\n\n 0x10, 0x8f, 0x8e, 0x8f, 0x78, 0xdd, 0x83, 0xd0, 0xf, 0xe2, 0xa2, 0x79, 0xc3, 0xce,\n\n 0xb2, 0x43,\n\n ];\n\n\n\n let key = [0u8; AES128_KEYSIZE];\n\n let iv = [0u8; AES_BLOCKSIZE];\n\n let alg = CString::new(\"gcm(aes)\").expect(\"Failed to init CString\");\n\n\n\n let mut outbuf = [0u8; pt.len() + taglen + assoclen];\n\n let assocdata_offset: usize = 0;\n", "file_path": "src/test_aead.rs", "rank": 92, "score": 11903.879073059543 }, { "content": " const PBKDF_SALT: [u8; 36] = [\n\n 0x73, 0x61, 0x6c, 0x74, 0x53, 0x41, 0x4c, 0x54, 0x73, 0x61, 0x6c, 0x74, 0x53, 0x41,\n\n 0x4c, 0x54, 0x73, 0x61, 0x6c, 0x74, 0x53, 0x41, 0x4c, 0x54, 0x73, 0x61, 0x6c, 0x74,\n\n 0x53, 0x41, 0x4c, 0x54, 0x73, 0x61, 0x6c, 0x74,\n\n ];\n\n const PBKDF_PASSWORD: [u8; 24] = [\n\n 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x50, 0x41, 0x53, 0x53, 0x57, 0x4f,\n\n 0x52, 0x44, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64,\n\n ];\n\n const PBKDF_EXP: [u8; 25] = [\n\n 0x3d, 0x2e, 0xec, 0x4f, 0xe4, 0x1c, 0x84, 0x9b, 0x80, 0xc8, 0xd8, 0x36, 0x62, 0xc0,\n\n 0xe4, 0x4a, 0x8b, 0x29, 0x1a, 0x96, 0x4c, 0xf2, 0xf0, 0x70, 0x38,\n\n ];\n\n const LOOPS: u32 = 4096;\n\n\n\n let alg = CString::new(\"hmac(sha1)\").expect(\"Failed to allocate CString\");\n\n let mut out = [0u8; 25];\n\n unsafe {\n\n let ret = crate::kcapi_pbkdf(\n\n alg.as_ptr(),\n", "file_path": "src/test_kdf.rs", "rank": 93, "score": 11903.65236128566 }, { "content": " const assoclen: usize = assocdata.len();\n\n\n\n let mut pt = [0u8; ct.len()];\n\n const pt_exp: [u8; 16] = [\n\n 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,\n\n 0x41, 0x41,\n\n ];\n\n\n\n let key = [0u8; AES128_KEYSIZE];\n\n let iv = [0u8; AES_BLOCKSIZE];\n\n let alg = CString::new(\"gcm(aes)\").expect(\"Failed to init CString\");\n\n\n\n let mut outbuf = [0u8; ct.len() + taglen + assoclen];\n\n let assocdata_offset: usize = 0;\n\n let ct_offset = assocdata_offset + assoclen;\n\n let tag_offset = ct_offset + taglen;\n\n\n\n outbuf[assocdata_offset..ct_offset].clone_from_slice(&assocdata);\n\n outbuf[ct_offset..tag_offset].clone_from_slice(&ct);\n\n outbuf[tag_offset..].clone_from_slice(&tag);\n", "file_path": "src/test_aead.rs", "rank": 94, "score": 11902.91068606999 }, { "content": " PBKDF_PASSWORD.as_ptr(),\n\n PBKDF_PASSWORD.len() as u32,\n\n PBKDF_SALT.as_ptr(),\n\n PBKDF_SALT.len() as crate::size_t,\n\n LOOPS,\n\n out.as_mut_ptr(),\n\n out.len() as crate::size_t,\n\n );\n\n assert_eq!(ret, 0);\n\n assert_eq!(out, PBKDF_EXP);\n\n }\n\n }\n\n}\n", "file_path": "src/test_kdf.rs", "rank": 95, "score": 11902.507427572067 }, { "content": " const DPI_KDF_MSG: [u8; 51] = [\n\n 0x85, 0xab, 0xe3, 0x8b, 0xf2, 0x65, 0xfb, 0xdc, 0x64, 0x45, 0xae, 0x5c, 0x71, 0x15,\n\n 0x9f, 0x15, 0x48, 0xc7, 0x3b, 0x7d, 0x52, 0x6a, 0x62, 0x31, 0x4, 0x90, 0x4a, 0xf, 0x87,\n\n 0x92, 0x7, 0xb, 0x3d, 0xf9, 0x90, 0x2b, 0x96, 0x69, 0x49, 0x4, 0x25, 0xa3, 0x85, 0xea,\n\n 0xdb, 0xf, 0x9c, 0x76, 0xe4, 0x6f, 0xf,\n\n ];\n\n\n\n const DPI_KDF_EXP: [u8; 64] = [\n\n 0xd6, 0x9f, 0x74, 0xf5, 0x18, 0xc9, 0xf6, 0x4f, 0x90, 0xa0, 0xbe, 0xeb, 0xab, 0x69,\n\n 0xf6, 0x89, 0xb7, 0x3b, 0x5c, 0x13, 0xeb, 0xf, 0x86, 0xa, 0x95, 0xca, 0xd7, 0xd9, 0x81,\n\n 0x4f, 0x8c, 0x50, 0x6e, 0xb7, 0xb1, 0x79, 0xa5, 0xc5, 0xb4, 0x46, 0x6a, 0x9e, 0xc1,\n\n 0x54, 0xc3, 0xbf, 0x1c, 0x13, 0xef, 0xd6, 0xec, 0xd, 0x82, 0xb0, 0x2c, 0x29, 0xaf,\n\n 0x2c, 0x69, 0x2, 0x99, 0xed, 0xc4, 0x53,\n\n ];\n\n\n\n let mut out = [0u8; 64];\n\n\n\n let alg = CString::new(\"hmac(sha256)\").expect(\"Failed to allocate CString\");\n\n unsafe {\n\n let mut handle = Box::into_raw(Box::new(crate::kcapi_handle { _unused: [0u8; 0] }))\n", "file_path": "src/test_kdf.rs", "rank": 96, "score": 11901.868590793396 }, { "content": " kcapi_aead_decrypt, kcapi_aead_encrypt, kcapi_aead_inbuflen_dec, kcapi_aead_inbuflen_enc,\n\n kcapi_aead_init, kcapi_aead_outbuflen_dec, kcapi_aead_outbuflen_enc,\n\n kcapi_aead_setassoclen, kcapi_aead_setkey, kcapi_aead_settaglen, kcapi_handle,\n\n kcapi_pad_iv, KCAPI_ACCESS_HEURISTIC,\n\n };\n\n\n\n const AES_BLOCKSIZE: usize = 16;\n\n const AES128_KEYSIZE: usize = 16;\n\n\n\n #[test]\n\n fn test_aead_encrypt() {\n\n const pt: [u8; AES_BLOCKSIZE] = [\n\n 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,\n\n 0x41, 0x41,\n\n ];\n\n const assocdata: [u8; 16] = [\n\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\n 0x00, 0x00,\n\n ];\n\n\n", "file_path": "src/test_aead.rs", "rank": 97, "score": 11899.00203422673 }, { "content": " assert_eq!(ct, ct_exp);\n\n assert_eq!(tag, tag_exp);\n\n }\n\n\n\n #[test]\n\n fn test_aead_decrypt() {\n\n const ct: [u8; AES_BLOCKSIZE] = [\n\n 0x42, 0xc9, 0x9b, 0x8f, 0x21, 0xf7, 0xe2, 0xd3, 0xb2, 0x69, 0x83, 0xf8, 0x30, 0xf3,\n\n 0xbf, 0x39,\n\n ];\n\n\n\n const tag: [u8; taglen] = [\n\n 0x10, 0x8f, 0x8e, 0x8f, 0x78, 0xdd, 0x83, 0xd0, 0xf, 0xe2, 0xa2, 0x79, 0xc3, 0xce,\n\n 0xb2, 0x43,\n\n ];\n\n const assocdata: [u8; 16] = [\n\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\n 0x00, 0x00,\n\n ];\n\n const taglen: usize = 16;\n", "file_path": "src/test_aead.rs", "rank": 98, "score": 11896.955679260855 }, { "content": " }\n\n }\n\n\n\n #[test]\n\n fn test_fb_kdf() {\n\n const FB_KDF_KEY: [u8; 32] = [\n\n 0x93, 0xf6, 0x98, 0xe8, 0x42, 0xee, 0xd7, 0x53, 0x94, 0xd6, 0x29, 0xd9, 0x57, 0xe2,\n\n 0xe8, 0x9c, 0x6e, 0x74, 0x1f, 0x81, 0xb, 0x62, 0x3c, 0x8b, 0x90, 0x1e, 0x38, 0x37,\n\n 0x6d, 0x6, 0x8e, 0x7b,\n\n ];\n\n\n\n const FB_KDF_MSG: [u8; 83] = [\n\n 0x9f, 0x57, 0x5d, 0x90, 0x59, 0xd3, 0xe0, 0xc0, 0x80, 0x3f, 0x8, 0x11, 0x2f, 0x8a,\n\n 0x80, 0x6d, 0xe3, 0xc3, 0x47, 0x19, 0x12, 0xcd, 0xf4, 0x2b, 0x9, 0x53, 0x88, 0xb1,\n\n 0x4b, 0x33, 0x50, 0x8e, 0x53, 0xb8, 0x9c, 0x18, 0x69, 0xe, 0x20, 0x57, 0xa1, 0xd1,\n\n 0x67, 0x82, 0x2e, 0x63, 0x6d, 0xe5, 0xb, 0xe0, 0x1, 0x85, 0x32, 0xc4, 0x31, 0xf7, 0xf5,\n\n 0xe3, 0x7f, 0x77, 0x13, 0x92, 0x20, 0xd5, 0xe0, 0x42, 0x59, 0x9e, 0xbe, 0x26, 0x6a,\n\n 0xf5, 0x76, 0x7e, 0xe1, 0x8c, 0xd2, 0xc5, 0xc1, 0x9a, 0x1f, 0xf, 0x80,\n\n ];\n\n\n", "file_path": "src/test_kdf.rs", "rank": 99, "score": 11895.955462073145 } ]
Rust
web_glitz_macros/src/resources.rs
RSSchermer/web_glitz.rs
a2e26ef0156705f0b5ac7707c4fc24a4a994d84b
use proc_macro2::{Span, TokenStream}; use quote::{quote, quote_spanned, ToTokens}; use syn::spanned::Spanned; use syn::{Attribute, Data, DeriveInput, Field, Ident, Lit, Meta, NestedMeta, Type}; use crate::util::ErrorLog; pub fn expand_derive_resources(input: &DeriveInput) -> Result<TokenStream, String> { if let Data::Struct(ref data) = input.data { let struct_name = &input.ident; let mod_path = quote!(web_glitz::pipeline::resources); let mut log = ErrorLog::new(); let mut resource_fields: Vec<ResourceField> = Vec::new(); for (position, field) in data.fields.iter().enumerate() { match ResourcesField::from_ast(field, position, &mut log) { ResourcesField::Resource(resource_field) => { for field in resource_fields.iter() { if field.binding == resource_field.binding { log.log_error(format!( "Fields `{}` and `{}` cannot both use binding `{}`.", field.name, resource_field.name, field.binding )); } } resource_fields.push(resource_field); } ResourcesField::Excluded => (), }; } let resource_slot_descriptors = resource_fields.iter().map(|field| { let ty = &field.ty; let slot_identifier = &field.name; let slot_index = field.binding as u32; let span = field.span; quote_spanned! {span=> #mod_path::TypedResourceSlotDescriptor { slot_identifier: #mod_path::ResourceSlotIdentifier::Static(#slot_identifier), slot_index: #slot_index, slot_type: <#ty as #mod_path::Resource>::TYPE } } }); let resource_types = resource_fields.iter().map(|field| { let ty = &field.ty; quote! { <#ty as #mod_path::Resource>::Encoding } }); let resource_encodings = resource_fields.iter().map(|field| { let field_name = field .ident .clone() .map(|i| i.into_token_stream()) .unwrap_or(field.position.into_token_stream()); let binding = field.binding as u32; quote! { let encoder = self.#field_name.encode(#binding, encoder); } }); let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let len = resource_fields.len(); let impl_block = quote! { #[automatically_derived] unsafe impl #impl_generics #mod_path::Resources for #struct_name #ty_generics #where_clause { type Encoding = (#(#resource_types,)*); const LAYOUT: &'static [#mod_path::TypedResourceSlotDescriptor] = &[ #(#resource_slot_descriptors,)* ]; fn encode_bind_group( self, context: &mut #mod_path::BindGroupEncodingContext, ) -> #mod_path::BindGroupEncoding<Self::Encoding> { let encoder = #mod_path::BindGroupEncoder::new(context, Some(#len)); #(#resource_encodings)* encoder.finish() } } }; let suffix = struct_name.to_string().trim_start_matches("r#").to_owned(); let dummy_const = Ident::new( &format!("_IMPL_RESOURCES_FOR_{}", suffix), Span::call_site(), ); let generated = quote! { #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] const #dummy_const: () = { #[allow(unknown_lints)] #[cfg_attr(feature = "cargo-clippy", allow(useless_attribute))] #[allow(rust_2018_idioms)] use #mod_path::Resource; #impl_block }; }; log.compile().map(|_| generated) } else { Err("`Resources` can only be derived for a struct.".into()) } } enum ResourcesField { Resource(ResourceField), Excluded, } impl ResourcesField { pub fn from_ast(ast: &Field, position: usize, log: &mut ErrorLog) -> Self { let field_name = ast .ident .clone() .map(|i| i.to_string()) .unwrap_or(position.to_string()); let mut iter = ast.attrs.iter().filter(|a| is_resource_attribute(a)); if let Some(attr) = iter.next() { if iter.next().is_some() { log.log_error(format!( "Cannot add more than 1 #[resource] attribute to field `{}`.", field_name )); return ResourcesField::Excluded; } let meta_items: Vec<NestedMeta> = match attr.parse_meta() { Ok(Meta::List(list)) => list.nested.iter().cloned().collect(), Ok(Meta::Path(path)) if path.is_ident("resource") => Vec::new(), _ => { log.log_error(format!( "Malformed #[resource] attribute for field `{}`.", field_name )); Vec::new() } }; let mut binding = None; let mut name = ast.ident.clone().map(|i| i.to_string()); for meta_item in meta_items.into_iter() { match meta_item { NestedMeta::Meta(Meta::NameValue(m)) if m.path.is_ident("binding") => { if let Lit::Int(i) = &m.lit { if let Ok(value) = i.base10_parse::<u32>() { binding = Some(value); } else { log.log_error(format!( "Malformed #[resource] attribute for field `{}`: \ expected `binding` to be representable as a u32.", field_name )); } } else { log.log_error(format!( "Malformed #[resource] attribute for field `{}`: \ expected `binding` to be a positive integer.", field_name )); }; } NestedMeta::Meta(Meta::NameValue(ref m)) if m.path.is_ident("name") => { if let Lit::Str(n) = &m.lit { name = Some(n.value()); } else { log.log_error(format!( "Malformed #[resource] attribute for field `{}`: \ expected `name` to be a string.", field_name )); }; } _ => log.log_error(format!( "Malformed #[resource] attribute for field `{}`: unrecognized \ option `{}`.", field_name, meta_item.into_token_stream() )), } } if binding.is_none() { log.log_error(format!( "Field `{}` is marked with #[resource], but does not declare a `binding` \ index.", field_name )); } if name.is_none() { log.log_error(format!( "Field `{}` is marked with #[resource], but does not declare a slot name.", field_name )); } if binding.is_some() && name.is_some() { let binding = binding.unwrap(); let name = name.unwrap(); ResourcesField::Resource(ResourceField { ident: ast.ident.clone(), ty: ast.ty.clone(), position, binding, name, span: ast.span(), }) } else { ResourcesField::Excluded } } else { ResourcesField::Excluded } } } struct ResourceField { ident: Option<Ident>, ty: Type, position: usize, binding: u32, name: String, span: Span, } fn is_resource_attribute(attribute: &Attribute) -> bool { attribute.path.segments[0].ident == "resource" }
use proc_macro2::{Span, TokenStream}; use quote::{quote, quote_spanned, ToTokens}; use syn::spanned::Spanned; use syn::{Attribute, Data, DeriveInput, Field, Ident, Lit, Meta, NestedMeta, Type}; use crate::util::ErrorLog; pub fn expand_derive_resources(input: &DeriveInput) -> Result<TokenStream, String> { if let Data::Struct(ref data) = input.data { let struct_name = &input.ident; let mod_path = quote!(web_glitz::pipeline::resources); let mut log = ErrorLog::new();
enum ResourcesField { Resource(ResourceField), Excluded, } impl ResourcesField { pub fn from_ast(ast: &Field, position: usize, log: &mut ErrorLog) -> Self { let field_name = ast .ident .clone() .map(|i| i.to_string()) .unwrap_or(position.to_string()); let mut iter = ast.attrs.iter().filter(|a| is_resource_attribute(a)); if let Some(attr) = iter.next() { if iter.next().is_some() { log.log_error(format!( "Cannot add more than 1 #[resource] attribute to field `{}`.", field_name )); return ResourcesField::Excluded; } let meta_items: Vec<NestedMeta> = match attr.parse_meta() { Ok(Meta::List(list)) => list.nested.iter().cloned().collect(), Ok(Meta::Path(path)) if path.is_ident("resource") => Vec::new(), _ => { log.log_error(format!( "Malformed #[resource] attribute for field `{}`.", field_name )); Vec::new() } }; let mut binding = None; let mut name = ast.ident.clone().map(|i| i.to_string()); for meta_item in meta_items.into_iter() { match meta_item { NestedMeta::Meta(Meta::NameValue(m)) if m.path.is_ident("binding") => { if let Lit::Int(i) = &m.lit { if let Ok(value) = i.base10_parse::<u32>() { binding = Some(value); } else { log.log_error(format!( "Malformed #[resource] attribute for field `{}`: \ expected `binding` to be representable as a u32.", field_name )); } } else { log.log_error(format!( "Malformed #[resource] attribute for field `{}`: \ expected `binding` to be a positive integer.", field_name )); }; } NestedMeta::Meta(Meta::NameValue(ref m)) if m.path.is_ident("name") => { if let Lit::Str(n) = &m.lit { name = Some(n.value()); } else { log.log_error(format!( "Malformed #[resource] attribute for field `{}`: \ expected `name` to be a string.", field_name )); }; } _ => log.log_error(format!( "Malformed #[resource] attribute for field `{}`: unrecognized \ option `{}`.", field_name, meta_item.into_token_stream() )), } } if binding.is_none() { log.log_error(format!( "Field `{}` is marked with #[resource], but does not declare a `binding` \ index.", field_name )); } if name.is_none() { log.log_error(format!( "Field `{}` is marked with #[resource], but does not declare a slot name.", field_name )); } if binding.is_some() && name.is_some() { let binding = binding.unwrap(); let name = name.unwrap(); ResourcesField::Resource(ResourceField { ident: ast.ident.clone(), ty: ast.ty.clone(), position, binding, name, span: ast.span(), }) } else { ResourcesField::Excluded } } else { ResourcesField::Excluded } } } struct ResourceField { ident: Option<Ident>, ty: Type, position: usize, binding: u32, name: String, span: Span, } fn is_resource_attribute(attribute: &Attribute) -> bool { attribute.path.segments[0].ident == "resource" }
let mut resource_fields: Vec<ResourceField> = Vec::new(); for (position, field) in data.fields.iter().enumerate() { match ResourcesField::from_ast(field, position, &mut log) { ResourcesField::Resource(resource_field) => { for field in resource_fields.iter() { if field.binding == resource_field.binding { log.log_error(format!( "Fields `{}` and `{}` cannot both use binding `{}`.", field.name, resource_field.name, field.binding )); } } resource_fields.push(resource_field); } ResourcesField::Excluded => (), }; } let resource_slot_descriptors = resource_fields.iter().map(|field| { let ty = &field.ty; let slot_identifier = &field.name; let slot_index = field.binding as u32; let span = field.span; quote_spanned! {span=> #mod_path::TypedResourceSlotDescriptor { slot_identifier: #mod_path::ResourceSlotIdentifier::Static(#slot_identifier), slot_index: #slot_index, slot_type: <#ty as #mod_path::Resource>::TYPE } } }); let resource_types = resource_fields.iter().map(|field| { let ty = &field.ty; quote! { <#ty as #mod_path::Resource>::Encoding } }); let resource_encodings = resource_fields.iter().map(|field| { let field_name = field .ident .clone() .map(|i| i.into_token_stream()) .unwrap_or(field.position.into_token_stream()); let binding = field.binding as u32; quote! { let encoder = self.#field_name.encode(#binding, encoder); } }); let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let len = resource_fields.len(); let impl_block = quote! { #[automatically_derived] unsafe impl #impl_generics #mod_path::Resources for #struct_name #ty_generics #where_clause { type Encoding = (#(#resource_types,)*); const LAYOUT: &'static [#mod_path::TypedResourceSlotDescriptor] = &[ #(#resource_slot_descriptors,)* ]; fn encode_bind_group( self, context: &mut #mod_path::BindGroupEncodingContext, ) -> #mod_path::BindGroupEncoding<Self::Encoding> { let encoder = #mod_path::BindGroupEncoder::new(context, Some(#len)); #(#resource_encodings)* encoder.finish() } } }; let suffix = struct_name.to_string().trim_start_matches("r#").to_owned(); let dummy_const = Ident::new( &format!("_IMPL_RESOURCES_FOR_{}", suffix), Span::call_site(), ); let generated = quote! { #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] const #dummy_const: () = { #[allow(unknown_lints)] #[cfg_attr(feature = "cargo-clippy", allow(useless_attribute))] #[allow(rust_2018_idioms)] use #mod_path::Resource; #impl_block }; }; log.compile().map(|_| generated) } else { Err("`Resources` can only be derived for a struct.".into()) } }
function_block-function_prefix_line
[ { "content": "pub fn expand_derive_vertex(input: &DeriveInput) -> Result<TokenStream, String> {\n\n if let Data::Struct(ref data) = input.data {\n\n let struct_name = &input.ident;\n\n let mod_path = quote!(web_glitz::pipeline::graphics);\n\n let mut log = ErrorLog::new();\n\n\n\n let mut per_instance = false;\n\n\n\n for attribute in &input.attrs {\n\n if attribute.path.is_ident(\"vertex_per_instance\") {\n\n if !attribute.tokens.is_empty() {\n\n log.log_error(\"The `vertex_per_instance` attribute does not take parameters.\");\n\n } else {\n\n per_instance = true;\n\n }\n\n }\n\n }\n\n\n\n let input_rate = if per_instance {\n\n quote!(#mod_path::InputRate::PerInstance)\n", "file_path": "web_glitz_macros/src/vertex.rs", "rank": 1, "score": 218973.492273117 }, { "content": "pub fn expand_derive_interface_block(input: &DeriveInput) -> Result<TokenStream, String> {\n\n if let Data::Struct(data) = &input.data {\n\n let mod_path = quote!(web_glitz::pipeline::interface_block);\n\n let struct_name = &input.ident;\n\n\n\n let recurse_len = data.fields.iter().map(|field| {\n\n let ty = &field.ty;\n\n let span = field.span();\n\n\n\n quote_spanned! {span=>\n\n <#ty as #mod_path::InterfaceBlockComponent>::MEMORY_UNITS.len()\n\n }\n\n });\n\n\n\n let recurse_array = data.fields.iter().enumerate().map(|(position, field)| {\n\n let ty = &field.ty;\n\n let ident = field\n\n .ident\n\n .clone()\n\n .map(|i| i.into_token_stream())\n", "file_path": "web_glitz_macros/src/interface_block.rs", "rank": 2, "score": 214696.2364980414 }, { "content": "pub fn expand_derive_transform_feedback(input: &DeriveInput) -> TokenStream {\n\n if let Data::Struct(data) = &input.data {\n\n let struct_name = &input.ident;\n\n let mod_path = quote!(web_glitz::pipeline::graphics);\n\n\n\n let recurse = data.fields.iter().map(|field| {\n\n let name = field\n\n .ident\n\n .clone()\n\n .expect(\"`TransformFeedback` can only be derived for a struct with named fields.\")\n\n .to_string();\n\n let ty = &field.ty;\n\n let span = field.span();\n\n\n\n quote_spanned!(span=> {\n\n #mod_path::TransformFeedbackAttributeDescriptor {\n\n ident: #mod_path::TransformFeedbackAttributeIdentifier::Static(#name),\n\n attribute_type: <#ty as #mod_path::TransformFeedbackAttribute>::TYPE,\n\n size: <#ty as #mod_path::TransformFeedbackAttribute>::SIZE\n\n }\n", "file_path": "web_glitz_macros/src/transform_feedback.rs", "rank": 3, "score": 169918.95786953694 }, { "content": "#[proc_macro_derive(Vertex, attributes(vertex_per_instance, vertex_attribute))]\n\npub fn derive_vertex(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n vertex::expand_derive_vertex(&input)\n\n .unwrap_or_else(compile_error)\n\n .into()\n\n}\n\n\n", "file_path": "web_glitz_macros/src/lib.rs", "rank": 4, "score": 160932.93373732892 }, { "content": "#[proc_macro_derive(Resources, attributes(resource))]\n\npub fn derive_resources(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n resources::expand_derive_resources(&input)\n\n .unwrap_or_else(compile_error)\n\n .into()\n\n}\n\n\n", "file_path": "web_glitz_macros/src/lib.rs", "rank": 5, "score": 160932.93373732892 }, { "content": "#[proc_macro_derive(TransformFeedback)]\n\npub fn derive_transform_feedback(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n transform_feedback::expand_derive_transform_feedback(&input).into()\n\n}\n\n\n", "file_path": "web_glitz_macros/src/lib.rs", "rank": 6, "score": 159312.83278743038 }, { "content": "#[proc_macro_derive(InterfaceBlock)]\n\npub fn derive_interface_block(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n interface_block::expand_derive_interface_block(&input)\n\n .unwrap_or_else(compile_error)\n\n .into()\n\n}\n\n\n", "file_path": "web_glitz_macros/src/lib.rs", "rank": 7, "score": 159312.83278743038 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n // Obtain a reference to the `web_sys::HtmlCanvasElement` we want to render to.\n\n let canvas: HtmlCanvasElement = window()\n\n .unwrap()\n\n .document()\n\n .unwrap()\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n // Initialize a single threaded WebGlitz context for the canvas. This is unsafe: WebGlitz tracks\n\n // various bits of state for the context. There is currently no way to prevent you from simply\n\n // obtaining another copy of the WebGL 2.0 context and modifying the state while bypassing\n\n // WebGlitz's state tracking. Therefore, obtaining a WebGlitz context is only safe if:\n\n //\n\n // - the canvas context is in its default state (you've not previously obtained another context\n\n // and modified the state), and;\n\n // - you will not modify the context state through another copy of the context for as long as\n\n // the WebGlitz context remains alive.\n", "file_path": "examples/0_triangle/src/lib.rs", "rank": 8, "score": 154625.96568822145 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let canvas: HtmlCanvasElement = window()\n\n .unwrap()\n\n .document()\n\n .unwrap()\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n // We'll disable antialiasing on the default render target for this example, as resolve\n\n // operations require the destination to be a single-sample render target.\n\n let options = ContextOptions::begin()\n\n .enable_depth()\n\n .disable_antialias()\n\n .finish();\n\n\n\n let (context, mut default_render_target) =\n\n unsafe { single_threaded::init(&canvas, &options).unwrap() };\n\n\n", "file_path": "examples/8_resolve/src/lib.rs", "rank": 9, "score": 154625.96568822145 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let canvas: HtmlCanvasElement = window()\n\n .unwrap()\n\n .document()\n\n .unwrap()\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n // We won't use use the default context options this time. Instead we build our own options for\n\n // which we enable the depth buffer: without a depth buffer a depth test can't be performed (see\n\n // below).\n\n let (context, mut render_target) = unsafe {\n\n single_threaded::init(&canvas, &ContextOptions::begin().enable_depth().finish()).unwrap()\n\n };\n\n\n\n let vertex_shader = context\n\n .try_create_vertex_shader(include_str!(\"vertex.glsl\"))\n\n .unwrap();\n", "file_path": "examples/6_cube_3d/src/lib.rs", "rank": 10, "score": 154625.96568822145 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let canvas: HtmlCanvasElement = window()\n\n .unwrap()\n\n .document()\n\n .unwrap()\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n // We'll disable antialiasing on the default render target for this example, as blit operations\n\n // are only available on single-sample render targets.\n\n let options = ContextOptions::begin().disable_antialias().finish();\n\n\n\n let (context, mut default_render_target) =\n\n unsafe { single_threaded::init(&canvas, &options).unwrap() };\n\n\n\n let vertex_shader = context\n\n .try_create_vertex_shader(include_str!(\"vertex.glsl\"))\n\n .unwrap();\n", "file_path": "examples/4_blit/src/lib.rs", "rank": 11, "score": 154625.96568822145 }, { "content": "fn compile_error(message: String) -> proc_macro2::TokenStream {\n\n quote! {\n\n compile_error!(#message);\n\n }\n\n}\n", "file_path": "web_glitz_macros/src/lib.rs", "rank": 12, "score": 153859.74436062507 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let canvas: HtmlCanvasElement = window()\n\n .unwrap()\n\n .document()\n\n .unwrap()\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n let (context, mut render_target) =\n\n unsafe { single_threaded::init(&canvas, &ContextOptions::default()).unwrap() };\n\n\n\n let vertex_shader = context\n\n .try_create_vertex_shader(include_str!(\"vertex.glsl\"))\n\n .unwrap();\n\n\n\n let fragment_shader = context\n\n .try_create_fragment_shader(include_str!(\"fragment.glsl\"))\n\n .unwrap();\n", "file_path": "examples/1_uniform_block/src/lib.rs", "rank": 13, "score": 152468.57564770157 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let document = window().unwrap().document().unwrap();\n\n\n\n let canvas: HtmlCanvasElement = document\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n let (context, mut default_render_target) =\n\n unsafe { single_threaded::init(&canvas, &ContextOptions::default()).unwrap() };\n\n\n\n let primary_vertex_shader = context\n\n .try_create_vertex_shader(include_str!(\"primary_vertex.glsl\"))\n\n .unwrap();\n\n\n\n let primary_fragment_shader = context\n\n .try_create_fragment_shader(include_str!(\"primary_fragment.glsl\"))\n\n .unwrap();\n\n\n", "file_path": "examples/3_render_to_texture/src/lib.rs", "rank": 14, "score": 152468.57564770157 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let canvas: HtmlCanvasElement = window()\n\n .unwrap()\n\n .document()\n\n .unwrap()\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n let options = ContextOptions::begin()\n\n .enable_depth()\n\n .disable_antialias()\n\n .finish();\n\n\n\n let (context, _default_render_target) =\n\n unsafe { single_threaded::init(&canvas, &options).unwrap() };\n\n\n\n let buffer_a: Buffer<[u32]> = context.create_buffer([0, 1, 2, 3, 4], UsageHint::StreamRead);\n\n let buffer_b: Buffer<[u32]> = context.create_buffer([0, 0, 0, 0, 0], UsageHint::StreamCopy);\n", "file_path": "examples/9_buffer_copy_from/src/lib.rs", "rank": 15, "score": 152468.57564770157 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let document = window().unwrap().document().unwrap();\n\n\n\n let canvas: HtmlCanvasElement = document\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n let (context, mut render_target) =\n\n unsafe { single_threaded::init(&canvas, &ContextOptions::default()).unwrap() };\n\n\n\n let vertex_shader = context\n\n .try_create_vertex_shader(include_str!(\"vertex.glsl\"))\n\n .unwrap();\n\n\n\n let fragment_shader = context\n\n .try_create_fragment_shader(include_str!(\"fragment.glsl\"))\n\n .unwrap();\n\n\n", "file_path": "examples/2_textured_triangle/src/lib.rs", "rank": 16, "score": 152468.57564770157 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let window = window().unwrap();\n\n let document = window.document().unwrap();\n\n\n\n let canvas: HtmlCanvasElement = document\n\n .query_id(\"canvas\")\n\n .expect(\"No element with id `canvas`.\")\n\n .try_into()\n\n .expect(\"Element is not a canvas element.\");\n\n\n\n let (context, mut render_target) = unsafe {\n\n single_threaded::init(\n\n canvas.as_ref(),\n\n &ContextOptions::begin().enable_depth().finish(),\n\n )\n\n .unwrap()\n\n };\n\n\n\n let vertex_shader = context\n\n .try_create_vertex_shader(include_str!(\"vertex.glsl\"))\n", "file_path": "examples/7_cube_3d_animated/src/lib.rs", "rank": 17, "score": 152468.57564770157 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let canvas: HtmlCanvasElement = window()\n\n .unwrap()\n\n .document()\n\n .unwrap()\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n let (context, mut render_target) =\n\n unsafe { single_threaded::init(&canvas, &ContextOptions::default()).unwrap() };\n\n\n\n let vertex_shader = context\n\n .try_create_vertex_shader(include_str!(\"vertex.glsl\"))\n\n .unwrap();\n\n\n\n let fragment_shader = context\n\n .try_create_fragment_shader(include_str!(\"fragment.glsl\"))\n\n .unwrap();\n", "file_path": "examples/5_transform_feedback/src/lib.rs", "rank": 18, "score": 152468.57564770157 }, { "content": "fn main() {\n\n\n\n}\n\n\n", "file_path": "web_glitz_test/tests/compile-fail/vertex_attribute_invalid_type.rs", "rank": 19, "score": 120914.73321500627 }, { "content": "/// Combines task `a`, `b`, `c`, `d` and `e`, waiting for all tasks to complete in order, with the\n\n/// output of task `e`.\n\n///\n\n/// Similar to [sequence5], except that instead of returning a tuple of the outputs of `a`, `b`,\n\n/// `c`, `d` and `e`, it only returns the output of `e`.\n\n///\n\n/// See also [sequence5_left].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c`, `d` and `e` are not compatible.\n\npub fn sequence5_right<A, B, C, D, E, Ec>(\n\n a: A,\n\n b: B,\n\n c: C,\n\n d: D,\n\n e: E,\n\n) -> Sequence5Right<A, B, C, D, E, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n E: GpuTask<Ec>,\n\n{\n\n Sequence5Right::new(a, b, c, d, e)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 20, "score": 120835.59777644032 }, { "content": "/// Combines task `a`, `b`, `c`, `d` and `e`, waiting for all tasks to complete in order, with the\n\n/// output of task `a`.\n\n///\n\n/// Similar to [sequence5], except that instead of returning a tuple of the outputs of `a`, `b`,\n\n/// `c`, `d` and `e`, it only returns the output of `a`.\n\n///\n\n/// See also [sequence5_right].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c`, `d` and `e` are not compatible.\n\npub fn sequence5_left<A, B, C, D, E, Ec>(\n\n a: A,\n\n b: B,\n\n c: C,\n\n d: D,\n\n e: E,\n\n) -> Sequence5Left<A, B, C, D, E, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n E: GpuTask<Ec>,\n\n{\n\n Sequence5Left::new(a, b, c, d, e)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 21, "score": 120835.59777644032 }, { "content": "/// Describes a data source that can be used to provide indexing data to a draw command.\n\npub trait IndexData {\n\n /// Returns a descriptor of the index data.\n\n fn descriptor(&self) -> IndexDataDescriptor;\n\n}\n\n\n\nimpl<'a, T> IndexData for &'a IndexBuffer<T>\n\nwhere\n\n T: IndexFormat,\n\n{\n\n fn descriptor(&self) -> IndexDataDescriptor {\n\n IndexDataDescriptor {\n\n buffer_data: self.data.clone(),\n\n index_type: T::TYPE,\n\n offset: 0,\n\n len: self.len() as u32,\n\n }\n\n }\n\n}\n\n\n\nimpl<'a, T> IndexData for IndexBufferView<'a, T>\n", "file_path": "web_glitz/src/pipeline/graphics/vertex/index_buffer.rs", "rank": 22, "score": 116411.62854025821 }, { "content": "/// A resource bindings layout description attached to a type.\n\n///\n\n/// See also [TypedResourceBindingsLayoutDescriptor].\n\n///\n\n/// This trait becomes useful in combination with the [TypedResourceBindings] trait. If a\n\n/// [TypedResourceBindingsLayout] is attached to a [GraphicsPipeline] (see\n\n/// [GraphicsPipelineDescriptorBuilder::typed_resource_bindings_layout]), then\n\n/// [TypedResourceBindings] with a matching [TypedResourceBindings::Layout] may be bound to the\n\n/// pipeline without further runtime checks.\n\n///\n\n/// Note that [TypedResourceBindingsLayout] is safe to implement, but implementing\n\n/// [TypedResourceBindings] is unsafe: the resource bindings encoded by a [TypedResourceBindings]\n\n/// implementation must always be compatible with the bindings layout specified by its\n\n/// [TypedResourceBindings::Layout], see [TypedResourceBindings] for details.\n\npub trait TypedResourceBindingsLayout {\n\n const LAYOUT: TypedResourceBindingsLayoutDescriptor;\n\n}\n\n\n\nmacro_rules! implement_typed_resource_bindings_layout {\n\n ($($T:ident: $i:tt),*) => {\n\n #[allow(unused_parens)]\n\n impl<$($T),*> TypedResourceBindingsLayout for ($($T),*)\n\n where\n\n $($T: TypedBindGroupLayout),*\n\n {\n\n const LAYOUT: TypedResourceBindingsLayoutDescriptor = unsafe {\n\n TypedResourceBindingsLayoutDescriptor::new(&[\n\n $(TypedBindGroupLayoutDescriptor::new($i, $T::LAYOUT)),*\n\n ])\n\n };\n\n }\n\n }\n\n}\n\n\n", "file_path": "web_glitz/src/pipeline/resources/resources.rs", "rank": 23, "score": 116399.01574359456 }, { "content": "/// A description of the resource slot layout of a bind group, attached to a type.\n\n///\n\n/// See also [TypedResourceSlotDescriptor].\n\n///\n\n/// This trait becomes useful in combination with the [TypedBindableResourceGroup] and\n\n/// [TypedResourceBindings] traits, the later of which is implemented for any tuple of [BindGroup]s\n\n/// where each [BindGroup] holds resources that implement [TypedBindableResourceGroup]. If a\n\n/// pipeline (or a tuple of such bind groups) declares a typed resource bindings layout, then a\n\n/// (tuple of) bind group(s) with a matching resource layout may be safely bound to the pipeline\n\n/// without additional runtime checks.\n\n///\n\n/// Note that [TypedBindGroupLayout] is safe to implement, but implementing\n\n/// [TypedBindableResourceGroup] is unsafe: the resource bindings encoded by the\n\n/// [TypedBindableResourceGroup] implementation must always be compatible with the bind group\n\n/// layout specified by its [TypedBindableResourceGroup::Layout], see [TypedBindableResourceGroup]\n\n/// for details.\n\npub trait TypedBindGroupLayout {\n\n const LAYOUT: &'static [TypedResourceSlotDescriptor];\n\n}\n\n\n", "file_path": "web_glitz/src/pipeline/resources/resources.rs", "rank": 24, "score": 116398.56773041784 }, { "content": "/// Combines all tasks in an iterator, waiting for all tasks to complete in no particular order.\n\n///\n\n/// This returns a new \"joined\" task. This joined task may progress the its sub-tasks in any order.\n\n/// The joined task will finish when both sub-tasks have finished. When it finishes, it will output\n\n/// `()`. All tasks in the iterator must also output `()`.\n\n///\n\n/// This combinator allocates. See also the [join_all] macro for an alternative that does not\n\n/// allocate if the set of tasks that are to be sequenced is statically known.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s of any of the tasks in the iterator are not compatible.\n\npub fn join_iter<I, Ec>(iterator: I) -> JoinIter<I::Item, Ec>\n\nwhere\n\n I: IntoIterator,\n\n I::Item: GpuTask<Ec, Output = ()>,\n\n{\n\n JoinIter::new(iterator)\n\n}\n", "file_path": "web_glitz/src/task/join.rs", "rank": 25, "score": 115384.79558263664 }, { "content": "/// Combines all tasks in an iterator, waiting for all tasks to complete in order.\n\n///\n\n/// This returns a new \"sequenced\" task. This sequenced task must progress its sub-tasks in order.\n\n/// The sequenced task will finish when all sub-tasks have finished. When it finishes, it will\n\n/// output `()`. All tasks in the iterator must also output `()`.\n\n///\n\n/// This combinator allocates. See also the [sequence_all] macro for an alternative that does not\n\n/// allocate if the set of tasks that are to be joined is statically known.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s of any of the tasks in the iterator are not compatible.\n\npub fn sequence_iter<I, Ec>(iterator: I) -> SequenceIter<I::Item, Ec>\n\nwhere\n\n I: IntoIterator,\n\n I::Item: GpuTask<Ec, Output = ()>,\n\n{\n\n SequenceIter::new(iterator)\n\n}\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 26, "score": 115384.79558263664 }, { "content": "/// A helper trait for indexing a [LevelsMut].\n\n///\n\n/// See [LevelsMut::get_mut] and [LevelsMut::get_unchecked_mut].\n\npub trait LevelsMutIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked_mut(self, levels: &'a mut LevelsMut<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelsMutIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelMut<'a, F>;\n\n\n\n fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output> {\n\n if self < levels.len {\n\n Some(LevelMut {\n", "file_path": "web_glitz/src/image/texture_3d.rs", "rank": 27, "score": 113817.9641135401 }, { "content": "/// A helper trait for indexing a [LevelsMut].\n\n///\n\n/// See [LevelsMut::get_mut] and [LevelsMut::get_unchecked_mut].\n\npub trait LevelsMutIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked_mut(self, levels: &'a mut LevelsMut<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelsMutIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelMut<'a, F>;\n\n\n\n fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output> {\n\n if self < levels.inner.len {\n\n Some(LevelMut {\n", "file_path": "web_glitz/src/image/texture_2d.rs", "rank": 28, "score": 113817.9641135401 }, { "content": "/// A vertex input layout description attached to a type.\n\n///\n\n/// See also [VertexInputLayoutDescriptor].\n\n///\n\n/// This trait becomes useful in combination with the [TypedVertexBuffers] trait. If a\n\n/// [TypedVertexInputLayout] is attached to a [GraphicsPipeline] (see\n\n/// [GraphicsPipelineDescriptorBuilder::typed_vertex_input_layout]), then [TypedVertexBuffers] with\n\n/// a matching [TypedVertexBuffers::Layout] may be bound to the pipeline without further runtime\n\n/// checks.\n\n///\n\n/// Note that [TypedVertexInputLayout] is safe to implement, but implementing [TypedVertexBuffers]\n\n/// is unsafe: the data in the buffer representation for which [TypedVertexBuffers] is implemented\n\n/// must always be compatible with the vertex input layout specified by the\n\n/// [TypedVertexBuffers::Layout], see [TypedVertexBuffers] for details.\n\npub trait TypedVertexInputLayout {\n\n type LayoutDescription: Into<VertexInputLayoutDescriptor>;\n\n\n\n const LAYOUT_DESCRIPTION: Self::LayoutDescription;\n\n}\n\n\n\nimpl TypedVertexInputLayout for () {\n\n type LayoutDescription = ();\n\n\n\n const LAYOUT_DESCRIPTION: Self::LayoutDescription = ();\n\n}\n\n\n\nmacro_rules! impl_typed_vertex_input_layout {\n\n ($n:tt, $($T:ident),*) => {\n\n #[allow(unused_parens)]\n\n impl<$($T),*> TypedVertexInputLayout for ($($T),*) where $($T: Vertex),* {\n\n type LayoutDescription = [StaticVertexBufferSlotDescriptor; $n];\n\n\n\n const LAYOUT_DESCRIPTION: Self::LayoutDescription = [\n\n $(\n", "file_path": "web_glitz/src/pipeline/graphics/vertex/layout_descriptor.rs", "rank": 29, "score": 112963.5439470927 }, { "content": "/// Combines task `a` with another task `b`, waiting for both tasks to complete in order.\n\n///\n\n/// This returns a new \"sequenced\" task. This sequenced task must progress its sub-tasks in order.\n\n/// The sequenced task will finish when both sub-tasks have finished. When it finishes, it will\n\n/// output a tuple `(A, B)` where `A` is this tasks output and `B` is task `b`'s output.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s of `a` and `b` are not compatible.\n\npub fn sequence<A, B, Ec>(a: A, b: B) -> Sequence<A, B, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n{\n\n Sequence::new(a, b)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 30, "score": 112608.71689774362 }, { "content": "/// Combines task `a` with another task `b`, waiting for both tasks to complete in no particular\n\n/// order.\n\n///\n\n/// This returns a new \"joined\" task. This joined task may progress the its sub-tasks in any order.\n\n/// The joined task will finish when both sub-tasks have finished. When it finishes, it will output\n\n/// a tuple `(A, B)` where `A` is this task's output and `B` is task `b`'s output.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s of `a` and `b` are not compatible.\n\npub fn join<A, B, Ec>(a: A, b: B) -> Join<A, B, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n{\n\n Join::new(a, b)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 31, "score": 112608.71689774362 }, { "content": "/// A helper trait for indexing a [LevelsMut].\n\n///\n\n/// See [LevelsMut::get_mut] and [LevelsMut::get_unchecked_mut].\n\npub trait LevelsMutIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked_mut(self, levels: &'a mut LevelsMut<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelsMutIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelMut<'a, F>;\n\n\n\n fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output> {\n\n if self < levels.inner.len {\n\n Some(LevelMut {\n", "file_path": "web_glitz/src/image/texture_cube.rs", "rank": 32, "score": 111993.36284083562 }, { "content": "/// A helper trait for indexing a [LevelsMut].\n\n///\n\n/// See [LevelsMut::get_mut] and [LevelsMut::get_unchecked_mut].\n\npub trait LevelsMutIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked_mut(self, levels: &'a mut LevelsMut<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelsMutIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelMut<'a, F>;\n\n\n\n fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output> {\n\n if self < levels.len {\n\n Some(LevelMut {\n", "file_path": "web_glitz/src/image/texture_2d_array.rs", "rank": 33, "score": 111993.36284083562 }, { "content": "/// A helper trait for indexing a [LevelLayersMut].\n\n///\n\n/// See [LevelsMut::get_mut] and [LevelsMut::get_unchecked_mut].\n\npub trait LevelLayersMutIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get_mut(self, layers: &'a mut LevelLayersMut<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked_mut(self, layers: &'a mut LevelLayersMut<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelLayersMutIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelLayerMut<'a, F>;\n\n\n\n fn get_mut(self, layers: &'a mut LevelLayersMut<F>) -> Option<Self::Output> {\n\n if self < layers.len {\n\n Some(LevelLayerMut {\n", "file_path": "web_glitz/src/image/texture_3d.rs", "rank": 34, "score": 111993.34683444789 }, { "content": "/// A helper trait for indexing a [LevelLayersMut].\n\n///\n\n/// See [LevelsMut::get_mut] and [LevelsMut::get_unchecked_mut].\n\npub trait LevelLayersMutIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get_mut(self, layers: &'a mut LevelLayersMut<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked_mut(self, layers: &'a mut LevelLayersMut<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelLayersMutIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelLayerMut<'a, F>;\n\n\n\n fn get_mut(self, layers: &'a mut LevelLayersMut<F>) -> Option<Self::Output> {\n\n if self < layers.len {\n\n Some(LevelLayerMut {\n", "file_path": "web_glitz/src/image/texture_2d_array.rs", "rank": 35, "score": 110240.3413808233 }, { "content": "/// Combines task `a` with another task `b`, waiting for both tasks to complete in no particular\n\n/// order, with the output of task `a`.\n\n///\n\n/// Similar to [join], except that instead of returning a tuple of the outputs of `a` and `b`, it\n\n/// only returns the output of `a`.\n\n///\n\n/// See also [join_right].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s of `a` and `b` are not compatible.\n\npub fn join_left<A, B, Ec>(a: A, b: B) -> JoinLeft<A, B, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n{\n\n JoinLeft::new(a, b)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 36, "score": 109428.55265561161 }, { "content": "/// Combines task `a` with another task `b`, waiting for both tasks to complete in order, with the\n\n/// output of task `a`.\n\n///\n\n/// Similar to [sequence], except that instead of returning a tuple of the outputs of `a` and `b`,\n\n/// it only returns the output of `a`.\n\n///\n\n/// See also [sequence_right].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s of `a` and `b` are not compatible.\n\npub fn sequence_left<A, B, Ec>(a: A, b: B) -> SequenceLeft<A, B, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n{\n\n SequenceLeft::new(a, b)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 37, "score": 109428.55265561161 }, { "content": "/// Combines task `a` with another task `b`, waiting for both tasks to complete in order, with the\n\n/// output of task `a`.\n\n///\n\n/// Similar to [sequence], except that instead of returning a tuple of the outputs of `a` and `b`,\n\n/// it only returns the output of `b`.\n\n///\n\n/// See also [sequence_left].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s of `a` and `b` are not compatible.\n\npub fn sequence_right<A, B, Ec>(a: A, b: B) -> SequenceRight<A, B, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n{\n\n SequenceRight::new(a, b)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 38, "score": 109428.55265561161 }, { "content": "/// Combines task `a` with another task `b`, waiting for both tasks to complete in no particular\n\n/// order, with the output of task `a`.\n\n///\n\n/// Similar to [join], except that instead of returning a tuple of the outputs of `a` and `b`, it\n\n/// only returns the output of `b`.\n\n///\n\n/// See also [join_left].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s of `a` and `b` are not compatible.\n\npub fn join_right<A, B, Ec>(a: A, b: B) -> JoinRight<A, B, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n{\n\n JoinRight::new(a, b)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 39, "score": 109428.55265561161 }, { "content": "/// Combines task `a`, `b` and `c`, waiting for all tasks to complete in order.\n\n///\n\n/// This returns a new \"sequenced\" task. This sequenced task must progress its sub-tasks in order.\n\n/// The sequenced task will finish when all sub-tasks have finished. When it finishes, it will\n\n/// output a tuple `(A, B, C)` where `A` is this task's output, `B` is task `b`'s output and `C` is\n\n/// task `c`'s output.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b` and `c` are not compatible.\n\npub fn sequence3<A, B, C, Ec>(a: A, b: B, c: C) -> Sequence3<A, B, C, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n{\n\n Sequence3::new(a, b, c)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 40, "score": 103686.50293331376 }, { "content": "/// Combines task `a`, `b` and `c`, waiting for all tasks to complete in no particular order.\n\n///\n\n/// This returns a new \"joined\" task. This joined task may progress the its sub-tasks in any order.\n\n/// The joined task will finish when all sub-tasks have finished. When it finishes, it will output a\n\n/// tuple `(A, B, C)` where `A` is this task's output, `B` is task `b`'s output and `C` is task\n\n/// `c`'s output.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b` and `c` are not compatible.\n\npub fn join3<A, B, C, Ec>(a: A, b: B, c: C) -> Join3<A, B, C, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n{\n\n Join3::new(a, b, c)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 41, "score": 103686.50293331376 }, { "content": "/// A helper trait type for indexing operations on a [BufferViewMut] that contains a slice.\n\npub trait BufferViewMutSliceIndex<T>: BufferViewSliceIndex<T> {\n\n /// Returns a mutable view on the output for this operation if in bounds, or `None` otherwise.\n\n fn get_mut<'a>(\n\n self,\n\n view: &'a mut BufferViewMut<[T]>,\n\n ) -> Option<BufferViewMut<'a, Self::Output>> {\n\n self.get(view).map(|view| BufferViewMut {\n\n inner: view,\n\n _marker: marker::PhantomData,\n\n })\n\n }\n\n\n\n /// Returns a mutable view the output for this operation, without performing any bounds\n\n /// checking.\n\n unsafe fn get_unchecked_mut<'a>(\n\n self,\n\n view: &'a mut BufferViewMut<[T]>,\n\n ) -> BufferViewMut<'a, Self::Output> {\n\n BufferViewMut {\n\n inner: self.get_unchecked(view),\n", "file_path": "web_glitz/src/buffer.rs", "rank": 42, "score": 102165.85153396777 }, { "content": "/// Combines task `a`, `b` and `c`, waiting for all tasks to complete in order, with\n\n/// the output of task `c`.\n\n///\n\n/// Similar to [sequence3], except that instead of returning a tuple of the outputs of `a`, `b` and\n\n/// `c`, it only returns the output of `c`.\n\n///\n\n/// See also [sequence3_left].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b` and `c` are not compatible.\n\npub fn sequence3_right<A, B, C, Ec>(a: A, b: B, c: C) -> Sequence3Right<A, B, C, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n{\n\n Sequence3Right::new(a, b, c)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 43, "score": 100838.22554732421 }, { "content": "/// Combines task `a`, `b` and `c`, waiting for all tasks to complete in no particular order, with\n\n/// the output of task `a`.\n\n///\n\n/// Similar to [join3], except that instead of returning a tuple of the outputs of `a`, `b` and `c`,\n\n/// it only returns the output of `a`.\n\n///\n\n/// See also [join3_right].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b` and `c` are not compatible.\n\npub fn join3_left<A, B, C, Ec>(a: A, b: B, c: C) -> Join3Left<A, B, C, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n{\n\n Join3Left::new(a, b, c)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 44, "score": 100838.22554732421 }, { "content": "/// Combines task `a`, `b` and `c`, waiting for all tasks to complete in order, with the output of\n\n/// task `a`.\n\n///\n\n/// Similar to [sequence3], except that instead of returning a tuple of the outputs of `a`, `b` and\n\n/// `c`, it only returns the output of `a`.\n\n///\n\n/// See also [sequence3_right].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b` and `c` are not compatible.\n\npub fn sequence3_left<A, B, C, Ec>(a: A, b: B, c: C) -> Sequence3Left<A, B, C, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n{\n\n Sequence3Left::new(a, b, c)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 45, "score": 100838.22554732421 }, { "content": "/// Combines task `a`, `b` and `c`, waiting for all tasks to complete in no particular order, with\n\n/// the output of task `c`.\n\n///\n\n/// Similar to [join3], except that instead of returning a tuple of the outputs of `a`, `b` and `c`,\n\n/// it only returns the output of `c`.\n\n///\n\n/// See also [join3_left].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b` and `c` are not compatible.\n\npub fn join3_right<A, B, C, Ec>(a: A, b: B, c: C) -> Join3Right<A, B, C, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n{\n\n Join3Right::new(a, b, c)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 46, "score": 100838.22554732421 }, { "content": "/// Combines task `a`, `b`, `c` and `d`, waiting for all tasks to complete in order.\n\n///\n\n/// This returns a new \"sequenced\" task. This sequenced task must progress its sub-tasks in order.\n\n/// The sequenced task will finish when all sub-tasks have finished. When it finishes, it will\n\n/// output a tuple `(A, B, C, D)` where `A` is this tasks output, `B` is task `b`'s output, `C` is\n\n/// task `c`'s output and `D` is task `d`'s output.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c` and `d` are not compatible.\n\npub fn sequence4<A, B, C, D, Ec>(a: A, b: B, c: C, d: D) -> Sequence4<A, B, C, D, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n{\n\n Sequence4::new(a, b, c, d)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 47, "score": 96407.02235443675 }, { "content": "/// Combines task `a`, `b`, `c` and `d`, waiting for all tasks to complete in no particular order.\n\n///\n\n/// This returns a new \"joined\" task. This joined task may progress the its sub-tasks in any order.\n\n/// The joined task will finish when all sub-tasks have finished. When it finishes, it will output a\n\n/// tuple `(A, B, C, D)` where `A` is this task's output, `B` is task `b`'s output, `C` is task\n\n/// `c`'s output and `D` is task `d`'s output.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c` and `d` are not compatible.\n\npub fn join4<A, B, C, D, Ec>(a: A, b: B, c: C, d: D) -> Join4<A, B, C, D, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n{\n\n Join4::new(a, b, c, d)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 48, "score": 96407.02235443675 }, { "content": "/// Combines task `a`, `b`, `c` and `d`, waiting for all tasks to complete in order, with the output\n\n/// of task `d`.\n\n///\n\n/// Similar to [sequence4], except that instead of returning a tuple of the outputs of `a`, `b`, `c`\n\n/// and `d`, it only returns the output of `d`.\n\n///\n\n/// See also [sequence4_left].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c` and `d` are not compatible.\n\npub fn sequence4_right<A, B, C, D, Ec>(a: A, b: B, c: C, d: D) -> Sequence4Right<A, B, C, D, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n{\n\n Sequence4Right::new(a, b, c, d)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 49, "score": 93841.25965143347 }, { "content": "/// Combines task `a`, `b`, `c` and `d`, waiting for all tasks to complete in order,\n\n/// with the output of task `a`.\n\n///\n\n/// Similar to [sequence4], except that instead of returning a tuple of the outputs of `a`, `b`, `c`\n\n/// and `d`, it only returns the output of `a`.\n\n///\n\n/// See also [sequence4_right].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c` and `d` are not compatible.\n\npub fn sequence4_left<A, B, C, D, Ec>(a: A, b: B, c: C, d: D) -> Sequence4Left<A, B, C, D, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n{\n\n Sequence4Left::new(a, b, c, d)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 50, "score": 93841.25965143347 }, { "content": "/// Combines task `a`, `b`, `c` and `d`, waiting for all tasks to complete in no particular order,\n\n/// with the output of task `a`.\n\n///\n\n/// Similar to [join4], except that instead of returning a tuple of the outputs of `a`, `b`, `c` and\n\n/// `d`, it only returns the output of `a`.\n\n///\n\n/// See also [join4_right].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c` and `d` are not compatible.\n\npub fn join4_left<A, B, C, D, Ec>(a: A, b: B, c: C, d: D) -> Join4Left<A, B, C, D, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n{\n\n Join4Left::new(a, b, c, d)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 51, "score": 93841.25965143347 }, { "content": "/// Combines task `a`, `b`, `c` and `d`, waiting for all tasks to complete in no particular order,\n\n/// with the output of task `d`.\n\n///\n\n/// Similar to [join4], except that instead of returning a tuple of the outputs of `a`, `b`, `c` and\n\n/// `d`, it only returns the output of `d`.\n\n///\n\n/// See also [join4_left].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c` and `d` are not compatible.\n\npub fn join4_right<A, B, C, D, Ec>(a: A, b: B, c: C, d: D) -> Join4Right<A, B, C, D, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n{\n\n Join4Right::new(a, b, c, d)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 52, "score": 93841.25965143347 }, { "content": "/// Combines task `a`, `b`, `c`, `d` and `e`, waiting for all tasks to complete in order.\n\n///\n\n/// This returns a new \"sequenced\" task. This sequenced task must progress its sub-tasks in order.\n\n/// The sequenced task will finish when all sub-tasks have finished. When it finishes, it will\n\n/// output a tuple `(A, B, C, D, E)` where `A` is this tasks output, `B` is task `b`'s output, `C`\n\n/// is task `c`'s output, `D` is task `d`'s output and `E` is task `e`'s output.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c`, `d` and `e` are not compatible.\n\npub fn sequence5<A, B, C, D, E, Ec>(a: A, b: B, c: C, d: D, e: E) -> Sequence5<A, B, C, D, E, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n E: GpuTask<Ec>,\n\n{\n\n Sequence5::new(a, b, c, d, e)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 53, "score": 90281.22338232778 }, { "content": "/// Combines task `a`, `b`, `c`, `d` and `e`, waiting for all tasks to complete in no particular\n\n/// order.\n\n///\n\n/// This returns a new \"joined\" task. This joined task may progress the its sub-tasks in any order.\n\n/// The joined task will finish when all sub-tasks have finished. When it finishes, it will output a\n\n/// tuple `(A, B, C, D, E)` where `A` is this task's output, `B` is task `b`'s output, `C` is task\n\n/// `c`'s output, `D` is task `d`'s output and `E` is task `e`'s output.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c`, `d` and `e` are not compatible.\n\npub fn join5<A, B, C, D, E, Ec>(a: A, b: B, c: C, d: D, e: E) -> Join5<A, B, C, D, E, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n E: GpuTask<Ec>,\n\n{\n\n Join5::new(a, b, c, d, e)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 54, "score": 90281.22338232778 }, { "content": "/// Combines task `a`, `b`, `c`, `d` and `e`, waiting for all tasks to complete in no particular\n\n/// order, with the output of task `a`.\n\n///\n\n/// Similar to [join5], except that instead of returning a tuple of the outputs of `a`, `b`, `c`,\n\n/// `d` and `e`, it only returns the output of `a`.\n\n///\n\n/// See also [join5_right].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c`, `d` and `e` are not compatible.\n\npub fn join5_left<A, B, C, D, E, Ec>(a: A, b: B, c: C, d: D, e: E) -> Join5Left<A, B, C, D, E, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n E: GpuTask<Ec>,\n\n{\n\n Join5Left::new(a, b, c, d, e)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 55, "score": 87957.93250945074 }, { "content": "/// Combines task `a`, `b`, `c`, `d` and `e`, waiting for all tasks to complete in no particular\n\n/// order, with the output of task `e`.\n\n///\n\n/// Similar to [join5], except that instead of returning a tuple of the outputs of `a`, `b`, `c`,\n\n/// `d` and `e`, it only returns the output of `e`.\n\n///\n\n/// See also [join5_left].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c`, `d` and `e` are not compatible.\n\npub fn join5_right<A, B, C, D, E, Ec>(a: A, b: B, c: C, d: D, e: E) -> Join5Right<A, B, C, D, E, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n E: GpuTask<Ec>,\n\n{\n\n Join5Right::new(a, b, c, d, e)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 56, "score": 87957.93250945074 }, { "content": "#[test]\n\nfn compile_test() {\n\n run_mode(\"compile-fail\");\n\n}\n", "file_path": "web_glitz_test/tests/compile_test.rs", "rank": 57, "score": 78997.59512408351 }, { "content": "fn main() {\n\n\n\n}\n", "file_path": "web_glitz_test/tests/compile-fail/vertex_attribute_no_location.rs", "rank": 58, "score": 77056.61488292718 }, { "content": "/// Trait implemented for image references that can be attached to a render target.\n\n///\n\n/// See also [RenderTargetDescriptor].\n\npub trait AsAttachment {\n\n /// The type of image storage format the image is stored in.\n\n type Format: InternalFormat;\n\n\n\n /// Converts the image reference into a render target attachment.\n\n fn as_attachment(&mut self) -> Attachment<Self::Format>;\n\n}\n\n\n\nimpl<'a, T> AsAttachment for &'a mut T\n\nwhere\n\n T: AsAttachment,\n\n{\n\n type Format = T::Format;\n\n\n\n fn as_attachment(&mut self) -> Attachment<Self::Format> {\n\n (*self).as_attachment()\n\n }\n\n}\n\n\n\nimpl<'a, F> AsAttachment for Texture2DLevelMut<'a, F>\n", "file_path": "web_glitz/src/rendering/attachment.rs", "rank": 59, "score": 75497.65164968936 }, { "content": " pub trait Seal {}\n\n\n\n impl Seal for Nearest {}\n\n impl Seal for Linear {}\n\n impl Seal for NearestMipmapNearest {}\n\n impl Seal for NearestMipmapLinear {}\n\n impl Seal for LinearMipmapNearest {}\n\n impl Seal for LinearMipmapLinear {}\n\n}\n\n\n", "file_path": "web_glitz/src/image/sampler.rs", "rank": 60, "score": 75497.65164968936 }, { "content": "fn main() {\n\n\n\n}\n", "file_path": "web_glitz_test/tests/compile-fail/vertex_attribute_invalid_format_override.rs", "rank": 61, "score": 75267.95950557794 }, { "content": "#[test]\n\nfn test_struct_attribute_descriptors() {\n\n let descriptors = VertexA::ATTRIBUTE_DESCRIPTORS;\n\n\n\n assert_eq!(\n\n descriptors,\n\n &[\n\n VertexAttributeDescriptor {\n\n location: 0,\n\n format: VertexAttributeFormat::Float4_f32,\n\n offset_in_bytes: 0\n\n },\n\n VertexAttributeDescriptor {\n\n location: 1,\n\n format: VertexAttributeFormat::Float3_i8_norm,\n\n offset_in_bytes: 16\n\n },\n\n VertexAttributeDescriptor {\n\n location: 2,\n\n format: VertexAttributeFormat::Float4x4_f32,\n\n offset_in_bytes: 24\n", "file_path": "web_glitz_test/tests/vertex_macro_derive_test.rs", "rank": 62, "score": 75267.95950557794 }, { "content": "pub trait Options {\n\n type Output;\n\n\n\n unsafe fn get_context(&self, canvas: &HtmlCanvasElement) -> Self::Output;\n\n}\n\n\n\nimpl Options for ContextOptions<DefaultMultisampleRenderTarget<DefaultRGBABuffer, ()>> {\n\n type Output = Result<\n\n (\n\n SingleThreadedContext,\n\n DefaultMultisampleRenderTarget<DefaultRGBABuffer, ()>,\n\n ),\n\n String,\n\n >;\n\n\n\n unsafe fn get_context(&self, canvas: &HtmlCanvasElement) -> Self::Output {\n\n let options = JsValue::from_serde(&OptionsJson {\n\n alpha: true,\n\n antialias: true,\n\n depth: false,\n", "file_path": "web_glitz/src/runtime/single_threaded.rs", "rank": 63, "score": 74465.95002831638 }, { "content": "/// Trait implemented for image references that can be attached to a multisample render target.\n\n///\n\n/// See also [MultisampleRenderTargetDescriptor].\n\npub trait AsMultisampleAttachment {\n\n /// The type of image storage format the image is stored in.\n\n type SampleFormat: InternalFormat + Multisamplable;\n\n\n\n /// Converts the image reference into a render target attachment.\n\n fn as_multisample_attachment(&mut self) -> MultisampleAttachment<Self::SampleFormat>;\n\n}\n\n\n\nimpl<'a, T> AsMultisampleAttachment for &'a mut T\n\nwhere\n\n T: AsMultisampleAttachment,\n\n{\n\n type SampleFormat = T::SampleFormat;\n\n\n\n fn as_multisample_attachment(&mut self) -> MultisampleAttachment<Self::SampleFormat> {\n\n (*self).as_multisample_attachment()\n\n }\n\n}\n\n\n\nimpl<F> AsMultisampleAttachment for Renderbuffer<Multisample<F>>\n", "file_path": "web_glitz/src/rendering/attachment.rs", "rank": 64, "score": 74465.95002831638 }, { "content": "/// Encodes a description of how a set of resources is bound to a pipeline, such that the pipeline\n\n/// may access these resources during its execution.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use web_glitz::buffer::Buffer;\n\n/// use web_glitz::image::texture_2d::FloatSampledTexture2D;\n\n/// use web_glitz::pipeline::resources::{ResourceBindings, ResourceBindingsEncodingContext, ResourceBindingsEncoding, StaticResourceBindingsEncoder, BindGroup, BindGroupDescriptor};\n\n///\n\n/// struct Resources<T0, T1> {\n\n/// bind_group_0: BindGroup<T0>,\n\n/// bind_group_1: BindGroup<T1>,\n\n/// }\n\n///\n\n/// impl<T0, T1> ResourceBindings for &'_ Resources<T0, T1> {\n\n/// type BindGroups = [BindGroupDescriptor; 2];\n\n///\n\n/// fn encode(\n\n/// self,\n\n/// encoding_context: &mut ResourceBindingsEncodingContext\n\n/// ) -> ResourceBindingsEncoding<Self::BindGroups> {\n\n/// let encoder = StaticResourceBindingsEncoder::new(encoding_context);\n\n///\n\n/// let encoder = encoder.add_bind_group(0, &self.bind_group_0);\n\n/// let encoder = encoder.add_bind_group(1, &self.bind_group_1);\n\n///\n\n/// encoder.finish()\n\n/// }\n\n/// }\n\n/// ```\n\n///\n\n/// See also [StaticResourceBindingsEncoder].\n\n///\n\n/// Note that when multiple bindings of the same type bind to the same slot-index, then only the\n\n/// binding that was added last will be used. However, buffer resources and texture resources belong\n\n/// to distinct bind groups, their slot-indices do not interact.\n\n///\n\n/// This trait is automatically implemented for any type that derives the [Resources] trait.\n\npub trait ResourceBindings {\n\n /// Type that describes the collection of bindings.\n\n type BindGroups: Borrow<[BindGroupDescriptor]> + 'static;\n\n\n\n /// Encodes a description of how this set of resources is bound to a pipeline.\n\n fn encode(\n\n self,\n\n encoding_context: &mut ResourceBindingsEncodingContext,\n\n ) -> ResourceBindingsEncoding<Self::BindGroups>;\n\n}\n\n\n\nimpl ResourceBindings for () {\n\n type BindGroups = [BindGroupDescriptor; 0];\n\n\n\n fn encode(\n\n self,\n\n encoding_context: &mut ResourceBindingsEncodingContext,\n\n ) -> ResourceBindingsEncoding<Self::BindGroups> {\n\n ResourceBindingsEncoding::empty(encoding_context)\n\n }\n", "file_path": "web_glitz/src/pipeline/resources/resources.rs", "rank": 65, "score": 73495.35762259296 }, { "content": "/// Trait implemented by types that represent a rendering output buffer in the framebuffer for a\n\n/// custom render target.\n\npub trait RenderingOutputBuffer {\n\n /// The type image storage format used by the buffer.\n\n type Format: InternalFormat;\n\n\n\n /// The width of the buffer (in pixels).\n\n fn width(&self) -> u32;\n\n\n\n /// The height of the buffer (in pixels).\n\n fn height(&self) -> u32;\n\n}\n\n\n\n/// Represents a color buffer that stores floating point values in a framebuffer for a custom render\n\n/// target.\n\npub struct FloatBuffer<F> {\n\n render_pass_id: u64,\n\n index: i32,\n\n width: u32,\n\n height: u32,\n\n _marker: marker::PhantomData<Box<F>>,\n\n}\n", "file_path": "web_glitz/src/rendering/framebuffer.rs", "rank": 66, "score": 73482.60360657178 }, { "content": "/// Trait implemented by types that can serve as a WebGlitz rendering context.\n\n///\n\n/// The rendering context is the main interface of interaction with the Graphics Processing Unit\n\n/// (GPU). It has 4 main roles:\n\n///\n\n/// 1. Provide information about the abilities of the current GPU connection, see\n\n/// [max_supported_samples].\n\n/// 2. Act as a factory for the following WebGlitz objects:\n\n/// - [Buffer]s, see [create_buffer].\n\n/// - [Texture2D]s, see [try_create_texture_2d].\n\n/// - [Texture2DArray]s, see [try_create_texture_2d_array].\n\n/// - [Texture3D]s, see [try_create_texture_3d].\n\n/// - [TextureCube]s, see [try_create_texture_cube].\n\n/// - [Sampler]s, see [create_sampler].\n\n/// - [ShadowSampler]s, see [create_shadow_sampler].\n\n/// - [Renderbuffer]s, see [create_renderbuffer] and [try_create_multisample_renderbuffer].\n\n/// - [VertexShader]s, see [try_create_vertex_shader].\n\n/// - [FragmentShader]s, see [try_create_fragment_shader].\n\n/// - [GraphicsPipeline]s, see [try_create_graphics_pipeline].\n\n/// - [BindGroup]s, see [create_bind_group].\n\n/// - [RenderTarget]s, see [create_render_target], [try_create_render_target],\n\n/// [create_multisample_render_target] and [try_create_multisample_render_target].\n\n/// 3. Submission of [GpuTask]s to the GPU with [submit].\n\n/// 4. Extension initialization, see [get_extension].\n\npub trait RenderingContext {\n\n /// Identifier that uniquely identifies this rendering context.\n\n fn id(&self) -> u64;\n\n\n\n /// Returns the requested extension, or `None` if the extension is not available on this\n\n /// context.\n\n ///\n\n /// See the [web_glitz::extensions] module for the available extensions.\n\n fn get_extension<T>(&self) -> Option<T>\n\n where\n\n T: Extension;\n\n\n\n /// Returns information about the sampling grid sizes that are supported for the `format` in\n\n /// descending order of size.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n\n /// # use web_glitz::runtime::{RenderingContext, SupportedSamples};\n\n /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {\n", "file_path": "web_glitz/src/runtime/rendering_context.rs", "rank": 67, "score": 73479.73773013195 }, { "content": "/// Helper trait implemented by color buffers that can serve as a target for a [BlitCommand],\n\n/// see [Framebuffer::blit_color_nearest_command] and [Framebuffer::blit_color_linear_command].\n\npub trait BlitColorTarget {\n\n /// Encapsulates the information about the color target needed by the [BlitCommand].\n\n fn descriptor(&self) -> BlitTargetDescriptor;\n\n}\n\n\n\nimpl BlitColorTarget for DefaultRGBBuffer {\n\n fn descriptor(&self) -> BlitTargetDescriptor {\n\n BlitTargetDescriptor {\n\n internal: BlitTargetDescriptorInternal::Default,\n\n }\n\n }\n\n}\n\n\n\nimpl BlitColorTarget for DefaultRGBABuffer {\n\n fn descriptor(&self) -> BlitTargetDescriptor {\n\n BlitTargetDescriptor {\n\n internal: BlitTargetDescriptorInternal::Default,\n\n }\n\n }\n\n}\n", "file_path": "web_glitz/src/rendering/framebuffer.rs", "rank": 68, "score": 73477.26331383846 }, { "content": "/// Trait implemented for types that represent or contain data that may be stored in a [Buffer].\n\n///\n\n/// Uploading data to a buffer involves doing a bitwise copy, as does downloading data from a\n\n/// buffer. WebGlitz relies on the semantics associated with the `Copy` trait to ensure that this\n\n/// is safe and does not result in memory leaks.\n\npub trait IntoBuffer<T>\n\nwhere\n\n T: ?Sized,\n\n{\n\n /// Stores the data in a buffer belonging to the given `context`, using the given `usage_hint`.\n\n ///\n\n /// This consumes the Rust value and produces a GPU-accessible [Buffer] containing a bitwise\n\n /// copy of data.\n\n ///\n\n /// The usage hint may be used by the GPU driver for performance optimizations, see [UsageHint]\n\n /// for details.\n\n fn into_buffer<Rc>(self, context: &Rc, buffer_id: BufferId, usage_hint: UsageHint) -> Buffer<T>\n\n where\n\n Rc: RenderingContext + Clone + 'static;\n\n}\n\n\n\nimpl<D, T> IntoBuffer<T> for D\n\nwhere\n\n D: Borrow<T> + 'static,\n\n T: Copy + 'static,\n", "file_path": "web_glitz/src/buffer.rs", "rank": 69, "score": 73112.02891272989 }, { "content": "/// Helper trait for [Buffer::copy_from_command] and [BufferView::copy_from_command], implemented\n\n/// for types that can be copied from.\n\npub trait CopyFrom<T>\n\nwhere\n\n T: ?Sized,\n\n{\n\n fn command(self, target_view: BufferView<T>) -> CopyCommand<T>;\n\n}\n\n\n\nimpl<'a, T> CopyFrom<T> for &'a Buffer<T> {\n\n fn command(self, target_view: BufferView<T>) -> CopyCommand<T> {\n\n if self.data.context_id != target_view.buffer.data.context_id {\n\n panic!(\"Source and target buffer must belong to the same context.\");\n\n }\n\n\n\n CopyCommand {\n\n target: target_view.buffer.data.clone(),\n\n source: self.data.clone(),\n\n target_offset_in_bytes: target_view.offset_in_bytes(),\n\n source_offset_in_bytes: 0,\n\n size_in_bytes: mem::size_of::<T>(),\n\n _marker: marker::PhantomData,\n", "file_path": "web_glitz/src/buffer.rs", "rank": 70, "score": 73106.59411619933 }, { "content": "/// Trait implemented for extension objects, used by [RenderingContext::get_extension] to\n\n/// initialize the extension.\n\npub trait Extension: Sized {\n\n /// Attempts to initialize the extension on the current [Connection] and return the extension\n\n /// object, or returns `None` if it fails.\n\n fn try_init(connection: &mut Connection, context_id: u64) -> Option<Self>;\n\n}\n", "file_path": "web_glitz/src/extensions/mod.rs", "rank": 71, "score": 72074.90658270556 }, { "content": "/// A group of resources that may be used to encode a [BindGroup].\n\n///\n\n/// See also [RenderingContext::create_bind_group] for details on how a [BindGroup] is created.\n\n///\n\n/// This trait is implemented for any type that implements the [Resources] trait. The [Resources]\n\n/// trait may automatically derived (see the documentation for the [Resources] trait for details).\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use web_glitz::buffer::{Buffer, BufferView};\n\n/// use web_glitz::image::texture_2d::FloatSampledTexture2D;\n\n/// use web_glitz::pipeline::resources::{EncodeBindableResourceGroup, BindGroupEncodingContext, BindGroupEncoding, BindGroupEncoder};\n\n///\n\n/// struct Resources<'a, 'b> {\n\n/// uniform_buffer: &'a Buffer<std140::mat4x4>,\n\n/// texture: FloatSampledTexture2D<'b>\n\n/// }\n\n///\n\n/// impl<'a, 'b> EncodeBindableResourceGroup for Resources<'a, 'b> {\n\n/// type Encoding = (\n\n/// BufferView<'a, std140::mat4x4>,\n\n/// FloatSampledTexture2D<'b>,\n\n/// );\n\n///\n\n/// fn encode_bindable_resource_group(\n\n/// self,\n\n/// encoding_context: &mut BindGroupEncodingContext\n\n/// ) -> BindGroupEncoding<Self::Encoding> {\n\n/// BindGroupEncoder::new(encoding_context, Some(2))\n\n/// .add_buffer_view(0, self.uniform_buffer.into())\n\n/// .add_float_sampled_texture_2d(1, self.texture)\n\n/// .finish()\n\n/// }\n\n/// }\n\n/// ```\n\npub trait EncodeBindableResourceGroup {\n\n type Encoding;\n\n\n\n /// Encodes a description of the bindings for the resources in the group.\n\n fn encode_bindable_resource_group(\n\n self,\n\n encoding_context: &mut BindGroupEncodingContext,\n\n ) -> BindGroupEncoding<Self::Encoding>;\n\n}\n\n\n\n/// Sub-trait of [EncodeBindGroup], where a type statically describes the layout for the bind group.\n\n///\n\n/// A [BindGroup] for resources that implement this trait may be bound to pipeline's with a matching\n\n/// typed resource bindings layout without additional runtime checks.\n\n///\n\n/// # Unsafe\n\n///\n\n/// Any instance of a type that implements this trait must encode a bind group (see\n\n/// [EncodeBindGroup::encode_bind_group]) with a layout that matches the bind group layout declared\n\n/// by [Layout].\n\npub unsafe trait TypedBindableResourceGroup: EncodeBindableResourceGroup {\n\n type Layout: TypedBindGroupLayout;\n\n}\n\n\n", "file_path": "web_glitz/src/pipeline/resources/resources.rs", "rank": 72, "score": 71632.50715814336 }, { "content": "/// Helper trait for the implementation of [VertexBuffers] for tuple types.\n\npub trait VertexBuffer {\n\n fn encode(self, encoding: &mut VertexBuffersEncoding);\n\n}\n\n\n\n/// Sub-trait of [VertexBuffers], where a type statically describes the vertex attribute layout\n\n/// supported by the vertex buffers.\n\n///\n\n/// Vertex buffers that implement this trait may be bound to graphics pipelines with a matching\n\n/// [TypedVertexAttributeLayout] without further runtime checks.\n\n///\n\n/// # Unsafe\n\n///\n\n/// This trait must only by implemented for [VertexBuffers] types if the vertex buffers encoding\n\n/// for any instance of the the type is guaranteed to provide compatible vertex input data for\n\n/// each of the [VertexAttributeDescriptors] specified by the [Layout].\n\npub unsafe trait TypedVertexBuffers: VertexBuffers {\n\n /// A type statically associated with a vertex attribute layout with which any instance of these\n\n /// [TypedVertexBuffers] is compatible.\n\n type Layout: TypedVertexInputLayout;\n\n}\n", "file_path": "web_glitz/src/pipeline/graphics/vertex/vertex_buffers.rs", "rank": 73, "score": 71624.14236269839 }, { "content": "/// Helper trait implemented by types that describe a color image attachment for a [RenderTarget].\n\npub trait EncodeColorBuffer {\n\n /// The type of [RenderingOutputBuffer] that is allocated in the framebuffer to buffer\n\n /// modifications to the attached image.\n\n type Buffer: RenderingOutputBuffer;\n\n\n\n /// Returns an encoding of the information needed by a [RenderPass] to load data from the\n\n /// attached image into the framebuffer before the render pass, and to store data from the\n\n /// framebuffer back into the attached image after the render pass.\n\n fn encode_color_buffer<'a, 'b>(\n\n &'a mut self,\n\n context: &'b mut ColorBufferEncodingContext,\n\n ) -> ColorBufferEncoding<'b, 'a, Self::Buffer>;\n\n}\n\n\n", "file_path": "web_glitz/src/rendering/encode_color_buffer.rs", "rank": 74, "score": 71623.99302353684 }, { "content": "/// Encodes a description of a (set of) buffer(s) or buffer region(s) that can serve as the vertex\n\n/// input data source(s) for a graphics pipeline.\n\npub trait VertexBuffers {\n\n fn encode<'a>(self, context: &'a mut VertexBuffersEncodingContext)\n\n -> VertexBuffersEncoding<'a>;\n\n}\n\n\n", "file_path": "web_glitz/src/pipeline/graphics/vertex/vertex_buffers.rs", "rank": 75, "score": 71623.68051355064 }, { "content": "/// Helper trait implemented by types that describe a multisample color image attachment for a\n\n/// [MultisampleRenderTarget].\n\npub trait EncodeMultisampleColorBuffer {\n\n /// The type of [RenderingOutputBuffer] that is allocated in the framebuffer to buffer\n\n /// modifications to the attached image.\n\n type Buffer: RenderingOutputBuffer;\n\n\n\n /// Returns an encoding of the information needed by a [RenderPass] to load data from the\n\n /// attached image into the framebuffer before the render pass, and to store data from the\n\n /// framebuffer back into the attached image after the render pass.\n\n fn encode_multisample_color_buffer<'a, 'b>(\n\n &'a mut self,\n\n context: &'b mut ColorBufferEncodingContext,\n\n ) -> ColorBufferEncoding<'b, 'a, Self::Buffer>;\n\n}\n\n\n\n/// Provides the context for encoding a [ColorAttachmentDescription].\n\n///\n\n/// See [ColorAttachmentDescription::encode].\n\npub struct ColorBufferEncodingContext {\n\n pub(crate) render_pass_id: u64,\n\n pub(crate) buffer_index: i32,\n", "file_path": "web_glitz/src/rendering/encode_color_buffer.rs", "rank": 76, "score": 70749.26771519097 }, { "content": "/// Trait implemented by attribute format identifiers.\n\n///\n\n/// Helper trait which, in conjunction with [FormatCompatible], allows the derive macro for the\n\n/// [Vertex] trait to verify at compile time that an attribute field type is compatible with the\n\n/// specified attribute format.\n\npub trait VertexAttributeFormatIdentifier {\n\n /// The [AttributeFormat] associated with this [AttributeFormatIdentifier].\n\n const FORMAT: VertexAttributeFormat;\n\n}\n\n\n\npub struct Float_f32;\n\n\n\nimpl VertexAttributeFormatIdentifier for Float_f32 {\n\n const FORMAT: VertexAttributeFormat = VertexAttributeFormat::Float_f32;\n\n}\n\n\n\npub struct Float_i8_fixed;\n\n\n\nimpl VertexAttributeFormatIdentifier for Float_i8_fixed {\n\n const FORMAT: VertexAttributeFormat = VertexAttributeFormat::Float_i8_fixed;\n\n}\n\n\n\npub struct Float_i8_norm;\n\n\n\nimpl VertexAttributeFormatIdentifier for Float_i8_norm {\n", "file_path": "web_glitz/src/pipeline/graphics/vertex/attribute_format.rs", "rank": 77, "score": 69912.57828249052 }, { "content": "/// Helper trait implemented by types that describe a depth-stencil image attachment for a\n\n/// [RenderTarget].\n\npub trait EncodeDepthStencilBuffer {\n\n /// The type of [RenderingOutputBuffer] that is allocated in the framebuffer to buffer\n\n /// modifications to the attached image.\n\n type Buffer: RenderingOutputBuffer;\n\n\n\n /// Returns an encoding of the information needed by a [RenderPass] to load data from the\n\n /// attached image into the framebuffer before the render pass, and to store data from the\n\n /// framebuffer back into the attached image after the render pass.\n\n fn encode_depth_stencil_buffer<'a, 'b>(\n\n &'a mut self,\n\n context: &'b mut DepthStencilBufferEncodingContext,\n\n ) -> DepthStencilBufferEncoding<'b, 'a, Self::Buffer>;\n\n}\n\n\n", "file_path": "web_glitz/src/rendering/encode_depth_stencil_buffer.rs", "rank": 78, "score": 69908.34409681638 }, { "content": "/// Helper trait for the implementation of [FeedbackBuffers] for tuple types.\n\npub trait TransformFeedbackBuffer {\n\n fn encode(self, encoding: &mut TransformFeedbackBuffersEncoding);\n\n}\n\n\n\n/// Sub-trait of [TransformFeedbackBuffers], where a type statically describes the feedback\n\n/// attribute layout supported by the feedback buffers.\n\n///\n\n/// Transform feedback buffers that implement this trait may be bound to graphics pipelines with a\n\n/// matching [TypedTransformFeedbackLayout] without further runtime checks.\n\n///\n\n/// # Unsafe\n\n///\n\n/// This trait must only by implemented for [FeedbackBuffers] types if the feedback buffers encoding\n\n/// for any instance of the the type is guaranteed to be bit-wise compatible with the output\n\n/// feedback recorded from the graphics pipeline.\n\npub unsafe trait TypedTransformFeedbackBuffers: TransformFeedbackBuffers {\n\n /// A type statically associated with a feedback attribute layout with which any instance of\n\n /// these [TypedFeedbackBuffers] is compatible.\n\n type Layout: TypedTransformFeedbackLayout;\n\n}\n", "file_path": "web_glitz/src/pipeline/graphics/transform_feedback/transform_feedback_buffers.rs", "rank": 80, "score": 69099.32368932627 }, { "content": "/// Helper trait implemented by types that describe a multisampledepth-stencil image attachment for\n\n/// a [MultisampleRenderTarget].\n\npub trait EncodeMultisampleDepthStencilBuffer {\n\n /// The type of [RenderingOutputBuffer] that is allocated in the framebuffer to buffer\n\n /// modifications to the attached image.\n\n type Buffer: RenderingOutputBuffer;\n\n\n\n /// Returns an encoding of the information needed by a [RenderPass] to load data from the\n\n /// attached image into the framebuffer before the render pass, and to store data from the\n\n /// framebuffer back into the attached image after the render pass.\n\n fn encode_multisample_depth_stencil_buffer<'a, 'b>(\n\n &'a mut self,\n\n context: &'b mut DepthStencilBufferEncodingContext,\n\n ) -> DepthStencilBufferEncoding<'b, 'a, Self::Buffer>;\n\n}\n\n\n\npub struct DepthStencilBufferEncodingContext {\n\n pub(crate) render_pass_id: u64,\n\n}\n\n\n\npub struct DepthStencilBufferEncoding<'a, 'b, B> {\n\n pub(crate) buffer: B,\n", "file_path": "web_glitz/src/rendering/encode_depth_stencil_buffer.rs", "rank": 81, "score": 69099.07918656181 }, { "content": "/// Encodes a description of a (set of) buffer(s) or buffer region(s) that can record the output\n\n/// feedback from the transform stage of a graphics pipeline.\n\npub trait TransformFeedbackBuffers {\n\n fn encode<'a>(\n\n self,\n\n context: &'a mut TransformFeedbackBuffersEncodingContext,\n\n ) -> TransformFeedbackBuffersEncoding<'a>;\n\n}\n\n\n", "file_path": "web_glitz/src/pipeline/graphics/transform_feedback/transform_feedback_buffers.rs", "rank": 82, "score": 69093.78605171156 }, { "content": "pub trait ContextUpdate<'a, E> {\n\n fn apply(self, context: &Gl) -> Result<(), E>;\n\n}\n\n\n\nimpl<'a, F, E> ContextUpdate<'a, E> for Option<F>\n\nwhere\n\n F: FnOnce(&Gl) -> Result<(), E> + 'a,\n\n{\n\n fn apply(self, context: &Gl) -> Result<(), E> {\n\n self.map(|f| f(context)).unwrap_or(Ok(()))\n\n }\n\n}\n\n\n\n#[derive(Clone, Copy)]\n\npub enum BufferRange<T> {\n\n None,\n\n Full(T),\n\n OffsetSize(T, u32, u32),\n\n}\n\n\n", "file_path": "web_glitz/src/runtime/state.rs", "rank": 83, "score": 69074.81504752964 }, { "content": "/// A helper trait for indexing [Levels].\n\n///\n\n/// See [Levels::get] and [Levels::get_unchecked].\n\npub trait LevelsIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, levels: &'a Levels<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, levels: &'a Levels<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelsIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = Level<'a, F>;\n\n\n\n fn get(self, levels: &'a Levels<F>) -> Option<Self::Output> {\n\n if self < levels.len {\n\n Some(Level {\n", "file_path": "web_glitz/src/image/texture_3d.rs", "rank": 84, "score": 69074.81504752964 }, { "content": "/// A helper trait for indexing [Levels].\n\n///\n\n/// See [Levels::get] and [Levels::get_unchecked].\n\npub trait LevelsIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, levels: &'a Levels<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, levels: &'a Levels<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelsIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = Level<'a, F>;\n\n\n\n fn get(self, levels: &'a Levels<F>) -> Option<Self::Output> {\n\n if self < levels.len {\n\n Some(Level {\n", "file_path": "web_glitz/src/image/texture_2d.rs", "rank": 85, "score": 69074.81504752964 }, { "content": "fn run_mode(mode: &'static str) {\n\n let mut config = compiletest::Config::default();\n\n\n\n config.mode = mode.parse().expect(\"Invalid mode\");\n\n config.src_base = PathBuf::from(format!(\"tests/{}\", mode));\n\n config.link_deps(); // Populate config.target_rustcflags with dependencies on the path\n\n config.clean_rmeta(); // If your tests import the parent crate, this helps with E0464\n\n\n\n compiletest::run_tests(&config);\n\n}\n\n\n", "file_path": "web_glitz_test/tests/compile_test.rs", "rank": 86, "score": 68457.80890622958 }, { "content": "/// A helper trait type for indexing operations on a [Buffer] that contains a slice.\n\npub trait BufferSliceIndex<T>: Sized {\n\n /// The output type returned by the indexing operations.\n\n type Output: ?Sized;\n\n\n\n /// Returns a view on the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, buffer: &Buffer<[T]>) -> Option<BufferView<Self::Output>>;\n\n\n\n /// Returns a view on the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, buffer: &Buffer<[T]>) -> BufferView<Self::Output>;\n\n\n\n /// Returns a mutable view on the output for this operation if in bounds, or `None` otherwise.\n\n fn get_mut(self, buffer: &mut Buffer<[T]>) -> Option<BufferViewMut<Self::Output>> {\n\n self.get(buffer).map(|view| BufferViewMut {\n\n inner: view,\n\n _marker: marker::PhantomData,\n\n })\n\n }\n\n\n\n /// Returns a mutable view the output for this operation, without performing any bounds\n\n /// checking.\n", "file_path": "web_glitz/src/buffer.rs", "rank": 87, "score": 68131.99498005511 }, { "content": "/// A helper trait for indexing [Levels].\n\n///\n\n/// See [Levels::get] and [Levels::get_unchecked].\n\npub trait LevelsIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, levels: &'a Levels<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, levels: &'a Levels<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelsIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = Level<'a, F>;\n\n\n\n fn get(self, levels: &'a Levels<F>) -> Option<Self::Output> {\n\n if self < levels.len {\n\n Some(Level {\n", "file_path": "web_glitz/src/image/texture_cube.rs", "rank": 88, "score": 68126.50803351987 }, { "content": "/// A helper trait for indexing [LevelLayers].\n\n///\n\n/// See [LevelLayers::get] and [LevelLayers::get_unchecked].\n\npub trait LevelLayersIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, layers: &'a LevelLayers<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, layers: &'a LevelLayers<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelLayersIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelLayer<'a, F>;\n\n\n\n fn get(self, layers: &'a LevelLayers<F>) -> Option<Self::Output> {\n\n if self < layers.len {\n\n Some(LevelLayer {\n", "file_path": "web_glitz/src/image/texture_3d.rs", "rank": 89, "score": 68126.50803351987 }, { "content": "/// A helper trait for indexing [Levels].\n\n///\n\n/// See [Levels::get] and [Levels::get_unchecked].\n\npub trait LevelsIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, levels: &'a Levels<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, levels: &'a Levels<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelsIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = Level<'a, F>;\n\n\n\n fn get(self, levels: &'a Levels<F>) -> Option<Self::Output> {\n\n if self < levels.len {\n\n Some(Level {\n", "file_path": "web_glitz/src/image/texture_2d_array.rs", "rank": 90, "score": 68126.50803351987 }, { "content": "/// Sealed trait implemented for marker types that identify magnification filtering operations used\n\n/// by [Sampler]s.\n\n///\n\n/// Magnification filtering is used when a sampling a texture value for a fragment that is smaller\n\n/// than the candidate texels. See [Nearest] and [Linear] for details on how these filtering\n\n/// operations resolve to sampling values.\n\npub trait MagnificationFilter: filter_seal::Seal {\n\n const ID: u32;\n\n}\n\n\n", "file_path": "web_glitz/src/image/sampler.rs", "rank": 91, "score": 67226.37103494347 }, { "content": "/// Sealed trait implemented for marker types that identify minification filtering operations used\n\n/// by [Sampler]s.\n\n///\n\n/// Minification filtering is used when a sampling a texture value for a fragment that is larger\n\n/// than the candidate texels.\n\n///\n\n/// # Minification Filtering and Mipmapping\n\n///\n\n/// Some of the filtering methods involve mipmapping. When a fragment is larger than the candidate\n\n/// texels, the fragment surface might span multiple texels. The most appropriate sample value might\n\n/// then be obtained by interpolating between these texels. However, doing this for each sampling\n\n/// operation can be very expensive.\n\n///\n\n/// This is instead solved by using a mipmap, which produces similar results with much better\n\n/// performance. A mipmap is a pre-calculated sequence of images, starting with the original image.\n\n/// Each subsequent image is half the width and half the height of the previous image (rounded\n\n/// down). The sequence ends when the width or height reaches 1. Each image in the mipmap sequence\n\n/// is identified by a mipmap level: the base image has a mipmap level of 0, the subsequent image\n\n/// has a mipmap level of 1, etc. For example, a mipmap of a base image of size 256 by 256 has 9\n\n/// mipmap levels: 256x256 (level 0), 128x128 (level 1), 64x64 (level 2), 32x32 (level 3), 16x16\n\n/// (level 4), 8x8 (level 5), 4x4 (level 6), 2x2 (level 7), 1x1 (level 8).\n\n///\n\n/// See the documentation for [NearestMipmapNearest], [NearestMipmapLinear], [LinearMipmapNearest]\n\n/// and [LinearMipmapLinear] for details on how these filtering operations will make use of a\n\n/// mipmap. See [Nearest] and [Linear] for details on filtering operations that don't use a mipmap.\n\npub trait MinificationFilter: filter_seal::Seal {\n\n const ID: u32;\n\n}\n\n\n\n/// Marker trait for valid filter and texture format combinations\n\npub unsafe trait CompatibleFilter<F>\n\nwhere\n\n F: TextureFormat,\n\n{\n\n}\n\n\n\n/// The sampled value is chosen to be the value of the texel whose coordinates are closest to\n\n/// the sampling coordinates.\n\n#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n\npub struct Nearest;\n\n\n\nimpl MinificationFilter for Nearest {\n\n const ID: u32 = Gl::NEAREST;\n\n}\n\n\n", "file_path": "web_glitz/src/image/sampler.rs", "rank": 92, "score": 67223.75126203352 }, { "content": "/// A helper trait type for indexing operations on a [BufferView] that contains a slice.\n\npub trait BufferViewSliceIndex<T>: Sized {\n\n /// The output type returned by the indexing operations.\n\n type Output: ?Sized;\n\n\n\n /// Returns a view on the output for this operation if in bounds, or `None` otherwise.\n\n fn get<'a>(self, view: &'a BufferView<[T]>) -> Option<BufferView<'a, Self::Output>>;\n\n\n\n /// Returns a view on the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked<'a>(self, view: &'a BufferView<[T]>) -> BufferView<'a, Self::Output>;\n\n}\n\n\n\nimpl<T> BufferViewSliceIndex<T> for usize {\n\n type Output = T;\n\n\n\n fn get<'a>(self, view: &'a BufferView<[T]>) -> Option<BufferView<'a, Self::Output>> {\n\n if self < view.len {\n\n Some(BufferView {\n\n buffer: unsafe { mem::transmute(view.buffer) },\n\n offset_in_bytes: view.offset_in_bytes + self * mem::size_of::<T>(),\n\n len: 1,\n", "file_path": "web_glitz/src/buffer.rs", "rank": 93, "score": 67221.59363385644 }, { "content": "/// A helper trait for indexing [LevelLayers].\n\n///\n\n/// See [LevelLayers::get] and [LevelLayers::get_unchecked].\n\npub trait LevelLayersIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, layers: &'a LevelLayers<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, layers: &'a LevelLayers<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelLayersIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelLayer<'a, F>;\n\n\n\n fn get(self, layers: &'a LevelLayers<F>) -> Option<Self::Output> {\n\n if self < layers.len {\n\n Some(LevelLayer {\n", "file_path": "web_glitz/src/image/texture_2d_array.rs", "rank": 94, "score": 67216.15645877487 }, { "content": "/// A helper trait for indexing [LevelSubImageLayers].\n\n///\n\n/// See [LevelSubImageLayers::get] and [LevelSubImageLayers::get_unchecked].\n\npub trait LevelSubImageLayersIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, layers: &'a LevelSubImageLayers<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, layers: &'a LevelSubImageLayers<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelSubImageLayersIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelLayerSubImage<'a, F>;\n\n\n\n fn get(self, layers: &'a LevelSubImageLayers<F>) -> Option<Self::Output> {\n\n if self < layers.len {\n\n Some(LevelLayerSubImage {\n", "file_path": "web_glitz/src/image/texture_3d.rs", "rank": 95, "score": 66341.52631403193 }, { "content": "/// A helper trait for indexing [LevelSubImageLayers].\n\n///\n\n/// See [LevelSubImageLayers::get] and [LevelSubImageLayers::get_unchecked].\n\npub trait LevelSubImageLayersIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, layers: &'a LevelSubImageLayers<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, layers: &'a LevelSubImageLayers<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelSubImageLayersIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelLayerSubImage<'a, F>;\n\n\n\n fn get(self, layers: &'a LevelSubImageLayers<F>) -> Option<Self::Output> {\n\n if self < layers.len {\n\n Some(LevelLayerSubImage {\n", "file_path": "web_glitz/src/image/texture_2d_array.rs", "rank": 96, "score": 65500.555537774235 }, { "content": "/// Helper trait for implementing [Framebuffer::pipeline_task] for both a plain graphics pipeline\n\n/// and a graphics pipeline that will record transform feedback.\n\npub trait GraphicsPipelineState<V, R, Tf> {\n\n /// Creates a new pipeline task.\n\n ///\n\n /// See [Framebuffer::pipeline_task] for details.\n\n fn pipeline_task<F, T>(&self, target: &GraphicsPipelineTarget, f: F) -> PipelineTask<T>\n\n where\n\n F: Fn(ActiveGraphicsPipeline<V, R, Tf>) -> T,\n\n T: GpuTask<PipelineTaskContext>;\n\n}\n\n\n\nimpl<V, R, Tf> GraphicsPipelineState<V, R, Tf> for GraphicsPipeline<V, R, Tf> {\n\n fn pipeline_task<F, T>(&self, target: &GraphicsPipelineTarget, f: F) -> PipelineTask<T>\n\n where\n\n F: Fn(ActiveGraphicsPipeline<V, R, Tf>) -> T,\n\n T: GpuTask<PipelineTaskContext>,\n\n {\n\n PipelineTask::new(target, self, None, f)\n\n }\n\n}\n\n\n", "file_path": "web_glitz/src/rendering/framebuffer.rs", "rank": 97, "score": 64637.42861351196 }, { "content": "/// A helper trait type for indexing operations on a [IndexBuffer].\n\npub trait IndexBufferSliceRange<T>: Sized {\n\n /// Returns a view on the index buffer if in bounds, or `None` otherwise.\n\n fn get(self, index_buffer: &IndexBuffer<T>) -> Option<IndexBufferView<T>>;\n\n\n\n /// Returns a view on the index buffer, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, index_buffer: &IndexBuffer<T>) -> IndexBufferView<T>;\n\n}\n\n\n\nimpl<T> IndexBufferSliceRange<T> for RangeFull {\n\n fn get(self, index_buffer: &IndexBuffer<T>) -> Option<IndexBufferView<T>> {\n\n Some(IndexBufferView {\n\n buffer: index_buffer,\n\n offset_in_bytes: 0,\n\n len: index_buffer.data.len,\n\n })\n\n }\n\n\n\n unsafe fn get_unchecked(self, index_buffer: &IndexBuffer<T>) -> IndexBufferView<T> {\n\n IndexBufferView {\n\n buffer: index_buffer,\n", "file_path": "web_glitz/src/pipeline/graphics/vertex/index_buffer.rs", "rank": 98, "score": 63917.6456404675 }, { "content": "/// A helper trait type for indexing operations on an [IndexBufferView].\n\npub trait IndexBufferViewSliceIndex<T>: Sized {\n\n /// Returns a view on the [IndexBufferView] if in bounds, or `None` otherwise.\n\n fn get<'a>(self, view: &'a IndexBufferView<T>) -> Option<IndexBufferView<'a, T>>;\n\n\n\n /// Returns a view on the [IndexBufferView], without performing any bounds checking.\n\n unsafe fn get_unchecked<'a>(self, view: &'a IndexBufferView<T>) -> IndexBufferView<'a, T>;\n\n}\n\n\n\nimpl<T> IndexBufferViewSliceIndex<T> for RangeFull {\n\n fn get<'a>(self, view: &'a IndexBufferView<T>) -> Option<IndexBufferView<'a, T>> {\n\n Some(IndexBufferView {\n\n buffer: view.buffer,\n\n offset_in_bytes: view.offset_in_bytes,\n\n len: view.len,\n\n })\n\n }\n\n\n\n unsafe fn get_unchecked<'a>(self, view: &'a IndexBufferView<T>) -> IndexBufferView<'a, T> {\n\n IndexBufferView {\n\n buffer: view.buffer,\n", "file_path": "web_glitz/src/pipeline/graphics/vertex/index_buffer.rs", "rank": 99, "score": 63166.71652140647 } ]
Rust
src/components/memory.rs
rust-motd/rust-motd
d9fdf32019993f7abc10bb01c0bdf7ef8224f44e
use serde::Deserialize; use systemstat::{saturating_sub_bytes, Platform, System}; use termion::{color, style}; use thiserror::Error; use crate::constants::{GlobalSettings, INDENT_WIDTH}; #[derive(Error, Debug)] pub enum MemoryError { #[error("Could not find memory quantity {quantity:?}")] MemoryNotFound { quantity: String }, #[error(transparent)] IO(#[from] std::io::Error), } #[derive(Debug, Deserialize)] pub struct MemoryCfg { swap_pos: SwapPosition, } #[derive(Debug, Deserialize, PartialEq)] enum SwapPosition { #[serde(alias = "beside")] Beside, #[serde(alias = "below")] Below, #[serde(alias = "none")] None, } struct MemoryUsage { name: String, used: String, total: String, used_ratio: f64, } impl MemoryUsage { fn get_by_name( name: String, sys: &System, free_name: &str, total_name: &str, ) -> Result<Self, MemoryError> { let memory = sys.memory()?; let total = memory .platform_memory .meminfo .get(total_name) .ok_or(MemoryError::MemoryNotFound { quantity: total_name.to_string(), })?; let free = memory .platform_memory .meminfo .get(free_name) .ok_or(MemoryError::MemoryNotFound { quantity: free_name.to_string(), })?; let used = saturating_sub_bytes(*total, *free); Ok(MemoryUsage { name, used: used.to_string(), total: total.to_string(), used_ratio: used.as_u64() as f64 / total.as_u64() as f64, }) } } fn print_bar( global_settings: &GlobalSettings, full_color: String, bar_full: usize, bar_empty: usize, ) { print!( "{}", [ " ".repeat(INDENT_WIDTH), global_settings.progress_prefix.to_string(), full_color, global_settings .progress_full_character .to_string() .repeat(bar_full), color::Fg(color::LightBlack).to_string(), global_settings .progress_empty_character .to_string() .repeat(bar_empty), style::Reset.to_string(), global_settings.progress_suffix.to_string(), ] .join("") ); } fn full_color(ratio: f64) -> String { match (ratio * 100.) as usize { 0..=75 => color::Fg(color::Green).to_string(), 76..=95 => color::Fg(color::Yellow).to_string(), _ => color::Fg(color::Red).to_string(), } } pub fn disp_memory( config: MemoryCfg, global_settings: &GlobalSettings, sys: &System, size_hint: Option<usize>, ) -> Result<(), MemoryError> { let size_hint = size_hint.unwrap_or(global_settings.progress_width - INDENT_WIDTH); let ram_usage = MemoryUsage::get_by_name("RAM".to_string(), sys, "MemAvailable", "MemTotal")?; println!("Memory"); match config.swap_pos { SwapPosition::Below => { let swap_usage = MemoryUsage::get_by_name("Swap".to_string(), sys, "SwapFree", "SwapTotal")?; let entries = vec![ram_usage, swap_usage]; let bar_width = size_hint - global_settings.progress_prefix.len() - global_settings.progress_suffix.len(); for entry in entries { let full_color = full_color(entry.used_ratio); let bar_full = ((bar_width as f64) * entry.used_ratio) as usize; let bar_empty = bar_width - bar_full; println!( "{}{}: {} / {}", " ".repeat(INDENT_WIDTH), entry.name, entry.used, entry.total ); print_bar(global_settings, full_color, bar_full, bar_empty); println!(); } } SwapPosition::Beside => { let swap_usage = MemoryUsage::get_by_name("Swap".to_string(), sys, "SwapFree", "SwapTotal")?; let bar_width = ((size_hint - global_settings.progress_prefix.len() - global_settings.progress_suffix.len()) / 2) - INDENT_WIDTH; let ram_label = format!( "{}: {} / {}", ram_usage.name, ram_usage.used, ram_usage.total ); let swap_label = format!( "{}: {} / {}", swap_usage.name, swap_usage.used, swap_usage.total ); println!( "{}{}{}{}", " ".repeat(INDENT_WIDTH), ram_label, " ".repeat(bar_width - ram_label.len() + 2 * INDENT_WIDTH), swap_label ); let bar_color = full_color(ram_usage.used_ratio); let bar_full = ((bar_width as f64) * ram_usage.used_ratio) as usize; let bar_empty = bar_width - bar_full; print_bar(global_settings, bar_color, bar_full, bar_empty); let bar_color = full_color(swap_usage.used_ratio); let bar_full = ((bar_width as f64) * swap_usage.used_ratio) as usize; let bar_empty = bar_width - bar_full; print_bar(global_settings, bar_color, bar_full, bar_empty); println!(); } SwapPosition::None => { let bar_width = size_hint - global_settings.progress_prefix.len() - global_settings.progress_suffix.len(); let full_color = full_color(ram_usage.used_ratio); let bar_full = ((bar_width as f64) * ram_usage.used_ratio) as usize; let bar_empty = bar_width - bar_full; println!( "{}{}: {} / {}", " ".repeat(INDENT_WIDTH), ram_usage.name, ram_usage.used, ram_usage.total ); print_bar(global_settings, full_color, bar_full, bar_empty); println!(); } } Ok(()) }
use serde::Deserialize; use systemstat::{saturating_sub_bytes, Platform, System}; use termion::{color, style}; use thiserror::Error; use crate::constants::{GlobalSettings, INDENT_WIDTH}; #[derive(Error, Debug)] pub enum MemoryError { #[error("Could not find memory quantity {quantity:?}")] MemoryNotFound { quantity: String }, #[error(transparent)] IO(#[from] std::io::Error), } #[derive(Debug, Deserialize)] pub struct MemoryCfg { swap_pos: SwapPosition, } #[derive(Debug, Deserialize, PartialEq)] enum SwapPosition { #[serde(alias = "beside")] Beside, #[serde(alias = "below")] Below, #[serde(alias = "none")] None, } struct MemoryUsage { name: String, used: String, total: String, used_ratio: f64, } impl MemoryUsage { fn get_by_name( name: String, sys: &System, free_name: &str, total_name: &str, ) -> Result<Self, MemoryError> { let memory = sys.memory()?; let total = memory .platform_memory .meminfo .get(total_name) .ok_or(MemoryError::MemoryNotFound { quantity: total_name.to_string(), })?; let free = memory .platform_memory .meminfo .get(free_name) .ok_or(MemoryError::MemoryNotFound { quantity: free_name.to_string(), })?; let used = saturating_sub_bytes(*total, *free); Ok(MemoryUsage { name, used: used.to_string(), total: total.to_string(), used_ratio: used.as_u64() as f64 / total.as_u64() as f64, }) } }
fn full_color(ratio: f64) -> String { match (ratio * 100.) as usize { 0..=75 => color::Fg(color::Green).to_string(), 76..=95 => color::Fg(color::Yellow).to_string(), _ => color::Fg(color::Red).to_string(), } } pub fn disp_memory( config: MemoryCfg, global_settings: &GlobalSettings, sys: &System, size_hint: Option<usize>, ) -> Result<(), MemoryError> { let size_hint = size_hint.unwrap_or(global_settings.progress_width - INDENT_WIDTH); let ram_usage = MemoryUsage::get_by_name("RAM".to_string(), sys, "MemAvailable", "MemTotal")?; println!("Memory"); match config.swap_pos { SwapPosition::Below => { let swap_usage = MemoryUsage::get_by_name("Swap".to_string(), sys, "SwapFree", "SwapTotal")?; let entries = vec![ram_usage, swap_usage]; let bar_width = size_hint - global_settings.progress_prefix.len() - global_settings.progress_suffix.len(); for entry in entries { let full_color = full_color(entry.used_ratio); let bar_full = ((bar_width as f64) * entry.used_ratio) as usize; let bar_empty = bar_width - bar_full; println!( "{}{}: {} / {}", " ".repeat(INDENT_WIDTH), entry.name, entry.used, entry.total ); print_bar(global_settings, full_color, bar_full, bar_empty); println!(); } } SwapPosition::Beside => { let swap_usage = MemoryUsage::get_by_name("Swap".to_string(), sys, "SwapFree", "SwapTotal")?; let bar_width = ((size_hint - global_settings.progress_prefix.len() - global_settings.progress_suffix.len()) / 2) - INDENT_WIDTH; let ram_label = format!( "{}: {} / {}", ram_usage.name, ram_usage.used, ram_usage.total ); let swap_label = format!( "{}: {} / {}", swap_usage.name, swap_usage.used, swap_usage.total ); println!( "{}{}{}{}", " ".repeat(INDENT_WIDTH), ram_label, " ".repeat(bar_width - ram_label.len() + 2 * INDENT_WIDTH), swap_label ); let bar_color = full_color(ram_usage.used_ratio); let bar_full = ((bar_width as f64) * ram_usage.used_ratio) as usize; let bar_empty = bar_width - bar_full; print_bar(global_settings, bar_color, bar_full, bar_empty); let bar_color = full_color(swap_usage.used_ratio); let bar_full = ((bar_width as f64) * swap_usage.used_ratio) as usize; let bar_empty = bar_width - bar_full; print_bar(global_settings, bar_color, bar_full, bar_empty); println!(); } SwapPosition::None => { let bar_width = size_hint - global_settings.progress_prefix.len() - global_settings.progress_suffix.len(); let full_color = full_color(ram_usage.used_ratio); let bar_full = ((bar_width as f64) * ram_usage.used_ratio) as usize; let bar_empty = bar_width - bar_full; println!( "{}{}: {} / {}", " ".repeat(INDENT_WIDTH), ram_usage.name, ram_usage.used, ram_usage.total ); print_bar(global_settings, full_color, bar_full, bar_empty); println!(); } } Ok(()) }
fn print_bar( global_settings: &GlobalSettings, full_color: String, bar_full: usize, bar_empty: usize, ) { print!( "{}", [ " ".repeat(INDENT_WIDTH), global_settings.progress_prefix.to_string(), full_color, global_settings .progress_full_character .to_string() .repeat(bar_full), color::Fg(color::LightBlack).to_string(), global_settings .progress_empty_character .to_string() .repeat(bar_empty), style::Reset.to_string(), global_settings.progress_suffix.to_string(), ] .join("") ); }
function_block-full_function
[ { "content": "fn print_row<'a>(items: [&str; 6], column_sizes: impl IntoIterator<Item = &'a usize>) {\n\n println!(\n\n \"{}\",\n\n Itertools::intersperse(\n\n items\n\n .iter()\n\n .zip(column_sizes.into_iter())\n\n .map(|(name, size)| format!(\"{: <size$}\", name, size = size)),\n\n \" \".repeat(INDENT_WIDTH)\n\n )\n\n .collect::<String>()\n\n );\n\n}\n\n\n", "file_path": "src/components/filesystem.rs", "rank": 2, "score": 85860.74449936723 }, { "content": "fn get_service_status(service: &str, user: bool) -> Result<String, ServiceStatusError> {\n\n let executable = \"systemctl\";\n\n let mut args = vec![\"is-active\", service];\n\n\n\n if user {\n\n args.insert(0, \"--user\");\n\n }\n\n\n\n let output = BetterCommand::new(executable)\n\n .args(args)\n\n .get_output_string()?;\n\n\n\n Ok(output.split_whitespace().collect())\n\n}\n\n\n", "file_path": "src/components/service_status.rs", "rank": 3, "score": 85537.61852984375 }, { "content": "pub fn disp_uptime(config: UptimeCfg, sys: &System) -> Result<(), std::io::Error> {\n\n let uptime = sys.uptime()?;\n\n println!(\"{} {}\", config.prefix, format_duration(uptime).to_string());\n\n\n\n Ok(())\n\n}\n", "file_path": "src/components/uptime.rs", "rank": 4, "score": 82777.85674874198 }, { "content": "fn parse_into_entry(filesystem_name: String, mount: &Filesystem) -> Entry {\n\n let total = mount.total.as_u64();\n\n let avail = mount.avail.as_u64();\n\n let used = total - avail;\n\n\n\n Entry {\n\n filesystem_name,\n\n mount_point: &mount.fs_mounted_on,\n\n dev: &mount.fs_mounted_from,\n\n fs_type: &mount.fs_type,\n\n used: ByteSize::b(used).to_string(),\n\n total: ByteSize::b(total).to_string(),\n\n used_ratio: (used as f64) / (total as f64),\n\n }\n\n}\n\n\n", "file_path": "src/components/filesystem.rs", "rank": 5, "score": 82634.31835912884 }, { "content": "fn default_progress_suffix() -> String {\n\n \"]\".to_string()\n\n}\n\n\n", "file_path": "src/constants.rs", "rank": 6, "score": 78543.04113143394 }, { "content": "fn default_progress_prefix() -> String {\n\n \"[\".to_string()\n\n}\n\n\n", "file_path": "src/constants.rs", "rank": 7, "score": 78543.04113143394 }, { "content": "fn default_time_format() -> String {\n\n \"%Y-%m-%d %H:%M:%S\".to_string()\n\n}\n\n\n\n// TODO: See if we can use this: https://github.com/serde-rs/serde/issues/1416\n\nimpl Default for GlobalSettings {\n\n fn default() -> Self {\n\n GlobalSettings {\n\n progress_full_character: default_progress_character(),\n\n progress_empty_character: default_progress_character(),\n\n progress_prefix: default_progress_prefix(),\n\n progress_suffix: default_progress_suffix(),\n\n progress_width: default_progress_width(),\n\n time_format: default_time_format(),\n\n }\n\n }\n\n}\n", "file_path": "src/constants.rs", "rank": 8, "score": 78543.04113143394 }, { "content": "fn u8vec_to_string(s: Vec<u8>) -> String {\n\n String::from_utf8_lossy(&s).to_string()\n\n}\n\n\n\nimpl BetterCommand {\n\n pub fn new(executable: &str) -> BetterCommand {\n\n BetterCommand {\n\n executable: executable.to_string(),\n\n command: Command::new(executable),\n\n }\n\n }\n\n\n\n pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut BetterCommand {\n\n self.command.arg(arg.as_ref());\n\n self\n\n }\n\n\n\n pub fn args<I, S>(&mut self, args: I) -> &mut BetterCommand\n\n where\n\n I: IntoIterator<Item = S>,\n", "file_path": "src/command.rs", "rank": 9, "score": 77482.25036667625 }, { "content": "pub fn disp_filesystem(\n\n config: FilesystemsCfg,\n\n global_settings: &GlobalSettings,\n\n sys: &System,\n\n) -> Result<Option<usize>, FilesystemsError> {\n\n if config.is_empty() {\n\n return Err(FilesystemsError::ConfigEmtpy);\n\n }\n\n\n\n let mounts = sys.mounts()?;\n\n let mounts: HashMap<String, &Filesystem> = mounts\n\n .iter()\n\n .map(|fs| (fs.fs_mounted_on.clone(), fs))\n\n .collect();\n\n\n\n let entries = config\n\n .into_iter()\n\n .map(\n\n |(filesystem_name, mount_point)| match mounts.get(&mount_point) {\n\n Some(mount) => Ok(parse_into_entry(filesystem_name, mount)),\n", "file_path": "src/components/filesystem.rs", "rank": 10, "score": 77131.26706452956 }, { "content": "pub fn disp_ssl(\n\n config: SSLCertsCfg,\n\n global_settings: &GlobalSettings,\n\n) -> Result<(), SSLCertsError> {\n\n let mut cert_infos: Vec<CertInfo> = Vec::new();\n\n\n\n println!(\"SSL Certificates:\");\n\n for (name, path) in config.certs {\n\n let cert = File::open(&path)?;\n\n let cert = BufReader::new(cert);\n\n let cert: Vec<u8> = cert.bytes().collect::<Result<_, _>>()?;\n\n let cert = X509::from_pem(&cert)?;\n\n\n\n let expiration =\n\n Utc.datetime_from_str(&format!(\"{}\", cert.not_after()), \"%B %_d %T %Y %Z\")?;\n\n\n\n let now = Utc::now();\n\n let status = if expiration < now {\n\n format!(\"{}expired on{}\", color::Fg(color::Red), style::Reset)\n\n } else if expiration < now + Duration::days(30) {\n", "file_path": "src/components/ssl_certs.rs", "rank": 12, "score": 75462.10894475911 }, { "content": "pub fn disp_last_run(\n\n _last_run_config: LastRunConfig,\n\n global_settings: &GlobalSettings,\n\n) -> Result<(), LastRunError> {\n\n println!(\n\n \"Last updated: {}\",\n\n Local::now().format(&global_settings.time_format)\n\n );\n\n Ok(())\n\n}\n", "file_path": "src/components/last_run.rs", "rank": 13, "score": 73913.80700421582 }, { "content": "pub fn disp_last_login(\n\n config: LastLoginCfg,\n\n global_settings: &GlobalSettings,\n\n) -> Result<(), LastLoginError> {\n\n println!(\"Last Login:\");\n\n\n\n for (username, num_logins) in config {\n\n println!(\"{}{}:\", \" \".repeat(INDENT_WIDTH as usize), username);\n\n let entries = get_logins(\"/var/log/wtmp\")?\n\n .into_iter()\n\n .filter(|entry| entry.user == username)\n\n .take(num_logins)\n\n .collect::<Vec<Enter>>();\n\n\n\n let longest_location = entries.iter().map(|entry| entry.host.len()).max();\n\n match longest_location {\n\n Some(longest_location) => {\n\n let formatted_entries = entries.iter().map(|entry| {\n\n format_entry(entry, longest_location, &global_settings.time_format)\n\n });\n", "file_path": "src/components/last_login.rs", "rank": 14, "score": 73913.80700421582 }, { "content": "#[derive(Debug, Deserialize)]\n\nenum WeatherStyle {\n\n #[serde(alias = \"oneline\")]\n\n Oneline,\n\n #[serde(alias = \"day\")]\n\n Day,\n\n #[serde(alias = \"full\")]\n\n Full,\n\n}\n\n\n\n#[derive(Error, Debug)]\n\npub enum WeatherError {\n\n #[error(\"Empty response body from weather service\")]\n\n ReplyEmpty,\n\n\n\n #[error(transparent)]\n\n Ureq(#[from] ureq::Error),\n\n\n\n #[error(transparent)]\n\n IO(#[from] std::io::Error),\n\n}\n\n\n", "file_path": "src/components/weather.rs", "rank": 15, "score": 70914.65039295307 }, { "content": "#[cfg(not(unix))]\n\npub fn new_docker() -> DockerResult<Docker> {\n\n Docker::new(\"tcp://127.0.0.1:8080\")\n\n}\n\n\n\npub async fn disp_docker(config: DockerConfig) -> Result<(), Box<dyn std::error::Error>> {\n\n let docker = new_docker()?;\n\n\n\n // Get all containers from library and then filter them\n\n // Not perfect, but I got strange issues when trying to use `.get(id)`\n\n let containers = docker.containers().list(&Default::default()).await?;\n\n let containers = config.iter().filter_map(|(docker_name, display_name)| {\n\n match containers.iter().find(|container| container.names.contains(docker_name)) {\n\n Some(container) => Some((display_name, container)),\n\n None => {\n\n println!(\"{indent}{color}Could not find container with name `{name}'{reset}\",\n\n indent = \" \".repeat(INDENT_WIDTH as usize),\n\n color = color::Fg(color::Yellow),\n\n name = docker_name,\n\n reset = style::Reset);\n\n None\n", "file_path": "src/components/docker.rs", "rank": 17, "score": 67903.78866498065 }, { "content": "pub fn disp_weather(config: WeatherCfg) -> Result<(), WeatherError> {\n\n let url = match config.url {\n\n Some(url) => url,\n\n None => {\n\n let mut base = String::from(\"https://wttr.in/\");\n\n let loc = config.loc.replace(\", \", \",\").replace(\" \", \"+\");\n\n base.push_str(&loc);\n\n match config.style.unwrap_or(WeatherStyle::Day) {\n\n WeatherStyle::Oneline => base.push_str(\"?format=4\"),\n\n WeatherStyle::Day => base.push_str(\"?0\"),\n\n WeatherStyle::Full => (),\n\n }\n\n base\n\n }\n\n };\n\n\n\n let agent = match config.proxy {\n\n Some(proxy) => {\n\n let proxy = ureq::Proxy::new(proxy)?;\n\n ureq::AgentBuilder::new().proxy(proxy).build()\n", "file_path": "src/components/weather.rs", "rank": 19, "score": 60680.89300994914 }, { "content": "pub fn disp_banner(config: BannerCfg) -> Result<(), BannerError> {\n\n // We probably don't have to handle command not found for sh\n\n let output = BetterCommand::new(\"sh\")\n\n .arg(\"-c\")\n\n .arg(config.command)\n\n .check_status_and_get_output_string()?;\n\n\n\n let banner_color = match config.color {\n\n BannerColor::Black => color::Black.fg_str(),\n\n BannerColor::Red => color::Red.fg_str(),\n\n BannerColor::Yellow => color::Yellow.fg_str(),\n\n BannerColor::Green => color::Green.fg_str(),\n\n BannerColor::Blue => color::Blue.fg_str(),\n\n BannerColor::Magenta => color::Magenta.fg_str(),\n\n BannerColor::Cyan => color::Cyan.fg_str(),\n\n BannerColor::White => color::White.fg_str(),\n\n BannerColor::LightBlack => color::LightBlack.fg_str(),\n\n BannerColor::LightRed => color::LightRed.fg_str(),\n\n BannerColor::LightYellow => color::LightYellow.fg_str(),\n\n BannerColor::LightGreen => color::LightGreen.fg_str(),\n", "file_path": "src/components/banner.rs", "rank": 20, "score": 60680.89300994914 }, { "content": "fn get_jail_status(jail: &str) -> Result<Entry, Fail2BanError> {\n\n lazy_static! {\n\n static ref TOTAL_REGEX: Regex = Regex::new(r\"Total banned:\\s+([0-9]+)\").unwrap();\n\n static ref CURRENT_REGEX: Regex = Regex::new(r\"Currently banned:\\s+([0-9]+)\").unwrap();\n\n }\n\n\n\n let executable = \"fail2ban-client\";\n\n let output = BetterCommand::new(executable)\n\n .arg(\"status\")\n\n .arg(jail)\n\n .check_status_and_get_output_string()?;\n\n\n\n let total = TOTAL_REGEX.captures_iter(&output).next().unwrap()[1].parse::<u32>()?;\n\n let current = CURRENT_REGEX.captures_iter(&output).next().unwrap()[1].parse::<u32>()?;\n\n\n\n Ok(Entry { total, current })\n\n}\n\n\n", "file_path": "src/components/fail_2_ban.rs", "rank": 21, "score": 60368.072322534405 }, { "content": "pub fn disp_fail_2_ban(config: Fail2BanCfg) -> Result<(), Fail2BanError> {\n\n println!(\"Fail2Ban:\");\n\n\n\n for jail in config.jails {\n\n let entry = get_jail_status(&jail)?;\n\n println!(\n\n concat!(\n\n \"{indent}{jail}:\\n\",\n\n \"{indent}{indent}Total bans: {total}\\n\",\n\n \"{indent}{indent}Current bans: {current}\",\n\n ),\n\n jail = jail,\n\n total = entry.total,\n\n current = entry.current,\n\n indent = \" \".repeat(INDENT_WIDTH as usize),\n\n );\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "src/components/fail_2_ban.rs", "rank": 22, "score": 56637.87967560426 }, { "content": "pub fn disp_service_status(config: ServiceStatusCfg, user: bool) -> Result<(), ServiceStatusError> {\n\n if config.is_empty() {\n\n return Err(ServiceStatusError::ConfigEmpty);\n\n }\n\n\n\n let padding = config.keys().map(|x| x.len()).max().unwrap();\n\n\n\n for key in config.keys().sorted() {\n\n let status = get_service_status(config.get(key).unwrap(), user)?;\n\n\n\n let status_color = match status.as_ref() {\n\n \"active\" => color::Fg(color::Green).to_string(),\n\n \"inactive\" => color::Fg(color::Yellow).to_string(),\n\n \"failed\" => color::Fg(color::Red).to_string(),\n\n _ => style::Reset.to_string(),\n\n };\n\n\n\n println!(\n\n \"{}{}: {}{}{}{}\",\n\n \" \".repeat(INDENT_WIDTH as usize),\n", "file_path": "src/components/service_status.rs", "rank": 23, "score": 52243.2479269928 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct Config {\n\n banner: Option<BannerCfg>,\n\n service_status: Option<ServiceStatusCfg>,\n\n user_service_status: Option<ServiceStatusCfg>,\n\n docker_status: Option<DockerConfig>,\n\n uptime: Option<UptimeCfg>,\n\n ssl_certificates: Option<SSLCertsCfg>,\n\n filesystems: Option<FilesystemsCfg>,\n\n memory: Option<MemoryCfg>,\n\n fail_2_ban: Option<Fail2BanCfg>,\n\n last_login: Option<LastLoginCfg>,\n\n weather: Option<WeatherCfg>,\n\n last_run: Option<LastRunConfig>,\n\n #[serde(default)]\n\n global: GlobalSettings,\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n let args = env::args();\n", "file_path": "src/main.rs", "rank": 24, "score": 48306.90846520344 }, { "content": "#[derive(Debug, Deserialize)]\n\nenum BannerColor {\n\n #[serde(alias = \"black\")]\n\n Black,\n\n #[serde(alias = \"red\")]\n\n Red,\n\n #[serde(alias = \"green\")]\n\n Green,\n\n #[serde(alias = \"yellow\")]\n\n Yellow,\n\n #[serde(alias = \"blue\")]\n\n Blue,\n\n #[serde(alias = \"magenta\")]\n\n Magenta,\n\n #[serde(alias = \"cyan\")]\n\n Cyan,\n\n #[serde(alias = \"white\")]\n\n White,\n\n #[serde(alias = \"light_black\")]\n\n LightBlack,\n\n #[serde(alias = \"light_red\")]\n", "file_path": "src/components/banner.rs", "rank": 25, "score": 46434.463163305176 }, { "content": "struct Entry {\n\n total: u32,\n\n current: u32,\n\n}\n\n\n\n#[derive(Error, Debug)]\n\npub enum Fail2BanError {\n\n #[error(transparent)]\n\n BetterCommand(#[from] BetterCommandError),\n\n\n\n #[error(\"Failed to parse int in output\")]\n\n ParseInt(#[from] std::num::ParseIntError),\n\n\n\n #[error(transparent)]\n\n IO(#[from] std::io::Error),\n\n}\n\n\n", "file_path": "src/components/fail_2_ban.rs", "rank": 26, "score": 46162.021223259755 }, { "content": "#[derive(Debug, Deserialize)]\n\nenum SortMethod {\n\n #[serde(alias = \"alphabetical\")] // Alias used to match lowercase spelling as well\n\n Alphabetical,\n\n #[serde(alias = \"expiration\")] // Alias used to match lowercase spelling as well\n\n Expiration,\n\n #[serde(alias = \"manual\")] // Alias used to match lowercase spelling as well\n\n Manual,\n\n}\n\n\n\nimpl Default for SortMethod {\n\n fn default() -> Self {\n\n SortMethod::Manual\n\n }\n\n}\n\n\n\n#[derive(Error, Debug)]\n\npub enum SSLCertsError {\n\n #[error(\"Failed to parse timestamp\")]\n\n ChronoParse(#[from] chrono::ParseError),\n\n\n\n #[error(transparent)]\n\n IO(#[from] std::io::Error),\n\n\n\n #[error(transparent)]\n\n ErrorStack(#[from] openssl::error::ErrorStack),\n\n}\n\n\n", "file_path": "src/components/ssl_certs.rs", "rank": 27, "score": 45487.30590221146 }, { "content": "#[derive(Debug)]\n\nstruct Entry<'a> {\n\n filesystem_name: String,\n\n dev: &'a str,\n\n mount_point: &'a str,\n\n fs_type: &'a str,\n\n used: String,\n\n total: String,\n\n used_ratio: f64,\n\n}\n\n\n\npub type FilesystemsCfg = HashMap<String, String>;\n\n\n", "file_path": "src/components/filesystem.rs", "rank": 28, "score": 45404.8407221119 }, { "content": "struct CertInfo {\n\n name: String,\n\n status: String,\n\n expiration: systemstat::DateTime<systemstat::Utc>,\n\n}\n\n\n", "file_path": "src/components/ssl_certs.rs", "rank": 29, "score": 45217.5503553856 }, { "content": "fn format_entry(\n\n entry: &Enter,\n\n longest_location: usize,\n\n time_format: &str,\n\n) -> Result<String, LastLoginError> {\n\n let location = format!(\"{:>width$}\", entry.host, width = longest_location);\n\n let login_time = entry.login_time;\n\n\n\n let exit = match entry.exit {\n\n Exit::Logout(time) => {\n\n let delta_time = (time - login_time).to_std()?;\n\n let delta_time = Duration::new((delta_time.as_secs() / 60) * 60, 0);\n\n format_duration(delta_time).to_string()\n\n }\n\n _ => {\n\n let (colour, message) = match entry.exit {\n\n Exit::StillLoggedIn => (color::Fg(color::Green).to_string(), \"still logged in\"),\n\n Exit::Crash(_) => (color::Fg(color::Yellow).to_string(), \"crash\"),\n\n Exit::Reboot(_) => (color::Fg(color::Yellow).to_string(), \"down\"),\n\n Exit::Logout(_) => unreachable!(),\n", "file_path": "src/components/last_login.rs", "rank": 30, "score": 36857.014543843005 }, { "content": "fn default_progress_width() -> usize {\n\n 80\n\n}\n\n\n", "file_path": "src/constants.rs", "rank": 31, "score": 35622.594755278726 }, { "content": "fn default_progress_character() -> char {\n\n '='\n\n}\n\n\n", "file_path": "src/constants.rs", "rank": 32, "score": 35622.594755278726 }, { "content": "fn get_config(mut args: env::Args) -> Result<Config, ConfigError> {\n\n let config_path = match args.nth(1) {\n\n Some(file_path) => Some(PathBuf::from(file_path)),\n\n None => {\n\n let config_base = env::var(\"XDG_CONFIG_HOME\").unwrap_or(env::var(\"HOME\")? + \"/.config\");\n\n let config_base = Path::new(&config_base).join(Path::new(\"rust-motd/config.toml\"));\n\n if config_base.exists() {\n\n Some(config_base)\n\n } else {\n\n None\n\n }\n\n }\n\n };\n\n match config_path {\n\n Some(path) => Ok(toml::from_str(&fs::read_to_string(path)?)?),\n\n None => Err(ConfigError::ConfigNotFound),\n\n }\n\n}\n", "file_path": "src/main.rs", "rank": 33, "score": 26937.499203589206 }, { "content": "use humantime::format_duration;\n\nuse serde::Deserialize;\n\nuse systemstat::{Platform, System};\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct UptimeCfg {\n\n prefix: String,\n\n}\n\n\n", "file_path": "src/components/uptime.rs", "rank": 40, "score": 16.537630573741186 }, { "content": "use serde::Deserialize;\n\nuse std::io::Write;\n\nuse thiserror::Error;\n\nuse ureq;\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct WeatherCfg {\n\n url: Option<String>,\n\n\n\n proxy: Option<String>,\n\n\n\n #[serde(default = \"String::new\")]\n\n loc: String,\n\n\n\n style: Option<WeatherStyle>,\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n", "file_path": "src/components/weather.rs", "rank": 41, "score": 14.751370634436254 }, { "content": "use serde::Deserialize;\n\nuse termion::{color, style};\n\nuse thiserror::Error;\n\n\n\nuse crate::command::{BetterCommand, BetterCommandError};\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct BannerCfg {\n\n color: BannerColor,\n\n command: String,\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n", "file_path": "src/components/banner.rs", "rank": 42, "score": 13.510468335430012 }, { "content": "use chrono::{Duration, TimeZone, Utc};\n\nuse openssl::x509::X509;\n\nuse serde::Deserialize;\n\nuse std::collections::HashMap;\n\nuse std::fs::File;\n\nuse std::io::{BufReader, Read};\n\nuse termion::{color, style};\n\nuse thiserror::Error;\n\n\n\nuse crate::constants::{GlobalSettings, INDENT_WIDTH};\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct SSLCertsCfg {\n\n #[serde(default)]\n\n sort_method: SortMethod,\n\n certs: HashMap<String, String>,\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n", "file_path": "src/components/ssl_certs.rs", "rank": 43, "score": 11.996777744085293 }, { "content": "use bytesize::ByteSize;\n\nuse itertools::Itertools;\n\nuse std::cmp;\n\nuse std::collections::HashMap;\n\nuse std::iter;\n\nuse systemstat::{Filesystem, Platform, System};\n\nuse termion::{color, style};\n\nuse thiserror::Error;\n\n\n\nuse crate::constants::{GlobalSettings, INDENT_WIDTH};\n\n\n\n#[derive(Error, Debug)]\n\npub enum FilesystemsError {\n\n #[error(\"Empty configuration for filesystems. Please remove the entire block to disable this component.\")]\n\n ConfigEmtpy,\n\n\n\n #[error(\"Could not find mount {mount_point:?}\")]\n\n MountNotFound { mount_point: String },\n\n\n\n #[error(transparent)]\n\n IO(#[from] std::io::Error),\n\n}\n\n\n\n#[derive(Debug)]\n", "file_path": "src/components/filesystem.rs", "rank": 44, "score": 11.178957258299159 }, { "content": "use crate::constants::INDENT_WIDTH;\n\nuse lazy_static::lazy_static;\n\nuse regex::Regex;\n\nuse serde::Deserialize;\n\nuse thiserror::Error;\n\n\n\nuse crate::command::{BetterCommand, BetterCommandError};\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct Fail2BanCfg {\n\n jails: Vec<String>,\n\n}\n\n\n", "file_path": "src/components/fail_2_ban.rs", "rank": 45, "score": 10.502297359812005 }, { "content": "use itertools::Itertools;\n\nuse std::collections::HashMap;\n\nuse termion::{color, style};\n\nuse thiserror::Error;\n\n\n\nuse crate::command::{BetterCommand, BetterCommandError};\n\nuse crate::constants::INDENT_WIDTH;\n\n\n\npub type ServiceStatusCfg = HashMap<String, String>;\n\n\n\n#[derive(Error, Debug)]\n\npub enum ServiceStatusError {\n\n #[error(\"Empty configuration for system services. Please remove the entire block to disable this component.\")]\n\n ConfigEmpty,\n\n\n\n #[error(transparent)]\n\n BetterCommand(#[from] BetterCommandError),\n\n\n\n #[error(transparent)]\n\n IO(#[from] std::io::Error),\n\n}\n\n\n", "file_path": "src/components/service_status.rs", "rank": 46, "score": 10.446266436235907 }, { "content": "\n\n print_row(\n\n [\n\n &[\" \".repeat(INDENT_WIDTH), entry.filesystem_name].concat(),\n\n entry.dev,\n\n entry.mount_point,\n\n entry.fs_type,\n\n entry.used.as_str(),\n\n entry.total.as_str(),\n\n ],\n\n &column_sizes,\n\n );\n\n\n\n let full_color = match (entry.used_ratio * 100.0) as usize {\n\n 0..=75 => color::Fg(color::Green).to_string(),\n\n 76..=95 => color::Fg(color::Yellow).to_string(),\n\n _ => color::Fg(color::Red).to_string(),\n\n };\n\n\n\n println!(\n", "file_path": "src/components/filesystem.rs", "rank": 47, "score": 10.20866245834993 }, { "content": "use serde::Deserialize;\n\n\n\npub const INDENT_WIDTH: usize = 2;\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct GlobalSettings {\n\n #[serde(default = \"default_progress_character\")]\n\n pub progress_full_character: char,\n\n #[serde(default = \"default_progress_character\")]\n\n pub progress_empty_character: char,\n\n #[serde(default = \"default_progress_prefix\")]\n\n pub progress_prefix: String,\n\n #[serde(default = \"default_progress_suffix\")]\n\n pub progress_suffix: String,\n\n #[serde(default = \"default_progress_width\")]\n\n pub progress_width: usize,\n\n #[serde(default = \"default_time_format\")]\n\n pub time_format: String,\n\n}\n\n\n", "file_path": "src/constants.rs", "rank": 48, "score": 9.75722974644128 }, { "content": "use std::ffi::OsStr;\n\nuse std::io::ErrorKind;\n\nuse std::process::{Command, Output};\n\nuse thiserror::Error;\n\n\n\n#[derive(Error, Debug)]\n\npub enum BetterCommandError {\n\n #[error(\"Command not found: {executable:?}\")]\n\n NotFound { executable: String },\n\n\n\n #[error(\"{executable:?} failed with exit code {exit_code:?}:\\n{error:?}\")]\n\n ExitStatusError {\n\n executable: String,\n\n exit_code: i32,\n\n error: String,\n\n },\n\n\n\n #[error(transparent)]\n\n IOError { source: std::io::Error },\n\n}\n\n\n\npub struct BetterCommand {\n\n executable: String,\n\n command: Command,\n\n}\n\n\n", "file_path": "src/command.rs", "rank": 49, "score": 9.680777844391233 }, { "content": "use chrono::Local;\n\nuse serde::Deserialize;\n\nuse thiserror::Error;\n\n\n\nuse crate::constants::GlobalSettings;\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct LastRunConfig {}\n\n\n\n#[derive(Error, Debug)]\n\npub enum LastRunError {\n\n #[error(transparent)]\n\n ChronoParse(#[from] chrono::ParseError),\n\n\n\n #[error(transparent)]\n\n IO(#[from] std::io::Error),\n\n}\n\n\n", "file_path": "src/components/last_run.rs", "rank": 50, "score": 9.595891393628524 }, { "content": "use serde::Deserialize;\n\nuse std::env;\n\nuse std::fs;\n\nuse std::path::{Path, PathBuf};\n\nuse systemstat::{Platform, System};\n\nuse thiserror::Error;\n\n\n\nmod components;\n\nuse components::banner::{disp_banner, BannerCfg};\n\nuse components::docker::{disp_docker, DockerConfig};\n\nuse components::fail_2_ban::{disp_fail_2_ban, Fail2BanCfg};\n\nuse components::filesystem::{disp_filesystem, FilesystemsCfg};\n\nuse components::last_login::{disp_last_login, LastLoginCfg};\n\nuse components::last_run::{disp_last_run, LastRunConfig};\n\nuse components::memory::{disp_memory, MemoryCfg};\n\nuse components::service_status::{disp_service_status, ServiceStatusCfg};\n\nuse components::ssl_certs::{disp_ssl, SSLCertsCfg};\n\nuse components::uptime::{disp_uptime, UptimeCfg};\n\nuse components::weather::{disp_weather, WeatherCfg};\n\nmod command;\n\nmod constants;\n\nuse constants::GlobalSettings;\n\n\n\n#[derive(Debug, Deserialize)]\n", "file_path": "src/main.rs", "rank": 51, "score": 9.157210185633152 }, { "content": "use crate::constants::INDENT_WIDTH;\n\nuse std::collections::HashMap;\n\nuse docker_api::{Docker, Result as DockerResult};\n\nuse docker_api::api::container::ContainerStatus;\n\nuse termion::{color, style};\n\n\n\npub type DockerConfig = HashMap<String, String>;\n\n\n\n#[cfg(unix)]\n", "file_path": "src/components/docker.rs", "rank": 52, "score": 8.635453594535079 }, { "content": "use humantime::format_duration;\n\nuse last_rs::{get_logins, Enter, Exit, LastError};\n\nuse std::collections::HashMap;\n\nuse std::time::Duration;\n\nuse termion::{color, style};\n\nuse thiserror::Error;\n\nuse time;\n\n\n\nuse crate::command::BetterCommandError;\n\nuse crate::constants::{GlobalSettings, INDENT_WIDTH};\n\n\n\npub type LastLoginCfg = HashMap<String, usize>;\n\n\n\n#[derive(Error, Debug)]\n\npub enum LastLoginError {\n\n #[error(transparent)]\n\n BetterCommand(#[from] BetterCommandError),\n\n\n\n #[error(transparent)]\n\n ChronoParse(#[from] chrono::ParseError),\n", "file_path": "src/components/last_login.rs", "rank": 53, "score": 8.488084162863547 }, { "content": "### Service Status\n\n\n\n- List of `systemd` services to display the status of. Keys are used as the service display name, while the value is the name of the service itself.\n\n\n\n### Docker Status\n\n\n\n- List of containers to show the status of.\n\nKeys are used as the internal docker names\n\n(`NAMES` column of `docker ps`)\n\n(containers can have multiple names, and the container is selected if any of the names match).\n\nValues are the display name shown in the output.\n\nThe key **must** start with a `/` for internal containers (please see [here](https://github.com/moby/moby/issues/6705)).\n\n\n\n### Uptime\n\n\n\n- `prefix`: Text to print before the formatted uptime.\n\n\n\n### SSL Certificates\n\n\n\n- `sort_method`: The order to sort the displayed ssl certificates. Options are \"alphabetical\", \"expiration\", or \"manual\", in which case the certs will be displayed in the same order that they appear in the config file.\n\n- `[ssl_certificates.certs]`: A subsection which is a list pairs of of certificate display names (keys) and certificate paths (values).\n\n\n\n### Filesystems\n\n\n\n - List of filesystems to print the information of, in the form of pairs of names (used for display) and mount points.\n\n\n\n ### Memory\n\n\n\n - `swap_pos`: Either `beside`, `below` or `none` to indicate the location to display the sawp memory usage, if any.\n\n\n\n### Fail2Ban\n\n\n\n- `jails`: A list of Fail2Ban jails to print the ban amounts of.\n\n\n\n### Last Login\n\n\n\n- List of users (keys) and number n (values) of that user's n most recent logins to display.\n\n\n\n### Last Run\n\n\n\n- If present, prints the time that the `rust-motd` was run (useful if updating the motd only periodically e.g. via Cron).\n\n\n", "file_path": "README.md", "rank": 54, "score": 7.555659033269942 }, { "content": "### Global Config\n\nThe global configuration is used for settings that may span multiple components, e.g. the time format string, and progress bar style.\n\n\n\n- `progress_full_character` (Default `'='`): The character to use for the line segment of the progress bar indicating the \"active\" portion of the quantity represented\n\n- `progress_empty_character` (Default `'='`): The character to use for the line segment of the progress bar indicating the \"inactive\" portion of the quantity represented\n\n- `progress_prefix` (Default `\"[\"`): The character to used to cap the left side of the progress bar\n\n- `progress_suffix` (Default `\"]\"`): The character to used to cap the right side of the progress bar\n\n- `progress_width` (Default `80`): The default width of the progress bar, used only if no other \"size hint\" is available. More specifically, the `filesystem` component will automatically determine its width. If the `filesystem` component is present, then the `memory` component will use the width of the filesystem as its size hint. Otherwise it will use the configured value.\n\n- `time_format` (Default `\"%Y-%m-%d %H:%M:%S\"`): time format string\n\n\n\n## Setup\n\n\n\n### Displaying MOTD on login (server setup)\n\n\n\nThe canonical MOTD is a message printed on login.\n\nTo achieve this, the file `/etc/motd` must be kept up to date with the output of `rust-motd`.\n\nOne of the simplest ways to do this is with a cron job.\n\nThe line below will update `/etc/motd` every 5 minutes.\n\nThis must be run as root (`sudo crontab -e`)\n\nin order to write to the protected file `/etc/motd`.\n\n\n\n```cron\n\n*/5 * * * * rust-motd > /etc/motd\n\n```\n\n\n", "file_path": "README.md", "rank": 55, "score": 6.515445090131465 }, { "content": " S: AsRef<OsStr>,\n\n {\n\n self.command.args(args);\n\n self\n\n }\n\n\n\n pub fn output(&mut self) -> Result<Output, BetterCommandError> {\n\n self.command.output().map_err(|err| match err.kind() {\n\n ErrorKind::NotFound => BetterCommandError::NotFound {\n\n executable: self.executable.clone(),\n\n },\n\n _ => BetterCommandError::IOError { source: err },\n\n })\n\n }\n\n\n\n pub fn get_output_string(&mut self) -> Result<String, BetterCommandError> {\n\n Ok(u8vec_to_string(self.output()?.stdout))\n\n }\n\n\n\n pub fn check_status_and_get_output_string(&mut self) -> Result<String, BetterCommandError> {\n", "file_path": "src/command.rs", "rank": 56, "score": 6.43406119766016 }, { "content": " _ => Err(FilesystemsError::MountNotFound { mount_point }),\n\n },\n\n )\n\n .collect::<Result<Vec<Entry>, FilesystemsError>>()?;\n\n\n\n let header = [\"Filesystems\", \"Device\", \"Mount\", \"Type\", \"Used\", \"Total\"];\n\n\n\n let column_sizes = entries\n\n .iter()\n\n .map(|entry| {\n\n vec![\n\n entry.filesystem_name.len() + INDENT_WIDTH,\n\n entry.dev.len(),\n\n entry.mount_point.len(),\n\n entry.fs_type.len(),\n\n entry.used.len(),\n\n entry.total.len(),\n\n ]\n\n })\n\n .chain(iter::once(header.iter().map(|x| x.len()).collect()))\n", "file_path": "src/components/filesystem.rs", "rank": 57, "score": 5.655997899458975 }, { "content": " for entry in formatted_entries {\n\n match entry {\n\n Ok(x) => println!(\"{}\", x),\n\n Err(err) => println!(\"{}\", err),\n\n }\n\n }\n\n }\n\n None => println!(\n\n \"{indent}{color}No logins found for `{username}'{reset}\",\n\n indent = \" \".repeat(2 * INDENT_WIDTH as usize),\n\n username = username,\n\n color = color::Fg(color::Red).to_string(),\n\n reset = style::Reset,\n\n ),\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "src/components/last_login.rs", "rank": 58, "score": 5.3949912599629055 }, { "content": "pub mod banner;\n\npub mod docker;\n\npub mod fail_2_ban;\n\npub mod filesystem;\n\npub mod last_login;\n\npub mod last_run;\n\npub mod memory;\n\npub mod service_status;\n\npub mod ssl_certs;\n\npub mod uptime;\n\npub mod weather;\n", "file_path": "src/components/mod.rs", "rank": 59, "score": 5.20837134392154 }, { "content": " \"{indent}{name}: {padding}{color}{status}{reset}\",\n\n indent = \" \".repeat(INDENT_WIDTH as usize),\n\n name = name,\n\n padding = \" \".repeat(max_len - name.len()),\n\n color = status_color,\n\n status = container.status,\n\n reset = style::Reset,\n\n );\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "src/components/docker.rs", "rank": 60, "score": 5.052394847191979 }, { "content": " format!(\"{}expiring on{}\", color::Fg(color::Yellow), style::Reset)\n\n } else {\n\n format!(\"{}valid until{}\", color::Fg(color::Green), style::Reset)\n\n };\n\n cert_infos.push(CertInfo {\n\n name,\n\n status,\n\n expiration,\n\n });\n\n }\n\n\n\n match config.sort_method {\n\n SortMethod::Alphabetical => {\n\n cert_infos.sort_by(|a, b| a.name.cmp(&b.name));\n\n }\n\n SortMethod::Expiration => {\n\n cert_infos.sort_by(|a, b| a.expiration.cmp(&b.expiration));\n\n }\n\n SortMethod::Manual => {}\n\n }\n", "file_path": "src/components/ssl_certs.rs", "rank": 61, "score": 4.8495010392602715 }, { "content": " BannerColor::LightBlue => color::LightBlue.fg_str(),\n\n BannerColor::LightMagenta => color::LightMagenta.fg_str(),\n\n BannerColor::LightCyan => color::LightCyan.fg_str(),\n\n BannerColor::LightWhite => color::LightWhite.fg_str(),\n\n };\n\n\n\n println!(\"{}{}{}\", banner_color, &output.trim_end(), style::Reset);\n\n\n\n Ok(())\n\n}\n", "file_path": "src/components/banner.rs", "rank": 62, "score": 4.648025949541964 }, { "content": " \"{}\",\n\n [\n\n \" \".repeat(INDENT_WIDTH),\n\n global_settings.progress_prefix.to_string(),\n\n full_color,\n\n global_settings\n\n .progress_full_character\n\n .to_string()\n\n .repeat(bar_full),\n\n color::Fg(color::LightBlack).to_string(),\n\n global_settings\n\n .progress_empty_character\n\n .to_string()\n\n .repeat(bar_empty),\n\n style::Reset.to_string(),\n\n global_settings.progress_suffix.to_string(),\n\n ]\n\n .join(\"\")\n\n );\n\n }\n\n\n\n Ok(Some(fs_display_width))\n\n}\n", "file_path": "src/components/filesystem.rs", "rank": 63, "score": 4.542073925521981 }, { "content": " println!();\n\n }\n\n\n\n if let Some(ssl_certificates_config) = config.ssl_certificates {\n\n disp_ssl(ssl_certificates_config, &config.global)\n\n .unwrap_or_else(|err| println!(\"SSL Certificate error: {}\", err));\n\n println!();\n\n }\n\n\n\n let mut bar_size_hint: Option<usize> = None;\n\n if let Some(filesystems) = config.filesystems {\n\n bar_size_hint =\n\n disp_filesystem(filesystems, &config.global, &sys).unwrap_or_else(|err| {\n\n println!(\"Filesystem error: {}\", err);\n\n None\n\n });\n\n println!();\n\n }\n\n\n\n if let Some(memory) = config.memory {\n", "file_path": "src/main.rs", "rank": 64, "score": 4.512461632219431 }, { "content": " }\n\n }\n\n }).collect::<Vec<_>>();\n\n\n\n // Max length of all the container names (first column)\n\n // to determine the padding\n\n if let Some(max_len) = config.values().map(|v| v.len()).max() {\n\n\n\n for (name, container) in containers {\n\n let status_color = match container.state {\n\n ContainerStatus::Created\n\n | ContainerStatus::Restarting\n\n | ContainerStatus::Paused\n\n | ContainerStatus::Removing\n\n | ContainerStatus::Configured => color::Fg(color::Yellow).to_string(),\n\n ContainerStatus::Running => color::Fg(color::Green).to_string(),\n\n ContainerStatus::Exited => color::Fg(color::LightBlack).to_string(),\n\n ContainerStatus::Dead => color::Fg(color::Red).to_string(),\n\n };\n\n println!(\n", "file_path": "src/components/docker.rs", "rank": 65, "score": 4.451052014849342 }, { "content": " }\n\n None => ureq::AgentBuilder::new().build(),\n\n };\n\n let body = agent\n\n .get(&url)\n\n .set(\"User-Agent\", \"curl\")\n\n .call()?\n\n .into_string()?;\n\n\n\n let mut body = body.lines();\n\n let first_line = body\n\n .next()\n\n .ok_or(WeatherError::ReplyEmpty)?\n\n .replace(\"+\", \" \") // de-slugify the placename by removing '+'\n\n .replace(\",\", \", \") // and adding a space after commas\n\n .replace(\" \", \" \"); // necessary because sometimes there are already spaces\n\n // after the comma in the placename\n\n let body = body\n\n .map(|x| [x, \"\\n\"].concat())\n\n .collect::<Vec<String>>()\n", "file_path": "src/components/weather.rs", "rank": 66, "score": 3.7116814202168693 }, { "content": " }\n\n }\n\n Err(e) => println!(\"Config Error: {}\", e),\n\n }\n\n Ok(())\n\n}\n\n\n\n#[derive(Error, Debug)]\n\npub enum ConfigError {\n\n #[error(\n\n \"Configuration file not found.\\n\\\n\n Make a copy of default config and either specify it as an arg or \\n\\\n\n place it in a default location. See ReadMe for details.\"\n\n )]\n\n ConfigNotFound,\n\n\n\n #[error(transparent)]\n\n ConfigHomeError(#[from] std::env::VarError),\n\n\n\n #[error(transparent)]\n\n IOError(#[from] std::io::Error),\n\n\n\n #[error(transparent)]\n\n ConfigParseError(#[from] toml::de::Error),\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 67, "score": 2.946996622073562 }, { "content": " LightRed,\n\n #[serde(alias = \"light_green\")]\n\n LightGreen,\n\n #[serde(alias = \"light_yellow\")]\n\n LightYellow,\n\n #[serde(alias = \"light_blue\")]\n\n LightBlue,\n\n #[serde(alias = \"light_magenta\")]\n\n LightMagenta,\n\n #[serde(alias = \"light_cyan\")]\n\n LightCyan,\n\n #[serde(alias = \"light_white\")]\n\n LightWhite,\n\n}\n\n\n\n#[derive(Error, Debug)]\n\npub enum BannerError {\n\n #[error(transparent)]\n\n BetterCommandError(#[from] BetterCommandError),\n\n\n\n #[error(transparent)]\n\n IOError(#[from] std::io::Error),\n\n}\n\n\n", "file_path": "src/components/banner.rs", "rank": 68, "score": 2.8214328304479186 }, { "content": "## Configuration\n\n\n\n`rust-motd` uses a `TOML` configuration file to determine which components to run, and any parameters for those components. Components can be enabled or disabled by including or removing/commenting out the relevant section of configuration. An example configuration file is included in [example_config.toml](example_config.toml).\n\n\n\nA configuration file can either be specified as the first argument to `rust-motd` via the comnmand line or placed in one of two default locations. If a config file is not specified as an argument, `rust-motd` will check `$XDG_CONFIG_HOME/rust-motd/config.toml` and `$HOME/.config/rust-motd/config.toml` in that order.\n\n\n\nThe options for each component are listed below:\n\n### Banner\n\n\n\n- `color`: The color of the banner text. Options are black, red, green, yellow, blue, magenta, cyan, white, and light variants of each.\n\n- `command`: A command executed via `sh` which generates the banner. For example, you could pipe the output of `hostname` to `figlet` to generate a block letter banner.\n\n\n\n### Weather\n\n\n\nThe weather component allows you to either specify a [wttr.in](https://wttr.in) url, or a location and display style which will be used to build the url.\n\n\n\nEither:\n\n\n\n- `url`: a [wttr.in](https://wttr.in) query url for the relevant location. E.g. `https://wttr.in` or `https://wttr.in/New+York,New+York?0`. For more detail about the options available via the request url, see the [wttr.in documentation](https://github.com/chubin/wttr.in). The response of an http request to the specified url is output directly to the console, so in theory you could use a service other than [wttr.in](wttr.in).\n\n\n\nor:\n\n\n\n- `loc`: The location to retrieve the weather for, e.g. \"New York,New York\".\n\n- `style`: One of either \"oneline\", \"day\", or \"full\".\n\n\n\nIn the case both are specified, the `url` parameter is given priority.\n\n\n\nIf you need a proxy to access the internet, specify it in below item:\n\n\n\n- `proxy`: The http proxy server which used to access internet.\n\n\n", "file_path": "README.md", "rank": 69, "score": 2.6681207245451732 }, { "content": "## Alternatives\n\n\n\n`rust-motd` took a lot of inspiration from `panda-motd`.\n\n\n\n- [panda-motd](https://github.com/taylorthurlow/panda-motd): \"a utility for generating a more useful MOTD\", Ruby\n\n- [motd-on-acid](https://github.com/x70b1/motd-on-acid): \"This MOTD has so many colors!\", Shell\n\n- [fancy-motd](https://github.com/bcyran/fancy-motd): \"Fancy, colorful MOTD written in bash. Server status at a glance.\", Shell\n\n- [HermannBjorgvin/MOTD](https://github.com/HermannBjorgvin/motd): \"Mini MOTD, a customizable, configurable, standardized MOTD for your homelab server or laptop\", Shell\n\n\n\nSearch \"MOTD\" on [r/unixporn](https://reddit.com/r/unixporn) for more!\n\n\n\n## Acknowledgements\n\n\n\nA huge thank you to the kind folks at Jupiter Broadcasting\n\nfor featuring `rust-motd` on [Linux Unplugged 428](https://linuxunplugged.com/428)!\n\n\n\n`rust-motd` is made possible by the following packages:\n\n\n\n- [wttr.in](https://github.com/chubin/wttr.in) \":partly_sunny: The right way to check the weather\"\n\n- [systemstat](https://github.com/unrelentingtech/systemstat): \"Rust library for getting system information\", used for filesystem usage\n\n- [termion](https://docs.rs/termion/1.5.6/termion/): Rust library used to print fancy colours in the terminal\n\n- [termtosvg](https://github.com/nbedos/termtosvg): \"Record terminal sessions as SVG animations\", used to generate the preview in the README\n\n- [bytesize](https://docs.rs/bytesize/1.0.1/bytesize/): Rust library used for binary size representations\n\n- [humantime](https://docs.rs/humantime/2.0.1/humantime/): \"Human-friendly time parser and formatter\", used for uptime component\n\n\n\n## Footnotes\n\n<a id=\"footnote-1\"></a>\n\n¹: Certain components do have dependencies: `fail2ban` (`fail2ban`), `service_status` (`systemd`),\n\n`last_login` (`last`).\n\nHowever, it would not make sense to request the status of a package that is not installed.\n\n[Furthermore, there are some caveats when compiling for minimal distributions like Alpine Linux.](#compiling-alpine)\n", "file_path": "README.md", "rank": 70, "score": 2.5474710582052147 }, { "content": " .fold(vec![0; header.len()], |acc, x| {\n\n x.iter()\n\n .zip(acc.iter())\n\n .map(|(a, b)| cmp::max(a, b).to_owned())\n\n .collect()\n\n });\n\n\n\n print_row(header, &column_sizes);\n\n\n\n // -2 because \"Filesystems\" does not count (it is not indented)\n\n // and because zero indexed\n\n let bar_width = column_sizes.iter().sum::<usize>() + (header.len() - 2) * INDENT_WIDTH\n\n - global_settings.progress_prefix.len()\n\n - global_settings.progress_suffix.len();\n\n let fs_display_width =\n\n bar_width + global_settings.progress_prefix.len() + global_settings.progress_suffix.len();\n\n\n\n for entry in entries {\n\n let bar_full = ((bar_width as f64) * entry.used_ratio) as usize;\n\n let bar_empty = bar_width - bar_full;\n", "file_path": "src/components/filesystem.rs", "rank": 71, "score": 2.4442976284232425 }, { "content": " key,\n\n \" \".repeat(padding - key.len()),\n\n status_color,\n\n status,\n\n style::Reset,\n\n );\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "src/components/service_status.rs", "rank": 72, "score": 2.4195335077206357 }, { "content": " let output = self.output()?;\n\n\n\n match output.status.success() {\n\n true => Ok(u8vec_to_string(output.stdout)),\n\n false => Err(BetterCommandError::ExitStatusError {\n\n executable: self.executable.clone(),\n\n exit_code: output.status.code().unwrap(),\n\n error: u8vec_to_string(output.stderr),\n\n }),\n\n }\n\n }\n\n}\n", "file_path": "src/command.rs", "rank": 73, "score": 2.36240698357469 }, { "content": "\n\n for cert_info in cert_infos.into_iter() {\n\n println!(\n\n \"{}{} {} {}\",\n\n \" \".repeat(INDENT_WIDTH as usize),\n\n cert_info.name,\n\n cert_info.status,\n\n cert_info.expiration.format(&global_settings.time_format)\n\n );\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "src/components/ssl_certs.rs", "rank": 74, "score": 2.0851652050304983 }, { "content": " };\n\n format!(\"{}{}{}\", colour, message, style::Reset)\n\n }\n\n };\n\n\n\n Ok(format!(\n\n \"{indent}from {location} at {login_time} ({exit})\",\n\n location = location,\n\n login_time = login_time.format(time_format),\n\n exit = exit,\n\n indent = \" \".repeat(2 * INDENT_WIDTH as usize),\n\n ))\n\n}\n\n\n", "file_path": "src/components/last_login.rs", "rank": 75, "score": 1.9431953968495776 }, { "content": " disp_memory(memory, &config.global, &sys, bar_size_hint) // TODO:\n\n .unwrap_or_else(|err| println!(\"Filesystem error: {}\", err));\n\n println!();\n\n }\n\n\n\n if let Some(last_login_config) = config.last_login {\n\n disp_last_login(last_login_config, &config.global)\n\n .unwrap_or_else(|err| println!(\"Last login error: {}\", err));\n\n println!();\n\n }\n\n\n\n if let Some(fail_2_ban_config) = config.fail_2_ban {\n\n disp_fail_2_ban(fail_2_ban_config)\n\n .unwrap_or_else(|err| println!(\"Fail2Ban error: {}\", err));\n\n println!();\n\n }\n\n\n\n if let Some(last_run_config) = config.last_run {\n\n disp_last_run(last_run_config, &config.global)\n\n .unwrap_or_else(|err| println!(\"Last run error: {}\", err));\n", "file_path": "src/main.rs", "rank": 76, "score": 1.8761236625549955 }, { "content": " match get_config(args) {\n\n Ok(config) => {\n\n let sys = System::new();\n\n\n\n if let Some(banner_config) = config.banner {\n\n disp_banner(banner_config).unwrap_or_else(|err| println!(\"Banner error: {}\", err));\n\n println!();\n\n }\n\n\n\n if let Some(weather_config) = config.weather {\n\n disp_weather(weather_config)\n\n .unwrap_or_else(|err| println!(\"Weather error: {}\", err));\n\n println!();\n\n }\n\n\n\n if let Some(uptime_config) = config.uptime {\n\n disp_uptime(uptime_config, &sys)\n\n .unwrap_or_else(|err| println!(\"Uptime error: {}\", err));\n\n println!();\n\n }\n", "file_path": "src/main.rs", "rank": 77, "score": 1.5172418411666229 }, { "content": "# `rust-motd`\n\n\n\n> Beautiful, useful, configurable MOTD generation with zero[¹](#footnote-1) runtime dependencies\n\n\n\n<p align=\"center\">\n\n\t<img src=\"./docs/example_output.svg\" />\n\n</p>\n\n\n\nI got stuck in dependency hell one too many times\n\ntrying to update interpreted alternatives\n\nand decided to write my own MOTD generator in Rust.\n\nThe goal of this project is to provide beautiful yet useful status screens\n\nwhich can quickly give an overview of your server or personal computer.\n\n\n\n## Installation\n\n\n\n### Building from source\n\n\n\n- Install [rustup](https://rustup.rs/) and [cargo](https://github.com/rust-lang/cargo/)\n\n- Install and configure the default toolchain with `rustup install stable` and `rustup default stable`\n\n- Install the equivalent of the `libssl-dev` package using your package manager\n\n- Clone this repository and enter it\n\n- Run `cargo build` or `cargo run`\n\n\n\n<a id=\"compiling-alpine\"></a>\n\nNote: To cross compile, you may need to install additional packages. For example, to cross compile for Alpine, it was necessary to install the `musl-tools` package on Ubuntu (specifically to compile the `ring` crate), after which an executable could be successfully cross-compiled with `cargo build --target x86_64-unknown-linux-musl` (assuming you've already added the musl toolchain via `rustup target add x86_64-unknown-linux-musl`).\n\n[See more.](https://www.reddit.com/r/rust/comments/qdm8gf/comment/hhor67v/?utm_source=share&utm_medium=web2x&context=3)\n\n\n\n### Arch Linux\n\n\n\n`rust-motd` is in the AUR under [`rust-motd-bin`](https://aur.archlinux.org/packages/rust-motd-bin/) thanks to [`cargo-aur`](https://github.com/fosskers/cargo-aur).\n\n\n", "file_path": "README.md", "rank": 78, "score": 1.3967122487677859 }, { "content": "\n\n if let Some(service_status_config) = config.service_status {\n\n println!(\"System Services:\");\n\n disp_service_status(service_status_config, false)\n\n .unwrap_or_else(|err| println!(\"Service status error: {}\", err));\n\n println!();\n\n }\n\n\n\n if let Some(service_status_config) = config.user_service_status {\n\n println!(\"User Services:\");\n\n disp_service_status(service_status_config, true)\n\n .unwrap_or_else(|err| println!(\"User service status error: {}\", err));\n\n println!();\n\n }\n\n\n\n if let Some(docker_config) = config.docker_status {\n\n println!(\"Docker:\");\n\n disp_docker(docker_config)\n\n .await\n\n .unwrap_or_else(|err| println!(\"Docker status error: {}\", err));\n", "file_path": "src/main.rs", "rank": 79, "score": 1.3542860135980903 }, { "content": "### Displaying MOTD on every new terminal (personal computer setup)\n\n\n\nIt can also be nice to show the MOTD locally every time you launch a new terminal emulator\n\n(or on every new pane if you use `tmux`).\n\nIndeed, some components make more sense on a server (ssl, fail2ban, last login)\n\nwhereas others make more sense on a local machine (weather, user services).\n\n\n\nThe setup for this is slightly different.\n\nFirst of all, you will probably want to run `rust-motd` as your normal user,\n\nnot as root.\n\nThis is especially true if you are using the user services component.\n\nThis also means that you won't have permission to write to `/etc/motd`.\n\nI chose `~/.local/etc/motd`.\n\nFinally, I had to set the environment variable `DBUS_SESSION_BUS_ADDRESS`\n\nin my `crontab` in order to see the status of my user systemd services.\n\nWithout it, the underlying call to `systemctl` would return nothing\n\nand nothing would be shown in `rust-motd`.\n\n\n\n```cron\n\n*/5 * * * * export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus; rust-motd > ~/.local/etc/motd\n\n```\n\n\n\nFinally, with `~/.local/etc/motd` populated,\n\nthe last step is to print the contents of this file every time a new terminal emulator is launched.\n\nOpen your shell's configuration file (`.bashrc`, `.zshrc`, etc.)\n\nand add the following line at the very bottom\n\n(if you aliased `cat` to `bat` as I did replace `cat` below with `command cat`):\n\n\n\n```\n\ncat $HOME/.local/etc/motd\n\n```\n\n\n\n\n", "file_path": "README.md", "rank": 80, "score": 1.2032683071699153 } ]
Rust
task-scheduler-rust/src/apply.rs
gyuho/task-scheduler-examples
bd9475b90679d060fdcb9bf856e5a81ed15917c2
use std::{ io, io::{Error, ErrorKind}, string::String, sync::Arc, time::{Duration, Instant}, }; use tokio::{ select, sync::mpsc, task::{self, JoinHandle}, time::timeout, }; use crate::echo; use crate::id; use crate::notify; #[derive(Debug)] pub struct Request { pub echo_request: Option<echo::Request>, } impl Request { pub fn new() -> Self { Self { echo_request: None } } } pub struct Applier { request_timeout: Duration, request_id_generator: id::Generator, notifier: Arc<notify::Notifier>, request_tx: mpsc::UnboundedSender<(u64, Request)>, stop_tx: mpsc::Sender<()>, } impl Applier { pub fn new(req_timeout: Duration) -> (Self, JoinHandle<io::Result<()>>) { let member_id = rand::random::<u64>(); let (request_ch_tx, request_ch_rx) = mpsc::unbounded_channel(); let (stop_ch_tx, stop_ch_rx) = mpsc::channel(1); let notifier = Arc::new(notify::Notifier::new()); let notifier_clone = notifier.clone(); let echo_manager = echo::Manager::new(); let handle = task::spawn(async move { apply_async(notifier_clone, request_ch_rx, stop_ch_rx, echo_manager).await }); ( Self { request_timeout: req_timeout, request_id_generator: id::Generator::new(member_id, Instant::now().elapsed()), notifier, request_tx: request_ch_tx, stop_tx: stop_ch_tx, }, handle, ) } pub async fn stop(&self) -> io::Result<()> { println!("stopping applier"); match self.stop_tx.send(()).await { Ok(()) => println!("sent stop_tx"), Err(e) => { println!("failed to send stop_tx: {}", e); return Err(Error::new(ErrorKind::Other, format!("failed to send"))); } } println!("stopped applier"); Ok(()) } pub async fn apply(&self, req: Request) -> io::Result<String> { let req_id = self.request_id_generator.next(); let resp_rx = self.notifier.register(req_id)?; match self.request_tx.send((req_id, req)) { Ok(_) => println!("scheduled a request"), Err(e) => { self.notifier .trigger(req_id, format!("failed to schedule {} {}", req_id, e))?; } } let msg = timeout(self.request_timeout, resp_rx) .await .map_err(|_| Error::new(ErrorKind::Other, "timeout"))?; let rs = msg.map_err(|e| Error::new(ErrorKind::Other, format!("failed to apply {}", e)))?; Ok(rs) } } pub async fn apply_async( notifier: Arc<notify::Notifier>, mut request_rx: mpsc::UnboundedReceiver<(u64, Request)>, mut stop_rx: mpsc::Receiver<()>, mut echo_manager: echo::Manager, ) -> io::Result<()> { println!("running apply loop"); 'outer: loop { let (req_id, req) = select! { Some(v) = request_rx.recv() => v, _ = stop_rx.recv() => { println!("received stop_rx"); break 'outer; } }; match req.echo_request { Some(v) => match echo_manager.apply(&v) { Ok(rs) => match notifier.trigger(req_id, rs) { Ok(_) => {} Err(e) => println!("failed to trigger {}", e), }, Err(e) => { println!("failed to apply {}", e); match notifier.trigger(req_id, format!("failed {}", e)) { Ok(_) => {} Err(e) => println!("failed to trigger {}", e), } } }, None => {} } } Ok(()) }
use std::{ io, io::{Error, ErrorKind}, string::String, sync::Arc, time::{Duration, Instant}, }; use tokio::{ select, sync::mpsc, task::{self, JoinHandle}, time::timeout, }; use crate::echo; use crate::id; use crate::notify; #[derive(Debug)] pub struct Request { pub echo_request: Option<echo::Request>, } impl Request { pub fn new() -> Self { Self { echo_request: None } } } pub struct Applier { request_timeout: Duration, request_id_generator: id::Generator, notifier: Arc<notify::Notifier>, request_tx: mpsc::UnboundedSender<(u64, Request)>, stop_tx: mpsc::Sender<()>, } impl Applier { pub fn new(req_timeout: Duration) -> (Self, JoinHandle<io::Result<()>>) { let member_id = rand::random::<u64>(); let (request_ch_tx, request_ch_rx) = mpsc::unbounded_channel(); let (stop_ch_tx, stop_ch_rx) = mpsc::channel(1); let notifier = Arc::new(notify::Notifier::new()); let notifier_clone = notifier.clone(); let echo_manager = echo::Manager::new(); let handle = task::spawn(async move { apply_async(notifier_clone, request_ch_rx, stop_ch_rx, echo_manager).await }); ( Self { request_timeout: req_timeout, request_id_generator: id::Generator::new(member_id, Instant::now().elapsed()), notifier, request_tx: request_ch_tx, stop_tx: stop_ch_tx, }, handle, ) } pub async fn stop(&self) -> io::Result<()> { println!("stopping applier"); match self.stop_tx.send(()).await { Ok(()) => println!("sent stop_tx"), Err(e) => { println!("failed to send stop_tx: {}", e); return Err(Error::new(ErrorKind::Other, format!("failed to send"))); } } println!("stopped applier"); Ok(()) } pub async fn apply(&self, req: Request) -> io::Result<String> { let req_id = self.request_id_generator.next(); let resp_rx = self.notifier.register(req_id)?; match self.request_tx.send((req_id, req)) { Ok(_) => println!("scheduled a request"), Err(e) => { self.notifier .trigger(req_id, format!("failed to schedule {} {}", req_id, e))?; } } let msg = timeout(self.request_timeout, resp_rx) .await .map_err(|_| Error::new(ErrorKind::Other, "timeout"))?; let rs = msg.map_err(|e| Error::new(ErrorKind::Other, format!("failed to apply {}", e)))?; Ok(rs) } }
pub async fn apply_async( notifier: Arc<notify::Notifier>, mut request_rx: mpsc::UnboundedReceiver<(u64, Request)>, mut stop_rx: mpsc::Receiver<()>, mut echo_manager: echo::Manager, ) -> io::Result<()> { println!("running apply loop"); 'outer: loop { let (req_id, req) = select! { Some(v) = request_rx.recv() => v, _ = stop_rx.recv() => { println!("received stop_rx"); break 'outer; } }; match req.echo_request { Some(v) => match echo_manager.apply(&v) { Ok(rs) => match notifier.trigger(req_id, rs) { Ok(_) => {} Err(e) => println!("failed to trigger {}", e), }, Err(e) => { println!("failed to apply {}", e); match notifier.trigger(req_id, format!("failed {}", e)) { Ok(_) => {} Err(e) => println!("failed to trigger {}", e), } } }, None => {} } } Ok(()) }
function_block-full_function
[ { "content": "pub fn parse_request(b: &[u8]) -> io::Result<Request> {\n\n serde_json::from_slice(b).map_err(|e| {\n\n return Error::new(ErrorKind::InvalidInput, format!(\"invalid JSON: {}\", e));\n\n })\n\n}\n\n\n", "file_path": "task-scheduler-rust/src/echo.rs", "rank": 0, "score": 142323.69819916965 }, { "content": "#[test]\n\nfn test_parse_request() {\n\n let ret = parse_request(\"{\\\"kind\\\":\\\"create\\\",\\\"message\\\":\\\"hello\\\"}\".as_bytes());\n\n assert!(ret.is_ok());\n\n let t = ret.unwrap();\n\n assert_eq!(t.kind, \"create\");\n\n assert_eq!(t.message, \"hello\");\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Manager {}\n\n\n\nimpl Manager {\n\n pub fn new() -> Self {\n\n Self {}\n\n }\n\n\n\n pub fn apply(&mut self, req: &Request) -> io::Result<String> {\n\n println!(\"applying echo request\");\n\n\n\n // check every 5-second\n", "file_path": "task-scheduler-rust/src/echo.rs", "rank": 1, "score": 90531.82010988015 }, { "content": "type applier struct {\n\n\trequestTimeout time.Duration\n\n\n\n\trequestIDGenerator Generator\n\n\tnotifier Notifier\n\n\n\n\t// for sending requests in the queue\n\n\trequestCh chan requestTuple\n\n\n\n\tstopCh chan struct{}\n\n\tdoneCh chan struct{}\n\n\n\n\techoManager EchoManager\n", "file_path": "task-scheduler-go/apply.go", "rank": 2, "score": 70797.56948712244 }, { "content": "type Applier interface {\n\n\tstart()\n\n\tstop() error\n\n\tapply(req Request) (string, error)\n", "file_path": "task-scheduler-go/apply.go", "rank": 3, "score": 70797.56948712244 }, { "content": "#[derive(Clap)]\n\n#[clap(version = \"0.2.0\")]\n\nstruct Opts {\n\n #[clap(long, default_value = \"3000\")]\n\n port: u16,\n\n #[clap(long, default_value = \"10\")]\n\n request_timeout_seconds: u64,\n\n}\n\n\n", "file_path": "task-scheduler-rust/src/main.rs", "rank": 4, "score": 70469.01529494839 }, { "content": "type Request struct {\n\n\techoRequest *EchoRequest\n", "file_path": "task-scheduler-go/apply.go", "rank": 5, "score": 70380.29119755367 }, { "content": "\trequest Request\n", "file_path": "task-scheduler-go/apply.go", "rank": 6, "score": 70380.29119755367 }, { "content": "func newApplier(requestTimeout time.Duration) Applier {\n\n\tmemberID := rand.Uint64()\n\n\treturn &applier{\n\n\t\trequestTimeout: requestTimeout,\n\n\n\n\t\trequestIDGenerator: newGenerator(memberID, time.Now().UnixNano()),\n\n\t\tnotifier: newNotifier(),\n\n\n\n\t\trequestCh: make(chan requestTuple, 1000),\n\n\t\tstopCh: make(chan struct{}),\n\n\t\tdoneCh: make(chan struct{}),\n\n\n\n\t\techoManager: newEchoManager(),\n\n\t}\n", "file_path": "task-scheduler-go/apply.go", "rank": 7, "score": 70230.01494767416 }, { "content": "\trequestTimeout time.Duration\n", "file_path": "task-scheduler-go/apply.go", "rank": 8, "score": 70021.82880834739 }, { "content": "fn main() {\n\n let opts: Opts = Opts::parse();\n\n println!(\"crate version {}\", crate_version!(),);\n\n\n\n let srv = server::Handler::new(opts.port, Duration::from_secs(opts.request_timeout_seconds));\n\n\n\n let future_task = srv.start();\n\n let rt = tokio::runtime::Runtime::new().unwrap();\n\n\n\n // we can run tokio within async_std and the other way around\n\n // NOTE: DO NOT CALL THIS RECURSIVELY\n\n // e.g. \"Cannot start a runtime from within a runtime. This happens because a function (like `block_on`) attempted to block the current thread while the thread is being used to drive asynchronous tasks\"\n\n let ret = rt.block_on(future_task);\n\n match ret {\n\n Ok(_) => println!(\"server done\"),\n\n Err(e) => println!(\"server aborted {}\", e),\n\n };\n\n}\n", "file_path": "task-scheduler-rust/src/main.rs", "rank": 9, "score": 69965.35938290972 }, { "content": "#[test]\n\nfn test_generator() {\n\n let member_id = rand::random::<u64>();\n\n\n\n use std::time::Instant;\n\n let elapsed = Instant::now().elapsed();\n\n let gen = Generator::new(member_id, elapsed);\n\n\n\n println!(\"{}\", gen.next());\n\n println!(\"{}\", gen.next());\n\n}\n\n\n", "file_path": "task-scheduler-rust/src/id.rs", "rank": 10, "score": 68219.22593428573 }, { "content": "#[test]\n\nfn test_generator_unique() {\n\n let gen0 = Generator::new(0, Duration::from_millis(100));\n\n let id0 = gen0.next();\n\n\n\n let gen1 = Generator::new(1, Duration::from_millis(100));\n\n let id1 = gen1.next();\n\n assert_ne!(id0, id1);\n\n\n\n let gen0_restarted = Generator::new(0, Duration::from_millis(101));\n\n let id0_restarted = gen0_restarted.next();\n\n assert_ne!(id0, id0_restarted);\n\n}\n", "file_path": "task-scheduler-rust/src/id.rs", "rank": 11, "score": 66581.87661091395 }, { "content": "#[test]\n\nfn test_generator_next() {\n\n let gen = Generator::new(0x12, Duration::from_millis(0x3456));\n\n let id = gen.next();\n\n assert_eq!(id, 0x12000000345600);\n\n for i in 0..1000 {\n\n let id2 = gen.next();\n\n assert_eq!(id2, id + i + 1);\n\n }\n\n}\n\n\n", "file_path": "task-scheduler-rust/src/id.rs", "rank": 12, "score": 66581.87661091395 }, { "content": "func newNotifier() Notifier {\n\n\treturn &notifier{\n\n\t\trequests: make(map[uint64]chan string),\n\n\t}\n", "file_path": "task-scheduler-go/notify.go", "rank": 13, "score": 56239.82152154921 }, { "content": " }\n\n Entry::Vacant(_) => {\n\n return Err(Error::new(\n\n ErrorKind::InvalidInput,\n\n format!(\"unknown request ID {}\", id),\n\n ))\n\n }\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\n#[tokio::test]\n\nasync fn test_notify() {\n\n use std::time::Duration;\n\n use tokio::time::timeout;\n\n use uuid::Uuid;\n\n\n\n let notifier = Notifier::new();\n", "file_path": "task-scheduler-rust/src/notify.rs", "rank": 14, "score": 55451.38838734623 }, { "content": "use std::{\n\n collections::{hash_map::Entry, HashMap},\n\n io,\n\n io::{Error, ErrorKind},\n\n string::String,\n\n sync::{Arc, Mutex},\n\n};\n\n\n\nuse tokio::sync::oneshot;\n\n\n\n#[derive(Debug)]\n\npub struct Notifier {\n\n requests: Arc<Mutex<HashMap<u64, oneshot::Sender<String>>>>,\n\n}\n\n\n\nimpl Notifier {\n\n pub fn new() -> Self {\n\n Self {\n\n requests: Arc::new(Mutex::new(HashMap::new())),\n\n }\n", "file_path": "task-scheduler-rust/src/notify.rs", "rank": 15, "score": 55449.230960041925 }, { "content": "\n\n let ret = notifier.register(100);\n\n assert!(ret.is_ok());\n\n let rx = ret.unwrap();\n\n\n\n let uuid = Uuid::new_v4().to_hyphenated().to_string();\n\n\n\n let tr = notifier.trigger(100, uuid.clone());\n\n assert!(tr.is_ok());\n\n\n\n let msg = timeout(Duration::from_secs(1), rx).await;\n\n assert_eq!(msg, Ok(Ok(uuid.clone())));\n\n\n\n let tr = notifier.trigger(100, uuid);\n\n assert!(!tr.is_ok());\n\n}\n", "file_path": "task-scheduler-rust/src/notify.rs", "rank": 16, "score": 55445.05645238373 }, { "content": " };\n\n\n\n println!(\"registered {}\", id);\n\n Ok(request_rx)\n\n }\n\n\n\n pub fn trigger(&self, id: u64, x: String) -> io::Result<()> {\n\n println!(\"triggering {}\", id);\n\n let mut locked_map = self\n\n .requests\n\n .lock()\n\n .map_err(|_| Error::new(ErrorKind::InvalidInput, \"failed to acquire lock\"))?;\n\n\n\n match locked_map.entry(id) {\n\n Entry::Occupied(entry) => {\n\n println!(\"triggered {}\", &id);\n\n let request_tx = entry.remove();\n\n request_tx.send(x).map_err(|e| {\n\n Error::new(ErrorKind::Other, format!(\"failed to send {} {}\", id, e))\n\n })?;\n", "file_path": "task-scheduler-rust/src/notify.rs", "rank": 17, "score": 55444.20790044202 }, { "content": " }\n\n\n\n pub fn register(&self, id: u64) -> io::Result<oneshot::Receiver<String>> {\n\n println!(\"registering {}\", id);\n\n let mut locked_map = self\n\n .requests\n\n .lock()\n\n .map_err(|_| Error::new(ErrorKind::InvalidInput, \"failed to acquire lock\"))?;\n\n\n\n let (request_tx, request_rx) = oneshot::channel();\n\n match locked_map.entry(id) {\n\n Entry::Vacant(entry) => {\n\n entry.insert(request_tx);\n\n }\n\n Entry::Occupied(_) => {\n\n return Err(Error::new(\n\n ErrorKind::InvalidInput,\n\n format!(\"duplicate request ID {}\", id),\n\n ))\n\n }\n", "file_path": "task-scheduler-rust/src/notify.rs", "rank": 18, "score": 55441.74465395507 }, { "content": "func (ap *applier) apply(req Request) (string, error) {\n\n\treqID := ap.requestIDGenerator.next()\n\n\trespRx, err := ap.notifier.register(reqID)\n\n\tif err != nil {\n\n\t\treturn \"\", err\n\n\t}\n\n\n\n\tselect {\n\n\tcase ap.requestCh <- requestTuple{requestID: reqID, request: req}:\n\n\tcase <-time.After(ap.requestTimeout):\n\n\t\tif err = ap.notifier.trigger(reqID, fmt.Sprintf(\"failed to schedule %d in time\", reqID)); err != nil {\n\n\t\t\treturn \"\", err\n\n\t\t}\n\n\t}\n\n\n\n\tmsg := \"\"\n\n\tselect {\n\n\tcase msg = <-respRx:\n\n\tcase <-time.After(ap.requestTimeout):\n\n\t\treturn \"\", errors.New(\"apply timeout\")\n\n\t}\n\n\n\n\treturn msg, nil\n", "file_path": "task-scheduler-go/apply.go", "rank": 19, "score": 55111.70840193164 }, { "content": "\trequests map[uint64]chan string\n", "file_path": "task-scheduler-go/notify.go", "rank": 27, "score": 49553.03825490214 }, { "content": "\tapplier Applier\n", "file_path": "task-scheduler-go/server.go", "rank": 28, "score": 49205.42524986711 }, { "content": "func handleRequest(applier Applier, w http.ResponseWriter, req *http.Request) {\n\n\tswitch req.Method {\n\n\tcase \"POST\":\n\n\t\tvar echoRequest EchoRequest\n\n\t\terr := json.NewDecoder(req.Body).Decode(&echoRequest)\n\n\t\tif err != nil {\n\n\t\t\tfmt.Fprintf(w, \"failed to read request %v\", err)\n\n\t\t\treturn\n\n\t\t}\n\n\t\ts, err := applier.apply(Request{echoRequest: &echoRequest})\n\n\t\tif err != nil {\n\n\t\t\tfmt.Fprintf(w, \"failed to apply request %v\", err)\n\n\t\t\treturn\n\n\t\t}\n\n\t\tfmt.Fprint(w, s)\n\n\n\n\tdefault:\n\n\t\thttp.Error(w, \"Method Not Allowed\", 405)\n\n\t}\n", "file_path": "task-scheduler-go/server.go", "rank": 29, "score": 49044.79761464025 }, { "content": "\tnotifier Notifier\n", "file_path": "task-scheduler-go/apply.go", "rank": 30, "score": 48599.8155037964 }, { "content": "func (ap *applier) stop() error {\n\n\tfmt.Println(\"stopping applier\")\n\n\tselect {\n\n\tcase ap.stopCh <- struct{}{}:\n\n\tcase <-time.After(5 * time.Second):\n\n\t\treturn errors.New(\"took too long to signal stop\")\n\n\t}\n\n\tselect {\n\n\tcase <-ap.doneCh:\n\n\tcase <-time.After(5 * time.Second):\n\n\t\treturn errors.New(\"took too long to receive done\")\n\n\t}\n\n\tfmt.Println(\"stopped applier\")\n\n\treturn nil\n", "file_path": "task-scheduler-go/apply.go", "rank": 31, "score": 47824.523750508626 }, { "content": "func (ap *applier) start() {\n\n\tgo func() {\n\n\t\tfmt.Println(\"starting applier async\")\n\n\t\tfor {\n\n\t\t\tselect {\n\n\t\t\tcase tup := <-ap.requestCh:\n\n\t\t\t\treqID := tup.requestID\n\n\t\t\t\treq := tup.request\n\n\t\t\t\tswitch {\n\n\t\t\t\tcase req.echoRequest != nil:\n\n\t\t\t\t\trs, err := ap.echoManager.apply(req.echoRequest)\n\n\t\t\t\t\tif err != nil {\n\n\t\t\t\t\t\trs = fmt.Sprintf(\"failed to apply %v\", err)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif err = ap.notifier.trigger(reqID, rs); err != nil {\n\n\t\t\t\t\t\tfmt.Printf(\"failed to trigger %v\", err)\n\n\t\t\t\t\t}\n\n\t\t\t\tdefault:\n\n\t\t\t\t}\n\n\t\t\tcase <-ap.stopCh:\n\n\t\t\t\tfmt.Println(\"received stop signal\")\n\n\t\t\t\tap.doneCh <- struct{}{}\n\n\t\t\t\tfmt.Println(\"signaled done\")\n\n\t\t\t\treturn\n\n\t\t\t}\n\n\t\t}\n\n\t}()\n", "file_path": "task-scheduler-go/apply.go", "rank": 32, "score": 47824.523750508626 }, { "content": "\trequestCh chan requestTuple\n", "file_path": "task-scheduler-go/apply.go", "rank": 33, "score": 47423.51450344588 }, { "content": "type requestTuple struct {\n\n\trequestID uint64\n\n\trequest Request\n", "file_path": "task-scheduler-go/apply.go", "rank": 34, "score": 47419.132808295595 }, { "content": "\trequestID uint64\n", "file_path": "task-scheduler-go/apply.go", "rank": 35, "score": 47419.132808295595 }, { "content": "\techoRequest *EchoRequest\n", "file_path": "task-scheduler-go/apply.go", "rank": 36, "score": 47419.132808295595 }, { "content": "\trequestIDGenerator Generator\n", "file_path": "task-scheduler-go/apply.go", "rank": 37, "score": 46145.93472349699 }, { "content": "type Notifier interface {\n\n\tregister(id uint64) (<-chan string, error)\n\n\ttrigger(id uint64, x string) error\n", "file_path": "task-scheduler-go/notify.go", "rank": 38, "score": 34496.38781975761 }, { "content": "type notifier struct {\n\n\tmu sync.RWMutex\n\n\trequests map[uint64]chan string\n", "file_path": "task-scheduler-go/notify.go", "rank": 39, "score": 34496.38781975761 }, { "content": "func (ntf *notifier) register(id uint64) (<-chan string, error) {\n\n\tfmt.Println(\"registering\", id)\n\n\tntf.mu.Lock()\n\n\tdefer ntf.mu.Unlock()\n\n\tch := ntf.requests[id]\n\n\tif ch != nil {\n\n\t\treturn nil, fmt.Errorf(\"dup id %x\", id)\n\n\t}\n\n\n\n\tch = make(chan string, 1)\n\n\tntf.requests[id] = ch\n\n\tfmt.Println(\"registered\", id)\n\n\treturn ch, nil\n", "file_path": "task-scheduler-go/notify.go", "rank": 40, "score": 33834.33032438366 }, { "content": "func (ntf *notifier) trigger(id uint64, x string) error {\n\n\tfmt.Println(\"triggering\", id)\n\n\tntf.mu.Lock()\n\n\tch, ok := ntf.requests[id]\n\n\tif ch == nil || !ok {\n\n\t\tntf.mu.Unlock()\n\n\t\treturn fmt.Errorf(\"request ID %d not found\", id)\n\n\t}\n\n\tdelete(ntf.requests, id)\n\n\tntf.mu.Unlock()\n\n\n\n\tch <- x\n\n\tclose(ch)\n\n\tfmt.Println(\"triggered\", id)\n\n\treturn nil\n", "file_path": "task-scheduler-go/notify.go", "rank": 41, "score": 33834.33032438366 }, { "content": "\tapply(req Request) (string, error)\n", "file_path": "task-scheduler-go/apply.go", "rank": 42, "score": 33445.09984027374 }, { "content": "func TestNotifier(t *testing.T) {\n\n\tntf := newNotifier()\n\n\tch, err := ntf.register(100)\n\n\tif err != nil {\n\n\t\tt.Fatal(err)\n\n\t}\n\n\tif err = ntf.trigger(100, \"success\"); err != nil {\n\n\t\tt.Fatal(err)\n\n\t}\n\n\tselect {\n\n\tcase msg := <-ch:\n\n\t\tif msg != \"success\" {\n\n\t\t\tt.Fatalf(\"unexpected message %q\", msg)\n\n\t\t}\n\n\tcase <-time.After(time.Second):\n\n\t}\n\n\n\n\tif err = ntf.trigger(100, \"success\"); err == nil {\n\n\t\tt.Fatal(\"expected error for trigger\")\n\n\t}\n", "file_path": "task-scheduler-go/notify_test.go", "rank": 43, "score": 33197.20681703176 }, { "content": "use std::{convert::Infallible, net::SocketAddr, sync::Arc, time::Duration};\n\n\n\nuse futures::{TryFutureExt, TryStreamExt};\n\nuse http::{Method, Request, Response, StatusCode};\n\nuse hyper::server::conn::AddrStream;\n\nuse hyper::service::{make_service_fn, service_fn};\n\nuse hyper::{Body, Server};\n\nuse tokio::signal;\n\n\n\nuse task_scheduler_rust::apply;\n\nuse task_scheduler_rust::echo;\n\n\n\npub struct Handler {\n\n listener_port: u16,\n\n request_timeout: Duration,\n\n}\n\n\n\nimpl Handler {\n\n pub fn new(listener_port: u16, request_timeout: Duration) -> Self {\n\n println!(\n", "file_path": "task-scheduler-rust/src/server.rs", "rank": 44, "score": 29225.7452713429 }, { "content": " \"creating handler with listener port {}, request timeout {:?}\",\n\n listener_port, request_timeout,\n\n );\n\n\n\n Self {\n\n listener_port,\n\n request_timeout,\n\n }\n\n }\n\n\n\n pub async fn start(self) -> Result<(), Box<dyn std::error::Error>> {\n\n println!(\"starting server\");\n\n\n\n let (applier, applier_handler) = apply::Applier::new(self.request_timeout);\n\n println!(\"started applier\");\n\n let applier = Arc::new(applier);\n\n\n\n let addr = ([0, 0, 0, 0], self.listener_port).into();\n\n let svc = make_service_fn(|socket: &AddrStream| {\n\n let remote_addr = socket.remote_addr();\n", "file_path": "task-scheduler-rust/src/server.rs", "rank": 45, "score": 29223.263854535104 }, { "content": " let applier = applier.clone();\n\n async move {\n\n Ok::<_, Infallible>(service_fn(move |req: Request<Body>| {\n\n handle_request(remote_addr, req, applier.clone()).or_else(\n\n |(status, body)| async move {\n\n println!(\"{}\", body);\n\n Ok::<_, Infallible>(\n\n Response::builder()\n\n .status(status)\n\n .body(Body::from(body))\n\n .unwrap(),\n\n )\n\n },\n\n )\n\n }))\n\n }\n\n });\n\n\n\n let server = Server::try_bind(&addr)?\n\n .serve(svc)\n", "file_path": "task-scheduler-rust/src/server.rs", "rank": 46, "score": 29222.7773722619 }, { "content": " .with_graceful_shutdown(handle_sigint());\n\n\n\n println!(\"listener start http://{}\", addr);\n\n if let Err(e) = server.await {\n\n println!(\"server error: {}\", e);\n\n }\n\n println!(\"listener done http://{}\", addr);\n\n\n\n match applier.stop().await {\n\n Ok(_) => println!(\"stopped applier\"),\n\n Err(e) => println!(\"failed to stop applier {}\", e),\n\n }\n\n\n\n applier_handler.await??;\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\nasync fn handle_request(\n", "file_path": "task-scheduler-rust/src/server.rs", "rank": 47, "score": 29222.66902501787 }, { "content": " // use std::{thread, time::Duration};\n\n // thread::sleep(Duration::from_secs(5));\n\n\n\n match req.kind.as_str() {\n\n \"create\" => Ok(format!(\"SUCCESS create {}\", req.message)),\n\n \"delete\" => Ok(format!(\"SUCCESS delete {}\", req.message)),\n\n _ => Err(Error::new(\n\n ErrorKind::InvalidInput,\n\n format!(\"unexpected none field value for kind {}\", req.kind),\n\n )),\n\n }\n\n }\n\n}\n", "file_path": "task-scheduler-rust/src/echo.rs", "rank": 48, "score": 29222.35441822206 }, { "content": " req.echo_request = Some(bb);\n\n req\n\n }\n\n _ => Err((\n\n StatusCode::INTERNAL_SERVER_ERROR,\n\n format!(\"unknown path {}\", path),\n\n ))?,\n\n };\n\n let rs = applier.apply(req).await.map_err(|e| {\n\n (\n\n StatusCode::INTERNAL_SERVER_ERROR,\n\n format!(\"failed to serde_json::from_str {}\", e),\n\n )\n\n })?;\n\n Response::new(Body::from(rs))\n\n }\n\n\n\n _ => Err((\n\n StatusCode::NOT_FOUND,\n\n format!(\"unknown method {} and path {}\", method, req.uri().path()),\n", "file_path": "task-scheduler-rust/src/server.rs", "rank": 49, "score": 29220.633249100672 }, { "content": "use std::{\n\n sync::atomic::{AtomicU64, Ordering},\n\n time::Duration,\n\n};\n\n\n\n#[derive(Debug)]\n\npub struct Generator {\n\n prefix: u64,\n\n suffix: AtomicU64,\n\n}\n\n\n\nimpl Generator {\n\n pub fn new(member_id: u64, since: Duration) -> Self {\n\n let unix_ms = since.as_nanos() / 1000000;\n\n\n\n let x = (u64::MAX >> 24) & (unix_ms as u64);\n\n let x = x << 8;\n\n\n\n Self {\n\n prefix: member_id << (8 * 6),\n", "file_path": "task-scheduler-rust/src/id.rs", "rank": 50, "score": 29219.480953570328 }, { "content": " addr: SocketAddr,\n\n req: Request<Body>,\n\n applier: Arc<apply::Applier>,\n\n) -> Result<Response<Body>, (http::StatusCode, String)> {\n\n let http_version = req.version();\n\n let method = req.method().clone();\n\n let cloned_uri = req.uri().clone();\n\n let path = cloned_uri.path();\n\n println!(\n\n \"version {:?}, method {}, uri path {}, remote addr {}\",\n\n http_version, method, path, addr,\n\n );\n\n\n\n let resp = match method {\n\n Method::POST => {\n\n let body = req\n\n .into_body()\n\n .try_fold(Vec::new(), |mut data, chunk| async move {\n\n data.extend_from_slice(&chunk);\n\n Ok(data)\n", "file_path": "task-scheduler-rust/src/server.rs", "rank": 51, "score": 29219.12784152174 }, { "content": " })\n\n .await\n\n .map_err(|e| {\n\n (\n\n StatusCode::INTERNAL_SERVER_ERROR,\n\n format!(\"failed to read request body {}\", e),\n\n )\n\n })?;\n\n // no need to convert to string (e.g. \"String::from_utf8(u)\")\n\n // just deserialize from bytes\n\n println!(\"read request body {}\", body.len());\n\n let req = match path {\n\n \"/echo\" => {\n\n let bb = echo::parse_request(&body).map_err(|e| {\n\n (\n\n StatusCode::INTERNAL_SERVER_ERROR,\n\n format!(\"failed to parse {}\", e),\n\n )\n\n })?;\n\n let mut req = apply::Request::new();\n", "file_path": "task-scheduler-rust/src/server.rs", "rank": 52, "score": 29218.628737810137 }, { "content": "use std::{\n\n io,\n\n io::{Error, ErrorKind},\n\n};\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\n#[serde(rename_all = \"kebab-case\")]\n\npub struct Request {\n\n pub kind: String,\n\n #[serde(default, skip_serializing_if = \"String::is_empty\")]\n\n pub message: String,\n\n}\n\n\n", "file_path": "task-scheduler-rust/src/echo.rs", "rank": 53, "score": 29217.72791683217 }, { "content": " ))?,\n\n };\n\n\n\n Ok(resp)\n\n}\n\n\n\nasync fn handle_sigint() {\n\n signal::ctrl_c()\n\n .await\n\n .expect(\"failed to install CTRL+C signal handler\");\n\n}\n", "file_path": "task-scheduler-rust/src/server.rs", "rank": 54, "score": 29216.516677166208 }, { "content": "pub mod apply;\n\npub mod echo;\n\nmod id;\n\nmod notify;\n", "file_path": "task-scheduler-rust/src/lib.rs", "rank": 55, "score": 29215.44004447264 }, { "content": "#![warn(clippy::all)]\n\n\n\nuse std::time::Duration;\n\n\n\nuse clap::{crate_version, Clap};\n\n\n\nmod server;\n\n\n\n#[derive(Clap)]\n\n#[clap(version = \"0.2.0\")]\n", "file_path": "task-scheduler-rust/src/main.rs", "rank": 56, "score": 29215.052149231047 }, { "content": " suffix: AtomicU64::new(x),\n\n }\n\n }\n\n\n\n pub fn next(&self) -> u64 {\n\n // ref. https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html\n\n let suffix = self.suffix.fetch_add(1, Ordering::Acquire);\n\n let id = self.prefix | (suffix & (u64::MAX >> 16));\n\n id\n\n }\n\n}\n\n\n\n#[test]\n", "file_path": "task-scheduler-rust/src/id.rs", "rank": 57, "score": 29213.247235553114 }, { "content": "package main\n\n\n\nimport (\n\n\t\"fmt\"\n\n\t\"sync\"\n\n)\n\n\n\n// ref. https://github.com/etcd-io/etcd/tree/release-3.5/pkg/wait\n\ntype Notifier interface {\n\n\tregister(id uint64) (<-chan string, error)\n\n\ttrigger(id uint64, x string) error\n\n}\n\n\n\nfunc newNotifier() Notifier {\n\n\treturn &notifier{\n\n\t\trequests: make(map[uint64]chan string),\n\n\t}\n\n}\n\n\n\ntype notifier struct {\n\n\tmu sync.RWMutex\n\n\trequests map[uint64]chan string\n\n}\n\n\n\nfunc (ntf *notifier) register(id uint64) (<-chan string, error) {\n\n\tfmt.Println(\"registering\", id)\n\n\tntf.mu.Lock()\n\n\tdefer ntf.mu.Unlock()\n\n\tch := ntf.requests[id]\n\n\tif ch != nil {\n\n\t\treturn nil, fmt.Errorf(\"dup id %x\", id)\n\n\t}\n\n\n\n\tch = make(chan string, 1)\n\n\tntf.requests[id] = ch\n\n\tfmt.Println(\"registered\", id)\n\n\treturn ch, nil\n\n}\n\n\n\nfunc (ntf *notifier) trigger(id uint64, x string) error {\n\n\tfmt.Println(\"triggering\", id)\n\n\tntf.mu.Lock()\n\n\tch, ok := ntf.requests[id]\n\n\tif ch == nil || !ok {\n\n\t\tntf.mu.Unlock()\n\n\t\treturn fmt.Errorf(\"request ID %d not found\", id)\n\n\t}\n\n\tdelete(ntf.requests, id)\n\n\tntf.mu.Unlock()\n\n\n\n\tch <- x\n\n\tclose(ch)\n\n\tfmt.Println(\"triggered\", id)\n\n\treturn nil\n\n}\n", "file_path": "task-scheduler-go/notify.go", "rank": 58, "score": 27007.671266541074 }, { "content": "\tmu sync.RWMutex\n", "file_path": "task-scheduler-go/notify.go", "rank": 59, "score": 27007.671266541074 }, { "content": "\ttrigger(id uint64, x string) error\n", "file_path": "task-scheduler-go/notify.go", "rank": 60, "score": 27007.671266541074 }, { "content": "\tregister(id uint64) (<-chan string, error)\n", "file_path": "task-scheduler-go/notify.go", "rank": 61, "score": 27007.671266541074 }, { "content": "func newHandler(listenerPort uint64, requestTimeout time.Duration) Handler {\n\n\treturn &handler{\n\n\t\tlistenerPort: listenerPort,\n\n\t\tapplier: newApplier(requestTimeout),\n\n\t}\n", "file_path": "task-scheduler-go/server.go", "rank": 62, "score": 26944.49410178807 }, { "content": "func newGenerator(memberID uint64, unixNano int64) Generator {\n\n\t// to count the number of milliseconds\n\n\tunixMx := uint64(unixNano) / 1000000\n\n\n\n\tx := (math.MaxUint64 >> 24) & unixMx\n\n\tx = x << 8\n\n\n\n\treturn &generator{\n\n\t\tprefix: memberID << (8 * 6),\n\n\t\tsuffix: x,\n\n\t}\n", "file_path": "task-scheduler-go/id.go", "rank": 63, "score": 26944.49410178807 }, { "content": "type EchoRequest struct {\n\n\tKind string `json:\"kind\"`\n\n\tMessage string `json:\"message,omitempty\"`\n", "file_path": "task-scheduler-go/echo.go", "rank": 64, "score": 26442.101614588457 }, { "content": "package main\n\n\n\nimport (\n\n\t\"testing\"\n\n\t\"time\"\n\n)\n\n\n\nfunc TestNotifier(t *testing.T) {\n\n\tntf := newNotifier()\n\n\tch, err := ntf.register(100)\n\n\tif err != nil {\n\n\t\tt.Fatal(err)\n\n\t}\n\n\tif err = ntf.trigger(100, \"success\"); err != nil {\n\n\t\tt.Fatal(err)\n\n\t}\n\n\tselect {\n\n\tcase msg := <-ch:\n\n\t\tif msg != \"success\" {\n\n\t\t\tt.Fatalf(\"unexpected message %q\", msg)\n\n\t\t}\n\n\tcase <-time.After(time.Second):\n\n\t}\n\n\n\n\tif err = ntf.trigger(100, \"success\"); err == nil {\n\n\t\tt.Fatal(\"expected error for trigger\")\n\n\t}\n\n}\n", "file_path": "task-scheduler-go/notify_test.go", "rank": 65, "score": 26281.300673696318 }, { "content": "func newEchoManager() EchoManager {\n\n\treturn &echoManager{\n\n\t\tmu: sync.RWMutex{},\n\n\t}\n", "file_path": "task-scheduler-go/echo.go", "rank": 66, "score": 26238.417709283993 }, { "content": "\tstart()\n", "file_path": "task-scheduler-go/apply.go", "rank": 67, "score": 26219.96464959024 }, { "content": "\tapply(req *EchoRequest) (string, error)\n", "file_path": "task-scheduler-go/echo.go", "rank": 68, "score": 26219.96464959024 }, { "content": "\tstop() error\n", "file_path": "task-scheduler-go/apply.go", "rank": 69, "score": 26219.96464959024 }, { "content": "package main\n\n\n\nimport (\n\n\t\"errors\"\n\n\t\"fmt\"\n\n\t\"math/rand\"\n\n\t\"time\"\n\n)\n\n\n\ntype Request struct {\n\n\techoRequest *EchoRequest\n\n}\n\n\n\ntype Applier interface {\n\n\tstart()\n\n\tstop() error\n\n\tapply(req Request) (string, error)\n\n}\n\n\n\nfunc newApplier(requestTimeout time.Duration) Applier {\n\n\tmemberID := rand.Uint64()\n\n\treturn &applier{\n\n\t\trequestTimeout: requestTimeout,\n\n\n\n\t\trequestIDGenerator: newGenerator(memberID, time.Now().UnixNano()),\n\n\t\tnotifier: newNotifier(),\n\n\n\n\t\trequestCh: make(chan requestTuple, 1000),\n\n\t\tstopCh: make(chan struct{}),\n\n\t\tdoneCh: make(chan struct{}),\n\n\n\n\t\techoManager: newEchoManager(),\n\n\t}\n\n}\n\n\n\n// ref. https://github.com/etcd-io/etcd/blob/release-3.5/pkg/schedule\n\ntype applier struct {\n\n\trequestTimeout time.Duration\n\n\n\n\trequestIDGenerator Generator\n\n\tnotifier Notifier\n\n\n\n\t// for sending requests in the queue\n\n\trequestCh chan requestTuple\n\n\n\n\tstopCh chan struct{}\n\n\tdoneCh chan struct{}\n\n\n\n\techoManager EchoManager\n\n}\n\n\n\ntype requestTuple struct {\n\n\trequestID uint64\n\n\trequest Request\n\n}\n\n\n\nfunc (ap *applier) start() {\n\n\tgo func() {\n\n\t\tfmt.Println(\"starting applier async\")\n\n\t\tfor {\n\n\t\t\tselect {\n\n\t\t\tcase tup := <-ap.requestCh:\n\n\t\t\t\treqID := tup.requestID\n\n\t\t\t\treq := tup.request\n\n\t\t\t\tswitch {\n\n\t\t\t\tcase req.echoRequest != nil:\n\n\t\t\t\t\trs, err := ap.echoManager.apply(req.echoRequest)\n\n\t\t\t\t\tif err != nil {\n\n\t\t\t\t\t\trs = fmt.Sprintf(\"failed to apply %v\", err)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif err = ap.notifier.trigger(reqID, rs); err != nil {\n\n\t\t\t\t\t\tfmt.Printf(\"failed to trigger %v\", err)\n\n\t\t\t\t\t}\n\n\t\t\t\tdefault:\n\n\t\t\t\t}\n\n\t\t\tcase <-ap.stopCh:\n\n\t\t\t\tfmt.Println(\"received stop signal\")\n\n\t\t\t\tap.doneCh <- struct{}{}\n\n\t\t\t\tfmt.Println(\"signaled done\")\n\n\t\t\t\treturn\n\n\t\t\t}\n\n\t\t}\n\n\t}()\n\n}\n\n\n\nfunc (ap *applier) stop() error {\n\n\tfmt.Println(\"stopping applier\")\n\n\tselect {\n\n\tcase ap.stopCh <- struct{}{}:\n\n\tcase <-time.After(5 * time.Second):\n\n\t\treturn errors.New(\"took too long to signal stop\")\n\n\t}\n\n\tselect {\n\n\tcase <-ap.doneCh:\n\n\tcase <-time.After(5 * time.Second):\n\n\t\treturn errors.New(\"took too long to receive done\")\n\n\t}\n\n\tfmt.Println(\"stopped applier\")\n\n\treturn nil\n\n}\n\n\n\nfunc (ap *applier) apply(req Request) (string, error) {\n\n\treqID := ap.requestIDGenerator.next()\n\n\trespRx, err := ap.notifier.register(reqID)\n\n\tif err != nil {\n\n\t\treturn \"\", err\n\n\t}\n\n\n\n\tselect {\n\n\tcase ap.requestCh <- requestTuple{requestID: reqID, request: req}:\n\n\tcase <-time.After(ap.requestTimeout):\n\n\t\tif err = ap.notifier.trigger(reqID, fmt.Sprintf(\"failed to schedule %d in time\", reqID)); err != nil {\n\n\t\t\treturn \"\", err\n\n\t\t}\n\n\t}\n\n\n\n\tmsg := \"\"\n\n\tselect {\n\n\tcase msg = <-respRx:\n\n\tcase <-time.After(ap.requestTimeout):\n\n\t\treturn \"\", errors.New(\"apply timeout\")\n\n\t}\n\n\n\n\treturn msg, nil\n\n}\n", "file_path": "task-scheduler-go/apply.go", "rank": 70, "score": 26219.96464959024 }, { "content": "func parseEchoRequest(d []byte) (req EchoRequest, err error) {\n\n\terr = json.Unmarshal(d, &req)\n\n\treturn req, err\n", "file_path": "task-scheduler-go/echo.go", "rank": 71, "score": 25749.94086092035 }, { "content": "\tdoneCh chan struct{}\n", "file_path": "task-scheduler-go/apply.go", "rank": 72, "score": 25516.03409832967 }, { "content": "\techoManager EchoManager\n", "file_path": "task-scheduler-go/apply.go", "rank": 73, "score": 25516.03409832967 }, { "content": "\tstopCh chan struct{}\n", "file_path": "task-scheduler-go/apply.go", "rank": 74, "score": 25516.03409832967 }, { "content": "func (ea *echoManager) apply(req *EchoRequest) (string, error) {\n\n\tfmt.Println(\"applying echo request\")\n\n\tea.mu.Lock()\n\n\tdefer ea.mu.Unlock()\n\n\tswitch req.Kind {\n\n\tcase \"create\":\n\n\t\treturn fmt.Sprintf(\"SUCCESS create %q\", req.Message), nil\n\n\tcase \"delete\":\n\n\t\treturn fmt.Sprintf(\"SUCCESS delete %q\", req.Message), nil\n\n\tdefault:\n\n\t\treturn \"\", fmt.Errorf(\"unknown request %q\", req)\n\n\t}\n", "file_path": "task-scheduler-go/echo.go", "rank": 75, "score": 24849.524247934038 }, { "content": "func TestParseEchoRequest(t *testing.T) {\n\n\treq, err := parseEchoRequest([]byte(\"{\\\"kind\\\":\\\"create\\\",\\\"message\\\":\\\"hello\\\"}\"))\n\n\tif err != nil {\n\n\t\tt.Fatal(err)\n\n\t}\n\n\tif req.Kind != \"create\" {\n\n\t\tt.Fatalf(\"unexpected Kind %q\", req.Kind)\n\n\t}\n\n\tif req.Message != \"hello\" {\n\n\t\tt.Fatalf(\"unexpected Message %q\", req.Message)\n\n\t}\n", "file_path": "task-scheduler-go/echo_test.go", "rank": 76, "score": 24470.460511998783 }, { "content": "type handler struct {\n\n\tlistenerPort uint64\n\n\tapplier Applier\n", "file_path": "task-scheduler-go/server.go", "rank": 77, "score": 4627.820412334919 }, { "content": "package main\n\n\n\nimport (\n\n\t\"encoding/json\"\n\n\t\"fmt\"\n\n\t\"sync\"\n\n)\n\n\n\ntype EchoRequest struct {\n\n\tKind string `json:\"kind\"`\n\n\tMessage string `json:\"message,omitempty\"`\n\n}\n\n\n\nfunc parseEchoRequest(d []byte) (req EchoRequest, err error) {\n\n\terr = json.Unmarshal(d, &req)\n\n\treturn req, err\n\n}\n\n\n\ntype EchoManager interface {\n\n\tapply(req *EchoRequest) (string, error)\n\n}\n\n\n\nfunc newEchoManager() EchoManager {\n\n\treturn &echoManager{\n\n\t\tmu: sync.RWMutex{},\n\n\t}\n\n}\n\n\n\ntype echoManager struct {\n\n\tmu sync.RWMutex\n\n}\n\n\n\nfunc (ea *echoManager) apply(req *EchoRequest) (string, error) {\n\n\tfmt.Println(\"applying echo request\")\n\n\tea.mu.Lock()\n\n\tdefer ea.mu.Unlock()\n\n\tswitch req.Kind {\n\n\tcase \"create\":\n\n\t\treturn fmt.Sprintf(\"SUCCESS create %q\", req.Message), nil\n\n\tcase \"delete\":\n\n\t\treturn fmt.Sprintf(\"SUCCESS delete %q\", req.Message), nil\n\n\tdefault:\n\n\t\treturn \"\", fmt.Errorf(\"unknown request %q\", req)\n\n\t}\n\n}\n", "file_path": "task-scheduler-go/echo.go", "rank": 78, "score": 4627.820412334919 }, { "content": "\tprefix uint64\n", "file_path": "task-scheduler-go/id.go", "rank": 79, "score": 4627.820412334919 }, { "content": "package main\n\n\n\nimport (\n\n\t\"encoding/json\"\n\n\t\"fmt\"\n\n\t\"net/http\"\n\n\t\"os\"\n\n\t\"os/signal\"\n\n\t\"syscall\"\n\n\t\"time\"\n\n)\n\n\n\ntype Handler interface {\n\n\tstart()\n\n}\n\n\n\ntype handler struct {\n\n\tlistenerPort uint64\n\n\tapplier Applier\n\n}\n\n\n\nfunc newHandler(listenerPort uint64, requestTimeout time.Duration) Handler {\n\n\treturn &handler{\n\n\t\tlistenerPort: listenerPort,\n\n\t\tapplier: newApplier(requestTimeout),\n\n\t}\n\n}\n\n\n\nfunc (hd *handler) start() {\n\n\tfmt.Println(\"starting server\")\n\n\thd.applier.start()\n\n\n\n\t// start listener\n\n\tserverMux := http.NewServeMux()\n\n\tserverMux.HandleFunc(\"/echo\", hd.wrapFunc(handleRequest))\n\n\n\n\thttpServer := &http.Server{\n\n\t\tAddr: fmt.Sprintf(\":%d\", hd.listenerPort),\n\n\t\tHandler: serverMux,\n\n\t}\n\n\n\n\ttch := make(chan os.Signal, 1)\n\n\tsignal.Notify(tch, syscall.SIGINT)\n\n\tdone := make(chan struct{})\n\n\tgo func() {\n\n\t\tfmt.Println(\"received signal:\", <-tch)\n\n\t\thttpServer.Close()\n\n\t\tclose(done)\n\n\t}()\n\n\n\n\tfmt.Printf(\"Serving http://localhost:%d\\n\", hd.listenerPort)\n\n\tif err := httpServer.ListenAndServe(); err != nil {\n\n\t\tfmt.Printf(\"http server error: %v\\n\", err)\n\n\t}\n\n\tselect {\n\n\tcase <-done:\n\n\tdefault:\n\n\t}\n\n\n\n\tif err := hd.applier.stop(); err != nil {\n\n\t\tfmt.Printf(\"failed to stop applier %v\", err)\n\n\t\tpanic(err)\n\n\t}\n\n}\n\n\n\nfunc (hd *handler) wrapFunc(fn func(applier Applier, w http.ResponseWriter, req *http.Request)) func(w http.ResponseWriter, req *http.Request) {\n\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\n\t\tfn(hd.applier, w, req)\n\n\t}\n\n}\n\n\n\nfunc handleRequest(applier Applier, w http.ResponseWriter, req *http.Request) {\n\n\tswitch req.Method {\n\n\tcase \"POST\":\n\n\t\tvar echoRequest EchoRequest\n\n\t\terr := json.NewDecoder(req.Body).Decode(&echoRequest)\n\n\t\tif err != nil {\n\n\t\t\tfmt.Fprintf(w, \"failed to read request %v\", err)\n\n\t\t\treturn\n\n\t\t}\n\n\t\ts, err := applier.apply(Request{echoRequest: &echoRequest})\n\n\t\tif err != nil {\n\n\t\t\tfmt.Fprintf(w, \"failed to apply request %v\", err)\n\n\t\t\treturn\n\n\t\t}\n\n\t\tfmt.Fprint(w, s)\n\n\n\n\tdefault:\n\n\t\thttp.Error(w, \"Method Not Allowed\", 405)\n\n\t}\n\n}\n", "file_path": "task-scheduler-go/server.go", "rank": 80, "score": 4627.820412334919 }, { "content": "package main\n\n\n\nimport (\n\n\t\"math\"\n\n\t\"sync/atomic\"\n\n)\n\n\n\n// https://github.com/etcd-io/etcd/blob/release-3.5/pkg/idutil\n\ntype Generator interface {\n\n\tnext() uint64\n\n}\n\n\n\nfunc newGenerator(memberID uint64, unixNano int64) Generator {\n\n\t// to count the number of milliseconds\n\n\tunixMx := uint64(unixNano) / 1000000\n\n\n\n\tx := (math.MaxUint64 >> 24) & unixMx\n\n\tx = x << 8\n\n\n\n\treturn &generator{\n\n\t\tprefix: memberID << (8 * 6),\n\n\t\tsuffix: x,\n\n\t}\n\n}\n\n\n\ntype generator struct {\n\n\tprefix uint64\n\n\tsuffix uint64\n\n}\n\n\n\nfunc (gen *generator) next() uint64 {\n\n\tsuffix := atomic.SwapUint64(&gen.suffix, gen.suffix+1)\n\n\tid := gen.prefix | (suffix & (math.MaxUint64 >> 16))\n\n\treturn id\n\n}\n", "file_path": "task-scheduler-go/id.go", "rank": 81, "score": 4627.820412334919 }, { "content": "\tstart()\n", "file_path": "task-scheduler-go/server.go", "rank": 82, "score": 4627.820412334919 }, { "content": "type Handler interface {\n\n\tstart()\n", "file_path": "task-scheduler-go/server.go", "rank": 83, "score": 4627.820412334919 }, { "content": "type generator struct {\n\n\tprefix uint64\n\n\tsuffix uint64\n", "file_path": "task-scheduler-go/id.go", "rank": 84, "score": 4627.820412334919 }, { "content": "\tnext() uint64\n", "file_path": "task-scheduler-go/id.go", "rank": 85, "score": 4627.820412334919 }, { "content": "func main() {\n\n\tlistenerPort := flag.Uint64(\"listener-port\", 3000, \"listener port\")\n\n\trequestTimeoutSeconds := flag.Uint64(\"request-timeout-seconds\", 5, \"request timeout in seconds\")\n\n\n\n\tsrv := newHandler(*listenerPort, time.Duration(*requestTimeoutSeconds)*time.Second)\n\n\tsrv.start()\n", "file_path": "task-scheduler-go/main.go", "rank": 86, "score": 4627.820412334919 }, { "content": "type Generator interface {\n\n\tnext() uint64\n", "file_path": "task-scheduler-go/id.go", "rank": 87, "score": 4627.820412334919 }, { "content": "\tMessage string `json:\"message,omitempty\"`\n", "file_path": "task-scheduler-go/echo.go", "rank": 88, "score": 4627.820412334919 }, { "content": "\tmu sync.RWMutex\n", "file_path": "task-scheduler-go/echo.go", "rank": 89, "score": 4627.820412334919 }, { "content": "\tsuffix uint64\n", "file_path": "task-scheduler-go/id.go", "rank": 90, "score": 4627.820412334919 }, { "content": "\tKind string `json:\"kind\"`\n", "file_path": "task-scheduler-go/echo.go", "rank": 91, "score": 4627.820412334919 }, { "content": "func (gen *generator) next() uint64 {\n\n\tsuffix := atomic.SwapUint64(&gen.suffix, gen.suffix+1)\n\n\tid := gen.prefix | (suffix & (math.MaxUint64 >> 16))\n\n\treturn id\n", "file_path": "task-scheduler-go/id.go", "rank": 92, "score": 4539.002904622528 }, { "content": "func (hd *handler) start() {\n\n\tfmt.Println(\"starting server\")\n\n\thd.applier.start()\n\n\n\n\t// start listener\n\n\tserverMux := http.NewServeMux()\n\n\tserverMux.HandleFunc(\"/echo\", hd.wrapFunc(handleRequest))\n\n\n\n\thttpServer := &http.Server{\n\n\t\tAddr: fmt.Sprintf(\":%d\", hd.listenerPort),\n\n\t\tHandler: serverMux,\n\n\t}\n\n\n\n\ttch := make(chan os.Signal, 1)\n\n\tsignal.Notify(tch, syscall.SIGINT)\n\n\tdone := make(chan struct{})\n\n\tgo func() {\n\n\t\tfmt.Println(\"received signal:\", <-tch)\n\n\t\thttpServer.Close()\n\n\t\tclose(done)\n\n\t}()\n\n\n\n\tfmt.Printf(\"Serving http://localhost:%d\\n\", hd.listenerPort)\n\n\tif err := httpServer.ListenAndServe(); err != nil {\n\n\t\tfmt.Printf(\"http server error: %v\\n\", err)\n\n\t}\n\n\tselect {\n\n\tcase <-done:\n\n\tdefault:\n\n\t}\n\n\n\n\tif err := hd.applier.stop(); err != nil {\n\n\t\tfmt.Printf(\"failed to stop applier %v\", err)\n\n\t\tpanic(err)\n\n\t}\n", "file_path": "task-scheduler-go/server.go", "rank": 93, "score": 4539.002904622528 }, { "content": "package main\n\n\n\nimport \"testing\"\n\n\n\nfunc TestParseEchoRequest(t *testing.T) {\n\n\treq, err := parseEchoRequest([]byte(\"{\\\"kind\\\":\\\"create\\\",\\\"message\\\":\\\"hello\\\"}\"))\n\n\tif err != nil {\n\n\t\tt.Fatal(err)\n\n\t}\n\n\tif req.Kind != \"create\" {\n\n\t\tt.Fatalf(\"unexpected Kind %q\", req.Kind)\n\n\t}\n\n\tif req.Message != \"hello\" {\n\n\t\tt.Fatalf(\"unexpected Message %q\", req.Message)\n\n\t}\n\n}\n", "file_path": "task-scheduler-go/echo_test.go", "rank": 94, "score": 4539.002904622528 }, { "content": "type EchoManager interface {\n\n\tapply(req *EchoRequest) (string, error)\n", "file_path": "task-scheduler-go/echo.go", "rank": 95, "score": 4539.002904622528 }, { "content": "type echoManager struct {\n\n\tmu sync.RWMutex\n", "file_path": "task-scheduler-go/echo.go", "rank": 96, "score": 4539.002904622528 }, { "content": "package main\n\n\n\nimport (\n\n\t\"fmt\"\n\n\t\"testing\"\n\n\t\"time\"\n\n)\n\n\n\nfunc TestGenerator(t *testing.T) {\n\n\tgen := newGenerator(1, time.Now().UnixNano())\n\n\tfmt.Println(gen.next())\n\n\tfmt.Println(gen.next())\n\n}\n\n\n\nfunc TestGeneratorNext(t *testing.T) {\n\n\tdur := time.Duration(0x3456) * time.Millisecond\n\n\tgen := newGenerator(0x12, dur.Nanoseconds())\n\n\tid := gen.next()\n\n\tif id != 0x12000000345600 {\n\n\t\tt.Fatalf(\"unexpected id %x\", id)\n\n\t}\n\n\tfor i := 0; i < 1000; i++ {\n\n\t\tid2 := gen.next()\n\n\t\tif id2 != id+uint64(i)+1 {\n\n\t\t\tt.Fatalf(\"#%d: unexpected id %x\", i, id2)\n\n\t\t}\n\n\t}\n\n}\n\n\n\nfunc TestGeneratorUnique(t *testing.T) {\n\n\tdur := time.Duration(100) * time.Millisecond\n\n\tgen0 := newGenerator(0, dur.Nanoseconds())\n\n\tid0 := gen0.next()\n\n\n\n\tgen1 := newGenerator(1, dur.Nanoseconds())\n\n\tid1 := gen1.next()\n\n\n\n\tif id0 == id1 {\n\n\t\tt.Fatalf(\"unexpected %x == %x\", id0, id1)\n\n\t}\n\n\n\n\tdur = time.Duration(101) * time.Millisecond\n\n\tgen2 := newGenerator(0, dur.Nanoseconds())\n\n\tid2 := gen2.next()\n\n\tif id0 == id2 {\n\n\t\tt.Fatalf(\"unexpected %x == %x\", id0, id2)\n\n\t}\n\n}\n", "file_path": "task-scheduler-go/id_test.go", "rank": 97, "score": 4539.002904622528 }, { "content": "\tlistenerPort uint64\n", "file_path": "task-scheduler-go/server.go", "rank": 98, "score": 4539.002904622528 }, { "content": "\n\n# Task scheduler implementation in Go and Rust\n\n\n\nFeature requirements are:\n\n\n\n1. A client sends a task request via HTTP endpoint, and such requests can be multiple and sent with concurrency.\n\n2. The server generates a task ID for each request.\n\n3. The server serialize requests into an apply wait queue with the task ID.\n\n4. The applier receives the requested task from the queue.\n\n5. The applier applies the task, and trigger complete event to notify the server.\n\n6. The server responds to the client request via HTTP.\n\n\n\nThis is basically how [etcd](https://github.com/etcd-io/etcd) server works.\n\n\n\nSee https://github.com/rust-lang/wg-async-foundations/pull/209 for more discussions.\n\n\n\nSee https://github.com/gyuho/task-scheduler-examples/pull/1 for clean-up changes.\n\n\n", "file_path": "README.md", "rank": 99, "score": 9.104492281438867 } ]
Rust
src/discord_client/serenity_discord_client.rs
Hammatt/tougou_bot
47f0457f66ef3815791d2d47e0eb503c7a72f996
use crate::discord_client::{CommandHandler, DiscordClient}; use log; use serenity::{ client, model::{channel::Message, gateway::Ready}, prelude::*, }; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread; type BoxedThreadsafeCommandHandler = Box<Arc<Mutex<CommandHandler + Send>>>; pub struct SerenityDiscordClient { command_callbacks: Arc<Mutex<HashMap<String, BoxedThreadsafeCommandHandler>>>, } struct SerenityDiscordHandler { command_callbacks: Arc<Mutex<HashMap<String, BoxedThreadsafeCommandHandler>>>, command_prefix: &'static str, } impl DiscordClient for SerenityDiscordClient { fn new(token: &str) -> Self { log::info!("valid token: {}", client::validate_token(token).is_ok()); let command_callbacks = Arc::new(Mutex::new(HashMap::new())); let serenity_handler = SerenityDiscordHandler { command_callbacks: command_callbacks.clone(), command_prefix: "!", }; let serenity_client = Arc::new(Mutex::new( Client::new(token, serenity_handler).expect("Error creating serenity client"), )); log::info!("created client"); let thread_serenity_client = serenity_client.clone(); thread::spawn(move || { if let Err(why) = thread_serenity_client.lock().unwrap().start() { log::error!("An error occurred while running the client: {:?}", why); } }); log::info!("started connection"); SerenityDiscordClient { command_callbacks: command_callbacks.clone(), } } fn register_command<T>( &self, command: &str, command_handler: Arc<Mutex<T>>, ) -> Result<(), Box<std::error::Error>> where T: CommandHandler + Send + 'static, { if self .command_callbacks .lock() .unwrap() .insert(command.to_string(), Box::new(command_handler)) .is_some() { panic!("command was entered twice for {}", command); } Ok(()) } } impl SerenityDiscordHandler { fn get_command_name(&self, full_command: &str) -> Option<String> { let mut result: Option<String> = None; if full_command.starts_with(self.command_prefix) { if let Some(command_with_prefix) = full_command.split_whitespace().nth(0) { if let Some(command) = command_with_prefix .chars() .next() .map(|c| &command_with_prefix[c.len_utf8()..]) { result = Some(command.to_string()); } } } result } } impl EventHandler for SerenityDiscordHandler { fn message(&self, ctx: Context, msg: Message) { if let Some(command) = self.get_command_name(&msg.content) { if let Some(command_handler) = self.command_callbacks.lock().unwrap().get(&command) { if let Err(err) = command_handler.lock().unwrap().process_command( &msg.content, msg.guild_id.unwrap().0, &|output| { if let Err(err) = msg.channel_id.say(&ctx.http, output) { log::error!("Error sending message: {:?}", err); } }, ) { log::error!("Error processing command: {:?}", err); } }; }; } fn ready(&self, _: Context, ready: Ready) { log::info!("{} is connected!", ready.user.name); } } #[cfg(test)] mod tests { use super::*; #[test] fn test_get_command_name() { let command_callbacks = Arc::new(Mutex::new(HashMap::new())); let handler = SerenityDiscordHandler { command_callbacks: command_callbacks.clone(), command_prefix: "!", }; assert_eq!( Some(String::from("ping")), handler.get_command_name("!ping") ); assert_eq!(Some(String::from("pic")), handler.get_command_name("!pic")); assert_eq!( Some(String::from("pic")), handler.get_command_name("!pic tag1 tag2 tag3") ); assert_eq!( Some(String::from("pic")), handler.get_command_name("!pic ももよ まじこい") ); assert_eq!( Some(String::from("辞書")), handler.get_command_name("!辞書") ); assert_eq!( Some(String::from("辞書")), handler.get_command_name("!辞書 勉強") ); } }
use crate::discord_client::{CommandHandler, DiscordClient}; use log; use serenity::{ client, model::{channel::Message, gateway::Ready}, prelude::*, }; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread; type BoxedThreadsafeCommandHandler = Box<Arc<Mutex<CommandHandler + Send>>>; pub struct SerenityDiscordClient { command_callbacks: Arc<Mutex<HashMap<String, BoxedThreadsafeCommandHandler>>>, } struct SerenityDiscordHandler { command_callbacks: Arc<Mutex<HashMap<String, BoxedThreadsafeCommandHandler>>>, command_prefix: &'static str, } impl DiscordClient for SerenityDiscordClient { fn new(token: &str) -> Self { log::info!("valid token: {}", client::validate_token(token).is_ok()); let command_callbacks = Arc::new(Mutex::new(HashMap::new())); let serenity_handler = SerenityDiscordHandler { command_callbacks: command_callbacks.clone(), command_prefix: "!", }; let serenity_client = Arc::new(Mutex::new( Client::new(token, serenity_handler).expect("Error creating serenity client"), )); log::info!("created client"); let thread_serenity_client = serenity_client.clone(); thread::spawn(move || { if let Err(why) = thread_serenity_client.lock().unwrap().start() { log::error!("An error occurred while running the client: {:?}", why); } }); log::info!("started connection"); SerenityDiscordClient { command_callbacks: command_callbacks.clone(), } } fn register_command<T>( &self, command: &str, command_handler: Arc<Mutex<T>>, ) -> Result<(), Box<std::error::Error>> where T: CommandHandler + Send + 'static, { if self .command_callbacks .lock() .unwrap() .insert(command.to_string(), Box::new(command_handler)) .is_some() { panic!("command was entered twice for {}", command); } Ok(()) } } impl SerenityDiscordHandler { fn get_command_name(&self, full_command: &str) -> Option<String> { let mut result: Option<String> = None; if full_command.starts_with(self.command_prefix) { if let Some(command_with_prefix) = full_command.split_whitespace().nth(0) { if let Some(command) = command_with_prefix .chars() .next() .map(|c| &command_with_prefix[c.len_utf
} impl EventHandler for SerenityDiscordHandler { fn message(&self, ctx: Context, msg: Message) { if let Some(command) = self.get_command_name(&msg.content) { if let Some(command_handler) = self.command_callbacks.lock().unwrap().get(&command) { if let Err(err) = command_handler.lock().unwrap().process_command( &msg.content, msg.guild_id.unwrap().0, &|output| { if let Err(err) = msg.channel_id.say(&ctx.http, output) { log::error!("Error sending message: {:?}", err); } }, ) { log::error!("Error processing command: {:?}", err); } }; }; } fn ready(&self, _: Context, ready: Ready) { log::info!("{} is connected!", ready.user.name); } } #[cfg(test)] mod tests { use super::*; #[test] fn test_get_command_name() { let command_callbacks = Arc::new(Mutex::new(HashMap::new())); let handler = SerenityDiscordHandler { command_callbacks: command_callbacks.clone(), command_prefix: "!", }; assert_eq!( Some(String::from("ping")), handler.get_command_name("!ping") ); assert_eq!(Some(String::from("pic")), handler.get_command_name("!pic")); assert_eq!( Some(String::from("pic")), handler.get_command_name("!pic tag1 tag2 tag3") ); assert_eq!( Some(String::from("pic")), handler.get_command_name("!pic ももよ まじこい") ); assert_eq!( Some(String::from("辞書")), handler.get_command_name("!辞書") ); assert_eq!( Some(String::from("辞書")), handler.get_command_name("!辞書 勉強") ); } }
8()..]) { result = Some(command.to_string()); } } } result }
function_block-function_prefixed
[ { "content": "fn parse_command(command: &str) -> Vec<&str> {\n\n command.split_ascii_whitespace().skip(1).collect()\n\n}\n\n\n\nimpl JishoCommand {\n\n pub fn new(jisho_repository: Box<JishoRepository + Send>) -> JishoCommand {\n\n JishoCommand { jisho_repository }\n\n }\n\n}\n\n\n\nimpl CommandHandler for JishoCommand {\n\n fn process_command(\n\n &self,\n\n command: &str,\n\n _tennant_id: u64,\n\n send_message_callback: &Fn(&str) -> (),\n\n ) -> Result<(), Box<std::error::Error>> {\n\n let query = parse_command(command);\n\n\n\n match self.jisho_repository.get_definition(query) {\n", "file_path": "src/commands/jisho.rs", "rank": 1, "score": 120040.68765355085 }, { "content": "fn parse_command(command: &str) -> Vec<&str> {\n\n command.split_ascii_whitespace().skip(1).collect()\n\n}\n\n\n\nimpl VNDBCommand {\n\n pub fn new(vndb_repository: Box<VNDBRepository + Send>) -> VNDBCommand {\n\n VNDBCommand { vndb_repository }\n\n }\n\n}\n\n\n\nimpl CommandHandler for VNDBCommand {\n\n fn process_command(\n\n &self,\n\n command: &str,\n\n _tennant_id: u64,\n\n send_message_callback: &Fn(&str) -> (),\n\n ) -> Result<(), Box<std::error::Error>> {\n\n let query = parse_command(command);\n\n\n\n match self.vndb_repository.get_visual_novel(query) {\n", "file_path": "src/commands/vndb.rs", "rank": 2, "score": 120040.68765355085 }, { "content": "fn parse_tag_command(command: &str) -> Option<&str> {\n\n command.split_whitespace().nth(1)\n\n}\n\n\n\nimpl TagCommand {\n\n pub fn new(\n\n tag_repository: Box<TagRepository + Send>,\n\n ) -> Result<TagCommand, Box<std::error::Error>> {\n\n Ok(TagCommand {\n\n tag_repository: Mutex::new(tag_repository),\n\n })\n\n }\n\n}\n\n\n\nimpl CommandHandler for TagCommand {\n\n fn process_command(\n\n &self,\n\n command: &str,\n\n tennant_id: u64,\n\n send_message_callback: &Fn(&str) -> (),\n", "file_path": "src/commands/tag.rs", "rank": 3, "score": 118246.98810106685 }, { "content": "fn get_search_parameters(command: &str) -> Vec<&str> {\n\n let mut result: Vec<&str> = Vec::new();\n\n\n\n let paramaters: Vec<&str> = command.split_whitespace().collect();\n\n for word in paramaters.iter().skip(1) {\n\n result.push(word);\n\n }\n\n\n\n result\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_get_search_parameters() {\n\n let empty_vec: Vec<&str> = Vec::new();\n\n assert_eq!(empty_vec, get_search_parameters(\"pic\"));\n\n assert_eq!(\n\n vec![\"tag1\", \"tag2\", \"tag3\"],\n\n get_search_parameters(\"pic tag1 tag2 tag3\")\n\n );\n\n assert_eq!(\n\n vec![\"一番\", \"に\", \"サン\"],\n\n get_search_parameters(\"pic 一番 に サン\")\n\n );\n\n }\n\n}\n", "file_path": "src/commands/pic.rs", "rank": 4, "score": 114685.05142532036 }, { "content": "fn get_recomended_link(body: &str) -> Result<String, Box<std::error::Error>> {\n\n let dom = html5ever::parse_document(\n\n html5ever::rcdom::RcDom::default(),\n\n html5ever::ParseOpts {\n\n tree_builder: html5ever::tree_builder::TreeBuilderOpts {\n\n drop_doctype: true,\n\n ..Default::default()\n\n },\n\n ..Default::default()\n\n },\n\n )\n\n .from_utf8()\n\n .read_from(&mut body.as_bytes())?;\n\n\n\n let result = find_top_table_result(&dom.document).ok_or_else(|| {\n\n VNDBOrgRepositoryError::new(String::from(\"unable to find table on vndb result page\"))\n\n })?;\n\n\n\n Ok(result)\n\n}\n", "file_path": "src/data_access/vndb_repository/vndb_org_repository.rs", "rank": 5, "score": 114216.86523644393 }, { "content": "fn parse_ntag(command: &str) -> Option<Tag> {\n\n let mut result: Option<Tag> = None;\n\n\n\n let mut broken_down_command = command.split_whitespace().skip(1);\n\n let name = broken_down_command.next();\n\n let body: Vec<&str> = broken_down_command.collect();\n\n let body: String = body.join(\" \");\n\n let body: Option<String> = if body.is_empty() { None } else { Some(body) };\n\n\n\n if let Some(name) = name {\n\n if let Some(body) = body {\n\n result = Some(Tag {\n\n name: String::from(name),\n\n body,\n\n });\n\n }\n\n }\n\n\n\n result\n\n}\n\n\n", "file_path": "src/commands/tag.rs", "rank": 6, "score": 104384.35961206947 }, { "content": "pub trait CommandHandler {\n\n fn process_command(\n\n &self,\n\n command: &str,\n\n tennant_id: u64,\n\n send_message_callback: &Fn(&str) -> (),\n\n ) -> Result<(), Box<std::error::Error>>;\n\n}\n", "file_path": "src/discord_client/mod.rs", "rank": 8, "score": 82280.07018514391 }, { "content": "pub trait DiscordClient {\n\n fn new(token: &str) -> Self;\n\n\n\n fn register_command<T>(\n\n &self,\n\n command: &str,\n\n command_handler: Arc<Mutex<T>>,\n\n ) -> Result<(), Box<std::error::Error>>\n\n where\n\n T: CommandHandler + Send + 'static;\n\n}\n\n\n", "file_path": "src/discord_client/mod.rs", "rank": 9, "score": 68022.72937430574 }, { "content": "fn format_search_parameters(parameters: &[&str]) -> String {\n\n parameters.join(\"+\")\n\n}\n\n\n\nimpl DanbooruPicRepository {\n\n pub fn default() -> DanbooruPicRepository {\n\n DanbooruPicRepository\n\n }\n\n}\n\n\n\nimpl PicRepository for DanbooruPicRepository {\n\n fn get_random_picture(&self, query: &[&str]) -> Result<Pic, Box<std::error::Error>> {\n\n if query.len() > 2 {\n\n Err(Box::new(DanbooruPicRepositoryError::new(\n\n \"Too many args. danbooru supports up to 2 query parameters to be provided\"\n\n .to_string(),\n\n )))\n\n } else {\n\n let parameters = format_search_parameters(query);\n\n let request_uri: String = format!(\n", "file_path": "src/data_access/pic_repository/danbooru_pic_repository.rs", "rank": 10, "score": 60943.21591938846 }, { "content": "fn format_search_parameters(parameters: Vec<&str>) -> String {\n\n parameters.join(\"+\")\n\n}\n\n\n", "file_path": "src/data_access/vndb_repository/vndb_org_repository.rs", "rank": 11, "score": 57991.91115706472 }, { "content": "fn format_search_parameters(parameters: Vec<&str>) -> String {\n\n parameters.join(\"%20\")\n\n}\n\n\n\nimpl JishoRepository for JishoOrgRepository {\n\n fn get_definition(&self, query: Vec<&str>) -> Result<JishoDefinition, Box<std::error::Error>> {\n\n let parameters = format_search_parameters(query);\n\n let request_uri = format!(\n\n \"https://jisho.org/api/v1/search/words?keyword={}\",\n\n parameters\n\n );\n\n\n\n let response_body: String = reqwest::get(&request_uri)?.text()?;\n\n\n\n let response_models: JishoOrgApiResponse = serde_json::from_str(&response_body)?;\n\n\n\n let first_response_model_data = response_models.data.first().ok_or_else(|| {\n\n JishoOrgRepositoryError::new(String::from(\"Got no item in response from jisho api\"))\n\n })?;\n\n\n", "file_path": "src/data_access/jisho_repository/jisho_org_repository.rs", "rank": 12, "score": 57991.91115706472 }, { "content": "#[derive(Debug)]\n\nstruct VNDBOrgRepositoryError {\n\n description: String,\n\n}\n\n\n", "file_path": "src/data_access/vndb_repository/vndb_org_repository.rs", "rank": 13, "score": 56266.53726208926 }, { "content": "#[derive(Debug)]\n\nstruct JishoOrgRepositoryError {\n\n description: String,\n\n}\n\n\n\nimpl JishoOrgRepository {\n\n pub fn default() -> JishoOrgRepository {\n\n JishoOrgRepository\n\n }\n\n}\n\n\n", "file_path": "src/data_access/jisho_repository/jisho_org_repository.rs", "rank": 14, "score": 56266.53726208926 }, { "content": "fn find_top_table_result(node: &Handle) -> Option<String> {\n\n if let NodeData::Element {\n\n ref name,\n\n ref attrs,\n\n ..\n\n } = node.data\n\n {\n\n if &name.local == \"table\" {\n\n for attribute in attrs.borrow().iter() {\n\n if (&attribute.name.local == \"class\")\n\n && (attribute.value == html5ever::tendril::Tendril::from(\"stripe\"))\n\n {\n\n let tbody_index = 1;\n\n let node_children = node.children.borrow();\n\n let tbody = node_children.get(tbody_index)?;\n\n let tbody_children = tbody.children.borrow();\n\n let first_row = &tbody_children.first()?;\n\n let first_row_children = first_row.children.borrow();\n\n let first_column = first_row_children.first()?;\n\n let first_column_children = first_column.children.borrow();\n", "file_path": "src/data_access/vndb_repository/vndb_org_repository.rs", "rank": 22, "score": 45428.090148117386 }, { "content": "fn main() {\n\n env_logger::init();\n\n info!(\"starting init...\");\n\n\n\n let token: String =\n\n env::var(\"DISCORD_TOKEN\").expect(\"Must set the environment variable `DISCORD_TOKEN`\");\n\n\n\n let client = serenity_discord_client::SerenityDiscordClient::new(&token);\n\n\n\n let danbooru_pic_repository =\n\n Box::new(pic_repository::danbooru_pic_repository::DanbooruPicRepository::default());\n\n\n\n let pic_command = Arc::new(Mutex::new(PicCommand::new(danbooru_pic_repository)));\n\n client.register_command(\"pic\", pic_command).unwrap();\n\n\n\n client\n\n .register_command(\"ping\", Arc::new(Mutex::new(PingCommand)))\n\n .unwrap();\n\n\n\n client\n", "file_path": "src/main.rs", "rank": 23, "score": 42494.03564899549 }, { "content": "#[derive(Deserialize)]\n\nstruct Japanese {\n\n word: Option<String>,\n\n reading: String,\n\n}\n\n\n", "file_path": "src/data_access/jisho_repository/jisho_org_repository.rs", "rank": 24, "score": 38887.92530705319 }, { "content": "#[derive(Deserialize)]\n\nstruct Data {\n\n japanese: Vec<Japanese>,\n\n senses: Vec<Senses>,\n\n}\n\n\n", "file_path": "src/data_access/jisho_repository/jisho_org_repository.rs", "rank": 25, "score": 38887.92530705319 }, { "content": "#[derive(Deserialize)]\n\nstruct Senses {\n\n english_definitions: Vec<String>,\n\n parts_of_speech: Vec<String>,\n\n}\n\n\n\npub struct JishoOrgRepository;\n\n\n", "file_path": "src/data_access/jisho_repository/jisho_org_repository.rs", "rank": 26, "score": 38887.92530705319 }, { "content": "pub trait VNDBRepository {\n\n fn get_visual_novel(&self, query: Vec<&str>) -> Result<VNDBResult, Box<std::error::Error>>;\n\n}\n\n\n\npub mod vndb_org_repository;\n", "file_path": "src/data_access/vndb_repository/mod.rs", "rank": 27, "score": 37415.58311948014 }, { "content": "pub trait PicRepository {\n\n fn get_random_picture(&self, query: &[&str]) -> Result<Pic, Box<std::error::Error>>;\n\n}\n\n\n\npub mod danbooru_pic_repository;\n", "file_path": "src/data_access/pic_repository/mod.rs", "rank": 28, "score": 37415.58311948014 }, { "content": "pub trait TagRepository {\n\n fn create_tag(\n\n &self,\n\n tag_name: &str,\n\n tag_body: &str,\n\n tennant_id: u64,\n\n ) -> Result<(), Box<std::error::Error>>;\n\n fn read_tag(&self, tag_name: &str, tennant_id: u64) -> Result<String, Box<std::error::Error>>;\n\n fn read_all_tags(&self, tennant_id: u64) -> Result<Vec<Tag>, Box<std::error::Error>>;\n\n}\n\n\n\npub mod sqlite_tag_repository;\n", "file_path": "src/data_access/tag_repository/mod.rs", "rank": 29, "score": 37415.58311948014 }, { "content": "pub trait JishoRepository {\n\n fn get_definition(&self, query: Vec<&str>) -> Result<JishoDefinition, Box<std::error::Error>>;\n\n}\n\n\n\npub mod jisho_org_repository;\n", "file_path": "src/data_access/jisho_repository/mod.rs", "rank": 30, "score": 37415.58311948014 }, { "content": "#[derive(Deserialize)]\n\nstruct JishoOrgApiResponse {\n\n data: Vec<Data>,\n\n}\n\n\n", "file_path": "src/data_access/jisho_repository/jisho_org_repository.rs", "rank": 31, "score": 36972.19539738632 }, { "content": "pub enum VNDBResult {\n\n Single(String),\n\n MostLikelyAndMore(String, String),\n\n None,\n\n}\n", "file_path": "src/models/vndb_result.rs", "rank": 32, "score": 25513.072399122462 }, { "content": "use crate::discord_client::CommandHandler;\n\n\n\npub struct PingCommand;\n\n\n\nimpl CommandHandler for PingCommand {\n\n fn process_command(\n\n &self,\n\n _command: &str,\n\n _tennant_id: u64,\n\n send_message_callback: &Fn(&str) -> (),\n\n ) -> Result<(), Box<std::error::Error>> {\n\n send_message_callback(\"Pong!\");\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n", "file_path": "src/commands/ping.rs", "rank": 33, "score": 24811.319209464462 }, { "content": "use crate::discord_client::CommandHandler;\n\n\n\nconst VERSION: &str = env!(\"CARGO_PKG_VERSION\");\n\n\n\npub struct StatusCommand;\n\n\n\nimpl StatusCommand {\n\n fn status(&self) -> String {\n\n format!(\"Version: {}\", VERSION)\n\n }\n\n}\n\n\n\nimpl CommandHandler for StatusCommand {\n\n fn process_command(\n\n &self,\n\n _command: &str,\n\n _tennant_id: u64,\n\n send_message_callback: &Fn(&str) -> (),\n\n ) -> Result<(), Box<std::error::Error>> {\n\n send_message_callback(&self.status());\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/commands/status.rs", "rank": 34, "score": 24810.43121511028 }, { "content": "use crate::data_access::pic_repository::PicRepository;\n\nuse crate::discord_client::CommandHandler;\n\n\n\npub struct PicCommand {\n\n pic_repository: Box<PicRepository + Send>,\n\n}\n\n\n\nimpl PicCommand {\n\n pub fn new(pic_repository: Box<PicRepository + Send>) -> PicCommand {\n\n PicCommand { pic_repository }\n\n }\n\n}\n\n\n\nimpl CommandHandler for PicCommand {\n\n fn process_command(\n\n &self,\n\n command: &str,\n\n _tennant_id: u64,\n\n send_message_callback: &Fn(&str) -> (),\n\n ) -> Result<(), Box<std::error::Error>> {\n", "file_path": "src/commands/pic.rs", "rank": 35, "score": 24808.930299414442 }, { "content": " ) -> Result<(), Box<std::error::Error>> {\n\n if command.starts_with(\"!ntag\") {\n\n match parse_ntag(command) {\n\n Some(new_tag) => {\n\n match self.tag_repository.lock().unwrap().create_tag(\n\n &new_tag.name,\n\n &new_tag.body,\n\n tennant_id,\n\n ) {\n\n Ok(()) => {\n\n send_message_callback(&format!(\n\n \"新しいタッグ「{}」➡「{}」を作った。\",\n\n &new_tag.name, &new_tag.body\n\n ));\n\n }\n\n Err(error) => {\n\n send_message_callback(\n\n \"エラーが発生しました。そのタッグもう知っている。\",\n\n );\n\n return Err(error);\n", "file_path": "src/commands/tag.rs", "rank": 36, "score": 24804.962239692486 }, { "content": "pub mod serenity_discord_client;\n\n\n\nuse std::sync::{Arc, Mutex};\n\n\n", "file_path": "src/discord_client/mod.rs", "rank": 37, "score": 24804.855630583836 }, { "content": " }\n\n }\n\n }\n\n None => send_message_callback(\"シンタックスエラーが発生しました\"),\n\n }\n\n } else if command.starts_with(\"!atags\") {\n\n let tags: Vec<Tag> = match self\n\n .tag_repository\n\n .lock()\n\n .unwrap()\n\n .read_all_tags(tennant_id)\n\n {\n\n Ok(tags) => tags,\n\n Err(error) => {\n\n send_message_callback(\"タッグが見つかりません。\");\n\n return Err(error);\n\n }\n\n };\n\n\n\n if tags.is_empty() {\n", "file_path": "src/commands/tag.rs", "rank": 38, "score": 24804.64225979306 }, { "content": " use std::sync::{Arc, Mutex};\n\n use std::thread;\n\n use std::time::{Duration, Instant};\n\n\n\n #[test]\n\n fn test_ping() {\n\n let ping = PingCommand;\n\n\n\n let result = Arc::new(Mutex::new(Box::new(String::new())));\n\n let closure_result = result.clone();\n\n assert!(ping\n\n .process_command(\"\", 0, &|message| *closure_result.lock().unwrap() =\n\n Box::new(String::from(message)))\n\n .is_ok());\n\n\n\n let expected_message = String::from(\"Pong!\");\n\n let timeout = Instant::now();\n\n while (timeout.elapsed() < Duration::from_secs(2))\n\n && (**result.lock().unwrap() != expected_message)\n\n {\n\n thread::sleep(Duration::from_millis(200));\n\n }\n\n\n\n assert_eq!(expected_message, **result.lock().unwrap());\n\n }\n\n}\n", "file_path": "src/commands/ping.rs", "rank": 39, "score": 24804.636627556338 }, { "content": "use crate::data_access::tag_repository::TagRepository;\n\nuse crate::discord_client::CommandHandler;\n\nuse crate::models::tag::Tag;\n\nuse std::sync::Mutex;\n\n\n\npub struct TagCommand {\n\n tag_repository: Mutex<Box<TagRepository + Send>>,\n\n}\n\n\n", "file_path": "src/commands/tag.rs", "rank": 40, "score": 24803.904610457124 }, { "content": "use crate::data_access::vndb_repository::VNDBRepository;\n\nuse crate::discord_client::CommandHandler;\n\nuse crate::models::vndb_result::VNDBResult;\n\n\n\npub struct VNDBCommand {\n\n vndb_repository: Box<VNDBRepository + Send>,\n\n}\n\n\n", "file_path": "src/commands/vndb.rs", "rank": 41, "score": 24803.865003242852 }, { "content": " {\n\n Ok(body) => {\n\n send_message_callback(&body);\n\n }\n\n Err(error) => {\n\n send_message_callback(\"そのタッグがいない\");\n\n return Err(error);\n\n }\n\n },\n\n None => send_message_callback(\"シンタックスエラーが発生しました\"),\n\n }\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n", "file_path": "src/commands/tag.rs", "rank": 42, "score": 24803.186449083 }, { "content": " Ok(result) => {\n\n match result {\n\n VNDBResult::Single(uri) => {\n\n send_message_callback(&uri);\n\n }\n\n VNDBResult::MostLikelyAndMore(suggested_uri, more_results) => {\n\n send_message_callback(&format!(\n\n \"{}\\n続き:<{}>\",\n\n suggested_uri, more_results\n\n ));\n\n }\n\n VNDBResult::None => {\n\n send_message_callback(\"ゲームを取得できない\");\n\n }\n\n }\n\n\n\n Ok(())\n\n }\n\n Err(error) => {\n\n send_message_callback(\"ゲームを取得できない\");\n\n Err(error)\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/commands/vndb.rs", "rank": 43, "score": 24802.994665269653 }, { "content": " let parameters = get_search_parameters(command);\n\n\n\n match self.pic_repository.get_random_picture(&parameters) {\n\n Ok(result) => {\n\n send_message_callback(&result.uri);\n\n Ok(())\n\n }\n\n Err(error) => {\n\n send_message_callback(\"画像を取得できない\");\n\n Err(error)\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/commands/pic.rs", "rank": 44, "score": 24802.89390167384 }, { "content": " send_message_callback(\"タッグがまだいない。\");\n\n } else {\n\n let mut message = String::new();\n\n\n\n for tag in tags {\n\n message.push_str(&tag.name);\n\n message.push_str(\": \");\n\n message.push_str(&tag.body);\n\n message.push('\\n')\n\n }\n\n\n\n send_message_callback(&message);\n\n }\n\n } else {\n\n match parse_tag_command(command) {\n\n Some(tag_name) => match self\n\n .tag_repository\n\n .lock()\n\n .unwrap()\n\n .read_tag(tag_name, tennant_id)\n", "file_path": "src/commands/tag.rs", "rank": 45, "score": 24802.42820657747 }, { "content": "use crate::data_access::jisho_repository::JishoRepository;\n\nuse crate::discord_client::CommandHandler;\n\n\n\npub struct JishoCommand {\n\n jisho_repository: Box<JishoRepository + Send>,\n\n}\n\n\n", "file_path": "src/commands/jisho.rs", "rank": 46, "score": 24802.277851245057 }, { "content": " Ok(definition) => {\n\n send_message_callback(&format!(\n\n \"言葉:{}\\n読み方:{}\\n言葉の意味:{}\\n続き:<{}>\",\n\n definition.word,\n\n definition.reading,\n\n definition.english_definitions.join(\"; \"),\n\n definition.link_for_more,\n\n ));\n\n Ok(())\n\n }\n\n Err(error) => {\n\n send_message_callback(\"言葉を取得できない\");\n\n Err(error)\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/commands/jisho.rs", "rank": 47, "score": 24798.33522927768 }, { "content": "\n\n #[test]\n\n fn test_parse_ntag() {\n\n let result = parse_ntag(\"ntag tag_name tag_body\").unwrap();\n\n assert_eq!(\"tag_name\", result.name);\n\n assert_eq!(\"tag_body\", result.body);\n\n\n\n let result =\n\n parse_ntag(\"ntag tag_name long tag body with whitespace and 日本語\").unwrap();\n\n assert_eq!(\"tag_name\", result.name);\n\n assert_eq!(\"long tag body with whitespace and 日本語\", result.body);\n\n }\n\n}\n", "file_path": "src/commands/tag.rs", "rank": 48, "score": 24796.660850476692 }, { "content": "pub mod jisho;\n\npub mod pic;\n\npub mod ping;\n\npub mod status;\n\npub mod tag;\n\npub mod vndb;\n", "file_path": "src/commands/mod.rs", "rank": 49, "score": 24795.28534394878 }, { "content": "\n\nimpl VNDBOrgRepository {\n\n pub fn default() -> VNDBOrgRepository {\n\n VNDBOrgRepository\n\n }\n\n}\n\n\n\nimpl VNDBRepository for VNDBOrgRepository {\n\n fn get_visual_novel(&self, query: Vec<&str>) -> Result<VNDBResult, Box<std::error::Error>> {\n\n let mut result;\n\n\n\n let formated_params = format_search_parameters(query);\n\n let request_uri = format!(\"https://vndb.org/v/all?sq={};o=d;s=rating\", formated_params);\n\n\n\n let mut response: reqwest::Response = reqwest::Client::builder()\n\n .redirect(reqwest::RedirectPolicy::none())\n\n .build()?\n\n .get(&request_uri)\n\n .send()?;\n\n\n", "file_path": "src/data_access/vndb_repository/vndb_org_repository.rs", "rank": 50, "score": 12.418209518769062 }, { "content": " );\n\n }\n\n _ => {\n\n result = VNDBResult::None;\n\n }\n\n }\n\n\n\n Ok(result)\n\n }\n\n}\n\n\n\nimpl VNDBOrgRepositoryError {\n\n fn new(description: String) -> VNDBOrgRepositoryError {\n\n VNDBOrgRepositoryError { description }\n\n }\n\n}\n\n\n\nimpl std::error::Error for VNDBOrgRepositoryError {}\n\n\n\nimpl std::fmt::Display for VNDBOrgRepositoryError {\n\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n\n write!(f, \"{}\", self.description)\n\n }\n\n}\n", "file_path": "src/data_access/vndb_repository/vndb_org_repository.rs", "rank": 51, "score": 11.561726782918488 }, { "content": "use crate::data_access::tag_repository::TagRepository;\n\nuse crate::models::tag::Tag;\n\nuse rusqlite::Connection;\n\nuse rusqlite::NO_PARAMS;\n\n\n\npub struct SqliteTagRepository {\n\n db_connection: Connection,\n\n}\n\n\n\nimpl SqliteTagRepository {\n\n pub fn new() -> Result<SqliteTagRepository, Box<std::error::Error>> {\n\n let db_connection = Connection::open(\"tags.db\")?;\n\n\n\n db_connection.execute(\n\n \"CREATE TABLE IF NOT EXISTS tags (\n\n id INTEGER PRIMARY KEY,\n\n name TEXT NOT NULL,\n\n body TEXT NOT NULL,\n\n tennant_id INTEGER NOT NULL,\n\n UNIQUE (name, tennant_id)\n", "file_path": "src/data_access/tag_repository/sqlite_tag_repository.rs", "rank": 52, "score": 11.182237785842718 }, { "content": " let vndb_org_repository =\n\n Box::new(vndb_repository::vndb_org_repository::VNDBOrgRepository::default());\n\n let vndb_command = Arc::new(Mutex::new(VNDBCommand::new(vndb_org_repository)));\n\n client.register_command(\"vndb\", vndb_command).unwrap();\n\n\n\n log::info!(\"init finished. starting keep alive lock.\");\n\n\n\n let keep_alive = Condvar::new();\n\n let keep_alive_lock = Mutex::new(());\n\n let _ = keep_alive\n\n .wait(keep_alive_lock.lock().unwrap())\n\n .expect(\"keep alive lock failed\");\n\n\n\n log::info!(\"exit requested. exiting.\")\n\n}\n", "file_path": "src/main.rs", "rank": 53, "score": 11.037818280672008 }, { "content": " )\",\n\n NO_PARAMS,\n\n )?;\n\n\n\n Ok(SqliteTagRepository { db_connection })\n\n }\n\n}\n\n\n\nimpl TagRepository for SqliteTagRepository {\n\n fn create_tag(\n\n &self,\n\n tag_name: &str,\n\n tag_body: &str,\n\n tennant_id: u64,\n\n ) -> Result<(), Box<std::error::Error>> {\n\n //sqlite3 doesn't support u64 properly so we have to cast to i64 first. as long as we do this consistantly we shouldn't have problems.\n\n let tennant_id = (tennant_id as i64).to_string();\n\n\n\n self.db_connection.execute(\n\n \"INSERT INTO tags\n", "file_path": "src/data_access/tag_repository/sqlite_tag_repository.rs", "rank": 54, "score": 10.652166839080435 }, { "content": "use log::info;\n\nuse std::env;\n\nuse std::sync::{Arc, Condvar, Mutex};\n\nuse tougou_bot::commands::{\n\n jisho::JishoCommand, pic::PicCommand, ping::PingCommand, status::StatusCommand,\n\n tag::TagCommand, vndb::VNDBCommand,\n\n};\n\nuse tougou_bot::data_access::*;\n\nuse tougou_bot::discord_client::*;\n\n\n", "file_path": "src/main.rs", "rank": 55, "score": 9.990071288313022 }, { "content": " .register_command(\"status\", Arc::new(Mutex::new(StatusCommand)))\n\n .unwrap();\n\n\n\n let sqlite_tag_repository =\n\n Box::new(tag_repository::sqlite_tag_repository::SqliteTagRepository::new().unwrap());\n\n\n\n let tag_command = Arc::new(Mutex::new(TagCommand::new(sqlite_tag_repository).unwrap()));\n\n client\n\n .register_command(\"ntag\", tag_command.clone())\n\n .unwrap();\n\n client.register_command(\"tag\", tag_command.clone()).unwrap();\n\n client\n\n .register_command(\"atags\", tag_command.clone())\n\n .unwrap();\n\n\n\n let jisho_org_repository =\n\n Box::new(jisho_repository::jisho_org_repository::JishoOrgRepository::default());\n\n let jisho_command = Arc::new(Mutex::new(JishoCommand::new(jisho_org_repository)));\n\n client.register_command(\"jisho\", jisho_command).unwrap();\n\n\n", "file_path": "src/main.rs", "rank": 56, "score": 9.40818804217187 }, { "content": " fn new(description: String) -> DanbooruPicRepositoryError {\n\n DanbooruPicRepositoryError { description }\n\n }\n\n}\n\n\n\nimpl std::error::Error for DanbooruPicRepositoryError {}\n\n\n\nimpl std::fmt::Display for DanbooruPicRepositoryError {\n\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n\n write!(f, \"{}\", self.description)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_format_search_parameters() {\n\n let empty_vec: Vec<&str> = Vec::new();\n", "file_path": "src/data_access/pic_repository/danbooru_pic_repository.rs", "rank": 57, "score": 9.313664317400264 }, { "content": "\n\nimpl JishoOrgRepositoryError {\n\n fn new(description: String) -> JishoOrgRepositoryError {\n\n JishoOrgRepositoryError { description }\n\n }\n\n}\n\n\n\nimpl std::error::Error for JishoOrgRepositoryError {}\n\n\n\nimpl std::fmt::Display for JishoOrgRepositoryError {\n\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n\n write!(f, \"{}\", self.description)\n\n }\n\n}\n", "file_path": "src/data_access/jisho_repository/jisho_org_repository.rs", "rank": 58, "score": 8.119311335714428 }, { "content": "pub mod commands;\n\npub mod data_access;\n\npub mod discord_client;\n\npub mod models;\n", "file_path": "src/lib.rs", "rank": 59, "score": 7.408032950101541 }, { "content": " (name, body, tennant_id) VALUES (?1, ?2, ?3)\",\n\n &[tag_name, tag_body, &tennant_id],\n\n )?;\n\n Ok(())\n\n }\n\n\n\n fn read_tag(&self, tag_name: &str, tennant_id: u64) -> Result<String, Box<std::error::Error>> {\n\n //sqlite3 doesn't support u64 properly so we have to cast to i64 first. as long as we do this consistantly we shouldn't have problems.\n\n let tennant_id = (tennant_id as i64).to_string();\n\n\n\n Ok(self\n\n .db_connection\n\n .prepare(\n\n \"SELECT body\n\n FROM tags \n\n WHERE tennant_id = (?1) AND name = (?2)\",\n\n )?\n\n .query_row(&[&tennant_id, tag_name], |row| Ok(row.get(0)?))?)\n\n }\n\n\n", "file_path": "src/data_access/tag_repository/sqlite_tag_repository.rs", "rank": 60, "score": 6.990763385950297 }, { "content": " \"https://danbooru.donmai.us/posts.json?search&random=true&limit=1&tags={}\",\n\n parameters\n\n );\n\n let response_body: String = reqwest::get(&request_uri)?.text()?;\n\n\n\n let response_model: Vec<DanbooruApiResponse> = serde_json::from_str(&response_body)?;\n\n\n\n let uri = match response_model.first() {\n\n Some(picture) => Ok(picture.file_url.clone()),\n\n None => Err(DanbooruPicRepositoryError::new(\n\n \"No images with those tags found\".to_string(),\n\n )),\n\n }?;\n\n\n\n Ok(Pic { uri })\n\n }\n\n }\n\n}\n\n\n\nimpl DanbooruPicRepositoryError {\n", "file_path": "src/data_access/pic_repository/danbooru_pic_repository.rs", "rank": 61, "score": 6.854960405966703 }, { "content": " fn read_all_tags(&self, tennant_id: u64) -> Result<Vec<Tag>, Box<std::error::Error>> {\n\n //sqlite3 doesn't support u64 properly so we have to cast to i64 first. as long as we do this consistantly we shouldn't have problems.\n\n let tennant_id = (tennant_id as i64).to_string();\n\n\n\n Ok(self\n\n .db_connection\n\n .prepare(\n\n \"SELECT name, body\n\n FROM tags\n\n WHERE tennant_id = (?1)\",\n\n )?\n\n .query_map(&[&tennant_id], |row| {\n\n Ok(Tag {\n\n name: row.get(0)?,\n\n body: row.get(1)?,\n\n })\n\n })?\n\n .filter_map(Result::ok)\n\n .collect())\n\n }\n\n}\n", "file_path": "src/data_access/tag_repository/sqlite_tag_repository.rs", "rank": 62, "score": 6.755267317750118 }, { "content": "use crate::data_access::vndb_repository::VNDBRepository;\n\nuse crate::models::vndb_result::VNDBResult;\n\nuse html5ever;\n\nuse html5ever::rcdom::{Handle, NodeData};\n\nuse html5ever::tendril::TendrilSink;\n\nuse reqwest;\n\nuse reqwest::StatusCode;\n\n\n\npub struct VNDBOrgRepository;\n\n\n\n#[derive(Debug)]\n", "file_path": "src/data_access/vndb_repository/vndb_org_repository.rs", "rank": 63, "score": 6.35770351539769 }, { "content": "use crate::data_access::pic_repository::PicRepository;\n\nuse crate::models::pic::Pic;\n\nuse reqwest;\n\nuse serde_derive::Deserialize;\n\n\n\n#[derive(Deserialize)]\n\npub struct DanbooruApiResponse {\n\n file_url: String,\n\n}\n\n\n\npub struct DanbooruPicRepository;\n\n\n\n#[derive(Debug)]\n\npub struct DanbooruPicRepositoryError {\n\n description: String,\n\n}\n\n\n", "file_path": "src/data_access/pic_repository/danbooru_pic_repository.rs", "rank": 64, "score": 6.344632693588091 }, { "content": "# Tougou Bot\n\n\n\nAn (in progress) bot for discord. The old version of this had all the features that are still marked as todo so use an old release if you want those still.\n\n\n\n## TODO:\n\n - commands to interface with the vndb.org website\n\n - commands to interface with some anime database (mal api still down?)\n\n - commands to interface with wikipedia (was this feature used?)\n\n - unit/feature tests (need to stub out external APIs somehow)\n\n - build packages for releases (.deb, .rpm?)\n\n\n\n## How to build it: \n\n[Make sure rustc & cargo are installed](https://www.rust-lang.org/learn/get-started) \n\n`cargo build [--release]`\n\n\n\n## How to test it:\n\nLinting: `cargo fmt && cargo clippy` \n\nUnit: `cargo test` \n\nMore detailed automated tests still to come.\n\n\n\n## How to run it:\n\nMake sure the environment variable `DISCORD_TOKEN` is set to your discord application's bot token. \n\nCompile using `cargo build --release` and then run the output executable.\n\n\n\nThe environment variable `RUST_LOG` can be set to log levels of `trace`, `debug`, `info`, `warn`, or `error`. I reccomend using at least `info`.\n\n\n\n## Commands: \n\n### !ping: \n\nTougou replies saying \"Pong!\"\n\n\n\n### !pic: \n\n(warning: likely to be NSFW) \n\nThis command fetches a random image from the danbooru site. \n\nUsage: `!pic [tag(s)]`. Tags are optional and space separated. Note: The Danbooru API caps the number of tags that can constrain a query to 2.\n\n\n\n### !tag: \n\nThis command allows you to set tougou to memorise and recall phrases. \n\nExample: \n\n```\n\nyou: !ntag tag_name some tag body\n\ntougou: 新しいタッグ「tag_name」➡「some tag body」を作った。\n\nyou: !tag tag_name\n\ntougou: some tag body\n\n```\n\n\n\n### !jisho:\n\nThis command allows you to check for the definition and/or reading of a japanese word. This command uses the jisho.org api. \n\nExample: \n\n```\n\nyou: !jisho wipe\n\ntougou: 言葉:拭く\n\n 読み方:ふく\n\n 言葉の意味:to wipe; to dry\n\n 続き:https://jisho.org/search/wipe\n\n```\n\n\n\n### !vndb: \n\nWarning: Lkely to be NSFW. \n\nThis command allows you to search the vndb website for visual novels.\n\nExample:\n\n```\n\nyou: !vndb lisp \n\ntougou: https://vndb.org/v7754\n\n 続き:https://vndb.org/v/all?sq=lisp;o=d;s=rating\n\n```\n", "file_path": "README.md", "rank": 65, "score": 6.189483795528158 }, { "content": " match response.status() {\n\n StatusCode::TEMPORARY_REDIRECT => {\n\n let location_header = response\n\n .headers()\n\n .get(reqwest::header::LOCATION)\n\n .ok_or_else(|| {\n\n VNDBOrgRepositoryError::new(String::from(\n\n \"VNDB API returned redirect but there was no location header\",\n\n ))\n\n })?\n\n .to_str()?\n\n .to_owned();\n\n result = VNDBResult::Single(format!(\"https://vndb.org{}\", location_header));\n\n }\n\n StatusCode::OK => {\n\n let recomended_link = get_recomended_link(&response.text()?)?;\n\n\n\n result = VNDBResult::MostLikelyAndMore(\n\n format!(\"https://vndb.org{}\", recomended_link),\n\n request_uri,\n", "file_path": "src/data_access/vndb_repository/vndb_org_repository.rs", "rank": 66, "score": 6.111524427724049 }, { "content": "use crate::models::vndb_result::VNDBResult;\n\n\n", "file_path": "src/data_access/vndb_repository/mod.rs", "rank": 67, "score": 5.24719748621664 }, { "content": "pub mod jisho_definition;\n\npub mod pic;\n\npub mod tag;\n\npub mod vndb_result;\n", "file_path": "src/models/mod.rs", "rank": 68, "score": 5.185057929650384 }, { "content": " let japanese_section = first_response_model_data.japanese.first().ok_or_else(|| {\n\n JishoOrgRepositoryError::new(String::from(\"japanese section was empty\"))\n\n })?;\n\n\n\n let senses_section = first_response_model_data.senses.first().ok_or_else(|| {\n\n JishoOrgRepositoryError::new(String::from(\"senses section was empty\"))\n\n })?;\n\n\n\n Ok(JishoDefinition {\n\n word: match japanese_section.word.clone() {\n\n Some(word) => word,\n\n None => japanese_section.reading.clone(),\n\n },\n\n reading: japanese_section.reading.clone(),\n\n english_definitions: senses_section.english_definitions.clone(),\n\n parts_of_speech: senses_section.parts_of_speech.clone(),\n\n link_for_more: format!(\"https://jisho.org/search/{}\", parameters),\n\n })\n\n }\n\n}\n", "file_path": "src/data_access/jisho_repository/jisho_org_repository.rs", "rank": 69, "score": 4.307117503894792 }, { "content": "pub struct JishoDefinition {\n\n pub word: String,\n\n pub reading: String,\n\n pub english_definitions: Vec<String>,\n\n pub parts_of_speech: Vec<String>,\n\n pub link_for_more: String,\n\n}\n", "file_path": "src/models/jisho_definition.rs", "rank": 70, "score": 3.214740848929359 }, { "content": "pub struct Tag {\n\n pub name: String,\n\n pub body: String,\n\n}\n", "file_path": "src/models/tag.rs", "rank": 71, "score": 3.1735606309062883 }, { "content": "pub mod jisho_repository;\n\npub mod pic_repository;\n\npub mod tag_repository;\n\npub mod vndb_repository;\n", "file_path": "src/data_access/mod.rs", "rank": 72, "score": 3.1178812744655966 }, { "content": "pub struct Pic {\n\n pub uri: String,\n\n}\n", "file_path": "src/models/pic.rs", "rank": 73, "score": 3.0601136822378816 }, { "content": "use crate::data_access::jisho_repository::JishoRepository;\n\nuse crate::models::jisho_definition::JishoDefinition;\n\nuse reqwest;\n\nuse serde_derive::Deserialize;\n\n\n\n#[derive(Deserialize)]\n", "file_path": "src/data_access/jisho_repository/jisho_org_repository.rs", "rank": 74, "score": 2.9138126944260754 }, { "content": " let link_to_vn_element = first_column_children.first()?;\n\n\n\n if let NodeData::Element { ref attrs, .. } = link_to_vn_element.data {\n\n for link_attribute in attrs.borrow().iter() {\n\n if &link_attribute.name.local == \"href\" {\n\n return Some(format!(\"{}\", link_attribute.value));\n\n }\n\n }\n\n };\n\n }\n\n }\n\n }\n\n }\n\n\n\n for child in node.children.borrow().iter() {\n\n if let Some(value) = find_top_table_result(child) {\n\n return Some(value);\n\n };\n\n }\n\n None\n\n}\n\n\n", "file_path": "src/data_access/vndb_repository/vndb_org_repository.rs", "rank": 75, "score": 2.714774793116753 }, { "content": "use crate::models::pic::Pic;\n\n\n", "file_path": "src/data_access/pic_repository/mod.rs", "rank": 76, "score": 2.5204092217157266 }, { "content": "use crate::models::tag::Tag;\n\n\n", "file_path": "src/data_access/tag_repository/mod.rs", "rank": 77, "score": 2.5204092217157266 }, { "content": "use crate::models::jisho_definition::JishoDefinition;\n\n\n", "file_path": "src/data_access/jisho_repository/mod.rs", "rank": 78, "score": 2.406977085109091 } ]
Rust
src/search.rs
dskleingeld/minimal_timeseries
0d03039ec4663a918a8adbe7a78fee2237dfe69a
use byteorder::{ByteOrder, LittleEndian}; use chrono::{DateTime, Utc}; use std::io::{Read, Seek, SeekFrom}; use crate::data::FullTime; use crate::header::SearchBounds; use crate::ByteSeries; use crate::Error; #[derive(thiserror::Error, Debug)] pub enum SeekError { #[error("could not find timestamp in this series")] NotFound, #[error("data file is empty")] EmptyFile, #[error("no data to return as the start time is after the last time in the data")] StartAfterData, #[error("no data to return as the stop time is before the data")] StopBeforeData, #[error("error while searching through data")] Io(#[from] std::io::Error), } #[derive(Debug)] pub struct TimeSeek { pub start: u64, pub stop: u64, pub curr: u64, pub full_time: FullTime, } impl TimeSeek { pub fn new( series: &mut ByteSeries, start: chrono::DateTime<Utc>, stop: chrono::DateTime<Utc>, ) -> Result<Self, Error> { let (start, stop, full_time) = series.get_bounds(start, stop)?; Ok(TimeSeek { start, stop, curr: start, full_time, }) } pub fn lines(&self, series: &ByteSeries) -> u64 { (self.stop - self.start) / (series.full_line_size as u64) } } impl ByteSeries { fn find_read_start( &mut self, start_time: DateTime<Utc>, start: u64, stop: u64, ) -> Result<u64, SeekError> { let mut buf = vec![0u8; (stop - start) as usize]; self.data.seek(SeekFrom::Start(start))?; self.data.read_exact(&mut buf)?; for line_start in (0..buf.len().saturating_sub(2)).step_by(self.full_line_size) { if LittleEndian::read_u16(&buf[line_start..line_start + 2]) >= start_time.timestamp() as u16 { log::debug!("setting start_byte from liniar search, pos: {}", line_start); let start_byte = start + line_start as u64; return Ok(start_byte); } } Ok(stop) } pub fn get_bounds( &mut self, start_time: DateTime<Utc>, end_time: DateTime<Utc>, ) -> Result<(u64, u64, FullTime), SeekError> { if self.data_size == 0 { return Err(SeekError::EmptyFile); } if start_time.timestamp() >= self.last_time_in_data.unwrap() { return Err(SeekError::StartAfterData); } if end_time.timestamp() <= self.first_time_in_data.unwrap() { return Err(SeekError::StopBeforeData); } let (start_bound, stop_bound, full_time) = self .header .search_bounds(start_time.timestamp(), end_time.timestamp()); let start_byte = match start_bound { SearchBounds::Found(pos) => pos, SearchBounds::Clipped => 0, SearchBounds::TillEnd(start) => { let end = self.data_size; self.find_read_start(start_time, start, end)? } SearchBounds::Window(start, stop) => self.find_read_start(start_time, start, stop)?, }; let stop_byte = match stop_bound { SearchBounds::Found(pos) => pos, SearchBounds::TillEnd(pos) => { let end = self.data_size; self.find_read_stop(end_time, pos, end)? } SearchBounds::Window(start, stop) => self.find_read_stop(end_time, start, stop)?, SearchBounds::Clipped => panic!("should never occur"), }; Ok((start_byte, stop_byte, full_time)) } fn find_read_stop( &mut self, end_time: DateTime<Utc>, start: u64, stop: u64, ) -> Result<u64, SeekError> { let mut buf = vec![0u8; (stop - start) as usize]; self.data.seek(SeekFrom::Start(start))?; self.data.read_exact(&mut buf)?; for line_start in (0..buf.len() - self.full_line_size + 1) .rev() .step_by(self.full_line_size) { if LittleEndian::read_u16(&buf[line_start..line_start + 2]) <= end_time.timestamp() as u16 { let stop_byte = start + line_start as u64; return Ok(stop_byte + self.full_line_size as u64); } } Ok(stop) } }
use byteorder::{ByteOrder, LittleEndian}; use chrono::{DateTime, Utc}; use std::io::{Read, Seek, SeekFrom}; use crate::data::FullTime; use crate::header::SearchBounds; use crate::ByteSeries; use crate::Error; #[derive(thiserror::Error, Debug)] pub enum SeekError { #[error("could not find timestamp in this series")] NotFound, #[error("data file is empty")] EmptyFile, #[error("no data to return as the start time is after the last time in the data")] StartAfterData, #[error("no data to return as the stop time is before the data")] StopBeforeData, #[error("error while searching through data")] Io(#[from] std::io::Error), } #[derive(Debug)] pub struct TimeSeek { pub start: u64, pub stop: u64, pub curr: u64, pub full_time: FullTime, } impl TimeSeek { pub fn new( series: &mut ByteSeries, start: chrono::DateTime<Utc>, stop: chrono::DateTime<Utc>, ) -> Result<Self, Error> { let (start, stop, full_time) = series.get_bounds(start, stop)?; Ok(TimeSeek { start, stop, curr: start, full_time, }) } pub fn lines(&self, series: &ByteSeries) -> u64 { (self.stop - self.start) / (series.full_line_size as u64) } } impl ByteSeries { fn find_read_start( &mut self, start_time: DateTime<Utc>, start: u64, stop: u64, ) -> Result<u64, SeekError> { let mut buf = vec![0u8; (stop - start) as usize];
pub fn get_bounds( &mut self, start_time: DateTime<Utc>, end_time: DateTime<Utc>, ) -> Result<(u64, u64, FullTime), SeekError> { if self.data_size == 0 { return Err(SeekError::EmptyFile); } if start_time.timestamp() >= self.last_time_in_data.unwrap() { return Err(SeekError::StartAfterData); } if end_time.timestamp() <= self.first_time_in_data.unwrap() { return Err(SeekError::StopBeforeData); } let (start_bound, stop_bound, full_time) = self .header .search_bounds(start_time.timestamp(), end_time.timestamp()); let start_byte = match start_bound { SearchBounds::Found(pos) => pos, SearchBounds::Clipped => 0, SearchBounds::TillEnd(start) => { let end = self.data_size; self.find_read_start(start_time, start, end)? } SearchBounds::Window(start, stop) => self.find_read_start(start_time, start, stop)?, }; let stop_byte = match stop_bound { SearchBounds::Found(pos) => pos, SearchBounds::TillEnd(pos) => { let end = self.data_size; self.find_read_stop(end_time, pos, end)? } SearchBounds::Window(start, stop) => self.find_read_stop(end_time, start, stop)?, SearchBounds::Clipped => panic!("should never occur"), }; Ok((start_byte, stop_byte, full_time)) } fn find_read_stop( &mut self, end_time: DateTime<Utc>, start: u64, stop: u64, ) -> Result<u64, SeekError> { let mut buf = vec![0u8; (stop - start) as usize]; self.data.seek(SeekFrom::Start(start))?; self.data.read_exact(&mut buf)?; for line_start in (0..buf.len() - self.full_line_size + 1) .rev() .step_by(self.full_line_size) { if LittleEndian::read_u16(&buf[line_start..line_start + 2]) <= end_time.timestamp() as u16 { let stop_byte = start + line_start as u64; return Ok(stop_byte + self.full_line_size as u64); } } Ok(stop) } }
self.data.seek(SeekFrom::Start(start))?; self.data.read_exact(&mut buf)?; for line_start in (0..buf.len().saturating_sub(2)).step_by(self.full_line_size) { if LittleEndian::read_u16(&buf[line_start..line_start + 2]) >= start_time.timestamp() as u16 { log::debug!("setting start_byte from liniar search, pos: {}", line_start); let start_byte = start + line_start as u64; return Ok(start_byte); } } Ok(stop) }
function_block-function_prefix_line
[ { "content": "fn insert_vector(ts: &mut Series, t_start: DateTime<Utc>, t_end: DateTime<Utc>, data: &[f32]) {\n\n let dt = (t_end - t_start) / (data.len() as i32);\n\n let mut time = t_start;\n\n\n\n for x in data {\n\n ts.append(time, &x.to_be_bytes()).unwrap();\n\n time = time + dt;\n\n }\n\n}\n\n\n", "file_path": "tests/combine.rs", "rank": 0, "score": 152089.690887407 }, { "content": "//open file and check if it has the right lenght\n\n//(an interger multiple of the line lenght) if it\n\n//has not warn and repair by truncating\n\npub fn open_and_check(path: PathBuf, full_line_size: usize) -> Result<(File, u64), Error> {\n\n let file = OpenOptions::new()\n\n .read(true)\n\n .append(true)\n\n .create(true)\n\n .open(path)?;\n\n let metadata = file.metadata()?;\n\n\n\n let rest = metadata.len() % (full_line_size as u64);\n\n if rest > 0 {\n\n log::warn!(\"Last write incomplete, truncating to largest multiple of the line size\");\n\n file.set_len(metadata.len() - rest)?;\n\n }\n\n Ok((file, metadata.len()))\n\n}\n", "file_path": "src/util.rs", "rank": 1, "score": 147462.38109285402 }, { "content": "pub fn insert_timestamp_hashes(\n\n data: &mut Series,\n\n n_to_insert: u32,\n\n step: i64,\n\n time: DateTime<Utc>,\n\n) {\n\n let mut timestamp = time.timestamp();\n\n\n\n for _ in 0..n_to_insert {\n\n let hash = hash64::<i64>(&timestamp);\n\n\n\n let mut buffer = Vec::with_capacity(8);\n\n &buffer.write_u64::<NativeEndian>(hash).unwrap();\n\n\n\n let dt = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(timestamp, 0), Utc);\n\n data.append(dt, buffer.as_slice()).unwrap();\n\n timestamp += step;\n\n }\n\n}\n\n\n", "file_path": "tests/shared.rs", "rank": 2, "score": 95983.46667483487 }, { "content": "pub fn insert_timestamp_arrays(\n\n data: &mut Series,\n\n n_to_insert: u32,\n\n step: i64,\n\n time: DateTime<Utc>,\n\n) {\n\n let mut timestamp = time.timestamp();\n\n\n\n for _ in 0..n_to_insert {\n\n let mut buffer = Vec::with_capacity(8);\n\n\n\n let dt = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(timestamp, 0), Utc);\n\n &buffer.write_i64::<NativeEndian>(timestamp).unwrap();\n\n\n\n data.append(dt, buffer.as_slice()).unwrap();\n\n timestamp += step;\n\n }\n\n}\n", "file_path": "tests/shared.rs", "rank": 3, "score": 95983.46667483487 }, { "content": "pub fn new_sampler<D, T>(series: &Series, decoder: D) -> SamplerBuilder<D, T, No>\n\nwhere\n\n T: Debug + Clone,\n\n D: Decoder<T>,\n\n{\n\n SamplerBuilder {\n\n start_set: PhantomData {},\n\n decoded: PhantomData {},\n\n\n\n series: series.clone(),\n\n decoder,\n\n start: None,\n\n stop: None,\n\n points: None,\n\n }\n\n}\n\n\n\nimpl<D, T, StartSet> SamplerBuilder<D, T, StartSet>\n\nwhere\n\n T: Debug + Clone + Default,\n", "file_path": "src/sampler/builder.rs", "rank": 4, "score": 80306.47425924256 }, { "content": "pub trait ToAssign: Debug {}\n", "file_path": "src/sampler/builder.rs", "rank": 5, "score": 74850.287840924 }, { "content": "pub trait Bin: Debug {\n\n fn update_bin(&mut self, t: i64) -> Option<i64>;\n\n fn binsize(&self) -> usize;\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct SampleBin {\n\n binsize: usize,\n\n n: usize,\n\n t_sum: i64,\n\n}\n\nimpl SampleBin {\n\n pub fn new(binsize: usize) -> Self {\n\n SampleBin {\n\n binsize,\n\n n: 0,\n\n t_sum: 0,\n\n }\n\n }\n\n}\n", "file_path": "src/sampler/combiners.rs", "rank": 6, "score": 74850.287840924 }, { "content": "pub fn insert_uniform_arrays(\n\n data: &mut Series,\n\n n_to_insert: u32,\n\n _step: i64,\n\n line_size: usize,\n\n time: DateTime<Utc>,\n\n) {\n\n let mut timestamp = time.timestamp();\n\n for i in 0..n_to_insert {\n\n let buffer = vec![i as u8; line_size];\n\n\n\n let dt = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(timestamp, 0), Utc);\n\n data.append(dt, buffer.as_slice()).unwrap();\n\n timestamp += 5;\n\n }\n\n}\n\n\n", "file_path": "tests/shared.rs", "rank": 7, "score": 74146.74484438845 }, { "content": "pub trait Decoder<T>: Debug\n\nwhere\n\n T: Debug + Clone,\n\n{\n\n fn decode(&mut self, bytes: &[u8], out: &mut Vec<T>);\n\n fn decoded(&mut self, bytes: &[u8]) -> Vec<T> {\n\n let mut values = Vec::new();\n\n self.decode(bytes, &mut values);\n\n values\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct EmptyDecoder {}\n\nimpl Decoder<u8> for EmptyDecoder {\n\n fn decode(&mut self, bytes: &[u8], out: &mut Vec<u8>) {\n\n out.extend_from_slice(&bytes[2..]);\n\n }\n\n}\n", "file_path": "src/sampler/decoders.rs", "rank": 8, "score": 69876.223033891 }, { "content": "#[derive(Debug)]\n\nstruct TimestampDecoder {}\n\n\n\nimpl Decoder<i64> for TimestampDecoder {\n\n fn decode(&mut self, bytes: &[u8], out: &mut Vec<i64>) {\n\n let ts = NativeEndian::read_i64(bytes);\n\n out.push(ts);\n\n }\n\n}\n\n\n", "file_path": "tests/append.rs", "rank": 9, "score": 68711.11127410195 }, { "content": "#[test]\n\nfn timestamps_then_verify() {\n\n const NUMBER_TO_INSERT: i64 = 10_000;\n\n const PERIOD: i64 = 24 * 3600 / NUMBER_TO_INSERT;\n\n\n\n //setup_debug_logging(2).unwrap();\n\n\n\n if Path::new(\"test_append_timestamps_then_verify.h\").exists() {\n\n fs::remove_file(\"test_append_timestamps_then_verify.h\").unwrap();\n\n }\n\n if Path::new(\"test_append_timestamps_then_verify.dat\").exists() {\n\n fs::remove_file(\"test_append_timestamps_then_verify.dat\").unwrap();\n\n }\n\n\n\n let time = Utc::now();\n\n\n\n let mut data = Series::open(\"test_append_timestamps_then_verify\", 8).unwrap();\n\n insert_timestamp_arrays(&mut data, NUMBER_TO_INSERT as u32, PERIOD, time);\n\n\n\n let timestamp = time.timestamp();\n\n let t1 = time;\n", "file_path": "tests/append.rs", "rank": 10, "score": 64019.176996267386 }, { "content": "#[test]\n\nfn beyond_range() {\n\n if Path::new(\"test_beyond_range.h\").exists() {\n\n fs::remove_file(\"test_beyond_range.h\").unwrap();\n\n }\n\n if Path::new(\"test_beyond_range.dat\").exists() {\n\n fs::remove_file(\"test_beyond_range.dat\").unwrap();\n\n }\n\n const LINE_SIZE: usize = 8;\n\n const STEP: i64 = 5;\n\n const N_TO_INSERT: u32 = 100;\n\n let start_read_inlines = N_TO_INSERT as i64 + 1;\n\n let read_length_inlines = 10;\n\n\n\n let time = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(1539180000, 0), Utc);\n\n let timestamp = time.timestamp();\n\n println!(\"start timestamp {}\", timestamp);\n\n let mut data = Series::open(\"test_beyond_range\", LINE_SIZE).unwrap();\n\n\n\n insert_uniform_arrays(&mut data, N_TO_INSERT, STEP, LINE_SIZE, time);\n\n\n", "file_path": "tests/seek.rs", "rank": 11, "score": 64019.176996267386 }, { "content": "/// the combiner gets both the value and the time, though unused\n\n/// by simple combinators such as the MeanCombiner this allows\n\n/// to combine values and time for example to calculate the derivative\n\npub trait SampleCombiner<T: Sized>: Debug {\n\n fn process(&mut self, time: i64, values: Vec<T>) -> Option<(i64, Vec<T>)>;\n\n fn binsize(&self) -> usize;\n\n fn binoffset(&self) -> usize {\n\n 0\n\n }\n\n fn set_decoded_size(&mut self, _n_values: usize) {}\n\n}\n\n\n\n#[derive(Debug, Clone, Default)]\n\npub struct Empty {}\n\nimpl<T: Debug + Clone + Sized> SampleCombiner<T> for Empty {\n\n fn process(&mut self, t: i64, v: Vec<T>) -> Option<(i64, Vec<T>)> {\n\n Some((t, v))\n\n }\n\n fn binsize(&self) -> usize {\n\n 1\n\n }\n\n}\n\n\n", "file_path": "src/sampler/combiners.rs", "rank": 12, "score": 63892.859499336046 }, { "content": "#[allow(dead_code)]\n\nfn setup_debug_logging(verbosity: u8) -> Result<(), fern::InitError> {\n\n let mut base_config = fern::Dispatch::new();\n\n let colors = ColoredLevelConfig::new()\n\n .info(Color::Green)\n\n .debug(Color::Yellow)\n\n .warn(Color::Magenta);\n\n\n\n base_config = match verbosity {\n\n 0 =>\n\n // Let's say we depend on something which whose \"info\" level messages are too\n\n // verbose to include in end-user output. If we don't need them,\n\n // let's not include them.\n\n {\n\n base_config.level(log::LevelFilter::Info)\n\n }\n\n 1 => base_config.level(log::LevelFilter::Debug),\n\n 2 => base_config.level(log::LevelFilter::Trace),\n\n _3_or_more => base_config.level(log::LevelFilter::Trace),\n\n };\n\n\n", "file_path": "tests/append.rs", "rank": 13, "score": 61884.761471300866 }, { "content": "//period in numb of data points\n\nfn linear_array(n: usize, slope: f32) -> Vec<f32> {\n\n (0..n).map(|i| i as f32 * slope).collect()\n\n}\n\n\n", "file_path": "tests/combine.rs", "rank": 14, "score": 46637.951130152054 }, { "content": "#[derive(Debug)]\n\nstruct TestDecoder {}\n\n\n\nimpl Decoder<f32> for TestDecoder {\n\n fn decode(&mut self, bytes: &[u8], out: &mut Vec<f32>) {\n\n out.extend(bytes.iter().map(|b| *b as f32));\n\n }\n\n}\n\n\n", "file_path": "examples/100d.rs", "rank": 15, "score": 45883.2212025608 }, { "content": "#[derive(Debug)]\n\nstruct TestDecoder {}\n\n\n\nimpl Decoder<f32> for TestDecoder {\n\n fn decode(&mut self, bytes: &[u8], out: &mut Vec<f32>) {\n\n out.extend(bytes.iter().map(|b| *b as f32));\n\n }\n\n}\n\n\n", "file_path": "examples/mean.rs", "rank": 16, "score": 44481.58418166073 }, { "content": "#[derive(Debug)]\n\nstruct HashDecoder {}\n\n\n\nimpl Decoder<u64> for HashDecoder {\n\n fn decode(&mut self, bytes: &[u8], out: &mut Vec<u64>) {\n\n let hash = NativeEndian::read_u64(bytes);\n\n out.push(hash);\n\n }\n\n}\n\n\n", "file_path": "tests/append.rs", "rank": 17, "score": 44481.58418166073 }, { "content": "#[derive(Debug)]\n\nstruct FloatDecoder {}\n\nimpl Decoder<f32> for FloatDecoder {\n\n fn decode(&mut self, bytes: &[u8], out: &mut Vec<f32>) {\n\n let mut arr = [0u8; 4];\n\n arr.copy_from_slice(&bytes[0..4]);\n\n let v = f32::from_be_bytes(arr);\n\n out.push(v)\n\n }\n\n}\n\n\n", "file_path": "tests/combine.rs", "rank": 18, "score": 44481.58418166073 }, { "content": "fn main() {\n\n SimpleLogger::init(LevelFilter::Trace, Config::default()).unwrap();\n\n\n\n let mut decoder = TestDecoder {};\n\n let mut ts = Series::open(\"examples/data/2\", 103).unwrap();\n\n let (endtime, _data) = ts.last_line(&mut decoder).unwrap();\n\n\n\n let bin = combiners::SampleBin::new(5);\n\n let combiner = combiners::Mean::new(bin);\n\n let mut sampler = new_sampler(&ts, decoder)\n\n .points(10)\n\n .start(endtime - Duration::days(100))\n\n .stop(endtime)\n\n .build_with_combiner(combiner)\n\n .unwrap();\n\n sampler.sample_all().unwrap();\n\n}\n", "file_path": "examples/100d.rs", "rank": 19, "score": 42656.199138101016 }, { "content": "//period in numb of data points\n\nfn sine_array(n: usize, mid: f32, period: f32) -> Vec<f32> {\n\n (0..n)\n\n .map(|i| i as f32 * 2. * PI / period)\n\n .map(|x| mid * x.sin())\n\n .collect()\n\n}\n\n\n", "file_path": "tests/combine.rs", "rank": 20, "score": 42499.64365914135 }, { "content": "fn main() {\n\n let mut decoder = EmptyDecoder {};\n\n let mut ts = Series::open(\"examples/data/4\", 24).unwrap();\n\n let (endtime, _data) = ts.last_line(&mut decoder).unwrap();\n\n\n\n let mut sampler = new_sampler(&ts, decoder)\n\n .points(10)\n\n .start(endtime - Duration::hours(90))\n\n .stop(endtime)\n\n .build()\n\n .unwrap();\n\n sampler.sample_all().unwrap();\n\n}\n", "file_path": "examples/skip.rs", "rank": 21, "score": 41139.84569324223 }, { "content": "fn main() {\n\n let mut decoder = TestDecoder {};\n\n let mut ts = Series::open(\"examples/data/4\", 24).unwrap();\n\n let (endtime, _data) = ts.last_line(&mut decoder).unwrap();\n\n\n\n let bin = combiners::SampleBin::new(5);\n\n let combiner = combiners::Mean::new(bin);\n\n let mut sampler = new_sampler(&ts, decoder)\n\n .points(10)\n\n .start(endtime - Duration::hours(90))\n\n .stop(endtime)\n\n .build_with_combiner(combiner)\n\n .unwrap();\n\n sampler.sample_all().unwrap();\n\n}\n", "file_path": "examples/mean.rs", "rank": 22, "score": 41139.84569324223 }, { "content": "#[test]\n\nfn mean() {\n\n if Path::new(\"test_combiner_mean.h\").exists() {\n\n fs::remove_file(\"test_combiner_mean.h\").unwrap();\n\n }\n\n if Path::new(\"test_combiner_mean.dat\").exists() {\n\n fs::remove_file(\"test_combiner_mean.dat\").unwrap();\n\n }\n\n\n\n let now = Utc::now();\n\n let t1 = now - Duration::hours(2);\n\n let t2 = now;\n\n let n = 200;\n\n let s = 10;\n\n\n\n let mut ts = Series::open(\"test_combiner_mean\", 4).unwrap();\n\n let data = sine_array(n, 5.0, 100.0);\n\n insert_vector(&mut ts, t1, t2, &data);\n\n\n\n let combiner = combiners::Mean::new(combiners::SampleBin::new(s));\n\n let decoder = FloatDecoder {};\n", "file_path": "tests/combine.rs", "rank": 23, "score": 41139.84569324223 }, { "content": "#[test]\n\nfn basic() {\n\n if Path::new(\"test_append.h\").exists() {\n\n fs::remove_file(\"test_append.h\").unwrap();\n\n }\n\n if Path::new(\"test_append.dat\").exists() {\n\n fs::remove_file(\"test_append.dat\").unwrap();\n\n }\n\n const LINE_SIZE: usize = 10;\n\n const STEP: i64 = 5;\n\n const N_TO_INSERT: u32 = 100;\n\n\n\n let time = Utc::now();\n\n\n\n let mut data = Series::open(\"test_append\", LINE_SIZE).unwrap();\n\n insert_uniform_arrays(&mut data, N_TO_INSERT, STEP, LINE_SIZE, time);\n\n\n\n assert_eq!(\n\n fs::metadata(\"test_append.dat\").unwrap().len(),\n\n ((LINE_SIZE + 2) as u32 * N_TO_INSERT) as u64\n\n );\n\n assert_eq!(fs::metadata(\"test_append.h\").unwrap().len(), 16);\n\n}\n\n\n", "file_path": "tests/append.rs", "rank": 24, "score": 41139.84569324223 }, { "content": "#[test]\n\nfn hashes_then_verify() {\n\n const NUMBER_TO_INSERT: i64 = 1_000;\n\n const PERIOD: i64 = 24 * 3600 / NUMBER_TO_INSERT;\n\n\n\n if Path::new(\"test_append_hashes_then_verify.h\").exists() {\n\n fs::remove_file(\"test_append_hashes_then_verify.h\").unwrap();\n\n }\n\n if Path::new(\"test_append_hashes_then_verify.dat\").exists() {\n\n fs::remove_file(\"test_append_hashes_then_verify.dat\").unwrap();\n\n }\n\n\n\n let time = Utc::now();\n\n let mut data = Series::open(\"test_append_hashes_then_verify\", 8).unwrap();\n\n insert_timestamp_hashes(&mut data, NUMBER_TO_INSERT as u32, PERIOD, time);\n\n\n\n let timestamp = time.timestamp();\n\n let t1 = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(timestamp, 0), Utc);\n\n let t2 = DateTime::<Utc>::from_utc(\n\n NaiveDateTime::from_timestamp(timestamp + NUMBER_TO_INSERT * PERIOD, 0),\n\n Utc,\n", "file_path": "tests/append.rs", "rank": 25, "score": 39789.64990382617 }, { "content": "#[test]\n\nfn diff_sine() {\n\n if Path::new(\"test_combiner_diff_sine.h\").exists() {\n\n fs::remove_file(\"test_combiner_diff_sine.h\").unwrap();\n\n }\n\n if Path::new(\"test_combiner_diff_sine.dat\").exists() {\n\n fs::remove_file(\"test_combiner_diff_sine.dat\").unwrap();\n\n }\n\n\n\n let now = Utc::now();\n\n let t1 = now - Duration::hours(2);\n\n let t2 = now;\n\n let n = 200;\n\n\n\n let mut ts = Series::open(\"test_combiner_diff_sine\", 4).unwrap();\n\n let data = sine_array(n, 5.0, 100.0);\n\n insert_vector(&mut ts, t1, t2, &data);\n\n\n\n let decoder = FloatDecoder {};\n\n let mut sampler = new_sampler(&ts, decoder)\n\n .points(n)\n", "file_path": "tests/combine.rs", "rank": 26, "score": 39789.64990382617 }, { "content": "#[test]\n\nfn diff_linear() {\n\n if Path::new(\"test_combiner_diff_linear.h\").exists() {\n\n fs::remove_file(\"test_combiner_diff_linear.h\").unwrap();\n\n }\n\n if Path::new(\"test_combiner_diff_linear.dat\").exists() {\n\n fs::remove_file(\"test_combiner_diff_linear.dat\").unwrap();\n\n }\n\n\n\n let now = Utc::now();\n\n let t1 = now - Duration::hours(2);\n\n let t2 = now;\n\n let n = 10;\n\n let slope = 0.2;\n\n\n\n let mut ts = Series::open(\"test_combiner_diff_linear\", 4).unwrap();\n\n let data = linear_array(n, slope);\n\n insert_vector(&mut ts, t1, t2, &data);\n\n\n\n let decoder = FloatDecoder {};\n\n let mut sampler = new_sampler(&ts, decoder)\n", "file_path": "tests/combine.rs", "rank": 27, "score": 39789.64990382617 }, { "content": "#[test]\n\nfn diff_linear_of_mean() {\n\n if Path::new(\"test_combiner_diff_linear_mean.h\").exists() {\n\n fs::remove_file(\"test_combiner_diff_linear_mean.h\").unwrap();\n\n }\n\n if Path::new(\"test_combiner_diff_linear_mean.dat\").exists() {\n\n fs::remove_file(\"test_combiner_diff_linear_mean.dat\").unwrap();\n\n }\n\n\n\n let now = Utc::now();\n\n let t1 = now - Duration::hours(2);\n\n let t2 = now;\n\n let n = 10;\n\n let slope = 0.2;\n\n\n\n let mut ts = Series::open(\"test_combiner_diff_linear_mean\", 4).unwrap();\n\n let data = linear_array(400, slope);\n\n insert_vector(&mut ts, t1, t2, &data);\n\n\n\n let bin = combiners::SampleBin::new(5);\n\n let first = combiners::Mean::new(bin);\n", "file_path": "tests/combine.rs", "rank": 28, "score": 38579.71973903458 }, { "content": "#[test]\n\nfn hashes_read_skipping_then_verify() {\n\n const NUMBER_TO_INSERT: i64 = 1_007;\n\n const PERIOD: i64 = 24 * 3600 / NUMBER_TO_INSERT;\n\n\n\n if Path::new(\"test_read_skipping_then_verify.h\").exists() {\n\n fs::remove_file(\"test_read_skipping_then_verify.h\").unwrap();\n\n }\n\n if Path::new(\"test_read_skipping_then_verify.dat\").exists() {\n\n fs::remove_file(\"test_read_skipping_then_verify.dat\").unwrap();\n\n }\n\n\n\n let time = Utc::now();\n\n\n\n let mut data = Series::open(\"test_read_skipping_then_verify\", 8).unwrap();\n\n insert_timestamp_hashes(&mut data, NUMBER_TO_INSERT as u32, PERIOD, time);\n\n\n\n let timestamp = time.timestamp();\n\n let t1 = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(timestamp, 0), Utc);\n\n let t2 = DateTime::<Utc>::from_utc(\n\n NaiveDateTime::from_timestamp(timestamp + NUMBER_TO_INSERT * PERIOD, 0),\n", "file_path": "tests/append.rs", "rank": 29, "score": 37489.277142197345 }, { "content": "pub trait NotAssigned: ToAssign {}\n\n\n\nimpl ToAssign for Yes {}\n\nimpl ToAssign for No {}\n\n\n\nimpl Assigned for Yes {}\n\nimpl NotAssigned for No {}\n\n\n\npub struct SamplerBuilder<D, T, StartSet>\n\nwhere\n\n StartSet: ToAssign,\n\n D: Decoder<T>,\n\n T: Debug + Clone,\n\n{\n\n start_set: PhantomData<StartSet>,\n\n decoded: PhantomData<T>,\n\n\n\n series: Series,\n\n decoder: D,\n\n start: Option<chrono::DateTime<chrono::Utc>>,\n\n stop: Option<chrono::DateTime<chrono::Utc>>,\n\n points: Option<usize>,\n\n}\n\n\n", "file_path": "src/sampler/builder.rs", "rank": 30, "score": 36797.46752257254 }, { "content": "pub trait Assigned: ToAssign {}\n", "file_path": "src/sampler/builder.rs", "rank": 31, "score": 36797.46752257254 }, { "content": "pub use crate::search::SeekError;\n\n\n\n#[derive(thiserror::Error, Debug)]\n\npub enum Error {\n\n #[error(\"error acessing filesystem\")]\n\n Io(#[from] std::io::Error),\n\n #[error(\"no data in series\")]\n\n NoData,\n\n #[error(\"file corrupt, got only partial line\")]\n\n PartialLine,\n\n #[error(\"could not find times\")]\n\n Seek(#[from] SeekError),\n\n}\n", "file_path": "src/error.rs", "rank": 32, "score": 27287.51259945187 }, { "content": "#![cfg(test)]\n\n\n\nuse byteseries::error::{Error, SeekError};\n\nuse byteseries::{new_sampler, EmptyDecoder, Series};\n\nuse chrono::{DateTime, NaiveDateTime, Utc};\n\nuse std::fs;\n\nuse std::path::Path;\n\n\n\nmod shared;\n\nuse shared::insert_uniform_arrays;\n\n\n\n#[test]\n", "file_path": "tests/seek.rs", "rank": 33, "score": 27233.003140717065 }, { "content": " let t1 = DateTime::<Utc>::from_utc(\n\n NaiveDateTime::from_timestamp(timestamp + start_read_inlines * STEP, 0),\n\n Utc,\n\n );\n\n let t2 = DateTime::<Utc>::from_utc(\n\n NaiveDateTime::from_timestamp(\n\n timestamp + (start_read_inlines + read_length_inlines) * STEP,\n\n 0,\n\n ),\n\n Utc,\n\n );\n\n\n\n let decoder = EmptyDecoder {};\n\n let sampler = new_sampler(&data, decoder)\n\n .points(10)\n\n .start(t1)\n\n .stop(t2)\n\n .build();\n\n\n\n match sampler {\n", "file_path": "tests/seek.rs", "rank": 34, "score": 27230.40364218513 }, { "content": " Err(e) => match e {\n\n Error::Seek(e) => assert!(\n\n std::mem::discriminant(&e) == std::mem::discriminant(&SeekError::StartAfterData)\n\n ),\n\n _ => panic!(\"sampler should be error StartAfterData\"),\n\n },\n\n Ok(_) => panic!(\"should return an error as we are trying to read beyond the data\"),\n\n }\n\n}\n", "file_path": "tests/seek.rs", "rank": 35, "score": 27223.606308745108 }, { "content": "fn unwrap_result<T>(res: Result<T, T>) -> T {\n\n match res {\n\n Ok(v) => v,\n\n Err(v) => v,\n\n }\n\n}\n\n// https://rust-algo.club/doc/src/rust_algorithm_club/searching/interpolation_search/mod.rs.html#16-69\n\n//\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n fn test_header(n: usize) -> Header {\n\n let path = format!(\"/tmp/test_header_{}.h\", n);\n\n let mut path = std::path::PathBuf::from(path);\n\n if path.exists() {\n\n std::fs::remove_file(&path).unwrap();\n\n }\n\n path.set_extension(\"\");\n\n Header::open(path).unwrap()\n", "file_path": "src/header.rs", "rank": 44, "score": 26823.62129594282 }, { "content": " full_ts.next = None;\n\n full_ts.next_pos = None;\n\n }\n\n }\n\n let timestamp_low = LittleEndian::read_u16(line) as u64;\n\n let timestamp_high = (full_ts.curr as u64 >> 16) << 16;\n\n let timestamp = timestamp_high | timestamp_low;\n\n\n\n T::from_u64(timestamp).unwrap()\n\n }\n\n pub fn read(\n\n &mut self,\n\n buf: &mut [u8],\n\n start_byte: u64,\n\n stop_byte: u64,\n\n ) -> Result<usize, Error> {\n\n self.data.seek(SeekFrom::Start(start_byte))?;\n\n let nread = self.data.read(buf)?;\n\n let left = stop_byte + self.full_line_size as u64 - start_byte;\n\n let nread = nread.min(left as usize);\n", "file_path": "src/data.rs", "rank": 45, "score": 26791.870781457903 }, { "content": " pub first_time_in_data: Option<i64>,\n\n pub last_time_in_data: Option<i64>,\n\n\n\n pub data_size: u64,\n\n}\n\n\n\n// ---------------------------------------------------------------------\n\n// -- we store only the last 4 bytes of the timestamp ------------------\n\n// ---------------------------------------------------------------------\n\n#[derive(Debug)]\n\npub struct FullTime {\n\n pub curr: i64,\n\n pub next: Option<i64>,\n\n pub next_pos: Option<u64>,\n\n}\n\n\n\nimpl ByteSeries {\n\n pub fn open<P: AsRef<Path>>(name: P, line_size: usize) -> Result<ByteSeries, Error> {\n\n let full_line_size = line_size + 2; //+2 accounts for u16 timestamp\n\n let (mut data, size) = open_and_check(name.as_ref().with_extension(\"dat\"), line_size + 2)?;\n", "file_path": "src/data.rs", "rank": 46, "score": 26790.88714780479 }, { "content": " }\n\n\n\n fn get_last_time_in_data(\n\n data: &mut File,\n\n header: &Header,\n\n full_line_size: usize,\n\n ) -> Option<i64> {\n\n let mut buf = [0u8; 2]; //rewrite to use bufferd data\n\n if data.seek(SeekFrom::End(-(full_line_size as i64))).is_ok() {\n\n data.read_exact(&mut buf).unwrap();\n\n let timestamp_low = LittleEndian::read_u16(&buf) as i64;\n\n let timestamp_high = header.last_timestamp & !0b1_1111_1111_1111_1111;\n\n let timestamp = timestamp_high | timestamp_low;\n\n Some(timestamp)\n\n } else {\n\n log::warn!(\"file is empty\");\n\n None\n\n }\n\n }\n\n\n", "file_path": "src/data.rs", "rank": 47, "score": 26789.681064492313 }, { "content": "use byteorder::{ByteOrder, LittleEndian};\n\nuse chrono::{DateTime, Utc};\n\nuse num_traits::cast::FromPrimitive;\n\nuse std::fs::File;\n\nuse std::io::{Read, Seek, SeekFrom, Write};\n\nuse std::path::Path;\n\n\n\nuse crate::header::Header;\n\nuse crate::util::open_and_check;\n\nuse crate::Error;\n\n\n\n#[derive(Debug)]\n\npub struct ByteSeries {\n\n pub data: File,\n\n pub header: Header,\n\n\n\n pub line_size: usize,\n\n pub full_line_size: usize,\n\n timestamp: i64,\n\n\n", "file_path": "src/data.rs", "rank": 48, "score": 26789.32485129213 }, { "content": " timestamps.push(self.get_timestamp::<u64>(line, file_pos, full_ts));\n\n file_pos += self.full_line_size as u64;\n\n line_data.extend_from_slice(&line[2..]);\n\n }\n\n Ok((timestamps, line_data))\n\n }\n\n pub fn decode_last_line(&mut self) -> Result<(i64, Vec<u8>), Error> {\n\n if self.data_size < self.full_line_size as u64 {\n\n return Err(Error::NoData);\n\n }\n\n\n\n let start_byte = self.data_size - self.full_line_size as u64;\n\n let stop_byte = self.data_size;\n\n\n\n let mut full_line = vec![0; self.full_line_size];\n\n let nread = self.read(&mut full_line, start_byte, stop_byte)?;\n\n\n\n if nread < self.full_line_size {\n\n return Err(Error::PartialLine);\n\n }\n\n\n\n full_line.remove(0);\n\n full_line.remove(0);\n\n let line = full_line;\n\n let time = self.last_time_in_data.ok_or(Error::NoData)?;\n\n Ok((time, line))\n\n }\n\n}\n", "file_path": "src/data.rs", "rank": 49, "score": 26786.846261498842 }, { "content": " let nread = nread - nread % self.full_line_size;\n\n Ok(nread)\n\n }\n\n\n\n pub fn decode_time(\n\n &mut self,\n\n lines_to_read: usize,\n\n start_byte: u64,\n\n stop_byte: u64,\n\n full_ts: &mut FullTime,\n\n ) -> Result<(Vec<u64>, Vec<u8>), Error> {\n\n let mut buf = vec![0; lines_to_read * self.full_line_size];\n\n\n\n let mut timestamps: Vec<u64> = Vec::with_capacity(lines_to_read);\n\n let mut line_data: Vec<u8> = Vec::with_capacity(lines_to_read);\n\n //save file pos indicator before read call moves it around\n\n let mut file_pos = start_byte;\n\n let n_read = self.read(&mut buf, start_byte, stop_byte)? as usize;\n\n log::trace!(\"read: {} bytes\", n_read);\n\n for line in buf[..n_read].chunks(self.full_line_size) {\n", "file_path": "src/data.rs", "rank": 50, "score": 26786.420531187563 }, { "content": " pub fn append(&mut self, time: DateTime<Utc>, line: &[u8]) -> Result<(), Error> {\n\n self.append_fast(time, line)?;\n\n self.force_write_to_disk();\n\n Ok(())\n\n }\n\n\n\n pub fn append_fast(&mut self, time: DateTime<Utc>, line: &[u8]) -> Result<(), Error> {\n\n //TODO decide if a lock is needed here\n\n //write 16 bit timestamp and then the line to file\n\n let timestamp = self.time_to_line_timestamp(time);\n\n self.data.write_all(&timestamp)?;\n\n self.data.write_all(&line[..self.line_size])?;\n\n\n\n //write 64 bit timestamp to header\n\n //(needed no more then once every 18 hours)\n\n self.update_header()?;\n\n self.data_size += self.full_line_size as u64;\n\n\n\n self.last_time_in_data = Some(time.timestamp());\n\n self.first_time_in_data.get_or_insert(time.timestamp());\n", "file_path": "src/data.rs", "rank": 51, "score": 26785.56735558703 }, { "content": " Ok(())\n\n }\n\n\n\n // needs to be called before self.data_size is increased\n\n fn update_header(&mut self) -> Result<(), Error> {\n\n let new_timestamp_numb = self.timestamp / 2i64.pow(16);\n\n if new_timestamp_numb > self.header.last_timestamp_numb {\n\n log::info!(\"updating file header\");\n\n let line_start = self.data_size;\n\n self.header\n\n .update(self.timestamp, line_start, new_timestamp_numb)?;\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn force_write_to_disk(&mut self) {\n\n self.data.sync_data().unwrap();\n\n self.header.file.sync_data().unwrap();\n\n }\n\n\n", "file_path": "src/data.rs", "rank": 52, "score": 26784.03608711059 }, { "content": " let header = Header::open(name)?;\n\n\n\n let first_time = header.first_time_in_data();\n\n let last_time = Self::get_last_time_in_data(&mut data, &header, full_line_size);\n\n\n\n Ok(ByteSeries {\n\n data,\n\n header, // add triple headers\n\n\n\n line_size,\n\n full_line_size, //+2 accounts for u16 timestamp\n\n timestamp: 0,\n\n\n\n first_time_in_data: first_time,\n\n last_time_in_data: last_time,\n\n\n\n //these are set during: set_read_start, set_read_end then read is\n\n //bound by these points\n\n data_size: size,\n\n })\n", "file_path": "src/data.rs", "rank": 53, "score": 26783.325567326756 }, { "content": " fn time_to_line_timestamp(&mut self, time: DateTime<Utc>) -> [u8; 2] {\n\n //for now no support for sign bit since data will always be after 0 (1970)\n\n self.timestamp = time.timestamp().abs();\n\n\n\n //we store the timestamp in little endian Signed magnitude representation\n\n //(least significant (lowest value) byte at lowest adress)\n\n //for the line timestamp we use only the 2 lower bytes\n\n let mut line_timestamp = [0; 2];\n\n LittleEndian::write_u16(&mut line_timestamp, self.timestamp as u16);\n\n line_timestamp\n\n }\n\n\n\n pub fn get_timestamp<T>(&mut self, line: &[u8], pos: u64, full_ts: &mut FullTime) -> T\n\n where\n\n T: FromPrimitive,\n\n {\n\n //update full timestamp when needed\n\n if full_ts\n\n .next_pos\n\n .map_or(false, |next_pos| pos + 1 > next_pos)\n", "file_path": "src/data.rs", "rank": 54, "score": 26780.78873749802 }, { "content": " {\n\n log::debug!(\n\n \"updating ts, pos: {:?}, next ts pos: {:?}\",\n\n pos,\n\n full_ts.next_pos\n\n );\n\n //update current timestamp\n\n full_ts.curr = full_ts.next.unwrap();\n\n\n\n //set next timestamp and timestamp pos\n\n //minimum in map greater then current timestamp\n\n if let Some(next) = self.header.next_full_timestamp(full_ts.curr) {\n\n full_ts.next = Some(next.timestamp);\n\n full_ts.next_pos = Some(next.pos);\n\n } else {\n\n //TODO handle edge case, last full timestamp\n\n log::debug!(\n\n \"loaded last timestamp in header, no next TS, current pos: {}\",\n\n pos\n\n );\n", "file_path": "src/data.rs", "rank": 55, "score": 26775.52082120159 }, { "content": " let SamplerBuilder {\n\n series,\n\n mut decoder,\n\n start,\n\n stop,\n\n points,\n\n ..\n\n } = self;\n\n let mut byteseries = series.shared.lock().unwrap();\n\n\n\n let stop = stop\n\n .or_else(|| {\n\n byteseries\n\n .last_time_in_data\n\n .map(|ts| DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(ts, 0), Utc))\n\n })\n\n .ok_or(Error::NoData)?;\n\n let seek = TimeSeek::new(&mut byteseries, start.unwrap(), stop)?;\n\n\n\n let lines = seek.lines(&byteseries);\n", "file_path": "src/sampler/builder.rs", "rank": 56, "score": 31.958227861998054 }, { "content": "use chrono::{DateTime, NaiveDateTime, Utc};\n\nuse std::path::Path;\n\nuse std::sync::{Arc, Mutex, MutexGuard};\n\n\n\nmod data;\n\npub mod error;\n\nmod header;\n\nmod sampler;\n\nmod search;\n\nmod util;\n\n\n\nuse data::ByteSeries;\n\npub use error::Error;\n\npub use sampler::{\n\n combiners, new_sampler, Decoder, EmptyDecoder, SampleCombiner, Sampler, SamplerBuilder,\n\n};\n\npub use search::TimeSeek;\n\n\n\n#[derive(Debug, Clone)]\n\npub struct Series {\n", "file_path": "src/lib.rs", "rank": 57, "score": 25.875194418949263 }, { "content": " shared: Arc<Mutex<data::ByteSeries>>,\n\n}\n\n\n\nimpl Series {\n\n fn lock<'a>(&'a self) -> MutexGuard<'a, data::ByteSeries> {\n\n self.shared.lock().unwrap()\n\n }\n\n\n\n pub fn open<P: AsRef<Path>>(name: P, line_size: usize) -> Result<Self, Error> {\n\n let series = ByteSeries::open(name, line_size)?;\n\n Ok(Self {\n\n shared: Arc::new(Mutex::new(series)),\n\n })\n\n }\n\n\n\n pub fn last_line<'a, T: std::fmt::Debug + std::clone::Clone>(\n\n &self,\n\n decoder: &'a mut (dyn Decoder<T> + 'a),\n\n ) -> Result<(DateTime<Utc>, Vec<T>), Error> {\n\n let mut series = self.lock();\n", "file_path": "src/lib.rs", "rank": 58, "score": 24.665532435529688 }, { "content": " let (time, bytes) = series.decode_last_line()?;\n\n let time = DateTime::from_utc(NaiveDateTime::from_timestamp(time, 0), Utc);\n\n let data = decoder.decoded(&bytes);\n\n Ok((time, data))\n\n }\n\n\n\n pub fn last_line_raw(&self) -> Result<(DateTime<Utc>, Vec<u8>), Error> {\n\n let mut series = self.lock();\n\n let (time, bytes) = series.decode_last_line()?;\n\n let time = DateTime::from_utc(NaiveDateTime::from_timestamp(time, 0), Utc);\n\n Ok((time, bytes))\n\n }\n\n\n\n pub fn append(&self, time: DateTime<Utc>, line: &[u8]) -> Result<(), Error> {\n\n let mut series = self.lock();\n\n series.append(time, line)?;\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 59, "score": 22.546893907203142 }, { "content": " D: Decoder<T>,\n\n StartSet: ToAssign,\n\n{\n\n /// set the start time\n\n pub fn start(self, start: chrono::DateTime<chrono::Utc>) -> SamplerBuilder<D, T, Yes> {\n\n SamplerBuilder {\n\n start_set: PhantomData {},\n\n decoded: PhantomData {},\n\n series: self.series,\n\n decoder: self.decoder,\n\n start: Some(start),\n\n stop: self.stop,\n\n points: self.points,\n\n }\n\n }\n\n /// set the stop time\n\n pub fn stop(mut self, stop: chrono::DateTime<chrono::Utc>) -> Self {\n\n self.stop = Some(stop);\n\n self\n\n }\n", "file_path": "src/sampler/builder.rs", "rank": 60, "score": 22.133422385007975 }, { "content": " pub last_timestamp: i64,\n\n pub last_timestamp_numb: i64,\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum SearchBounds {\n\n Found(u64),\n\n Clipped,\n\n TillEnd(u64),\n\n Window(u64, u64),\n\n}\n\n\n\nimpl Header {\n\n pub fn open<P: AsRef<Path>>(name: P) -> Result<Header, Error> {\n\n let (mut file, _) = open_and_check(name.as_ref().with_extension(\"h\"), 16)?;\n\n\n\n let mut bytes = Vec::new();\n\n file.read_to_end(&mut bytes)?;\n\n let mut numbers = vec![0u64; bytes.len() / 8];\n\n LittleEndian::read_u64_into(&bytes, numbers.as_mut_slice());\n", "file_path": "src/header.rs", "rank": 61, "score": 21.080304008162063 }, { "content": " }\n\n\n\n pub fn search_bounds(&self, start: i64, stop: i64) -> (SearchBounds, SearchBounds, FullTime) {\n\n let idx = self.data.binary_search_by_key(&start, |e| e.timestamp);\n\n let (start_bound, full_time) = match idx {\n\n Ok(i) => (\n\n SearchBounds::Found(self.data[i].pos),\n\n FullTime {\n\n curr: start,\n\n next: self.data.get(i + 1).map(|e| e.timestamp),\n\n next_pos: self.data.get(i + 1).map(|e| e.pos),\n\n },\n\n ),\n\n Err(end) => {\n\n if end == 0 {\n\n //start lies before file\n\n (\n\n SearchBounds::Clipped,\n\n FullTime {\n\n curr: self.data[0].timestamp,\n", "file_path": "src/header.rs", "rank": 62, "score": 20.52612281280278 }, { "content": "use byteorder::{ByteOrder, LittleEndian, WriteBytesExt};\n\nuse std::fs::File;\n\nuse std::io::Read;\n\nuse std::path::Path;\n\n\n\nuse crate::data::FullTime;\n\nuse crate::util::open_and_check;\n\nuse crate::Error;\n\n\n\n#[derive(Debug)]\n\npub struct Entry {\n\n pub timestamp: i64,\n\n pub pos: u64,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Header {\n\n pub file: File,\n\n\n\n pub data: Vec<Entry>,\n", "file_path": "src/header.rs", "rank": 63, "score": 20.241442186370104 }, { "content": " })\n\n }\n\n\n\n pub fn update(\n\n &mut self,\n\n timestamp: i64,\n\n line_start: u64,\n\n new_timestamp_numb: i64,\n\n ) -> Result<(), Error> {\n\n let ts = timestamp as u64;\n\n self.file.write_u64::<LittleEndian>(ts)?;\n\n self.file.write_u64::<LittleEndian>(line_start)?;\n\n log::trace!(\"wrote headerline: {}, {}\", ts, line_start);\n\n\n\n self.data.push(Entry {\n\n timestamp,\n\n pos: line_start,\n\n });\n\n self.last_timestamp_numb = new_timestamp_numb;\n\n Ok(())\n", "file_path": "src/header.rs", "rank": 64, "score": 20.210938605714105 }, { "content": "use crate::{Error, Series, TimeSeek};\n\nuse std::clone::Clone;\n\nuse std::fmt::Debug;\n\n\n\nmod builder;\n\npub mod combiners;\n\nmod decoders;\n\npub use builder::{new_sampler, SamplerBuilder};\n\npub use combiners::SampleCombiner;\n\npub use decoders::{Decoder, EmptyDecoder};\n\n\n\npub struct Sampler<D, T, C> {\n\n series: Series,\n\n selector: Option<Selector>,\n\n decoder: D, //check if generic better fit\n\n combiner: C,\n\n seek: TimeSeek,\n\n\n\n time: Vec<i64>,\n\n values: Vec<T>,\n", "file_path": "src/sampler/mod.rs", "rank": 65, "score": 20.15070310498167 }, { "content": " for (line, pos) in self.buff[..n_read]\n\n .chunks(full_line_size)\n\n .zip((seek.curr..).step_by(full_line_size))\n\n .filter(|_| selector.as_mut().map(|s| s.use_index()).unwrap_or(true))\n\n {\n\n let time = byteseries.get_timestamp::<i64>(line, pos, &mut seek.full_time);\n\n let values = self.decoder.decoded(&line[2..]);\n\n if let Some((t, combined)) = self.combiner.process(time, values) {\n\n self.values.extend(combined.into_iter());\n\n self.time.push(t);\n\n }\n\n }\n\n seek.curr += n_read as u64;\n\n drop(byteseries);\n\n Ok(())\n\n }\n\n ///returns true if this sampler has read its entire range\n\n pub fn done(&self) -> bool {\n\n self.seek.curr >= self.seek.stop\n\n }\n", "file_path": "src/sampler/mod.rs", "rank": 66, "score": 20.12217242093803 }, { "content": " //end is not 0 or 1 thus data[end] and data[end-1] exist\n\n SearchBounds::Window(self.data[end - 1].pos, self.data[end].pos)\n\n }\n\n }\n\n };\n\n (start_bound, stop_bound, full_time)\n\n }\n\n pub fn first_time_in_data(&self) -> Option<i64> {\n\n self.data.first().map(|e| e.timestamp)\n\n }\n\n\n\n pub fn next_full_timestamp(&self, curr: i64) -> Option<&Entry> {\n\n let i = self.data.binary_search_by_key(&(curr + 1), |e| e.timestamp);\n\n let i = unwrap_result(i);\n\n self.data.get(i)\n\n }\n\n}\n\n\n", "file_path": "src/header.rs", "rank": 67, "score": 19.948819263000317 }, { "content": " }\n\n }\n\n Ok(())\n\n }\n\n ///decodes and averages enough lines to get n samples unless the end of the file\n\n ///given range is reached\n\n pub fn sample(&mut self) -> Result<(), Error> {\n\n self.time.reserve_exact(self.values.len());\n\n self.values\n\n .reserve_exact(self.values.len() + self.decoded_per_line);\n\n\n\n let series = self.series.clone();\n\n let mut byteseries = series.lock();\n\n\n\n let seek = &mut self.seek;\n\n let selector = &mut self.selector;\n\n let full_line_size = byteseries.full_line_size;\n\n\n\n let n_read = byteseries.read(&mut self.buff, seek.curr, seek.stop)?;\n\n\n", "file_path": "src/sampler/mod.rs", "rank": 68, "score": 19.42539348890033 }, { "content": "use super::{combiners, Decoder, SampleCombiner, Sampler, Selector};\n\n\n\nuse crate::{Error, Series, TimeSeek};\n\nuse chrono::{DateTime, NaiveDateTime, Utc};\n\nuse std::default::Default;\n\nuse std::fmt::Debug;\n\nuse std::marker::PhantomData;\n\n\n\n//some stuff to create the builder struct\n\n//see: https://dev.to/mindflavor/rust-builder-pattern-with-types-3chf\n\n#[derive(Debug, Default)]\n\npub struct Yes;\n\n#[derive(Debug, Default)]\n\npub struct No;\n\n\n", "file_path": "src/sampler/builder.rs", "rank": 69, "score": 19.154599581925655 }, { "content": "impl Selector {\n\n pub fn new(\n\n mut max_plot_points: usize,\n\n n_lines: u64,\n\n binsize: usize,\n\n offset: usize,\n\n ) -> Option<Self> {\n\n max_plot_points += offset;\n\n max_plot_points *= binsize;\n\n if n_lines as usize <= max_plot_points {\n\n return None;\n\n }\n\n\n\n let spacing = n_lines as f32 / max_plot_points as f32;\n\n Some(Self {\n\n spacing,\n\n next_to_use: 0, //spacing/2.0) as u64,\n\n line: 0,\n\n used: 0,\n\n })\n", "file_path": "src/sampler/mod.rs", "rank": 70, "score": 17.99846541188041 }, { "content": " }\n\n fn fill_header(h: &mut Header) {\n\n for i in 20..24 {\n\n let ts = i * 2i64.pow(16);\n\n let new_timestamp_numb = ts / 2i64.pow(16);\n\n h.update(ts, i as u64, new_timestamp_numb).unwrap();\n\n }\n\n }\n\n\n\n #[test]\n\n fn start_found() {\n\n let mut h = test_header(0);\n\n fill_header(&mut h);\n\n let start = 22 * 2i64.pow(16);\n\n let stop = 23 * 2i64.pow(16);\n\n let (start, _stop, ft) = h.search_bounds(start, stop);\n\n assert_eq!(\n\n std::mem::discriminant(&start),\n\n std::mem::discriminant(&SearchBounds::Found(0))\n\n );\n", "file_path": "src/header.rs", "rank": 71, "score": 17.41755552340569 }, { "content": " C: SampleCombiner<T>,\n\n D: Decoder<T>,\n\n{\n\n type Item = (i64, T);\n\n type IntoIter = std::iter::Zip<std::vec::IntoIter<i64>, std::vec::IntoIter<T>>;\n\n\n\n fn into_iter(self) -> Self::IntoIter {\n\n let (time, values) = self.into_data();\n\n time.into_iter().zip(values.into_iter())\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Selector {\n\n spacing: f32, //in lines\n\n next_to_use: u64,\n\n line: u64, //starts at 0\n\n used: u64,\n\n}\n\n\n", "file_path": "src/sampler/mod.rs", "rank": 72, "score": 16.334992458073664 }, { "content": " /// set the number of points to read\n\n pub fn points(mut self, n: usize) -> Self {\n\n self.points = Some(n);\n\n self\n\n }\n\n}\n\n\n\nimpl<D, T> SamplerBuilder<D, T, Yes>\n\nwhere\n\n T: Debug + Clone + Default,\n\n D: Decoder<T>,\n\n{\n\n pub fn build(self) -> Result<Sampler<D, T, combiners::Empty>, Error> {\n\n self.build_with_combiner(combiners::Empty::default())\n\n }\n\n\n\n pub fn build_with_combiner<C>(self, mut combiner: C) -> Result<Sampler<D, T, C>, Error>\n\n where\n\n C: SampleCombiner<T>,\n\n {\n", "file_path": "src/sampler/builder.rs", "rank": 73, "score": 16.31289168575153 }, { "content": " next: self.data.get(1).map(|e| e.timestamp),\n\n next_pos: self.data.get(1).map(|e| e.pos),\n\n },\n\n )\n\n } else if end == self.data.len() {\n\n (\n\n SearchBounds::TillEnd(self.data.last().unwrap().pos),\n\n FullTime {\n\n curr: self.data.last().unwrap().timestamp,\n\n next: None, //there is no full timestamp beyond the end\n\n next_pos: None,\n\n },\n\n )\n\n } else {\n\n //end is not 0 or 1 thus data[end] and data[end-1] exist\n\n (\n\n SearchBounds::Window(self.data[end - 1].pos, self.data[end].pos),\n\n FullTime {\n\n curr: self.data[end - 1].timestamp,\n\n next: Some(self.data[end].timestamp),\n", "file_path": "src/header.rs", "rank": 74, "score": 16.243794780594992 }, { "content": " let t2 = DateTime::<Utc>::from_utc(\n\n NaiveDateTime::from_timestamp(timestamp + NUMBER_TO_INSERT * PERIOD, 0),\n\n Utc,\n\n );\n\n\n\n let n = 8_000;\n\n let decoder = TimestampDecoder {};\n\n let mut sampler = new_sampler(&data, decoder)\n\n .points(n)\n\n .start(t1)\n\n .stop(t2)\n\n .build()\n\n .unwrap();\n\n sampler.sample_all().unwrap();\n\n\n\n assert_eq!(sampler.values().len(), n);\n\n let mut prev = None;\n\n for (i, (timestamp, decoded)) in sampler.into_iter().enumerate() {\n\n let correct = timestamp as i64;\n\n assert_eq!(\n\n decoded, correct,\n\n \"failed on element: {}, which should have ts: {}, but has been given {},\n\n prev element has ts: {:?}, the step is: {}\",\n\n i, timestamp, decoded, prev, PERIOD\n\n );\n\n prev = Some(timestamp);\n\n }\n\n}\n", "file_path": "tests/append.rs", "rank": 75, "score": 15.794759617725772 }, { "content": " next_pos: Some(self.data[end].pos),\n\n },\n\n )\n\n }\n\n }\n\n };\n\n let idx = self.data.binary_search_by_key(&stop, |e| e.timestamp);\n\n let stop_bound = match idx {\n\n Ok(i) => SearchBounds::Found(self.data[i].pos),\n\n Err(end) => {\n\n if end == 0 {\n\n //stop lies before file\n\n panic!(\n\n \"stop lying before start of data should be caught\n\n before calling search_bounds. We should never reach\n\n this\"\n\n )\n\n } else if end == self.data.len() {\n\n SearchBounds::TillEnd(self.data.last().unwrap().pos)\n\n } else {\n", "file_path": "src/header.rs", "rank": 76, "score": 15.016895096420892 }, { "content": "use byteseries::{new_sampler, EmptyDecoder, Series};\n\nuse chrono::Duration;\n\n\n", "file_path": "examples/skip.rs", "rank": 77, "score": 14.821718847858666 }, { "content": "#![cfg(test)]\n\n\n\nuse byteorder::{ByteOrder, NativeEndian};\n\nuse byteseries::{new_sampler, Decoder, Series};\n\nuse chrono::{DateTime, NaiveDateTime, Utc};\n\nuse fern::colors::{Color, ColoredLevelConfig};\n\nuse fxhash::hash64;\n\nuse std::fs;\n\nuse std::path::Path;\n\n\n\nmod shared;\n\nuse shared::{insert_timestamp_arrays, insert_timestamp_hashes, insert_uniform_arrays};\n\n\n\n#[allow(dead_code)]\n", "file_path": "tests/append.rs", "rank": 78, "score": 14.728306224830956 }, { "content": "pub struct TimeBin {\n\n period: i64,\n\n first: Option<i64>,\n\n}\n\nimpl TimeBin {\n\n pub fn new(period: chrono::Duration) -> Self {\n\n Self {\n\n period: period.num_seconds(),\n\n first: None,\n\n }\n\n }\n\n}\n\n\n\nimpl Bin for TimeBin {\n\n fn update_bin(&mut self, t: i64) -> Option<i64> {\n\n if let Some(s) = self.first {\n\n if t - s > self.period {\n\n Some(self.first.take().unwrap() + self.period / 2)\n\n } else {\n\n None\n", "file_path": "src/sampler/combiners.rs", "rank": 79, "score": 14.366997560555715 }, { "content": "use byteseries::{combiners, new_sampler, Decoder, Series};\n\nuse chrono::Duration;\n\n\n\n#[derive(Debug)]\n", "file_path": "examples/mean.rs", "rank": 80, "score": 14.23570466147456 }, { "content": "#[derive(Debug, Clone)]\n\npub struct Mean<B> {\n\n v_sum: Vec<f32>,\n\n t_sum: i64,\n\n n: usize,\n\n bin: B,\n\n}\n\n\n\nimpl<B> Mean<B> {\n\n pub fn new(bin: B) -> Self {\n\n Mean {\n\n v_sum: Vec::new(),\n\n t_sum: 0,\n\n n: 0,\n\n bin,\n\n }\n\n }\n\n}\n\n\n\nimpl<B> SampleCombiner<f32> for Mean<B>\n", "file_path": "src/sampler/combiners.rs", "rank": 81, "score": 14.156598293784871 }, { "content": " buff: Vec<u8>,\n\n decoded_per_line: usize,\n\n}\n\n\n\nimpl<D, T, C> Debug for Sampler<D, T, C>\n\nwhere\n\n T: Clone + Debug,\n\n C: Debug,\n\n D: Debug,\n\n{\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n //only print first n values\n\n let time = self.time[..5.min(self.time.len())].to_vec();\n\n let values = self.values[..5.min(self.time.len())].to_vec();\n\n let buff = self.buff[..5.min(self.time.len())].to_vec();\n\n f.debug_struct(\"Sampler\")\n\n .field(\"series\", &self.series)\n\n .field(\"selector\", &self.selector)\n\n .field(\"decoder\", &self.decoder)\n\n .field(\"combiner\", &self.combiner)\n", "file_path": "src/sampler/mod.rs", "rank": 82, "score": 14.125426392005494 }, { "content": "#![cfg(test)]\n\n\n\nuse byteseries::{combiners, new_sampler, Decoder, Series};\n\nuse chrono::{DateTime, Duration, Utc};\n\nuse float_eq::assert_float_eq;\n\nuse std::f32::consts::PI;\n\nuse std::fs;\n\nuse std::path::Path;\n\n\n", "file_path": "tests/combine.rs", "rank": 83, "score": 14.00623230379896 }, { "content": " Utc,\n\n );\n\n\n\n let n = 100;\n\n let decoder = HashDecoder {};\n\n let mut sampler = new_sampler(&data, decoder)\n\n .points(n)\n\n .start(t1)\n\n .stop(t2)\n\n .build()\n\n .unwrap();\n\n sampler.sample_all().unwrap();\n\n\n\n assert_eq!(sampler.values().len(), n);\n\n for (timestamp, hash) in sampler.into_iter() {\n\n let correct = hash64::<i64>(&(timestamp as i64));\n\n assert_eq!(hash, correct);\n\n }\n\n}\n\n\n", "file_path": "tests/append.rs", "rank": 84, "score": 13.960089124739767 }, { "content": " ///swap the time and values vectors with the given ones, returning the\n\n ///original\n\n pub fn swap_data(&mut self, times: &mut Vec<i64>, value: &mut Vec<T>) {\n\n std::mem::swap(&mut self.time, times);\n\n std::mem::swap(&mut self.values, value);\n\n }\n\n ///de-constructs the sampler into the time and values data\n\n pub fn into_data(self) -> (Vec<i64>, Vec<T>) {\n\n let Sampler { time, values, .. } = self;\n\n (time, values)\n\n }\n\n ///return the read values as slice\n\n pub fn values(&self) -> &[T] {\n\n &self.values\n\n }\n\n}\n\n\n\nimpl<D, T, C> std::iter::IntoIterator for Sampler<D, T, C>\n\nwhere\n\n T: Debug + Clone,\n", "file_path": "src/sampler/mod.rs", "rank": 85, "score": 13.839008700119935 }, { "content": " .field(\"seek\", &self.seek)\n\n .field(\"time\", &time)\n\n .field(\"values\", &values)\n\n .field(\"buff\", &buff)\n\n .field(\"decoded_per_line\", &self.decoded_per_line)\n\n .finish()\n\n }\n\n}\n\n\n\nimpl<D, T, C> Sampler<D, T, C>\n\nwhere\n\n C: SampleCombiner<T>,\n\n T: Debug + Clone,\n\n D: Decoder<T>,\n\n{\n\n pub fn sample_all(&mut self) -> Result<(), Error> {\n\n loop {\n\n self.sample()?;\n\n if self.done() {\n\n break;\n", "file_path": "src/sampler/mod.rs", "rank": 86, "score": 13.539529412305939 }, { "content": "use byteseries::{combiners, new_sampler, Decoder, Series};\n\nuse chrono::Duration;\n\nuse simplelog::{Config, LevelFilter, SimpleLogger};\n\n\n\n#[derive(Debug)]\n", "file_path": "examples/100d.rs", "rank": 87, "score": 13.29707223436466 }, { "content": "\n\n let mut data = Vec::new();\n\n for i in (0..numbers.len()).step_by(2) {\n\n data.push(Entry {\n\n timestamp: numbers[i] as i64,\n\n pos: numbers[i + 1],\n\n });\n\n }\n\n\n\n let last_timestamp = numbers\n\n .get(numbers.len().saturating_sub(2))\n\n .map(|n| *n as i64)\n\n .unwrap_or(0);\n\n\n\n log::trace!(\"last_timestamp: {}\", last_timestamp);\n\n Ok(Header {\n\n file,\n\n data,\n\n last_timestamp,\n\n last_timestamp_numb: last_timestamp / (u16::max_value() as i64),\n", "file_path": "src/header.rs", "rank": 88, "score": 13.19106174446518 }, { "content": "#![allow(dead_code, unused_imports)]\n\nuse byteorder::{ByteOrder, NativeEndian, WriteBytesExt};\n\nuse byteseries::Series;\n\nuse chrono::{DateTime, NaiveDateTime, Utc};\n\nuse fxhash::hash64;\n\n\n", "file_path": "tests/shared.rs", "rank": 89, "score": 12.821407822282602 }, { "content": " );\n\n\n\n let n = 8_000;\n\n let decoder = HashDecoder {};\n\n let mut sampler = new_sampler(&data, decoder)\n\n .points(n)\n\n .start(t1)\n\n .stop(t2)\n\n .build()\n\n .unwrap();\n\n\n\n sampler.sample_all().unwrap();\n\n\n\n for (timestamp, hash) in sampler.into_iter() {\n\n let correct = hash64::<i64>(&(timestamp as i64));\n\n assert_eq!(hash, correct);\n\n }\n\n}\n\n\n", "file_path": "tests/append.rs", "rank": 90, "score": 12.774817711875976 }, { "content": " B: SampleCombiner<f32>,\n\n{\n\n #[allow(dead_code)]\n\n pub fn new(a: A, b: B) -> Self {\n\n Self { a, b }\n\n }\n\n}\n\n\n\nimpl<A, B> SampleCombiner<f32> for Combiner<A, B>\n\nwhere\n\n A: SampleCombiner<f32>,\n\n B: SampleCombiner<f32>,\n\n{\n\n fn process(&mut self, time: i64, values: Vec<f32>) -> Option<(i64, Vec<f32>)> {\n\n if let Some((time, values)) = self.a.process(time, values) {\n\n if let Some((time, values)) = self.b.process(time, values) {\n\n return Some((time, values));\n\n }\n\n }\n\n None\n", "file_path": "src/sampler/combiners.rs", "rank": 91, "score": 12.484398729526779 }, { "content": " let mut h = test_header(2);\n\n fill_header(&mut h);\n\n let start = 22 * 2i64.pow(16) + 400;\n\n let stop = 23 * 2i64.pow(16);\n\n let (start, _stop, ft) = h.search_bounds(start, stop);\n\n\n\n assert_eq!(\n\n std::mem::discriminant(&start),\n\n std::mem::discriminant(&SearchBounds::Window(0, 0))\n\n );\n\n assert!(ft.next.is_some());\n\n assert!(ft.next_pos.is_some());\n\n }\n\n #[test]\n\n fn start_till_end() {\n\n let mut h = test_header(3);\n\n fill_header(&mut h);\n\n let start = 24 * 2i64.pow(16) + 400;\n\n let stop = 25 * 2i64.pow(16);\n\n let (start, _stop, ft) = h.search_bounds(start, stop);\n", "file_path": "src/header.rs", "rank": 92, "score": 12.31401799279881 }, { "content": " assert!(ft.next.is_some());\n\n assert!(ft.next_pos.is_some());\n\n }\n\n #[test]\n\n fn start_clipped() {\n\n let mut h = test_header(1);\n\n fill_header(&mut h);\n\n let start = 12342;\n\n let stop = 23 * 2i64.pow(16);\n\n let (start, _stop, ft) = h.search_bounds(start, stop);\n\n\n\n assert_eq!(\n\n std::mem::discriminant(&start),\n\n std::mem::discriminant(&SearchBounds::Clipped)\n\n );\n\n assert!(ft.next.is_some());\n\n assert!(ft.next_pos.is_some());\n\n }\n\n #[test]\n\n fn start_window() {\n", "file_path": "src/header.rs", "rank": 93, "score": 11.08117208809102 }, { "content": " let selector = points\n\n .map(|p| Selector::new(p, lines, combiner.binsize(), combiner.binoffset()))\n\n .flatten();\n\n\n\n let dummy = vec![0u8; byteseries.full_line_size];\n\n let decoded_per_line = decoder.decoded(&dummy).len();\n\n combiner.set_decoded_size(decoded_per_line);\n\n drop(byteseries);\n\n\n\n Ok(Sampler {\n\n series,\n\n selector,\n\n decoder,\n\n combiner,\n\n seek,\n\n time: Vec::new(),\n\n values: Vec::new(),\n\n buff: vec![0u8; 64_000],\n\n decoded_per_line,\n\n })\n\n }\n\n}\n", "file_path": "src/sampler/builder.rs", "rank": 94, "score": 10.214560367932895 }, { "content": " self.bin.binsize()\n\n }\n\n fn set_decoded_size(&mut self, n_values: usize) {\n\n self.v_sum = vec![0.0; n_values];\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Default)]\n\npub struct Combiner<A, B>\n\nwhere\n\n A: SampleCombiner<f32>,\n\n B: SampleCombiner<f32>,\n\n{\n\n a: A,\n\n b: B,\n\n}\n\n\n\nimpl<A, B> Combiner<A, B>\n\nwhere\n\n A: SampleCombiner<f32>,\n", "file_path": "src/sampler/combiners.rs", "rank": 95, "score": 10.136696254074618 }, { "content": "use std::fs::{File, OpenOptions};\n\nuse std::io::Error;\n\nuse std::path::PathBuf;\n\n\n\n//open file and check if it has the right lenght\n\n//(an interger multiple of the line lenght) if it\n\n//has not warn and repair by truncating\n", "file_path": "src/util.rs", "rank": 96, "score": 10.116209134557039 }, { "content": " }\n\n fn set_decoded_size(&mut self, n_values: usize) {\n\n self.a.set_decoded_size(n_values);\n\n self.b.set_decoded_size(n_values);\n\n }\n\n fn binsize(&self) -> usize {\n\n self.a.binsize() * self.b.binsize()\n\n }\n\n fn binoffset(&self) -> usize {\n\n self.a.binoffset() * self.b.binsize() + self.b.binoffset()\n\n }\n\n}\n\n\n\n//minimum sample size is 2\n\n#[derive(Debug, Clone, Default)]\n\npub struct Differentiate {\n\n pair_1: Option<(i64, Vec<f32>)>,\n\n}\n\nimpl SampleCombiner<f32> for Differentiate {\n\n fn process(&mut self, t2: i64, v2: Vec<f32>) -> Option<(i64, Vec<f32>)> {\n", "file_path": "src/sampler/combiners.rs", "rank": 97, "score": 10.107923702357045 }, { "content": "\n\nimpl Bin for SampleBin {\n\n fn update_bin(&mut self, t: i64) -> Option<i64> {\n\n self.n += 1;\n\n self.t_sum += t;\n\n if self.n >= self.binsize {\n\n let t = self.t_sum / (self.binsize as i64);\n\n self.t_sum = 0;\n\n self.n = 0;\n\n Some(t)\n\n } else {\n\n None\n\n }\n\n }\n\n fn binsize(&self) -> usize {\n\n self.binsize\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n", "file_path": "src/sampler/combiners.rs", "rank": 98, "score": 9.343628941728536 }, { "content": " let mut sampler = new_sampler(&ts, decoder)\n\n .points(n)\n\n .start(t1)\n\n .stop(t2)\n\n .build_with_combiner(combiner)\n\n .unwrap();\n\n sampler.sample_all().unwrap();\n\n\n\n assert_eq!(sampler.values().len(), n / s);\n\n for (sample, mean) in sampler\n\n .values()\n\n .iter()\n\n .zip(data.chunks(s).map(|c| c.iter().sum::<f32>() / (s as f32)))\n\n {\n\n assert_eq!(*sample, mean);\n\n }\n\n}\n\n\n", "file_path": "tests/combine.rs", "rank": 99, "score": 9.19167934521175 } ]
Rust
src/synth_ui/widgets.rs
GorgeousMooseNipple/beep-boop
834cdea5a011be9c992ecbcb55c433cf341c2667
use std::sync::MutexGuard; use druid::widget::prelude::*; use druid::widget::{Flex, Slider, CrossAxisAlignment}; use druid::Code as KeyCode; use druid::KeyEvent; use super::{ model::{SynthUIData, SynthUIEvent, OscSettings, EnvSettings}, layout::{slider_log, LOG_SCALE_BASE}, constants::{WAVEFORMS, DefaultParameter}, }; use crate::synth::{Synth, WaveForm, ADSRParam}; fn round_float(f: f32, accuracy: i32) -> f32 { let base = 10f32.powi(accuracy); (f * base).round() / base } fn get_note(key: &KeyCode) -> Option<f32> { let freq = match key { KeyCode::KeyZ => 130.81, KeyCode::KeyS => 138.59, KeyCode::KeyX => 146.83, KeyCode::KeyD => 155.56, KeyCode::KeyC => 164.81, KeyCode::KeyV => 174.61, KeyCode::KeyG => 185.00, KeyCode::KeyB => 196.00, KeyCode::KeyH => 207.65, KeyCode::KeyN => 220.00, KeyCode::KeyJ => 233.08, KeyCode::KeyM => 246.94, _ => return None, }; Some(freq) } #[derive(Clone)] pub struct WaveFormUI { pub name: &'static str, pub waveform: WaveForm, } pub struct SynthUI { pub root: Flex<SynthUIData>, } impl SynthUI { pub fn new() -> Self { Self { root: Flex::row().cross_axis_alignment(CrossAxisAlignment::Start) } } fn handle_key_press(&self, key: &KeyCode, data: &mut SynthUIData) { match key { KeyCode::ArrowLeft => { let modified = round_float(data.octave_modifier / 2.0, 3); if modified <= 1.0 / 4.0 { } else { data.octave_modifier = modified } } KeyCode::ArrowRight => { let modified = round_float(data.octave_modifier * 2.0, 3); if modified >= 16.0 { } else { data.octave_modifier = modified } } KeyCode::ArrowUp => {} KeyCode::ArrowDown => {} KeyCode::KeyU => {} _ => match get_note(key) { None => {} Some(freq) => { let mut synth = data.synth.lock().unwrap(); if !synth.playing() { data.event_sender.send(SynthUIEvent::NewNotes).unwrap(); } synth.note_on(freq * data.octave_modifier, *key) } } } } fn handle_key_release(&self, key: &KeyCode, data: &mut SynthUIData) { if let Some(_) = get_note(key) { data.synth.lock().unwrap().note_off(*key); } } fn update_osc(&self, synth: &mut MutexGuard<Synth<i16>>, new: &OscSettings, old: &OscSettings) { if new.volume != old.volume { synth.set_osc_volume(new.id, new.volume as f32); } if new.wave_idx != old.wave_idx { synth.set_waveform(new.id, &WAVEFORMS[new.wave_idx as usize].waveform); } if new.transpose != old.transpose { synth.set_transpose(new.id, new.transpose as i8); } if new.tune != old.tune { synth.set_tune(new.id, new.tune as i8); } if new.unisons != old.unisons { synth.set_unisons(new.id, new.unisons.round() as usize); } if new.env_idx != old.env_idx { synth.set_env(new.id, new.env_idx.round() as usize); } } fn update_env(&self, synth: &mut MutexGuard<Synth<i16>>, new: &EnvSettings, old: &EnvSettings) { if new.attack != old.attack { synth.set_env_parameter(new.id, ADSRParam::Attack(LOG_SCALE_BASE.powf(new.attack).round() as f32)) } if new.decay != old.decay { synth.set_env_parameter(new.id, ADSRParam::Decay(LOG_SCALE_BASE.powf(new.decay).round() as f32)) } if new.sustain != old.sustain { synth.set_env_parameter(new.id, ADSRParam::Sustain(new.sustain as f32)) } if new.release != old.release { synth.set_env_parameter(new.id, ADSRParam::Release(LOG_SCALE_BASE.powf(new.release).round() as f32)) } } } impl Widget<SynthUIData> for SynthUI { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut SynthUIData, env: &Env) { match event { Event::WindowConnected => { if !ctx.is_focused() { ctx.request_focus() } } Event::KeyDown(KeyEvent { code, repeat, .. }) => { if *code == KeyCode::Escape { ctx.window().close() } else if !repeat { self.handle_key_press(code, data) } } Event::KeyUp(KeyEvent { code, repeat, .. }) => { if !repeat { self.handle_key_release(code, data) } } event => self.root.event(ctx, event, data, env), } } fn lifecycle( &mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &SynthUIData, env: &Env, ) { match event { LifeCycle::WidgetAdded => ctx.register_for_focus(), _ => {} } self.root.lifecycle(ctx, event, data, env) } fn update( &mut self, ctx: &mut UpdateCtx, old: &SynthUIData, new: &SynthUIData, env: &Env, ) { if !new.same(old) { if !new.osc1.same(&old.osc1) { let mut synth = new.synth.lock().unwrap(); self.update_osc(&mut synth, &new.osc1, &old.osc1); } if !new.osc2.same(&old.osc2) { let mut synth = new.synth.lock().unwrap(); self.update_osc(&mut synth, &new.osc2, &old.osc2); } if new.volume_db != old.volume_db { new.synth.lock().unwrap().set_volume(new.volume_db as i32).unwrap(); } if !new.env1.same(&old.env1) { let mut synth = new.synth.lock().unwrap(); self.update_env(&mut synth, &new.env1, &old.env1); } if !new.env2.same(&old.env2) { let mut synth = new.synth.lock().unwrap(); self.update_env(&mut synth, &new.env2, &old.env2); } } self.root.update(ctx, old, new, env); } fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &SynthUIData, env: &Env, ) -> Size { self.root.layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &SynthUIData, env: &Env) { self.root.paint(ctx, data, env); } } pub struct DefaultSlider { slider: Slider, parameter: DefaultParameter, } impl DefaultSlider { pub fn new(slider: Slider, parameter: DefaultParameter) -> Self { Self { slider, parameter, } } } impl Widget<f64> for DefaultSlider { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut f64, env: &Env) { match event { Event::MouseDown(e) => { if e.button.is_left() && e.mods.ctrl() { match self.parameter { DefaultParameter::EnvAttack | DefaultParameter::EnvDecay | DefaultParameter::EnvRelease => { *data = slider_log(self.parameter.default_val() as f32); }, _ => *data = self.parameter.default_val(), } return } }, _ => {}, } self.slider.event(ctx, event, data, env) } fn lifecycle( &mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &f64, env: &Env, ) { self.slider.lifecycle(ctx, event, data, env) } fn update( &mut self, ctx: &mut UpdateCtx, old: &f64, new: &f64, env: &Env, ) { self.slider.update(ctx, old, new, env) } fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &f64, env: &Env, ) -> Size { self.slider.layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &f64, env: &Env) { self.slider.paint(ctx, data, env) } }
use std::sync::MutexGuard; use druid::widget::prelude::*; use druid::widget::{Flex, Slider, CrossAxisAlignment}; use druid::Code as KeyCode; use druid::KeyEvent; use super::{ model::{SynthUIData, SynthUIEvent, OscSettings, EnvSettings}, layout::{slider_log, LOG_SCALE_BASE}, constants::{WAVEFORMS, DefaultParameter}, }; use crate::synth::{Synth, WaveForm, ADSRParam}; fn round_float(f: f32, accuracy: i32) -> f32 { let base = 10f32.powi(accuracy); (f * base).round() / base } fn get_note(key: &KeyCode) -> Option<f32> { let freq = match key { KeyCode::KeyZ => 130.81, KeyCode::KeyS => 138.59, KeyCode::KeyX => 146.83, KeyCode::KeyD => 155.56, KeyCode::KeyC => 164.81, KeyCode::KeyV => 174.61, KeyCode::KeyG => 185.00, KeyCode::KeyB => 196.00, KeyCode::KeyH => 207.65, KeyCode::KeyN => 220.00, KeyCode::KeyJ => 233.08, KeyCode::KeyM => 246.94, _ => return None, }; Some(freq) } #[derive(Clone)] pub struct WaveFormUI { pub name: &'static str, pub waveform: WaveForm, } pub struct SynthUI { pub root: Flex<SynthUIData>, } impl SynthUI { pub fn new() -> Self { Self { root: Flex::row().cross_axis_alignment(CrossAxisAlignment::Start) } } fn handle_key_press(&self, key: &KeyCode, data: &mut SynthUIData) { match key { KeyCode::ArrowLeft => { let modified = round_float(data.octave_modifier / 2.0, 3); if modified <= 1.0 / 4.0 { } else { data.octave_modifier = modified } } KeyCode::ArrowRight => { let modified = round_float(data.octave_modifier * 2.0, 3); if modified >= 16.0 { } else { data.octave_modifier = modified } } KeyCode::ArrowUp => {} KeyCode::ArrowDown => {} KeyCode::KeyU => {} _ => match get_note(key) { None => {} Some(freq) => { let mut synth = data.synth.lock().unwrap(); if !synth.playing() { data.event_sender.send(SynthUIEvent::NewNotes).unwrap(); } synth.note_on(freq * data.octave_modifier, *key) } } } } fn handle_key_release(&self, key: &KeyCode, data: &mut SynthUIData) { if let Some(_) = get_note(key) { data.synth.lock().unwrap().note_off(*key); } } fn update_osc(&self, synth: &mut MutexGuard<Synth<i16>>, new: &OscSettings, old: &OscSettings) { if new.volume != old.volume { synth.set_osc_volume(new.id, new.volume as f32); } if new.wave_idx != old.wave_idx { synth.set_waveform(new.id, &WAVEFORMS[new.wave_idx as usize].waveform); } if new.transpose != old.transpose { synth.set_transpose(new.id, new.transpose as i8); } if new.tune != old.tune { synth.set_tune(new.id, new.tune as i8); } if new.unisons != old.unisons { synth.set_unisons(new.id, new.unisons.round() as usize); } if new.env_idx != old.env_idx { synth.set_env(new.id, new.env_idx.round() as usize); } } fn update_env(&self, synth: &mut MutexGuard<Synth<i16>>, new: &EnvSettings, old: &EnvSettings) {
if new.decay != old.decay { synth.set_env_parameter(new.id, ADSRParam::Decay(LOG_SCALE_BASE.powf(new.decay).round() as f32)) } if new.sustain != old.sustain { synth.set_env_parameter(new.id, ADSRParam::Sustain(new.sustain as f32)) } if new.release != old.release { synth.set_env_parameter(new.id, ADSRParam::Release(LOG_SCALE_BASE.powf(new.release).round() as f32)) } } } impl Widget<SynthUIData> for SynthUI { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut SynthUIData, env: &Env) { match event { Event::WindowConnected => { if !ctx.is_focused() { ctx.request_focus() } } Event::KeyDown(KeyEvent { code, repeat, .. }) => { if *code == KeyCode::Escape { ctx.window().close() } else if !repeat { self.handle_key_press(code, data) } } Event::KeyUp(KeyEvent { code, repeat, .. }) => { if !repeat { self.handle_key_release(code, data) } } event => self.root.event(ctx, event, data, env), } } fn lifecycle( &mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &SynthUIData, env: &Env, ) { match event { LifeCycle::WidgetAdded => ctx.register_for_focus(), _ => {} } self.root.lifecycle(ctx, event, data, env) } fn update( &mut self, ctx: &mut UpdateCtx, old: &SynthUIData, new: &SynthUIData, env: &Env, ) { if !new.same(old) { if !new.osc1.same(&old.osc1) { let mut synth = new.synth.lock().unwrap(); self.update_osc(&mut synth, &new.osc1, &old.osc1); } if !new.osc2.same(&old.osc2) { let mut synth = new.synth.lock().unwrap(); self.update_osc(&mut synth, &new.osc2, &old.osc2); } if new.volume_db != old.volume_db { new.synth.lock().unwrap().set_volume(new.volume_db as i32).unwrap(); } if !new.env1.same(&old.env1) { let mut synth = new.synth.lock().unwrap(); self.update_env(&mut synth, &new.env1, &old.env1); } if !new.env2.same(&old.env2) { let mut synth = new.synth.lock().unwrap(); self.update_env(&mut synth, &new.env2, &old.env2); } } self.root.update(ctx, old, new, env); } fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &SynthUIData, env: &Env, ) -> Size { self.root.layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &SynthUIData, env: &Env) { self.root.paint(ctx, data, env); } } pub struct DefaultSlider { slider: Slider, parameter: DefaultParameter, } impl DefaultSlider { pub fn new(slider: Slider, parameter: DefaultParameter) -> Self { Self { slider, parameter, } } } impl Widget<f64> for DefaultSlider { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut f64, env: &Env) { match event { Event::MouseDown(e) => { if e.button.is_left() && e.mods.ctrl() { match self.parameter { DefaultParameter::EnvAttack | DefaultParameter::EnvDecay | DefaultParameter::EnvRelease => { *data = slider_log(self.parameter.default_val() as f32); }, _ => *data = self.parameter.default_val(), } return } }, _ => {}, } self.slider.event(ctx, event, data, env) } fn lifecycle( &mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &f64, env: &Env, ) { self.slider.lifecycle(ctx, event, data, env) } fn update( &mut self, ctx: &mut UpdateCtx, old: &f64, new: &f64, env: &Env, ) { self.slider.update(ctx, old, new, env) } fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &f64, env: &Env, ) -> Size { self.slider.layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &f64, env: &Env) { self.slider.paint(ctx, data, env) } }
if new.attack != old.attack { synth.set_env_parameter(new.id, ADSRParam::Attack(LOG_SCALE_BASE.powf(new.attack).round() as f32)) }
if_condition
[ { "content": "pub fn build_ui() -> impl Widget<SynthUIData> {\n\n let mut synth_ui = SynthUI::new();\n\n\n\n synth_ui.root.add_child(Flex::column()\n\n .cross_axis_alignment(CrossAxisAlignment::Center)\n\n .with_child(oscillator_layout(\"Osc1\", SynthUIData::osc1))\n\n .with_spacer(10.0)\n\n .with_child(oscillator_layout(\"Osc2\", SynthUIData::osc2)));\n\n\n\n let control_layout = Flex::<SynthUIData>::column()\n\n .cross_axis_alignment(CrossAxisAlignment::Center)\n\n .with_child(synth_volume_layout())\n\n .with_spacer(10.0)\n\n .with_child(env_layout(\"Env1\", SynthUIData::env1))\n\n .with_spacer(10.0)\n\n .with_child(env_layout(\"Env2\", SynthUIData::env2));\n\n synth_ui.root.add_child(control_layout.padding((20.0, 0.0, 0.0, 0.0)));\n\n\n\n synth_ui.center().background(BACKGROUND_COLOR)\n\n}\n", "file_path": "src/synth_ui.rs", "rank": 1, "score": 122122.91244795876 }, { "content": "pub fn synth_volume_layout() -> impl Widget<SynthUIData> {\n\n let mut volume_flex = Flex::column()\n\n .cross_axis_alignment(CrossAxisAlignment::Center)\n\n .with_child(Label::new(\"BEEP-BOOP\")\n\n .with_text_color(LABEL_COLOR_MAIN)\n\n .with_text_size(TEXT_LARGE))\n\n .with_spacer(10.0);\n\n let volume_control = Flex::row()\n\n .cross_axis_alignment(CrossAxisAlignment::Center)\n\n .with_child(Label::new(\"Volume\").with_text_size(TEXT_MEDIUM).fix_width(BASIC_LABEL_WITDH))\n\n .with_child(\n\n Slider::new()\n\n .with_range(-96.0, 0.0)\n\n .lens(SynthUIData::volume_db)\n\n .padding((5.0, 0.0, 5.0, 0.0))\n\n .fix_width(SLIDER_WIDTH_SMALL))\n\n .with_child(\n\n Label::dynamic(\n\n |data: &SynthUIData, _| {\n\n format!(\"{} dB\", data.volume_db.round())\n\n }\n\n ).fix_width(25.0)\n\n );\n\n\n\n volume_flex.add_child(volume_control);\n\n\n\n volume_flex\n\n}\n\n\n", "file_path": "src/synth_ui/layout.rs", "rank": 2, "score": 119021.1032306046 }, { "content": "pub fn slider_log(x: f32) -> f64 {\n\n f64::log2(x as f64)\n\n}\n\n\n", "file_path": "src/synth_ui/layout.rs", "rank": 3, "score": 114941.88423677531 }, { "content": "// unison(label + label + stepper);\n\npub fn oscillator_layout<L>(title: &str, osc_lens: L) -> impl Widget<SynthUIData>\n\nwhere\n\n L: Lens<SynthUIData, OscSettings>\n\n + Clone\n\n + 'static\n\n{\n\n let left_padding = (10.0, 0.0, 0.0, 0.0);\n\n let row_padding = (10.0, 0.0, 0.0, 10.0);\n\n let mut osc_flex = Flex::column()\n\n .cross_axis_alignment(CrossAxisAlignment::Start)\n\n .with_child(\n\n Label::new(title).with_text_size(TEXT_MEDIUM).with_text_color(LABEL_COLOR_SECONDARY).padding(10.0)\n\n );\n\n // Volume and envelope\n\n osc_flex.add_child(Label::new(\"Volume\").with_text_size(TEXT_SMALL).padding(left_padding));\n\n // Volume slider\n\n let volume_slider = DefaultSlider::new(Slider::new()\n\n .with_range(0.0, 1.0), DefaultParameter::OscVolume)\n\n .lens(osc_lens.clone().then(OscSettings::volume)).fix_width(SLIDER_WIDTH_SMALL);\n\n // Envelope\n", "file_path": "src/synth_ui/layout.rs", "rank": 4, "score": 112279.6107616227 }, { "content": "pub fn env_layout<L>(title: &str, env_lens: L) -> impl Widget<SynthUIData>\n\nwhere\n\n L: Lens<SynthUIData, EnvSettings>\n\n + Clone\n\n + 'static\n\n{\n\n let mut env_flex = Flex::column()\n\n .cross_axis_alignment(CrossAxisAlignment::Start)\n\n .with_child(Label::new(title).with_text_size(TEXT_MEDIUM).padding(5.0));\n\n\n\n // Attack\n\n let lens_clone = env_lens.clone();\n\n let attack_value = Label::dynamic(\n\n move |data: &SynthUIData, _| {\n\n format!(\"{} ms\", lens_clone.with(data, |env| { LOG_SCALE_BASE.powf(env.attack).round() }))\n\n }\n\n ).with_text_size(TEXT_SMALL);\n\n // Log scale slider\n\n let attack_min = slider_log(adsr_constraints::MIN_ATTACK);\n\n let attack_max = slider_log(adsr_constraints::MAX_ATTACK);\n", "file_path": "src/synth_ui/layout.rs", "rank": 5, "score": 112279.6107616227 }, { "content": "#[derive(Debug)]\n\nstruct Unison {\n\n freq_mod: f32,\n\n volume: f32,\n\n}\n\n\n", "file_path": "src/synth/oscillator.rs", "rank": 7, "score": 55182.81824388109 }, { "content": "#[derive(Debug)]\n\nstruct UnisonVoice {\n\n phase: f32,\n\n phase_incr: f32,\n\n volume: f32,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Voice {\n\n note: Note,\n\n volume: f32,\n\n unisons: Vec<UnisonVoice>,\n\n}\n\n\n\n#[allow(dead_code)]\n\npub enum Start {\n\n Soft,\n\n Hard,\n\n Random,\n\n}\n\n\n", "file_path": "src/synth/oscillator.rs", "rank": 8, "score": 53267.83565575477 }, { "content": "#[allow(non_camel_case_types)]\n\ntype dB = i32;\n\n\n", "file_path": "src/synth.rs", "rank": 9, "score": 52588.7350108572 }, { "content": "pub trait Wave {\n\n fn wave_func(&self, phase: f32) -> f32;\n\n fn next_phase(&self, phase: f32, incr: f32) -> f32;\n\n fn period(&self) -> f32;\n\n}\n\n\n\npub struct Sine {\n\n period: f32,\n\n}\n\n\n\nimpl Sine {\n\n pub fn new() -> Self {\n\n Self { period: TWO_PI }\n\n }\n\n}\n\n\n\nimpl Wave for Sine {\n\n fn wave_func(&self, phase: f32) -> f32 {\n\n phase.sin()\n\n }\n", "file_path": "src/synth/waves.rs", "rank": 10, "score": 49659.965683951494 }, { "content": "pub trait SampleFormat:\n\n portaudio_rs::stream::SampleType\n\n + num_traits::AsPrimitive<f32>\n\n + num_traits::Bounded\n\n + num_traits::FromPrimitive\n\n + std::cmp::PartialOrd\n\n{\n\n}\n\n\n\nimpl SampleFormat for u8 {}\n\nimpl SampleFormat for i8 {}\n\nimpl SampleFormat for i16 {}\n\nimpl SampleFormat for i32 {}\n\nimpl SampleFormat for f32 {}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct Released {\n\n pub time: Instant,\n\n pub value: f32,\n\n}\n", "file_path": "src/synth.rs", "rank": 11, "score": 49659.965683951494 }, { "content": "fn main() -> Result<()> {\n\n let mut synth = Synth::<i16>::new(SAMPLE_RATE);\n\n synth.set_volume(-36)?;\n\n let synth_arc = Arc::new(Mutex::new(synth));\n\n\n\n let (synth_event, wait_synth_event): (mpsc::Sender<SynthUIEvent>, mpsc::Receiver<SynthUIEvent>) = mpsc::channel();\n\n\n\n let synth_in_thread = Arc::clone(&synth_arc);\n\n let th = std::thread::Builder::new()\n\n .name(\"beep-boop-synth\".into())\n\n .spawn(move || -> Result<()> {\n\n pa::initialize()?;\n\n let synth = synth_in_thread;\n\n let synth_callback = Arc::clone(&synth);\n\n let (stream_finished, wait_stream_finished): (mpsc::Sender<()>, mpsc::Receiver<()>) = mpsc::channel();\n\n let callback = Box::new(\n\n move |\n\n _input: &[i16],\n\n output: &mut [i16],\n\n _time: pa::stream::StreamTimeInfo,\n", "file_path": "src/main.rs", "rank": 12, "score": 36841.90007712072 }, { "content": "fn create_output_stream<SF>(\n\n sample_rate: f32,\n\n buf_size: u32,\n\n channels_num: u32,\n\n callback: Option<Box<pa::stream::StreamCallback<'static, SF, SF>>>\n\n) -> Result<pa::stream::Stream<'_, SF, SF>>\n\nwhere\n\n SF: SampleFormat,\n\n{\n\n let default_output = match pa::device::get_default_output_index() {\n\n Some(dev) => dev,\n\n None => {\n\n return Err(BaseError::StreamError(\n\n \"Can't open default device\".into(),\n\n ))\n\n }\n\n };\n\n\n\n let latency = match pa::device::get_info(default_output) {\n\n Some(info) => info.default_low_output_latency,\n", "file_path": "src/main.rs", "rank": 13, "score": 34588.39093648696 }, { "content": " pub fn note_on(&mut self, freq: f32, key: KeyCode) {\n\n let note = Note::new(freq, key);\n\n self.oscillators\n\n .iter_mut()\n\n .for_each(|osc| osc.create_voice(&note))\n\n }\n\n\n\n pub fn note_off(&mut self, key: KeyCode) {\n\n self.oscillators\n\n .iter_mut()\n\n .for_each(|osc| osc.voice_off(key))\n\n }\n\n\n\n pub fn playing(&self) -> bool {\n\n self.oscillators.iter().any(|osc| osc.has_active_voices())\n\n }\n\n\n\n pub fn set_waveform(&mut self, osc_idx: usize, waveform: &WaveForm) {\n\n self.oscillators[osc_idx].set_waveform(waveform);\n\n }\n", "file_path": "src/synth.rs", "rank": 14, "score": 15963.822435998918 }, { "content": "\n\n#[derive(Debug, Clone)]\n\npub struct Note {\n\n frequency: f32,\n\n triggered_by: KeyCode,\n\n triggered_time: Instant,\n\n released: Option<Released>,\n\n}\n\n\n\nimpl Note {\n\n pub fn new(frequency: f32, key: KeyCode) -> Self {\n\n Self {\n\n frequency: frequency,\n\n triggered_by: key,\n\n triggered_time: Instant::now(),\n\n released: None,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/synth.rs", "rank": 15, "score": 15961.612683596666 }, { "content": "impl PartialEq for Note {\n\n fn eq(&self, other: &Self) -> bool {\n\n self.frequency == other.frequency && self.triggered_by == other.triggered_by\n\n }\n\n}\n\n\n\npub struct Synth<SampleType: SampleFormat> {\n\n #[allow(dead_code)]\n\n sample_rate: f32,\n\n volume: f32,\n\n pub oscillators: Vec<Oscillator>,\n\n pub envelopes: Vec<ADSR>,\n\n _sample_type: std::marker::PhantomData<SampleType>,\n\n}\n\n\n\nimpl<SampleType: SampleFormat> Synth<SampleType> {\n\n pub fn new(sample_rate: f32) -> Self {\n\n Self {\n\n sample_rate: sample_rate,\n\n volume: 1024.0,\n", "file_path": "src/synth.rs", "rank": 16, "score": 15960.063198386917 }, { "content": " }\n\n\n\n pub fn set_tune(&mut self, osc_idx: usize, cents: i8) {\n\n self.oscillators[osc_idx].tune(cents);\n\n }\n\n\n\n pub fn set_volume(&mut self, volume: dB) -> Result<()> {\n\n if volume > 0 || volume < -96 {\n\n return Err(BaseError::SynthError(\n\n \"[-96, 0] dB is the range for volume\".to_owned(),\n\n ));\n\n }\n\n self.volume = SampleType::max_value().as_() * 10f32.powf(volume as f32 / 20.0);\n\n Ok(())\n\n }\n\n\n\n pub fn set_osc_volume(&mut self, osc_idx: usize, volume: f32) {\n\n self.oscillators[osc_idx].volume = volume;\n\n }\n\n\n", "file_path": "src/synth.rs", "rank": 17, "score": 15959.564613141953 }, { "content": " oscillators: Vec::new(),\n\n envelopes: Vec::new(),\n\n _sample_type: std::marker::PhantomData,\n\n }\n\n }\n\n\n\n pub fn add_osc(&mut self, osc: Oscillator) {\n\n self.oscillators.push(osc)\n\n }\n\n\n\n pub fn add_env(&mut self, env: ADSR) {\n\n self.envelopes.push(env)\n\n }\n\n\n\n pub fn set_unisons(&mut self, osc_idx: usize, num: usize) {\n\n self.oscillators[osc_idx].set_unison_num(num);\n\n }\n\n\n\n pub fn set_transpose(&mut self, osc_idx: usize, semitones: i8) {\n\n self.oscillators[osc_idx].transpose(semitones);\n", "file_path": "src/synth.rs", "rank": 18, "score": 15958.308487793878 }, { "content": "\n\n pub fn set_env_parameter(&mut self, env_idx: usize, param: ADSRParam) {\n\n self.envelopes[env_idx].set_parameter(param);\n\n }\n\n\n\n pub fn set_env(&mut self, osc_idx: usize, env_idx: usize) {\n\n self.oscillators[osc_idx].env_idx = env_idx;\n\n }\n\n}\n\n\n\nimpl<SampleType: SampleFormat> Iterator for Synth<SampleType> {\n\n type Item = SampleType;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n // let sample = self\n\n // .oscillators\n\n // .iter_mut()\n\n // .map(|osc| osc.get_sample())\n\n // .sum::<f32>()\n\n // * self.volume;\n\n let mut sample: f32 = 0.0;\n\n for osc in self.oscillators.iter_mut() {\n\n sample += osc.get_sample(&self.envelopes[osc.env_idx]);\n\n }\n\n Some(SampleType::from_f32(sample * self.volume).unwrap())\n\n }\n\n}\n", "file_path": "src/synth.rs", "rank": 19, "score": 15957.975495309453 }, { "content": "mod envelope;\n\nmod oscillator;\n\npub mod waves;\n\n\n\npub use self::envelope::{ADSR, ADSRParam, adsr_constraints};\n\npub use self::oscillator::{Oscillator, Start};\n\npub use self::waves::WaveForm;\n\nuse crate::error::{BaseError, Result};\n\npub use crate::synth_ui::KeyCode;\n\n\n\nuse std::time::Instant;\n\n\n\n#[allow(non_camel_case_types)]\n", "file_path": "src/synth.rs", "rank": 20, "score": 15956.565741498498 }, { "content": " phase_start: PhaseStart,\n\n}\n\n\n\nimpl Oscillator {\n\n pub fn new(sample_rate: f32, waveform: WaveForm, env_idx: usize, volume: f32) -> Self {\n\n let volume = volume.min(1.0).max(0.0);\n\n Self {\n\n sample_rate: sample_rate,\n\n wave: waveform.get_wave(),\n\n waveform: waveform,\n\n env_idx: env_idx,\n\n volume: volume,\n\n voices: Vec::new(),\n\n panning: 0.0,\n\n transpose: 1.0,\n\n tune: 1.0,\n\n unisons: vec![Unison {\n\n freq_mod: 1.0,\n\n volume: 1.0,\n\n }],\n", "file_path": "src/synth/oscillator.rs", "rank": 21, "score": 15077.71466733092 }, { "content": " amplitide: f32,\n\n half_amplitude: f32,\n\n}\n\n\n\nimpl Triangle {\n\n pub fn new() -> Self {\n\n Self {\n\n period: 4.0,\n\n amplitide: 2.0,\n\n half_amplitude: 1.0,\n\n }\n\n }\n\n}\n\n\n\nimpl Wave for Triangle {\n\n fn wave_func(&self, phase: f32) -> f32 {\n\n -(phase - self.amplitide).abs() + self.half_amplitude\n\n }\n\n\n\n fn next_phase(&self, mut phase: f32, incr: f32) -> f32 {\n", "file_path": "src/synth/waves.rs", "rank": 22, "score": 15075.49492642538 }, { "content": "}\n\n\n\npub struct Pulse25 {\n\n period: f32,\n\n upper_part: f32,\n\n}\n\n\n\nimpl Pulse25 {\n\n pub fn new() -> Self {\n\n Self {\n\n period: 2.0,\n\n upper_part: 2.0 * 0.25,\n\n }\n\n }\n\n}\n\n\n\nimpl Wave for Pulse25 {\n\n fn wave_func(&self, phase: f32) -> f32 {\n\n if phase <= self.upper_part {\n\n 0.7\n", "file_path": "src/synth/waves.rs", "rank": 23, "score": 15074.89507108885 }, { "content": " pub fn new() -> Self {\n\n Self {\n\n period: TWO_PI,\n\n half_period: PI,\n\n }\n\n }\n\n}\n\n\n\nimpl Wave for Square {\n\n fn wave_func(&self, phase: f32) -> f32 {\n\n if phase <= self.half_period {\n\n 0.7\n\n } else {\n\n -0.7\n\n }\n\n }\n\n\n\n fn next_phase(&self, mut phase: f32, incr: f32) -> f32 {\n\n phase += incr * self.period;\n\n if phase >= self.period {\n", "file_path": "src/synth/waves.rs", "rank": 24, "score": 15074.829533046746 }, { "content": " }\n\n }\n\n self.transpose = transpose;\n\n }\n\n\n\n // Cents\n\n pub fn tune(&mut self, cents: i8) {\n\n self.tune = 2f32.powf(cents as f32 / (12.0 * 100.0));\n\n self.update_unison();\n\n }\n\n\n\n fn update_unison(&mut self) {\n\n self.set_unison_num(self.unisons.len());\n\n }\n\n\n\n pub fn set_unison_num(&mut self, num: usize) {\n\n self.unisons.clear();\n\n if num <= 1 {\n\n self.unisons.push(Unison {\n\n freq_mod: self.tune,\n", "file_path": "src/synth/oscillator.rs", "rank": 25, "score": 15074.727540766098 }, { "content": " phase -= self.period;\n\n }\n\n phase\n\n }\n\n\n\n fn period(&self) -> f32 {\n\n self.period\n\n }\n\n}\n\n\n\npub struct Saw {\n\n period: f32,\n\n half_period: f32,\n\n}\n\n\n\nimpl Saw {\n\n pub fn new() -> Self {\n\n Self {\n\n period: 2.0,\n\n half_period: 1.0,\n", "file_path": "src/synth/waves.rs", "rank": 26, "score": 15074.613236926223 }, { "content": " pub fn set_waveform(&mut self, waveform: &WaveForm) {\n\n self.waveform = waveform.clone();\n\n self.wave = waveform.get_wave();\n\n self.phase_start.change_period(self.wave.period());\n\n }\n\n\n\n pub fn set_start(&mut self, start: Start) {\n\n match start {\n\n Start::Soft => self.phase_start = PhaseStart::Soft,\n\n Start::Hard => self.phase_start = PhaseStart::Hard(self.wave.period()),\n\n Start::Random => self.phase_start = PhaseStart::Random(self.wave.period()),\n\n }\n\n }\n\n\n\n // Semitones\n\n pub fn transpose(&mut self, semitones: i8) {\n\n let transpose = 2f32.powf(semitones as f32 / 12.0);\n\n for Voice { unisons, .. } in self.voices.iter_mut() {\n\n for UnisonVoice { phase_incr, .. } in unisons.iter_mut() {\n\n *phase_incr = *phase_incr / self.transpose * transpose;\n", "file_path": "src/synth/oscillator.rs", "rank": 27, "score": 15073.645539143663 }, { "content": "mod model;\n\nmod layout;\n\nmod widgets;\n\nmod constants;\n\n\n\npub use druid::Code as KeyCode;\n\nuse druid::widget::prelude::*;\n\nuse druid::widget::{Flex,CrossAxisAlignment};\n\nuse druid::{WidgetExt};\n\n\n\npub use model::{SynthUIData, SynthUIEvent, Delegate};\n\nuse widgets::SynthUI;\n\nuse layout::{BACKGROUND_COLOR, oscillator_layout, synth_volume_layout, env_layout};\n\n\n\n\n", "file_path": "src/synth_ui.rs", "rank": 28, "score": 15072.956541196514 }, { "content": "const TWO_PI: f32 = std::f32::consts::PI * 2.0;\n\nconst PI: f32 = std::f32::consts::PI;\n\n\n\n#[derive(Clone, PartialEq)]\n\npub enum WaveForm {\n\n Sine,\n\n Square,\n\n Pulse25,\n\n Saw,\n\n Triangle,\n\n}\n\n\n\nimpl WaveForm {\n\n pub fn get_wave(&self) -> Box<dyn Wave + Send> {\n\n match self {\n\n WaveForm::Sine => Box::new(Sine::new()),\n\n WaveForm::Square => Box::new(Square::new()),\n\n WaveForm::Pulse25 => Box::new(Pulse25::new()),\n\n WaveForm::Saw => Box::new(Saw::new()),\n\n WaveForm::Triangle => Box::new(Triangle::new()),\n\n }\n\n }\n\n}\n\n\n\n\n", "file_path": "src/synth/waves.rs", "rank": 29, "score": 15072.0629908132 }, { "content": " .voices\n\n .iter_mut()\n\n .find(|v| v.note.triggered_by == key && v.note.released.is_none())\n\n {\n\n note.released = Some(Released {\n\n time: Instant::now(),\n\n value: *volume,\n\n })\n\n }\n\n }\n\n\n\n pub fn get_sample(&mut self, adsr: &ADSR) -> f32 {\n\n let mut sample = 0.0;\n\n let mut muted_voices = false;\n\n for Voice {\n\n note,\n\n volume,\n\n unisons,\n\n } in self.voices.iter_mut()\n\n {\n", "file_path": "src/synth/oscillator.rs", "rank": 30, "score": 15071.890658188293 }, { "content": "\n\n#[derive(Clone)]\n\npub struct ADSR {\n\n sample_rate: f32,\n\n pub attack: f32,\n\n pub decay: f32,\n\n pub sustain: f32,\n\n pub release: f32,\n\n attack_incr: f32,\n\n decay_decr: f32,\n\n #[allow(dead_code)]\n\n release_decr: f32,\n\n release_samples: f32,\n\n}\n\n\n\nimpl ADSR {\n\n pub fn new(\n\n sample_rate: f32,\n\n attack: Milliseconds,\n\n decay: Milliseconds,\n", "file_path": "src/synth/envelope.rs", "rank": 31, "score": 15071.292929281699 }, { "content": "\n\n fn next_phase(&self, mut phase: f32, incr: f32) -> f32 {\n\n phase += incr * self.period;\n\n if phase >= self.period {\n\n phase -= self.period\n\n }\n\n phase\n\n }\n\n\n\n fn period(&self) -> f32 {\n\n self.period\n\n }\n\n}\n\n\n\npub struct Square {\n\n period: f32,\n\n half_period: f32,\n\n}\n\n\n\nimpl Square {\n", "file_path": "src/synth/waves.rs", "rank": 32, "score": 15070.721598629258 }, { "content": " volume: central_uni.volume,\n\n });\n\n }\n\n for uni in uni_iter {\n\n unisons.push(UnisonVoice {\n\n phase: period * rand::random::<f32>(),\n\n phase_incr: phase_incr * uni.freq_mod,\n\n volume: uni.volume,\n\n })\n\n }\n\n self.voices.push(Voice {\n\n note: note.clone(),\n\n volume: 0.0,\n\n unisons: unisons,\n\n });\n\n }\n\n }\n\n\n\n pub fn voice_off(&mut self, key: KeyCode) {\n\n if let Some(Voice { note, volume, .. }) = self\n", "file_path": "src/synth/oscillator.rs", "rank": 33, "score": 15070.641369959689 }, { "content": "use std::time::Instant;\n\n\n\nuse super::envelope::ADSR;\n\nuse super::waves::{Wave, WaveForm};\n\nuse super::{KeyCode, Note, Released};\n\n\n\n#[derive(Debug)]\n", "file_path": "src/synth/oscillator.rs", "rank": 34, "score": 15070.53595825509 }, { "content": " }\n\n }\n\n}\n\n\n\n// Panning TODO:\n\n// pan value == 0.0 - full left; == 1.0 - full right\n\n// left = value * sin((1- pan) * PI / 2)\n\n// right = value * sin(pan * PI / 2)\n\npub struct Oscillator {\n\n sample_rate: f32,\n\n wave: Box<dyn Wave + Send>,\n\n pub waveform: WaveForm,\n\n pub env_idx: usize,\n\n pub volume: f32,\n\n voices: Vec<Voice>,\n\n #[allow(dead_code)]\n\n panning: f32,\n\n pub transpose: f32,\n\n pub tune: f32,\n\n unisons: Vec<Unison>,\n", "file_path": "src/synth/oscillator.rs", "rank": 35, "score": 15070.470822824293 }, { "content": " }\n\n // Decay stage\n\n if alive_for <= self.attack.add(self.decay) {\n\n let output = current + self.decay_decr;\n\n if output > self.sustain {\n\n return output;\n\n }\n\n }\n\n self.sustain\n\n }\n\n }\n\n\n\n // Old heavy version\n\n #[allow(dead_code)]\n\n pub fn get_volume(&self, triggered: &Instant, released: &Option<Released>) -> f32 {\n\n match released {\n\n Some(ref released) => {\n\n let released_for = released.time.elapsed().as_millis() as f32;\n\n return released.value * (1.0 - released_for / self.release);\n\n }\n", "file_path": "src/synth/envelope.rs", "rank": 36, "score": 15068.958867259853 }, { "content": " } else {\n\n -0.7\n\n }\n\n }\n\n\n\n fn next_phase(&self, mut phase: f32, incr: f32) -> f32 {\n\n phase += incr * self.period;\n\n if phase >= self.period {\n\n phase -= self.period;\n\n }\n\n phase\n\n }\n\n\n\n fn period(&self) -> f32 {\n\n self.period\n\n }\n\n}\n\n\n\npub struct Triangle {\n\n period: f32,\n", "file_path": "src/synth/waves.rs", "rank": 37, "score": 15068.80272181823 }, { "content": " }\n\n }\n\n}\n\n\n\nimpl Wave for Saw {\n\n fn wave_func(&self, phase: f32) -> f32 {\n\n phase\n\n }\n\n\n\n fn next_phase(&self, mut phase: f32, incr: f32) -> f32 {\n\n phase += incr * self.period;\n\n if phase >= self.half_period {\n\n phase -= self.period;\n\n }\n\n phase\n\n }\n\n\n\n fn period(&self) -> f32 {\n\n self.period\n\n }\n", "file_path": "src/synth/waves.rs", "rank": 38, "score": 15068.649069064732 }, { "content": " phase_start: PhaseStart::Soft,\n\n }\n\n }\n\n\n\n pub fn create_voice(&mut self, note: &Note) {\n\n if let None = self\n\n .voices\n\n .iter()\n\n .find(|v| v.note == *note && v.note.released.is_none())\n\n {\n\n let phase_incr = note.frequency / self.sample_rate * self.transpose;\n\n let mut unisons = Vec::<UnisonVoice>::with_capacity(7);\n\n let period = self.wave.period();\n\n let mut uni_iter = self.unisons.iter();\n\n if self.unisons.len() % 2 == 1 {\n\n // At least one \"unison\" is always present\n\n let central_uni = uni_iter.next().unwrap();\n\n unisons.push(UnisonVoice {\n\n phase: self.phase_start.value(),\n\n phase_incr: phase_incr * central_uni.freq_mod,\n", "file_path": "src/synth/oscillator.rs", "rank": 39, "score": 15068.556149663118 }, { "content": " });\n\n // Detune in other direction\n\n self.unisons.push(Unison {\n\n freq_mod: 1.0 / freq_mod,\n\n volume: volume,\n\n });\n\n }\n\n }\n\n // Update for existing voices\n\n let period = self.wave.period();\n\n for Voice { note, unisons, .. } in self.voices.iter_mut() {\n\n let phase_incr = note.frequency * self.transpose / self.sample_rate;\n\n let phases: Vec<f32> = unisons.iter().map(|u| u.phase).collect();\n\n unisons.clear();\n\n for i in 0..self.unisons.len() {\n\n let phase: f32;\n\n if i < phases.len() {\n\n phase = phases[i];\n\n } else {\n\n phase = period * rand::random::<f32>();\n", "file_path": "src/synth/oscillator.rs", "rank": 40, "score": 15067.737985657428 }, { "content": "use super::Released;\n\nuse std::ops::{Add, Sub};\n\nuse std::time::Instant;\n\n\n", "file_path": "src/synth/envelope.rs", "rank": 41, "score": 15067.515266938115 }, { "content": " volume: 1.0,\n\n });\n\n } else {\n\n if num % 2 == 1 {\n\n self.unisons.push(Unison {\n\n freq_mod: 1.0,\n\n volume: 1.0,\n\n })\n\n }\n\n let pairs_num = (num - num % 2) / 2;\n\n // Do better\n\n let max_volume = 0.7;\n\n let volume_step = max_volume / pairs_num as f32;\n\n for i in 0..pairs_num {\n\n let fraction: f32 = (pairs_num - i) as f32 / pairs_num as f32;\n\n let volume = volume_step * (pairs_num - i) as f32;\n\n let freq_mod = self.tune.powf(fraction);\n\n self.unisons.push(Unison {\n\n freq_mod: freq_mod,\n\n volume: volume,\n", "file_path": "src/synth/oscillator.rs", "rank": 42, "score": 15067.301143835899 }, { "content": " sustain: f32,\n\n release: Milliseconds,\n\n ) -> Self {\n\n let attack = adsr_constraints::MIN_ATTACK.max(attack as f32);\n\n let decay = adsr_constraints::MIN_DECAY.max(decay as f32);\n\n let release = adsr_constraints::MIN_RELEASE.max(release as f32);\n\n let attack_incr = 1.0 / (attack / 1000.0 * sample_rate);\n\n let decay_decr = -((1.0 - sustain) / (decay / 1000.0 * sample_rate));\n\n let release_decr = -(sustain / (release / 1000.0 * sample_rate));\n\n let release_samples = release / 1000.0 * sample_rate;\n\n Self {\n\n sample_rate,\n\n attack,\n\n decay,\n\n sustain,\n\n release,\n\n attack_incr,\n\n decay_decr,\n\n release_decr,\n\n release_samples,\n", "file_path": "src/synth/envelope.rs", "rank": 43, "score": 15066.042556379862 }, { "content": " self.release_samples = self.release / 1000.0 * self.sample_rate;\n\n }\n\n }\n\n }\n\n\n\n // Incremental version\n\n pub fn get_volume_incr(\n\n &self,\n\n current: &f32,\n\n triggered: &Instant,\n\n released: &Option<Released>,\n\n ) -> f32 {\n\n if let Some(r) = released {\n\n // Release stage\n\n current - (r.value / self.release_samples)\n\n } else {\n\n let alive_for = triggered.elapsed().as_millis() as f32;\n\n // Attack stage\n\n if alive_for <= self.attack {\n\n return current + self.attack_incr;\n", "file_path": "src/synth/envelope.rs", "rank": 44, "score": 15065.724529460556 }, { "content": " }\n\n }\n\n\n\n pub fn set_parameter(&mut self, param: ADSRParam) {\n\n match param {\n\n ADSRParam::Attack(val) => {\n\n self.attack = val.max(1.0);\n\n self.attack_incr = 1.0 / (self.attack / 1000.0 * self.sample_rate);\n\n }\n\n ADSRParam::Decay(val) => {\n\n self.decay = val.max(3.0);\n\n self.decay_decr = -((1.0 - self.sustain) / (self.decay / 1000.0 * self.sample_rate));\n\n }\n\n ADSRParam::Sustain(val) => {\n\n self.sustain = val;\n\n // Update decay decrement too, because it depends on sustain value\n\n self.decay_decr = -((1.0 - self.sustain) / (self.decay / 1000.0 * self.sample_rate));\n\n }\n\n ADSRParam::Release(val) => {\n\n self.release = val;\n", "file_path": "src/synth/envelope.rs", "rank": 45, "score": 15065.686032332764 }, { "content": " }\n\n unisons.push(UnisonVoice {\n\n phase: phase,\n\n phase_incr: phase_incr * self.unisons[i].freq_mod,\n\n volume: self.unisons[i].volume,\n\n })\n\n }\n\n }\n\n //\n\n }\n\n\n\n pub fn has_active_voices(&self) -> bool {\n\n !self.voices.is_empty()\n\n }\n\n}\n", "file_path": "src/synth/oscillator.rs", "rank": 46, "score": 15065.668928334304 }, { "content": " None => {\n\n let active_for = triggered.elapsed().as_millis() as f32;\n\n if active_for <= self.attack {\n\n return active_for / self.attack;\n\n }\n\n if active_for <= self.attack.add(self.decay) {\n\n let to_sustain = 1.0 - self.sustain;\n\n let cur_fraction = 1.0 - active_for.sub(self.attack) / self.decay;\n\n return self.sustain + to_sustain * cur_fraction;\n\n }\n\n return self.sustain;\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/synth/envelope.rs", "rank": 47, "score": 15065.411769708484 }, { "content": " phase += incr * self.period;\n\n if phase >= self.period {\n\n phase -= self.period;\n\n }\n\n phase\n\n }\n\n\n\n fn period(&self) -> f32 {\n\n self.period\n\n }\n\n}\n", "file_path": "src/synth/waves.rs", "rank": 48, "score": 15063.639373848973 }, { "content": " *volume = adsr.get_volume_incr(volume, &note.triggered_time, &note.released);\n\n *volume = volume.min(1.0);\n\n if *volume <= 0.01 {\n\n muted_voices = true;\n\n continue;\n\n }\n\n let mut voice_sample = 0.0;\n\n for uni in unisons.iter_mut() {\n\n voice_sample += self.wave.wave_func(uni.phase) * uni.volume;\n\n uni.phase = self.wave.next_phase(uni.phase, uni.phase_incr);\n\n }\n\n sample += voice_sample * *volume;\n\n }\n\n if muted_voices {\n\n self.voices\n\n .retain(|v| !(v.note.released.is_some() && v.volume <= 0.01));\n\n }\n\n sample * self.volume\n\n }\n\n\n", "file_path": "src/synth/oscillator.rs", "rank": 49, "score": 15063.27563657563 }, { "content": "use std::sync::{Arc, mpsc, Mutex};\n\n\n\nuse druid::widget::prelude::*;\n\nuse druid::{Data, Lens};\n\n\n\nuse crate::synth::{Synth, Oscillator, ADSR, Start};\n\nuse super::layout::{slider_log};\n\nuse super::constants::{WAVEFORMS, DefaultParameter};\n\n\n\n\n\nuse druid::{DelegateCtx, WindowId};\n\n\n\npub enum SynthUIEvent {\n\n NewNotes,\n\n WindowClosed,\n\n}\n\n\n\npub struct Delegate;\n\n\n\nimpl druid::AppDelegate<SynthUIData> for Delegate {\n", "file_path": "src/synth_ui/model.rs", "rank": 55, "score": 14289.860895071244 }, { "content": " pub(super) osc1: OscSettings,\n\n pub(super) osc2: OscSettings,\n\n pub(super) env1: EnvSettings,\n\n pub(super) env2: EnvSettings,\n\n}\n\n\n\nimpl SynthUIData {\n\n pub fn new(synth: Arc<Mutex<Synth<i16>>>, event_sender: mpsc::Sender<SynthUIEvent>, sample_rate: f32) -> Self {\n\n let mut synth_lock = synth.lock().unwrap();\n\n\n\n // attack, decay and release are log scaler representation now\n\n let default_attack_log = slider_log(DefaultParameter::EnvAttack.default_val() as f32);\n\n let default_decay_log = slider_log(DefaultParameter::EnvDecay.default_val() as f32);\n\n let default_release_log = slider_log(DefaultParameter::EnvRelease.default_val() as f32);\n\n let env1 = EnvSettings {\n\n id: 0,\n\n attack: default_attack_log,\n\n decay: default_decay_log,\n\n sustain: DefaultParameter::EnvSustain.default_val(),\n\n release: default_release_log,\n", "file_path": "src/synth_ui/model.rs", "rank": 59, "score": 14287.44249025436 }, { "content": " pub(super) env_idx: f64,\n\n}\n\n\n\n#[derive(Clone, Data, Lens)]\n\npub struct EnvSettings {\n\n pub(super) id: usize,\n\n pub(super) attack: f64,\n\n pub(super) decay: f64,\n\n pub(super) sustain: f64,\n\n pub(super) release: f64,\n\n}\n\n\n\n#[derive(Clone, Data, Lens)]\n\npub struct SynthUIData {\n\n #[data(ignore)]\n\n pub(super) synth: Arc<Mutex<Synth<i16>>>,\n\n #[data(ignore)]\n\n pub(super) event_sender: mpsc::Sender<SynthUIEvent>,\n\n pub(super) octave_modifier: f32,\n\n pub(super) volume_db: f64,\n", "file_path": "src/synth_ui/model.rs", "rank": 61, "score": 14287.202084755176 }, { "content": " fn window_removed(\n\n &mut self,\n\n _id: WindowId,\n\n data: &mut SynthUIData,\n\n _env: &Env,\n\n _ctx: &mut DelegateCtx\n\n ) {\n\n data.event_sender.send(SynthUIEvent::WindowClosed).unwrap();\n\n }\n\n}\n\n\n\n#[derive(Clone, Data, Lens)]\n\npub struct OscSettings {\n\n pub id: usize,\n\n // title: String,\n\n pub(super) wave_idx: f64,\n\n pub(super) volume: f64,\n\n pub(super) transpose: f64,\n\n pub(super) tune: f64,\n\n pub(super) unisons: f64,\n", "file_path": "src/synth_ui/model.rs", "rank": 62, "score": 14285.789749904876 }, { "content": "use crate::synth::WaveForm;\n\nuse super::widgets::WaveFormUI;\n\n\n\n\n\npub const WAVEFORMS: [WaveFormUI; 5] = [\n\n WaveFormUI {\n\n name: \"Saw\",\n\n waveform: WaveForm::Saw,\n\n },\n\n WaveFormUI {\n\n name: \"Sine\",\n\n waveform: WaveForm::Sine,\n\n },\n\n WaveFormUI {\n\n name: \"Square\",\n\n waveform: WaveForm::Square,\n\n },\n\n WaveFormUI {\n\n name: \"Pulse25%\",\n\n waveform: WaveForm::Pulse25,\n", "file_path": "src/synth_ui/constants.rs", "rank": 63, "score": 14284.084031926577 }, { "content": "use druid::{Lens, LensExt, WidgetExt};\n\nuse druid::widget::prelude::*;\n\nuse druid::widget::{Flex, Stepper, Slider, Label, CrossAxisAlignment};\n\n\n\nuse super::model::{SynthUIData, OscSettings, EnvSettings};\n\nuse super::constants::{WAVEFORMS, DefaultParameter};\n\nuse super::widgets::DefaultSlider;\n\nuse crate::synth::adsr_constraints;\n\n\n\n\n\npub const LOG_SCALE_BASE: f64 = 2.;\n\n\n\nconst BASIC_LABEL_WITDH: f64 = 80.0;\n\nconst LABEL_COLOR_MAIN: druid::Color = druid::Color::rgba8(0xe9, 0x1e, 0x63, 0xff);\n\nconst LABEL_COLOR_SECONDARY: druid::Color = druid::Color::rgba8(0x35, 0xaa, 0xee, 0xff);\n\nconst BORDER_COLOR: druid::Color = druid::Color::rgba8(0x03, 0x12, 0x14, 0xff);\n\npub const BACKGROUND_COLOR: druid::Color = druid::Color::rgba8(0x29, 0x29, 0x29, 0xff);\n\nconst TEXT_LARGE: f64 = 22.0;\n\nconst TEXT_MEDIUM: f64 = 18.0;\n\nconst TEXT_SMALL: f64 = 14.0;\n\nconst MAX_UNISONS: f64 = 7.0;\n\nconst ENV_NUM: f64 = 2.0;\n\nconst SLIDER_WIDTH_SMALL: f64 = 110.0;\n\nconst SLIDER_WIDTH_MEDIUM: f64 = 170.0;\n\n\n\n\n", "file_path": "src/synth_ui/layout.rs", "rank": 65, "score": 14283.615326029789 }, { "content": " oscillator1.transpose(osc1.transpose as i8);\n\n oscillator1.set_unison_num(osc1.unisons as usize);\n\n synth_lock.add_osc(oscillator1);\n\n let osc2 = OscSettings {\n\n id: 1,\n\n wave_idx: 1.0,\n\n volume: 0.5,\n\n transpose: -12.0,\n\n tune: 0.0,\n\n unisons: 1.0,\n\n env_idx: 0.0,\n\n };\n\n let mut oscillator2 = Oscillator::new(\n\n sample_rate,\n\n WAVEFORMS[osc2.wave_idx as usize].waveform.clone(),\n\n osc2.env_idx as usize,\n\n osc2.volume as f32);\n\n oscillator2.set_start(Start::Soft);\n\n oscillator2.tune(osc2.tune as i8);\n\n oscillator2.transpose(osc2.transpose as i8);\n", "file_path": "src/synth_ui/model.rs", "rank": 66, "score": 14283.57939873389 }, { "content": " DefaultParameter::EnvSustain.default_val() as f32,\n\n DefaultParameter::EnvRelease.default_val() as u32);\n\n synth_lock.add_env(envelope2);\n\n\n\n let osc1 = OscSettings {\n\n id: 0,\n\n wave_idx: 0.0,\n\n volume: 0.3,\n\n transpose: 0.0,\n\n tune: 15.0,\n\n unisons: 3.0,\n\n env_idx: 0.0,\n\n };\n\n let mut oscillator1 = Oscillator::new(\n\n sample_rate,\n\n WAVEFORMS[osc1.wave_idx as usize].waveform.clone(),\n\n osc1.env_idx as usize,\n\n osc1.volume as f32);\n\n oscillator1.set_start(Start::Soft);\n\n oscillator1.tune(osc1.tune as i8);\n", "file_path": "src/synth_ui/model.rs", "rank": 67, "score": 14282.923646074452 }, { "content": " move |data: &SynthUIData, _| {\n\n let idx = lens_clone.with(data, |osc: &OscSettings| { osc.wave_idx });\n\n WAVEFORMS[idx.round() as usize].name.into()\n\n }\n\n );\n\n let wave_step = Stepper::new()\n\n .with_range(0.0, (WAVEFORMS.len() - 1) as f64)\n\n .with_wraparound(true)\n\n .lens(osc_lens.clone().then(OscSettings::wave_idx));\n\n let wave_flex = Flex::row().with_child(wave_label.fix_width(100.0)).with_child(wave_step);\n\n osc_flex.add_child(wave_flex.padding(row_padding));\n\n\n\n // Transpose\n\n let lens_clone = osc_lens.clone();\n\n let transpose_value = Label::dynamic(\n\n move |data: &SynthUIData, _| {\n\n lens_clone.with(data, |osc: &OscSettings| {\n\n format!(\"{} semitones\",(osc.transpose as i8))\n\n })\n\n }\n", "file_path": "src/synth_ui/layout.rs", "rank": 68, "score": 14282.263559623725 }, { "content": " oscillator2.set_unison_num(osc2.unisons as usize);\n\n synth_lock.add_osc(oscillator2);\n\n\n\n let volume_db = -25.0;\n\n synth_lock.set_volume(volume_db as i32).unwrap();\n\n drop(synth_lock);\n\n Self {\n\n synth,\n\n event_sender,\n\n octave_modifier: 2.0,\n\n volume_db,\n\n osc1,\n\n osc2,\n\n env1,\n\n env2,\n\n }\n\n }\n\n}", "file_path": "src/synth_ui/model.rs", "rank": 71, "score": 14281.372787546201 }, { "content": " ).with_text_size(TEXT_SMALL);\n\n let transpose_slider = DefaultSlider::new(Slider::new()\n\n .with_range(-24.0, 24.0), DefaultParameter::OscTranspose)\n\n .lens(osc_lens.clone().then(OscSettings::transpose));\n\n let transpose_flex = Flex::row()\n\n .with_child(Label::new(\"Transpose\").with_text_size(TEXT_SMALL).fix_width(BASIC_LABEL_WITDH))\n\n .with_child(transpose_slider.fix_width(SLIDER_WIDTH_MEDIUM))\n\n .with_child(transpose_value.fix_width(25.0));\n\n osc_flex.add_child(transpose_flex.padding(row_padding));\n\n\n\n // Tune\n\n let lens_clone = osc_lens.clone();\n\n let tune_value = Label::dynamic(\n\n move |data: &SynthUIData, _| {\n\n lens_clone.with(data, |osc: &OscSettings| { \n\n format!(\"{} cents\",(osc.tune as i8))\n\n })\n\n }\n\n ).with_text_size(TEXT_SMALL);\n\n let tune_slider = DefaultSlider::new(Slider::new()\n", "file_path": "src/synth_ui/layout.rs", "rank": 72, "score": 14280.68612413577 }, { "content": " let attack_slider = DefaultSlider::new(Slider::new()\n\n .with_range(attack_min, attack_max), DefaultParameter::EnvAttack)\n\n .lens(env_lens.clone().then(EnvSettings::attack));\n\n env_flex.add_child(\n\n Flex::row()\n\n .with_child(Label::new(\"Attack\").with_text_size(TEXT_SMALL).fix_width(BASIC_LABEL_WITDH))\n\n .with_child(attack_slider.padding(2.0).fix_width(SLIDER_WIDTH_MEDIUM))\n\n .with_child(attack_value.fix_width(45.0)).padding(5.0)\n\n );\n\n\n\n // Decay\n\n let lens_clone = env_lens.clone();\n\n let decay_value = Label::dynamic(\n\n move |data: &SynthUIData, _| {\n\n format!(\"{} ms\", lens_clone.with(data, |env| { LOG_SCALE_BASE.powf(env.decay).round() }))\n\n }\n\n ).with_text_size(TEXT_SMALL);\n\n // Log scale slider\n\n let decay_min = slider_log(adsr_constraints::MIN_DECAY);\n\n let decay_max = slider_log(adsr_constraints::MAX_DECAY);\n", "file_path": "src/synth_ui/layout.rs", "rank": 73, "score": 14279.814262926539 }, { "content": " let decay_slider = DefaultSlider::new(Slider::new()\n\n .with_range(decay_min, decay_max), DefaultParameter::EnvDecay)\n\n .lens(env_lens.clone().then(EnvSettings::decay));\n\n env_flex.add_child(\n\n Flex::row()\n\n .with_child(Label::new(\"Decay\").with_text_size(TEXT_SMALL).fix_width(BASIC_LABEL_WITDH))\n\n .with_child(decay_slider.padding(2.0).fix_width(SLIDER_WIDTH_MEDIUM))\n\n .with_child(decay_value.fix_width(45.0)).padding(5.0)\n\n );\n\n\n\n // Sustain\n\n let lens_clone = env_lens.clone();\n\n let sustain_value = Label::dynamic(\n\n move |data: &SynthUIData, _| {\n\n format!(\"{:.2}\", lens_clone.with(data, |env| { env.sustain }))\n\n }\n\n ).with_text_size(TEXT_SMALL);\n\n let sustain_slider = DefaultSlider::new(Slider::new()\n\n .with_range(0.0, 1.0), DefaultParameter::EnvSustain)\n\n .lens(env_lens.clone().then(EnvSettings::sustain));\n", "file_path": "src/synth_ui/layout.rs", "rank": 74, "score": 14279.362801523332 }, { "content": " env_flex.add_child(\n\n Flex::row()\n\n .with_child(Label::new(\"Sustain\").with_text_size(TEXT_SMALL).fix_width(BASIC_LABEL_WITDH))\n\n .with_child(sustain_slider.padding(2.0).fix_width(SLIDER_WIDTH_MEDIUM))\n\n .with_child(sustain_value.fix_width(45.0)).padding(5.0)\n\n );\n\n\n\n // Release\n\n let lens_clone = env_lens.clone();\n\n let release_value = Label::dynamic(\n\n move |data: &SynthUIData, _| {\n\n format!(\"{} ms\", lens_clone.with(data, |env| { LOG_SCALE_BASE.powf(env.release).round() }))\n\n }\n\n ).with_text_size(TEXT_SMALL);\n\n // Log scale slider\n\n let release_min = slider_log(adsr_constraints::MIN_RELEASE);\n\n let release_max = slider_log(adsr_constraints::MAX_RELEASE);\n\n let release_slider = DefaultSlider::new(Slider::new()\n\n .with_range(release_min, release_max), DefaultParameter::EnvRelease)\n\n .lens(env_lens.clone().then(EnvSettings::release));\n\n env_flex.add_child(\n\n Flex::row()\n\n .with_child(Label::new(\"Release\").with_text_size(TEXT_SMALL).fix_width(BASIC_LABEL_WITDH))\n\n .with_child(release_slider.padding(2.0).fix_width(SLIDER_WIDTH_MEDIUM))\n\n .with_child(release_value.fix_width(45.0)).padding(5.0)\n\n );\n\n\n\n env_flex.padding(15.0).fix_width(360.0)\n\n}", "file_path": "src/synth_ui/layout.rs", "rank": 76, "score": 14279.153552571563 }, { "content": " let lens_clone = osc_lens.clone();\n\n let env_idx = Label::dynamic(\n\n move |data: &SynthUIData, _| {\n\n ((lens_clone.with(data, |osc| osc.env_idx) + 1.0).round()).to_string()\n\n }\n\n ).with_text_size(TEXT_SMALL);\n\n let env_stepper = Stepper::new()\n\n .with_range(0.0, ENV_NUM - 1.0)\n\n .with_wraparound(true)\n\n .lens(osc_lens.clone().then(OscSettings::env_idx));\n\n let volume_env_flex = Flex::row()\n\n .with_child(volume_slider)\n\n .with_child(Label::new(\"Envelope\").with_text_size(TEXT_SMALL))\n\n .with_child(env_idx)\n\n .with_child(env_stepper);\n\n osc_flex.add_child(volume_env_flex.padding((0.0, 0.0, 0.0, 10.0)));\n\n\n\n // Waveform\n\n let lens_clone = osc_lens.clone();\n\n let wave_label = Label::dynamic(\n", "file_path": "src/synth_ui/layout.rs", "rank": 78, "score": 14278.249415446966 }, { "content": " .with_range(-100.0, 100.0), DefaultParameter::OscTune)\n\n .lens(osc_lens.clone().then(OscSettings::tune));\n\n let tune_flex = Flex::row()\n\n .with_child(Label::new(\"Tune\").with_text_size(TEXT_SMALL).fix_width(BASIC_LABEL_WITDH))\n\n .with_child(tune_slider.fix_width(SLIDER_WIDTH_MEDIUM))\n\n .with_child(tune_value.fix_width(25.0));\n\n osc_flex.add_child(tune_flex.padding(row_padding));\n\n\n\n // Unisons\n\n let uni_stepper = Stepper::new()\n\n .with_range(1.0, MAX_UNISONS)\n\n .with_wraparound(false)\n\n .with_step(1.0)\n\n .lens(osc_lens.clone().then(OscSettings::unisons));\n\n let lens_clone = osc_lens.clone();\n\n let uni_label = Label::dynamic(\n\n move |data: &SynthUIData, _| {\n\n lens_clone.with(data, |osc| {\n\n osc.unisons.round().to_string()\n\n })\n", "file_path": "src/synth_ui/layout.rs", "rank": 79, "score": 14277.482785685801 }, { "content": " },\n\n WaveFormUI {\n\n name: \"Triangle\",\n\n waveform: WaveForm::Triangle,\n\n },\n\n];\n\n\n\nconst DEFAULT_ATTACK: f64 = 300.;\n\nconst DEFAULT_DECAY: f64 = 300.;\n\nconst DEFAULT_SUSTAIN: f64 = 0.7;\n\nconst DEFAULT_RELEASE: f64 = 300.;\n\nconst DEFAULT_TRANSPOSE: f64 = 0.0;\n\nconst DEFAULT_TUNE: f64 = 0.0;\n\nconst DEFAULT_OSC_VOLUME: f64 = 0.5;\n\n\n\npub enum DefaultParameter {\n\n EnvAttack,\n\n EnvDecay,\n\n EnvSustain,\n\n EnvRelease,\n", "file_path": "src/synth_ui/constants.rs", "rank": 80, "score": 14275.779843376575 }, { "content": " OscTranspose,\n\n OscTune,\n\n OscVolume,\n\n}\n\n\n\nimpl DefaultParameter {\n\n pub fn default_val(&self) -> f64 {\n\n match self {\n\n DefaultParameter::EnvAttack => DEFAULT_ATTACK,\n\n DefaultParameter::EnvDecay => DEFAULT_DECAY,\n\n DefaultParameter::EnvSustain => DEFAULT_SUSTAIN,\n\n DefaultParameter::EnvRelease => DEFAULT_RELEASE,\n\n DefaultParameter::OscTranspose => DEFAULT_TRANSPOSE,\n\n DefaultParameter::OscTune => DEFAULT_TUNE,\n\n DefaultParameter::OscVolume => DEFAULT_OSC_VOLUME,\n\n }\n\n }\n\n}", "file_path": "src/synth_ui/constants.rs", "rank": 81, "score": 14274.963811635444 }, { "content": " };\n\n let envelope1 = ADSR::new(\n\n sample_rate,\n\n DefaultParameter::EnvAttack.default_val() as u32,\n\n DefaultParameter::EnvDecay.default_val() as u32,\n\n DefaultParameter::EnvSustain.default_val() as f32,\n\n DefaultParameter::EnvRelease.default_val() as u32);\n\n synth_lock.add_env(envelope1);\n\n\n\n let env2 = EnvSettings {\n\n id: 1,\n\n attack: default_attack_log,\n\n decay: default_decay_log,\n\n sustain: DefaultParameter::EnvSustain.default_val(),\n\n release: default_release_log,\n\n };\n\n let envelope2 = ADSR::new(\n\n sample_rate,\n\n DefaultParameter::EnvAttack.default_val() as u32,\n\n DefaultParameter::EnvDecay.default_val() as u32,\n", "file_path": "src/synth_ui/model.rs", "rank": 82, "score": 14274.645602623541 }, { "content": " }\n\n );\n\n let uni_flex = Flex::row()\n\n .with_child(Label::new(\"Unisons\").with_text_size(TEXT_SMALL))\n\n .with_child(uni_label)\n\n .with_child(uni_stepper);\n\n osc_flex.add_child(uni_flex.padding(row_padding));\n\n\n\n osc_flex.padding(5.0).border(BORDER_COLOR, 1.0).fix_width(390.0)\n\n}\n\n\n", "file_path": "src/synth_ui/layout.rs", "rank": 83, "score": 14272.157492340088 }, { "content": "enum PhaseStart {\n\n Soft,\n\n Hard(f32),\n\n Random(f32),\n\n}\n\n\n\nimpl PhaseStart {\n\n fn value(&self) -> f32 {\n\n match self {\n\n PhaseStart::Soft => 0.0,\n\n PhaseStart::Hard(period) => period / 4.0,\n\n PhaseStart::Random(period) => period * rand::random::<f32>(),\n\n }\n\n }\n\n\n\n fn change_period(&mut self, period: f32) {\n\n match self {\n\n PhaseStart::Soft => {}\n\n PhaseStart::Hard(_) => *self = PhaseStart::Random(period),\n\n PhaseStart::Random(_) => *self = PhaseStart::Random(period),\n", "file_path": "src/synth/oscillator.rs", "rank": 84, "score": 13558.309132649632 }, { "content": "type Milliseconds = u32;\n\n\n\n#[allow(dead_code)]\n\npub mod adsr_constraints {\n\n pub const MIN_ATTACK: f32 = 1.;\n\n pub const MAX_ATTACK: f32 = 3000.;\n\n pub const MIN_DECAY: f32 = 1.;\n\n pub const MAX_DECAY: f32 = 3000.;\n\n pub const MIN_SUSTAIN: f32 = 0.;\n\n pub const MAX_SUSTAIN: f32 = 1.;\n\n pub const MIN_RELEASE: f32 = 1.;\n\n pub const MAX_RELEASE: f32 = 3000.;\n\n}\n\n\n\npub enum ADSRParam {\n\n Attack(f32),\n\n Decay(f32),\n\n Sustain(f32),\n\n Release(f32),\n\n}\n", "file_path": "src/synth/envelope.rs", "rank": 85, "score": 13558.309132649632 }, { "content": "mod error;\n\nmod synth;\n\nmod synth_ui;\n\n/// TODO: Callback, Github, Panning, Filter\n\nuse error::{BaseError, Result};\n\nuse synth::{SampleFormat, Synth};\n\n\n\nuse druid::{AppLauncher, WindowDesc};\n\nuse std::sync::{mpsc, Arc, Mutex};\n\nuse synth_ui::{build_ui, SynthUIData, SynthUIEvent};\n\n\n\nuse portaudio_rs as pa;\n\n\n\nconst SAMPLE_RATE: f32 = 44100.0;\n\nconst CHANNELS_NUM: usize = 2;\n\nconst BUF_SIZE: u32 = 600;\n\n\n", "file_path": "src/main.rs", "rank": 86, "score": 12.82856578463339 }, { "content": "}\n\n\n\nimpl From<portaudio_rs::PaError> for BaseError {\n\n fn from(e: portaudio_rs::PaError) -> Self {\n\n BaseError::PaError(e)\n\n }\n\n}\n\n\n\n// impl From<alsa::Error> for BaseError {\n\n// fn from(e: alsa::Error) -> Self {\n\n// BaseError::AlsaError(e)\n\n// }\n\n// }\n\n\n\n// Unstable feature\n\n// impl From<std::option::NoneError> for BaseError {\n\n// fn from(e: std::option::NoneError) -> Self {\n\n\n\n// }\n\n// }\n", "file_path": "src/error.rs", "rank": 87, "score": 12.069789406198566 }, { "content": "use std::error::Error;\n\nuse std::fmt;\n\n\n\npub type Result<T> = std::result::Result<T, BaseError>;\n\n\n\n#[allow(dead_code)]\n\n#[derive(Debug)]\n\npub enum BaseError {\n\n PaError(portaudio_rs::PaError),\n\n InputError(String),\n\n WindowCreation(String),\n\n SynthError(String),\n\n ConversionError(String),\n\n StreamError(String),\n\n GUIError(String),\n\n ThreadError(String),\n\n}\n\n\n\nimpl std::fmt::Display for BaseError {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n", "file_path": "src/error.rs", "rank": 88, "score": 11.436293153662955 }, { "content": " match self {\n\n BaseError::PaError(e) => e.fmt(f),\n\n BaseError::InputError(msg) => write!(f, \"Input error: {}\", msg),\n\n BaseError::WindowCreation(msg) => write!(f, \"Window creation error: {}\", msg),\n\n BaseError::SynthError(msg) => write!(f, \"Synth error: {}\", msg),\n\n BaseError::ConversionError(msg) => write!(f, \"Conversion error: {}\", msg),\n\n BaseError::StreamError(msg) => write!(f, \"Stream error: {}\", msg),\n\n BaseError::GUIError(msg) => write!(f, \"GUI error: {}\", msg),\n\n BaseError::ThreadError(msg) => write!(f, \"Thread error: {}\", msg),\n\n }\n\n }\n\n}\n\n\n\nimpl Error for BaseError {\n\n fn source(&self) -> Option<&(dyn Error + 'static)> {\n\n match self {\n\n BaseError::PaError(ref e) => Some(e),\n\n _ => None,\n\n }\n\n }\n", "file_path": "src/error.rs", "rank": 89, "score": 11.235758486566034 }, { "content": " Ok(())\n\n });\n\n\n\n let _th = match th {\n\n Ok(handler) => handler,\n\n Err(_) => return Err(BaseError::ThreadError(\"Can't start synth thread\".into())),\n\n };\n\n\n\n {\n\n let window = WindowDesc::new(build_ui)\n\n .title(\"beep-boop\")\n\n .with_min_size((860.0, 550.0))\n\n .resizable(false);\n\n let launcher = AppLauncher::with_window(window);\n\n\n\n launcher\n\n .delegate(synth_ui::Delegate)\n\n .launch(SynthUIData::new(synth_arc, synth_event, SAMPLE_RATE))\n\n .expect(\"Starting beep-boop GUI failed :(\");\n\n }\n\n\n\n _th.join().expect(\"Synth thread join error\")?;\n\n Ok(())\n\n}\n", "file_path": "src/main.rs", "rank": 90, "score": 9.60180103672463 }, { "content": " None => return Err(BaseError::StreamError(\"Can't get latency info\".to_owned())),\n\n };\n\n\n\n let output_params = pa::stream::StreamParameters::<SF> {\n\n device: default_output,\n\n channel_count: channels_num,\n\n suggested_latency: latency,\n\n data: SF::min_value(),\n\n };\n\n\n\n let _supported =\n\n pa::stream::is_format_supported::<SF, SF>(None, Some(output_params), sample_rate as f64)?;\n\n\n\n let stream = match pa::stream::Stream::<SF, SF>::open(\n\n None,\n\n Some(output_params),\n\n sample_rate as f64,\n\n buf_size as u64,\n\n pa::stream::StreamFlags::empty(),\n\n callback,\n", "file_path": "src/main.rs", "rank": 91, "score": 7.050972542733526 }, { "content": " let stream = create_output_stream::<i16>(SAMPLE_RATE, BUF_SIZE, CHANNELS_NUM as u32, Some(callback))?;\n\n\n\n 'synthloop: loop {\n\n match wait_synth_event.recv() {\n\n Ok(SynthUIEvent::NewNotes) => {\n\n if !stream.is_active()? {\n\n stream.start()?\n\n }\n\n wait_stream_finished.recv().unwrap();\n\n if stream.is_active()? {\n\n stream.stop()?\n\n }\n\n },\n\n Ok(SynthUIEvent::WindowClosed) | Err(_) => {\n\n break 'synthloop\n\n },\n\n }\n\n }\n\n drop(stream);\n\n pa::terminate()?;\n", "file_path": "src/main.rs", "rank": 92, "score": 5.922732137022182 }, { "content": " _flags: pa::stream::StreamCallbackFlags| -> pa::stream::StreamCallbackResult\n\n {\n\n let mut synth = synth_callback.lock().unwrap();\n\n if !synth.playing() {\n\n stream_finished.send(()).unwrap();\n\n return pa::stream::StreamCallbackResult::Complete\n\n }\n\n let mut sample = synth.next().unwrap();\n\n let mut written = 0;\n\n for i in 0..output.len() {\n\n output[i] = sample;\n\n written += 1;\n\n if written == CHANNELS_NUM {\n\n sample = synth.next().unwrap();\n\n written = 0;\n\n }\n\n }\n\n pa::stream::StreamCallbackResult::Continue\n\n }\n\n );\n", "file_path": "src/main.rs", "rank": 93, "score": 5.614990590537012 }, { "content": "## Controls\n\nIt can be played only with keyboard and uses piano-like layout where 'z' key is binded to C piano key, 's' key is C#, 'x' is D and so on ending on 'm' key which represents B. It's range is only one octave, but you can switch octaves up and down using left and right arrow keys.\n\n\n\nApplication can be closed by pressing Escape.\n\n\n\n## Demo\n\nVery unprofessional demo recorded on a microphone directly from my speakers. Sorry about quality. \n\nhttps://user-images.githubusercontent.com/36864010/163676890-1f525295-d085-4942-bb2b-0abf3f6bddbd.mp4\n\n\n\n\n\n## TODO:\n\n\n\n* Probably rework all the internals responsible for producing sounds and optimise it\n\n* Make limited pool of voices available\n\n* Switch between mono and poly modes\n\n* Some form of panning, maybe stereo spread for unisons\n\n* Would be great to implement basic LP/HP filters\n\n\n\n\n\n[portaudio-rs]: https://github.com/mvdnes/portaudio-rs\n\n[druid]: https://github.com/linebender/druid\n\n[rand]: https://github.com/rust-random/rand\n\n[num-traits]: https://github.com/rust-num/num-traits\n", "file_path": "README.md", "rank": 94, "score": 4.444387123721478 }, { "content": "## Beep-boop\n\nToy synthesizer written in Rust. \n\nI was just curious how to make this thing produce sounds. Also this was my first non \"Hello, world!\"-type project in Rust. \n\nIt works on Ubuntu 20 and its the one and only platform I truly tested it on.\n\n\n\n## Content\n\n* [Dependencies](#dependencies)\n\n* [Interface](#interface)\n\n* [Controls](#controls)\n\n* [Demo](#demo)\n\n* [TODO:](#todo) \n\n\n\n## Dependencies\n\n* Beep-boop uses [Portaudio-rs][portaudio-rs] to produce sounds\n\n* [Druid][druid] for that magnificent look\n\n* [Rand][rand] to generate random numbers for phase purposes\n\n* and [Num-traits][num-traits] to define sample formats\n\n\n\n## Interface\n\n![Beep-boop UI](../media/images/beep-boop-default-ui.png?raw=true) \n\n\n\nBeep-boop has two identical **oscillators** with five waveforms each:\n\n* Sine\n\n* Triangle\n\n* Saw\n\n* Square\n\n* Pulse with 25% width\n\n\n\nBoth oscillators have volume slider, transpose control which changes pitch in semitones and tune control to change pitch in cents. \n\nThere are up to 7 unison voices. If current unison count for oscillator is more than 1, tune control starts to act as a spread control, affecting fine tuning of each unison differently relative to base pitch. \n\nSo if you have 5 unisons with tune control at 10 and play middle C, 1 voice is going to be right on the middle C frequency (around 261.63 Hz), 2 unisons 5 cents apart from that (one 5 cents up and the other 5 cents down) and other 2 unisons 2.5 cents apart from middle C. \n\n\n\nFor each oscillator you can pick one of the two **ADSR-envelopes**. \n\nEnvelopes have log scale sliders for standard attack, decay, sustain and release controls. Values for sustain are in 0.0-1.0 range and for the other parameters it's from 1 ms to 3000 ms. With _Ctrl+click_ those values can be reset to default.\n\n\n\nOf course there is general output volume slider on top-right. And that's it.\n\n\n", "file_path": "README.md", "rank": 95, "score": 3.955185501362012 }, { "content": " ) {\n\n Ok(s) => s,\n\n Err(e) => {\n\n eprintln!(\"Error opening stream: {}\", e);\n\n return Err(BaseError::PaError(e));\n\n }\n\n };\n\n\n\n Ok(stream)\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 96, "score": 2.6755678532352913 } ]
Rust
vendor/dwrote/src/font_face.rs
vcapra1/alacritty
64026e22f889004c04297dfece71b2a65edb7f38
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::cell::UnsafeCell; use std::mem::{self, zeroed}; use std::ptr; use std::slice; use winapi::ctypes::c_void; use winapi::shared::minwindef::{BOOL, FALSE, TRUE}; use winapi::shared::winerror::S_OK; use winapi::um::dcommon::DWRITE_MEASURING_MODE; use winapi::um::dwrite::IDWriteRenderingParams; use winapi::um::dwrite::DWRITE_FONT_FACE_TYPE_TRUETYPE; use winapi::um::dwrite::{IDWriteFontFace, IDWriteFontFile}; use winapi::um::dwrite::{DWRITE_FONT_FACE_TYPE_BITMAP, DWRITE_FONT_FACE_TYPE_CFF}; use winapi::um::dwrite::{DWRITE_FONT_FACE_TYPE_RAW_CFF, DWRITE_FONT_FACE_TYPE_TYPE1}; use winapi::um::dwrite::{DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION, DWRITE_FONT_FACE_TYPE_VECTOR}; use winapi::um::dwrite::{DWRITE_FONT_SIMULATIONS, DWRITE_GLYPH_METRICS}; use winapi::um::dwrite::{DWRITE_GLYPH_OFFSET, DWRITE_MATRIX, DWRITE_RENDERING_MODE}; use winapi::um::dwrite::{DWRITE_RENDERING_MODE_DEFAULT, DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC}; use winapi::um::dwrite_1::IDWriteFontFace1; use winapi::um::dwrite_3::{IDWriteFontFace5, IDWriteFontResource, DWRITE_FONT_AXIS_VALUE}; use wio::com::ComPtr; use super::{DWriteFactory, DefaultDWriteRenderParams, FontFile, FontMetrics}; use crate::com_helpers::Com; use crate::geometry_sink_impl::GeometrySinkImpl; use crate::outline_builder::OutlineBuilder; pub struct FontFace { native: UnsafeCell<ComPtr<IDWriteFontFace>>, face5: UnsafeCell<Option<ComPtr<IDWriteFontFace5>>>, } impl FontFace { pub fn take(native: ComPtr<IDWriteFontFace>) -> FontFace { let cell = UnsafeCell::new(native); FontFace { native: cell, face5: UnsafeCell::new(None), } } pub unsafe fn as_ptr(&self) -> *mut IDWriteFontFace { (*self.native.get()).as_raw() } unsafe fn get_raw_files(&self) -> Vec<*mut IDWriteFontFile> { let mut number_of_files: u32 = 0; let hr = (*self.native.get()).GetFiles(&mut number_of_files, ptr::null_mut()); assert!(hr == 0); let mut file_ptrs: Vec<*mut IDWriteFontFile> = vec![ptr::null_mut(); number_of_files as usize]; let hr = (*self.native.get()).GetFiles(&mut number_of_files, file_ptrs.as_mut_ptr()); assert!(hr == 0); file_ptrs } pub fn get_files(&self) -> Vec<FontFile> { unsafe { let file_ptrs = self.get_raw_files(); file_ptrs .iter() .map(|p| FontFile::take(ComPtr::from_raw(*p))) .collect() } } pub fn create_font_face_with_simulations( &self, simulations: DWRITE_FONT_SIMULATIONS, ) -> FontFace { unsafe { let file_ptrs = self.get_raw_files(); let face_type = (*self.native.get()).GetType(); let face_index = (*self.native.get()).GetIndex(); let mut face: *mut IDWriteFontFace = ptr::null_mut(); let hr = (*DWriteFactory()).CreateFontFace( face_type, file_ptrs.len() as u32, file_ptrs.as_ptr(), face_index, simulations, &mut face, ); for p in file_ptrs { let _ = ComPtr::<IDWriteFontFile>::from_raw(p); } assert!(hr == 0); FontFace::take(ComPtr::from_raw(face)) } } pub fn get_glyph_count(&self) -> u16 { unsafe { (*self.native.get()).GetGlyphCount() } } pub fn metrics(&self) -> FontMetrics { unsafe { let font_1: Option<ComPtr<IDWriteFontFace1>> = (*self.native.get()).cast().ok(); match font_1 { None => { let mut metrics = mem::zeroed(); (*self.native.get()).GetMetrics(&mut metrics); FontMetrics::Metrics0(metrics) } Some(font_1) => { let mut metrics_1 = mem::zeroed(); font_1.GetMetrics(&mut metrics_1); FontMetrics::Metrics1(metrics_1) } } } } pub fn get_glyph_indices(&self, code_points: &[u32]) -> Vec<u16> { unsafe { let mut glyph_indices: Vec<u16> = vec![0; code_points.len()]; let hr = (*self.native.get()).GetGlyphIndices( code_points.as_ptr(), code_points.len() as u32, glyph_indices.as_mut_ptr(), ); assert!(hr == 0); glyph_indices } } pub fn get_design_glyph_metrics( &self, glyph_indices: &[u16], is_sideways: bool, ) -> Vec<DWRITE_GLYPH_METRICS> { unsafe { let mut metrics: Vec<DWRITE_GLYPH_METRICS> = vec![zeroed(); glyph_indices.len()]; let hr = (*self.native.get()).GetDesignGlyphMetrics( glyph_indices.as_ptr(), glyph_indices.len() as u32, metrics.as_mut_ptr(), is_sideways as BOOL, ); assert!(hr == 0); metrics } } pub fn get_gdi_compatible_glyph_metrics( &self, em_size: f32, pixels_per_dip: f32, transform: *const DWRITE_MATRIX, use_gdi_natural: bool, glyph_indices: &[u16], is_sideways: bool, ) -> Vec<DWRITE_GLYPH_METRICS> { unsafe { let mut metrics: Vec<DWRITE_GLYPH_METRICS> = vec![zeroed(); glyph_indices.len()]; let hr = (*self.native.get()).GetGdiCompatibleGlyphMetrics( em_size, pixels_per_dip, transform, use_gdi_natural as BOOL, glyph_indices.as_ptr(), glyph_indices.len() as u32, metrics.as_mut_ptr(), is_sideways as BOOL, ); assert!(hr == 0); metrics } } pub fn get_font_table(&self, opentype_table_tag: u32) -> Option<Vec<u8>> { unsafe { let mut table_data_ptr: *const u8 = ptr::null_mut(); let mut table_size: u32 = 0; let mut table_context: *mut c_void = ptr::null_mut(); let mut exists: BOOL = FALSE; let hr = (*self.native.get()).TryGetFontTable( opentype_table_tag, &mut table_data_ptr as *mut *const _ as *mut *const c_void, &mut table_size, &mut table_context, &mut exists, ); assert!(hr == 0); if exists == FALSE { return None; } let table_bytes = slice::from_raw_parts(table_data_ptr, table_size as usize).to_vec(); (*self.native.get()).ReleaseFontTable(table_context); Some(table_bytes) } } pub fn get_recommended_rendering_mode( &self, em_size: f32, pixels_per_dip: f32, measure_mode: DWRITE_MEASURING_MODE, rendering_params: *mut IDWriteRenderingParams, ) -> DWRITE_RENDERING_MODE { unsafe { let mut render_mode: DWRITE_RENDERING_MODE = DWRITE_RENDERING_MODE_DEFAULT; let hr = (*self.native.get()).GetRecommendedRenderingMode( em_size, pixels_per_dip, measure_mode, rendering_params, &mut render_mode, ); if hr != 0 { return DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC; } render_mode } } pub fn get_recommended_rendering_mode_default_params( &self, em_size: f32, pixels_per_dip: f32, measure_mode: DWRITE_MEASURING_MODE, ) -> DWRITE_RENDERING_MODE { self.get_recommended_rendering_mode( em_size, pixels_per_dip, measure_mode, DefaultDWriteRenderParams(), ) } pub fn get_glyph_run_outline( &self, em_size: f32, glyph_indices: &[u16], glyph_advances: Option<&[f32]>, glyph_offsets: Option<&[DWRITE_GLYPH_OFFSET]>, is_sideways: bool, is_right_to_left: bool, outline_builder: Box<dyn OutlineBuilder>, ) { unsafe { let glyph_advances = match glyph_advances { None => ptr::null(), Some(glyph_advances) => { assert_eq!(glyph_advances.len(), glyph_indices.len()); glyph_advances.as_ptr() } }; let glyph_offsets = match glyph_offsets { None => ptr::null(), Some(glyph_offsets) => { assert_eq!(glyph_offsets.len(), glyph_indices.len()); glyph_offsets.as_ptr() } }; let is_sideways = if is_sideways { TRUE } else { FALSE }; let is_right_to_left = if is_right_to_left { TRUE } else { FALSE }; let geometry_sink = GeometrySinkImpl::new(outline_builder); let geometry_sink = geometry_sink.into_interface(); let hr = (*self.native.get()).GetGlyphRunOutline( em_size, glyph_indices.as_ptr(), glyph_advances, glyph_offsets, glyph_indices.len() as u32, is_sideways, is_right_to_left, geometry_sink, ); assert_eq!(hr, S_OK); } } #[inline] pub fn get_type(&self) -> FontFaceType { unsafe { match (*self.native.get()).GetType() { DWRITE_FONT_FACE_TYPE_CFF => FontFaceType::Cff, DWRITE_FONT_FACE_TYPE_RAW_CFF => FontFaceType::RawCff, DWRITE_FONT_FACE_TYPE_TRUETYPE => FontFaceType::TrueType, DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION => FontFaceType::TrueTypeCollection, DWRITE_FONT_FACE_TYPE_TYPE1 => FontFaceType::Type1, DWRITE_FONT_FACE_TYPE_VECTOR => FontFaceType::Vector, DWRITE_FONT_FACE_TYPE_BITMAP => FontFaceType::Bitmap, _ => FontFaceType::Unknown, } } } #[inline] pub fn get_index(&self) -> u32 { unsafe { (*self.native.get()).GetIndex() } } #[inline] unsafe fn get_face5(&self) -> Option<ComPtr<IDWriteFontFace5>> { if (*self.face5.get()).is_none() { *self.face5.get() = (*self.native.get()).cast().ok() } (*self.face5.get()).clone() } pub fn has_variations(&self) -> bool { unsafe { match self.get_face5() { Some(face5) => face5.HasVariations() == TRUE, None => false, } } } pub fn create_font_face_with_variations( &self, simulations: DWRITE_FONT_SIMULATIONS, axis_values: &[DWRITE_FONT_AXIS_VALUE], ) -> Option<FontFace> { unsafe { if let Some(face5) = self.get_face5() { let mut resource: *mut IDWriteFontResource = ptr::null_mut(); let hr = face5.GetFontResource(&mut resource); if hr == S_OK && !resource.is_null() { let resource = ComPtr::from_raw(resource); let mut var_face: *mut IDWriteFontFace5 = ptr::null_mut(); let hr = resource.CreateFontFace( simulations, axis_values.as_ptr(), axis_values.len() as u32, &mut var_face, ); if hr == S_OK && !var_face.is_null() { let var_face = ComPtr::from_raw(var_face).cast().unwrap(); return Some(FontFace::take(var_face)); } } } None } } } impl Clone for FontFace { fn clone(&self) -> FontFace { unsafe { FontFace { native: UnsafeCell::new((*self.native.get()).clone()), face5: UnsafeCell::new(None), } } } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum FontFaceType { Unknown, Cff, RawCff, TrueType, TrueTypeCollection, Type1, Vector, Bitmap, }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::cell::UnsafeCell; use std::mem::{self, zeroed}; use std::ptr; use std::slice; use winapi::ctypes::c_void; use winapi::shared::minwindef::{BOOL, FALSE, TRUE}; use winapi::shared::winerror::S_OK; use winapi::um::dcommon::DWRITE_MEASURING_MODE; use winapi::um::dwrite::IDWriteRenderingParams; use winapi::um::dwrite::DWRITE_FONT_FACE_TYPE_TRUETYPE; use winapi::um::dwrite::{IDWriteFontFace, IDWriteFontFile}; use winapi::um::dwrite::{DWRITE_FONT_FACE_TYPE_BITMAP, DWRITE_FONT_FACE_TYPE_CFF}; use winapi::um::dwrite::{DWRITE_FONT_FACE_TYPE_RAW_CFF, DWRITE_FONT_FACE_TYPE_TYPE1}; use winapi::um::dwrite::{DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION, DWRITE_FONT_FACE_TYPE_VECTOR}; use winapi::um::dwrite::{DWRITE_FONT_SIMULATIONS, DWRITE_GLYPH_METRICS}; use winapi::um::dwrite::{DWRITE_GLYPH_OFFSET, DWRITE_MATRIX, DWRITE_RENDERING_MODE}; use winapi::um::dwrite::{DWRITE_RENDERING_MODE_DEFAULT, DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC}; use winapi::um::dwrite_1::IDWriteFontFace1; use winapi::um::dwrite_3::{IDWriteFontFace5, IDWriteFontResource, DWRITE_FONT_AXIS_VALUE}; use wio::com::ComPtr; use super::{DWriteFactory, DefaultDWriteRenderParams, FontFile, FontMetrics}; use crate::com_helpers::Com; use crate::geometry_sink_impl::GeometrySinkImpl; use crate::outline_builder::OutlineBuilder; pub struct FontFace { native: UnsafeCell<ComPtr<IDWriteFontFace>>, face5: UnsafeCell<Option<ComPtr<IDWriteFontFace5>>>, } impl FontFace { pub fn take(native: ComPtr<IDWriteFontFace>) -> FontFace { let cell = UnsafeCell::new(native); FontFace { native: cell, face5: UnsafeCell::new(None), } } pub unsafe fn as_ptr(&self) -> *mut IDWriteFontFace { (*self.native.get()).as_raw() } unsafe fn get_raw_files(&self) -> Vec<*mut IDWriteFontFile> { let mut number_of_files: u32 = 0; let hr = (*self.native.get()).GetFiles(&mut number_of_files, ptr::null_mut()); assert!(hr == 0); let mut file_ptrs: Vec<*mut IDWriteFontFile> = vec![ptr::null_mut(); number_of_files as usize]; let hr = (*self.native.get()).GetFiles(&mut number_of_files, file_ptrs.as_mut_ptr()); assert!(hr == 0); file_ptrs } pub fn get_files(&self) -> Vec<FontFile> { unsafe { let file_ptrs = self.get_raw_files(); file_ptrs .iter() .map(|p| FontFile::take(ComPtr::from_raw(*p))) .collect() } } pub fn create_font_face_with_simulations( &self, simulations: DWRITE_FONT_SIMULATIONS, ) -> FontFace { unsafe { let file_ptrs = self.get_raw_files(); let face_type = (*self.native.get()).GetType(); let face_index = (*self.native.get()).GetIndex(); let mut face: *mut IDWriteFontFace = ptr::null_mut(); let hr = (*DWriteFactory()).CreateFontFace( face_type, file_ptrs.len() as u32, file_ptrs.as_ptr(), face_index, simulations, &mut face, ); for p in file_ptrs { let _ = ComPtr::<IDWriteFontFile>::from_raw(p); } assert!(hr == 0); FontFace::take(ComPtr::from_raw(face)) } } pub fn get_glyph_count(&self) -> u16 { unsafe { (*self.native.get()).GetGlyphCount() } } pub fn metrics(&self) -> FontMetrics { unsafe { let font_1: Option<ComPtr<IDWriteFontFace1>> = (*self.native.get()).cast().ok(); match font_1 { None => { let mut metrics = mem::zeroed(); (*self.native.get()).GetMetrics(&mut metrics); FontMetrics::Metrics0(metrics) } Some(font_1) => { let mut metrics_1 = mem::zeroed(); font_1.GetMetrics(&mut metrics_1); FontMetrics::Metrics1(metrics_1) } } } } pub fn get_glyph_indices(&self, code_points: &[u32]) -> Vec<u16> { unsafe { let mut glyph_indices: Vec<u16> = vec![0; code_points.len()]; let hr = (*self.native.get()).GetGlyphIndices( code_points.as_ptr(), code_points.len() as u32, glyph_indices.as_mut_ptr(), ); assert!(hr == 0); glyph_indices } } pub fn get_design_glyph_metrics( &self, glyph_indices: &[u16], is_sideways: bool, ) -> Vec<DWRITE_GLYPH_METRICS> { unsafe { let mut metrics: Vec<DWRITE_GLYPH_METRICS> = vec![zeroed(); glyph_indices.len()]; let hr = (*self.native.get()).GetDesignGlyphMetrics( glyph_indices.as_ptr(), glyph_indices.len() as u32, metrics.as_mut_ptr(), is_sideways as BOOL, ); assert!(hr == 0); metrics } } pub fn get_gdi_compatible_glyph_metrics( &self, em_size: f32, pixels_per_dip: f3
pub fn get_font_table(&self, opentype_table_tag: u32) -> Option<Vec<u8>> { unsafe { let mut table_data_ptr: *const u8 = ptr::null_mut(); let mut table_size: u32 = 0; let mut table_context: *mut c_void = ptr::null_mut(); let mut exists: BOOL = FALSE; let hr = (*self.native.get()).TryGetFontTable( opentype_table_tag, &mut table_data_ptr as *mut *const _ as *mut *const c_void, &mut table_size, &mut table_context, &mut exists, ); assert!(hr == 0); if exists == FALSE { return None; } let table_bytes = slice::from_raw_parts(table_data_ptr, table_size as usize).to_vec(); (*self.native.get()).ReleaseFontTable(table_context); Some(table_bytes) } } pub fn get_recommended_rendering_mode( &self, em_size: f32, pixels_per_dip: f32, measure_mode: DWRITE_MEASURING_MODE, rendering_params: *mut IDWriteRenderingParams, ) -> DWRITE_RENDERING_MODE { unsafe { let mut render_mode: DWRITE_RENDERING_MODE = DWRITE_RENDERING_MODE_DEFAULT; let hr = (*self.native.get()).GetRecommendedRenderingMode( em_size, pixels_per_dip, measure_mode, rendering_params, &mut render_mode, ); if hr != 0 { return DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC; } render_mode } } pub fn get_recommended_rendering_mode_default_params( &self, em_size: f32, pixels_per_dip: f32, measure_mode: DWRITE_MEASURING_MODE, ) -> DWRITE_RENDERING_MODE { self.get_recommended_rendering_mode( em_size, pixels_per_dip, measure_mode, DefaultDWriteRenderParams(), ) } pub fn get_glyph_run_outline( &self, em_size: f32, glyph_indices: &[u16], glyph_advances: Option<&[f32]>, glyph_offsets: Option<&[DWRITE_GLYPH_OFFSET]>, is_sideways: bool, is_right_to_left: bool, outline_builder: Box<dyn OutlineBuilder>, ) { unsafe { let glyph_advances = match glyph_advances { None => ptr::null(), Some(glyph_advances) => { assert_eq!(glyph_advances.len(), glyph_indices.len()); glyph_advances.as_ptr() } }; let glyph_offsets = match glyph_offsets { None => ptr::null(), Some(glyph_offsets) => { assert_eq!(glyph_offsets.len(), glyph_indices.len()); glyph_offsets.as_ptr() } }; let is_sideways = if is_sideways { TRUE } else { FALSE }; let is_right_to_left = if is_right_to_left { TRUE } else { FALSE }; let geometry_sink = GeometrySinkImpl::new(outline_builder); let geometry_sink = geometry_sink.into_interface(); let hr = (*self.native.get()).GetGlyphRunOutline( em_size, glyph_indices.as_ptr(), glyph_advances, glyph_offsets, glyph_indices.len() as u32, is_sideways, is_right_to_left, geometry_sink, ); assert_eq!(hr, S_OK); } } #[inline] pub fn get_type(&self) -> FontFaceType { unsafe { match (*self.native.get()).GetType() { DWRITE_FONT_FACE_TYPE_CFF => FontFaceType::Cff, DWRITE_FONT_FACE_TYPE_RAW_CFF => FontFaceType::RawCff, DWRITE_FONT_FACE_TYPE_TRUETYPE => FontFaceType::TrueType, DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION => FontFaceType::TrueTypeCollection, DWRITE_FONT_FACE_TYPE_TYPE1 => FontFaceType::Type1, DWRITE_FONT_FACE_TYPE_VECTOR => FontFaceType::Vector, DWRITE_FONT_FACE_TYPE_BITMAP => FontFaceType::Bitmap, _ => FontFaceType::Unknown, } } } #[inline] pub fn get_index(&self) -> u32 { unsafe { (*self.native.get()).GetIndex() } } #[inline] unsafe fn get_face5(&self) -> Option<ComPtr<IDWriteFontFace5>> { if (*self.face5.get()).is_none() { *self.face5.get() = (*self.native.get()).cast().ok() } (*self.face5.get()).clone() } pub fn has_variations(&self) -> bool { unsafe { match self.get_face5() { Some(face5) => face5.HasVariations() == TRUE, None => false, } } } pub fn create_font_face_with_variations( &self, simulations: DWRITE_FONT_SIMULATIONS, axis_values: &[DWRITE_FONT_AXIS_VALUE], ) -> Option<FontFace> { unsafe { if let Some(face5) = self.get_face5() { let mut resource: *mut IDWriteFontResource = ptr::null_mut(); let hr = face5.GetFontResource(&mut resource); if hr == S_OK && !resource.is_null() { let resource = ComPtr::from_raw(resource); let mut var_face: *mut IDWriteFontFace5 = ptr::null_mut(); let hr = resource.CreateFontFace( simulations, axis_values.as_ptr(), axis_values.len() as u32, &mut var_face, ); if hr == S_OK && !var_face.is_null() { let var_face = ComPtr::from_raw(var_face).cast().unwrap(); return Some(FontFace::take(var_face)); } } } None } } } impl Clone for FontFace { fn clone(&self) -> FontFace { unsafe { FontFace { native: UnsafeCell::new((*self.native.get()).clone()), face5: UnsafeCell::new(None), } } } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum FontFaceType { Unknown, Cff, RawCff, TrueType, TrueTypeCollection, Type1, Vector, Bitmap, }
2, transform: *const DWRITE_MATRIX, use_gdi_natural: bool, glyph_indices: &[u16], is_sideways: bool, ) -> Vec<DWRITE_GLYPH_METRICS> { unsafe { let mut metrics: Vec<DWRITE_GLYPH_METRICS> = vec![zeroed(); glyph_indices.len()]; let hr = (*self.native.get()).GetGdiCompatibleGlyphMetrics( em_size, pixels_per_dip, transform, use_gdi_natural as BOOL, glyph_indices.as_ptr(), glyph_indices.len() as u32, metrics.as_mut_ptr(), is_sideways as BOOL, ); assert!(hr == 0); metrics } }
function_block-function_prefixed
[]
Rust
src/options/new_Session/tests.rs
hugo-k-m/tmux-session-generator
dcde680cc5f2128004ea94691f6fa17f14ab23de
use super::*; use crate::options::Opts; use lib::{ dir::create_dir, err::ScriptError, produce_script_error, test::{TestObject, TestSessionDir, TestSessionDirGroupScript, TestTmuxHomeDir}, }; use std::fs; #[test] fn create_session_script_success() -> CustomResult<()> { const SESSION_NAME: &str = "new_session"; let content = "test content".to_owned(); let group_option = false; let tsg_test = TestTmuxHomeDir::setup()?; let tsg_home_dir = tsg_test.test_tmuxsg_path; let session_dir = PathBuf::from(&format!("{}/{}", tsg_home_dir.display(), SESSION_NAME)); let script_path_expected = PathBuf::from(&format!("{}/{}.sh", session_dir.display(), SESSION_NAME)); create_session_script(content, SESSION_NAME, tsg_home_dir, group_option)?; assert!(script_path_expected.is_file()); Ok(()) } #[test] fn session_script_already_exists() -> CustomResult<()> { let session_name = "test_session"; let tsg_test = TestSessionDir::setup()?; let session_dir = tsg_test.test_session_path; assert!(create_script(session_dir, session_name).is_err()); Ok(()) } #[test] fn create_session_directory_success() -> CustomResult<()> { let session_name = "new_session".to_owned(); let tsg_test = TestTmuxHomeDir::setup()?; let tsg_home_dir_path = tsg_test.test_tmuxsg_path; let s_dir_expected = PathBuf::from(&format!( "{}/{}", &tsg_home_dir_path.display(), session_name )); create_dir(tsg_home_dir_path, session_name)?; assert!(s_dir_expected.is_dir()); Ok(()) } #[test] fn session_script_content_attach_test() -> CustomResult<()> { let attach_test_session_content = test_session_content( "~".to_owned(), false, None, "attach_test_session".to_owned(), None, None, None, )?; let test_content = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join( "resources/test/script_content_checks/\ session/attach_test_session.sh", ); let expected_test_session_content = fs::read_to_string(test_content)?; assert_eq!(attach_test_session_content, expected_test_session_content); Ok(()) } #[test] fn session_script_content_detach_test() -> CustomResult<()> { let detach_test_session_content = test_session_content( "~".to_owned(), true, None, "detach_test_session".to_owned(), None, None, None, )?; let test_content = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join( "resources/test/script_content_checks/\ session/detach_test_session.sh", ); let expected_test_session_content = fs::read_to_string(test_content)?; assert_eq!(detach_test_session_content, expected_test_session_content); Ok(()) } #[test] fn session_script_content_window_name_test() -> CustomResult<()> { let detach_test_session_content = test_session_content( "~".to_owned(), true, Some("window_name".to_owned()), "window_name_test_session".to_owned(), None, None, None, )?; let test_content = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join( "resources/test/script_content_checks/\ session/name_window_option_test_session.sh", ); let expected_test_session_content = fs::read_to_string(test_content)?; assert_eq!(detach_test_session_content, expected_test_session_content); Ok(()) } #[test] fn session_group_option_script_creation_success() -> CustomResult<()> { let group_option = false; let tsg_test = TestSessionDir::setup()?; let session_dir = tsg_test.test_session_path; let expected_group_script = session_dir.join("__session_group_option.sh"); set_session_group_option(&session_dir, group_option)?; assert!(expected_group_script.is_file()); Ok(()) } #[test] fn group_script_creation_fails_if_exists() -> CustomResult<()> { let group_option = false; let tsg_test = TestSessionDirGroupScript::setup()?; let session_dir = tsg_test.test_session_path; let expected_group_script = session_dir.join("__session_group_option.sh"); assert!(expected_group_script.is_file()); assert!(set_session_group_option(&session_dir, group_option).is_err()); Ok(()) } fn test_session_content( command: String, detach: bool, name_window: Option<String>, session_name: String, target_session: Option<String>, x: Option<usize>, y: Option<usize>, ) -> CustomResult<String> { let error = "Session content related".to_owned(); let detach_test_session = Opts::NewSession { command, detach, name_window, session_name, target_session, x, y, }; let test_session_content = if let Opts::NewSession { command, detach, name_window, session_name, target_session, x, y, } = detach_test_session { session_script_content( &command, &detach, &name_window, &session_name, &target_session, &x, &y, ) } else { produce_script_error!(error); }; Ok(test_session_content) }
use super::*; use crate::options::Opts; use lib::{ dir::create_dir, err::ScriptError, produce_script_error, test::{TestObject, TestSessionDir, TestSessionDirGroupScript, TestTmuxHomeDir}, }; use std::fs; #[test] fn create_session_script_success() -> CustomResult<()> { const SESSION_NAME: &str = "new_session"; let content = "test content".to_owned(); let group_option = false; let tsg_test = TestTmuxHomeDir::setup()?; let tsg_home_dir = tsg_test.test_tmuxsg_path; let session_dir = PathBuf::from(&format!("{}/{}", tsg_home_dir.display(), SESSION_NAME)); let script_path_expected = PathBuf::from(&format!("{}/{}.sh", session_dir.display(), SESSION_NAME)); create_session_script(content, SESSION_NAME, tsg_home_dir, group_option)?; assert!(script_path_expected.is_file()); Ok(()) } #[test] fn session_script_alrea
#[test] fn create_session_directory_success() -> CustomResult<()> { let session_name = "new_session".to_owned(); let tsg_test = TestTmuxHomeDir::setup()?; let tsg_home_dir_path = tsg_test.test_tmuxsg_path; let s_dir_expected = PathBuf::from(&format!( "{}/{}", &tsg_home_dir_path.display(), session_name )); create_dir(tsg_home_dir_path, session_name)?; assert!(s_dir_expected.is_dir()); Ok(()) } #[test] fn session_script_content_attach_test() -> CustomResult<()> { let attach_test_session_content = test_session_content( "~".to_owned(), false, None, "attach_test_session".to_owned(), None, None, None, )?; let test_content = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join( "resources/test/script_content_checks/\ session/attach_test_session.sh", ); let expected_test_session_content = fs::read_to_string(test_content)?; assert_eq!(attach_test_session_content, expected_test_session_content); Ok(()) } #[test] fn session_script_content_detach_test() -> CustomResult<()> { let detach_test_session_content = test_session_content( "~".to_owned(), true, None, "detach_test_session".to_owned(), None, None, None, )?; let test_content = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join( "resources/test/script_content_checks/\ session/detach_test_session.sh", ); let expected_test_session_content = fs::read_to_string(test_content)?; assert_eq!(detach_test_session_content, expected_test_session_content); Ok(()) } #[test] fn session_script_content_window_name_test() -> CustomResult<()> { let detach_test_session_content = test_session_content( "~".to_owned(), true, Some("window_name".to_owned()), "window_name_test_session".to_owned(), None, None, None, )?; let test_content = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join( "resources/test/script_content_checks/\ session/name_window_option_test_session.sh", ); let expected_test_session_content = fs::read_to_string(test_content)?; assert_eq!(detach_test_session_content, expected_test_session_content); Ok(()) } #[test] fn session_group_option_script_creation_success() -> CustomResult<()> { let group_option = false; let tsg_test = TestSessionDir::setup()?; let session_dir = tsg_test.test_session_path; let expected_group_script = session_dir.join("__session_group_option.sh"); set_session_group_option(&session_dir, group_option)?; assert!(expected_group_script.is_file()); Ok(()) } #[test] fn group_script_creation_fails_if_exists() -> CustomResult<()> { let group_option = false; let tsg_test = TestSessionDirGroupScript::setup()?; let session_dir = tsg_test.test_session_path; let expected_group_script = session_dir.join("__session_group_option.sh"); assert!(expected_group_script.is_file()); assert!(set_session_group_option(&session_dir, group_option).is_err()); Ok(()) } fn test_session_content( command: String, detach: bool, name_window: Option<String>, session_name: String, target_session: Option<String>, x: Option<usize>, y: Option<usize>, ) -> CustomResult<String> { let error = "Session content related".to_owned(); let detach_test_session = Opts::NewSession { command, detach, name_window, session_name, target_session, x, y, }; let test_session_content = if let Opts::NewSession { command, detach, name_window, session_name, target_session, x, y, } = detach_test_session { session_script_content( &command, &detach, &name_window, &session_name, &target_session, &x, &y, ) } else { produce_script_error!(error); }; Ok(test_session_content) }
dy_exists() -> CustomResult<()> { let session_name = "test_session"; let tsg_test = TestSessionDir::setup()?; let session_dir = tsg_test.test_session_path; assert!(create_script(session_dir, session_name).is_err()); Ok(()) }
function_block-function_prefixed
[ { "content": "/// Creates the script and opens it in write-only mode.\n\npub fn create_script(session_dir: PathBuf, script_name: &str) -> CustomResult<File> {\n\n let script_path = session_dir.join(&format!(\"{}.sh\", script_name));\n\n\n\n if script_path.is_file() {\n\n produce_script_error!(format!(\"{}\", script_name));\n\n }\n\n\n\n let file = fs::File::create(&script_path)?;\n\n\n\n Ok(file)\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! tmux_option {\n\n ( $( $y:expr ) +, $content:ident ) => {\n\n $(\n\n if let Some(tmux_opt) = $y {\n\n $content.push_str(&format!(\" -{} {}\", stringify!($y), tmux_opt));\n\n };\n\n ) +\n", "file_path": "lib/src/options.rs", "rank": 0, "score": 68043.60086937247 }, { "content": "pub trait TestObject {\n\n fn setup() -> CustomResult<Self>\n\n where\n\n Self: Sized;\n\n}\n\n\n\npub struct TestHomeDir {\n\n pub test_home_path: PathBuf,\n\n _test_home_dir: TempDir,\n\n}\n\n\n\nimpl TestObject for TestHomeDir {\n\n fn setup() -> CustomResult<Self> {\n\n let test_home_dir = tempfile::tempdir()?;\n\n let test_home_path = PathBuf::from(&test_home_dir.path());\n\n\n\n Ok(TestHomeDir {\n\n test_home_path,\n\n _test_home_dir: test_home_dir,\n\n })\n", "file_path": "lib/src/test.rs", "rank": 9, "score": 42881.48342840136 }, { "content": "//! Test helpers\n\n\n\nuse crate::err::CustomResult;\n\nuse std::{fs, path::PathBuf};\n\nuse tempfile::TempDir;\n\n\n", "file_path": "lib/src/test.rs", "rank": 10, "score": 42266.359505146276 }, { "content": " fs::create_dir(&test_session_path)?;\n\n fs::File::create(script_path)?;\n\n\n\n Ok(TestSessionDir {\n\n test_tmuxsg_path,\n\n test_session_path,\n\n _test_home_dir: test_home_dir,\n\n })\n\n }\n\n}\n\n\n\npub struct TestSessionDirGroupScript {\n\n pub test_tmuxsg_path: PathBuf,\n\n pub test_session_path: PathBuf,\n\n _test_home_dir: TempDir,\n\n}\n\n\n\nimpl TestObject for TestSessionDirGroupScript {\n\n fn setup() -> CustomResult<Self> {\n\n let test_home_dir = tempfile::tempdir()?;\n", "file_path": "lib/src/test.rs", "rank": 11, "score": 42265.608705092476 }, { "content": " }\n\n}\n\n\n\npub struct TestTmuxHomeDir {\n\n pub test_tmuxsg_path: PathBuf,\n\n pub test_home_dir_path: PathBuf,\n\n _test_home_dir: TempDir,\n\n}\n\n\n\nimpl TestObject for TestTmuxHomeDir {\n\n fn setup() -> CustomResult<Self> {\n\n let test_home_dir = tempfile::tempdir()?;\n\n let test_home_dir_path = PathBuf::from(&test_home_dir.path());\n\n let test_tmuxsg_path = test_home_dir_path.join(\".tmuxsg\");\n\n\n\n fs::create_dir(&test_tmuxsg_path)?;\n\n\n\n Ok(TestTmuxHomeDir {\n\n test_tmuxsg_path,\n\n test_home_dir_path,\n", "file_path": "lib/src/test.rs", "rank": 12, "score": 42265.54490075869 }, { "content": " let test_home_dir_path = PathBuf::from(&test_home_dir.path());\n\n let test_tmuxsg_path = test_home_dir_path.join(\".tmuxsg\");\n\n let test_session_path = test_tmuxsg_path.join(\"test_session\");\n\n let group_script_path = test_session_path.join(&format!(\"__session_group_option.sh\"));\n\n let script_path = test_session_path.join(&format!(\"test_session.sh\"));\n\n\n\n fs::create_dir(&test_tmuxsg_path)?;\n\n fs::create_dir(&test_session_path)?;\n\n fs::File::create(group_script_path)?;\n\n fs::File::create(script_path)?;\n\n\n\n Ok(TestSessionDirGroupScript {\n\n test_tmuxsg_path,\n\n test_session_path,\n\n _test_home_dir: test_home_dir,\n\n })\n\n }\n\n}\n", "file_path": "lib/src/test.rs", "rank": 13, "score": 42265.42382527256 }, { "content": " _test_home_dir: test_home_dir,\n\n })\n\n }\n\n}\n\n\n\npub struct TestSessionDir {\n\n pub test_tmuxsg_path: PathBuf,\n\n pub test_session_path: PathBuf,\n\n _test_home_dir: TempDir,\n\n}\n\n\n\nimpl TestObject for TestSessionDir {\n\n fn setup() -> CustomResult<Self> {\n\n let test_home_dir = tempfile::tempdir()?;\n\n let test_home_dir_path = PathBuf::from(&test_home_dir.path());\n\n let test_tmuxsg_path = test_home_dir_path.join(\".tmuxsg\");\n\n let test_session_path = test_tmuxsg_path.join(\"test_session\");\n\n let script_path = test_session_path.join(&format!(\"test_session.sh\"));\n\n\n\n fs::create_dir(&test_tmuxsg_path)?;\n", "file_path": "lib/src/test.rs", "rank": 14, "score": 42264.70189315985 }, { "content": "pub fn create_dir(parent: PathBuf, child: String) -> CustomResult<PathBuf> {\n\n let new_dir = parent.join(&child);\n\n\n\n fs::create_dir_all(&new_dir)?;\n\n\n\n Ok(new_dir)\n\n}\n", "file_path": "lib/src/dir.rs", "rank": 16, "score": 35440.20772829352 }, { "content": "fn set_session_group_option(session_dir: &PathBuf, group_option: bool) -> CustomResult<()> {\n\n let session_group_option = if group_option {\n\n \"is_session_group\"\n\n } else {\n\n \"is_not_session_group\"\n\n };\n\n\n\n let mut file = create_script(session_dir.to_owned(), \"__session_group_option\")?;\n\n file.write_all(session_group_option.as_bytes())?;\n\n\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests;\n", "file_path": "src/options/new_session.rs", "rank": 17, "score": 33268.91527886566 }, { "content": "fn main() -> CustomResult<()> {\n\n let opts = options::Opts::from_args();\n\n let home_d = home_directory(BaseDirs::new())?;\n\n let tmuxsg_home = tmuxsg_home_dir(home_d)?;\n\n\n\n println!(\"{:?}\", opts.invoke_subcommand(tmuxsg_home));\n\n\n\n Ok(())\n\n}\n", "file_path": "src/main.rs", "rank": 18, "score": 33036.06372403206 }, { "content": "//! Shared utilities\n\n\n\npub mod dir;\n\npub mod err;\n\npub mod options;\n\npub mod test;\n", "file_path": "lib/src/lib.rs", "rank": 19, "score": 26798.855340682414 }, { "content": "pub fn tmuxsg_home_dir(home_d: PathBuf) -> CustomResult<PathBuf> {\n\n let tsg_home = create_dir(home_d, \".tmuxsg\".to_owned())?;\n\n\n\n Ok(tsg_home)\n\n}\n\n\n", "file_path": "src/home_dirs.rs", "rank": 20, "score": 23660.059598915934 }, { "content": "pub fn home_directory(base_dirs: Option<BaseDirs>) -> CustomResult<PathBuf> {\n\n let base_d = match base_dirs {\n\n Some(bd) => bd,\n\n None => {\n\n produce_directory_error!(\"Home\".to_owned());\n\n }\n\n };\n\n\n\n Ok(base_d.home_dir().to_owned())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::home_dirs::{home_directory, tmuxsg_home_dir};\n\n use directories::BaseDirs;\n\n use lib::{\n\n err::CustomResult,\n\n test::{TestHomeDir, TestObject, TestTmuxHomeDir},\n\n };\n\n use std::path::PathBuf;\n", "file_path": "src/home_dirs.rs", "rank": 21, "score": 22590.72037240155 }, { "content": " };\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! tmux_bool_option {\n\n ( $( $x:expr, $y:ident ) + ) => {\n\n $(\n\n if $x.to_owned() {\n\n $y.push_str(&format!(\" -{}\", stringify!($x)));\n\n }\n\n ) +\n\n };\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::{\n\n err::CustomResult,\n\n options::create_script,\n\n test::{TestObject, TestTmuxHomeDir},\n", "file_path": "lib/src/options.rs", "rank": 22, "score": 21214.17069615039 }, { "content": " };\n\n use std::{fs, path::PathBuf};\n\n\n\n /// Test script creation process\n\n #[test]\n\n fn create_script_success() -> CustomResult<()> {\n\n const SESSION_NAME: &str = \"new_session\";\n\n\n\n let tsg_test = TestTmuxHomeDir::setup()?;\n\n let tsg_dir = tsg_test.test_tmuxsg_path;\n\n\n\n let session_dir = PathBuf::from(&format!(\"{}/{}\", tsg_dir.display(), SESSION_NAME));\n\n fs::create_dir(&session_dir)?;\n\n\n\n let script_path_expected =\n\n PathBuf::from(&format!(\"{}/{}.sh\", session_dir.display(), SESSION_NAME));\n\n\n\n create_script(session_dir, SESSION_NAME)?;\n\n\n\n assert!(script_path_expected.is_file());\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "lib/src/options.rs", "rank": 23, "score": 21213.693348541296 }, { "content": " ($err_details:expr) => {\n\n let script_err = ScriptError($err_details);\n\n\n\n return Err(script_err).map_err(anyhow::Error::msg);\n\n };\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::err::{DirectoryError, ScriptError};\n\n\n\n #[test]\n\n fn directory_error_displays_correctly() {\n\n let actual_error_disp = format!(\"{}\", DirectoryError(\"Test\".to_owned()));\n\n let expected_error_disp = format!(\"Directory error: Test\");\n\n\n\n assert_eq!(actual_error_disp, expected_error_disp);\n\n }\n\n\n\n #[test]\n\n fn script_error_displays_correctly() {\n\n let actual_error_disp = format!(\"{}\", ScriptError(\"Test\".to_owned()));\n\n let expected_error_disp = format!(\"Script error: Test\");\n\n\n\n assert_eq!(actual_error_disp, expected_error_disp);\n\n }\n\n}\n", "file_path": "lib/src/err.rs", "rank": 24, "score": 21211.871893550604 }, { "content": "//! Directory helper methods\n\n\n\nuse crate::err::CustomResult;\n\nuse std::{fs, path::PathBuf};\n\n\n", "file_path": "lib/src/dir.rs", "rank": 25, "score": 21211.302700102635 }, { "content": "//! Shared utilities for the options module.\n\n\n\nuse crate::{\n\n err::{CustomResult, ScriptError},\n\n produce_script_error,\n\n};\n\nuse std::{\n\n fs::{self, File},\n\n path::PathBuf,\n\n};\n\n\n\n/// Creates the script and opens it in write-only mode.\n", "file_path": "lib/src/options.rs", "rank": 26, "score": 21211.002373641993 }, { "content": "//! Custom errors\n\n\n\nuse anyhow::Result as AnyhowResult;\n\nuse std::{error::Error as StdError, fmt::Display};\n\n\n\npub type CustomResult<T> = AnyhowResult<T>;\n\n\n\n#[derive(Debug, Clone)]\n\npub struct DirectoryError(pub String);\n\n\n\nimpl Display for DirectoryError {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"Directory error: {}\", &self.0)\n\n }\n\n}\n\n\n\nimpl StdError for DirectoryError {}\n\n\n\n#[macro_export]\n\nmacro_rules! produce_directory_error {\n", "file_path": "lib/src/err.rs", "rank": 27, "score": 21210.433835215168 }, { "content": " ($err_details:expr) => {\n\n let dir_err = DirectoryError($err_details);\n\n\n\n return Err(dir_err).map_err(anyhow::Error::msg);\n\n };\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct ScriptError(pub String);\n\n\n\nimpl Display for ScriptError {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"Script error: {}\", &self.0)\n\n }\n\n}\n\n\n\nimpl StdError for ScriptError {}\n\n\n\n#[macro_export]\n\nmacro_rules! produce_script_error {\n", "file_path": "lib/src/err.rs", "rank": 28, "score": 21208.814953966266 }, { "content": " tmux_option!(\n\n n t,\n\n content\n\n );\n\n\n\n tmux_bool_option!(\n\n a, content\n\n d, content\n\n k, content\n\n );\n\n\n\n Ok((content, session_name.to_owned(), window_name.to_owned()))\n\n}\n\n\n\n// TODO: write tests\n\n#[cfg(test)]\n\nmod tests {\n\n use lib::{\n\n err::CustomResult,\n\n test::{TestObject, TestSessionDir},\n", "file_path": "src/options/new_window.rs", "rank": 31, "score": 9.463199182281995 }, { "content": "use super::new_session::{create_session_script, session_script_content};\n\nuse super::new_window::{create_window_script, window_script_content};\n\nuse super::Opts;\n\nuse lib::err::CustomResult;\n\nuse std::path::PathBuf;\n\n\n\nimpl Opts {\n\n pub fn invoke_subcommand(self, tmuxsg_home: PathBuf) -> CustomResult<Self> {\n\n match &self {\n\n Opts::NewSession {\n\n command,\n\n detach,\n\n name_window,\n\n session_name,\n\n target_session,\n\n x,\n\n y,\n\n } => {\n\n let content = session_script_content(\n\n command,\n", "file_path": "src/options/parser_associated_functions.rs", "rank": 32, "score": 7.691820285406988 }, { "content": " };\n\n use std::path::PathBuf;\n\n\n\n use crate::options::new_window::create_window_script;\n\n\n\n #[test]\n\n fn create_window_script_success() -> CustomResult<()> {\n\n const WINDOW_NAME: &str = \"test_window\";\n\n\n\n let content = (\n\n \"test content\".to_owned(),\n\n \"test_session\".to_owned(),\n\n WINDOW_NAME.to_owned(),\n\n );\n\n\n\n let tsg_test = TestSessionDir::setup()?;\n\n let tmuxsg_home = tsg_test.test_tmuxsg_path;\n\n let session_dir = tsg_test.test_session_path;\n\n\n\n let script_path_expected =\n", "file_path": "src/options/new_window.rs", "rank": 33, "score": 6.8983774770928195 }, { "content": " Ok(())\n\n}\n\n\n\npub(in crate::options) fn session_script_content(\n\n command: &String,\n\n detach: &bool,\n\n n: &Option<String>,\n\n session_name: &String,\n\n t: &Option<String>,\n\n x: &Option<usize>,\n\n y: &Option<usize>,\n\n) -> String {\n\n const SESSION_VAR: &str = \"session\";\n\n const PATH_VAR: &str = \"session_path\";\n\n\n\n let mut content = \"#!/bin/sh\\n\\n\".to_owned();\n\n\n\n content.push_str(&format!(\"{}=\\\"{}\\\"\\n\", SESSION_VAR, session_name));\n\n content.push_str(&format!(\"{}={}\\n\", PATH_VAR, command));\n\n\n", "file_path": "src/options/new_session.rs", "rank": 34, "score": 5.860664067735297 }, { "content": "//! NewWindow subcommand helpers\n\n\n\nuse lib::{\n\n err::{CustomResult, DirectoryError, ScriptError},\n\n options::create_script,\n\n produce_directory_error, produce_script_error, tmux_bool_option, tmux_option,\n\n};\n\nuse std::{io::Write, path::PathBuf};\n\n\n\npub(in crate::options) fn create_window_script(\n\n content: (String, String, String),\n\n tmuxsg_home: PathBuf,\n\n) -> CustomResult<()> {\n\n let script_content = content.0;\n\n let session_name = content.1;\n\n let window_name = content.2;\n\n\n\n let isolated_session_name = if session_name.contains(\":\") {\n\n session_name.split(\":\").collect::<Vec<&str>>()[0].to_owned()\n\n } else {\n", "file_path": "src/options/new_window.rs", "rank": 35, "score": 5.649338448178824 }, { "content": " content.push_str(&format!(\n\n \"tmux new-session -d -s ${} -c ${}\",\n\n SESSION_VAR, PATH_VAR\n\n ));\n\n\n\n tmux_option!(\n\n n t x y,\n\n content\n\n );\n\n\n\n if detach.to_owned() {\n\n return content;\n\n } else {\n\n content.push_str(\"\\n\\n# Attach\\n\");\n\n content.push_str(&format!(\"tmux attach -t ${}\", SESSION_VAR));\n\n };\n\n\n\n content\n\n}\n\n\n", "file_path": "src/options/new_session.rs", "rank": 36, "score": 5.4308310545371015 }, { "content": "//! NewSession subcommand helpers.\n\n\n\nuse anyhow::Context;\n\nuse lib::{dir::create_dir, err::CustomResult, options::create_script, tmux_option};\n\nuse std::{io::Write, path::PathBuf};\n\n\n\npub(in crate::options) fn create_session_script(\n\n content: String,\n\n s_name: &str,\n\n tmuxsg_home: PathBuf,\n\n group_option: bool,\n\n) -> CustomResult<()> {\n\n let s_dir = create_dir(tmuxsg_home, s_name.to_owned())?;\n\n\n\n set_session_group_option(&s_dir, group_option)?;\n\n\n\n let mut file =\n\n create_script(s_dir, s_name).with_context(|| format!(\"could not create session script\"))?;\n\n file.write_all(content.as_bytes())?;\n\n\n", "file_path": "src/options/new_session.rs", "rank": 37, "score": 5.091664967054478 }, { "content": " name_window,\n\n target_window,\n\n } => {\n\n let content =\n\n window_script_content(a, kill, command, detach, name_window, target_window)?;\n\n\n\n create_window_script(content, tmuxsg_home)?;\n\n\n\n Ok(self)\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/options/parser_associated_functions.rs", "rank": 38, "score": 4.310965290255874 }, { "content": "mod home_dirs;\n\nmod options;\n\n\n\nuse crate::home_dirs::{home_directory, tmuxsg_home_dir};\n\nuse directories::BaseDirs;\n\nuse lib::err::CustomResult;\n\nuse structopt::StructOpt;\n\n\n", "file_path": "src/main.rs", "rank": 39, "score": 4.30585547037305 }, { "content": "//! Handle home directories\n\n\n\nuse directories::BaseDirs;\n\nuse lib::{\n\n dir::create_dir,\n\n err::{CustomResult, DirectoryError},\n\n produce_directory_error,\n\n};\n\nuse std::path::PathBuf;\n\n\n", "file_path": "src/home_dirs.rs", "rank": 40, "score": 4.2065675167139425 }, { "content": " let expected_error_disp = format!(\"Directory error: Home\");\n\n\n\n assert_eq!(actual_error_disp, expected_error_disp);\n\n\n\n Ok(())\n\n }\n\n\n\n // TODO: rewrite as integration test\n\n #[test]\n\n fn home_directory_found() -> CustomResult<()> {\n\n let home_d = home_directory(BaseDirs::new())?;\n\n\n\n assert!(home_d.is_dir());\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/home_dirs.rs", "rank": 41, "score": 3.751775267046319 }, { "content": " n: &Option<String>,\n\n t: &Option<String>,\n\n) -> CustomResult<(String, String, String)> {\n\n let error = \"Window content related\".to_owned();\n\n\n\n let session_name = if let Some(target) = t {\n\n target\n\n } else {\n\n produce_script_error!(error);\n\n };\n\n\n\n let window_name = if let Some(name) = n {\n\n name\n\n } else {\n\n \"new_window\"\n\n };\n\n\n\n let mut content = \"#!/bin/sh\\n\\n\".to_owned();\n\n content.push_str(&format!(\"tmux new-window -c {}\", command));\n\n\n", "file_path": "src/options/new_window.rs", "rank": 42, "score": 3.5926618662672176 }, { "content": "\n\n tmuxsg_home_dir(home_dir)?;\n\n\n\n Ok(())\n\n }\n\n\n\n // TODO: rewrite as integration test\n\n #[test]\n\n fn tsg_home_directory_found() -> CustomResult<()> {\n\n let home_d = home_directory(BaseDirs::new())?;\n\n let tsg_home_expected = PathBuf::from(&format!(\"{}/.tmuxsg\", home_d.display()));\n\n\n\n assert!(tsg_home_expected.is_dir());\n\n\n\n Ok(())\n\n }\n\n\n\n #[test]\n\n fn home_directory_error() -> CustomResult<()> {\n\n let actual_error_disp = format!(\"{}\", home_directory(None).unwrap_err());\n", "file_path": "src/home_dirs.rs", "rank": 43, "score": 3.531784231812755 }, { "content": " PathBuf::from(&format!(\"{}/{}.sh\", session_dir.display(), WINDOW_NAME));\n\n\n\n create_window_script(content, tmuxsg_home)?;\n\n\n\n assert!(script_path_expected.is_file());\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/options/new_window.rs", "rank": 44, "score": 3.474372879743681 }, { "content": "\n\n #[test]\n\n fn create_tmuxsg_home_directory_success() -> CustomResult<()> {\n\n let tsg_test = TestHomeDir::setup()?;\n\n let home_dir = tsg_test.test_home_path;\n\n let tsg_home_expected = PathBuf::from(&format!(\"{}/.tmuxsg\", home_dir.display()));\n\n tmuxsg_home_dir(home_dir)?;\n\n\n\n assert!(tsg_home_expected.is_dir());\n\n\n\n Ok(())\n\n }\n\n\n\n #[test]\n\n fn test_tmuxsg_home_dir_when_directory_already_exists() -> CustomResult<()> {\n\n let tsg_test = TestTmuxHomeDir::setup()?;\n\n let home_dir = tsg_test.test_home_dir_path;\n\n let tsg_home_expected = PathBuf::from(&format!(\"{}/.tmuxsg\", home_dir.display()));\n\n\n\n assert!(tsg_home_expected.is_dir());\n", "file_path": "src/home_dirs.rs", "rank": 45, "score": 3.2871887899887278 }, { "content": " detach,\n\n name_window,\n\n session_name,\n\n target_session,\n\n x,\n\n y,\n\n );\n\n\n\n let group_option = false;\n\n\n\n create_session_script(content, session_name, tmuxsg_home, group_option)?;\n\n\n\n Ok(self)\n\n }\n\n\n\n Opts::NewWindow {\n\n a,\n\n kill,\n\n command,\n\n detach,\n", "file_path": "src/options/parser_associated_functions.rs", "rank": 46, "score": 3.1505285090804374 }, { "content": " session_name\n\n };\n\n\n\n let session_dir = tmuxsg_home.join(&isolated_session_name);\n\n\n\n if !session_dir.is_dir() {\n\n produce_directory_error!(format!(\"{}\", isolated_session_name));\n\n } else {\n\n let mut file = create_script(session_dir, &window_name)?;\n\n file.write_all(script_content.as_bytes())?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\npub(in crate::options) fn window_script_content(\n\n a: &bool,\n\n k: &bool,\n\n command: &String,\n\n d: &bool,\n", "file_path": "src/options/new_window.rs", "rank": 47, "score": 3.056144673784424 }, { "content": "mod new_session;\n\nmod new_window;\n\nmod parser_associated_functions;\n\n\n\nuse std::usize;\n\nuse structopt::StructOpt;\n\n\n\n#[derive(Debug, StructOpt)]\n\npub enum Opts {\n\n NewSession {\n\n /// Specify working directory for the session.\n\n #[structopt(short, long, default_value = \"~\")]\n\n command: String,\n\n\n\n /// Don't attach new session to current terminal\n\n #[structopt(short, long)]\n\n detach: bool,\n\n\n\n /// Initial window name\n\n #[structopt(short, long)]\n", "file_path": "src/options/mod.rs", "rank": 48, "score": 1.673243427104201 } ]
Rust
db/tests/unit/collection_items.rs
taritom/bn-api
6fbf05bf426c4ddd3d5f50378ac9b51f3ebf2a3f
use db::dev::TestProject; use db::prelude::*; #[test] fn commit() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1 = CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); assert_eq!(collection_item1.collectible_id, collectible_id1); assert_eq!(collection_item1.collection_id, collection1.id); } #[test] fn new_collection_item_collision() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let event2 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event2) .for_user(&user1) .quantity(1) .is_paid() .finish(); let collectible_id2 = event2.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1_collectible1 = CollectionItem::create(collection1.id, collectible_id1).commit(conn); let collection_item1_collectible2 = CollectionItem::create(collection1.id, collectible_id2).commit(conn); let collectible1_dup = CollectionItem::create(collection1.id, collectible_id1).commit(conn); assert!(collection_item1_collectible1.is_ok()); assert!(collection_item1_collectible2.is_ok()); assert!(collectible1_dup.is_err()); let er = collectible1_dup.unwrap_err(); assert_eq!(er.code, errors::get_error_message(&ErrorCode::DuplicateKeyError).0); } #[test] fn find() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1 = CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); let found_item = CollectionItem::find(collection_item1.id, conn).unwrap(); assert_eq!(collection_item1, found_item); } #[test] fn find_for_collection_with_num_owned() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let event2 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event2) .for_user(&user1) .quantity(1) .is_paid() .finish(); let collectible_id2 = event2.ticket_types(false, None, conn).unwrap().first().unwrap().id; CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); CollectionItem::create(collection1.id, collectible_id2) .commit(conn) .unwrap(); let found_items = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!( found_items .iter() .find(|&i| i.collectible_id == collectible_id1) .unwrap() .number_owned, 2 ); assert_eq!( found_items .iter() .find(|&i| i.collectible_id == collectible_id2) .unwrap() .number_owned, 1 ); } #[test] fn update() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let event2 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event2) .for_user(&user1) .quantity(1) .is_paid() .finish(); let collectible_id2 = event2.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1_collectible1 = CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); let collection_item1_collectible1_clone1 = collection_item1_collectible1.clone(); let collection_item1_collectible1_clone2 = collection_item1_collectible1.clone(); let collection_item1_collectible2 = CollectionItem::create(collection1.id, collectible_id2) .commit(conn) .unwrap(); let update1 = UpdateCollectionItemAttributes { next_collection_item_id: Some(Some(collection_item1_collectible2.id)), }; CollectionItem::update(collection_item1_collectible1, update1, conn).unwrap(); let found_items1 = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!( found_items1 .iter() .find(|&i| i.collectible_id == collectible_id1) .unwrap() .next_collection_item_id .unwrap(), collection_item1_collectible2.id ); let update2 = UpdateCollectionItemAttributes { next_collection_item_id: None, }; CollectionItem::update(collection_item1_collectible1_clone1, update2, conn).unwrap(); let found_items2 = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!( found_items2 .iter() .find(|&i| i.collectible_id == collectible_id1) .unwrap() .next_collection_item_id .unwrap(), collection_item1_collectible2.id ); let update3 = UpdateCollectionItemAttributes { next_collection_item_id: Some(None), }; CollectionItem::update(collection_item1_collectible1_clone2, update3, conn).unwrap(); let found_items3 = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!( found_items3 .iter() .find(|&i| i.collectible_id == collectible_id1) .unwrap() .next_collection_item_id, None ); } #[test] fn destroy() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let event2 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event2) .for_user(&user1) .quantity(1) .is_paid() .finish(); let collectible_id2 = event2.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1_collectible1 = CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); CollectionItem::create(collection1.id, collectible_id2) .commit(conn) .unwrap(); CollectionItem::destroy(collection_item1_collectible1, conn).unwrap(); let found_items = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!(found_items.len(), 1); }
use db::dev::TestProject; use db::prelude::*; #[test] fn commit() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1 = CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); assert_eq!(collection_item1.collectible_id, collectible_id1); assert_eq!(collection_item1.collection_id, collection1.id); } #[test] fn new_collection_item_collision() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let event2 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event2) .for_user(&user1) .quantity(1) .is_paid() .finish(); let collectible_id2 = event2.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1_collectible1 = CollectionItem::create(collection1.id, collectible_id1).commit(conn); le
#[test] fn find() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1 = CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); let found_item = CollectionItem::find(collection_item1.id, conn).unwrap(); assert_eq!(collection_item1, found_item); } #[test] fn find_for_collection_with_num_owned() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let event2 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event2) .for_user(&user1) .quantity(1) .is_paid() .finish(); let collectible_id2 = event2.ticket_types(false, None, conn).unwrap().first().unwrap().id; CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); CollectionItem::create(collection1.id, collectible_id2) .commit(conn) .unwrap(); let found_items = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!( found_items .iter() .find(|&i| i.collectible_id == collectible_id1) .unwrap() .number_owned, 2 ); assert_eq!( found_items .iter() .find(|&i| i.collectible_id == collectible_id2) .unwrap() .number_owned, 1 ); } #[test] fn update() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let event2 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event2) .for_user(&user1) .quantity(1) .is_paid() .finish(); let collectible_id2 = event2.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1_collectible1 = CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); let collection_item1_collectible1_clone1 = collection_item1_collectible1.clone(); let collection_item1_collectible1_clone2 = collection_item1_collectible1.clone(); let collection_item1_collectible2 = CollectionItem::create(collection1.id, collectible_id2) .commit(conn) .unwrap(); let update1 = UpdateCollectionItemAttributes { next_collection_item_id: Some(Some(collection_item1_collectible2.id)), }; CollectionItem::update(collection_item1_collectible1, update1, conn).unwrap(); let found_items1 = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!( found_items1 .iter() .find(|&i| i.collectible_id == collectible_id1) .unwrap() .next_collection_item_id .unwrap(), collection_item1_collectible2.id ); let update2 = UpdateCollectionItemAttributes { next_collection_item_id: None, }; CollectionItem::update(collection_item1_collectible1_clone1, update2, conn).unwrap(); let found_items2 = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!( found_items2 .iter() .find(|&i| i.collectible_id == collectible_id1) .unwrap() .next_collection_item_id .unwrap(), collection_item1_collectible2.id ); let update3 = UpdateCollectionItemAttributes { next_collection_item_id: Some(None), }; CollectionItem::update(collection_item1_collectible1_clone2, update3, conn).unwrap(); let found_items3 = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!( found_items3 .iter() .find(|&i| i.collectible_id == collectible_id1) .unwrap() .next_collection_item_id, None ); } #[test] fn destroy() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event1) .for_user(&user1) .quantity(2) .is_paid() .finish(); let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id; let event2 = project.create_event().with_ticket_pricing().finish(); project .create_order() .for_event(&event2) .for_user(&user1) .quantity(1) .is_paid() .finish(); let collectible_id2 = event2.ticket_types(false, None, conn).unwrap().first().unwrap().id; let collection_item1_collectible1 = CollectionItem::create(collection1.id, collectible_id1) .commit(conn) .unwrap(); CollectionItem::create(collection1.id, collectible_id2) .commit(conn) .unwrap(); CollectionItem::destroy(collection_item1_collectible1, conn).unwrap(); let found_items = CollectionItem::find_for_collection_with_num_owned(collection1.id, user1.id, conn).unwrap(); assert_eq!(found_items.len(), 1); }
t collection_item1_collectible2 = CollectionItem::create(collection1.id, collectible_id2).commit(conn); let collectible1_dup = CollectionItem::create(collection1.id, collectible_id1).commit(conn); assert!(collection_item1_collectible1.is_ok()); assert!(collection_item1_collectible2.is_ok()); assert!(collectible1_dup.is_err()); let er = collectible1_dup.unwrap_err(); assert_eq!(er.code, errors::get_error_message(&ErrorCode::DuplicateKeyError).0); }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn commit() {\n\n let project = TestProject::new();\n\n let name = \"Name\";\n\n let connection = project.get_connection();\n\n let venue = Venue::create(name.clone(), None, \"America/Los_Angeles\".into())\n\n .commit(connection)\n\n .unwrap();\n\n let stage_name = \"Stage Name\".to_string();\n\n let stage = Stage::create(\n\n venue.id,\n\n stage_name.clone(),\n\n Some(\"Description\".to_string()),\n\n Some(1000),\n\n )\n\n .commit(connection)\n\n .unwrap();\n\n\n\n assert_eq!(stage.name, stage_name);\n\n assert_eq!(stage.id.to_string().is_empty(), false);\n\n}\n\n\n", "file_path": "db/tests/unit/stages.rs", "rank": 0, "score": 296889.3778100214 }, { "content": "#[test]\n\nfn commit() {\n\n let project = TestProject::new();\n\n let first_name = Some(\"Jeff\".to_string());\n\n let last_name = Some(\"Wilco\".to_string());\n\n let email = Some(\"jeff@tari.com\".to_string());\n\n let phone_number = Some(\"555-555-5555\".to_string());\n\n let password = \"examplePassword\";\n\n let user = User::create(\n\n first_name.clone(),\n\n last_name.clone(),\n\n email.clone(),\n\n phone_number.clone(),\n\n password,\n\n )\n\n .commit(None, project.get_connection())\n\n .unwrap();\n\n\n\n assert_eq!(user.first_name, first_name);\n\n assert_eq!(user.last_name, last_name);\n\n assert_eq!(user.email, email);\n\n assert_eq!(user.phone, phone_number);\n\n assert_ne!(user.hashed_pw, password);\n\n assert_eq!(user.hashed_pw.is_empty(), false);\n\n assert_eq!(user.id.to_string().is_empty(), false);\n\n\n\n let wallets = user.wallets(project.get_connection()).unwrap();\n\n assert_eq!(wallets.len(), 1);\n\n}\n\n\n", "file_path": "db/tests/unit/users.rs", "rank": 1, "score": 296889.3778100214 }, { "content": "#[test]\n\nfn commit() {\n\n let project = TestProject::new();\n\n let conn = project.get_connection();\n\n let user1 = project.create_user().finish();\n\n let name1 = \"Collection1\";\n\n let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap();\n\n\n\n assert_eq!(collection1.name, name1);\n\n assert_eq!(collection1.user_id, user1.id);\n\n}\n\n\n", "file_path": "db/tests/unit/collections.rs", "rank": 2, "score": 296889.3778100214 }, { "content": "#[test]\n\nfn commit() {\n\n let project = TestProject::new();\n\n let name = \"Name\";\n\n let bio = \"Bio\";\n\n let website_url = \"http://www.example.com\";\n\n\n\n let artist = Artist::create(name, None, bio, website_url)\n\n .commit(project.get_connection())\n\n .unwrap();\n\n assert_eq!(name, artist.name);\n\n assert_eq!(bio, artist.bio);\n\n assert_eq!(website_url, artist.website_url.unwrap());\n\n assert_eq!(artist.id.to_string().is_empty(), false);\n\n}\n\n\n", "file_path": "db/tests/unit/artists.rs", "rank": 3, "score": 296889.3778100214 }, { "content": "#[test]\n\nfn commit() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let name = \"Name\";\n\n let venue = Venue::create(name.clone(), None, \"America/Los_Angeles\".into())\n\n .commit(connection)\n\n .unwrap();\n\n\n\n assert_eq!(venue.name, name);\n\n assert_eq!(venue.id.to_string().is_empty(), false);\n\n assert!(venue.slug_id.is_some());\n\n let slug = Slug::primary_slug(venue.id, Tables::Venues, connection).unwrap();\n\n assert_eq!(slug.main_table_id, venue.id);\n\n assert_eq!(slug.main_table, Tables::Venues);\n\n assert_eq!(slug.slug_type, SlugTypes::Venue);\n\n\n\n // No city slug exists for this record\n\n assert!(Slug::find_by_type(venue.id, Tables::Venues, SlugTypes::City, connection).is_err());\n\n\n\n // Create venue with default San Francisco, CA, USA city\n", "file_path": "db/tests/unit/venues.rs", "rank": 4, "score": 296889.3778100214 }, { "content": "#[test]\n\nfn commit() {\n\n let project = TestProject::new();\n\n let conn = project.get_connection();\n\n let domain_action = DomainAction::create(\n\n None,\n\n DomainActionTypes::Communication,\n\n None,\n\n serde_json::Value::Null,\n\n None,\n\n None,\n\n );\n\n\n\n let now = Utc::now().naive_utc();\n\n assert!(domain_action.scheduled_at <= now && domain_action.scheduled_at > now - Duration::hours(1));\n\n\n\n let domain_action = domain_action.commit(conn).unwrap();\n\n assert!(!domain_action.id.is_nil());\n\n assert_eq!(DomainActionTypes::Communication, domain_action.domain_action_type);\n\n}\n\n\n", "file_path": "db/tests/unit/domain_actions.rs", "rank": 5, "score": 294275.88373765815 }, { "content": "#[test]\n\nfn commit() {\n\n let project = TestProject::new();\n\n let conn = project.get_connection();\n\n\n\n let domain_event = DomainEvent::create(\n\n DomainEventTypes::EventArtistAdded,\n\n \"\".to_string(),\n\n Tables::EventArtists,\n\n None,\n\n None,\n\n None,\n\n );\n\n\n\n let domain_action = domain_event.commit(conn).unwrap();\n\n\n\n assert!(!domain_action.id.is_nil());\n\n}\n\n\n", "file_path": "db/tests/unit/domain_events.rs", "rank": 6, "score": 294275.88373765815 }, { "content": "#[test]\n\nfn create_commit() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let user = project.create_user().finish();\n\n let message = \"Announcement message\".to_string();\n\n let announcement = Announcement::create(None, message.clone())\n\n .commit(Some(user.id), connection)\n\n .unwrap();\n\n\n\n assert_eq!(announcement.message, message);\n\n assert!(announcement.organization_id.is_none());\n\n\n\n let domain_events = DomainEvent::find(\n\n Tables::Announcements,\n\n Some(announcement.id),\n\n Some(DomainEventTypes::AnnouncementCreated),\n\n connection,\n\n )\n\n .unwrap();\n\n assert_eq!(1, domain_events.len());\n\n assert_eq!(domain_events[0].user_id, Some(user.id));\n\n}\n\n\n", "file_path": "db/tests/unit/announcements.rs", "rank": 8, "score": 238983.68392495706 }, { "content": "#[test]\n\nfn create_commit() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let user = project.create_user().finish();\n\n project.create_order().for_user(&user).quantity(1).is_paid().finish();\n\n let ticket = TicketInstance::find_for_user(user.id, connection).unwrap().remove(0);\n\n let transfer_key = Uuid::new_v4();\n\n let transfer = Transfer::create(user.id, transfer_key, None, None, false)\n\n .commit(connection)\n\n .unwrap();\n\n transfer.add_transfer_ticket(ticket.id, connection).unwrap();\n\n assert_eq!(transfer.status, TransferStatus::Pending);\n\n assert_eq!(transfer.source_user_id, user.id);\n\n assert_eq!(transfer.transfer_key, transfer_key);\n\n\n\n let result = Transfer::create(user.id, transfer_key, None, None, false).commit(connection);\n\n match result {\n\n Ok(_) => {\n\n panic!(\"Expected error\");\n\n }\n", "file_path": "db/tests/unit/transfers.rs", "rank": 9, "score": 238983.68392495706 }, { "content": "#[test]\n\nfn create_commit() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let user = project.create_user().finish();\n\n let announcement = project.create_announcement().finish();\n\n let announcement_engagement =\n\n AnnouncementEngagement::create(user.id, announcement.id, AnnouncementEngagementAction::Dismiss)\n\n .commit(connection)\n\n .unwrap();\n\n\n\n assert_eq!(announcement_engagement.announcement_id, announcement.id);\n\n assert_eq!(announcement_engagement.user_id, user.id);\n\n}\n\n\n", "file_path": "db/tests/unit/announcement_engagements.rs", "rank": 10, "score": 236442.1940312282 }, { "content": "#[test]\n\nfn new_broadcast_commit() {\n\n let project = TestProject::new();\n\n let conn = project.get_connection();\n\n let event = project.create_event().finish();\n\n\n\n let send_at = Utc::now().naive_utc();\n\n\n\n let broadcast = Broadcast::create(\n\n event.id,\n\n BroadcastType::LastCall,\n\n BroadcastChannel::PushNotification,\n\n \"myname\".to_string(),\n\n None,\n\n Some(send_at),\n\n None,\n\n None,\n\n BroadcastAudience::PeopleAtTheEvent,\n\n None,\n\n );\n\n\n", "file_path": "db/tests/unit/broadcasts.rs", "rank": 11, "score": 236442.1940312282 }, { "content": "#[test]\n\nfn commit_duplicate_email() {\n\n let project = TestProject::new();\n\n let user1 = project.create_user().finish();\n\n let first_name = Some(\"Jeff\".to_string());\n\n let last_name = Some(\"Wilco\".to_string());\n\n let email = user1.email;\n\n let phone_number = Some(\"555-555-5555\".to_string());\n\n let password = \"examplePassword\";\n\n let result =\n\n User::create(first_name, last_name, email, phone_number, password).commit(None, project.get_connection());\n\n\n\n assert_eq!(result.is_err(), true);\n\n assert_eq!(\n\n result.err().unwrap().code,\n\n errors::get_error_message(&ErrorCode::DuplicateKeyError).0\n\n );\n\n}\n\n\n", "file_path": "db/tests/unit/users.rs", "rank": 12, "score": 236442.1940312282 }, { "content": "#[test]\n\nfn create_commit() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let user = project.create_user().finish();\n\n project.create_order().for_user(&user).quantity(1).is_paid().finish();\n\n let ticket = TicketInstance::find_for_user(user.id, connection).unwrap().remove(0);\n\n\n\n let transfer = Transfer::create(user.id, Uuid::new_v4(), None, None, false)\n\n .commit(connection)\n\n .unwrap();\n\n let transfer_ticket = TransferTicket::create(ticket.id, transfer.id)\n\n .commit(connection)\n\n .unwrap();\n\n assert_eq!(transfer_ticket.ticket_instance_id, ticket.id);\n\n assert_eq!(transfer_ticket.transfer_id, transfer.id);\n\n}\n\n\n", "file_path": "db/tests/unit/transfer_tickets.rs", "rank": 13, "score": 236442.1940312282 }, { "content": "#[test]\n\nfn new_custom_broadcast_commit() {\n\n let project = TestProject::new();\n\n let conn = project.get_connection();\n\n let event = project.create_event().finish();\n\n\n\n let broadcast = Broadcast::create(\n\n event.id,\n\n BroadcastType::Custom,\n\n BroadcastChannel::PushNotification,\n\n \"Custom Name\".to_string(),\n\n Some(\"Custom Message\".to_string()),\n\n None,\n\n None,\n\n None,\n\n BroadcastAudience::PeopleAtTheEvent,\n\n None,\n\n );\n\n\n\n assert_eq!(\n\n BroadcastStatus::Pending,\n", "file_path": "db/tests/unit/broadcasts.rs", "rank": 14, "score": 233969.77307783312 }, { "content": "#[test]\n\nfn new_organization_interaction_commit() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let organization = project.create_organization().finish();\n\n let user = project.create_user().finish();\n\n let first_interaction_date = dates::now().add_minutes(-1).finish();\n\n let last_interaction_date = dates::now().finish();\n\n let interaction_count = 1;\n\n\n\n let organization_interaction = OrganizationInteraction::create(\n\n organization.id,\n\n user.id,\n\n first_interaction_date,\n\n last_interaction_date,\n\n interaction_count,\n\n )\n\n .commit(connection)\n\n .unwrap();\n\n\n\n assert_eq!(interaction_count, organization_interaction.interaction_count);\n\n assert_eq!(\n\n first_interaction_date.timestamp_subsec_millis(),\n\n organization_interaction.first_interaction.timestamp_subsec_millis()\n\n );\n\n assert_eq!(\n\n last_interaction_date.timestamp_subsec_millis(),\n\n organization_interaction.last_interaction.timestamp_subsec_millis()\n\n );\n\n}\n\n\n", "file_path": "db/tests/unit/organization_interactions.rs", "rank": 15, "score": 231563.64322700026 }, { "content": "#[test]\n\nfn create_commit_with_validation_error() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let user = project.create_user().finish();\n\n let user2 = project.create_user().finish();\n\n project.create_order().for_user(&user).quantity(1).is_paid().finish();\n\n let ticket = TicketInstance::find_for_user(user.id, connection).unwrap().remove(0);\n\n\n\n let transfer = Transfer::create(user.id, Uuid::new_v4(), None, None, false)\n\n .commit(connection)\n\n .unwrap();\n\n TransferTicket::create(ticket.id, transfer.id)\n\n .commit(connection)\n\n .unwrap();\n\n\n\n // Active pending transfer already exists triggering validation errors\n\n let transfer2 = Transfer::create(user.id, Uuid::new_v4(), None, None, false)\n\n .commit(connection)\n\n .unwrap();\n\n let result = TransferTicket::create(ticket.id, transfer2.id).commit(connection);\n", "file_path": "db/tests/unit/transfer_tickets.rs", "rank": 16, "score": 231563.64322700026 }, { "content": "#[test]\n\npub fn find_number_of_uses() {\n\n let project = TestProject::new();\n\n let conn = project.get_connection();\n\n let user = project.create_user().finish();\n\n let event = project\n\n .create_event()\n\n .with_ticket_pricing()\n\n .with_ticket_type_count(2)\n\n .finish();\n\n let ticket_types = event.ticket_types(true, None, &conn).unwrap();\n\n let ticket_type = &ticket_types[0];\n\n let ticket_type2 = &ticket_types[1];\n\n let code = project\n\n .create_code()\n\n .with_name(\"Discount 1\".into())\n\n .with_event(&event)\n\n .with_max_uses(2)\n\n .with_code_type(CodeTypes::Discount)\n\n .finish();\n\n\n", "file_path": "db/tests/unit/codes.rs", "rank": 17, "score": 229256.39920862328 }, { "content": "// dont want to update the details in the main function, so keeping this in the unit test section\n\nfn update(org_invite: &OrganizationInvite, conn: &PgConnection) -> Result<OrganizationInvite, DatabaseError> {\n\n DatabaseError::wrap(\n\n ErrorCode::UpdateError,\n\n \"Could not update organization_invite\",\n\n diesel::update(org_invite).set(org_invite).get_result(conn),\n\n )\n\n}\n", "file_path": "db/tests/unit/organization_invites.rs", "rank": 18, "score": 224169.79603143627 }, { "content": "fn check_migrations(conn: &PgConnection) -> Result<(), ApplicationError> {\n\n migration::has_pending_migrations(conn)\n\n .map_err(|_err| ApplicationError::new(\"Error while checking migrations\".to_string()))\n\n .and_then(|has_pending| {\n\n if has_pending {\n\n Err(ApplicationError::new(\"Migrations need to be run\".to_string()))\n\n } else {\n\n Ok(())\n\n }\n\n })\n\n}\n", "file_path": "api/src/controllers/status.rs", "rank": 19, "score": 197904.52182768995 }, { "content": "pub fn unwrap_body_to_string(response: &HttpResponse) -> Result<&str, &'static str> {\n\n match response.body() {\n\n ResponseBody::Body(Body::Bytes(binary)) => Ok(str::from_utf8(binary.as_ref()).unwrap()),\n\n _ => Err(\"Unexpected response body\"),\n\n }\n\n}\n\n\n", "file_path": "api/tests/support/mod.rs", "rank": 20, "score": 196731.5002167914 }, { "content": "fn create_domain_action_event(event_id: Uuid, conn: &PgConnection) {\n\n let domain_action = DomainAction::create(\n\n None,\n\n DomainActionTypes::SubmitSitemapToSearchEngines,\n\n None,\n\n json!({}),\n\n Some(Tables::Events),\n\n Some(event_id),\n\n );\n\n domain_action.commit(conn).unwrap();\n\n}\n\n\n\npub async fn delete(\n\n (connection, parameters, user): (Connection, Path<PathParameters>, AuthUser),\n\n) -> Result<HttpResponse, ApiError> {\n\n let connection = connection.get();\n\n let event = Event::find(parameters.id, connection)?;\n\n let organization = event.organization(connection)?;\n\n user.requires_scope_for_organization_event(Scopes::EventDelete, &organization, &event, connection)?;\n\n\n", "file_path": "api/src/controllers/events.rs", "rank": 21, "score": 194935.08256913157 }, { "content": "pub fn unwrap_body_to_object<'a, T>(response: &'a HttpResponse) -> Result<T, &'static str>\n\nwhere\n\n T: Deserialize<'a>,\n\n{\n\n Ok(serde_json::from_str(unwrap_body_to_string(response)?).unwrap())\n\n}\n\n\n", "file_path": "api/tests/support/mod.rs", "rank": 22, "score": 189944.8939485449 }, { "content": "pub fn schedule_domain_actions(conn: &PgConnection) -> Result<(), DatabaseError> {\n\n // Settlements weekly domain event\n\n if DomainAction::upcoming_domain_action(None, None, DomainActionTypes::SendAutomaticReportEmails, conn)?.is_none() {\n\n Report::create_next_automatic_report_domain_action(conn)?;\n\n }\n\n\n\n if DomainAction::upcoming_domain_action(None, None, DomainActionTypes::RetargetAbandonedOrders, conn)?.is_none() {\n\n Order::create_next_retarget_abandoned_cart_domain_action(conn)?;\n\n }\n\n\n\n if DomainAction::upcoming_domain_action(None, None, DomainActionTypes::FinalizeSettlements, conn)?.is_none() {\n\n Settlement::create_next_finalize_settlements_domain_action(conn)?;\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "db/src/models/global.rs", "rank": 23, "score": 189829.29343277507 }, { "content": "pub fn create_sitemap_conn(conn: &PgConnection, front_end_url: &String) -> Result<String, ApiError> {\n\n //find all active events\n\n let events_slug_ids = Event::find_all_active_events(conn)?\n\n .iter()\n\n .filter(|e| e.publish_date.is_some() && e.publish_date.unwrap() < Utc::now().naive_utc())\n\n .map(|e| e.slug_id)\n\n .filter(|s| s.is_some())\n\n .map(|s| s.unwrap())\n\n .collect_vec();\n\n\n\n let event_urls = create_urls(front_end_url, events_slug_ids, \"tickets\".to_string(), conn);\n\n\n\n // Cities\n\n let city_slug_id = Slug::find_by_slug_type(SlugTypes::City, conn)?\n\n .iter()\n\n .map(|s| s.id)\n\n .collect_vec();\n\n let city_urls = create_urls(front_end_url, city_slug_id, \"cities\".to_string(), conn);\n\n\n\n // Venues\n", "file_path": "api/src/utils/gen_sitemap.rs", "rank": 24, "score": 184388.20777356313 }, { "content": "pub fn has_pending_migrations(conn: &PgConnection) -> Result<bool, RunMigrationsError> {\n\n let migration_dirs = MigrationDirs::DIR_NAMES;\n\n\n\n let already_run = conn.previously_run_migration_versions()?;\n\n\n\n let migration_versions = migration_dirs\n\n .iter()\n\n .map(|d| d.split(\"_\").collect::<Vec<&str>>()[0])\n\n .collect::<Vec<&str>>();\n\n\n\n let has_pending_migrations = migration_versions.iter().any(|v| !already_run.contains(&v.to_string()));\n\n\n\n Ok(has_pending_migrations)\n\n}\n", "file_path": "db/src/utils/migration.rs", "rank": 25, "score": 183908.61897000094 }, { "content": "#[test]\n\nfn test_sending_status() {\n\n let project = TestProject::new();\n\n let user = project.create_user().finish();\n\n let user2 = project.create_user().finish();\n\n let organization = project\n\n .create_organization()\n\n .with_member(&user, Roles::OrgOwner)\n\n .finish();\n\n let org_invite = project\n\n .create_organization_invite()\n\n .with_org(&organization)\n\n .with_invitee(&user)\n\n .link_to_user(&user2)\n\n .finish();\n\n /*making the assumption that it wont take more than 60 seconds to update the status\n\n we cant test for an exact date, as this will depend on the database write delay\n\n we will test for a period of 30 seconds\n\n */\n\n let pre_send_invite = org_invite.clone();\n\n let post_send_invite = org_invite.change_sent_status(true, &project.get_connection()).unwrap();\n\n\n\n assert_eq!(pre_send_invite.sent_invite, false);\n\n assert_eq!(post_send_invite.sent_invite, true);\n\n}\n\n\n", "file_path": "db/tests/unit/organization_invites.rs", "rank": 26, "score": 182488.6778121463 }, { "content": "#[test]\n\nfn test_token_validity() {\n\n let project = TestProject::new();\n\n let user = project.create_user().finish();\n\n let organization = project\n\n .create_organization()\n\n .with_member(&user, Roles::OrgOwner)\n\n .finish();\n\n let mut org_invite = project\n\n .create_organization_invite()\n\n .with_org(&organization)\n\n .with_invitee(&user)\n\n .finish();\n\n let recovered_invite =\n\n OrganizationInvite::find_by_token(org_invite.security_token.unwrap(), project.get_connection()).unwrap();\n\n assert_eq!(org_invite, recovered_invite);\n\n org_invite.created_at = NaiveDate::from_ymd(2016, 7, 8).and_hms(9, 10, 11);\n\n org_invite = update(&org_invite, &project.get_connection()).unwrap();\n\n let recovered_invite2 =\n\n OrganizationInvite::find_by_token(org_invite.security_token.unwrap(), &project.get_connection());\n\n let error_value = DatabaseError {\n", "file_path": "db/tests/unit/organization_invites.rs", "rank": 27, "score": 182488.6778121463 }, { "content": "#[test]\n\nfn all() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n\n\n // Initial set\n\n assert_eq!(Genre::all(connection).unwrap().len(), 126);\n\n}\n", "file_path": "db/tests/unit/genres.rs", "rank": 28, "score": 178155.59872869978 }, { "content": "#[test]\n\nfn from() {\n\n let communication_address = CommAddress::from(\"abc@tari.com\".to_string());\n\n assert_eq!(communication_address.addresses, vec![\"abc@tari.com\".to_string()]);\n\n}\n\n\n", "file_path": "db/tests/unit/communication.rs", "rank": 29, "score": 178155.59872869978 }, { "content": "#[test]\n\nfn all() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n assert!(Announcement::all(0, 100, connection).unwrap().is_empty());\n\n\n\n let announcement = project.create_announcement().finish();\n\n diesel::sql_query(\n\n r#\"\n\n UPDATE announcements\n\n SET created_at = $1\n\n WHERE id = $2;\n\n \"#,\n\n )\n\n .bind::<sql_types::Timestamp, _>(dates::now().add_hours(-1).finish())\n\n .bind::<sql_types::Uuid, _>(announcement.id)\n\n .execute(connection)\n\n .unwrap();\n\n let announcement = Announcement::find(announcement.id, false, connection).unwrap();\n\n\n\n let announcement2 = project.create_announcement().finish();\n", "file_path": "db/tests/unit/announcements.rs", "rank": 30, "score": 178155.59872869978 }, { "content": "#[test]\n\nfn all() {\n\n let project = TestProject::new();\n\n let region = project.create_region().with_name(\"Region1\".into()).finish();\n\n let region2 = project.create_region().with_name(\"Region2\".into()).finish();\n\n let other_region = Region::find(Uuid::nil(), project.get_connection()).unwrap();\n\n\n\n let all_found_regions = Region::all(project.get_connection()).unwrap();\n\n let all_regions = vec![other_region, region, region2];\n\n assert_eq!(all_regions, all_found_regions);\n\n}\n", "file_path": "db/tests/unit/regions.rs", "rank": 31, "score": 178155.59872869978 }, { "content": "#[test]\n\nfn all() {\n\n let project = TestProject::new();\n\n let venue = project.create_venue().with_name(\"Venue1\".to_string()).finish();\n\n let venue2 = project.create_venue().with_name(\"Venue2\".to_string()).finish();\n\n let organization = project.create_organization().finish();\n\n let conn = &project.get_connection();\n\n\n\n let all_found_venues = Venue::all(None, conn).unwrap();\n\n let mut all_venues = vec![venue, venue2];\n\n assert_eq!(all_venues, all_found_venues);\n\n\n\n let venue3 = project\n\n .create_venue()\n\n .with_name(\"Venue3\".to_string())\n\n .make_private()\n\n .finish();\n\n venue3.add_to_organization(organization.id, conn).unwrap();\n\n let user = project.create_user().finish();\n\n let _org_user = organization\n\n .add_user(user.id, vec![Roles::OrgMember], Vec::new(), conn)\n\n .unwrap();\n\n all_venues.push(venue3);\n\n let all_found_venues = Venue::all(Some(&user), conn).unwrap();\n\n assert_eq!(all_venues, all_found_venues);\n\n let all_found_venues = Venue::all(Some(&User::find(user.id, conn).unwrap()), conn).unwrap();\n\n assert_eq!(all_venues, all_found_venues);\n\n}\n\n\n", "file_path": "db/tests/unit/venues.rs", "rank": 32, "score": 178155.59872869978 }, { "content": "#[test]\n\nfn all() {\n\n let project = TestProject::new();\n\n let conn = &project.get_connection();\n\n let name = \"Name\";\n\n let owner = project.create_user().finish();\n\n let user = project.create_user().finish();\n\n let admin = project.create_user().finish().add_role(Roles::Admin, conn).unwrap();\n\n\n\n let organization = project\n\n .create_organization()\n\n .with_member(&owner, Roles::OrgOwner)\n\n .with_member(&user, Roles::OrgMember)\n\n .finish();\n\n\n\n let artist = project.create_artist().with_name(name.into()).finish();\n\n assert_eq!(name, artist.name);\n\n assert_eq!(artist.id.to_string().is_empty(), false);\n\n\n\n let found_artists = Artist::all(None, conn).unwrap();\n\n assert_eq!(1, found_artists.len());\n", "file_path": "db/tests/unit/artists.rs", "rank": 33, "score": 178155.59872869978 }, { "content": "#[test]\n\nfn all() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let hold = project.create_hold().with_name(\"Hold1\".to_string()).finish();\n\n let hold2 = project.create_hold().with_name(\"Hold2\".to_string()).finish();\n\n let hold3 = project.create_hold().with_name(\"Hold3\".to_string()).finish();\n\n assert_eq!(vec![hold, hold2, hold3], Hold::all(connection).unwrap());\n\n}\n\n\n", "file_path": "db/tests/unit/holds.rs", "rank": 34, "score": 178155.59872869978 }, { "content": "#[test]\n\nfn all() {\n\n let project = TestProject::new();\n\n let user = project.create_user().finish();\n\n let user2 = project.create_user().finish();\n\n let org1 = project\n\n .create_organization()\n\n .with_member(&user, Roles::OrgOwner)\n\n .finish();\n\n let org2 = project\n\n .create_organization()\n\n .with_member(&user2, Roles::OrgOwner)\n\n .with_member(&user, Roles::OrgMember)\n\n .finish();\n\n let org3 = project\n\n .create_organization()\n\n .with_member(&user2, Roles::OrgOwner)\n\n .finish();\n\n\n\n let orgs = Organization::all(project.get_connection()).unwrap();\n\n let mut test_vec = vec![org1, org2, org3];\n\n test_vec.sort_by_key(|org| org.name.clone());\n\n assert_eq!(orgs, test_vec);\n\n}\n\n\n", "file_path": "db/tests/unit/organizations.rs", "rank": 35, "score": 178155.59872869978 }, { "content": "fn promote_temp_to_user(user_id: Uuid, conn: &PgConnection) -> Result<User, ApiError> {\n\n let temp_user = TemporaryUser::find(user_id, &conn)?;\n\n let user = temp_user.users(&conn)?.into_iter().next();\n\n if let Some(user) = user {\n\n return Ok(user);\n\n }\n\n let user = User::create(\n\n None,\n\n None,\n\n temp_user.email.clone(),\n\n temp_user.phone.clone(),\n\n &Uuid::new_v4().to_string(),\n\n )\n\n .commit(None, &conn)?;\n\n temp_user.associate_user(user.id, conn)?;\n\n Ok(user)\n\n}\n", "file_path": "api/src/controllers/auth.rs", "rank": 36, "score": 177172.2412768426 }, { "content": "#[test]\n\nfn create() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let user = project.create_user().finish();\n\n let order = project.create_order().is_paid().finish();\n\n let note_text = \"Note goes here\".to_string();\n\n assert_eq!(\n\n 0,\n\n DomainEvent::find(\n\n Tables::Orders,\n\n Some(order.id),\n\n Some(DomainEventTypes::NoteCreated),\n\n connection,\n\n )\n\n .unwrap()\n\n .len()\n\n );\n\n\n\n let note = Note::create(Tables::Orders, order.id, user.id, note_text.clone())\n\n .commit(connection)\n", "file_path": "db/tests/unit/notes.rs", "rank": 37, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn transfers() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let user = project.create_user().finish();\n\n let order = project.create_order().for_user(&user).quantity(1).is_paid().finish();\n\n let ticket = &TicketInstance::find_for_user(user.id, connection).unwrap()[0];\n\n\n\n let transfer = Transfer::create(user.id, Uuid::new_v4(), None, None, false)\n\n .commit(connection)\n\n .unwrap();\n\n transfer.add_transfer_ticket(ticket.id, connection).unwrap();\n\n assert!(transfer.update_associated_orders(connection).is_ok());\n\n assert_eq!(vec![transfer], order.transfers(connection).unwrap());\n\n}\n\n\n", "file_path": "db/tests/unit/orders.rs", "rank": 38, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn destroy() {\n\n let project = TestProject::new();\n\n let code = project.create_code().finish();\n\n assert!(code.destroy(None, project.get_connection()).unwrap() > 0);\n\n assert!(Code::find(code.id, project.get_connection()).is_err());\n\n}\n\n\n", "file_path": "db/tests/unit/codes.rs", "rank": 39, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn destroy() {\n\n let project = TestProject::new();\n\n let conn = project.get_connection();\n\n let user1 = project.create_user().finish();\n\n let name1 = \"Collection1\";\n\n let name2 = \"Collection2\";\n\n let collection1_user1 = Collection::create(name1, user1.id).commit(conn).unwrap();\n\n let collection2_user1 = Collection::create(name2, user1.id).commit(conn).unwrap();\n\n\n\n let result = Collection::destroy(collection1_user1, conn);\n\n assert!(result.is_ok());\n\n let found_collections = Collection::find_for_user(user1.id, conn).unwrap();\n\n\n\n assert_eq!(found_collections.len(), 1);\n\n assert_eq!(found_collections[0].id, collection2_user1.id);\n\n}\n", "file_path": "db/tests/unit/collections.rs", "rank": 40, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn update() {\n\n let project = TestProject::new();\n\n let name = \"Old Name\";\n\n let artist = project.create_artist().with_name(name.into()).finish();\n\n\n\n let mut main_genre = Genre::find_or_create(&vec![\"blues\".to_string()], project.get_connection()).unwrap();\n\n let mut artist_parameters = ArtistEditableAttributes::new();\n\n artist_parameters.name = Some(\"New Name\".into());\n\n artist_parameters.bio = Some(\"Bio\".into());\n\n artist_parameters.website_url = Some(Some(\"http://www.example.com\".into()));\n\n artist_parameters.main_genre_id = Some(main_genre.pop());\n\n\n\n let updated_artist = artist.update(&artist_parameters, &project.get_connection()).unwrap();\n\n\n\n assert_eq!(updated_artist.id, artist.id);\n\n assert_ne!(updated_artist.name, artist.name);\n\n assert_eq!(updated_artist.name, artist_parameters.name.unwrap());\n\n assert_eq!(updated_artist.main_genre_id, artist_parameters.main_genre_id.unwrap());\n\n}\n\n\n", "file_path": "db/tests/unit/artists.rs", "rank": 41, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn get() {\n\n let communication_address = CommAddress::from_vec(vec![\"abc@tari.com\".to_string(), \"abc2@tari.com\".to_string()]);\n\n assert_eq!(communication_address.addresses, communication_address.get());\n\n}\n\n\n", "file_path": "db/tests/unit/communication.rs", "rank": 42, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn dir() {\n\n let mut paging_parameters = PagingParameters::default();\n\n assert_eq!(paging_parameters.dir(), SortingDir::Asc);\n\n\n\n paging_parameters.dir = Some(SortingDir::Desc);\n\n assert_eq!(paging_parameters.dir(), SortingDir::Desc);\n\n}\n\n\n", "file_path": "db/tests/unit/paging.rs", "rank": 43, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn push() {\n\n let mut communication_address = CommAddress::from(\"abc@tari.com\".to_string());\n\n communication_address.push(&\"abc2@tari.com\".to_string());\n\n assert_eq!(\n\n communication_address.addresses,\n\n vec![\"abc@tari.com\".to_string(), \"abc2@tari.com\".to_string()]\n\n );\n\n}\n\n\n", "file_path": "db/tests/unit/communication.rs", "rank": 44, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn split() {\n\n let db = TestProject::new();\n\n let connection = db.get_connection();\n\n let hold = db.create_hold().finish();\n\n let name = \"Name1\".to_string();\n\n let redemption_code = \"ABCD34927262\".to_string();\n\n let child = true;\n\n let end_at = None;\n\n let max_per_user = None;\n\n let discount_in_cents = None;\n\n let email = Some(\"email@domain.com\".to_string());\n\n let phone = Some(\"11111111111111\".to_string());\n\n let quantity = 2;\n\n let hold_type = HoldTypes::Comp;\n\n\n\n // Split off a comp that uses the current hold as its new parent\n\n let new_hold = hold\n\n .split(\n\n None,\n\n name.clone(),\n", "file_path": "db/tests/unit/holds.rs", "rank": 45, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn find() {\n\n let project = TestProject::new();\n\n let conn = project.get_connection();\n\n let user1 = project.create_user().finish();\n\n let name1 = \"Collection1\";\n\n let collection1_user1 = Collection::create(name1, user1.id).commit(conn).unwrap();\n\n\n\n let found_collection = Collection::find(collection1_user1.id, conn).unwrap();\n\n\n\n assert_eq!(collection1_user1, found_collection);\n\n}\n\n\n", "file_path": "db/tests/unit/collections.rs", "rank": 46, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn venue() {\n\n let project = TestProject::new();\n\n let venue = project.create_venue().finish();\n\n let event = project\n\n .create_event()\n\n .with_name(\"NewEvent\".into())\n\n .with_venue(&venue)\n\n .finish();\n\n assert_eq!(event.venue(project.get_connection()).unwrap(), Some(venue));\n\n\n\n let event = project.create_event().with_name(\"NewEvent\".into()).finish();\n\n assert_eq!(event.venue(project.get_connection()).unwrap(), None);\n\n}\n\n\n", "file_path": "db/tests/unit/events.rs", "rank": 47, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn activity() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let user = project.create_user().finish();\n\n let user2 = project.create_user().finish();\n\n let organization = project.create_organization().with_event_fee().with_fees().finish();\n\n let organization2 = project.create_organization().with_event_fee().with_fees().finish();\n\n let event = project\n\n .create_event()\n\n .with_organization(&organization)\n\n .with_ticket_type_count(1)\n\n .with_tickets()\n\n .with_ticket_pricing()\n\n .finish();\n\n let event2 = project\n\n .create_event()\n\n .with_organization(&organization2)\n\n .with_ticket_pricing()\n\n .finish();\n\n let hold = project\n", "file_path": "db/tests/unit/orders.rs", "rank": 48, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn find() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let note = project.create_note().finish();\n\n assert_eq!(note, Note::find(note.id, connection).unwrap());\n\n}\n\n\n", "file_path": "db/tests/unit/notes.rs", "rank": 49, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn find() {\n\n let db = TestProject::new();\n\n let hold = db.create_hold().finish();\n\n\n\n let db_hold = Hold::find(hold.id, db.get_connection()).unwrap();\n\n\n\n assert_eq!(hold, db_hold);\n\n}\n\n\n", "file_path": "db/tests/unit/holds.rs", "rank": 50, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn destroy() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let note = project.create_note().finish();\n\n let user = project.create_user().finish();\n\n assert_eq!(\n\n 0,\n\n DomainEvent::find(\n\n Tables::Orders,\n\n Some(note.main_id),\n\n Some(DomainEventTypes::NoteDeleted),\n\n connection,\n\n )\n\n .unwrap()\n\n .len()\n\n );\n\n\n\n // Soft deleted note returns error as it's not found\n\n assert!(note.destroy(user.id, connection).is_ok());\n\n\n", "file_path": "db/tests/unit/notes.rs", "rank": 51, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn update() {\n\n let project = TestProject::new();\n\n let conn = project.get_connection();\n\n let user1 = project.create_user().finish();\n\n let name1 = \"Collection1\";\n\n let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap();\n\n let event1 = project.create_event().with_ticket_pricing().finish();\n\n project\n\n .create_order()\n\n .for_event(&event1)\n\n .for_user(&user1)\n\n .quantity(2)\n\n .is_paid()\n\n .finish();\n\n let collectible_id1 = event1.ticket_types(false, None, conn).unwrap().first().unwrap().id;\n\n\n\n let update1 = UpdateCollectionAttributes {\n\n featured_collectible_id: Some(Some(collectible_id1)),\n\n };\n\n\n", "file_path": "db/tests/unit/collections.rs", "rank": 52, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn destroy() {\n\n let project = TestProject::new();\n\n let artist = project.create_artist().finish();\n\n assert!(artist.destroy(project.get_connection()).unwrap() > 0);\n\n assert!(Artist::find(&artist.id, project.get_connection()).is_err());\n\n}\n\n\n", "file_path": "db/tests/unit/artists.rs", "rank": 53, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn for_display() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let event = project\n\n .create_event()\n\n .with_ticket_pricing()\n\n .with_ticket_type_count(2)\n\n .finish();\n\n let ticket_types = event.ticket_types(true, None, &connection).unwrap();\n\n let ticket_type = &ticket_types[0];\n\n let ticket_type2 = &ticket_types[1];\n\n let code = project\n\n .create_code()\n\n .with_event(&event)\n\n .for_ticket_type(&ticket_type)\n\n .for_ticket_type(&ticket_type2)\n\n .finish();\n\n\n\n let mut display_code: DisplayCodeAvailability = code.for_display(connection).unwrap();\n\n assert_eq!(code.id, display_code.display_code.id);\n\n assert_eq!(code.name, display_code.display_code.name);\n\n assert_eq!(vec![code.redemption_code], display_code.display_code.redemption_codes);\n\n assert_eq!(\n\n display_code.display_code.ticket_type_ids.sort(),\n\n vec![ticket_type.id, ticket_type2.id].sort()\n\n );\n\n}\n\n\n", "file_path": "db/tests/unit/codes.rs", "rank": 54, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn update() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let announcement = project.create_announcement().finish();\n\n let new_message = \"Something new\".to_string();\n\n let updated_announcement = announcement\n\n .update(\n\n AnnouncementEditableAttributes {\n\n message: Some(new_message.clone()),\n\n ..Default::default()\n\n },\n\n connection,\n\n )\n\n .unwrap();\n\n assert_eq!(new_message, updated_announcement.message);\n\n}\n\n\n", "file_path": "db/tests/unit/announcements.rs", "rank": 55, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn genres() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let creator = project.create_user().finish();\n\n let artist = project.create_artist().with_name(\"Artist 1\".to_string()).finish();\n\n let artist2 = project.create_artist().with_name(\"Artist 2\".to_string()).finish();\n\n\n\n let event = project.create_event().finish();\n\n let event2 = project.create_event().finish();\n\n project\n\n .create_event_artist()\n\n .with_event(&event)\n\n .with_artist(&artist)\n\n .finish();\n\n project\n\n .create_event_artist()\n\n .with_event(&event)\n\n .with_artist(&artist2)\n\n .finish();\n\n project\n", "file_path": "db/tests/unit/events.rs", "rank": 56, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn search() {\n\n //create event\n\n let project = TestProject::new();\n\n let country_lookup = CountryLookup::new().unwrap();\n\n let creator = project.create_user().finish();\n\n let connection = project.get_connection();\n\n let region1 = project.create_region().finish();\n\n let region2 = project.create_region().finish();\n\n let city = \"Dangerville city\".to_string();\n\n let state = \"Alaska\".to_string();\n\n let venue1 = project\n\n .create_venue()\n\n .with_name(\"Venue1\".into())\n\n .with_region(&region1)\n\n .finish();\n\n let venue1 = venue1\n\n .update(\n\n VenueEditableAttributes {\n\n city: Some(city.clone()),\n\n state: Some(state.clone()),\n", "file_path": "db/tests/unit/events.rs", "rank": 57, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn cancel() {\n\n //create event\n\n let project = TestProject::new();\n\n let venue = project.create_venue().finish();\n\n\n\n let user = project.create_user().finish();\n\n let organization = project\n\n .create_organization()\n\n .with_member(&user, Roles::OrgOwner)\n\n .finish();\n\n let event = project\n\n .create_event()\n\n .with_name(\"NewEvent\".into())\n\n .with_organization(&organization)\n\n .with_venue(&venue)\n\n .finish();\n\n\n\n let event = event.cancel(None, &project.get_connection()).unwrap();\n\n assert!(!event.cancelled_at.is_none());\n\n}\n\n\n", "file_path": "db/tests/unit/events.rs", "rank": 58, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn query() {\n\n let mut paging_parameters = PagingParameters::default();\n\n let mut tags: HashMap<String, Value> = HashMap::new();\n\n tags.insert(\"query\".to_string(), json!(\"example-response\"));\n\n assert_eq!(paging_parameters.query(), None);\n\n paging_parameters.tags = tags;\n\n\n\n assert_eq!(paging_parameters.query(), Some(\"example-response\"));\n\n}\n", "file_path": "db/tests/unit/paging.rs", "rank": 59, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn organization() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let event = project.create_event().with_ticket_pricing().finish();\n\n let hold = project.create_hold().with_event(&event).finish();\n\n\n\n let organization = hold.organization(connection).unwrap();\n\n assert_eq!(event.organization(connection).unwrap(), organization);\n\n}\n\n\n", "file_path": "db/tests/unit/holds.rs", "rank": 60, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn create() {\n\n let db = TestProject::new();\n\n let start_date = NaiveDateTime::from(Utc::now().naive_utc() - Duration::days(1));\n\n let end_date = NaiveDateTime::from(Utc::now().naive_utc() + Duration::days(2));\n\n let event = db.create_event().with_tickets().finish();\n\n Code::create(\n\n \"test\".into(),\n\n event.id,\n\n CodeTypes::Discount,\n\n \"REDEMPTION\".into(),\n\n 10,\n\n Some(100),\n\n None,\n\n start_date,\n\n end_date,\n\n None,\n\n )\n\n .commit(None, db.get_connection())\n\n .unwrap();\n\n}\n\n\n", "file_path": "db/tests/unit/codes.rs", "rank": 61, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn for_display() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let artist = project.create_artist().finish();\n\n artist\n\n .set_genres(&vec![\"emo\".to_string(), \"hard-rock\".to_string()], None, connection)\n\n .unwrap();\n\n\n\n let display_artist = artist.clone().for_display(connection).unwrap();\n\n assert_eq!(display_artist.id, artist.id);\n\n assert_eq!(display_artist.name, artist.name);\n\n assert_eq!(display_artist.genres, vec![\"emo\".to_string(), \"hard-rock\".to_string()]);\n\n}\n\n\n", "file_path": "db/tests/unit/artists.rs", "rank": 62, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn create() {\n\n let db = TestProject::new();\n\n let hold = db.create_hold().with_hold_type(HoldTypes::Comp).finish();\n\n Hold::create_comp_for_person(\n\n \"test\".into(),\n\n None,\n\n hold.id,\n\n Some(\"email@address.com\".into()),\n\n None,\n\n \"redemption\".to_string(),\n\n None,\n\n None,\n\n 5,\n\n db.get_connection(),\n\n )\n\n .unwrap();\n\n}\n\n\n", "file_path": "db/tests/unit/comps.rs", "rank": 63, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn create() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let venue = project.create_venue().finish();\n\n let user = project.create_user().finish();\n\n let organization = project\n\n .create_organization()\n\n .with_member(&user, Roles::OrgOwner)\n\n .finish();\n\n let event = project\n\n .create_event()\n\n .with_name(\"NewEvent\".into())\n\n .with_organization(&organization)\n\n .with_venue(&venue)\n\n .finish();\n\n\n\n assert_eq!(event.venue_id, Some(venue.id));\n\n assert_eq!(event.organization_id, organization.id);\n\n assert_eq!(event.id.to_string().is_empty(), false);\n\n assert!(event.slug_id.is_some());\n", "file_path": "db/tests/unit/events.rs", "rank": 64, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn user() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let user = project.create_user().finish();\n\n let order = Order::find_or_create_cart(&user, connection).unwrap();\n\n let user = User::find(user.id, connection).unwrap();\n\n let user2 = User::find(user.id, connection).unwrap();\n\n\n\n let order2 = project\n\n .create_order()\n\n .for_user(&user2)\n\n .on_behalf_of_user(&user)\n\n .finish();\n\n\n\n assert_eq!(order.user(connection), Ok(user));\n\n assert_eq!(order2.user(connection), Ok(user2));\n\n}\n\n\n", "file_path": "db/tests/unit/orders.rs", "rank": 65, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn update() {\n\n let db = TestProject::new();\n\n let code = db.create_code().finish();\n\n\n\n let update_patch = UpdateCodeAttributes {\n\n name: Some(\"New name\".into()),\n\n ..Default::default()\n\n };\n\n let new_code = code.update(update_patch, None, db.get_connection()).unwrap();\n\n assert_eq!(new_code.name, \"New name\".to_string());\n\n}\n\n\n", "file_path": "db/tests/unit/codes.rs", "rank": 66, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn update() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let hold = project.create_hold().finish();\n\n\n\n let update_patch = UpdateHoldAttributes {\n\n discount_in_cents: Some(Some(10)),\n\n max_per_user: Some(None),\n\n end_at: Some(None),\n\n name: Some(\"New name\".to_string()),\n\n ..Default::default()\n\n };\n\n // No release inventory event\n\n let domain_action = DomainAction::upcoming_domain_action(\n\n Some(Tables::Holds),\n\n Some(hold.id),\n\n DomainActionTypes::ReleaseHoldInventory,\n\n connection,\n\n )\n\n .unwrap();\n", "file_path": "db/tests/unit/holds.rs", "rank": 67, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn event() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let event = project.create_event().with_ticket_pricing().finish();\n\n let hold = project.create_hold().with_event(&event).finish();\n\n\n\n assert_eq!(hold.event(connection).unwrap(), event);\n\n}\n\n\n", "file_path": "db/tests/unit/holds.rs", "rank": 68, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn new() {\n\n let communication_address = CommAddress::new();\n\n assert!(communication_address.addresses.is_empty());\n\n}\n\n\n", "file_path": "db/tests/unit/communication.rs", "rank": 69, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn event() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let event = project.create_event().finish();\n\n let code = project.create_code().with_event(&event).finish();\n\n\n\n assert_eq!(code.event(connection).unwrap(), event);\n\n}\n\n\n", "file_path": "db/tests/unit/codes.rs", "rank": 70, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn new() {\n\n let paging = Paging::new(1, 100);\n\n assert_eq!(paging.page, 1);\n\n assert_eq!(paging.limit, 100);\n\n assert_eq!(paging.sort, \"\".to_string());\n\n assert_eq!(paging.dir, SortingDir::Asc);\n\n assert_eq!(paging.total, 0);\n\n assert_eq!(paging.tags, HashMap::new());\n\n}\n\n\n", "file_path": "db/tests/unit/paging.rs", "rank": 71, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn has_refunds() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let user = project.create_user().finish();\n\n let mut order = project.create_order().for_user(&user).is_paid().finish();\n\n assert!(!order.has_refunds(connection).unwrap());\n\n\n\n let items = order.items(&connection).unwrap();\n\n let order_item = items.iter().find(|i| i.item_type == OrderItemTypes::Tickets).unwrap();\n\n let tickets = TicketInstance::find_for_order_item(order_item.id, connection).unwrap();\n\n let refund_items = vec![RefundItemRequest {\n\n order_item_id: order_item.id,\n\n ticket_instance_id: Some(tickets[0].id),\n\n }];\n\n assert!(order.refund(&refund_items, user.id, None, false, connection).is_ok());\n\n assert!(order.has_refunds(connection).unwrap());\n\n}\n\n\n", "file_path": "db/tests/unit/orders.rs", "rank": 72, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn occurred_at() {\n\n let project = TestProject::new();\n\n let user = project.create_user().finish();\n\n let now = Utc::now().naive_utc();\n\n let examples = vec![\n\n ActivityItem::Purchase {\n\n order_id: Uuid::new_v4(),\n\n order_number: \"1234\".to_string(),\n\n ticket_quantity: 1,\n\n events: Vec::new(),\n\n occurred_at: now.clone(),\n\n paid_at: Some(now),\n\n purchased_by: user.clone().into(),\n\n user: user.clone().into(),\n\n total_in_cents: 10,\n\n },\n\n ActivityItem::Transfer {\n\n transfer_id: Uuid::new_v4(),\n\n action: \"Completed\".to_string(),\n\n status: TransferStatus::Completed,\n", "file_path": "db/tests/unit/activities.rs", "rank": 73, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn summary() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let user = project.create_user().finish();\n\n let event = project\n\n .create_event()\n\n .with_ticket_type_count(1)\n\n .with_tickets()\n\n .with_ticket_pricing()\n\n .finish();\n\n assert!(event.summary(connection).is_ok());\n\n event.clone().delete(user.id, connection).unwrap();\n\n assert_eq!(\n\n event.summary(connection),\n\n DatabaseError::business_process_error(\"Unable to display summary, summary data not available for event\",)\n\n );\n\n}\n\n\n", "file_path": "db/tests/unit/events.rs", "rank": 74, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn page() {\n\n let mut paging_parameters = PagingParameters::default();\n\n assert_eq!(paging_parameters.page(), 0);\n\n\n\n paging_parameters.page = Some(2);\n\n assert_eq!(paging_parameters.page(), 2);\n\n}\n\n\n", "file_path": "db/tests/unit/paging.rs", "rank": 75, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn slug() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let event = project.create_event().finish();\n\n let slug = Slug::primary_slug(event.id, Tables::Events, connection).unwrap();\n\n assert_eq!(event.slug(connection).unwrap(), slug.slug);\n\n}\n\n\n", "file_path": "db/tests/unit/events.rs", "rank": 76, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn default() {\n\n let event: NewEvent = Default::default();\n\n assert_eq!(event.status, NewEvent::default_status());\n\n assert_eq!(event.is_external, NewEvent::default_is_external());\n\n}\n\n\n", "file_path": "db/tests/unit/events.rs", "rank": 77, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn available() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let event = project\n\n .create_event()\n\n .with_ticket_type_count(1)\n\n .with_tickets()\n\n .with_ticket_pricing()\n\n .finish();\n\n let code = project.create_code().with_event(&event).with_max_uses(100).finish();\n\n assert_eq!(code.available(connection).unwrap(), Some(100));\n\n project\n\n .create_order()\n\n .for_event(&event)\n\n .quantity(10)\n\n .with_redemption_code(code.redemption_code.clone())\n\n .is_paid()\n\n .finish();\n\n assert_eq!(code.available(connection).unwrap(), Some(99));\n\n\n\n let code = project.create_code().with_event(&event).with_max_uses(0).finish();\n\n assert_eq!(code.available(connection).unwrap(), None);\n\n}\n\n\n", "file_path": "db/tests/unit/codes.rs", "rank": 78, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn organization() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let event = project.create_event().finish();\n\n let code = project.create_code().with_event(&event).finish();\n\n\n\n let organization = code.organization(connection).unwrap();\n\n assert_eq!(event.organization(connection).unwrap(), organization);\n\n}\n\n\n", "file_path": "db/tests/unit/codes.rs", "rank": 79, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn events() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let artist = project.create_artist().finish();\n\n let artist2 = project.create_artist().finish();\n\n let event = project.create_event().with_name(\"Event 1\".to_string()).finish();\n\n let event2 = project.create_event().with_name(\"Event 2\".to_string()).finish();\n\n project\n\n .create_event_artist()\n\n .with_event(&event)\n\n .with_artist(&artist)\n\n .finish();\n\n project\n\n .create_event_artist()\n\n .with_event(&event)\n\n .with_artist(&artist2)\n\n .finish();\n\n project\n\n .create_event_artist()\n\n .with_event(&event2)\n\n .with_artist(&artist2)\n\n .finish();\n\n\n\n assert_eq!(artist.events(connection), Ok(vec![event.clone()]));\n\n assert_eq!(artist2.events(connection), Ok(vec![event, event2]));\n\n}\n\n\n", "file_path": "db/tests/unit/artists.rs", "rank": 80, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn from_vec() {\n\n let communication_address = CommAddress::from_vec(vec![\"abc@tari.com\".to_string(), \"abc2@tari.com\".to_string()]);\n\n assert_eq!(\n\n communication_address.addresses,\n\n vec![\"abc@tari.com\".to_string(), \"abc2@tari.com\".to_string()]\n\n );\n\n}\n\n\n", "file_path": "db/tests/unit/communication.rs", "rank": 81, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn find() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let code = project.create_code().finish();\n\n\n\n // Record found\n\n let found_code = Code::find(code.id, connection).unwrap();\n\n assert_eq!(code, found_code);\n\n\n\n // Code does not exist so returns error\n\n assert!(Code::find(Uuid::new_v4(), connection).is_err());\n\n}\n\n\n", "file_path": "db/tests/unit/codes.rs", "rank": 82, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn unpublish() {\n\n //create event\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let venue = project.create_venue().finish();\n\n\n\n let user = project.create_user().finish();\n\n let organization = project\n\n .create_organization()\n\n .with_member(&user, Roles::OrgOwner)\n\n .finish();\n\n let event = project\n\n .create_event()\n\n .with_status(EventStatus::Draft)\n\n .with_name(\"NewEvent\".into())\n\n .with_organization(&organization)\n\n .with_venue(&venue)\n\n .finish();\n\n\n\n assert_eq!(event.status, EventStatus::Draft);\n", "file_path": "db/tests/unit/events.rs", "rank": 83, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn create() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let event = project.create_event().with_tickets().finish();\n\n let name = \"test\".to_string();\n\n let code = \"IHAVEACODE\".to_string();\n\n let hold = Hold::create_hold(\n\n name.clone(),\n\n event.id,\n\n Some(code.clone()),\n\n Some(0),\n\n Some(dates::now().add_hours(1).finish()),\n\n Some(4),\n\n HoldTypes::Discount,\n\n event.ticket_types(true, None, connection).unwrap()[0].id,\n\n )\n\n .commit(None, connection)\n\n .unwrap();\n\n assert_eq!(name, hold.name);\n\n assert_eq!(code, hold.redemption_code.unwrap());\n", "file_path": "db/tests/unit/holds.rs", "rank": 84, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn publish() {\n\n //create event\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let venue = project.create_venue().finish();\n\n\n\n let user = project.create_user().finish();\n\n let organization = project\n\n .create_organization()\n\n .with_member(&user, Roles::OrgOwner)\n\n .finish();\n\n let event = project\n\n .create_event()\n\n .with_status(EventStatus::Draft)\n\n .with_name(\"NewEvent\".into())\n\n .with_organization(&organization)\n\n .with_venue(&venue)\n\n .finish();\n\n\n\n assert_eq!(event.status, EventStatus::Draft);\n", "file_path": "db/tests/unit/events.rs", "rank": 85, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn limit() {\n\n let mut paging_parameters = PagingParameters::default();\n\n assert_eq!(paging_parameters.limit(), 100);\n\n\n\n paging_parameters.limit = Some(2);\n\n assert_eq!(paging_parameters.limit(), 2);\n\n}\n\n\n", "file_path": "db/tests/unit/paging.rs", "rank": 86, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn delete() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let user = project.create_user().finish();\n\n let event = project\n\n .create_event()\n\n .with_ticket_type_count(1)\n\n .with_tickets()\n\n .with_ticket_pricing()\n\n .finish();\n\n let domain_events = DomainEvent::find(\n\n Tables::Events,\n\n Some(event.id),\n\n Some(DomainEventTypes::EventDeleted),\n\n connection,\n\n )\n\n .unwrap();\n\n assert_eq!(0, domain_events.len());\n\n\n\n assert!(event.clone().delete(user.id, connection).is_ok());\n", "file_path": "db/tests/unit/events.rs", "rank": 87, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn is_expired() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let user = project.create_user().finish();\n\n let order = Order::find_or_create_cart(&user, connection).unwrap();\n\n\n\n // No expiration date set\n\n assert_eq!(order.expires_at, None);\n\n assert!(!order.is_expired());\n\n\n\n // Past expiration date\n\n let past_expiry = NaiveDateTime::from(Utc::now().naive_utc() - Duration::minutes(5));\n\n diesel::update(orders::table.filter(orders::id.eq(order.id)))\n\n .set((orders::expires_at.eq(past_expiry),))\n\n .execute(connection)\n\n .unwrap();\n\n let order = Order::find(order.id, connection).unwrap();\n\n assert!(order.is_expired());\n\n\n\n // Future expiration date\n\n let future_expiry = NaiveDateTime::from(Utc::now().naive_utc() + Duration::minutes(5));\n\n diesel::update(orders::table.filter(orders::id.eq(order.id)))\n\n .set((orders::expires_at.eq(future_expiry),))\n\n .execute(connection)\n\n .unwrap();\n\n let order = Order::find(order.id, connection).unwrap();\n\n assert!(!order.is_expired());\n\n}\n\n\n", "file_path": "db/tests/unit/orders.rs", "rank": 88, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn update() {\n\n let db = TestProject::new();\n\n let comp = db.create_comp().finish();\n\n\n\n let update_patch = UpdateHoldAttributes {\n\n name: Some(\"New name\".to_string()),\n\n email: Some(Some(\"new@email.com\".to_string())),\n\n ..Default::default()\n\n };\n\n let new_comp = comp.update(update_patch, db.get_connection()).unwrap();\n\n assert_eq!(new_comp.name, \"New name\".to_string());\n\n assert_eq!(new_comp.email, Some(\"new@email.com\".to_string()));\n\n}\n\n\n", "file_path": "db/tests/unit/comps.rs", "rank": 89, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn delete() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let user = project.create_user().finish();\n\n let announcement = project.create_announcement().finish();\n\n\n\n let domain_events = DomainEvent::find(\n\n Tables::Announcements,\n\n Some(announcement.id),\n\n Some(DomainEventTypes::AnnouncementDeleted),\n\n connection,\n\n )\n\n .unwrap();\n\n assert_eq!(0, domain_events.len());\n\n\n\n announcement.delete(Some(user.id), connection).unwrap();\n\n\n\n let announcement = Announcement::find(announcement.id, true, connection).unwrap();\n\n assert!(announcement.deleted_at.is_some());\n\n let domain_events = DomainEvent::find(\n\n Tables::Announcements,\n\n Some(announcement.id),\n\n Some(DomainEventTypes::AnnouncementDeleted),\n\n connection,\n\n )\n\n .unwrap();\n\n assert_eq!(1, domain_events.len());\n\n assert_eq!(domain_events[0].user_id, Some(user.id));\n\n}\n", "file_path": "db/tests/unit/announcements.rs", "rank": 90, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn find() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let user = project.create_user().finish();\n\n let cart = Order::find_or_create_cart(&user, connection).unwrap();\n\n\n\n let found_cart = Order::find(cart.id, connection).unwrap();\n\n assert_eq!(found_cart, cart);\n\n}\n\n\n", "file_path": "db/tests/unit/orders.rs", "rank": 91, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn organization() {\n\n let project = TestProject::new();\n\n let user = project.create_user().finish();\n\n let organization = project\n\n .create_organization()\n\n .with_member(&user, Roles::OrgOwner)\n\n .finish();\n\n let event = project\n\n .create_event()\n\n .with_name(\"NewEvent\".into())\n\n .with_organization(&organization)\n\n .finish();\n\n\n\n assert_eq!(event.organization(project.get_connection()).unwrap(), organization);\n\n}\n\n\n", "file_path": "db/tests/unit/events.rs", "rank": 92, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn organization() {\n\n let project = TestProject::new();\n\n let organization = project.create_organization().finish();\n\n let artist = project.create_artist().with_organization(&organization).finish();\n\n let artist2 = project.create_artist().finish();\n\n\n\n assert_eq!(Ok(Some(organization)), artist.organization(project.get_connection()));\n\n assert_eq!(Ok(None), artist2.organization(project.get_connection()));\n\n}\n\n\n", "file_path": "db/tests/unit/artists.rs", "rank": 93, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn find() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let artist = project.create_artist().finish();\n\n\n\n let found_artist = Artist::find(&artist.id, connection).expect(\"Artist was not found\");\n\n assert_eq!(found_artist.id, artist.id);\n\n assert_eq!(found_artist.name, artist.name);\n\n\n\n assert!(\n\n match Artist::find(&Uuid::new_v4(), connection) {\n\n Ok(_artist) => false,\n\n Err(_e) => true,\n\n },\n\n \"Artist incorrectly returned when id invalid\"\n\n );\n\n}\n\n\n", "file_path": "db/tests/unit/artists.rs", "rank": 94, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn is_published() {\n\n let project = TestProject::new();\n\n let mut event = project.create_event().finish();\n\n event.publish_date = None;\n\n assert!(!event.is_published());\n\n\n\n event.publish_date = Some(dates::now().add_minutes(1).finish());\n\n assert!(!event.is_published());\n\n\n\n event.publish_date = Some(dates::now().add_minutes(-1).finish());\n\n assert!(event.is_published());\n\n}\n\n\n", "file_path": "db/tests/unit/events.rs", "rank": 95, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn update() {\n\n //create event\n\n let project = TestProject::new();\n\n let venue = project.create_venue().finish();\n\n\n\n let user = project.create_user().finish();\n\n let organization = project\n\n .create_organization()\n\n .with_member(&user, Roles::OrgOwner)\n\n .finish();\n\n let event = project\n\n .create_event()\n\n .with_name(\"NewEvent\".into())\n\n .with_organization(&organization)\n\n .with_venue(&venue)\n\n .finish();\n\n //Edit event\n\n let parameters = EventEditableAttributes {\n\n private_access_code: Some(Some(\"PRIVATE\".to_string())),\n\n door_time: Some(NaiveDate::from_ymd(2016, 7, 8).and_hms(4, 10, 11)),\n\n ..Default::default()\n\n };\n\n let event = event.update(None, parameters, project.get_connection()).unwrap();\n\n assert_eq!(\n\n event.door_time,\n\n Some(NaiveDate::from_ymd(2016, 7, 8).and_hms(4, 10, 11))\n\n );\n\n assert_eq!(event.private_access_code, Some(\"private\".to_string()));\n\n}\n\n\n", "file_path": "db/tests/unit/events.rs", "rank": 96, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn find() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let user = project.create_user().finish();\n\n let event = project\n\n .create_event()\n\n .with_ticket_type_count(1)\n\n .with_tickets()\n\n .with_ticket_pricing()\n\n .finish();\n\n assert_eq!(Event::find(event.id, connection).unwrap(), event.clone());\n\n event.clone().delete(user.id, connection).unwrap();\n\n assert!(Event::find(event.id, connection).is_err());\n\n}\n\n\n", "file_path": "db/tests/unit/events.rs", "rank": 97, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn find() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let announcement = project.create_announcement().finish();\n\n let found_announcement = Announcement::find(announcement.id, false, connection).unwrap();\n\n assert_eq!(found_announcement, announcement);\n\n}\n\n\n", "file_path": "db/tests/unit/announcements.rs", "rank": 98, "score": 176403.77959812304 }, { "content": "#[test]\n\nfn destroy() {\n\n let project = TestProject::new();\n\n let connection = project.get_connection();\n\n let hold = project.create_hold().finish();\n\n assert!(hold.clone().destroy(None, connection).is_ok());\n\n assert!(Hold::find(hold.id, connection).unwrap().deleted_at.is_some());\n\n\n\n // Destroy hold with comps\n\n let comp = project.create_comp().finish();\n\n let hold = Hold::find(comp.id, connection).unwrap();\n\n hold.clone().destroy(None, connection).unwrap();\n\n assert!(Hold::find(hold.id, connection).unwrap().deleted_at.is_some());\n\n}\n\n\n", "file_path": "db/tests/unit/holds.rs", "rank": 99, "score": 176403.77959812304 } ]
Rust
ciborium-ll/src/dec.rs
roman-kashitsyn/ciborium
b6d9ae284ece285011f48d7a70456d5d93da0cdc
use super::*; use ciborium_io::Read; #[derive(Debug)] pub enum Error<T> { Io(T), Syntax(usize), } impl<T> From<T> for Error<T> { #[inline] fn from(value: T) -> Self { Self::Io(value) } } pub struct Decoder<R: Read> { reader: R, offset: usize, buffer: Option<Title>, } impl<R: Read> From<R> for Decoder<R> { #[inline] fn from(value: R) -> Self { Self { reader: value, offset: 0, buffer: None, } } } impl<R: Read> Read for Decoder<R> { type Error = R::Error; #[inline] fn read_exact(&mut self, data: &mut [u8]) -> Result<(), Self::Error> { assert!(self.buffer.is_none()); self.reader.read_exact(data)?; self.offset += data.len(); Ok(()) } } impl<R: Read> Decoder<R> { #[inline] fn pull_title(&mut self) -> Result<Title, Error<R::Error>> { if let Some(title) = self.buffer.take() { self.offset += title.1.as_ref().len() + 1; return Ok(title); } let mut prefix = [0u8; 1]; self.read_exact(&mut prefix[..])?; let major = match prefix[0] >> 5 { 0 => Major::Positive, 1 => Major::Negative, 2 => Major::Bytes, 3 => Major::Text, 4 => Major::Array, 5 => Major::Map, 6 => Major::Tag, 7 => Major::Other, _ => unreachable!(), }; let mut minor = match prefix[0] & 0b00011111 { x if x < 24 => Minor::This(x), 24 => Minor::Next1([0; 1]), 25 => Minor::Next2([0; 2]), 26 => Minor::Next4([0; 4]), 27 => Minor::Next8([0; 8]), 31 => Minor::More, _ => return Err(Error::Syntax(self.offset - 1)), }; self.read_exact(minor.as_mut())?; Ok(Title(major, minor)) } #[inline] fn push_title(&mut self, item: Title) { assert!(self.buffer.is_none()); self.buffer = Some(item); self.offset -= item.1.as_ref().len() + 1; } #[inline] pub fn pull(&mut self) -> Result<Header, Error<R::Error>> { let offset = self.offset; self.pull_title()? .try_into() .map_err(|_| Error::Syntax(offset)) } #[inline] pub fn push(&mut self, item: Header) { self.push_title(Title::from(item)) } #[inline] pub fn offset(&mut self) -> usize { self.offset } #[inline] pub fn bytes(&mut self, len: Option<usize>) -> Segments<R, crate::seg::Bytes> { self.push(Header::Bytes(len)); Segments::new(self, |header| match header { Header::Bytes(len) => Ok(len), _ => Err(()), }) } #[inline] pub fn text(&mut self, len: Option<usize>) -> Segments<R, crate::seg::Text> { self.push(Header::Text(len)); Segments::new(self, |header| match header { Header::Text(len) => Ok(len), _ => Err(()), }) } }
use super::*; use ciborium_io::Read; #[derive(Debug)] pub enum Error<T> { Io(T), Syntax(usize), } impl<T> From<T> for Error<T> { #[inline] fn from(value: T) -> Self { Self::Io(value) } } pub struct Decoder<R: Read> { reader: R, offset: usize, buffer: Option<Title>, } impl<R: Read> From<R> for Decoder<R> { #[inline] fn from(value: R) -> Self { Self { reader: value, offset: 0, buffer: None, } } } impl<R: Read> Read for Decoder<R> { type Error = R::Error; #[inline] fn read_exact(&mut self, data: &mut [u8]) -> Result<(), Self::Error> { asse
} impl<R: Read> Decoder<R> { #[inline] fn pull_title(&mut self) -> Result<Title, Error<R::Error>> { if let Some(title) = self.buffer.take() { self.offset += title.1.as_ref().len() + 1; return Ok(title); } let mut prefix = [0u8; 1]; self.read_exact(&mut prefix[..])?; let major = match prefix[0] >> 5 { 0 => Major::Positive, 1 => Major::Negative, 2 => Major::Bytes, 3 => Major::Text, 4 => Major::Array, 5 => Major::Map, 6 => Major::Tag, 7 => Major::Other, _ => unreachable!(), }; let mut minor = match prefix[0] & 0b00011111 { x if x < 24 => Minor::This(x), 24 => Minor::Next1([0; 1]), 25 => Minor::Next2([0; 2]), 26 => Minor::Next4([0; 4]), 27 => Minor::Next8([0; 8]), 31 => Minor::More, _ => return Err(Error::Syntax(self.offset - 1)), }; self.read_exact(minor.as_mut())?; Ok(Title(major, minor)) } #[inline] fn push_title(&mut self, item: Title) { assert!(self.buffer.is_none()); self.buffer = Some(item); self.offset -= item.1.as_ref().len() + 1; } #[inline] pub fn pull(&mut self) -> Result<Header, Error<R::Error>> { let offset = self.offset; self.pull_title()? .try_into() .map_err(|_| Error::Syntax(offset)) } #[inline] pub fn push(&mut self, item: Header) { self.push_title(Title::from(item)) } #[inline] pub fn offset(&mut self) -> usize { self.offset } #[inline] pub fn bytes(&mut self, len: Option<usize>) -> Segments<R, crate::seg::Bytes> { self.push(Header::Bytes(len)); Segments::new(self, |header| match header { Header::Bytes(len) => Ok(len), _ => Err(()), }) } #[inline] pub fn text(&mut self, len: Option<usize>) -> Segments<R, crate::seg::Text> { self.push(Header::Text(len)); Segments::new(self, |header| match header { Header::Text(len) => Ok(len), _ => Err(()), }) } }
rt!(self.buffer.is_none()); self.reader.read_exact(data)?; self.offset += data.len(); Ok(()) }
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn from_reader<'de, T: de::Deserialize<'de>, R: Read>(reader: R) -> Result<T, Error<R::Error>>\n\nwhere\n\n R::Error: core::fmt::Debug,\n\n{\n\n let mut scratch = [0; 4096];\n\n\n\n let mut reader = Deserializer {\n\n decoder: reader.into(),\n\n scratch: &mut scratch,\n\n recurse: 256,\n\n };\n\n\n\n T::deserialize(&mut reader)\n\n}\n", "file_path": "ciborium/src/de/mod.rs", "rank": 0, "score": 283000.4733488463 }, { "content": "struct TagAccess<'a, 'b, R: Read>(&'a mut Deserializer<'b, R>, usize);\n\n\n\nimpl<'de, 'a, 'b, R: Read> de::Deserializer<'de> for &mut TagAccess<'a, 'b, R>\n\nwhere\n\n R::Error: core::fmt::Debug,\n\n{\n\n type Error = Error<R::Error>;\n\n\n\n #[inline]\n\n fn deserialize_any<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {\n\n let offset = self.0.decoder.offset();\n\n\n\n match self.0.decoder.pull()? {\n\n Header::Tag(x) => visitor.visit_u64(x),\n\n _ => Err(Error::semantic(offset, \"expected tag\")),\n\n }\n\n }\n\n\n\n forward_to_deserialize_any! {\n\n i8 i16 i32 i64 i128\n", "file_path": "ciborium/src/de/mod.rs", "rank": 1, "score": 206359.5257102113 }, { "content": "struct Access<'a, 'b, R: Read>(&'a mut Deserializer<'b, R>, Option<usize>);\n\n\n\nimpl<'de, 'a, 'b, R: Read> de::SeqAccess<'de> for Access<'a, 'b, R>\n\nwhere\n\n R::Error: core::fmt::Debug,\n\n{\n\n type Error = Error<R::Error>;\n\n\n\n #[inline]\n\n fn next_element_seed<U: de::DeserializeSeed<'de>>(\n\n &mut self,\n\n seed: U,\n\n ) -> Result<Option<U::Value>, Self::Error> {\n\n match self.1 {\n\n Some(0) => return Ok(None),\n\n Some(x) => self.1 = Some(x - 1),\n\n None => match self.0.decoder.pull()? {\n\n Header::Break => return Ok(None),\n\n header => self.0.decoder.push(header),\n\n },\n", "file_path": "ciborium/src/de/mod.rs", "rank": 2, "score": 203971.8501837507 }, { "content": "struct Deserializer<'b, R: Read> {\n\n decoder: Decoder<R>,\n\n scratch: &'b mut [u8],\n\n recurse: usize,\n\n}\n\n\n\nimpl<'de, 'a, 'b, R: Read> Deserializer<'b, R>\n\nwhere\n\n R::Error: core::fmt::Debug,\n\n{\n\n #[inline]\n\n fn recurse<V, F: FnOnce(&mut Self) -> Result<V, Error<R::Error>>>(\n\n &mut self,\n\n func: F,\n\n ) -> Result<V, Error<R::Error>> {\n\n if self.recurse == 0 {\n\n return Err(Error::RecursionLimitExceeded);\n\n }\n\n\n\n self.recurse -= 1;\n", "file_path": "ciborium/src/de/mod.rs", "rank": 3, "score": 153204.6509977806 }, { "content": "/// Compares two values uses canonical comparison, as defined in both\n\n/// RFC 7049 Section 3.9 (regarding key sorting) and RFC 8949 4.2.3 (as errata).\n\n///\n\n/// In short, the comparison follow the following rules:\n\n/// - If two keys have different lengths, the shorter one sorts earlier;\n\n/// - If two keys have the same length, the one with the lower value in\n\n/// (byte-wise) lexical order sorts earlier.\n\n///\n\n/// This specific comparison allows Maps and sorting that respect these two rules.\n\npub fn cmp_value(v1: &Value, v2: &Value) -> Ordering {\n\n use Value::*;\n\n\n\n match (v1, v2) {\n\n (Integer(i), Integer(o)) => {\n\n // Because of the first rule above, two numbers might be in a different\n\n // order than regular i128 comparison. For example, 10 < -1 in\n\n // canonical ordering, since 10 serializes to `0x0a` and -1 to `0x20`,\n\n // and -1 < -1000 because of their lengths.\n\n i.canonical_cmp(o)\n\n }\n\n (Text(s), Text(o)) => match s.len().cmp(&o.len()) {\n\n Ordering::Equal => s.cmp(o),\n\n x => x,\n\n },\n\n (Bool(s), Bool(o)) => s.cmp(o),\n\n (Null, Null) => Ordering::Equal,\n\n (Tag(t, v), Tag(ot, ov)) => match Value::from(*t).partial_cmp(&Value::from(*ot)) {\n\n Some(Ordering::Equal) | None => match v.partial_cmp(ov) {\n\n Some(x) => x,\n", "file_path": "ciborium/src/value/canonical.rs", "rank": 4, "score": 128145.27195595577 }, { "content": "#[derive(Deserialize, Serialize, Copy, Clone, Debug, PartialEq, Eq)]\n\nstruct TupleStruct(u8, u16);\n\n\n", "file_path": "ciborium/tests/codec.rs", "rank": 5, "score": 114152.80232090026 }, { "content": "fn test(bytes: &str, error: Error<std::io::Error>) {\n\n let bytes = hex::decode(bytes).unwrap();\n\n\n\n let correct = match error {\n\n Error::Io(..) => panic!(),\n\n Error::Syntax(x) => (\"syntax\", Some(x), None),\n\n Error::Semantic(x, y) => (\"semantic\", x, Some(y)),\n\n Error::RecursionLimitExceeded => panic!(),\n\n };\n\n\n\n let result: Result<Value, _> = from_reader(&bytes[..]);\n\n let actual = match result.unwrap_err() {\n\n Error::Io(..) => panic!(),\n\n Error::Syntax(x) => (\"syntax\", Some(x), None),\n\n Error::Semantic(x, y) => (\"semantic\", x, Some(y)),\n\n Error::RecursionLimitExceeded => panic!(),\n\n };\n\n\n\n assert_eq!(correct, actual);\n\n}\n", "file_path": "ciborium/tests/error.rs", "rank": 6, "score": 113278.05146827771 }, { "content": "#[derive(Deserialize, Serialize, Copy, Clone, Debug, PartialEq, Eq)]\n\nstruct Newtype(u8);\n\n\n", "file_path": "ciborium/tests/codec.rs", "rank": 7, "score": 112535.31878754143 }, { "content": "/// A trait indicating a type that can read bytes\n\n///\n\n/// Note that this is similar to `std::io::Read`, but simplified for use in a\n\n/// `no_std` context.\n\npub trait Read {\n\n /// The error type\n\n type Error;\n\n\n\n /// Reads exactly `data.len()` bytes or fails\n\n fn read_exact(&mut self, data: &mut [u8]) -> Result<(), Self::Error>;\n\n}\n\n\n", "file_path": "ciborium-io/src/lib.rs", "rank": 8, "score": 111410.06928104689 }, { "content": "#[derive(Copy, Clone, Debug, PartialEq, Eq)]\n\nstruct Title(pub Major, pub Minor);\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n macro_rules! neg {\n\n ($i:expr) => {\n\n Header::Negative((($i as i128) ^ !0) as u64)\n\n };\n\n }\n\n\n\n #[allow(clippy::excessive_precision)]\n\n #[test]\n\n fn leaf() {\n\n use core::f64::{INFINITY, NAN};\n\n\n\n let data = &[\n\n (Header::Positive(0), \"00\", true),\n\n (Header::Positive(1), \"01\", true),\n", "file_path": "ciborium-ll/src/lib.rs", "rank": 9, "score": 111228.66944608446 }, { "content": "struct Visitor;\n\n\n\nimpl<'de> serde::de::Visitor<'de> for Visitor {\n\n type Value = Value;\n\n\n\n fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n\n write!(formatter, \"a valid CBOR item\")\n\n }\n\n\n\n mkvisit! {\n\n visit_bool(bool),\n\n visit_f32(f32),\n\n visit_f64(f64),\n\n\n\n visit_i8(i8),\n\n visit_i16(i16),\n\n visit_i32(i32),\n\n visit_i64(i64),\n\n visit_i128(i128),\n\n\n", "file_path": "ciborium/src/value/de.rs", "rank": 10, "score": 89623.1221591045 }, { "content": "struct Map {\n\n data: Vec<(Value, Value)>,\n\n temp: Option<Value>,\n\n}\n\n\n", "file_path": "ciborium/src/value/ser.rs", "rank": 11, "score": 89623.1221591045 }, { "content": "struct Tagged {\n\n tag: Option<u64>,\n\n val: Option<Value>,\n\n}\n\n\n", "file_path": "ciborium/src/value/ser.rs", "rank": 12, "score": 89623.1221591045 }, { "content": "#[derive(Debug)]\n\nstruct InvalidError(());\n\n\n", "file_path": "ciborium-ll/src/lib.rs", "rank": 13, "score": 89186.52402065211 }, { "content": "#[inline]\n\nfn bigint() -> Value {\n\n let bytes = hex::decode(\"0000000000000000000000000000000000000001\").unwrap();\n\n Value::Tag(2, Value::Bytes(bytes).into())\n\n}\n\n\n", "file_path": "ciborium/tests/codec.rs", "rank": 14, "score": 85970.58123811806 }, { "content": "struct Named<T> {\n\n name: &'static str,\n\n data: T,\n\n tag: Option<Tagged>,\n\n}\n\n\n", "file_path": "ciborium/src/value/ser.rs", "rank": 15, "score": 85515.03350790608 }, { "content": "fn test(answer: Value, question: Value) {\n\n assert_eq!(answer, question);\n\n}\n", "file_path": "ciborium/tests/macro.rs", "rank": 16, "score": 84963.47291860793 }, { "content": "#[inline]\n\nfn vmap_big() -> Value {\n\n Value::Map(\n\n map_big()\n\n .into_iter()\n\n .map(|x| (x.0.into(), x.1.into()))\n\n .collect(),\n\n )\n\n}\n\n\n", "file_path": "ciborium/tests/codec.rs", "rank": 17, "score": 83765.75180962257 }, { "content": "#[inline]\n\npub fn into_writer<T: ?Sized + ser::Serialize, W: Write>(\n\n value: &T,\n\n writer: W,\n\n) -> Result<(), Error<W::Error>>\n\nwhere\n\n W::Error: core::fmt::Debug,\n\n{\n\n let mut encoder = Serializer::from(writer);\n\n value.serialize(&mut encoder)?;\n\n Ok(encoder.0.flush()?)\n\n}\n", "file_path": "ciborium/src/ser/mod.rs", "rank": 18, "score": 83019.1775387182 }, { "content": "/// Manually serialize values to compare them.\n\nfn serialized_canonical_cmp(v1: &Value, v2: &Value) -> Ordering {\n\n // There is an optimization to be done here, but it would take a lot more code\n\n // and using mixing keys, Arrays or Maps as CanonicalValue is probably not the\n\n // best use of this type as it is meant mainly to be used as keys.\n\n\n\n let mut bytes1 = Vec::new();\n\n let _ = crate::ser::into_writer(v1, &mut bytes1);\n\n let mut bytes2 = Vec::new();\n\n let _ = crate::ser::into_writer(v2, &mut bytes2);\n\n\n\n match bytes1.len().cmp(&bytes2.len()) {\n\n Ordering::Equal => bytes1.cmp(&bytes2),\n\n x => x,\n\n }\n\n}\n\n\n", "file_path": "ciborium/src/value/canonical.rs", "rank": 19, "score": 82539.3724768795 }, { "content": "#[inline]\n\nfn veq(lhs: &Value, rhs: &Value) -> bool {\n\n if let Value::Float(l) = lhs {\n\n if let Value::Float(r) = rhs {\n\n return Float(*l) == Float(*r);\n\n }\n\n }\n\n\n\n lhs == rhs\n\n}\n\n\n", "file_path": "ciborium/tests/codec.rs", "rank": 20, "score": 82308.15096765141 }, { "content": "struct Serializer<T>(T);\n\n\n\nimpl ser::Serializer for Serializer<()> {\n\n type Ok = Value;\n\n type Error = Error;\n\n\n\n type SerializeSeq = Serializer<Vec<Value>>;\n\n type SerializeTuple = Serializer<Vec<Value>>;\n\n type SerializeTupleStruct = Serializer<Vec<Value>>;\n\n type SerializeTupleVariant = Serializer<Named<Vec<Value>>>;\n\n type SerializeMap = Serializer<Map>;\n\n type SerializeStruct = Serializer<Vec<(Value, Value)>>;\n\n type SerializeStructVariant = Serializer<Named<Vec<(Value, Value)>>>;\n\n\n\n mkserialize! {\n\n serialize_bool(bool),\n\n\n\n serialize_f32(f32),\n\n serialize_f64(f64),\n\n\n", "file_path": "ciborium/src/value/ser.rs", "rank": 21, "score": 81841.04594170238 }, { "content": "struct Deserializer<T>(T);\n\n\n\nimpl<'a, 'de> Deserializer<&'a Value> {\n\n fn integer<N>(&self, kind: &'static str) -> Result<N, Error>\n\n where\n\n N: TryFrom<u128>,\n\n N: TryFrom<i128>,\n\n {\n\n fn raw(value: &Value) -> Result<u128, Error> {\n\n let mut buffer = 0u128.to_ne_bytes();\n\n let length = buffer.len();\n\n\n\n let bytes = match value {\n\n Value::Bytes(bytes) => {\n\n // Skip leading zeros...\n\n let mut bytes: &[u8] = bytes.as_ref();\n\n while bytes.len() > buffer.len() && bytes[0] == 0 {\n\n bytes = &bytes[1..];\n\n }\n\n\n", "file_path": "ciborium/src/value/de.rs", "rank": 22, "score": 81841.04594170238 }, { "content": "#[derive(Deserialize, Serialize, Copy, Clone, Debug, PartialEq, Eq)]\n\nenum Enum {\n\n Unit,\n\n Newtype(u8),\n\n Tuple(u8, u16),\n\n Struct { first: u8, second: u16 },\n\n}\n", "file_path": "ciborium/tests/codec.rs", "rank": 23, "score": 74774.41906995504 }, { "content": "// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse alloc::string::{String, ToString};\n\n\n\n/// The error when serializing to/from a `Value`\n\n#[derive(Debug)]\n\npub enum Error {\n\n /// A custom error string produced by serde\n\n Custom(String),\n\n}\n\n\n\nimpl core::fmt::Display for Error {\n\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n\n write!(f, \"{:?}\", self)\n\n }\n\n}\n\n\n\nimpl serde::de::StdError for Error {}\n\n\n\nimpl serde::de::Error for Error {\n", "file_path": "ciborium/src/value/error.rs", "rank": 24, "score": 69359.3688862515 }, { "content": " #[inline]\n\n fn custom<T: core::fmt::Display>(msg: T) -> Self {\n\n Self::Custom(msg.to_string())\n\n }\n\n}\n\n\n\nimpl serde::ser::Error for Error {\n\n #[inline]\n\n fn custom<T: core::fmt::Display>(msg: T) -> Self {\n\n Self::Custom(msg.to_string())\n\n }\n\n}\n", "file_path": "ciborium/src/value/error.rs", "rank": 25, "score": 69353.99123256018 }, { "content": "#[derive(Deserialize, Serialize, Copy, Clone, Debug, PartialEq, Eq)]\n\nstruct UnitStruct;\n\n\n", "file_path": "ciborium/tests/codec.rs", "rank": 26, "score": 66035.21321602716 }, { "content": "#[derive(Copy, Clone, Debug, PartialEq, Eq)]\n\nenum Minor {\n\n This(u8),\n\n Next1([u8; 1]),\n\n Next2([u8; 2]),\n\n Next4([u8; 4]),\n\n Next8([u8; 8]),\n\n More,\n\n}\n\n\n\nimpl AsRef<[u8]> for Minor {\n\n #[inline]\n\n fn as_ref(&self) -> &[u8] {\n\n match self {\n\n Self::More => &[],\n\n Self::This(..) => &[],\n\n Self::Next1(x) => x.as_ref(),\n\n Self::Next2(x) => x.as_ref(),\n\n Self::Next4(x) => x.as_ref(),\n\n Self::Next8(x) => x.as_ref(),\n\n }\n", "file_path": "ciborium-ll/src/lib.rs", "rank": 27, "score": 59169.016829012304 }, { "content": "#[derive(Copy, Clone, Debug, PartialEq, Eq)]\n\nenum Major {\n\n Positive,\n\n Negative,\n\n Bytes,\n\n Text,\n\n Array,\n\n Map,\n\n Tag,\n\n Other,\n\n}\n\n\n", "file_path": "ciborium-ll/src/lib.rs", "rank": 28, "score": 59169.016829012304 }, { "content": "#[allow(non_camel_case_types)]\n\ntype pid_t = i32;\n\n\n\nextern \"C\" {\n\n fn close(fd: RawFd) -> c_int;\n\n fn fork() -> pid_t;\n\n fn pipe(pipefd: &mut [RawFd; 2]) -> c_int;\n\n fn waitpid(pid: pid_t, wstatus: *mut c_int, options: c_int) -> pid_t;\n\n}\n\n\n", "file_path": "ciborium/tests/fuzz.rs", "rank": 29, "score": 57526.39993349585 }, { "content": "#[derive(Deserialize, Serialize)]\n\n#[serde(rename = \"@@TAG@@\")]\n\nenum Internal<T> {\n\n #[serde(rename = \"@@UNTAGGED@@\")]\n\n Untagged(T),\n\n\n\n #[serde(rename = \"@@TAGGED@@\")]\n\n Tagged(u64, T),\n\n}\n\n\n\n/// An optional CBOR tag and its data item\n\n///\n\n/// No semantic evaluation of the tag is made.\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\npub struct Captured<V>(pub Option<u64>, pub V);\n\n\n\nimpl<'de, V: Deserialize<'de>> Deserialize<'de> for Captured<V> {\n\n #[inline]\n\n fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {\n\n match Internal::deserialize(deserializer)? {\n\n Internal::Tagged(t, v) => Ok(Captured(Some(t), v)),\n\n Internal::Untagged(v) => Ok(Captured(None, v)),\n", "file_path": "ciborium/src/tag.rs", "rank": 30, "score": 57111.737086557754 }, { "content": "#[test]\n\nfn decode() {\n\n assert_eq!(from_reader::<u8, &[u8]>(&[7u8][..]).unwrap(), 7);\n\n}\n\n\n", "file_path": "ciborium/tests/no_std.rs", "rank": 31, "score": 56357.23201321889 }, { "content": "#[test]\n\nfn map() {\n\n let bytes = [0xbf; 128 * 1024];\n\n match from_reader::<Value, _>(&bytes[..]).unwrap_err() {\n\n Error::RecursionLimitExceeded => (),\n\n e => panic!(\"incorrect error: {:?}\", e),\n\n }\n\n}\n\n\n", "file_path": "ciborium/tests/recursion.rs", "rank": 32, "score": 56357.23201321889 }, { "content": "#[test]\n\nfn array() {\n\n let bytes = [0x9f; 128 * 1024];\n\n match from_reader::<Value, _>(&bytes[..]).unwrap_err() {\n\n Error::RecursionLimitExceeded => (),\n\n e => panic!(\"incorrect error: {:?}\", e),\n\n }\n\n}\n\n\n", "file_path": "ciborium/tests/recursion.rs", "rank": 33, "score": 56357.23201321889 }, { "content": "#[test]\n\nfn map() {\n\n let mut map = BTreeMap::new();\n\n map.insert(cval!(false), val!(2));\n\n map.insert(cval!([-1]), val!(5));\n\n map.insert(cval!(-1), val!(1));\n\n map.insert(cval!(10), val!(0));\n\n map.insert(cval!(100), val!(3));\n\n map.insert(cval!([100]), val!(7));\n\n map.insert(cval!(\"z\"), val!(4));\n\n map.insert(cval!(\"aa\"), val!(6));\n\n\n\n let mut bytes1 = Vec::new();\n\n ciborium::ser::into_writer(&map, &mut bytes1).unwrap();\n\n\n\n assert_eq!(\n\n hex::encode(&bytes1),\n\n \"a80a002001f402186403617a048120056261610681186407\"\n\n );\n\n}\n\n\n", "file_path": "ciborium/tests/canonical.rs", "rank": 34, "score": 56357.23201321889 }, { "content": "#[test]\n\nfn bytes() {\n\n let bytes = [0x5f; 128 * 1024];\n\n match from_reader::<Value, _>(&bytes[..]).unwrap_err() {\n\n Error::Io(..) => (),\n\n e => panic!(\"incorrect error: {:?}\", e),\n\n }\n\n}\n\n\n", "file_path": "ciborium/tests/recursion.rs", "rank": 35, "score": 56357.23201321889 }, { "content": "#[test]\n\nfn text() {\n\n let bytes = [0x7f; 128 * 1024];\n\n match from_reader::<Value, _>(&bytes[..]).unwrap_err() {\n\n Error::Io(..) => (),\n\n e => panic!(\"incorrect error: {:?}\", e),\n\n }\n\n}\n", "file_path": "ciborium/tests/recursion.rs", "rank": 36, "score": 56357.23201321889 }, { "content": "#[test]\n\nfn fuzz() {\n\n let mut fds: [RawFd; 2] = [0; 2];\n\n assert_eq!(unsafe { pipe(&mut fds) }, 0);\n\n\n\n let pid = unsafe { fork() };\n\n assert!(pid >= 0);\n\n\n\n match pid {\n\n 0 => {\n\n let mut child = unsafe { File::from_raw_fd(fds[1]) };\n\n unsafe { close(fds[0]) };\n\n\n\n let mut rng = rand::thread_rng();\n\n let mut buffer = [0u8; 32];\n\n\n\n for _ in 0..ITERATIONS {\n\n let len = rng.gen_range(0..buffer.len());\n\n rng.fill(&mut buffer[..len]);\n\n\n\n writeln!(child, \"{}\", hex::encode(&buffer[..len])).unwrap();\n", "file_path": "ciborium/tests/fuzz.rs", "rank": 37, "score": 56357.23201321889 }, { "content": "#[test]\n\nfn eof() {\n\n from_reader::<u8, &[u8]>(&[]).unwrap_err();\n\n}\n\n\n", "file_path": "ciborium/tests/no_std.rs", "rank": 38, "score": 56357.23201321889 }, { "content": "#[test]\n\nfn oos() {\n\n into_writer(&3u8, &mut [][..]).unwrap_err();\n\n}\n", "file_path": "ciborium/tests/no_std.rs", "rank": 39, "score": 56357.23201321889 }, { "content": "/// A trait indicating a type that can write bytes\n\n///\n\n/// Note that this is similar to `std::io::Write`, but simplified for use in a\n\n/// `no_std` context.\n\npub trait Write {\n\n /// The error type\n\n type Error;\n\n\n\n /// Writes all bytes from `data` or fails\n\n fn write_all(&mut self, data: &[u8]) -> Result<(), Self::Error>;\n\n\n\n /// Flushes all output\n\n fn flush(&mut self) -> Result<(), Self::Error>;\n\n}\n\n\n\n#[cfg(feature = \"std\")]\n\nimpl<T: std::io::Read> Read for T {\n\n type Error = std::io::Error;\n\n\n\n #[inline]\n\n fn read_exact(&mut self, data: &mut [u8]) -> Result<(), Self::Error> {\n\n self.read_exact(data)\n\n }\n\n}\n", "file_path": "ciborium-io/src/lib.rs", "rank": 40, "score": 55569.35427765784 }, { "content": "#[test]\n\nfn rfc8949_example() {\n\n let mut array: Vec<CanonicalValue> = vec![\n\n cval!(10),\n\n cval!(-1),\n\n cval!(false),\n\n cval!(100),\n\n cval!(\"z\"),\n\n cval!([-1]),\n\n cval!(\"aa\"),\n\n cval!([100]),\n\n ];\n\n let golden = array.clone();\n\n\n\n // Shuffle the array.\n\n array.shuffle(&mut rand::thread_rng());\n\n\n\n array.sort();\n\n\n\n assert_eq!(array, golden);\n\n}\n\n\n", "file_path": "ciborium/tests/canonical.rs", "rank": 41, "score": 55148.2645874975 }, { "content": "#[test]\n\nfn encode_slice() {\n\n let mut buffer = [0u8; 1];\n\n into_writer(&3u8, &mut buffer[..]).unwrap();\n\n assert_eq!(buffer[0], 3);\n\n}\n\n\n", "file_path": "ciborium/tests/no_std.rs", "rank": 42, "score": 55148.2645874975 }, { "content": "#[test]\n\nfn encode_vec() {\n\n let mut buffer = Vec::with_capacity(1);\n\n into_writer(&3u8, &mut buffer).unwrap();\n\n assert_eq!(buffer[0], 3);\n\n}\n\n\n", "file_path": "ciborium/tests/no_std.rs", "rank": 43, "score": 55148.2645874975 }, { "content": "#[test]\n\nfn negative_numbers() {\n\n let mut array: Vec<CanonicalValue> = vec![\n\n cval!(10),\n\n cval!(-1),\n\n cval!(-2),\n\n cval!(-3),\n\n cval!(-4),\n\n cval!(false),\n\n cval!(100),\n\n cval!(-100),\n\n cval!(-200),\n\n cval!(\"z\"),\n\n cval!([-1]),\n\n cval!(-300),\n\n cval!(\"aa\"),\n\n cval!([100]),\n\n ];\n\n let golden = array.clone();\n\n\n\n // Shuffle the array.\n\n array.shuffle(&mut rand::thread_rng());\n\n\n\n array.sort();\n\n\n\n assert_eq!(array, golden);\n\n}\n", "file_path": "ciborium/tests/canonical.rs", "rank": 44, "score": 55148.2645874975 }, { "content": "/// A parser for incoming segments\n\npub trait Parser: Default {\n\n /// The type of item that is parsed\n\n type Item: ?Sized;\n\n\n\n /// The parsing error that may occur\n\n type Error;\n\n\n\n /// The main parsing function\n\n ///\n\n /// This function processes the incoming bytes and returns the item.\n\n ///\n\n /// One important detail that **MUST NOT** be overlooked is that the\n\n /// parser may save data from a previous parsing attempt. The number of\n\n /// bytes saved is indicated by the `Parser::saved()` function. The saved\n\n /// bytes will be copied into the beginning of the `bytes` array before\n\n /// processing. Therefore, two requirements should be met.\n\n ///\n\n /// First, the incoming byte slice should be larger than the saved bytes.\n\n ///\n\n /// Second, the incoming byte slice should contain new bytes only after\n", "file_path": "ciborium-ll/src/seg.rs", "rank": 45, "score": 52783.3162991432 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct Float<T>(T);\n\n\n\nimpl PartialEq for Float<f32> {\n\n fn eq(&self, other: &Float<f32>) -> bool {\n\n if self.0.is_nan() && other.0.is_nan() {\n\n return true;\n\n }\n\n\n\n self.0 == other.0\n\n }\n\n}\n\n\n\nimpl PartialEq for Float<f64> {\n\n fn eq(&self, other: &Float<f64>) -> bool {\n\n if self.0.is_nan() && other.0.is_nan() {\n\n return true;\n\n }\n\n\n\n self.0 == other.0\n\n }\n\n}\n\n\n", "file_path": "ciborium/tests/codec.rs", "rank": 46, "score": 52415.31585436531 }, { "content": "trait Expected<E: de::Error> {\n\n fn expected(self, kind: &'static str) -> E;\n\n}\n\n\n\nimpl<E: de::Error> Expected<E> for Header {\n\n #[inline]\n\n fn expected(self, kind: &'static str) -> E {\n\n de::Error::invalid_type(\n\n match self {\n\n Header::Positive(x) => de::Unexpected::Unsigned(x),\n\n Header::Negative(x) => de::Unexpected::Signed(x as i64 ^ !0),\n\n Header::Bytes(..) => de::Unexpected::Other(\"bytes\"),\n\n Header::Text(..) => de::Unexpected::Other(\"string\"),\n\n\n\n Header::Array(..) => de::Unexpected::Seq,\n\n Header::Map(..) => de::Unexpected::Map,\n\n\n\n Header::Tag(..) => de::Unexpected::Other(\"tag\"),\n\n\n\n Header::Simple(simple::FALSE) => de::Unexpected::Bool(false),\n", "file_path": "ciborium/src/de/mod.rs", "rank": 47, "score": 50637.09331312248 }, { "content": "struct CollectionSerializer<'a, W: Write> {\n\n encoder: &'a mut Serializer<W>,\n\n ending: bool,\n\n tag: bool,\n\n}\n\n\n\nimpl<'a, W: Write> ser::SerializeSeq for CollectionSerializer<'a, W>\n\nwhere\n\n W::Error: core::fmt::Debug,\n\n{\n\n type Ok = ();\n\n type Error = Error<W::Error>;\n\n\n\n #[inline]\n\n fn serialize_element<U: ?Sized + ser::Serialize>(\n\n &mut self,\n\n value: &U,\n\n ) -> Result<(), Self::Error> {\n\n value.serialize(&mut *self.encoder)\n\n }\n", "file_path": "ciborium/src/ser/mod.rs", "rank": 48, "score": 48982.359775447825 }, { "content": "fn codec<'de, T: Serialize + Clone, V: Debug + PartialEq + Deserialize<'de>, F: Fn(T) -> V>(\n\n input: T,\n\n value: Value,\n\n bytes: &str,\n\n alternate: bool,\n\n equality: F,\n\n) {\n\n let bytes = hex::decode(bytes).unwrap();\n\n\n\n if !alternate {\n\n let mut encoded = Vec::new();\n\n into_writer(&input, &mut encoded).unwrap();\n\n eprintln!(\"{:x?} == {:x?}\", bytes, encoded);\n\n assert_eq!(bytes, encoded);\n\n\n\n let mut encoded = Vec::new();\n\n into_writer(&value, &mut encoded).unwrap();\n\n eprintln!(\"{:x?} == {:x?}\", bytes, encoded);\n\n assert_eq!(bytes, encoded);\n\n\n", "file_path": "ciborium/tests/codec.rs", "rank": 49, "score": 48588.36017780729 }, { "content": "#[inline]\n\nfn same<T>(x: T) -> T {\n\n x\n\n}\n\n\n", "file_path": "ciborium/tests/codec.rs", "rank": 50, "score": 48420.85371220608 }, { "content": "struct Serializer<W: Write>(Encoder<W>);\n\n\n\nimpl<W: Write> From<W> for Serializer<W> {\n\n #[inline]\n\n fn from(writer: W) -> Self {\n\n Self(writer.into())\n\n }\n\n}\n\n\n\nimpl<W: Write> From<Encoder<W>> for Serializer<W> {\n\n #[inline]\n\n fn from(writer: Encoder<W>) -> Self {\n\n Self(writer)\n\n }\n\n}\n\n\n\nimpl<'a, W: Write> ser::Serializer for &'a mut Serializer<W>\n\nwhere\n\n W::Error: core::fmt::Debug,\n\n{\n", "file_path": "ciborium/src/ser/mod.rs", "rank": 51, "score": 46854.65832780738 }, { "content": "#[inline]\n\nfn map_big() -> BTreeMap<String, String> {\n\n let mut map = BTreeMap::new();\n\n map.insert(\"a\".into(), \"A\".into());\n\n map.insert(\"b\".into(), \"B\".into());\n\n map.insert(\"c\".into(), \"C\".into());\n\n map.insert(\"d\".into(), \"D\".into());\n\n map.insert(\"e\".into(), \"E\".into());\n\n map\n\n}\n\n\n", "file_path": "ciborium/tests/codec.rs", "rank": 52, "score": 45662.97404096925 }, { "content": "fn test<'de, T: Serialize + Deserialize<'de> + Debug + Eq>(\n\n item: T,\n\n bytes: &str,\n\n value: Value,\n\n encode: bool,\n\n success: bool,\n\n) {\n\n let bytes = hex::decode(bytes).unwrap();\n\n\n\n if encode {\n\n // Encode into bytes\n\n let mut encoded = Vec::new();\n\n into_writer(&item, &mut encoded).unwrap();\n\n assert_eq!(bytes, encoded);\n\n\n\n // Encode into value\n\n assert_eq!(value, Value::serialized(&item).unwrap());\n\n }\n\n\n\n // Decode from bytes\n", "file_path": "ciborium/tests/tag.rs", "rank": 53, "score": 41166.74734356059 }, { "content": "// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse ciborium::{de::from_reader, de::Error, value::Value};\n\nuse rstest::rstest;\n\n\n\n#[rstest(bytes, error,\n\n // Invalid value\n\n case(\"1e\", Error::Syntax(0)),\n\n\n\n // Indeterminate integers are invalid\n\n case(\"1f\", Error::Syntax(0)),\n\n\n\n // Indeterminate integer in an array\n\n case(\"83011f03\", Error::Syntax(2)),\n\n\n\n // Integer in a string continuation\n\n case(\"7F616101FF\", Error::Syntax(3)),\n\n\n\n // Bytes in a string continuation\n\n case(\"7F61614101FF\", Error::Syntax(3)),\n\n\n\n // Invalid UTF-8\n\n case(\"62C328\", Error::Syntax(0)),\n\n\n\n // Invalid UTF-8 in a string continuation\n\n case(\"7F62C328FF\", Error::Syntax(1)),\n\n)]\n", "file_path": "ciborium/tests/error.rs", "rank": 54, "score": 36939.675286043195 }, { "content": "// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse alloc::string::{String, ToString};\n\nuse core::fmt::{Debug, Display, Formatter, Result};\n\n\n\nuse serde::de::{Error as DeError, StdError};\n\n\n\n/// An error occurred during deserialization\n\n#[derive(Debug)]\n\npub enum Error<T> {\n\n /// An error occurred while reading bytes\n\n ///\n\n /// Contains the underlying error reaturned while reading.\n\n Io(T),\n\n\n\n /// An error occurred while parsing bytes\n\n ///\n\n /// Contains the offset into the stream where the syntax error occurred.\n\n Syntax(usize),\n\n\n", "file_path": "ciborium/src/de/error.rs", "rank": 55, "score": 35642.281442585576 }, { "content": " /// An error occurred while processing a parsed value\n\n ///\n\n /// Contains a description of the error that occurred and (optionally)\n\n /// the offset into the stream indicating the start of the item being\n\n /// processed when the error occurred.\n\n Semantic(Option<usize>, String),\n\n\n\n /// The input caused serde to recurse too much\n\n ///\n\n /// This error prevents a stack overflow.\n\n RecursionLimitExceeded,\n\n}\n\n\n\nimpl<T> Error<T> {\n\n /// A helper method for composing a semantic error\n\n #[inline]\n\n pub fn semantic(offset: impl Into<Option<usize>>, msg: impl Into<String>) -> Self {\n\n Self::Semantic(offset.into(), msg.into())\n\n }\n\n}\n", "file_path": "ciborium/src/de/error.rs", "rank": 56, "score": 35642.24313624647 }, { "content": "\n\nimpl<T> From<T> for Error<T> {\n\n #[inline]\n\n fn from(value: T) -> Self {\n\n Error::Io(value)\n\n }\n\n}\n\n\n\nimpl<T: Debug> Display for Error<T> {\n\n #[inline]\n\n fn fmt(&self, f: &mut Formatter<'_>) -> Result {\n\n write!(f, \"{:?}\", self)\n\n }\n\n}\n\n\n\nimpl<T: Debug> StdError for Error<T> {}\n\n\n\nimpl<T: Debug> SerError for Error<T> {\n\n fn custom<U: Display>(msg: U) -> Self {\n\n Error::Value(msg.to_string())\n\n }\n\n}\n", "file_path": "ciborium/src/ser/error.rs", "rank": 57, "score": 35640.433882849444 }, { "content": " fn fmt(&self, f: &mut Formatter<'_>) -> Result {\n\n write!(f, \"{:?}\", self)\n\n }\n\n}\n\n\n\nimpl<T: Debug> StdError for Error<T> {}\n\n\n\nimpl<T: Debug> DeError for Error<T> {\n\n #[inline]\n\n fn custom<U: Display>(msg: U) -> Self {\n\n Self::Semantic(None, msg.to_string())\n\n }\n\n}\n", "file_path": "ciborium/src/de/error.rs", "rank": 58, "score": 35640.19952631412 }, { "content": "// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse alloc::string::{String, ToString};\n\nuse core::fmt::{Debug, Display, Formatter, Result};\n\n\n\nuse serde::ser::{Error as SerError, StdError};\n\n\n\n/// An error occurred during serialization\n\n#[derive(Debug)]\n\npub enum Error<T> {\n\n /// An error occurred while writing bytes\n\n ///\n\n /// Contains the underlying error reaturned while writing.\n\n Io(T),\n\n\n\n /// An error indicating a value that cannot be serialized\n\n ///\n\n /// Contains a description of the problem.\n\n Value(String),\n\n}\n", "file_path": "ciborium/src/ser/error.rs", "rank": 59, "score": 35637.025500519376 }, { "content": "\n\nimpl<T> From<T> for Error<T> {\n\n #[inline]\n\n fn from(value: T) -> Self {\n\n Error::Io(value)\n\n }\n\n}\n\n\n\nimpl<T> From<ciborium_ll::Error<T>> for Error<T> {\n\n #[inline]\n\n fn from(value: ciborium_ll::Error<T>) -> Self {\n\n match value {\n\n ciborium_ll::Error::Io(x) => Self::Io(x),\n\n ciborium_ll::Error::Syntax(x) => Self::Syntax(x),\n\n }\n\n }\n\n}\n\n\n\nimpl<T: Debug> Display for Error<T> {\n\n #[inline]\n", "file_path": "ciborium/src/de/error.rs", "rank": 60, "score": 35636.94588220457 }, { "content": " #[inline]\n\n fn serialize_field<U: ?Sized + ser::Serialize>(\n\n &mut self,\n\n key: &'static str,\n\n value: &U,\n\n ) -> Result<(), Self::Error> {\n\n let k = Value::serialized(&key)?;\n\n let v = Value::serialized(&value)?;\n\n self.0.data.push((k, v));\n\n Ok(())\n\n }\n\n\n\n #[inline]\n\n fn end(self) -> Result<Self::Ok, Self::Error> {\n\n Ok(vec![(self.0.name.into(), self.0.data.into())].into())\n\n }\n\n}\n\n\n\nimpl Value {\n\n /// Serializes an object into a `Value`\n\n #[inline]\n\n pub fn serialized<T: ?Sized + ser::Serialize>(value: &T) -> Result<Self, Error> {\n\n value.serialize(Serializer(()))\n\n }\n\n}\n", "file_path": "ciborium/src/value/ser.rs", "rank": 61, "score": 33749.833428869395 }, { "content": " fn serialize_value<U: ?Sized + ser::Serialize>(&mut self, value: &U) -> Result<(), Error> {\n\n let key = self.0.temp.take().unwrap();\n\n let val = Value::serialized(&value)?;\n\n\n\n self.0.data.push((key, val));\n\n Ok(())\n\n }\n\n\n\n #[inline]\n\n fn end(self) -> Result<Self::Ok, Self::Error> {\n\n Ok(self.0.data.into())\n\n }\n\n}\n\n\n\nimpl<'a> ser::SerializeStruct for Serializer<Vec<(Value, Value)>> {\n\n type Ok = Value;\n\n type Error = Error;\n\n\n\n #[inline]\n\n fn serialize_field<U: ?Sized + ser::Serialize>(\n", "file_path": "ciborium/src/value/ser.rs", "rank": 62, "score": 33748.75326264052 }, { "content": " (\"@@TAG@@\", \"@@TAGGED@@\") => Some(Tagged {\n\n tag: None,\n\n val: None,\n\n }),\n\n\n\n _ => None,\n\n },\n\n }))\n\n }\n\n\n\n #[inline]\n\n fn serialize_map(self, length: Option<usize>) -> Result<Self::SerializeMap, Error> {\n\n Ok(Serializer(Map {\n\n data: Vec::with_capacity(length.unwrap_or(0)),\n\n temp: None,\n\n }))\n\n }\n\n\n\n #[inline]\n\n fn serialize_struct(\n", "file_path": "ciborium/src/value/ser.rs", "rank": 63, "score": 33747.80433919263 }, { "content": "\n\n Ok(Value::Map(map))\n\n }\n\n\n\n #[inline]\n\n fn visit_enum<A: de::EnumAccess<'de>>(self, acc: A) -> Result<Self::Value, A::Error> {\n\n use serde::de::VariantAccess;\n\n\n\n struct Inner;\n\n\n\n impl<'de> serde::de::Visitor<'de> for Inner {\n\n type Value = Value;\n\n\n\n fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n\n write!(formatter, \"a valid CBOR item\")\n\n }\n\n\n\n #[inline]\n\n fn visit_seq<A: de::SeqAccess<'de>>(self, mut acc: A) -> Result<Self::Value, A::Error> {\n\n let tag: u64 = acc\n", "file_path": "ciborium/src/value/de.rs", "rank": 64, "score": 33747.79130471231 }, { "content": "\n\n match self.0 {\n\n Value::Tag(.., v) => Deserializer(v.as_ref()).deserialize_enum(name, variants, visitor),\n\n Value::Map(x) if x.len() == 1 => visitor.visit_enum(Deserializer(&x[0])),\n\n x @ Value::Text(..) => visitor.visit_enum(Deserializer(x)),\n\n _ => Err(de::Error::invalid_type(self.0.into(), &\"map\")),\n\n }\n\n }\n\n}\n\n\n\nimpl<'a, 'de, T: Iterator<Item = &'a Value>> de::SeqAccess<'de> for Deserializer<T> {\n\n type Error = Error;\n\n\n\n #[inline]\n\n fn next_element_seed<U: de::DeserializeSeed<'de>>(\n\n &mut self,\n\n seed: U,\n\n ) -> Result<Option<U::Value>, Self::Error> {\n\n match self.0.next() {\n\n None => Ok(None),\n", "file_path": "ciborium/src/value/de.rs", "rank": 65, "score": 33747.68614608302 }, { "content": " self,\n\n _name: &'static str,\n\n length: usize,\n\n ) -> Result<Self::SerializeStruct, Error> {\n\n Ok(Serializer(Vec::with_capacity(length)))\n\n }\n\n\n\n #[inline]\n\n fn serialize_struct_variant(\n\n self,\n\n _name: &'static str,\n\n _index: u32,\n\n variant: &'static str,\n\n length: usize,\n\n ) -> Result<Self::SerializeStructVariant, Error> {\n\n Ok(Serializer(Named {\n\n name: variant,\n\n data: Vec::with_capacity(length),\n\n tag: None,\n\n }))\n", "file_path": "ciborium/src/value/ser.rs", "rank": 66, "score": 33747.6616093107 }, { "content": " type Ok = Value;\n\n type Error = Error;\n\n\n\n #[inline]\n\n fn serialize_element<U: ?Sized + ser::Serialize>(&mut self, value: &U) -> Result<(), Error> {\n\n self.0.push(Value::serialized(&value)?);\n\n Ok(())\n\n }\n\n\n\n #[inline]\n\n fn end(self) -> Result<Self::Ok, Self::Error> {\n\n Ok(self.0.into())\n\n }\n\n}\n\n\n\nimpl<'a> ser::SerializeTupleStruct for Serializer<Vec<Value>> {\n\n type Ok = Value;\n\n type Error = Error;\n\n\n\n #[inline]\n", "file_path": "ciborium/src/value/ser.rs", "rank": 67, "score": 33747.1061165822 }, { "content": " /// ```\n\n pub fn as_bytes_mut(&mut self) -> Option<&mut Vec<u8>> {\n\n match *self {\n\n Value::Bytes(ref mut bytes) => Some(bytes),\n\n _ => None,\n\n }\n\n }\n\n\n\n /// If the `Value` is a `Bytes`, returns a the associated `Vec<u8>` data as `Ok`.\n\n /// Returns `Err(Self)` otherwise.\n\n ///\n\n /// ```\n\n /// # use ciborium::Value;\n\n /// #\n\n /// let value = Value::Bytes(vec![104, 101, 108, 108, 111]);\n\n /// assert_eq!(value.into_bytes(), Ok(vec![104, 101, 108, 108, 111]));\n\n ///\n\n /// let value = Value::Bool(true);\n\n /// assert_eq!(value.into_bytes(), Err(Value::Bool(true)));\n\n /// ```\n", "file_path": "ciborium/src/value/mod.rs", "rank": 68, "score": 33746.6138460581 }, { "content": " &mut self,\n\n key: &'static str,\n\n value: &U,\n\n ) -> Result<(), Error> {\n\n let k = Value::serialized(&key)?;\n\n let v = Value::serialized(&value)?;\n\n self.0.push((k, v));\n\n Ok(())\n\n }\n\n\n\n #[inline]\n\n fn end(self) -> Result<Self::Ok, Self::Error> {\n\n Ok(self.0.into())\n\n }\n\n}\n\n\n\nimpl<'a> ser::SerializeStructVariant for Serializer<Named<Vec<(Value, Value)>>> {\n\n type Ok = Value;\n\n type Error = Error;\n\n\n", "file_path": "ciborium/src/value/ser.rs", "rank": 69, "score": 33746.110297648345 }, { "content": " fn serialize_field<U: ?Sized + ser::Serialize>(&mut self, value: &U) -> Result<(), Error> {\n\n self.0.push(Value::serialized(&value)?);\n\n Ok(())\n\n }\n\n\n\n #[inline]\n\n fn end(self) -> Result<Self::Ok, Self::Error> {\n\n Ok(self.0.into())\n\n }\n\n}\n\n\n\nimpl<'a> ser::SerializeTupleVariant for Serializer<Named<Vec<Value>>> {\n\n type Ok = Value;\n\n type Error = Error;\n\n\n\n #[inline]\n\n fn serialize_field<U: ?Sized + ser::Serialize>(&mut self, value: &U) -> Result<(), Error> {\n\n match self.0.tag.as_mut() {\n\n Some(tag) => match tag.tag {\n\n None => match value.serialize(crate::tag::Serializer) {\n", "file_path": "ciborium/src/value/ser.rs", "rank": 70, "score": 33746.059115726915 }, { "content": " Value::Null => visitor.visit_unit(),\n\n _ => Err(de::Error::invalid_type(self.0.into(), &\"null\")),\n\n }\n\n }\n\n\n\n #[inline]\n\n fn deserialize_unit_struct<V: de::Visitor<'de>>(\n\n self,\n\n _name: &'static str,\n\n visitor: V,\n\n ) -> Result<V::Value, Self::Error> {\n\n self.deserialize_unit(visitor)\n\n }\n\n\n\n #[inline]\n\n fn deserialize_newtype_struct<V: de::Visitor<'de>>(\n\n self,\n\n _name: &'static str,\n\n visitor: V,\n\n ) -> Result<V::Value, Self::Error> {\n", "file_path": "ciborium/src/value/de.rs", "rank": 71, "score": 33745.410796375225 }, { "content": " _len: usize,\n\n visitor: V,\n\n ) -> Result<V::Value, Self::Error> {\n\n self.deserialize_seq(visitor)\n\n }\n\n\n\n #[inline]\n\n fn struct_variant<V: de::Visitor<'de>>(\n\n self,\n\n _fields: &'static [&'static str],\n\n visitor: V,\n\n ) -> Result<V::Value, Self::Error> {\n\n self.deserialize_map(visitor)\n\n }\n\n}\n\n\n\nimpl Value {\n\n /// Deserializes the `Value` into an object\n\n #[inline]\n\n pub fn deserialized<'de, T: de::Deserialize<'de>>(&self) -> Result<T, Error> {\n\n T::deserialize(Deserializer(self))\n\n }\n\n}\n", "file_path": "ciborium/src/value/de.rs", "rank": 72, "score": 33745.1047645388 }, { "content": " match *self {\n\n Value::Text(ref mut s) => Some(s),\n\n _ => None,\n\n }\n\n }\n\n\n\n /// If the `Value` is a `String`, returns a the associated `String` data as `Ok`.\n\n /// Returns `Err(Self)` otherwise.\n\n ///\n\n /// ```\n\n /// # use ciborium::Value;\n\n /// #\n\n /// let value = Value::Text(String::from(\"hello\"));\n\n /// assert_eq!(value.into_text().as_deref(), Ok(\"hello\"));\n\n ///\n\n /// let value = Value::Bool(true);\n\n /// assert_eq!(value.into_text(), Err(Value::Bool(true)));\n\n /// ```\n\n pub fn into_text(self) -> Result<String, Self> {\n\n match self {\n", "file_path": "ciborium/src/value/mod.rs", "rank": 73, "score": 33745.068856355 }, { "content": " }\n\n }\n\n\n\n #[inline]\n\n fn deserialize_bool<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {\n\n let mut value = self.0;\n\n while let Value::Tag(.., v) = value {\n\n value = v;\n\n }\n\n\n\n match value {\n\n Value::Bool(x) => visitor.visit_bool(*x),\n\n _ => Err(de::Error::invalid_type(value.into(), &\"bool\")),\n\n }\n\n }\n\n\n\n #[inline]\n\n fn deserialize_f32<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {\n\n self.deserialize_f64(visitor)\n\n }\n", "file_path": "ciborium/src/value/de.rs", "rank": 74, "score": 33745.05189038631 }, { "content": "\n\n #[inline]\n\n fn next_value_seed<V: de::DeserializeSeed<'de>>(\n\n &mut self,\n\n seed: V,\n\n ) -> Result<V::Value, Self::Error> {\n\n seed.deserialize(Deserializer(&self.0.next().unwrap().1))\n\n }\n\n}\n\n\n\nimpl<'a, 'de> de::EnumAccess<'de> for Deserializer<&'a (Value, Value)> {\n\n type Error = Error;\n\n type Variant = Deserializer<&'a Value>;\n\n\n\n #[inline]\n\n fn variant_seed<V: de::DeserializeSeed<'de>>(\n\n self,\n\n seed: V,\n\n ) -> Result<(V::Value, Self::Variant), Self::Error> {\n\n let k = seed.deserialize(Deserializer(&self.0 .0))?;\n", "file_path": "ciborium/src/value/de.rs", "rank": 75, "score": 33744.99540656369 }, { "content": " /// If the `Value` is a `Float`, returns a reference to the associated float data.\n\n /// Returns None otherwise.\n\n ///\n\n /// ```\n\n /// # use ciborium::Value;\n\n /// #\n\n /// let value = Value::Float(17.0.into());\n\n ///\n\n /// // We can read the float number\n\n /// assert_eq!(value.as_float().unwrap(), 17.0_f64);\n\n /// ```\n\n pub fn as_float(&self) -> Option<f64> {\n\n match *self {\n\n Value::Float(f) => Some(f),\n\n _ => None,\n\n }\n\n }\n\n\n\n /// If the `Value` is a `Float`, returns a the associated `f64` data as `Ok`.\n\n /// Returns `Err(Self)` otherwise.\n", "file_path": "ciborium/src/value/mod.rs", "rank": 76, "score": 33744.44027188007 }, { "content": " Ok(t) => tag.tag = Some(t),\n\n Err(..) => return Err(ser::Error::custom(\"expected tag\")),\n\n },\n\n\n\n Some(..) => tag.val = Some(Value::serialized(value)?),\n\n },\n\n\n\n None => self.0.data.push(Value::serialized(value)?),\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n #[inline]\n\n fn end(self) -> Result<Self::Ok, Self::Error> {\n\n Ok(match self.0.tag {\n\n Some(tag) => match tag {\n\n Tagged {\n\n tag: Some(t),\n\n val: Some(v),\n", "file_path": "ciborium/src/value/ser.rs", "rank": 77, "score": 33744.25976286735 }, { "content": " } => Value::Tag(t, v.into()),\n\n _ => return Err(ser::Error::custom(\"invalid tag input\")),\n\n },\n\n\n\n None => vec![(self.0.name.into(), self.0.data.into())].into(),\n\n })\n\n }\n\n}\n\n\n\nimpl<'a> ser::SerializeMap for Serializer<Map> {\n\n type Ok = Value;\n\n type Error = Error;\n\n\n\n #[inline]\n\n fn serialize_key<U: ?Sized + ser::Serialize>(&mut self, key: &U) -> Result<(), Error> {\n\n self.0.temp = Some(Value::serialized(key)?);\n\n Ok(())\n\n }\n\n\n\n #[inline]\n", "file_path": "ciborium/src/value/ser.rs", "rank": 78, "score": 33744.197536128384 }, { "content": " variant: &'static str,\n\n value: &U,\n\n ) -> Result<Value, Error> {\n\n Ok(match (name, variant) {\n\n (\"@@TAG@@\", \"@@UNTAGGED@@\") => Value::serialized(value)?,\n\n _ => vec![(variant.into(), Value::serialized(value)?)].into(),\n\n })\n\n }\n\n\n\n #[inline]\n\n fn serialize_seq(self, length: Option<usize>) -> Result<Self::SerializeSeq, Error> {\n\n Ok(Serializer(Vec::with_capacity(length.unwrap_or(0))))\n\n }\n\n\n\n #[inline]\n\n fn serialize_tuple(self, length: usize) -> Result<Self::SerializeTuple, Error> {\n\n self.serialize_seq(Some(length))\n\n }\n\n\n\n #[inline]\n", "file_path": "ciborium/src/value/ser.rs", "rank": 79, "score": 33744.01982482488 }, { "content": "\n\n #[inline]\n\n fn visit_some<D: de::Deserializer<'de>>(\n\n self,\n\n deserializer: D,\n\n ) -> Result<Self::Value, D::Error> {\n\n deserializer.deserialize_any(self)\n\n }\n\n\n\n #[inline]\n\n fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {\n\n Ok(Value::Null)\n\n }\n\n\n\n #[inline]\n\n fn visit_newtype_struct<D: de::Deserializer<'de>>(\n\n self,\n\n deserializer: D,\n\n ) -> Result<Self::Value, D::Error> {\n\n deserializer.deserialize_any(self)\n", "file_path": "ciborium/src/value/de.rs", "rank": 80, "score": 33743.995379071705 }, { "content": " fn serialize_tuple_struct(\n\n self,\n\n _name: &'static str,\n\n length: usize,\n\n ) -> Result<Self::SerializeTupleStruct, Error> {\n\n self.serialize_seq(Some(length))\n\n }\n\n\n\n #[inline]\n\n fn serialize_tuple_variant(\n\n self,\n\n name: &'static str,\n\n _index: u32,\n\n variant: &'static str,\n\n length: usize,\n\n ) -> Result<Self::SerializeTupleVariant, Error> {\n\n Ok(Serializer(Named {\n\n name: variant,\n\n data: Vec::with_capacity(length),\n\n tag: match (name, variant) {\n", "file_path": "ciborium/src/value/ser.rs", "rank": 81, "score": 33743.93316185739 }, { "content": "\n\n #[inline]\n\n fn serialize_some<U: ?Sized + ser::Serialize>(self, value: &U) -> Result<Value, Error> {\n\n value.serialize(self)\n\n }\n\n\n\n #[inline]\n\n fn serialize_unit(self) -> Result<Value, Error> {\n\n self.serialize_none()\n\n }\n\n\n\n #[inline]\n\n fn serialize_unit_struct(self, _name: &'static str) -> Result<Value, Error> {\n\n self.serialize_unit()\n\n }\n\n\n\n #[inline]\n\n fn serialize_unit_variant(\n\n self,\n\n _name: &'static str,\n", "file_path": "ciborium/src/value/ser.rs", "rank": 82, "score": 33743.82687211745 }, { "content": " visitor.visit_newtype_struct(self)\n\n }\n\n\n\n #[inline]\n\n fn deserialize_enum<V: de::Visitor<'de>>(\n\n self,\n\n name: &'static str,\n\n variants: &'static [&'static str],\n\n visitor: V,\n\n ) -> Result<V::Value, Self::Error> {\n\n if name == \"@@TAG@@\" {\n\n let (tag, val) = match self.0 {\n\n Value::Tag(t, v) => (Some(*t), v.as_ref()),\n\n v => (None, v),\n\n };\n\n\n\n let parent: Deserializer<&Value> = Deserializer(&*val);\n\n let access = crate::tag::TagAccess::new(parent, tag);\n\n return visitor.visit_enum(access);\n\n }\n", "file_path": "ciborium/src/value/de.rs", "rank": 83, "score": 33743.7812501774 }, { "content": " /// ]\n\n /// );\n\n ///\n\n /// value.as_map_mut().unwrap().clear();\n\n /// assert_eq!(value, Value::Map(vec![]));\n\n /// assert_eq!(value.as_map().unwrap().len(), 0);\n\n /// ```\n\n pub fn as_map_mut(&mut self) -> Option<&mut Vec<(Value, Value)>> {\n\n match *self {\n\n Value::Map(ref mut map) => Some(map),\n\n _ => None,\n\n }\n\n }\n\n\n\n /// If the `Value` is a `Map`, returns a the associated `Vec<(Value, Value)>` data as `Ok`.\n\n /// Returns `Err(Self)` otherwise.\n\n ///\n\n /// ```\n\n /// # use ciborium::Value;\n\n /// #\n", "file_path": "ciborium/src/value/mod.rs", "rank": 84, "score": 33743.713746092384 }, { "content": " /// to the tag `Value`. Returns None otherwise.\n\n ///\n\n /// ```\n\n /// # use ciborium::Value;\n\n /// #\n\n /// let mut value = Value::Tag(61, Box::from(Value::Bytes(vec![104, 101, 108, 108, 111])));\n\n ///\n\n /// let (tag, mut data) = value.as_tag_mut().unwrap();\n\n /// data.as_bytes_mut().unwrap().clear();\n\n /// assert_eq!(tag, &61);\n\n /// assert_eq!(data, &Value::Bytes(vec![]));\n\n /// ```\n\n pub fn as_tag_mut(&mut self) -> Option<(&mut u64, &mut Value)> {\n\n match self {\n\n Value::Tag(tag, data) => Some((tag, data.as_mut())),\n\n _ => None,\n\n }\n\n }\n\n\n\n /// If the `Value` is a `Tag`, returns a the associated pair of `u64` and `Box<value>` data as `Ok`.\n", "file_path": "ciborium/src/value/mod.rs", "rank": 85, "score": 33743.57922765324 }, { "content": "\n\n #[inline]\n\n fn deserialize_f64<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {\n\n let mut value = self.0;\n\n while let Value::Tag(.., v) = value {\n\n value = v;\n\n }\n\n\n\n match value {\n\n Value::Float(x) => visitor.visit_f64(*x),\n\n _ => Err(de::Error::invalid_type(value.into(), &\"f64\")),\n\n }\n\n }\n\n\n\n fn deserialize_i8<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {\n\n visitor.visit_i8(self.integer(\"i8\")?)\n\n }\n\n\n\n fn deserialize_i16<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {\n\n visitor.visit_i16(self.integer(\"i16\")?)\n", "file_path": "ciborium/src/value/de.rs", "rank": 86, "score": 33743.483188032944 }, { "content": " }\n\n}\n\n\n\nimpl<'a> ser::SerializeSeq for Serializer<Vec<Value>> {\n\n type Ok = Value;\n\n type Error = Error;\n\n\n\n #[inline]\n\n fn serialize_element<U: ?Sized + ser::Serialize>(&mut self, value: &U) -> Result<(), Error> {\n\n self.0.push(Value::serialized(&value)?);\n\n Ok(())\n\n }\n\n\n\n #[inline]\n\n fn end(self) -> Result<Self::Ok, Self::Error> {\n\n Ok(self.0.into())\n\n }\n\n}\n\n\n\nimpl<'a> ser::SerializeTuple for Serializer<Vec<Value>> {\n", "file_path": "ciborium/src/value/ser.rs", "rank": 87, "score": 33743.40747207997 }, { "content": " /// ```\n\n pub fn as_text(&self) -> Option<&str> {\n\n match *self {\n\n Value::Text(ref s) => Some(s),\n\n _ => None,\n\n }\n\n }\n\n\n\n /// If the `Value` is a `Text`, returns a mutable reference to the associated `String` data.\n\n /// Returns None otherwise.\n\n ///\n\n /// ```\n\n /// # use ciborium::Value;\n\n /// #\n\n /// let mut value = Value::Text(String::from(\"hello\"));\n\n /// value.as_text_mut().unwrap().clear();\n\n ///\n\n /// assert_eq!(value.as_text().unwrap(), &String::from(\"\"));\n\n /// ```\n\n pub fn as_text_mut(&mut self) -> Option<&mut String> {\n", "file_path": "ciborium/src/value/mod.rs", "rank": 88, "score": 33743.286687400185 }, { "content": "// SPDX-License-Identifier: Apache-2.0\n\nuse core::cmp::Ordering;\n\n\n\nmacro_rules! implfrom {\n\n ($( $(#[$($attr:meta)+])? $t:ident)+) => {\n\n $(\n\n $(#[$($attr)+])?\n\n impl From<$t> for Integer {\n\n #[inline]\n\n fn from(value: $t) -> Self {\n\n Self(value as _)\n\n }\n\n }\n\n\n\n impl TryFrom<Integer> for $t {\n\n type Error = core::num::TryFromIntError;\n\n\n\n #[inline]\n\n fn try_from(value: Integer) -> Result<Self, Self::Error> {\n\n $t::try_from(value.0)\n", "file_path": "ciborium/src/value/integer.rs", "rank": 89, "score": 33743.07659333253 }, { "content": " visitor: V,\n\n ) -> Result<V::Value, Self::Error> {\n\n self.deserialize_bytes(visitor)\n\n }\n\n\n\n fn deserialize_seq<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {\n\n let mut value = self.0;\n\n while let Value::Tag(.., v) = value {\n\n value = v;\n\n }\n\n\n\n match value {\n\n Value::Array(x) => visitor.visit_seq(Deserializer(x.iter())),\n\n _ => Err(de::Error::invalid_type(value.into(), &\"array\")),\n\n }\n\n }\n\n\n\n fn deserialize_map<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {\n\n let mut value = self.0;\n\n while let Value::Tag(.., v) = value {\n", "file_path": "ciborium/src/value/de.rs", "rank": 90, "score": 33743.02140054378 }, { "content": " }\n\n\n\n #[inline]\n\n fn visit_seq<A: de::SeqAccess<'de>>(self, mut acc: A) -> Result<Self::Value, A::Error> {\n\n let mut seq = Vec::new();\n\n\n\n while let Some(elem) = acc.next_element()? {\n\n seq.push(elem);\n\n }\n\n\n\n Ok(Value::Array(seq))\n\n }\n\n\n\n #[inline]\n\n fn visit_map<A: de::MapAccess<'de>>(self, mut acc: A) -> Result<Self::Value, A::Error> {\n\n let mut map = Vec::<(Value, Value)>::new();\n\n\n\n while let Some(kv) = acc.next_entry()? {\n\n map.push(kv);\n\n }\n", "file_path": "ciborium/src/value/de.rs", "rank": 91, "score": 33743.005276750286 }, { "content": " }\n\n\n\n fn deserialize_ignored_any<V: de::Visitor<'de>>(\n\n self,\n\n visitor: V,\n\n ) -> Result<V::Value, Self::Error> {\n\n self.deserialize_any(visitor)\n\n }\n\n\n\n #[inline]\n\n fn deserialize_option<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {\n\n match self.0 {\n\n Value::Null => visitor.visit_none(),\n\n x => visitor.visit_some(Self(x)),\n\n }\n\n }\n\n\n\n #[inline]\n\n fn deserialize_unit<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {\n\n match self.0 {\n", "file_path": "ciborium/src/value/de.rs", "rank": 92, "score": 33742.95982238128 }, { "content": " _len: usize,\n\n visitor: V,\n\n ) -> Result<V::Value, Self::Error> {\n\n self.deserialize_seq(visitor)\n\n }\n\n\n\n fn deserialize_tuple_struct<V: de::Visitor<'de>>(\n\n self,\n\n _name: &'static str,\n\n _len: usize,\n\n visitor: V,\n\n ) -> Result<V::Value, Self::Error> {\n\n self.deserialize_seq(visitor)\n\n }\n\n\n\n fn deserialize_identifier<V: de::Visitor<'de>>(\n\n self,\n\n visitor: V,\n\n ) -> Result<V::Value, Self::Error> {\n\n self.deserialize_str(visitor)\n", "file_path": "ciborium/src/value/de.rs", "rank": 93, "score": 33742.96266265384 }, { "content": " Some(v) => seed.deserialize(Deserializer(v)).map(Some),\n\n }\n\n }\n\n}\n\n\n\nimpl<'a, 'de, T: Iterator<Item = &'a (Value, Value)>> de::MapAccess<'de>\n\n for Deserializer<Peekable<T>>\n\n{\n\n type Error = Error;\n\n\n\n #[inline]\n\n fn next_key_seed<K: de::DeserializeSeed<'de>>(\n\n &mut self,\n\n seed: K,\n\n ) -> Result<Option<K::Value>, Self::Error> {\n\n match self.0.peek() {\n\n None => Ok(None),\n\n Some(x) => Ok(Some(seed.deserialize(Deserializer(&x.0))?)),\n\n }\n\n }\n", "file_path": "ciborium/src/value/de.rs", "rank": 94, "score": 33742.898118254416 }, { "content": "\n\n #[inline]\n\n fn unit_variant(self) -> Result<(), Self::Error> {\n\n match self.0 {\n\n Value::Null => Ok(()),\n\n _ => Err(de::Error::invalid_type(self.0.into(), &\"unit\")),\n\n }\n\n }\n\n\n\n #[inline]\n\n fn newtype_variant_seed<U: de::DeserializeSeed<'de>>(\n\n self,\n\n seed: U,\n\n ) -> Result<U::Value, Self::Error> {\n\n seed.deserialize(self)\n\n }\n\n\n\n #[inline]\n\n fn tuple_variant<V: de::Visitor<'de>>(\n\n self,\n", "file_path": "ciborium/src/value/de.rs", "rank": 95, "score": 33742.86285733882 }, { "content": " type Error = core::num::TryFromIntError;\n\n\n\n #[inline]\n\n fn try_from(value: u128) -> Result<Self, Self::Error> {\n\n Ok(Self(u64::try_from(value)?.into()))\n\n }\n\n}\n\n\n\nimpl From<Integer> for i128 {\n\n #[inline]\n\n fn from(value: Integer) -> Self {\n\n value.0\n\n }\n\n}\n\n\n\nimpl TryFrom<Integer> for u128 {\n\n type Error = core::num::TryFromIntError;\n\n\n\n #[inline]\n\n fn try_from(value: Integer) -> Result<Self, Self::Error> {\n\n u128::try_from(value.0)\n\n }\n\n}\n", "file_path": "ciborium/src/value/integer.rs", "rank": 96, "score": 33742.38473511077 }, { "content": " }\n\n\n\n /// If the `Value` is a `Array`, returns a the associated `Vec<Value>` data as `Ok`.\n\n /// Returns `Err(Self)` otherwise.\n\n ///\n\n /// ```\n\n /// # use ciborium::{Value, value::Integer};\n\n /// #\n\n /// let mut value = Value::Array(\n\n /// vec![\n\n /// Value::Integer(17.into()),\n\n /// Value::Float(18.),\n\n /// ]\n\n /// );\n\n /// assert_eq!(value.into_array(), Ok(vec![Value::Integer(17.into()), Value::Float(18.)]));\n\n ///\n\n /// let value = Value::Bool(true);\n\n /// assert_eq!(value.into_array(), Err(Value::Bool(true)));\n\n /// ```\n\n pub fn into_array(self) -> Result<Vec<Value>, Self> {\n", "file_path": "ciborium/src/value/mod.rs", "rank": 97, "score": 33742.15861091196 }, { "content": " self.as_integer().is_some()\n\n }\n\n\n\n /// If the `Value` is a `Integer`, returns a reference to the associated `Integer` data.\n\n /// Returns None otherwise.\n\n ///\n\n /// ```\n\n /// # use ciborium::Value;\n\n /// #\n\n /// let value = Value::Integer(17.into());\n\n ///\n\n /// // We can read the number\n\n /// assert_eq!(17, value.as_integer().unwrap().try_into().unwrap());\n\n /// ```\n\n pub fn as_integer(&self) -> Option<Integer> {\n\n match self {\n\n Value::Integer(int) => Some(*int),\n\n _ => None,\n\n }\n\n }\n", "file_path": "ciborium/src/value/mod.rs", "rank": 98, "score": 33741.904266958656 }, { "content": " ///\n\n /// ```\n\n /// # use ciborium::Value;\n\n /// #\n\n /// let value = Value::Bool(false);\n\n ///\n\n /// assert_eq!(value.as_bool().unwrap(), false);\n\n /// ```\n\n pub fn as_bool(&self) -> Option<bool> {\n\n match *self {\n\n Value::Bool(b) => Some(b),\n\n _ => None,\n\n }\n\n }\n\n\n\n /// If the `Value` is a `Bool`, returns a the associated `bool` data as `Ok`.\n\n /// Returns `Err(Self)` otherwise.\n\n ///\n\n /// ```\n\n /// # use ciborium::Value;\n", "file_path": "ciborium/src/value/mod.rs", "rank": 99, "score": 33741.896748331514 } ]
Rust
kimchi/src/tests/lookup.rs
chee-chyuan/proof-systems
b883501b06375da79fc9965c1c17e02a72e9ded7
use super::framework::{print_witness, TestFramework}; use crate::circuits::{ gate::{CircuitGate, GateType}, lookup::{ runtime_tables::{RuntimeTable, RuntimeTableCfg, RuntimeTableSpec}, tables::LookupTable, }, polynomial::COLUMNS, wires::Wire, }; use ark_ff::Zero; use array_init::array_init; use mina_curves::pasta::fp::Fp; fn setup_lookup_proof(use_values_from_table: bool, num_lookups: usize, table_sizes: Vec<usize>) { let lookup_table_values: Vec<Vec<_>> = table_sizes .iter() .map(|size| (0..*size).map(|_| rand::random()).collect()) .collect(); let lookup_tables = lookup_table_values .iter() .enumerate() .map(|(id, lookup_table_values)| { let index_column = (0..lookup_table_values.len() as u64) .map(Into::into) .collect(); LookupTable { id: id as i32, data: vec![index_column, lookup_table_values.clone()], } }) .collect(); let gates = (0..num_lookups) .map(|i| CircuitGate { typ: GateType::Lookup, coeffs: vec![], wires: Wire::new(i), }) .collect(); let witness = { let mut lookup_table_ids = Vec::with_capacity(num_lookups); let mut lookup_indexes: [_; 3] = array_init(|_| Vec::with_capacity(num_lookups)); let mut lookup_values: [_; 3] = array_init(|_| Vec::with_capacity(num_lookups)); let unused = || vec![Fp::zero(); num_lookups]; let num_tables = table_sizes.len(); let mut tables_used = std::collections::HashSet::new(); for _ in 0..num_lookups { let table_id = rand::random::<usize>() % num_tables; tables_used.insert(table_id); let lookup_table_values: &Vec<Fp> = &lookup_table_values[table_id]; lookup_table_ids.push((table_id as u64).into()); for i in 0..3 { let index = rand::random::<usize>() % lookup_table_values.len(); let value = if use_values_from_table { lookup_table_values[index] } else { rand::random() }; lookup_indexes[i].push((index as u64).into()); lookup_values[i].push(value); } } assert!(tables_used.len() >= 2 || table_sizes.len() <= 1); let [lookup_indexes0, lookup_indexes1, lookup_indexes2] = lookup_indexes; let [lookup_values0, lookup_values1, lookup_values2] = lookup_values; [ lookup_table_ids, lookup_indexes0, lookup_values0, lookup_indexes1, lookup_values1, lookup_indexes2, lookup_values2, unused(), unused(), unused(), unused(), unused(), unused(), unused(), unused(), ] }; TestFramework::default() .gates(gates) .witness(witness) .lookup_tables(lookup_tables) .setup() .prove_and_verify(); } #[test] fn lookup_gate_proving_works() { setup_lookup_proof(true, 500, vec![256]) } #[test] #[should_panic] fn lookup_gate_rejects_bad_lookups() { setup_lookup_proof(false, 500, vec![256]) } #[test] fn lookup_gate_proving_works_multiple_tables() { setup_lookup_proof(true, 500, vec![100, 50, 50, 2, 2]) } #[test] #[should_panic] fn lookup_gate_rejects_bad_lookups_multiple_tables() { setup_lookup_proof(false, 500, vec![100, 50, 50, 2, 2]) } fn runtime_table(num: usize, indexed: bool) { let mut runtime_tables_setup = vec![]; for table_id in 0..num { let cfg = if indexed { RuntimeTableCfg::Indexed(RuntimeTableSpec { id: table_id as i32, len: 5, }) } else { RuntimeTableCfg::Custom { id: table_id as i32, first_column: [8u32, 9, 8, 7, 1].into_iter().map(Into::into).collect(), } }; runtime_tables_setup.push(cfg); } let data: Vec<Fp> = [0u32, 2, 3, 4, 5].into_iter().map(Into::into).collect(); let runtime_tables: Vec<RuntimeTable<Fp>> = runtime_tables_setup .iter() .map(|cfg| RuntimeTable { id: cfg.id(), data: data.clone(), }) .collect(); let mut gates = vec![]; for row in 0..20 { gates.push(CircuitGate { typ: GateType::Lookup, wires: Wire::new(row), coeffs: vec![], }); } let witness = { let mut cols: [_; COLUMNS] = array_init(|_col| vec![Fp::zero(); gates.len()]); let (lookup_cols, _rest) = cols.split_at_mut(7); for row in 0..20 { lookup_cols[0][row] = 0u32.into(); let lookup_cols = &mut lookup_cols[1..]; for chunk in lookup_cols.chunks_mut(2) { chunk[0][row] = if indexed { 1u32.into() } else { 9u32.into() }; chunk[1][row] = 2u32.into(); } } cols }; print_witness(&witness, 0, 20); TestFramework::default() .gates(gates) .witness(witness) .runtime_tables_setup(runtime_tables_setup) .setup() .runtime_tables(runtime_tables) .prove_and_verify(); } #[test] fn test_indexed_runtime_table() { runtime_table(5, true); } #[test] fn test_custom_runtime_table() { runtime_table(5, false); }
use super::framework::{print_witness, TestFramework}; use crate::circuits::{ gate::{CircuitGate, GateType}, lookup::{ runtime_tables::{RuntimeTable, RuntimeTableCfg, RuntimeTableSpec}, tables::LookupTable, }, polynomial::COLUMNS, wires::Wire, }; use ark_ff::Zero; use array_init::array_init; use mina_curves::pasta::fp::Fp; fn setup_lookup_proof(use_values_from_table: bool, num_lookups: usize, table_sizes: Vec<usize>) { let lookup_table_values: Vec<Vec<_>> = table_sizes .iter() .map(|size| (0..*size).map(|_| rand::random()).collect()) .collect(); let lookup_tables = lookup_table_values .iter() .enumerate() .map(|(id, lookup_table_values)| { let index_column = (0..lookup_table_values.len() as u64) .map(Into::into) .collect(); LookupTable { id: id as i32, data: vec![index_column, lookup_table_values.clone()], } }) .collect(); let gates = (0..num_lookups) .map(|i| CircuitGate { typ: GateType::Lookup, coeffs: vec![], wires: Wire::new(i), }) .collect(); let witness = { let mut lookup_table_ids = Vec::with_capacity(num_lookups); let mut lookup_indexes: [_; 3] = array_init(|_| Vec::with_capacity(num_lookups)); let mut lookup_values: [_; 3] = array_init(|_| Vec::with_capacity(num_lookups)); let unused = || vec![Fp::zero(); num_lookups]; let num_tables = table_sizes.len(); let mut tables_used = std::collections::HashSet::new(); for _ in 0..num_lookups { let table_id = rand::random::<usize>() % num_tables; tables_used.insert(table_id); let lookup_table_values: &Vec<Fp> = &lookup_table_values[table_id]; lookup_table_ids.push((table_id as u64).into()); for i in 0..3 { let index = rand::random::<usize>() % lookup_table_values.len(); let value = if use_values_from_table { lookup_table_values[index] } else { rand::random() }; lookup_indexes[i].push((index as u64).into()); lookup_values[i].push(value); } } assert!(tables_used.len() >= 2 || table_sizes.len() <= 1); let [lookup_indexes0, lookup_indexes1, lookup_indexes2] = lookup_indexes; let [lookup_values0, lookup_values1, lookup_values2] = lookup_values; [ lookup_table_ids, lookup_indexes0, lookup_values0, lookup_indexes1, lookup_values1, lookup_indexes2, lookup_values2, unused(), unused(), unused(), unused(), unused(), unused(), unused(), unused(), ] }; TestFramework::default() .gates(gates) .witness(witness) .lookup_tables(lookup_tables) .setup() .prove_and_verify(); } #[test] fn lookup_gate_proving_works() { setup_lookup_proof(true, 500, vec![256]) } #[test] #[should_panic] fn lookup_gate_rejects_bad_lookups() { setup_lookup_proof(false, 500, vec![256]) } #[test] fn lookup_gate_proving_works_multiple_tables() { setup_lookup_proof(true, 500, vec![100, 50, 50, 2, 2]) } #[test] #[should_panic] fn lookup_gate_rejects_bad_lookups_multiple_tables() { setup_lookup_proof(false, 500, vec![100, 50, 50, 2, 2]) } fn runtime_table(num: usize, indexed: bool) { let mut runtime_tables_setup = vec![]; for table_id in 0..num { let cfg = if indexed { RuntimeTableCfg::Indexed(RuntimeTableSpec { id: table_id as i32, len: 5, }) } else { RuntimeTableCfg::Custom { id: table_id as i3
#[test] fn test_indexed_runtime_table() { runtime_table(5, true); } #[test] fn test_custom_runtime_table() { runtime_table(5, false); }
2, first_column: [8u32, 9, 8, 7, 1].into_iter().map(Into::into).collect(), } }; runtime_tables_setup.push(cfg); } let data: Vec<Fp> = [0u32, 2, 3, 4, 5].into_iter().map(Into::into).collect(); let runtime_tables: Vec<RuntimeTable<Fp>> = runtime_tables_setup .iter() .map(|cfg| RuntimeTable { id: cfg.id(), data: data.clone(), }) .collect(); let mut gates = vec![]; for row in 0..20 { gates.push(CircuitGate { typ: GateType::Lookup, wires: Wire::new(row), coeffs: vec![], }); } let witness = { let mut cols: [_; COLUMNS] = array_init(|_col| vec![Fp::zero(); gates.len()]); let (lookup_cols, _rest) = cols.split_at_mut(7); for row in 0..20 { lookup_cols[0][row] = 0u32.into(); let lookup_cols = &mut lookup_cols[1..]; for chunk in lookup_cols.chunks_mut(2) { chunk[0][row] = if indexed { 1u32.into() } else { 9u32.into() }; chunk[1][row] = 2u32.into(); } } cols }; print_witness(&witness, 0, 20); TestFramework::default() .gates(gates) .witness(witness) .runtime_tables_setup(runtime_tables_setup) .setup() .runtime_tables(runtime_tables) .prove_and_verify(); }
function_block-function_prefixed
[ { "content": "fn chacha_setup_bad_lookup(table_id: i32) {\n\n // circuit gates: one 'real' ChaCha0 and one 'fake' one.\n\n let gates = vec![\n\n GateType::ChaCha0,\n\n GateType::Zero,\n\n GateType::ChaCha0,\n\n GateType::Zero,\n\n ];\n\n let gates: Vec<CircuitGate<Fp>> = gates\n\n .into_iter()\n\n .enumerate()\n\n .map(|(i, typ)| CircuitGate {\n\n typ,\n\n coeffs: vec![],\n\n wires: Wire::new(i),\n\n })\n\n // Pad with generic gates to get a sufficiently-large domain.\n\n .chain((4..513).map(|i| CircuitGate {\n\n typ: GateType::Generic,\n\n coeffs: vec![Fp::zero(); 10],\n", "file_path": "kimchi/src/tests/chacha.rs", "rank": 1, "score": 331102.6579427287 }, { "content": "fn circuit_gate_selector_index(typ: GateType) -> usize {\n\n match typ {\n\n GateType::RangeCheck0 => 0,\n\n GateType::RangeCheck1 => 1,\n\n _ => panic!(\"invalid gate type\"),\n\n }\n\n}\n\n\n", "file_path": "kimchi/src/circuits/polynomials/range_check/gate.rs", "rank": 3, "score": 257536.9256338728 }, { "content": "// Connect the pair of cells specified by the cell1 and cell2 parameters\n\n// cell1 --> cell2 && cell2 --> cell1\n\n//\n\n// Note: This function assumes that the targeted cells are freshly instantiated\n\n// with self-connections. If the two cells are transitively already part\n\n// of the same permutation then this would split it.\n\nfn connect_cell_pair(wires: &mut [GateWires], cell1: (usize, usize), cell2: (usize, usize)) {\n\n let tmp = wires[cell1.0][cell1.1];\n\n wires[cell1.0][cell1.1] = wires[cell2.0][cell2.1];\n\n wires[cell2.0][cell2.1] = tmp;\n\n}\n\n\n\nimpl<F: FftField + SquareRootField> CircuitGate<F> {\n\n /// Create range check gate\n\n /// Inputs the starting row\n\n /// Outputs tuple (next_row, circuit_gates) where\n\n /// next_row - next row after this gate\n\n /// circuit_gates - vector of circuit gates comprising this gate\n\n pub fn create_range_check(start_row: usize) -> (usize, Vec<Self>) {\n\n let mut wires: Vec<GateWires> = (0..4).map(|i| Wire::new(start_row + i)).collect();\n\n\n\n // copy a0p4\n\n connect_cell_pair(&mut wires, (0, 5), (3, 1));\n\n\n\n // copy a0p5\n\n connect_cell_pair(&mut wires, (0, 6), (3, 2));\n", "file_path": "kimchi/src/circuits/polynomials/range_check/gate.rs", "rank": 4, "score": 253139.3178192079 }, { "content": "fn init_range_check_row<F: PrimeField>(witness: &mut [Vec<F>; COLUMNS], row: usize, limb: F) {\n\n for col in 0..COLUMNS {\n\n match &WITNESS_SHAPE[row][col] {\n\n WitnessCell::Copy(copy_cell) => {\n\n witness[col][row] = witness[copy_cell.col][copy_cell.row];\n\n }\n\n WitnessCell::Limb => {\n\n witness[col][row] = limb;\n\n }\n\n WitnessCell::Sublimb(sublimb_cell) => {\n\n witness[col][row] = limb_to_sublimb(\n\n witness[sublimb_cell.col][sublimb_cell.row], // limb cell (row, col)\n\n sublimb_cell.start, // starting bit\n\n sublimb_cell.end, // ending bit (exclusive)\n\n );\n\n }\n\n WitnessCell::Zero => {\n\n witness[col][row] = F::zero();\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "kimchi/src/circuits/polynomials/range_check/witness.rs", "rank": 5, "score": 221133.98137273116 }, { "content": "pub fn print_witness<F>(cols: &[Vec<F>; COLUMNS], start_row: usize, end_row: usize)\n\nwhere\n\n F: PrimeField,\n\n{\n\n let rows = cols[0].len();\n\n if start_row > rows || end_row > rows {\n\n panic!(\"start_row and end_row are supposed to be in [0, {rows}]\");\n\n }\n\n\n\n for row in start_row..end_row {\n\n let mut line = \"| \".to_string();\n\n for col in cols {\n\n let bigint: BigUint = col[row].into();\n\n line.push_str(&format!(\"{} | \", bigint));\n\n }\n\n println!(\"{line}\");\n\n }\n\n}\n", "file_path": "kimchi/src/tests/framework.rs", "rank": 6, "score": 220744.4286080121 }, { "content": "fn max_lookups_per_row<F>(kinds: &[Vec<JointLookupSpec<F>>]) -> usize {\n\n kinds.iter().fold(0, |acc, x| std::cmp::max(x.len(), acc))\n\n}\n\n\n\n/// Specifies whether a constraint system uses joint lookups. Used to make sure we\n\n/// squeeze the challenge `joint_combiner` when needed, and not when not needed.\n\n#[derive(Copy, Clone, Debug, Serialize, Deserialize)]\n\npub enum LookupsUsed {\n\n Single,\n\n Joint,\n\n}\n\n\n\n/// Describes the desired lookup configuration.\n\n#[derive(Clone, Serialize, Deserialize)]\n\npub struct LookupInfo<F> {\n\n /// A single lookup constraint is a vector of lookup constraints to be applied at a row.\n\n /// This is a vector of all the kinds of lookup constraints in this configuration.\n\n pub kinds: Vec<Vec<JointLookupSpec<F>>>,\n\n /// A map from the kind of gate (and whether it is the current row or next row) to the lookup\n\n /// constraint (given as an index into `kinds`) that should be applied there, if any.\n", "file_path": "kimchi/src/circuits/lookup/lookups.rs", "rank": 12, "score": 208016.19443450414 }, { "content": "/// generates a vector of `length` field elements\n\nfn rand_fields(rng: &mut impl Rng, length: u8) -> Vec<Fp> {\n\n let mut fields = vec![];\n\n for _ in 0..length {\n\n let fe = Fp::rand(rng);\n\n fields.push(fe)\n\n }\n\n fields\n\n}\n\n\n", "file_path": "oracle/export_test_vectors/src/vectors.rs", "rank": 13, "score": 202964.1666392025 }, { "content": "fn set<F>(w: &mut [Vec<F>; COLUMNS], row0: usize, var: Variable, x: F) {\n\n match var.col {\n\n Column::Witness(i) => w[i][row0 + var.row.shift()] = x,\n\n _ => panic!(\"Can only set witness columns\"),\n\n }\n\n}\n\n\n", "file_path": "kimchi/src/circuits/polynomials/varbasemul.rs", "rank": 14, "score": 192535.64336113076 }, { "content": "/// Get vector of range check circuit gate types\n\npub fn circuit_gates() -> Vec<GateType> {\n\n vec![GateType::RangeCheck0, GateType::RangeCheck1]\n\n}\n\n\n", "file_path": "kimchi/src/circuits/polynomials/range_check/gate.rs", "rank": 15, "score": 187697.00555350585 }, { "content": "pub fn i32_to_field<F: From<u64> + Neg<Output = F>>(i: i32) -> F {\n\n if i >= 0 {\n\n F::from(i as u64)\n\n } else {\n\n -F::from(-i as u64)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use ark_ec::AffineCurve;\n\n use ark_ff::{One, PrimeField};\n\n use mina_curves::pasta::pallas;\n\n\n\n // Affine curve point type\n\n pub use pallas::Affine as CurvePoint;\n\n // Base field element type\n\n pub type BaseField = <CurvePoint as AffineCurve>::BaseField;\n\n\n\n use super::*;\n", "file_path": "utils/src/field_helpers.rs", "rank": 16, "score": 178552.00576493394 }, { "content": "#[test]\n\nfn test_generic_gate() {\n\n let gates = create_circuit(0, 0);\n\n\n\n // create witness\n\n let mut witness: [Vec<Fp>; COLUMNS] = array_init(|_| vec![Fp::zero(); gates.len()]);\n\n fill_in_witness(0, &mut witness, &[]);\n\n\n\n // create and verify proof based on the witness\n\n TestFramework::default()\n\n .gates(gates)\n\n .witness(witness)\n\n .setup()\n\n .prove_and_verify();\n\n}\n\n\n", "file_path": "kimchi/src/tests/generic.rs", "rank": 17, "score": 177579.90887448582 }, { "content": "#[test]\n\nfn test_cairo_gate() {\n\n let instrs = vec![\n\n 0x400380007ffc7ffd,\n\n 0x482680017ffc8000,\n\n 1,\n\n 0x208b7fff7fff7ffe,\n\n 0x480680017fff8000,\n\n 10,\n\n 0x48307fff7fff8000,\n\n 0x48507fff7fff8000,\n\n 0x48307ffd7fff8000,\n\n 0x480a7ffd7fff8000,\n\n 0x48127ffb7fff8000,\n\n 0x1104800180018000,\n\n -11,\n\n 0x48127ff87fff8000,\n\n 0x1104800180018000,\n\n -14,\n\n 0x48127ff67fff8000,\n\n 0x1104800180018000,\n", "file_path": "kimchi/src/tests/turshi.rs", "rank": 18, "score": 177579.90887448582 }, { "content": "#[test]\n\nfn dlog_commitment_test()\n\nwhere\n\n <Fp as std::str::FromStr>::Err: std::fmt::Debug,\n\n{\n\n let rng = &mut rand::thread_rng();\n\n let mut random = rand::thread_rng();\n\n\n\n let size = 1 << 7;\n\n let srs = SRS::<Affine>::create(size);\n\n\n\n let group_map = <Affine as CommitmentCurve>::Map::setup();\n\n let sponge = DefaultFqSponge::<VestaParameters, SC>::new(oracle::pasta::fq_kimchi::params());\n\n\n\n let mut commit = Duration::new(0, 0);\n\n let mut open = Duration::new(0, 0);\n\n\n\n let prfs = (0..7)\n\n .map(|_| {\n\n let length = (0..11)\n\n .map(|_| {\n", "file_path": "poly-commitment/tests/batch_15_wires.rs", "rank": 19, "score": 174666.93206952888 }, { "content": "#[test]\n\nfn test_generic_gate_pub() {\n\n let public = vec![Fp::from(3u8); 5];\n\n let gates = create_circuit(0, public.len());\n\n\n\n // create witness\n\n let mut witness: [Vec<Fp>; COLUMNS] = array_init(|_| vec![Fp::zero(); gates.len()]);\n\n fill_in_witness(0, &mut witness, &public);\n\n\n\n // create and verify proof based on the witness\n\n TestFramework::default()\n\n .gates(gates)\n\n .witness(witness)\n\n .public_inputs(public)\n\n .setup()\n\n .prove_and_verify();\n\n}\n", "file_path": "kimchi/src/tests/generic.rs", "rank": 20, "score": 174517.78603228639 }, { "content": "fn test_vectors(test_vector_file: &str, hasher: &mut dyn Hasher<TestVector>) {\n\n // read test vectors from given file\n\n let mut path = PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"));\n\n path.push(\"../oracle/tests/test_vectors\");\n\n path.push(&test_vector_file);\n\n\n\n let file = File::open(&path).expect(\"couldn't open test vector file\");\n\n let test_vectors: TestVectors =\n\n serde_json::from_reader(file).expect(\"couldn't deserialize test vector file\");\n\n\n\n // execute test vectors\n\n for test_vector in test_vectors.test_vectors {\n\n let expected_output =\n\n Fp::from_hex(&test_vector.output).expect(\"failed to deserialize field element\");\n\n\n\n // hash & check against expect output\n\n let output = hasher.hash(&test_vector);\n\n assert_eq!(output, expected_output);\n\n }\n\n}\n\n\n\n//\n\n// Tests\n\n//\n\n\n", "file_path": "hasher/tests/hasher.rs", "rank": 22, "score": 173668.34348007233 }, { "content": "fn add_pairs_in_place<P: SWModelParameters>(pairs: &mut Vec<SWJAffine<P>>) {\n\n let len = if pairs.len() % 2 == 0 {\n\n pairs.len()\n\n } else {\n\n pairs.len() - 1\n\n };\n\n let mut denominators = pairs\n\n .chunks_exact_mut(2)\n\n .map(|p| {\n\n if p[0].x == p[1].x {\n\n if p[1].y.is_zero() {\n\n P::BaseField::one()\n\n } else {\n\n p[1].y.double()\n\n }\n\n } else {\n\n p[0].x - p[1].x\n\n }\n\n })\n\n .collect::<Vec<_>>();\n", "file_path": "poly-commitment/src/combine.rs", "rank": 23, "score": 168425.82993428837 }, { "content": "pub fn coeff<F>(i: usize) -> E<F> {\n\n E::<F>::cell(Column::Coefficient(i), CurrOrNext::Curr)\n\n}\n\n\n\n/// You can import this module like `use kimchi::circuits::expr::prologue::*` to obtain a number of handy aliases and helpers\n\npub mod prologue {\n\n pub use super::{coeff, constant, index, witness, witness_curr, witness_next, E};\n\n}\n\n\n\n#[cfg(test)]\n\npub mod test {\n\n use super::*;\n\n use crate::circuits::{\n\n constraints::ConstraintSystem, gate::CircuitGate, polynomials::generic::GenericGateSpec,\n\n wires::Wire,\n\n };\n\n use array_init::array_init;\n\n use mina_curves::pasta::fp::Fp;\n\n\n\n #[test]\n", "file_path": "kimchi/src/circuits/expr.rs", "rank": 24, "score": 167437.97685069084 }, { "content": "/// Number of constraints for a given range check circuit gate type\n\npub fn circuit_gate_constraint_count<F: FftField>(typ: GateType) -> u32 {\n\n match typ {\n\n GateType::RangeCheck0 => RangeCheck0::<F>::CONSTRAINTS,\n\n GateType::RangeCheck1 => RangeCheck1::<F>::CONSTRAINTS,\n\n _ => panic!(\"invalid gate type\"),\n\n }\n\n}\n\n\n", "file_path": "kimchi/src/circuits/polynomials/range_check/gate.rs", "rank": 25, "score": 165068.9172334248 }, { "content": "/// Handy function to quickly create an expression for a gate.\n\npub fn index<F>(g: GateType) -> E<F> {\n\n E::<F>::cell(Column::Index(g), CurrOrNext::Curr)\n\n}\n\n\n", "file_path": "kimchi/src/circuits/expr.rs", "rank": 26, "score": 164331.76241450995 }, { "content": "/// Returns the constraints related to the runtime tables.\n\npub fn constraints<F>() -> Vec<E<F>>\n\nwhere\n\n F: Field,\n\n{\n\n // This constrains that runtime_table takes values\n\n // when selector_RT is 0, and doesn't when selector_RT is 1:\n\n //\n\n // runtime_table * selector_RT = 0\n\n //\n\n let var = |x| E::cell(x, CurrOrNext::Curr);\n\n\n\n let rt_check = var(Column::LookupRuntimeTable) * var(Column::LookupRuntimeSelector);\n\n\n\n vec![rt_check]\n\n}\n", "file_path": "kimchi/src/circuits/lookup/runtime_tables.rs", "rank": 27, "score": 164300.0614805018 }, { "content": "/// Produces a `circuit.html` in the current folder.\n\npub fn visu<G>(index: &ProverIndex<G>, witness: Option<Witness<ScalarField<G>>>)\n\nwhere\n\n G: CommitmentCurve,\n\n{\n\n // serialize index\n\n let index = serde_json::to_string(index).expect(\"couldn't serialize index\");\n\n let mut data = format!(\"const index = {index};\");\n\n\n\n // serialize witness\n\n if let Some(witness) = witness {\n\n let witness = serde_json::to_string(&witness).expect(\"couldn't serialize witness\");\n\n data.push_str(&format!(\"const witness = {witness};\"));\n\n } else {\n\n data.push_str(\"const witness = null;\");\n\n }\n\n\n\n // serialize constraints\n\n let constraints = latex_constraints::<G>();\n\n let constraints = serde_json::to_string(&constraints).expect(\"couldn't serialize constraints\");\n\n data.push_str(&format!(\"const constraints = {constraints};\"));\n", "file_path": "tools/kimchi-visu/src/lib.rs", "rank": 28, "score": 164247.75267216805 }, { "content": "fn get_bit(limbs_lsb: &[u64], i: u64) -> u64 {\n\n let limb = i / 64;\n\n let j = i % 64;\n\n (limbs_lsb[limb as usize] >> j) & 1\n\n}\n\n\n\nimpl<F: PrimeField> ScalarChallenge<F> {\n\n pub fn to_field(&self, endo_coeff: &F) -> F {\n\n let length_in_bits: u64 = (64 * CHALLENGE_LENGTH_IN_LIMBS) as u64;\n\n let rep = self.0.into_repr();\n\n let r = rep.as_ref();\n\n\n\n let mut a: F = 2_u64.into();\n\n let mut b: F = 2_u64.into();\n\n\n\n let one = F::one();\n\n let neg_one = -one;\n\n\n\n for i in (0..(length_in_bits / 2)).rev() {\n\n a.double_in_place();\n", "file_path": "oracle/src/sponge.rs", "rank": 29, "score": 162903.83828216547 }, { "content": "#[test]\n\nfn chacha_prover_fake_lookup_in_same_table() {\n\n chacha_setup_bad_lookup(XOR_TABLE_ID)\n\n}\n", "file_path": "kimchi/src/tests/chacha.rs", "rank": 30, "score": 159724.1868247811 }, { "content": "/// 8-nybble sequences that are laid out as 4 nybbles per row over the two row,\n\n/// like y^x' or x+z\n\nfn chunks_over_2_rows<F>(col_offset: usize) -> Vec<E<F>> {\n\n (0..8)\n\n .map(|i| {\n\n use CurrOrNext::{Curr, Next};\n\n let r = if i < 4 { Curr } else { Next };\n\n witness(col_offset + (i % 4), r)\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "kimchi/src/circuits/polynomials/chacha.rs", "rank": 31, "score": 156523.92490320926 }, { "content": "/// Compute the powers of `x`, `x^0, ..., x^{n - 1}`\n\npub fn pows<F: Field>(x: F, n: usize) -> Vec<F> {\n\n if n == 0 {\n\n return vec![F::one()];\n\n } else if n == 1 {\n\n return vec![F::one(), x];\n\n }\n\n let mut v = vec![F::one(), x];\n\n for i in 2..n {\n\n v.push(v[i - 1] * x);\n\n }\n\n v\n\n}\n\n\n", "file_path": "kimchi/src/circuits/expr.rs", "rank": 32, "score": 154621.42999444142 }, { "content": "/// `pows(d, x)` returns a vector containing the first `d` powers of the field element `x` (from `1` to `x^(d-1)`).\n\npub fn pows<F: Field>(d: usize, x: F) -> Vec<F> {\n\n let mut acc = F::one();\n\n let mut res = vec![];\n\n for _ in 1..=d {\n\n res.push(acc);\n\n acc *= x;\n\n }\n\n res\n\n}\n\n\n", "file_path": "poly-commitment/src/commitment.rs", "rank": 33, "score": 154621.42999444142 }, { "content": "#[test]\n\n#[should_panic]\n\nfn chacha_prover_fake_lookup_in_different_table_fails() {\n\n chacha_setup_bad_lookup(XOR_TABLE_ID + 1)\n\n}\n\n\n\n// Test lookup domain collisions: if the same table ID is used, we should be able to inject and use\n\n// a value when it wasn't previously in the table.\n", "file_path": "kimchi/src/tests/chacha.rs", "rank": 34, "score": 153911.86292201452 }, { "content": "/// Constraints for the line L(x, x', y, y', z, k), where k = 4 * nybble_rotation\n\nfn line<F: Field>(nybble_rotation: usize) -> Vec<E<F>> {\n\n let y_xor_xprime_nybbles = chunks_over_2_rows(3);\n\n let x_plus_z_nybbles = chunks_over_2_rows(7);\n\n let y_nybbles = chunks_over_2_rows(11);\n\n\n\n let x_plus_z_overflow_bit = witness_next(2);\n\n\n\n let x = witness_curr(0);\n\n let xprime = witness_next(0);\n\n let y = witness_curr(1);\n\n let yprime = witness_next(1);\n\n let z = witness_curr(2);\n\n\n\n // Because the nybbles are little-endian, rotating the vector \"right\"\n\n // is equivalent to left-shifting the nybbles.\n\n let mut y_xor_xprime_rotated = y_xor_xprime_nybbles;\n\n y_xor_xprime_rotated.rotate_right(nybble_rotation);\n\n\n\n vec![\n\n // booleanity of overflow bit\n", "file_path": "kimchi/src/circuits/polynomials/chacha.rs", "rank": 35, "score": 153907.89434191663 }, { "content": "/// Create a range check witness\n\npub fn create_witness<F: PrimeField>(fe: BigUint) -> [Vec<F>; COLUMNS] {\n\n assert!(fe.bits() <= (MAX_LIMBS * LIMB_SIZE) as u64);\n\n let mut witness: [Vec<F>; COLUMNS] = array_init(|_| vec![F::zero(); 4]);\n\n append_range_check_field_element_rows(&mut witness, fe);\n\n witness\n\n}\n", "file_path": "kimchi/src/circuits/polynomials/range_check/witness.rs", "rank": 36, "score": 153369.11907866318 }, { "content": "/// Get combined constraints for a given range check circuit gate type\n\npub fn circuit_gate_constraints<F: FftField>(typ: GateType, alphas: &Alphas<F>) -> E<F> {\n\n match typ {\n\n GateType::RangeCheck0 => RangeCheck0::combined_constraints(alphas),\n\n GateType::RangeCheck1 => RangeCheck1::combined_constraints(alphas),\n\n _ => panic!(\"invalid gate type\"),\n\n }\n\n}\n\n\n", "file_path": "kimchi/src/circuits/polynomials/range_check/gate.rs", "rank": 37, "score": 150835.55862015093 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn verify<F: FftField, I: Iterator<Item = F>, G: Fn() -> I>(\n\n dummy_lookup_value: F,\n\n lookup_table: G,\n\n lookup_table_entries: usize,\n\n d1: D<F>,\n\n gates: &[CircuitGate<F>],\n\n witness: &[Vec<F>; COLUMNS],\n\n joint_combiner: &F,\n\n table_id_combiner: &F,\n\n sorted: &[Evaluations<F, D<F>>],\n\n) {\n\n sorted\n\n .iter()\n\n .for_each(|s| assert_eq!(d1.size, s.domain().size));\n\n let n = d1.size();\n\n let lookup_rows = n - ZK_ROWS - 1;\n\n\n\n // Check that the (desnakified) sorted table is\n\n // 1. Sorted\n\n // 2. Adjacent pairs agree on the final overlap point\n", "file_path": "kimchi/src/circuits/lookup/constraints.rs", "rank": 38, "score": 148375.23774088384 }, { "content": "/// Combines the constraints for the Cairo gates depending on its type\n\npub fn circuit_gate_combined_constraints<F: FftField>(typ: GateType, alphas: &Alphas<F>) -> E<F> {\n\n match typ {\n\n GateType::CairoClaim => Claim::combined_constraints(alphas),\n\n GateType::CairoInstruction => Instruction::combined_constraints(alphas),\n\n GateType::CairoFlags => Flags::combined_constraints(alphas),\n\n GateType::CairoTransition => Transition::combined_constraints(alphas),\n\n GateType::Zero => E::literal(F::zero()),\n\n _ => panic!(\"invalid gate type\"),\n\n }\n\n}\n\n\n\npub struct Claim<F>(PhantomData<F>);\n\n\n\nimpl<F> Argument<F> for Claim<F>\n\nwhere\n\n F: FftField,\n\n{\n\n const ARGUMENT_TYPE: ArgumentType = ArgumentType::Gate(GateType::CairoClaim);\n\n const CONSTRAINTS: u32 = 5;\n\n\n", "file_path": "kimchi/src/circuits/polynomials/turshi.rs", "rank": 39, "score": 145715.30448968764 }, { "content": "/// Specifies the lookup constraints as expressions.\n\npub fn constraints<F: FftField>(configuration: &LookupConfiguration<F>, d1: D<F>) -> Vec<E<F>> {\n\n // Something important to keep in mind is that the last 2 rows of\n\n // all columns will have random values in them to maintain zero-knowledge.\n\n //\n\n // Another important thing to note is that there are no lookups permitted\n\n // in the 3rd to last row.\n\n //\n\n // This is because computing the lookup-product requires\n\n // num_lookup_rows + 1\n\n // rows, so we need to have\n\n // num_lookup_rows + 1 = n - 2 (the last 2 being reserved for the zero-knowledge random\n\n // values) and thus\n\n //\n\n // num_lookup_rows = n - 3\n\n let lookup_info = LookupInfo::<F>::create();\n\n\n\n let column = |col: Column| E::cell(col, Curr);\n\n\n\n // gamma * (beta + 1)\n\n let gammabeta1 =\n", "file_path": "kimchi/src/circuits/lookup/constraints.rs", "rank": 40, "score": 144000.08644156874 }, { "content": "/// Same as [witness] but for the next row.\n\npub fn witness_next<F>(i: usize) -> E<F> {\n\n witness(i, CurrOrNext::Next)\n\n}\n\n\n", "file_path": "kimchi/src/circuits/expr.rs", "rank": 41, "score": 141694.53928617862 }, { "content": "/// Same as [witness] but for the current row.\n\npub fn witness_curr<F>(i: usize) -> E<F> {\n\n witness(i, CurrOrNext::Curr)\n\n}\n\n\n", "file_path": "kimchi/src/circuits/expr.rs", "rank": 42, "score": 141694.53928617862 }, { "content": "/// Returns the lookup table associated to a [GateLookupTable].\n\npub fn get_table<F: FftField>(table_name: GateLookupTable) -> LookupTable<F> {\n\n match table_name {\n\n GateLookupTable::Xor => xor::xor_table(),\n\n }\n\n}\n\n\n", "file_path": "kimchi/src/circuits/lookup/tables/mod.rs", "rank": 43, "score": 138811.92365088928 }, { "content": "#[test]\n\nfn poseidon_test_vectors_kimchi() {\n\n fn hash(input: &[Fp]) -> Fp {\n\n let mut hash =\n\n Poseidon::<Fp, PlonkSpongeConstantsKimchi>::new(SpongeParametersKimchi::params());\n\n hash.absorb(input);\n\n hash.squeeze()\n\n }\n\n test_vectors(\"kimchi.json\", hash);\n\n}\n", "file_path": "oracle/tests/poseidon_tests.rs", "rank": 44, "score": 136465.44079464415 }, { "content": "#[test]\n\nfn poseidon_test_vectors_legacy() {\n\n fn hash(input: &[Fp]) -> Fp {\n\n let mut hash =\n\n Poseidon::<Fp, PlonkSpongeConstantsLegacy>::new(SpongeParametersLegacy::params());\n\n hash.absorb(input);\n\n hash.squeeze()\n\n }\n\n test_vectors(\"legacy.json\", hash);\n\n}\n\n\n", "file_path": "oracle/tests/poseidon_tests.rs", "rank": 45, "score": 136465.44079464415 }, { "content": "#[test]\n\nfn sign_delegation_test_2() {\n\n assert_sign_verify_tx!(\n\n /* Transaction type */ TransactionType::DelegationTx,\n\n /* sender secret key */ \"20f84123a26e58dd32b0ea3c80381f35cd01bc22a20346cc65b0a67ae48532ba\",\n\n /* source address */ \"B62qkiT4kgCawkSEF84ga5kP9QnhmTJEYzcfgGuk6okAJtSBfVcjm1M\",\n\n /* receiver address */ \"B62qnzbXmRNo9q32n4SNu2mpB8e7FYYLH8NmaX6oFCBYjjQ8SbD7uzV\",\n\n /* amount */ 0,\n\n /* fee */ 2000000000,\n\n /* nonce */ 0,\n\n /* valid until */ 4294967295,\n\n /* memo */ \"\",\n\n /* testnet signature */ \"07e9f88fc671ed06781f9edb233fdbdee20fa32303015e795747ad9e43fcb47b3ce34e27e31f7c667756403df3eb4ce670d9175dd0ae8490b273485b71c56066\",\n\n /* mainnet signature */ \"2406ab43f8201bd32bdd81b361fdb7871979c0eec4e3b7a91edf87473963c8a4069f4811ebc5a0e85cbb4951bffe93b638e230ce5a250cb08d2c250113a1967c\"\n\n );\n\n}\n\n\n", "file_path": "signer/tests/signer.rs", "rank": 46, "score": 135150.77374441404 }, { "content": "#[test]\n\nfn signer_test_raw() {\n\n let kp = Keypair::from_hex(\"164244176fddb5d769b7de2027469d027ad428fadcc0c02396e6280142efb718\")\n\n .expect(\"failed to create keypair\");\n\n let tx = Transaction::new_payment(\n\n kp.public,\n\n PubKey::from_address(\"B62qicipYxyEHu7QjUqS7QvBipTs5CzgkYZZZkPoKVYBu6tnDUcE9Zt\")\n\n .expect(\"invalid address\"),\n\n 1729000000000,\n\n 2000000000,\n\n 16,\n\n )\n\n .set_valid_until(271828)\n\n .set_memo_str(\"Hello Mina!\");\n\n\n\n assert_eq!(tx.valid_until, 271828);\n\n assert_eq!(\n\n tx.memo,\n\n [\n\n 0x01, 0x0b, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x4d, 0x69, 0x6e, 0x61, 0x21, 0x00,\n\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n", "file_path": "signer/tests/signer.rs", "rank": 47, "score": 135150.77374441404 }, { "content": "#[test]\n\nfn sign_delegation_test_3() {\n\n assert_sign_verify_tx!(\n\n /* Transaction type */ TransactionType::DelegationTx,\n\n /* sender secret key */ \"3414fc16e86e6ac272fda03cf8dcb4d7d47af91b4b726494dab43bf773ce1779\",\n\n /* source address */ \"B62qoG5Yk4iVxpyczUrBNpwtx2xunhL48dydN53A2VjoRwF8NUTbVr4\",\n\n /* receiver address */ \"B62qkiT4kgCawkSEF84ga5kP9QnhmTJEYzcfgGuk6okAJtSBfVcjm1M\",\n\n /* amount */ 0,\n\n /* fee */ 42000000000,\n\n /* nonce */ 1,\n\n /* valid until */ 4294967295,\n\n /* memo */ \"more delegates, more fun........\",\n\n /* testnet signature */ \"1ff9f77fed4711e0ebe2a7a46a7b1988d1b62a850774bf299ec71a24d5ebfdd81d04a570e4811efe867adefe3491ba8b210f24bd0ec8577df72212d61b569b15\",\n\n /* mainnet signature */ \"36a80d0421b9c0cbfa08ea95b27f401df108b30213ae138f1f5978ffc59606cf2b64758db9d26bd9c5b908423338f7445c8f0a07520f2154bbb62926aa0cb8fa\"\n\n );\n\n}\n\n\n", "file_path": "signer/tests/signer.rs", "rank": 48, "score": 135150.77374441404 }, { "content": "#[test]\n\nfn ec_test() {\n\n let num_doubles = 100;\n\n let num_additions = 100;\n\n let num_infs = 100;\n\n\n\n let mut gates = vec![];\n\n\n\n for row in 0..(num_doubles + num_additions + num_infs) {\n\n gates.push(CircuitGate {\n\n typ: GateType::CompleteAdd,\n\n wires: Wire::new(row),\n\n coeffs: vec![],\n\n });\n\n }\n\n\n\n let mut witness: [Vec<F>; COLUMNS] = array_init(|_| vec![]);\n\n\n\n let rng = &mut StdRng::from_seed([0; 32]);\n\n\n\n let ps = {\n", "file_path": "kimchi/src/tests/ec.rs", "rank": 49, "score": 135150.77374441404 }, { "content": "#[test]\n\nfn endomul_test() {\n\n let bits_per_chunk = 4;\n\n let num_bits = 128;\n\n let chunks = num_bits / bits_per_chunk;\n\n\n\n let num_scalars = 100;\n\n\n\n assert_eq!(num_bits % bits_per_chunk, 0);\n\n\n\n let mut gates = vec![];\n\n\n\n let rows_per_scalar = 1 + chunks;\n\n\n\n for s in 0..num_scalars {\n\n for i in 0..chunks {\n\n let row = rows_per_scalar * s + i;\n\n gates.push(CircuitGate {\n\n typ: GateType::EndoMul,\n\n wires: Wire::new(row),\n\n coeffs: vec![],\n", "file_path": "kimchi/src/tests/endomul.rs", "rank": 50, "score": 135150.77374441404 }, { "content": "#[test]\n\nfn signer_zero_test() {\n\n let kp = Keypair::from_hex(\"164244176fddb5d769b7de2027469d027ad428fadcc0c02396e6280142efb718\")\n\n .expect(\"failed to create keypair\");\n\n let tx = Transaction::new_payment(\n\n kp.public,\n\n PubKey::from_address(\"B62qicipYxyEHu7QjUqS7QvBipTs5CzgkYZZZkPoKVYBu6tnDUcE9Zt\")\n\n .expect(\"invalid address\"),\n\n 1729000000000,\n\n 2000000000,\n\n 16,\n\n );\n\n\n\n let mut ctx = mina_signer::create_legacy(NetworkId::TESTNET);\n\n let sig = ctx.sign(&kp, &tx);\n\n\n\n assert_eq!(ctx.verify(&sig, &kp.public, &tx), true);\n\n\n\n // Zero some things\n\n let mut sig2 = sig;\n\n sig2.rx = BaseField::zero();\n\n assert_eq!(ctx.verify(&sig2, &kp.public, &tx), false);\n\n let mut sig3 = sig;\n\n sig3.s = ScalarField::zero();\n\n assert_eq!(ctx.verify(&sig3, &kp.public, &tx), false);\n\n sig3.rx = BaseField::zero();\n\n assert_eq!(ctx.verify(&sig3, &kp.public, &tx), false);\n\n}\n\n\n", "file_path": "signer/tests/signer.rs", "rank": 51, "score": 135150.77374441404 }, { "content": "#[test]\n\nfn sign_payment_test_4() {\n\n assert_sign_verify_tx!(\n\n /* Transaction type */ TransactionType::PaymentTx,\n\n /* sender secret key */ \"1dee867358d4000f1dafa5978341fb515f89eeddbe450bd57df091f1e63d4444\",\n\n /* source address */ \"B62qoqiAgERjCjXhofXiD7cMLJSKD8hE8ZtMh4jX5MPNgKB4CFxxm1N\",\n\n /* receiver address */ \"B62qnzbXmRNo9q32n4SNu2mpB8e7FYYLH8NmaX6oFCBYjjQ8SbD7uzV\",\n\n /* amount */ 0,\n\n /* fee */ 2000000000,\n\n /* nonce */ 0,\n\n /* valid until */ 1982,\n\n /* memo */ \"\",\n\n /* testnet signature */ \"25bb730a25ce7180b1e5766ff8cc67452631ee46e2d255bccab8662e5f1f0c850a4bb90b3e7399e935fff7f1a06195c6ef89891c0260331b9f381a13e5507a4c\",\n\n /* mainnet signature */ \"058ed7fb4e17d9d400acca06fe20ca8efca2af4ac9a3ed279911b0bf93c45eea0e8961519b703c2fd0e431061d8997cac4a7574e622c0675227d27ce2ff357d9\"\n\n );\n\n}\n\n\n", "file_path": "signer/tests/signer.rs", "rank": 52, "score": 135150.77374441404 }, { "content": "#[test]\n\nfn sign_payment_test_2() {\n\n assert_sign_verify_tx!(\n\n /* Transaction type */ TransactionType::PaymentTx,\n\n /* sender secret key */ \"3414fc16e86e6ac272fda03cf8dcb4d7d47af91b4b726494dab43bf773ce1779\",\n\n /* source address */ \"B62qoG5Yk4iVxpyczUrBNpwtx2xunhL48dydN53A2VjoRwF8NUTbVr4\",\n\n /* receiver address */ \"B62qrKG4Z8hnzZqp1AL8WsQhQYah3quN1qUj3SyfJA8Lw135qWWg1mi\",\n\n /* amount */ 314159265359,\n\n /* fee */ 1618033988,\n\n /* nonce */ 0,\n\n /* valid until */ 4294967295,\n\n /* memo */ \"\",\n\n /* testnet signature */ \"23a9e2375dd3d0cd061e05c33361e0ba270bf689c4945262abdcc81d7083d8c311ae46b8bebfc98c584e2fb54566851919b58cf0917a256d2c1113daa1ccb27f\",\n\n /* mainnet signature */ \"204eb1a37e56d0255921edd5a7903c210730b289a622d45ed63a52d9e3e461d13dfcf301da98e218563893e6b30fa327600c5ff0788108652a06b970823a4124\"\n\n );\n\n}\n\n\n", "file_path": "signer/tests/signer.rs", "rank": 53, "score": 135150.77374441404 }, { "content": "#[test]\n\nfn test_recursion() {\n\n let gates = create_circuit(0, 0);\n\n\n\n // create witness\n\n let mut witness: [Vec<Fp>; COLUMNS] = array_init(|_| vec![Fp::zero(); gates.len()]);\n\n fill_in_witness(0, &mut witness, &[]);\n\n\n\n // setup\n\n let test_runner = TestFramework::default()\n\n .gates(gates)\n\n .witness(witness)\n\n .setup();\n\n\n\n // previous opening for recursion\n\n let index = test_runner.prover_index();\n\n let rng = &mut StdRng::from_seed([0u8; 32]);\n\n let prev_challenges = {\n\n let k = math::ceil_log2(index.srs.g.len());\n\n let chals: Vec<_> = (0..k).map(|_| Fp::rand(rng)).collect();\n\n let comm = {\n", "file_path": "kimchi/src/tests/recursion.rs", "rank": 54, "score": 135150.77374441404 }, { "content": "#[test]\n\nfn sign_payment_test_3() {\n\n assert_sign_verify_tx!(\n\n /* Transaction type */ TransactionType::PaymentTx,\n\n /* sender secret key */ \"3414fc16e86e6ac272fda03cf8dcb4d7d47af91b4b726494dab43bf773ce1779\",\n\n /* source address */ \"B62qoG5Yk4iVxpyczUrBNpwtx2xunhL48dydN53A2VjoRwF8NUTbVr4\",\n\n /* receiver address */ \"B62qoqiAgERjCjXhofXiD7cMLJSKD8hE8ZtMh4jX5MPNgKB4CFxxm1N\",\n\n /* amount */ 271828182845904,\n\n /* fee */ 100000,\n\n /* nonce */ 5687,\n\n /* valid until */ 4294967295,\n\n /* memo */ \"01234567890123456789012345678901\",\n\n /* testnet signature */ \"2b4d0bffcb57981d11a93c05b17672b7be700d42af8496e1ba344394da5d0b0b0432c1e8a77ee1bd4b8ef6449297f7ed4956b81df95bdc6ac95d128984f77205\",\n\n /* mainnet signature */ \"076d8ebca8ccbfd9c8297a768f756ff9d08c049e585c12c636d57ffcee7f6b3b1bd4b9bd42cc2cbee34b329adbfc5127fe5a2ceea45b7f55a1048b7f1a9f7559\"\n\n );\n\n}\n\n\n", "file_path": "signer/tests/signer.rs", "rank": 55, "score": 135150.77374441404 }, { "content": "#[test]\n\nfn sign_delegation_test_4() {\n\n assert_sign_verify_tx!(\n\n /* Transaction type */ TransactionType::DelegationTx,\n\n /* sender secret key */ \"336eb4a19b3d8905824b0f2254fb495573be302c17582748bf7e101965aa4774\",\n\n /* source address */ \"B62qrKG4Z8hnzZqp1AL8WsQhQYah3quN1qUj3SyfJA8Lw135qWWg1mi\",\n\n /* receiver address */ \"B62qicipYxyEHu7QjUqS7QvBipTs5CzgkYZZZkPoKVYBu6tnDUcE9Zt\",\n\n /* amount */ 0,\n\n /* fee */ 1202056900,\n\n /* nonce */ 0,\n\n /* valid until */ 577216,\n\n /* memo */ \"\",\n\n /* testnet signature */ \"26ca6b95dee29d956b813afa642a6a62cd89b1929320ed6b099fd191a217b08d2c9a54ba1c95e5000b44b93cfbd3b625e20e95636f1929311473c10858a27f09\",\n\n /* mainnet signature */ \"093f9ef0e4e051279da0a3ded85553847590ab739ee1bfd59e5bb30f98ed8a001a7a60d8506e2572164b7a525617a09f17e1756ac37555b72e01b90f37271595\"\n\n );\n\n}\n", "file_path": "signer/tests/signer.rs", "rank": 56, "score": 135150.77374441404 }, { "content": "#[test]\n\nfn test_poseidon() {\n\n let max_size = 1 << math::ceil_log2(N_LOWER_BOUND);\n\n println!(\"max_size = {}\", max_size);\n\n println!(\"rounds per hash = {}\", ROUNDS_PER_HASH);\n\n println!(\"rounds per row = {}\", ROUNDS_PER_ROW);\n\n println!(\" number of rows for poseidon ={}\", POS_ROWS_PER_HASH);\n\n assert_eq!(ROUNDS_PER_HASH % ROUNDS_PER_ROW, 0);\n\n\n\n let round_constants = oracle::pasta::fp_kimchi::params().round_constants;\n\n\n\n // we keep track of an absolute row, and relative row within a gadget\n\n let mut abs_row = 0;\n\n\n\n // circuit gates\n\n let mut gates: Vec<CircuitGate<Fp>> = Vec::with_capacity(max_size);\n\n\n\n // custom constraints for Poseidon hash function permutation\n\n // ROUNDS_FULL full rounds constraint gates\n\n for _ in 0..NUM_POS {\n\n let first_wire = Wire::new(abs_row);\n", "file_path": "kimchi/src/tests/poseidon.rs", "rank": 57, "score": 135150.77374441404 }, { "content": "#[test]\n\nfn sign_payment_test_1() {\n\n assert_sign_verify_tx!(\n\n /* Transaction type */ TransactionType::PaymentTx,\n\n /* sender secret key */ \"164244176fddb5d769b7de2027469d027ad428fadcc0c02396e6280142efb718\",\n\n /* source address */ \"B62qnzbXmRNo9q32n4SNu2mpB8e7FYYLH8NmaX6oFCBYjjQ8SbD7uzV\",\n\n /* receiver address */ \"B62qicipYxyEHu7QjUqS7QvBipTs5CzgkYZZZkPoKVYBu6tnDUcE9Zt\",\n\n /* amount */ 1729000000000,\n\n /* fee */ 2000000000,\n\n /* nonce */ 16,\n\n /* valid until */ 271828,\n\n /* memo */ \"Hello Mina!\",\n\n /* testntet signature */ \"11a36a8dfe5b857b95a2a7b7b17c62c3ea33411ae6f4eb3a907064aecae353c60794f1d0288322fe3f8bb69d6fabd4fd7c15f8d09f8783b2f087a80407e299af\",\n\n /* mainnet signature */ \"124c592178ed380cdffb11a9f8e1521bf940e39c13f37ba4c55bb4454ea69fba3c3595a55b06dac86261bb8ab97126bf3f7fff70270300cb97ff41401a5ef789\"\n\n );\n\n}\n\n\n", "file_path": "signer/tests/signer.rs", "rank": 58, "score": 135150.77374441404 }, { "content": "#[test]\n\nfn sign_delegation_test_1() {\n\n assert_sign_verify_tx!(\n\n /* Transaction type */ TransactionType::DelegationTx,\n\n /* sender secret key */ \"164244176fddb5d769b7de2027469d027ad428fadcc0c02396e6280142efb718\",\n\n /* source address */ \"B62qnzbXmRNo9q32n4SNu2mpB8e7FYYLH8NmaX6oFCBYjjQ8SbD7uzV\",\n\n /* receiver address */ \"B62qicipYxyEHu7QjUqS7QvBipTs5CzgkYZZZkPoKVYBu6tnDUcE9Zt\",\n\n /* amount */ 0,\n\n /* fee */ 2000000000,\n\n /* nonce */ 16,\n\n /* valid until */ 1337,\n\n /* memo */ \"Delewho?\",\n\n /* testnet signature */ \"30797d7d0426e54ff195d1f94dc412300f900cc9e84990603939a77b3a4d2fc11ebab12857b47c481c182abe147279732549f0fd49e68d5541f825e9d1e6fa04\",\n\n /* mainnet signature */ \"0904e9521a95334e3f6757cb0007ec8af3322421954255e8d263d0616910b04d213344f8ec020a4b873747d1cbb07296510315a2ec76e52150a4c765520d387f\"\n\n );\n\n}\n\n\n", "file_path": "signer/tests/signer.rs", "rank": 59, "score": 135150.77374441404 }, { "content": "/// Tests polynomial commitments, batched openings and\n\n/// verification of a batch of batched opening proofs of polynomial commitments\n\nfn test_commit()\n\nwhere\n\n <Fp as std::str::FromStr>::Err: std::fmt::Debug,\n\n{\n\n // setup\n\n let mut rng = rand::thread_rng();\n\n let group_map = <Affine as CommitmentCurve>::Map::setup();\n\n let fq_sponge = DefaultFqSponge::<VestaParameters, SC>::new(oracle::pasta::fq_kimchi::params());\n\n\n\n // create an SRS optimized for polynomials of degree 2^7 - 1\n\n let srs = SRS::<Affine>::create(1 << 7);\n\n\n\n // TODO: move to bench\n\n let mut time_commit = Duration::new(0, 0);\n\n let mut time_open = Duration::new(0, 0);\n\n\n\n // create 7 distinct \"aggregated evaluation proofs\"\n\n let mut proofs = vec![];\n\n for _ in 0..7 {\n\n // generate 7 random evaluation points\n", "file_path": "poly-commitment/tests/commitment.rs", "rank": 60, "score": 135150.27939996796 }, { "content": "fn batch_endo_in_place<P: SWModelParameters>(endo_coeff: P::BaseField, ps: &mut [SWJAffine<P>]) {\n\n ps.par_iter_mut().for_each(|p| p.x *= endo_coeff);\n\n}\n\n\n", "file_path": "poly-commitment/src/combine.rs", "rank": 61, "score": 134820.28909272375 }, { "content": "/// Helper function to quickly create an expression for a witness.\n\npub fn witness<F>(i: usize, row: CurrOrNext) -> E<F> {\n\n E::<F>::cell(Column::Witness(i), row)\n\n}\n\n\n", "file_path": "kimchi/src/circuits/expr.rs", "rank": 62, "score": 134001.44823636627 }, { "content": "///\n\npub fn latex_constraints<G>() -> HashMap<&'static str, Vec<Vec<String>>>\n\nwhere\n\n G: CommitmentCurve,\n\n{\n\n let mut map = HashMap::new();\n\n map.insert(\"Poseidon\", Poseidon::<ScalarField<G>>::latex());\n\n map.insert(\"CompleteAdd\", CompleteAdd::<ScalarField<G>>::latex());\n\n map.insert(\"VarBaseMul\", VarbaseMul::<ScalarField<G>>::latex());\n\n map.insert(\"EndoMul\", EndosclMul::<ScalarField<G>>::latex());\n\n map.insert(\"EndoMulScalar\", EndomulScalar::<ScalarField<G>>::latex());\n\n map.insert(\"ChaCha0\", ChaCha0::<ScalarField<G>>::latex());\n\n map.insert(\"ChaCha1\", ChaCha1::<ScalarField<G>>::latex());\n\n map.insert(\"ChaCha2\", ChaCha2::<ScalarField<G>>::latex());\n\n map.insert(\"ChaChaFinal\", ChaChaFinal::<ScalarField<G>>::latex());\n\n map\n\n}\n\n\n", "file_path": "tools/kimchi-visu/src/lib.rs", "rank": 63, "score": 133330.54006112664 }, { "content": "#[test]\n\nfn varbase_mul_test() {\n\n let num_bits = F::size_in_bits();\n\n let chunks = num_bits / 5;\n\n\n\n let num_scalars = 10;\n\n let rows_per_scalar = 2 * (255 / 5);\n\n\n\n assert_eq!(num_bits % 5, 0);\n\n\n\n let mut gates = vec![];\n\n\n\n for i in 0..(chunks * num_scalars) {\n\n let row = 2 * i;\n\n gates.push(CircuitGate {\n\n typ: GateType::VarBaseMul,\n\n wires: Wire::new(row),\n\n coeffs: vec![],\n\n });\n\n gates.push(CircuitGate {\n\n typ: GateType::Zero,\n", "file_path": "kimchi/src/tests/varbasemul.rs", "rank": 64, "score": 133105.77914771397 }, { "content": "#[test]\n\nfn hasher_test_vectors_kimchi() {\n\n let mut hasher = mina_hasher::create_kimchi::<TestVector>(());\n\n test_vectors(\"kimchi.json\", &mut hasher);\n\n}\n", "file_path": "hasher/tests/hasher.rs", "rank": 65, "score": 133105.77914771397 }, { "content": "#[test]\n\nfn test_group_map_on_curve() {\n\n let params = BWParameters::<G>::setup();\n\n let t: Fq = rand::random();\n\n let (x, y) = BWParameters::<G>::to_group(&params, t);\n\n let g = Affine::new(x, y, false);\n\n assert!(g.is_on_curve());\n\n}\n\n\n", "file_path": "groupmap/tests/groupmap.rs", "rank": 66, "score": 133105.77914771397 }, { "content": "#[test]\n\nfn test_fp() {\n\n let mut rng = test_rng();\n\n let a: Fp = rng.gen();\n\n let b: Fp = rng.gen();\n\n field_test(a, b);\n\n sqrt_field_test(a);\n\n primefield_test::<Fp>();\n\n}\n\n\n", "file_path": "curves/src/pasta/fields/tests.rs", "rank": 67, "score": 133105.77914771397 }, { "content": "#[test]\n\nfn test_fq() {\n\n let mut rng = test_rng();\n\n let a: Fq = rng.gen();\n\n let b: Fq = rng.gen();\n\n field_test(a, b);\n\n sqrt_field_test(a);\n\n primefield_test::<Fq>();\n\n}\n", "file_path": "curves/src/pasta/fields/tests.rs", "rank": 68, "score": 133105.77914771397 }, { "content": "#[test]\n\nfn test_cairo_should_fail() {\n\n let instrs = vec![0x480680017fff8000, 10, 0x208b7fff7fff7ffe]\n\n .iter()\n\n .map(|&i: &i64| F::from(i))\n\n .collect();\n\n let mut mem = CairoMemory::<F>::new(instrs);\n\n mem.write(F::from(4u32), F::from(7u32)); //beginning of output\n\n mem.write(F::from(5u32), F::from(7u32)); //end of output\n\n let prog = CairoProgram::new(&mut mem, 1);\n\n\n\n // Create the Cairo circuit\n\n let ninstr = prog.trace().len();\n\n let inirow = 0;\n\n let (circuit, _) = CircuitGate::<F>::create_cairo_gadget(inirow, ninstr);\n\n\n\n let mut witness = cairo_witness(&prog);\n\n // break a witness\n\n witness[0][0] += F::from(1u32);\n\n let res_ensure = ensure_cairo_gate(&circuit[0], 0, &witness);\n\n assert_eq!(Err(\"wrong initial pc\".to_string()), res_ensure);\n\n}\n\n\n", "file_path": "kimchi/src/tests/turshi.rs", "rank": 69, "score": 133105.77914771397 }, { "content": "#[test]\n\nfn hasher_test_vectors_legacy() {\n\n let mut hasher = mina_hasher::create_legacy::<TestVector>(());\n\n test_vectors(\"legacy.json\", &mut hasher);\n\n}\n\n\n", "file_path": "hasher/tests/hasher.rs", "rank": 70, "score": 133105.77914771397 }, { "content": "fn limb_to_sublimb<F: PrimeField>(fe: F, start: usize, end: usize) -> F {\n\n F::from_bits(&fe.to_bits()[start..end]).expect(\"failed to deserialize field bits\")\n\n}\n\n\n", "file_path": "kimchi/src/circuits/polynomials/range_check/witness.rs", "rank": 71, "score": 132315.52805685007 }, { "content": "pub fn bench_proof_creation(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"Proof creation\");\n\n group.sample_size(10).sampling_mode(SamplingMode::Flat); // for slow benchmarks\n\n\n\n let ctx = BenchmarkCtx::new(1 << 14);\n\n group.bench_function(\"proof creation (2^15)\", |b| {\n\n b.iter(|| black_box(ctx.create_proof()))\n\n });\n\n}\n\n\n", "file_path": "kimchi/benches/proof_criterion.rs", "rank": 72, "score": 132287.94506976908 }, { "content": "pub fn bench_proof_verification(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"Proof verification\");\n\n group.sample_size(10).sampling_mode(SamplingMode::Flat); // for slow benchmarks\n\n\n\n let ctx = BenchmarkCtx::new(1 << 4); // since verification time is unrelated to the circuit size, we just reduce the time the proof takes\n\n let proof = ctx.create_proof();\n\n group.bench_function(\"proof verification\", |b| {\n\n b.iter(|| ctx.batch_verification(black_box(vec![proof.clone()])))\n\n });\n\n}\n\ncriterion_group!(benches, bench_proof_creation, bench_proof_verification);\n\ncriterion_main!(benches);\n", "file_path": "kimchi/benches/proof_criterion.rs", "rank": 73, "score": 132287.94506976908 }, { "content": "#[test]\n\nfn test_pallas_generator() {\n\n let generator = pallas::Affine::prime_subgroup_generator();\n\n assert!(generator.is_on_curve());\n\n assert!(generator.is_in_correct_subgroup_assuming_on_curve());\n\n}\n", "file_path": "curves/src/pasta/curves/tests.rs", "rank": 74, "score": 131145.85379824726 }, { "content": "#[test]\n\nfn test_batch_group_map_on_curve() {\n\n let params = BWParameters::<G>::setup();\n\n let ts: Vec<Fq> = (0..1000).map(|_| rand::random()).collect();\n\n for xs in BWParameters::<G>::batch_to_group_x(&params, ts).iter() {\n\n let (x, y) = first_xy(xs);\n\n let g = Affine::new(x, y, false);\n\n assert!(g.is_on_curve());\n\n }\n\n}\n", "file_path": "groupmap/tests/groupmap.rs", "rank": 75, "score": 131145.85379824726 }, { "content": "#[test]\n\nfn endomul_scalar_test() {\n\n let bits_per_row = 2 * 8;\n\n let num_bits = 128;\n\n let rows_per_scalar = num_bits / bits_per_row;\n\n\n\n let num_scalars = 100;\n\n\n\n assert_eq!(num_bits % bits_per_row, 0);\n\n\n\n let mut gates = vec![];\n\n\n\n for s in 0..num_scalars {\n\n for i in 0..rows_per_scalar {\n\n let row = rows_per_scalar * s + i;\n\n gates.push(CircuitGate {\n\n typ: GateType::EndoMulScalar,\n\n wires: Wire::new(row),\n\n coeffs: vec![],\n\n });\n\n }\n", "file_path": "kimchi/src/tests/endomul_scalar.rs", "rank": 76, "score": 131145.85379824726 }, { "content": "fn into_address(x: BaseField, is_odd: bool) -> String {\n\n let mut raw: Vec<u8> = vec![\n\n 0xcb, // version for base58 check\n\n 0x01, // non_zero_curve_point version\n\n 0x01, // compressed_poly version\n\n ];\n\n\n\n // pub key x-coordinate\n\n raw.extend(x.to_bytes());\n\n\n\n // pub key y-coordinate parity\n\n raw.push(is_odd as u8);\n\n\n\n // 4-byte checksum\n\n let hash = Sha256::digest(&Sha256::digest(&raw[..])[..]);\n\n raw.extend(&hash[..4]);\n\n\n\n // The raw buffer is MINA_ADDRESS_RAW_LEN (= 40) bytes in length\n\n bs58::encode(raw).into_string()\n\n}\n", "file_path": "signer/src/pubkey.rs", "rank": 77, "score": 130946.94566285315 }, { "content": "fn first_xy(xs: &[Fq; 3]) -> (Fq, Fq) {\n\n for x in xs.iter() {\n\n match groupmap::get_y::<G>(*x) {\n\n Some(y) => return (*x, y),\n\n None => (),\n\n }\n\n }\n\n panic!(\"get_xy\")\n\n}\n\n\n", "file_path": "groupmap/tests/groupmap.rs", "rank": 78, "score": 130414.53000374981 }, { "content": "#[test]\n\npub fn test_serialization() {\n\n let public = vec![Fp::from(3u8); 5];\n\n let gates = create_circuit(0, public.len());\n\n\n\n // create witness\n\n let mut witness: [Vec<Fp>; COLUMNS] = array_init(|_| vec![Fp::zero(); gates.len()]);\n\n fill_in_witness(0, &mut witness, &public);\n\n\n\n let index = new_index_for_test(gates, public.len());\n\n let verifier_index = index.verifier_index();\n\n\n\n let verifier_index_serialize =\n\n serde_json::to_string(&verifier_index).expect(\"couldn't serialize index\");\n\n\n\n // verify the circuit satisfiability by the computed witness\n\n index.cs.verify(&witness, &public).unwrap();\n\n\n\n // add the proof to the batch\n\n let group_map = <Affine as CommitmentCurve>::Map::setup();\n\n let proof =\n", "file_path": "kimchi/src/tests/serialization.rs", "rank": 79, "score": 129920.30561208885 }, { "content": "#[test]\n\nfn test_pallas_projective_curve() {\n\n curve_tests::<pallas::Projective>();\n\n\n\n sw_tests::<pallas::PallasParameters>();\n\n}\n\n\n", "file_path": "curves/src/pasta/curves/tests.rs", "rank": 80, "score": 129265.5630807863 }, { "content": "#[test]\n\nfn test_pallas_projective_group() {\n\n let mut rng = test_rng();\n\n let a: pallas::Projective = rng.gen();\n\n let b: pallas::Projective = rng.gen();\n\n group_test(a, b);\n\n}\n\n\n", "file_path": "curves/src/pasta/curves/tests.rs", "rank": 81, "score": 129265.5630807863 }, { "content": "fn pack<B: BigInteger>(limbs_lsb: &[u64]) -> B {\n\n let mut res: B = 0.into();\n\n for &x in limbs_lsb.iter().rev() {\n\n res.muln(64);\n\n res.add_nocarry(&x.into());\n\n }\n\n res\n\n}\n\n\n\nimpl<Fr: PrimeField, SC: SpongeConstants> DefaultFrSponge<Fr, SC> {\n\n pub fn squeeze(&mut self, num_limbs: usize) -> Fr {\n\n if self.last_squeezed.len() >= num_limbs {\n\n let last_squeezed = self.last_squeezed.clone();\n\n let (limbs, remaining) = last_squeezed.split_at(num_limbs);\n\n self.last_squeezed = remaining.to_vec();\n\n Fr::from_repr(pack::<Fr::BigInt>(limbs))\n\n .expect(\"internal representation was not a valid field element\")\n\n } else {\n\n let x = self.sponge.squeeze().into_repr();\n\n self.last_squeezed\n", "file_path": "oracle/src/sponge.rs", "rank": 82, "score": 127052.96788941062 }, { "content": "#[test]\n\nfn transaction_domain() {\n\n assert_eq!(\n\n Transaction::domain_string(NetworkId::MAINNET).expect(\"missing domain string\"),\n\n \"MinaSignatureMainnet\"\n\n );\n\n assert_eq!(\n\n Transaction::domain_string(NetworkId::TESTNET).expect(\"missing domain string\"),\n\n \"CodaSignature\"\n\n );\n\n}\n\n\n", "file_path": "signer/tests/transaction.rs", "rank": 83, "score": 126572.33223006762 }, { "content": "#[test]\n\nfn transaction_memo() {\n\n let kp = Keypair::from_hex(\"164244176fddb5d769b7de2027469d027ad428fadcc0c02396e6280142efb718\")\n\n .expect(\"failed to create keypair\");\n\n\n\n let tx = Transaction::new_payment(kp.public, kp.public, 0, 0, 0);\n\n assert_eq!(\n\n tx.memo,\n\n [\n\n 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\n 0, 0, 0, 0, 0\n\n ]\n\n );\n\n\n\n // Memo length < max memo length\n\n let tx = tx.set_memo([\n\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\n 0, 0, 0,\n\n ]);\n\n assert_eq!(\n\n tx.memo,\n", "file_path": "signer/tests/transaction.rs", "rank": 84, "score": 126572.33223006762 }, { "content": "fn main() {\n\n let mut w = std::io::stdout();\n\n let env = &mut Env::default();\n\n\n\n decl_type!(w, env, SingleTuple => \"single_tuple\");\n\n decl_func!(w, env, new => \"new_t\");\n\n decl_func!(w, env, print => \"print_t\");\n\n}\n", "file_path": "ocaml/tests/src/main.rs", "rank": 85, "score": 126566.72032853293 }, { "content": "#[test]\n\nfn transaction_memo_str() {\n\n let kp = Keypair::from_hex(\"164244176fddb5d769b7de2027469d027ad428fadcc0c02396e6280142efb718\")\n\n .expect(\"failed to create keypair\");\n\n\n\n let tx = Transaction::new_payment(kp.public, kp.public, 0, 0, 0);\n\n assert_eq!(\n\n tx.memo,\n\n [\n\n 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\n 0, 0, 0, 0, 0\n\n ]\n\n );\n\n\n\n // Memo length < max memo length\n\n let tx = tx.set_memo_str(\"Hello Mina!\");\n\n assert_eq!(\n\n tx.memo,\n\n [\n\n 1, 11, 72, 101, 108, 108, 111, 32, 77, 105, 110, 97, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n", "file_path": "signer/tests/transaction.rs", "rank": 86, "score": 124151.74787132259 }, { "content": "#[test]\n\nfn chacha_prover() {\n\n let num_chachas = 8;\n\n let rows_per_chacha = 20 * 4 * 10;\n\n let n_lower_bound = rows_per_chacha * num_chachas;\n\n let max_size = 1 << math::ceil_log2(n_lower_bound);\n\n println!(\"{} {}\", n_lower_bound, max_size);\n\n\n\n let s0: Vec<u32> = vec![\n\n 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574, 0x03020100, 0x07060504, 0x0b0a0908,\n\n 0x0f0e0d0c, 0x13121110, 0x17161514, 0x1b1a1918, 0x1f1e1d1c, 0x00000001, 0x09000000,\n\n 0x4a000000, 0x00000000,\n\n ];\n\n let expected_result: Vec<u32> = vec![\n\n 0x837778ab, 0xe238d763, 0xa67ae21e, 0x5950bb2f, 0xc4f2d0c7, 0xfc62bb2f, 0x8fa018fc,\n\n 0x3f5ec7b7, 0x335271c2, 0xf29489f3, 0xeabda8fc, 0x82e46ebd, 0xd19c12b4, 0xb04e16de,\n\n 0x9e83d0cb, 0x4e3c50a2,\n\n ];\n\n assert_eq!(expected_result, chacha::testing::chacha20(s0.clone()));\n\n\n\n // circuit gates\n", "file_path": "kimchi/src/tests/chacha.rs", "rank": 87, "score": 124151.74787132259 }, { "content": "/// Returns ceil(log2(d)) but panics if d = 0.\n\npub fn ceil_log2(d: usize) -> usize {\n\n // NOTE: should this really be usize, since usize is depended on the underlying system architecture?\n\n\n\n assert!(d != 0);\n\n let mut pow2 = 1;\n\n let mut ceil_log2 = 0;\n\n while d > pow2 {\n\n ceil_log2 += 1;\n\n pow2 = match pow2.checked_mul(2) {\n\n Some(x) => x,\n\n None => break,\n\n }\n\n }\n\n ceil_log2\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n", "file_path": "utils/src/math.rs", "rank": 88, "score": 121868.10991976067 }, { "content": "/// \"Usage: cargo run --all-features --bin export_test_vectors -- [hex|b10] [legacy|kimchi] <OUTPUT_FILE>\",\n\nfn main() {\n\n inner::main();\n\n}\n\n\n\nmod inner {\n\n use super::vectors;\n\n use std::env;\n\n use std::fs::File;\n\n use std::io::{self, Write};\n\n use std::str::FromStr;\n\n\n\n #[derive(Debug)]\n\n pub enum Mode {\n\n Hex,\n\n B10,\n\n }\n\n\n\n impl FromStr for Mode {\n\n type Err = ();\n\n\n", "file_path": "oracle/export_test_vectors/src/main.rs", "rank": 89, "score": 121853.61561938895 }, { "content": "fn test_vectors<F>(test_vector_file: &str, hash: F)\n\nwhere\n\n F: Fn(&[Fp]) -> Fp,\n\n{\n\n // read test vectors from given file\n\n let mut path = PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"));\n\n path.push(\"tests/test_vectors\");\n\n path.push(&test_vector_file);\n\n let file = File::open(&path).expect(\"couldn't open test vector file\");\n\n let test_vectors: TestVectors =\n\n serde_json::from_reader(file).expect(\"couldn't deserialize test vector file\");\n\n\n\n // execute test vectors\n\n for test_vector in test_vectors.test_vectors {\n\n // deserialize input & ouptut\n\n let input: Vec<Fp> = test_vector\n\n .input\n\n .into_iter()\n\n .map(|hexstring| Fp::from_hex(&hexstring).expect(\"failed to deserialize field element\"))\n\n .collect();\n", "file_path": "oracle/tests/poseidon_tests.rs", "rank": 90, "score": 120510.53007421014 }, { "content": "pub fn b_poly_coefficients<F: Field>(chals: &[F]) -> Vec<F> {\n\n let rounds = chals.len();\n\n let s_length = 1 << rounds;\n\n let mut s = vec![F::one(); s_length];\n\n let mut k: usize = 0;\n\n let mut pow: usize = 1;\n\n for i in 1..s_length {\n\n k += if i == pow { 1 } else { 0 };\n\n pow <<= if i == pow { 1 } else { 0 };\n\n s[i] = s[i - (pow >> 1)] * chals[rounds - 1 - (k - 1)];\n\n }\n\n s\n\n}\n\n\n", "file_path": "poly-commitment/src/commitment.rs", "rank": 91, "score": 117693.5049810936 }, { "content": "fn batch_negate_in_place<P: SWModelParameters>(ps: &mut [SWJAffine<P>]) {\n\n ps.par_iter_mut().for_each(|p| {\n\n p.y = -p.y;\n\n });\n\n}\n\n\n", "file_path": "poly-commitment/src/combine.rs", "rank": 92, "score": 115662.82875457096 }, { "content": "/// Computes the sorted lookup tables required by the lookup argument.\n\npub fn sorted<F>(\n\n dummy_lookup_value: F,\n\n joint_lookup_table_d8: &Evaluations<F, D<F>>,\n\n d1: D<F>,\n\n gates: &[CircuitGate<F>],\n\n witness: &[Vec<F>; COLUMNS],\n\n joint_combiner: F,\n\n table_id_combiner: F,\n\n) -> Result<Vec<Vec<F>>, ProverError>\n\nwhere\n\n F: FftField,\n\n{\n\n // We pad the lookups so that it is as if we lookup exactly\n\n // `max_lookups_per_row` in every row.\n\n\n\n let n = d1.size();\n\n let mut counts: HashMap<&F, usize> = HashMap::new();\n\n\n\n let lookup_rows = n - ZK_ROWS - 1;\n\n let lookup_info = LookupInfo::<F>::create();\n", "file_path": "kimchi/src/circuits/lookup/constraints.rs", "rank": 93, "score": 114038.94625169571 }, { "content": "#[ocaml_gen::func]\n\n#[ocaml::func]\n\npub fn new() -> SingleTuple {\n\n SingleTuple(String::from(\"Hello\"))\n\n}\n\n\n", "file_path": "ocaml/tests/src/lib.rs", "rank": 94, "score": 113843.61633456105 }, { "content": "fn combine_nybbles<F: Field>(ns: Vec<E<F>>) -> E<F> {\n\n ns.into_iter()\n\n .enumerate()\n\n .fold(E::zero(), |acc: E<F>, (i, t)| {\n\n acc + E::from(1 << (4 * i)) * t\n\n })\n\n}\n\n\n", "file_path": "kimchi/src/circuits/polynomials/chacha.rs", "rank": 95, "score": 112126.4539190449 }, { "content": "#[ocaml_gen::func]\n\n#[ocaml::func]\n\npub fn print(s: SingleTuple) {\n\n println!(\"{}\", s.0);\n\n}\n", "file_path": "ocaml/tests/src/lib.rs", "rank": 96, "score": 111626.49736360893 }, { "content": "/// Same as [combine_table_entry], but for an entire table.\n\n/// The function will panic if given an empty table (0 columns).\n\npub fn combine_table<G>(\n\n columns: &[&PolyComm<G>],\n\n column_combiner: ScalarField<G>,\n\n table_id_combiner: ScalarField<G>,\n\n table_id_vector: Option<&PolyComm<G>>,\n\n runtime_vector: Option<&PolyComm<G>>,\n\n) -> PolyComm<G>\n\nwhere\n\n G: commitment_dlog::commitment::CommitmentCurve,\n\n{\n\n assert!(!columns.is_empty());\n\n\n\n // combine the columns\n\n let mut j = ScalarField::<G>::one();\n\n let mut scalars = vec![j];\n\n let mut commitments = vec![columns[0]];\n\n for comm in columns.iter().skip(1) {\n\n j *= column_combiner;\n\n scalars.push(j);\n\n commitments.push(comm);\n", "file_path": "kimchi/src/circuits/lookup/tables/mod.rs", "rank": 97, "score": 109965.87128860087 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn aggregation<R, F>(\n\n dummy_lookup_value: F,\n\n joint_lookup_table_d8: &Evaluations<F, D<F>>,\n\n d1: D<F>,\n\n gates: &[CircuitGate<F>],\n\n witness: &[Vec<F>; COLUMNS],\n\n joint_combiner: &F,\n\n table_id_combiner: &F,\n\n beta: F,\n\n gamma: F,\n\n sorted: &[Evaluations<F, D<F>>],\n\n rng: &mut R,\n\n) -> Result<Evaluations<F, D<F>>, ProverError>\n\nwhere\n\n R: Rng + ?Sized,\n\n F: FftField,\n\n{\n\n let n = d1.size();\n\n let lookup_rows = n - ZK_ROWS - 1;\n\n let beta1 = F::one() + beta;\n", "file_path": "kimchi/src/circuits/lookup/constraints.rs", "rank": 98, "score": 109733.03354968566 }, { "content": "/// Returns the XOR lookup table\n\npub fn xor_table<F: Field>() -> LookupTable<F> {\n\n let mut data = vec![vec![]; 3];\n\n\n\n // XOR for all possible four-bit arguments.\n\n // I suppose this could be computed a bit faster using symmetry but it's quite\n\n // small (16*16 = 256 entries) so let's just keep it simple.\n\n for i in 0u32..=0b1111 {\n\n for j in 0u32..=0b1111 {\n\n data[0].push(F::from(i));\n\n data[1].push(F::from(j));\n\n data[2].push(F::from(i ^ j));\n\n }\n\n }\n\n\n\n for r in &mut data {\n\n r.reverse();\n\n // Just to be safe.\n\n assert!(r[r.len() - 1].is_zero());\n\n }\n\n LookupTable {\n\n id: XOR_TABLE_ID,\n\n data,\n\n }\n\n}\n", "file_path": "kimchi/src/circuits/lookup/tables/xor.rs", "rank": 99, "score": 109556.56244576076 } ]
Rust
crates/notion-core/src/distro/yarn.rs
acorncom/notion
6458f41a8c32b2e0618a6c4dd8eb5eca31ba0cd7
use std::fs::{rename, File}; use std::path::PathBuf; use std::string::ToString; use super::{Distro, Fetched}; use archive::{Archive, Tarball}; use distro::error::DownloadError; use distro::DistroVersion; use fs::ensure_containing_dir_exists; use inventory::YarnCollection; use path; use style::{progress_bar, Action}; use tool::ToolSpec; use version::VersionSpec; use notion_fail::{Fallible, ResultExt}; use semver::Version; #[cfg(feature = "mock-network")] use mockito; cfg_if! { if #[cfg(feature = "mock-network")] { fn public_yarn_server_root() -> String { mockito::SERVER_URL.to_string() } } else { fn public_yarn_server_root() -> String { "https://github.com/yarnpkg/yarn/releases/download".to_string() } } } pub struct YarnDistro { archive: Box<Archive>, version: Version, } fn distro_is_valid(file: &PathBuf) -> bool { if file.is_file() { if let Ok(file) = File::open(file) { match Tarball::load(file) { Ok(_) => return true, Err(_) => return false, } } } false } impl Distro for YarnDistro { fn public(version: Version) -> Fallible<Self> { let version_str = version.to_string(); let distro_file_name = path::yarn_distro_file_name(&version_str); let url = format!( "{}/v{}/{}", public_yarn_server_root(), version_str, distro_file_name ); YarnDistro::remote(version, &url) } fn remote(version: Version, url: &str) -> Fallible<Self> { let distro_file_name = path::yarn_distro_file_name(&version.to_string()); let distro_file = path::yarn_inventory_dir()?.join(&distro_file_name); if distro_is_valid(&distro_file) { return YarnDistro::local(version, File::open(distro_file).unknown()?); } ensure_containing_dir_exists(&distro_file)?; Ok(YarnDistro { archive: Tarball::fetch(url, &distro_file).with_context(DownloadError::for_tool( ToolSpec::Yarn(VersionSpec::exact(&version)), url.to_string(), ))?, version: version, }) } fn local(version: Version, file: File) -> Fallible<Self> { Ok(YarnDistro { archive: Tarball::load(file).unknown()?, version: version, }) } fn version(&self) -> &Version { &self.version } fn fetch(self, collection: &YarnCollection) -> Fallible<Fetched<DistroVersion>> { if collection.contains(&self.version) { return Ok(Fetched::Already(DistroVersion::Yarn(self.version))); } let dest = path::yarn_image_root_dir()?; let bar = progress_bar( Action::Fetching, &format!("v{}", self.version), self.archive .uncompressed_size() .unwrap_or(self.archive.compressed_size()), ); self.archive .unpack(&dest, &mut |_, read| { bar.inc(read as u64); }) .unknown()?; let version_string = self.version.to_string(); rename( dest.join(path::yarn_archive_root_dir_name(&version_string)), path::yarn_image_dir(&version_string)?, ) .unknown()?; bar.finish_and_clear(); Ok(Fetched::Now(DistroVersion::Yarn(self.version))) } }
use std::fs::{rename, File}; use std::path::PathBuf; use std::string::ToString; use super::{Distro, Fetched}; use archive::{Archive, Tarball}; use distro::error::DownloadError; use distro::DistroVersion; use fs::ensure_containing_dir_exists; use inventory::YarnCollection; use path; use style::{progress_bar, Action}; use tool::ToolSpec; use version::VersionSpec; use notion_fail::{Fallible, ResultExt}; use semver::Version; #[cfg(feature = "mock-network")] use mockito; cfg_if! { if #[cfg(feature = "mock-network")] { fn public_yarn_server_root() -> String { mockito::SERVER_URL.to_string() } } else { fn public_yarn_server_root() -> String { "https://github.com/yarnpkg/yarn/releases/download".to_string() } } } pub struct YarnDistro { archive: Box<Archive>, version: Version, } fn distro_is_valid(file: &PathBuf) -> bool { if file.is_file() { if let Ok(file) = File::open(file) { match Tarball::load(file) { Ok(_) => return true, Err(_) => return false, } } } false } impl Distro for YarnDistro { fn public(version: Version) -> Fallible<Self> { let version_str = version.to_string(); let distro_file_name = path::yarn_distro_file_name(&version_str); let url = fo
fn remote(version: Version, url: &str) -> Fallible<Self> { let distro_file_name = path::yarn_distro_file_name(&version.to_string()); let distro_file = path::yarn_inventory_dir()?.join(&distro_file_name); if distro_is_valid(&distro_file) { return YarnDistro::local(version, File::open(distro_file).unknown()?); } ensure_containing_dir_exists(&distro_file)?; Ok(YarnDistro { archive: Tarball::fetch(url, &distro_file).with_context(DownloadError::for_tool( ToolSpec::Yarn(VersionSpec::exact(&version)), url.to_string(), ))?, version: version, }) } fn local(version: Version, file: File) -> Fallible<Self> { Ok(YarnDistro { archive: Tarball::load(file).unknown()?, version: version, }) } fn version(&self) -> &Version { &self.version } fn fetch(self, collection: &YarnCollection) -> Fallible<Fetched<DistroVersion>> { if collection.contains(&self.version) { return Ok(Fetched::Already(DistroVersion::Yarn(self.version))); } let dest = path::yarn_image_root_dir()?; let bar = progress_bar( Action::Fetching, &format!("v{}", self.version), self.archive .uncompressed_size() .unwrap_or(self.archive.compressed_size()), ); self.archive .unpack(&dest, &mut |_, read| { bar.inc(read as u64); }) .unknown()?; let version_string = self.version.to_string(); rename( dest.join(path::yarn_archive_root_dir_name(&version_string)), path::yarn_image_dir(&version_string)?, ) .unknown()?; bar.finish_and_clear(); Ok(Fetched::Now(DistroVersion::Yarn(self.version))) } }
rmat!( "{}/v{}/{}", public_yarn_server_root(), version_str, distro_file_name ); YarnDistro::remote(version, &url) }
function_block-function_prefixed
[ { "content": "pub fn yarn_distro_file_name(version: &str) -> String {\n\n format!(\"{}.tar.gz\", yarn_archive_root_dir_name(version))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 0, "score": 365902.2436720986 }, { "content": "pub fn node_distro_file_name(version: &str) -> String {\n\n format!(\n\n \"{}.{}\",\n\n node_archive_root_dir_name(version),\n\n archive_extension()\n\n )\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 1, "score": 365902.2436720986 }, { "content": "pub fn yarn_archive_root_dir_name(version: &str) -> String {\n\n format!(\"yarn-v{}\", version)\n\n}\n\n\n\n#[cfg(test)]\n\npub mod tests {\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn test_node_distro_file_name() {\n\n assert_eq!(\n\n node_distro_file_name(\"1.2.3\"),\n\n format!(\"node-v1.2.3-{}-{}.{}\", OS, ARCH, archive_extension())\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_node_archive_root_dir() {\n\n assert_eq!(\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 2, "score": 325378.4435938592 }, { "content": "pub fn node_archive_root_dir_name(version: &str) -> String {\n\n format!(\"node-v{}-{}-{}\", version, OS, ARCH)\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 3, "score": 325378.4435938592 }, { "content": "/// Check if the fetched file is valid. It may have been corrupted or interrupted in the middle of\n\n/// downloading.\n\n// ISSUE(#134) - verify checksum\n\nfn distro_is_valid(file: &PathBuf) -> bool {\n\n if file.is_file() {\n\n if let Ok(file) = File::open(file) {\n\n match archive::load_native(file) {\n\n Ok(_) => return true,\n\n Err(_) => return false,\n\n }\n\n }\n\n }\n\n false\n\n}\n\n\n\n#[derive(Deserialize)]\n\npub struct Manifest {\n\n version: String,\n\n}\n\n\n\nimpl Manifest {\n\n fn read(path: &Path) -> Fallible<Manifest> {\n\n let file = File::open(path).unknown()?;\n", "file_path": "crates/notion-core/src/distro/node.rs", "rank": 4, "score": 314176.9783396551 }, { "content": "/// Reads a file, if it exists.\n\npub fn read_file_opt(path: &PathBuf) -> io::Result<Option<String>> {\n\n let result: io::Result<String> = fs::read_to_string(path);\n\n\n\n match result {\n\n Ok(string) => Ok(Some(string)),\n\n Err(error) => match error.kind() {\n\n ErrorKind::NotFound => Ok(None),\n\n _ => Err(error),\n\n },\n\n }\n\n}\n\n\n", "file_path": "crates/notion-core/src/fs.rs", "rank": 6, "score": 307842.9529530493 }, { "content": "pub fn node_npm_version_file(version: &str) -> Fallible<PathBuf> {\n\n let filename = format!(\"node-v{}-npm\", version);\n\n Ok(node_inventory_dir()?.join(&filename))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 7, "score": 300007.59385894955 }, { "content": "pub fn node_archive_npm_package_json_path(version: &str) -> PathBuf {\n\n Path::new(&node_archive_root_dir_name(version))\n\n .join(\"lib\")\n\n .join(\"node_modules\")\n\n .join(\"npm\")\n\n .join(\"package.json\")\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 8, "score": 296819.37318676093 }, { "content": "fn match_node_version(predicate: impl Fn(&NodeEntry) -> bool) -> Fallible<Option<Version>> {\n\n let index: NodeIndex = resolve_node_versions()?.into_index()?;\n\n let mut entries = index.entries.into_iter();\n\n Ok(entries\n\n .find(predicate)\n\n .map(|NodeEntry { version, .. }| version))\n\n}\n\n\n\nimpl FetchResolve<NodeDistro> for NodeCollection {\n\n fn fetch(\n\n &mut self,\n\n matching: &VersionSpec,\n\n config: &Config,\n\n ) -> Fallible<Fetched<DistroVersion>> {\n\n let distro = self.resolve_remote(matching, config.node.as_ref())?;\n\n let fetched = distro.fetch(&self).unknown()?;\n\n\n\n if let &Fetched::Now(DistroVersion::Node(ref version, ..)) = &fetched {\n\n self.versions.insert(version.clone());\n\n }\n", "file_path": "crates/notion-core/src/inventory/mod.rs", "rank": 9, "score": 294090.8439948207 }, { "content": "pub fn archive_extension() -> String {\n\n String::from(\"zip\")\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/windows.rs", "rank": 10, "score": 282212.788624603 }, { "content": "pub fn archive_extension() -> String {\n\n String::from(\"tar.gz\")\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/unix.rs", "rank": 11, "score": 282212.788624603 }, { "content": "pub fn touch(path: &Path) -> Fallible<File> {\n\n if !path.is_file() {\n\n let basedir = path.parent().unwrap();\n\n create_dir_all(basedir).unknown()?;\n\n File::create(path).unknown()?;\n\n }\n\n File::open(path).unknown()\n\n}\n\n\n\n#[derive(Debug, Fail, NotionFail)]\n\n#[fail(display = \"Could not create directory {}: {}\", dir, error)]\n\n#[notion_fail(code = \"FileSystemError\")]\n\npub(crate) struct CreateDirError {\n\n pub(crate) dir: String,\n\n pub(crate) error: String,\n\n}\n\n\n\nimpl CreateDirError {\n\n pub(crate) fn for_dir(dir: String) -> impl FnOnce(&io::Error) -> CreateDirError {\n\n move |error| CreateDirError {\n", "file_path": "crates/notion-core/src/fs.rs", "rank": 12, "score": 275871.58608965506 }, { "content": "fn read_file_to_string(file_path: PathBuf) -> String {\n\n let mut contents = String::new();\n\n let mut file = ok_or_panic! { File::open(file_path) };\n\n ok_or_panic! { file.read_to_string(&mut contents) };\n\n contents\n\n}\n", "file_path": "tests/acceptance/support/sandbox.rs", "rank": 13, "score": 263408.5239651026 }, { "content": "fn read_file_to_string(file_path: PathBuf) -> String {\n\n let mut contents = String::new();\n\n let mut file = ok_or_panic!{ File::open(file_path) };\n\n ok_or_panic!{ file.read_to_string(&mut contents) };\n\n contents\n\n}\n", "file_path": "tests/smoke/support/temp_project.rs", "rank": 14, "score": 261350.56070728606 }, { "content": "pub fn yarn_image_dir(version: &str) -> Fallible<PathBuf> {\n\n Ok(yarn_image_root_dir()?.join(version))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 15, "score": 255930.46727413044 }, { "content": "pub fn yarn_image_bin_dir(version: &str) -> Fallible<PathBuf> {\n\n Ok(yarn_image_dir(version)?.join(\"bin\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 16, "score": 253821.58011660224 }, { "content": "/// Load the local npm version file to determine the default npm version for a given version of Node\n\npub fn load_default_npm_version(node: &Version) -> Fallible<Version> {\n\n let npm_version_file_path = path::node_npm_version_file(&node.to_string())?;\n\n Ok(read_to_string(npm_version_file_path)\n\n .unknown()?\n\n .parse()\n\n .unknown()?)\n\n}\n\n\n", "file_path": "crates/notion-core/src/distro/node.rs", "rank": 17, "score": 243293.47374873428 }, { "content": "pub fn notion_file() -> Fallible<PathBuf> {\n\n Ok(notion_home()?.join(\"notion.exe\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/windows.rs", "rank": 18, "score": 241147.32102080795 }, { "content": "pub fn notion_file() -> Fallible<PathBuf> {\n\n Ok(notion_home()?.join(\"notion\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/unix.rs", "rank": 19, "score": 241147.32102080795 }, { "content": "pub fn launchbin_file() -> Fallible<PathBuf> {\n\n Ok(notion_home()?.join(\"launchbin.exe\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/windows.rs", "rank": 20, "score": 241147.32102080795 }, { "content": "pub fn launchbin_file() -> Fallible<PathBuf> {\n\n Ok(notion_home()?.join(\"launchbin\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/unix.rs", "rank": 21, "score": 241147.32102080795 }, { "content": "pub fn launchscript_file() -> Fallible<PathBuf> {\n\n Ok(notion_home()?.join(\"launchscript\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/unix.rs", "rank": 22, "score": 241147.32102080795 }, { "content": "pub fn launchscript_file() -> Fallible<PathBuf> {\n\n Ok(notion_home()?.join(\"launchscript.exe\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/windows.rs", "rank": 23, "score": 241147.32102080795 }, { "content": "pub fn node_index_file() -> Fallible<PathBuf> {\n\n Ok(node_cache_dir()?.join(\"index.json\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 24, "score": 238843.41943950375 }, { "content": "pub fn user_config_file() -> Fallible<PathBuf> {\n\n Ok(notion_home()?.join(\"config.toml\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 25, "score": 238843.41943950375 }, { "content": "pub fn user_platform_file() -> Fallible<PathBuf> {\n\n Ok(user_toolchain_dir()?.join(\"platform.json\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 26, "score": 238843.41943950375 }, { "content": "pub fn node_index_expiry_file() -> Fallible<PathBuf> {\n\n Ok(node_cache_dir()?.join(\"index.json.expires\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 27, "score": 236607.3039658878 }, { "content": "pub fn shim_file(toolname: &str) -> Fallible<PathBuf> {\n\n Ok(shim_dir()?.join(toolname))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/unix.rs", "rank": 28, "score": 229335.05340209944 }, { "content": "pub fn shim_file(toolname: &str) -> Fallible<PathBuf> {\n\n Ok(shim_dir()?.join(&format!(\"{}.exe\", toolname)))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/windows.rs", "rank": 29, "score": 229335.05340209944 }, { "content": "/// Fetches just the `isize` field (the field that indicates the uncompressed size)\n\n/// of a gzip file from a URL. This makes two round-trips to the server but avoids\n\n/// downloading the entire gzip file. For very small files it's unlikely to be\n\n/// more efficient than simply downloading the entire file up front.\n\nfn fetch_isize(url: &str, len: u64) -> Result<[u8; 4], failure::Error> {\n\n let client = reqwest::Client::new()?;\n\n let mut response = client\n\n .get(url)?\n\n .header(Range::Bytes(vec![ByteRangeSpec::FromTo(len - 4, len - 1)]))\n\n .send()?;\n\n\n\n if !response.status().is_success() {\n\n Err(super::HttpError {\n\n code: response.status(),\n\n })?;\n\n }\n\n\n\n let actual_length = content_length(&response)?;\n\n\n\n if actual_length != 4 {\n\n Err(UnexpectedContentLengthError {\n\n length: actual_length,\n\n })?;\n\n }\n\n\n\n let mut buf = [0; 4];\n\n response.read_exact(&mut buf)?;\n\n Ok(buf)\n\n}\n\n\n", "file_path": "crates/archive/src/tarball.rs", "rank": 30, "score": 225921.20394151902 }, { "content": "/// Reads the full contents of a directory, eagerly extracting each directory entry\n\n/// and its metadata and returning an iterator over them. Returns `Error` if any of\n\n/// these steps fails.\n\n///\n\n/// This function makes it easier to write high level logic for manipulating the\n\n/// contents of directories (map, filter, etc).\n\n///\n\n/// Note that this function allocates an intermediate vector of directory entries to\n\n/// construct the iterator from, so if a directory is expected to be very large, it\n\n/// will allocate temporary data proportional to the number of entries.\n\npub fn read_dir_eager(dir: &Path) -> Fallible<impl Iterator<Item = (DirEntry, Metadata)>> {\n\n Ok(read_dir(dir)\n\n .unknown()?\n\n .map(|entry| {\n\n let entry = entry.unknown()?;\n\n let metadata = entry.metadata().unknown()?;\n\n Ok((entry, metadata))\n\n })\n\n .collect::<Fallible<Vec<(DirEntry, Metadata)>>>()?\n\n .into_iter())\n\n}\n", "file_path": "crates/notion-core/src/fs.rs", "rank": 31, "score": 225903.26639368152 }, { "content": "/// Determines the uncompressed size of a gzip file hosted at the specified\n\n/// URL by fetching just the metadata associated with the file. This makes\n\n/// an extra round-trip to the server, so it's only more efficient than just\n\n/// downloading the file if the file is large enough that downloading it is\n\n/// slower than the extra round trips.\n\nfn fetch_uncompressed_size(url: &str, len: u64) -> Result<u64, failure::Error> {\n\n let packed = fetch_isize(url, len)?;\n\n Ok(unpack_isize(packed))\n\n}\n\n\n", "file_path": "crates/archive/src/tarball.rs", "rank": 32, "score": 224677.98059139765 }, { "content": "pub fn create_file_symlink(src: PathBuf, dst: PathBuf) -> Result<(), io::Error> {\n\n unix::fs::symlink(src, dst)\n\n}\n", "file_path": "crates/notion-core/src/path/unix.rs", "rank": 33, "score": 224042.72657511197 }, { "content": "pub fn create_file_symlink(src: PathBuf, dst: PathBuf) -> Result<(), io::Error> {\n\n #[cfg(windows)]\n\n return windows::fs::symlink_file(src, dst);\n\n\n\n // \"universal-docs\" is built on a Unix machine, so we can't include Windows-specific libs\n\n #[cfg(feature = \"universal-docs\")]\n\n unimplemented!()\n\n}\n", "file_path": "crates/notion-core/src/path/windows.rs", "rank": 34, "score": 224042.72657511197 }, { "content": "/// Reads the contents of a directory and returns the set of all versions found\n\n/// in the directory's listing by matching filenames against the specified regex\n\n/// and parsing the `version` named capture as a semantic version.\n\n///\n\n/// The regex should contain the `version` named capture by using the Rust regex\n\n/// syntax `?P<version>`.\n\nfn versions_matching(dir: &Path, re: &Regex) -> Fallible<BTreeSet<Version>> {\n\n Ok(read_dir_eager(dir)?\n\n .filter(|(_, metadata)| metadata.is_file())\n\n .filter_map(|(entry, _)| {\n\n if let Some(file_name) = entry.path().file_name() {\n\n if let Some(caps) = re.captures(&file_name.to_string_lossy()) {\n\n return Some(Version::parse(&caps[\"version\"]).unknown());\n\n }\n\n }\n\n None\n\n })\n\n .collect::<Fallible<BTreeSet<Version>>>()?)\n\n}\n\n\n\nimpl NodeCollection {\n\n pub(crate) fn load() -> Fallible<Self> {\n\n let re = Regex::new(\n\n r\"(?x)\n\n node\n\n -\n", "file_path": "crates/notion-core/src/inventory/serial.rs", "rank": 35, "score": 221189.54751725716 }, { "content": "/// Compare a line with an expected pattern.\n\n/// - Use `[..]` as a wildcard to match 0 or more characters on the same line\n\n/// (similar to `.*` in a regex).\n\n/// - Use `[EXE]` to optionally add `.exe` on Windows (empty string on other\n\n/// platforms).\n\n/// - There is a wide range of macros (such as `[COMPILING]` or `[WARNING]`)\n\n/// to match cargo's \"status\" output and allows you to ignore the alignment.\n\n/// See `substitute_macros` for a complete list of macros.\n\npub fn lines_match(expected: &str, actual: &str) -> bool {\n\n // Let's not deal with / vs \\ (windows...)\n\n let expected = expected.replace(\"\\\\\", \"/\");\n\n let mut actual: &str = &actual.replace(\"\\\\\", \"/\");\n\n let expected = substitute_macros(&expected);\n\n for (i, part) in expected.split(\"[..]\").enumerate() {\n\n match actual.find(part) {\n\n Some(j) => {\n\n if i == 0 && j != 0 {\n\n return false;\n\n }\n\n actual = &actual[j + part.len()..];\n\n }\n\n None => return false,\n\n }\n\n }\n\n actual.is_empty() || expected.ends_with(\"[..]\")\n\n}\n\n\n", "file_path": "crates/test-support/src/matchers.rs", "rank": 36, "score": 221189.4877094657 }, { "content": "pub fn root() -> PathBuf {\n\n init();\n\n global_root().join(&TASK_ID.with(|my_id| format!(\"t{}\", my_id)))\n\n}\n\n\n", "file_path": "crates/test-support/src/paths.rs", "rank": 37, "score": 212416.15113916347 }, { "content": "pub fn home() -> PathBuf {\n\n root().join(\"home\")\n\n}\n\n\n", "file_path": "crates/test-support/src/paths.rs", "rank": 38, "score": 212416.15113916347 }, { "content": "/// Loads the `isize` field (the field that indicates the uncompressed size)\n\n/// of a gzip file from disk.\n\nfn load_isize(file: &mut File) -> Result<[u8; 4], failure::Error> {\n\n file.seek(SeekFrom::End(-4))?;\n\n let mut buf = [0; 4];\n\n file.read_exact(&mut buf)?;\n\n file.seek(SeekFrom::Start(0))?;\n\n Ok(buf)\n\n}\n\n\n", "file_path": "crates/archive/src/tarball.rs", "rank": 39, "score": 211607.984939112 }, { "content": "/// Determines the uncompressed size of the specified gzip file on disk.\n\nfn load_uncompressed_size(file: &mut File) -> Result<u64, failure::Error> {\n\n let packed = load_isize(file)?;\n\n Ok(unpack_isize(packed))\n\n}\n\n\n\n#[cfg(test)]\n\npub mod tests {\n\n\n\n use std::fs::File;\n\n use std::path::PathBuf;\n\n use tarball::Tarball;\n\n\n\n fn fixture_path(fixture_dir: &str) -> PathBuf {\n\n let mut cargo_manifest_dir = PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"));\n\n cargo_manifest_dir.push(\"fixtures\");\n\n cargo_manifest_dir.push(fixture_dir);\n\n cargo_manifest_dir\n\n }\n\n\n\n #[test]\n", "file_path": "crates/archive/src/tarball.rs", "rank": 40, "score": 211041.96726835202 }, { "content": "fn is_node_version_installed(version: &Version, session: &Session) -> Fallible<bool> {\n\n Ok(session.inventory()?.node.contains(version))\n\n}\n\n\n", "file_path": "src/command/shim.rs", "rank": 41, "score": 210798.9413954066 }, { "content": "pub fn postscript_path() -> Option<PathBuf> {\n\n env::var_os(\"NOTION_POSTSCRIPT\")\n\n .as_ref()\n\n .map(|ref s| Path::new(s).to_path_buf())\n\n}\n\n\n\n#[cfg(test)]\n\npub mod tests {\n\n\n\n use super::*;\n\n use std::env;\n\n use std::path::PathBuf;\n\n\n\n #[test]\n\n fn test_shell_name() {\n\n env::set_var(\"NOTION_SHELL\", \"bash\");\n\n assert_eq!(shell_name().unwrap(), \"bash\".to_string());\n\n }\n\n\n\n #[test]\n\n fn test_postscript_path() {\n\n env::set_var(\"NOTION_POSTSCRIPT\", \"/some/path\");\n\n assert_eq!(postscript_path().unwrap(), PathBuf::from(\"/some/path\"));\n\n }\n\n\n\n}\n", "file_path": "crates/notion-core/src/env.rs", "rank": 42, "score": 204588.26950448396 }, { "content": "fn is_dependency(dir: &Path) -> bool {\n\n dir.parent().map_or(false, |parent| is_node_modules(parent))\n\n}\n\n\n", "file_path": "crates/notion-core/src/project.rs", "rank": 43, "score": 203667.9279622428 }, { "content": "// Path to compiled executables\n\npub fn cargo_dir() -> PathBuf {\n\n env::var_os(\"CARGO_BIN_PATH\")\n\n .map(PathBuf::from)\n\n .or_else(|| {\n\n env::current_exe().ok().map(|mut path| {\n\n path.pop();\n\n if path.ends_with(\"deps\") {\n\n path.pop();\n\n }\n\n path\n\n })\n\n })\n\n .unwrap_or_else(|| panic!(\"CARGO_BIN_PATH wasn't set. Cannot continue running test\"))\n\n}\n\n\n", "file_path": "tests/acceptance/support/sandbox.rs", "rank": 44, "score": 203237.1757210537 }, { "content": "pub fn image_dir() -> Fallible<PathBuf> {\n\n Ok(tools_dir()?.join(\"image\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 45, "score": 202853.85226591944 }, { "content": "pub fn inventory_dir() -> Fallible<PathBuf> {\n\n Ok(tools_dir()?.join(\"inventory\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 46, "score": 202853.85226591944 }, { "content": "pub fn cache_dir() -> Fallible<PathBuf> {\n\n Ok(notion_home()?.join(\"cache\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 47, "score": 202853.85226591944 }, { "content": "pub fn notion_home() -> Fallible<PathBuf> {\n\n if let Some(home) = env::var_os(\"NOTION_HOME\") {\n\n Ok(Path::new(&home).to_path_buf())\n\n } else {\n\n default_notion_home()\n\n }\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 48, "score": 202853.85226591944 }, { "content": "pub fn shim_dir() -> Fallible<PathBuf> {\n\n Ok(notion_home()?.join(\"bin\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 49, "score": 202853.8522659195 }, { "content": "pub fn tools_dir() -> Fallible<PathBuf> {\n\n Ok(notion_home()?.join(\"tools\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 50, "score": 202853.85226591944 }, { "content": "fn is_project_root(dir: &Path) -> bool {\n\n is_node_root(dir) && !is_dependency(dir)\n\n}\n\n\n\npub struct LazyDependentBins {\n\n bins: LazyCell<HashMap<String, String>>,\n\n}\n\n\n\nimpl LazyDependentBins {\n\n /// Constructs a new `LazyDependentBins`.\n\n pub fn new() -> LazyDependentBins {\n\n LazyDependentBins {\n\n bins: LazyCell::new(),\n\n }\n\n }\n\n\n\n /// Forces creating the dependent bins and returns an immutable reference to it.\n\n pub fn get(&self, project: &Project) -> Fallible<&HashMap<String, String>> {\n\n self.bins\n\n .try_borrow_with(|| Ok(project.dependent_binaries()?))\n", "file_path": "crates/notion-core/src/project.rs", "rank": 51, "score": 201655.80561116314 }, { "content": "fn is_node_root(dir: &Path) -> bool {\n\n dir.join(\"package.json\").is_file()\n\n}\n\n\n", "file_path": "crates/notion-core/src/project.rs", "rank": 52, "score": 201655.80561116314 }, { "content": "fn is_node_modules(dir: &Path) -> bool {\n\n dir.file_name() == Some(OsStr::new(\"node_modules\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/project.rs", "rank": 53, "score": 201655.80561116314 }, { "content": "// Path to compiled executables\n\npub fn cargo_dir() -> PathBuf {\n\n env::var_os(\"CARGO_BIN_PATH\")\n\n .map(PathBuf::from)\n\n .or_else(|| {\n\n env::current_exe().ok().map(|mut path| {\n\n path.pop();\n\n if path.ends_with(\"deps\") {\n\n path.pop();\n\n }\n\n path\n\n })\n\n })\n\n .unwrap_or_else(|| panic!(\"CARGO_BIN_PATH wasn't set. Cannot continue running test\"))\n\n}\n\n\n", "file_path": "tests/smoke/support/temp_project.rs", "rank": 54, "score": 201236.63159174076 }, { "content": "pub fn node_cache_dir() -> Fallible<PathBuf> {\n\n Ok(cache_dir()?.join(\"node\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 55, "score": 201169.70645551308 }, { "content": "pub fn user_toolchain_dir() -> Fallible<PathBuf> {\n\n Ok(tools_dir()?.join(\"user\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 56, "score": 201169.70645551308 }, { "content": "pub fn node_inventory_dir() -> Fallible<PathBuf> {\n\n Ok(inventory_dir()?.join(\"node\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 57, "score": 201169.70645551308 }, { "content": "pub fn default_notion_home() -> Fallible<PathBuf> {\n\n let home = dirs::home_dir().ok_or(NoHomeEnvVar)?;\n\n Ok(home.join(\".notion\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/unix.rs", "rank": 58, "score": 201169.70645551308 }, { "content": "pub fn yarn_inventory_dir() -> Fallible<PathBuf> {\n\n Ok(inventory_dir()?.join(\"yarn\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 59, "score": 201169.70645551308 }, { "content": "pub fn package_inventory_dir() -> Fallible<PathBuf> {\n\n Ok(inventory_dir()?.join(\"packages\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 60, "score": 201169.70645551308 }, { "content": "pub fn default_notion_home() -> Fallible<PathBuf> {\n\n let home = dirs::data_local_dir().ok_or(NoDataLocalDir)?;\n\n Ok(home.join(\"Notion\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/windows.rs", "rank": 61, "score": 201169.70645551308 }, { "content": "pub fn yarn_image_root_dir() -> Fallible<PathBuf> {\n\n Ok(image_dir()?.join(\"yarn\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 62, "score": 199533.60553524026 }, { "content": "pub fn node_image_root_dir() -> Fallible<PathBuf> {\n\n Ok(image_dir()?.join(\"node\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 63, "score": 199533.60553524026 }, { "content": "// ISSUE(#208) - explicitly including the npm version will not be necessary after that\n\nfn package_json_with_pinned_node_npm(version: &str, npm_version: &str) -> String {\n\n format!(\n\n r#\"{{\n\n \"name\": \"test-package\",\n\n \"toolchain\": {{\n\n \"node\": \"{}\",\n\n \"npm\": \"{}\"\n\n }}\n\n}}\"#,\n\n version, npm_version\n\n )\n\n}\n\n\n", "file_path": "tests/smoke/autodownload.rs", "rank": 64, "score": 197154.29086291607 }, { "content": "/// This creates the parent directory of the input path, assuming the input path is a file.\n\npub fn ensure_containing_dir_exists<P: AsRef<Path>>(path: &P) -> Fallible<()> {\n\n if let Some(dir) = path.as_ref().parent() {\n\n fs::create_dir_all(dir)\n\n .with_context(CreateDirError::for_dir(dir.to_string_lossy().to_string()))\n\n } else {\n\n // this was called for a file with no parent directory\n\n throw!(PathInternalError.unknown());\n\n }\n\n}\n\n\n", "file_path": "crates/notion-core/src/fs.rs", "rank": 65, "score": 193835.24036664987 }, { "content": "/// Constructs a command-line progress bar with the specified Action enum\n\n/// (e.g., `Action::Installing`), details string (e.g., `\"v1.23.4\"`), and logical\n\n/// length (i.e., the number of logical progress steps in the process being\n\n/// visualized by the progress bar).\n\npub fn progress_bar(action: Action, details: &str, len: u64) -> ProgressBar {\n\n let display_width = term_size::dimensions().map(|(w, _)| w).unwrap_or(80);\n\n let msg_width = Action::MAX_WIDTH + 1 + details.len();\n\n\n\n // Installing v1.23.4 [====================> ] 50%\n\n // |----------| |-----| |--------------------------------------| |-|\n\n // action details bar percentage\n\n let available_width = display_width - 2 - msg_width - 2 - 2 - 1 - 3 - 1;\n\n let bar_width = ::std::cmp::min(available_width, 40);\n\n\n\n let bar = ProgressBar::new(len);\n\n\n\n bar.set_message(&format!(\n\n \"{: >width$} {}\",\n\n style(action.to_string()).green().bold(),\n\n details,\n\n width = Action::MAX_WIDTH\n\n ));\n\n bar.set_style(\n\n ProgressStyle::default_bar()\n\n .template(&format!(\n\n \"{{msg}} [{{bar:{}.cyan/blue}}] {{percent:>3}}%\",\n\n bar_width\n\n ))\n\n .progress_chars(\"=> \"),\n\n );\n\n\n\n bar\n\n}\n\n\n", "file_path": "crates/notion-core/src/style.rs", "rank": 66, "score": 192608.168719206 }, { "content": "fn print_file_info(file: fs::DirEntry, session: &Session, verbose: bool) -> Fallible<()> {\n\n let shim_name = file.file_name();\n\n if verbose {\n\n let shim_info = resolve_shim(session, &shim_name)?;\n\n println!(\"{} -> {}\", shim_name.to_string_lossy(), shim_info);\n\n } else {\n\n println!(\"{}\", shim_name.to_string_lossy());\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/command/shim.rs", "rank": 67, "score": 186654.57900248206 }, { "content": "fn autoshim(session: &Session, maybe_path: Option<PathBuf>, _verbose: bool) -> Fallible<()> {\n\n let errors = if let Some(path) = maybe_path {\n\n if let Some(path_project) = Project::for_dir(&path)? {\n\n path_project.autoshim()\n\n } else {\n\n throw!(NotAPackageError {\n\n path: path.to_str().unwrap().to_string(),\n\n })\n\n }\n\n } else if let Some(session_project) = session.project() {\n\n session_project.autoshim()\n\n } else {\n\n throw!(NotAPackageError {\n\n path: \".\".to_string(),\n\n })\n\n };\n\n\n\n if errors.len() == 0 {\n\n Ok(())\n\n } else {\n", "file_path": "src/command/shim.rs", "rank": 68, "score": 185779.20830523694 }, { "content": "fn create(_session: &Session, shim_name: String, _verbose: bool) -> Fallible<()> {\n\n match shim::create(&shim_name)? {\n\n shim::ShimResult::AlreadyExists => throw!(ShimAlreadyExistsError { name: shim_name }),\n\n _ => Ok(()),\n\n }\n\n}\n\n\n", "file_path": "src/command/shim.rs", "rank": 69, "score": 184414.07944342826 }, { "content": "fn delete(_session: &Session, shim_name: String, _verbose: bool) -> Fallible<()> {\n\n match shim::delete(&shim_name)? {\n\n shim::ShimResult::DoesntExist => throw!(ShimDoesntExistError { name: shim_name }),\n\n _ => Ok(()),\n\n }\n\n}\n\n\n", "file_path": "src/command/shim.rs", "rank": 70, "score": 184414.07944342826 }, { "content": "pub fn node_image_dir(node: &str, npm: &str) -> Fallible<PathBuf> {\n\n Ok(node_image_root_dir()?.join(node).join(npm))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 71, "score": 181541.22008094736 }, { "content": "/// Save the default npm version to the filesystem for a given version of Node\n\nfn save_default_npm_version(node: &Version, npm: &Version) -> Fallible<()> {\n\n let npm_version_file_path = path::node_npm_version_file(&node.to_string())?;\n\n let mut npm_version_file = File::create(npm_version_file_path).unknown()?;\n\n npm_version_file\n\n .write_all(npm.to_string().as_bytes())\n\n .unknown()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/notion-core/src/distro/node.rs", "rank": 72, "score": 180463.76247506426 }, { "content": "// 3rd-party binaries installed globally for this node version\n\npub fn node_image_3p_bin_dir(_node: &str, _npm: &str) -> Fallible<PathBuf> {\n\n // ISSUE (#90) Figure out where binaries are globally installed on Windows\n\n unimplemented!(\"global 3rd party executables not yet implemented for Windows\")\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/windows.rs", "rank": 73, "score": 180081.77131546882 }, { "content": "// 3rd-party binaries installed globally for this node version\n\npub fn node_image_3p_bin_dir(node: &str, npm: &str) -> Fallible<PathBuf> {\n\n Ok(node_image_dir(node, npm)?.join(\"lib/node_modules/.bin\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/unix.rs", "rank": 74, "score": 180081.77131546882 }, { "content": "pub fn node_image_bin_dir(node: &str, npm: &str) -> Fallible<PathBuf> {\n\n Ok(node_image_dir(node, npm)?.join(\"bin\"))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/unix.rs", "rank": 75, "score": 180077.54398612428 }, { "content": "pub fn node_image_bin_dir(node: &str, npm: &str) -> Fallible<PathBuf> {\n\n node_image_dir(node, npm)\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/windows.rs", "rank": 76, "score": 180077.54398612428 }, { "content": "fn package_json_file(mut root: PathBuf) -> PathBuf {\n\n root.push(\"package.json\");\n\n root\n\n}\n", "file_path": "tests/acceptance/support/sandbox.rs", "rank": 77, "score": 177972.3928465213 }, { "content": "pub trait FetchResolve<D: Distro> {\n\n /// Fetch a Distro version matching the specified semantic versioning requirements.\n\n fn fetch(\n\n &mut self,\n\n matching: &VersionSpec,\n\n config: &Config,\n\n ) -> Fallible<Fetched<DistroVersion>>;\n\n\n\n /// Resolves the specified semantic versioning requirements from a remote distributor.\n\n fn resolve_remote(\n\n &self,\n\n matching: &VersionSpec,\n\n config: Option<&ToolConfig<D>>,\n\n ) -> Fallible<D> {\n\n match config {\n\n Some(ToolConfig {\n\n resolve: Some(ref plugin),\n\n ..\n\n }) => plugin.resolve(matching),\n\n _ => self.resolve_public(matching),\n", "file_path": "crates/notion-core/src/inventory/mod.rs", "rank": 78, "score": 177867.9613131548 }, { "content": "fn package_json_file(mut root: PathBuf) -> PathBuf {\n\n root.push(\"package.json\");\n\n root\n\n}\n\n\n\npub struct TempProject {\n\n root: PathBuf,\n\n}\n\n\n\nimpl TempProject {\n\n /// Root of the project, ex: `/path/to/cargo/target/integration_test/t0/foo`\n\n pub fn root(&self) -> PathBuf {\n\n self.root.clone()\n\n }\n\n\n\n /// Create a `ProcessBuilder` to run a program in the project.\n\n /// Example:\n\n /// assert_that(\n\n /// p.process(&p.bin(\"foo\")),\n\n /// execs().with_stdout(\"bar\\n\"),\n", "file_path": "tests/smoke/support/temp_project.rs", "rank": 79, "score": 176328.00868315343 }, { "content": "fn user_platform_file() -> PathBuf {\n\n user_dir().join(\"platform.json\")\n\n}\n\n\n\npub struct Sandbox {\n\n root: PathBuf,\n\n mocks: Vec<mockito::Mock>,\n\n env_vars: Vec<EnvVar>,\n\n path: OsString,\n\n}\n\n\n\nimpl Sandbox {\n\n /// Root of the project, ex: `/path/to/cargo/target/integration_test/t0/foo`\n\n pub fn root(&self) -> PathBuf {\n\n self.root.clone()\n\n }\n\n\n\n /// Create a `ProcessBuilder` to run a program in the project.\n\n /// Example:\n\n /// assert_that(\n", "file_path": "tests/acceptance/support/sandbox.rs", "rank": 80, "score": 175771.2643136156 }, { "content": "#[allow(dead_code)]\n\nfn node_index_file() -> PathBuf {\n\n node_cache_dir().join(\"index.json\")\n\n}\n", "file_path": "tests/acceptance/support/sandbox.rs", "rank": 81, "score": 175771.2643136156 }, { "content": "#[allow(dead_code)]\n\nfn node_index_expiry_file() -> PathBuf {\n\n node_cache_dir().join(\"index.json.expires\")\n\n}\n", "file_path": "tests/acceptance/support/sandbox.rs", "rank": 82, "score": 173761.260974758 }, { "content": "fn package_json_with_pinned_node_yarn(node_version: &str, yarn_version: &str) -> String {\n\n format!(\n\n r#\"{{\n\n \"name\": \"test-package\",\n\n \"toolchain\": {{\n\n \"node\": \"{}\",\n\n \"yarn\": \"{}\"\n\n }}\n\n}}\"#,\n\n node_version, yarn_version\n\n )\n\n}\n\n\n", "file_path": "tests/acceptance/notion_pin.rs", "rank": 83, "score": 165176.54512000055 }, { "content": "fn project_node_version(session: &Session) -> Fallible<Option<String>> {\n\n Ok(session\n\n .project_platform()?\n\n .map(|platform| platform.node_runtime.to_string()))\n\n}\n\n\n", "file_path": "src/command/current.rs", "rank": 84, "score": 163795.08717841312 }, { "content": "fn user_node_version(session: &Session) -> Fallible<Option<String>> {\n\n Ok(session\n\n .user_platform()?\n\n .map(|platform| platform.node_runtime.to_string()))\n\n}\n", "file_path": "src/command/current.rs", "rank": 85, "score": 163795.08717841312 }, { "content": "#[derive(Fail, Debug)]\n\n#[fail(display = \"HTTP header '{}' not found\", header)]\n\nstruct MissingHeaderError {\n\n header: String,\n\n}\n\n\n", "file_path": "crates/archive/src/tarball.rs", "rank": 86, "score": 162063.3624295662 }, { "content": "fn package_json_with_pinned_node_npm_yarn(node_version: &str, npm_version: &str, yarn_version: &str) -> String {\n\n format!(\n\n r#\"{{\n\n \"name\": \"test-package\",\n\n \"toolchain\": {{\n\n \"node\": \"{}\",\n\n \"npm\": \"{}\",\n\n \"yarn\": \"{}\"\n\n }}\n\n}}\"#,\n\n node_version, npm_version, yarn_version\n\n )\n\n}\n\n\n", "file_path": "tests/smoke/autodownload.rs", "rank": 87, "score": 161831.71925045218 }, { "content": "#[derive(Fail, Debug)]\n\n#[fail(display = \"HTTP server does not accept byte range requests\")]\n\nstruct ByteRangesNotAcceptedError;\n\n\n", "file_path": "crates/archive/src/tarball.rs", "rank": 88, "score": 159855.58939844213 }, { "content": "#[derive(Fail, Debug)]\n\n#[fail(display = \"unexpected content length in HTTP response: {}\", length)]\n\nstruct UnexpectedContentLengthError {\n\n length: u64,\n\n}\n\n\n", "file_path": "crates/archive/src/tarball.rs", "rank": 89, "score": 159855.58939844213 }, { "content": "pub fn parse_requirements(src: &str) -> Result<VersionReq, ReqParseError> {\n\n let src = src.trim();\n\n if src.len() > 0 && src.chars().next().unwrap().is_digit(10) {\n\n let defaulted = format!(\"={}\", src);\n\n VersionReq::parse(&defaulted)\n\n } else if src.len() > 0 && src.chars().next().unwrap() == 'v' {\n\n let defaulted = src.replacen(\"v\", \"=\", 1);\n\n VersionReq::parse(&defaulted)\n\n } else {\n\n VersionReq::parse(src)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub mod tests {\n\n\n\n use semver::VersionReq;\n\n use version::serial::parse_requirements;\n\n\n\n #[test]\n", "file_path": "crates/notion-core/src/version/serial.rs", "rank": 90, "score": 159256.8919818973 }, { "content": "pub trait Distro: Sized {\n\n /// Provision a distribution from the public distributor (e.g. `https://nodejs.org`).\n\n fn public(version: Version) -> Fallible<Self>;\n\n\n\n /// Provision a distribution from a remote distributor.\n\n fn remote(version: Version, url: &str) -> Fallible<Self>;\n\n\n\n /// Provision a distribution from the filesystem.\n\n fn local(version: Version, file: File) -> Fallible<Self>;\n\n\n\n /// Produces a reference to this distro's Tool version.\n\n fn version(&self) -> &Version;\n\n\n\n /// Fetches this version of the Tool. (It is left to the responsibility of the `Collection`\n\n /// to update its state after fetching succeeds.)\n\n fn fetch(self, collection: &Collection<Self>) -> Fallible<Fetched<DistroVersion>>;\n\n}\n", "file_path": "crates/notion-core/src/distro/mod.rs", "rank": 91, "score": 153938.65808964038 }, { "content": "// the root directory for the smoke tests, in `target/smoke_test`\n\nfn global_root() -> PathBuf {\n\n let mut path = ok_or_panic! { env::current_exe() };\n\n path.pop(); // chop off exe name\n\n path.pop(); // chop off 'debug'\n\n\n\n // If `cargo test` is run manually then our path looks like\n\n // `target/debug/foo`, in which case our `path` is already pointing at\n\n // `target`. If, however, `cargo test --target $target` is used then the\n\n // output is `target/$target/debug/foo`, so our path is pointing at\n\n // `target/$target`. Here we conditionally pop the `$target` name.\n\n if path.file_name().and_then(|s| s.to_str()) != Some(\"target\") {\n\n path.pop();\n\n }\n\n\n\n path.join(SMOKE_TEST_DIR)\n\n}\n\n\n", "file_path": "crates/test-support/src/paths.rs", "rank": 92, "score": 144673.28142330959 }, { "content": "/// The entry point for the `npx` shim.\n\npub fn main() {\n\n Npx::launch()\n\n}\n", "file_path": "src/npx.rs", "rank": 93, "score": 142674.2450653177 }, { "content": "/// The entry point for the `yarn` shim.\n\npub fn main() {\n\n Yarn::launch()\n\n}\n", "file_path": "src/yarn.rs", "rank": 94, "score": 142674.2450653177 }, { "content": "/// The entry point for the `node` shim.\n\npub fn main() {\n\n Node::launch()\n\n}\n", "file_path": "src/node.rs", "rank": 95, "score": 142674.2450653177 }, { "content": "/// The entry point for the `notion` CLI.\n\npub fn main() {\n\n let mut session = Session::new();\n\n\n\n session.add_event_start(ActivityKind::Notion);\n\n\n\n let exit_code = match Notion::go(&mut session) {\n\n Ok(_) => ExitCode::Success,\n\n Err(err) => {\n\n display_error_and_usage(&err);\n\n session.add_event_error(ActivityKind::Notion, &err);\n\n err.exit_code()\n\n }\n\n };\n\n session.add_event_end(ActivityKind::Notion, exit_code);\n\n session.exit(exit_code);\n\n}\n", "file_path": "src/notion.rs", "rank": 96, "score": 142674.2450653177 }, { "content": "/// The entry point for shims to third-party scripts.\n\npub fn main() {\n\n Script::launch()\n\n}\n", "file_path": "src/launchscript.rs", "rank": 97, "score": 142674.2450653177 }, { "content": "/// The entry point for the `npm` shim.\n\npub fn main() {\n\n Npm::launch()\n\n}\n", "file_path": "src/npm.rs", "rank": 98, "score": 142674.2450653177 }, { "content": "/// The entry point for shims to third-party binary executables.\n\npub fn main() {\n\n Binary::launch()\n\n}\n", "file_path": "src/launchbin.rs", "rank": 99, "score": 142674.2450653177 } ]
Rust
src/clock_gettime.rs
GoCodeIT-Inc/cpu-time
d36927e013565bd3cf1a06813e45e764558cf30a
use std::io::{Result, Error}; use std::marker::PhantomData; use std::rc::Rc; use std::time::Duration; use libc::{clock_gettime, timespec}; use libc::{CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID}; #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] pub struct ProcessTime(Duration); #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] pub struct ThreadTime( Duration, PhantomData<Rc<()>>, ); impl ProcessTime { pub fn try_now() -> Result<Self> { let mut time = timespec { tv_sec: 0, tv_nsec: 0, }; if unsafe { clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &mut time) } == -1 { return Err(Error::last_os_error()); } Ok(ProcessTime(Duration::new( time.tv_sec as u64, time.tv_nsec as u32, ))) } pub fn now() -> Self { Self::try_now().expect("CLOCK_PROCESS_CPUTIME_ID unsupported") } pub fn try_elapsed(&self) -> Result<Duration> { Ok(Self::try_now()?.duration_since(*self)) } pub fn elapsed(&self) -> Duration { Self::now().duration_since(*self) } pub fn duration_since(&self, timestamp: Self) -> Duration { self.0 - timestamp.0 } pub fn as_duration(&self) -> Duration { self.0 } } impl ThreadTime { pub fn try_now() -> Result<Self> { let mut time = timespec { tv_sec: 0, tv_nsec: 0, }; if unsafe { clock_gettime(CLOCK_THREAD_CPUTIME_ID, &mut time) } == -1 { return Err(Error::last_os_error()); } Ok(ThreadTime( Duration::new(time.tv_sec as u64, time.tv_nsec as u32), PhantomData, )) } pub fn now() -> Self { Self::try_now().expect("CLOCK_PROCESS_CPUTIME_ID unsupported") } pub fn try_elapsed(&self) -> Result<Duration> { Ok(ThreadTime::try_now()?.duration_since(*self)) } pub fn elapsed(&self) -> Duration { Self::now().duration_since(*self) } pub fn duration_since(&self, timestamp: ThreadTime) -> Duration { self.0 - timestamp.0 } pub fn as_duration(&self) -> Duration { self.0 } }
use std::io::{Result, Error}; use std::marker::PhantomData; use std::rc::Rc; use std::time::Duration; use libc::{clock_gettime, timespec}; use libc::{CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID}; #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] pub struct ProcessTime(Duration); #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] pub struct ThreadTime( Duration, PhantomData<Rc<()>>, ); impl ProcessTime { pub fn try_now() -> Result<Self> { let mut time = times
pub fn now() -> Self { Self::try_now().expect("CLOCK_PROCESS_CPUTIME_ID unsupported") } pub fn try_elapsed(&self) -> Result<Duration> { Ok(Self::try_now()?.duration_since(*self)) } pub fn elapsed(&self) -> Duration { Self::now().duration_since(*self) } pub fn duration_since(&self, timestamp: Self) -> Duration { self.0 - timestamp.0 } pub fn as_duration(&self) -> Duration { self.0 } } impl ThreadTime { pub fn try_now() -> Result<Self> { let mut time = timespec { tv_sec: 0, tv_nsec: 0, }; if unsafe { clock_gettime(CLOCK_THREAD_CPUTIME_ID, &mut time) } == -1 { return Err(Error::last_os_error()); } Ok(ThreadTime( Duration::new(time.tv_sec as u64, time.tv_nsec as u32), PhantomData, )) } pub fn now() -> Self { Self::try_now().expect("CLOCK_PROCESS_CPUTIME_ID unsupported") } pub fn try_elapsed(&self) -> Result<Duration> { Ok(ThreadTime::try_now()?.duration_since(*self)) } pub fn elapsed(&self) -> Duration { Self::now().duration_since(*self) } pub fn duration_since(&self, timestamp: ThreadTime) -> Duration { self.0 - timestamp.0 } pub fn as_duration(&self) -> Duration { self.0 } }
pec { tv_sec: 0, tv_nsec: 0, }; if unsafe { clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &mut time) } == -1 { return Err(Error::last_os_error()); } Ok(ProcessTime(Duration::new( time.tv_sec as u64, time.tv_nsec as u32, ))) }
function_block-function_prefixed
[ { "content": "fn to_duration(kernel_time: FILETIME, user_time: FILETIME) -> Duration {\n\n // resolution: 100ns\n\n let kns100 = ((kernel_time.dwHighDateTime as u64) << 32) + kernel_time.dwLowDateTime as u64;\n\n let uns100 = ((user_time.dwHighDateTime as u64) << 32) + user_time.dwLowDateTime as u64;\n\n return Duration::new(\n\n (kns100 + uns100) / 10_000_000,\n\n (((kns100 + uns100) * 100) % 1000_000_000) as u32,\n\n );\n\n}\n\n\n", "file_path": "src/windows.rs", "rank": 0, "score": 44517.30331435201 }, { "content": "#[test]\n\nfn thread_time() {\n\n let time = ThreadTime::now();\n\n sleep(Duration::new(1, 0));\n\n let elapsed = time.elapsed();\n\n assert!(elapsed < Duration::from_millis(100));\n\n}\n", "file_path": "tests/time.rs", "rank": 1, "score": 39026.7621392899 }, { "content": "#[test]\n\nfn process_time() {\n\n let time = ProcessTime::now();\n\n sleep(Duration::new(1, 0));\n\n let elapsed = time.elapsed();\n\n assert!(elapsed < Duration::from_millis(100));\n\n}\n\n\n", "file_path": "tests/time.rs", "rank": 2, "score": 39026.7621392899 }, { "content": "fn zero() -> FILETIME {\n\n FILETIME {\n\n dwLowDateTime: 0,\n\n dwHighDateTime: 0,\n\n }\n\n}\n\n\n\nimpl ProcessTime {\n\n /// Get current CPU time used by a process\n\n pub fn try_now() -> Result<Self> {\n\n let mut kernel_time = zero();\n\n let mut user_time = zero();\n\n let process = unsafe { GetCurrentProcess() };\n\n let ok = unsafe { GetProcessTimes(process,\n\n &mut zero(), &mut zero(),\n\n &mut kernel_time, &mut user_time) };\n\n if ok == 0 {\n\n return Err(std::io::Error::last_os_error());\n\n }\n\n Ok(Self(to_duration(kernel_time, user_time)))\n", "file_path": "src/windows.rs", "rank": 3, "score": 18967.876349286773 }, { "content": "extern crate cpu_time;\n\n\n\nuse std::time::Duration;\n\nuse std::thread::sleep;\n\n\n\nuse cpu_time::{ProcessTime, ThreadTime};\n\n\n\n\n\n#[test]\n", "file_path": "tests/time.rs", "rank": 4, "score": 16218.346388999376 }, { "content": "CPU Time Measurement Library\n\n============================\n\n\n\n[Documentation](https://docs.rs/cpu-time) |\n\n[Github](https://github.com/tailhook/cpu-time) |\n\n[Crate](https://crates.io/crates/cpu-time)\n\n\n\n\n\nA simple and idiomatic interface for measurement CPU time:\n\n\n\n```rust\n\n\n\nlet start = ProcessTime::now();\n\n# .. do something ..\n\nlet cpu_time: Duration = start.elapsed();\n\nprintln!(\" {:?}\");\n\n\n\n```\n\n\n\n\n\nLicense\n\n=======\n\n\n\nLicensed under either of\n\n\n\n* Apache License, Version 2.0,\n\n (./LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)\n\n* MIT license (./LICENSE-MIT or http://opensource.org/licenses/MIT)\n\n at your option.\n\n\n\nContribution\n\n------------\n\n\n\nUnless you explicitly state otherwise, any contribution intentionally\n\nsubmitted for inclusion in the work by you, as defined in the Apache-2.0\n\nlicense, shall be dual licensed as above, without any additional terms or\n\nconditions.\n\n\n", "file_path": "README.md", "rank": 5, "score": 8248.095783826937 }, { "content": "///\n\n/// This type is non-thread-shareable (!Sync, !Send) because otherwise it's\n\n/// to easy to mess up times from different threads. However, you can freely\n\n/// send Duration's returned by `elapsed()` and `duration_since()`.\n\n#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]\n\npub struct ThreadTime(\n\n Duration,\n\n // makes type non-sync and non-send\n\n PhantomData<Rc<()>>,\n\n);\n\n\n", "file_path": "src/windows.rs", "rank": 9, "score": 8.933837417921326 }, { "content": "use std::io::Result;\n\nuse std::marker::PhantomData;\n\nuse std::rc::Rc;\n\nuse std::time::Duration;\n\n\n\nuse winapi::shared::minwindef::{BOOL, FILETIME};\n\nuse winapi::um::processthreadsapi::{GetCurrentProcess, GetCurrentThread};\n\nuse winapi::um::processthreadsapi::{GetProcessTimes, GetThreadTimes};\n\n\n\n/// CPU Time Used by The Whole Process\n\n///\n\n/// This is an opaque type similar to `std::time::Instant`.\n\n/// Use `elapsed()` or `duration_since()` to get meaningful time deltas.\n\n#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]\n\npub struct ProcessTime(Duration);\n\n\n\n/// CPU Time Used by The Current Thread\n\n///\n\n/// This is an opaque type similar to `std::time::Instant`.\n\n/// Use `elapsed()` or `duration_since()` to get meaningful time deltas.\n", "file_path": "src/windows.rs", "rank": 10, "score": 8.323170257206739 }, { "content": "}\n\n\n\nimpl ThreadTime {\n\n /// Get current CPU time used by a process process\n\n pub fn try_now() -> Result<Self> {\n\n let mut kernel_time = zero();\n\n let mut user_time = zero();\n\n let thread = unsafe { GetCurrentThread() };\n\n let ok = unsafe { GetThreadTimes(thread,\n\n &mut zero(), &mut zero(),\n\n &mut kernel_time, &mut user_time) };\n\n if ok == 0 {\n\n return Err(std::io::Error::last_os_error());\n\n }\n\n Ok(Self(to_duration(kernel_time, user_time), PhantomData))\n\n }\n\n\n\n ///\n\n /// # Panics\n\n ///\n", "file_path": "src/windows.rs", "rank": 11, "score": 8.282568918386126 }, { "content": "//! // Panic in case of an error\n\n//! let start = ProcessTime::now();\n\n//! // .. do something ..\n\n//! let cpu_time: Duration = start.elapsed();\n\n//! println!(\" {:?}\", cpu_time);\n\n//! ```\n\n\n\n#![warn(missing_debug_implementations)]\n\n#![warn(missing_docs)]\n\n\n\n#[cfg(unix)] extern crate libc;\n\n#[cfg(windows)] extern crate winapi;\n\n\n\n// It looks like all modern unixes support clock_gettime(..CPUTIME..)\n\n#[cfg(unix)] mod clock_gettime;\n\n#[cfg(windows)] mod windows;\n\n\n\n#[cfg(unix)] pub use clock_gettime::{ProcessTime, ThreadTime};\n\n\n\n#[cfg(windows)] pub use windows::{ProcessTime, ThreadTime};\n", "file_path": "src/lib.rs", "rank": 12, "score": 5.7309010896155606 }, { "content": " }\n\n\n\n /// Returns the amount of CPU time used from the previous timestamp to now.\n\n ///\n\n /// # Panics\n\n ///\n\n /// If `ProcessTime::now()` panics.\n\n pub fn elapsed(&self) -> Duration {\n\n Self::now().duration_since(*self)\n\n }\n\n\n\n /// Returns the amount of CPU time used from the previous timestamp.\n\n pub fn duration_since(&self, timestamp: Self) -> Duration {\n\n self.0 - timestamp.0\n\n }\n\n\n\n /// Returns the total amount of CPU time used from the program start.\n\n pub fn as_duration(&self) -> Duration {\n\n self.0\n\n }\n", "file_path": "src/windows.rs", "rank": 13, "score": 4.957642442876411 }, { "content": " }\n\n\n\n /// Get current CPU time used by a process\n\n ///\n\n /// # Panics\n\n ///\n\n /// If GetProcessTimes fails. This may happen, for instance, in case of\n\n /// insufficient permissions.\n\n ///\n\n /// See [this MSDN page][msdn] for details. If you prefer to handle such errors, consider\n\n /// using `try_now`.\n\n ///\n\n /// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getprocesstimes\n\n pub fn now() -> Self {\n\n Self::try_now().expect(\"GetProcessTimes failed\")\n\n }\n\n\n\n /// Returns the amount of CPU time used from the previous timestamp to now.\n\n pub fn try_elapsed(&self) -> Result<Duration> {\n\n Ok(Self::try_now()?.duration_since(*self))\n", "file_path": "src/windows.rs", "rank": 14, "score": 4.945114580850572 }, { "content": " /// If `ThreadTime::now()` panics.\n\n pub fn elapsed(&self) -> Duration {\n\n Self::now().duration_since(*self)\n\n }\n\n\n\n /// Returns the amount of CPU time used by the current thread\n\n /// from the previous timestamp.\n\n pub fn duration_since(&self, timestamp: ThreadTime) -> Duration {\n\n self.0 - timestamp.0\n\n }\n\n\n\n /// Returns the total amount of CPU time used from the program start.\n\n pub fn as_duration(&self) -> Duration {\n\n self.0\n\n }\n\n}\n", "file_path": "src/windows.rs", "rank": 15, "score": 4.931593749022355 }, { "content": " /// If GetThreadTimes fails. This may happen, for instance, in case of\n\n /// insufficient permissions.\n\n ///\n\n /// See [this MSDN page][msdn] for details. If you prefer to handle such errors, consider\n\n /// using `try_now`.\n\n ///\n\n /// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreadtimes\n\n pub fn now() -> Self {\n\n Self::try_now().expect(\"GetThreadTimes failed\")\n\n }\n\n\n\n /// Returns the amount of CPU time used from the previous timestamp to now.\n\n pub fn try_elapsed(&self) -> Result<Duration> {\n\n Ok(Self::try_now()?.duration_since(*self))\n\n }\n\n\n\n /// Returns the amount of CPU time used from the previous timestamp to now.\n\n ///\n\n /// # Panics\n\n ///\n", "file_path": "src/windows.rs", "rank": 16, "score": 4.892748912309489 }, { "content": "//! CPU Time Measurement Library\n\n//! ============================\n\n//!\n\n//! [Documentation](https://docs.rs/cpu-time) |\n\n//! [Github](https://github.com/tailhook/cpu-time) |\n\n//! [Crate](https://crates.io/crates/cpu-time)\n\n//!\n\n//! # Example\n\n//!\n\n//! ```rust\n\n//!\n\n//! use std::time::Duration;\n\n//! use cpu_time::ProcessTime;\n\n//!\n\n//! // Manually handle errors\n\n//! let start = ProcessTime::try_now().expect(\"Getting process time failed\");\n\n//! // .. do something ..\n\n//! let cpu_time: Duration = start.try_elapsed().expect(\"Getting process time failed\");;\n\n//! println!(\" {:?}\", cpu_time);\n\n//!\n", "file_path": "src/lib.rs", "rank": 20, "score": 4.062668082141 } ]
Rust
cli/src/opts.rs
djKooks/Viceroy
6462271f1c9176f79ac059cc87bfdde61d65ac62
use { std::net::{IpAddr, Ipv4Addr}, std::{ net::SocketAddr, path::{Path, PathBuf}, }, structopt::StructOpt, viceroy_lib::Error, }; #[derive(Debug, StructOpt)] #[structopt(name = "viceroy", author)] pub struct Opts { #[structopt(long = "addr")] socket_addr: Option<SocketAddr>, #[structopt(parse(try_from_str = check_module))] input: PathBuf, #[structopt(short = "C", long = "config")] config_path: Option<PathBuf>, #[structopt(long = "log-stdout")] log_stdout: bool, #[structopt(long = "log-stderr")] log_stderr: bool, #[structopt(short = "v", parse(from_occurrences))] verbosity: usize, } impl Opts { pub fn addr(&self) -> SocketAddr { self.socket_addr .unwrap_or_else(|| SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7878)) } pub fn input(&self) -> &Path { self.input.as_ref() } pub fn config_path(&self) -> Option<&Path> { self.config_path.as_deref() } pub fn log_stdout(&self) -> bool { self.log_stdout } pub fn log_stderr(&self) -> bool { self.log_stderr } pub fn verbosity(&self) -> usize { self.verbosity } } fn check_module(s: &str) -> Result<PathBuf, Error> { let path = PathBuf::from(s); let contents = std::fs::read(&path)?; match wat::parse_bytes(&contents) { Ok(_) => Ok(path), _ => Err(Error::FileFormat), } } #[cfg(test)] mod opts_tests { use { super::Opts, std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, std::path::PathBuf, structopt::{ clap::{Error, ErrorKind}, StructOpt, }, }; fn test_file(name: &str) -> String { let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("tests") .join("wasm"); path.push(name); assert!(path.exists(), "test file does not exist"); path.into_os_string().into_string().unwrap() } type TestResult = Result<(), anyhow::Error>; #[test] fn default_addr_works() -> TestResult { let empty_args = &["dummy-program-name", &test_file("minimal.wat")]; let opts = Opts::from_iter_safe(empty_args)?; let expected = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7878); assert_eq!(opts.addr(), expected); Ok(()) } #[test] fn invalid_addrs_are_rejected() -> TestResult { let args_with_bad_addr = &[ "dummy-program-name", "--addr", "999.0.0.1:7878", &test_file("minimal.wat"), ]; match Opts::from_iter_safe(args_with_bad_addr) { Err(Error { kind: ErrorKind::ValueValidation, message, .. }) if message.contains("invalid IP address syntax") => Ok(()), res => panic!("unexpected result: {:?}", res), } } #[test] fn ipv6_addrs_are_accepted() -> TestResult { let args_with_ipv6_addr = &[ "dummy-program-name", "--addr", "[::1]:7878", &test_file("minimal.wat"), ]; let opts = Opts::from_iter_safe(args_with_ipv6_addr)?; let addr_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); let expected = SocketAddr::new(addr_v6, 7878); assert_eq!(opts.addr(), expected); Ok(()) } #[test] fn nonexistent_file_is_rejected() -> TestResult { let args_with_nonexistent_file = &["dummy-program-name", "path/to/a/nonexistent/file"]; match Opts::from_iter_safe(args_with_nonexistent_file) { Err(Error { kind: ErrorKind::ValueValidation, message, .. }) if message.contains("No such file or directory") || message.contains("cannot find the path specified") => { Ok(()) } res => panic!("unexpected result: {:?}", res), } } #[test] fn invalid_file_is_rejected() -> TestResult { let args_with_invalid_file = &["dummy-program-name", &test_file("invalid.wat")]; let expected_msg = format!("{}", viceroy_lib::Error::FileFormat); match Opts::from_iter_safe(args_with_invalid_file) { Err(Error { kind: ErrorKind::ValueValidation, message, .. }) if message.contains(&expected_msg) => Ok(()), res => panic!("unexpected result: {:?}", res), } } #[test] fn text_format_is_accepted() -> TestResult { let args = &["dummy-program-name", &test_file("minimal.wat")]; match Opts::from_iter_safe(args) { Ok(_) => Ok(()), res => panic!("unexpected result: {:?}", res), } } #[test] fn binary_format_is_accepted() -> TestResult { let args = &["dummy-program-name", &test_file("minimal.wasm")]; match Opts::from_iter_safe(args) { Ok(_) => Ok(()), res => panic!("unexpected result: {:?}", res), } } }
use { std::net::{IpAddr, Ipv4Addr}, std::{ net::SocketAddr, path::{Path, PathBuf}, }, structopt::StructOpt, viceroy_lib::Error, }; #[derive(Debug, StructOpt)] #[structopt(name = "viceroy", author)] pub struct Opts { #[structopt(long = "addr")] socket_addr: Option<SocketAddr>, #[structopt(parse(try_from_str = check_module))] input: PathBuf, #[structopt(short = "C", long = "config")] config_path: Option<PathBuf>, #[structopt(long = "log-stdout")] log_stdout: bool, #[structopt(long = "log-stderr")] log_stderr: bool, #[structopt(short = "v", parse(from_occurrences))] verbosity: usize, } impl Opts { pub fn addr(&self) -> SocketAddr { self.socket_addr .unwrap_or_else(|| SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7878)) } pub fn input(&self) -> &Path { self.input.as_ref() } pub fn config_path(&self) -> Option<&Path> { self.config_path.as_deref() } pub fn log_stdout(&self) -> bool { self.log_stdout } pub fn log_stderr(&self) -> bool { self.log_stderr } pub fn verbosity(&self) -> usize { self.verbosity } } fn check_module(s: &str) -> Result<PathBuf, Error> { let path = PathBuf::from(s); let contents = std::fs::read(&path)?; match wat::parse_bytes(&contents) { Ok(_) => Ok(path), _ => Err(Error::FileFormat), } } #[cfg(test)] mod opts_tests { use { super::Opts, std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, std::path::PathBuf, structopt::{ clap::{Error, ErrorKind}, StructOpt, }, }; fn test_file(name: &str) -> String { let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("tests") .join("wasm"); path.push(name); assert!(path.exists(), "test file does not exist"); path.into_os_string().into_string().unwrap() } type TestResult = Result<(), anyhow::Error>; #[test] fn default_addr_works() -> TestResult { let empty_args = &["dummy-program-name", &test_file("minimal.wat")]; let opts = Opts::from_iter_safe(empty_args)?; let expected = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7878); assert_eq!(opts.addr(), expected); Ok(()) } #[test] fn invalid_addrs_are_rejected() -> TestResult { let args_with_bad_addr = &[ "dummy-program-name", "--addr", "999.0.0.1:7878", &test_file("minimal.wat"), ]; match Opts::from_iter_safe(args_with_bad_addr) { Err(Error { kind: ErrorKind::ValueValidation, message, .. }) if message.contains("invalid IP address syntax") => Ok(()), res => panic!("unexpected result: {:?}", res), } } #[test] fn ipv6_addrs_are_accepted() -> TestResult { let args_with_ipv6_addr = &[ "dummy-program-name", "--addr", "[::1]:7878", &test_file("minimal.wat"), ]; let opts = Opts::from_iter_safe(args_with_ipv6_addr)?; let addr_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); let expected = SocketAddr::new(addr_v6, 7878); assert_eq!(opts.addr(), expected); Ok(()) } #[test] fn nonexistent_file_is_rejected() -> TestResult { let args_with_nonexistent_file = &["dummy-program-name", "path/to/a/nonexistent/file"]; match Opts::from_iter_safe(args_with_nonexistent_file) { Err(Error { kind: ErrorKind::ValueValidation, message, .. }) if message.contains("No such file or directory") || message.contains("cannot find the path specified") => { Ok(()) } res => panic!("unexpected result: {:?}", res), } } #[test] fn invalid_file_is_rejected() -> TestResult { let args_with_invalid_file = &["dummy-program-name", &test_file("invalid.wat")]; let expected_msg = format!("{}", viceroy_lib::Error::FileFormat); match Opts::from_iter_safe(args_with_invalid_file) { Err(Error { kind: ErrorKind::ValueValidation, message, .. }) if message.contains(&expected_msg) => Ok(()), res => panic!("unexpected result: {:?}", res), } } #[test] fn text_format_is_accepted() -> TestResult { let arg
#[test] fn binary_format_is_accepted() -> TestResult { let args = &["dummy-program-name", &test_file("minimal.wasm")]; match Opts::from_iter_safe(args) { Ok(_) => Ok(()), res => panic!("unexpected result: {:?}", res), } } }
s = &["dummy-program-name", &test_file("minimal.wat")]; match Opts::from_iter_safe(args) { Ok(_) => Ok(()), res => panic!("unexpected result: {:?}", res), } }
function_block-function_prefixed
[]
Rust
src/xor_repair.rs
sc2021anonym/slp-ec
e8afdff36311f4897f73b4e6c1593b8211e10282
use crate::bitmatrix::*; use crate::fast_repair::SortOrder; use crate::repair::{bitvec_distance, bitvec_xor}; use crate::slp::*; use crate::*; fn replace_by(m: &mut SLP, a: usize, b: usize, v: usize) { for i in 0..m.height() { if m[i][a] && m[i][b] { m[i][a] = false; m[i][b] = false; m[i][v] = true; } } } fn count_occurences2(i: usize, j: usize, slp: &SLP) -> usize { let mut count = 0; for def in 0..slp.height() { if slp[def][i] && slp[def][j] { count += 1 } } count } fn gen_forward_iter(start: usize, end: usize) -> Vec<usize> { (start..end).collect() } fn gen_rev_iter(start: usize, end: usize) -> Vec<usize> { (start..end).rev().collect() } fn build_syntax( valuation: &SLP, goal: &[bool], gen_iter: fn(usize, usize) -> Vec<usize>, ) -> (Vec<bool>, Vec<bool>) { let mut depends: Vec<bool> = vec![false; valuation.height() + valuation.num_of_original_constants()]; let mut rest = goal.to_vec(); loop { let mut which_var = None; let mut current_min = popcount(&rest); for var in gen_iter(0, valuation.height()) { let value = &valuation[var]; let count = bitvec_distance(&value, &rest); if count < current_min { which_var = Some(var); current_min = count; } } if let Some(var) = which_var { depends[valuation.num_of_original_constants() + var] = true; rest = bitvec_xor(&rest, &valuation[var]); } else { for idx in 0..rest.len() { if rest[idx] { depends[idx] = true; } } break; } } (depends, rest) } fn xor_pair_finder( valuation: &SLP, slp: &SLP, program: &mut SLP, gen_iter: fn(usize, usize) -> Vec<usize>, order: &SortOrder, ) -> Option<(Term, Term)> { use std::cmp::Ordering; let mut count_max = 0; let mut candidates = Vec::new(); for i in 0..slp.num_of_variables() { let goal = &slp[i]; let (depends, _) = build_syntax(valuation, &goal, gen_iter); if popcount(&depends) < popcount(&program[i]) { program[i] = depends; } } for i in 0..program.width() { for j in i + 1..program.width() { let count = count_occurences2(i, j, &program); match count_max.cmp(&count) { Ordering::Equal => { candidates.push((i, j)); } Ordering::Less => { candidates = vec![(i, j)]; count_max = count; } _ => {} } } } match order { SortOrder::LexSmall => { candidates.sort_by(|(a1, a2), (b1, b2)| a1.cmp(b1).then(a2.cmp(b2))); } SortOrder::LexLarge => { candidates.sort_by(|(a1, a2), (b1, b2)| a1.cmp(b1).then(a2.cmp(b2)).reverse()); } } if let Some((i, j)) = candidates.pop() { Some((valuation.index_to_term(i), valuation.index_to_term(j))) } else { None } } fn get_valuation(valuation: &SLP, left: &Term, right: &Term) -> Vec<bool> { let mut val: Vec<bool> = vec![false; valuation.num_of_original_constants()]; match left { Term::Cst(c) => { val[*c] ^= true; } Term::Var(v) => { val = valuation[*v].clone(); } } match right { Term::Cst(c) => { val[*c] ^= true; } Term::Var(v) => { val = bitvec_xor(&val, &valuation[*v]); } } val } pub fn run_xor_repair_forward(goal: &SLP, order: SortOrder) -> Vec<(Term, Term, Term)> { run_xor_repair(goal, gen_forward_iter, order) } pub fn run_xor_repair_reverse(goal: &SLP, order: SortOrder) -> Vec<(Term, Term, Term)> { run_xor_repair(goal, gen_rev_iter, order) } fn run_xor_repair( goal: &SLP, gen_iter: fn(usize, usize) -> Vec<usize>, order: SortOrder, ) -> Vec<(Term, Term, Term)> { let mut defs = Vec::new(); let mut slp = goal.clone(); let mut program = slp.clone(); let mut valuation = SLP::new( BitMatrix::new(0, goal.num_of_original_constants()), goal.num_of_original_constants(), 0, ); loop { let candidate = xor_pair_finder(&valuation, &slp, &mut program, gen_iter, &order); if let Some((left, right)) = candidate { let fresh = defs.len(); let new_var = Term::Var(fresh); let new_val = get_valuation(&valuation, &left, &right); program.add_column(); { let left = slp.term_to_index(&left); let right = slp.term_to_index(&right); let new = slp.term_to_index(&new_var); replace_by(&mut program, left, right, new); valuation.add_var(new_val); } defs.push((new_var, left, right)); } else { panic!("bug!"); } remove_achieved_goal(&valuation, &mut program, &mut slp); if slp.height() == 0 { return defs; } } } fn remove_achieved_goal(valuation: &SLP, program: &mut SLP, slp: &mut SLP) { let num_of_variables = valuation.height(); let latest_var = &valuation[num_of_variables - 1]; for i in (0..slp.height()).rev() { let val = &slp[i]; if val == latest_var { program.remove_row(i); slp.remove_row(i); break; } } }
use crate::bitmatrix::*; use crate::fast_repair::SortOrder; use crate::repair::{bitvec_distance, bitvec_xor}; use crate::slp::*; use crate::*; fn replace_by(m: &mut SLP, a: usize, b: usize, v: usize) { for i in 0..m.height() { if m[i][a] && m[i][b] { m[i][a] = false; m[i][b] = false; m[i][v] = true; } } } fn count_occurences2(i: usize, j: usize, slp: &SLP) -> usize { let mut count = 0; for def in 0..slp.height() { if slp[def][i] && slp[def][j] { count += 1 } } count } fn gen_forward_iter(start: usize, end: usize) -> Vec<usize> { (start..end).collect() } fn gen_rev_iter(start: usize, end: usize) -> Vec<usize> { (start..end).rev().collect() } fn build_syntax( valuation: &SLP, goal: &[bool], gen_iter: fn(usize, usize) -> Vec<usize>, ) -> (Vec<bool>, Vec<bool>) { let mut depends: Vec<bool> = vec![false; valuation.height() + valuation.num_of_original_constants()]; let mut rest = goal.to_vec(); loop { let mut which_var = None; let mut current_min = popcount(&rest); for var in gen_iter(0, valuation.height()) { let value = &valuation[var]; let count = bitvec_distance(&value, &rest); if count < current_min {
candidates.push((i, j)); } Ordering::Less => { candidates = vec![(i, j)]; count_max = count; } _ => {} } } } match order { SortOrder::LexSmall => { candidates.sort_by(|(a1, a2), (b1, b2)| a1.cmp(b1).then(a2.cmp(b2))); } SortOrder::LexLarge => { candidates.sort_by(|(a1, a2), (b1, b2)| a1.cmp(b1).then(a2.cmp(b2)).reverse()); } } if let Some((i, j)) = candidates.pop() { Some((valuation.index_to_term(i), valuation.index_to_term(j))) } else { None } } fn get_valuation(valuation: &SLP, left: &Term, right: &Term) -> Vec<bool> { let mut val: Vec<bool> = vec![false; valuation.num_of_original_constants()]; match left { Term::Cst(c) => { val[*c] ^= true; } Term::Var(v) => { val = valuation[*v].clone(); } } match right { Term::Cst(c) => { val[*c] ^= true; } Term::Var(v) => { val = bitvec_xor(&val, &valuation[*v]); } } val } pub fn run_xor_repair_forward(goal: &SLP, order: SortOrder) -> Vec<(Term, Term, Term)> { run_xor_repair(goal, gen_forward_iter, order) } pub fn run_xor_repair_reverse(goal: &SLP, order: SortOrder) -> Vec<(Term, Term, Term)> { run_xor_repair(goal, gen_rev_iter, order) } fn run_xor_repair( goal: &SLP, gen_iter: fn(usize, usize) -> Vec<usize>, order: SortOrder, ) -> Vec<(Term, Term, Term)> { let mut defs = Vec::new(); let mut slp = goal.clone(); let mut program = slp.clone(); let mut valuation = SLP::new( BitMatrix::new(0, goal.num_of_original_constants()), goal.num_of_original_constants(), 0, ); loop { let candidate = xor_pair_finder(&valuation, &slp, &mut program, gen_iter, &order); if let Some((left, right)) = candidate { let fresh = defs.len(); let new_var = Term::Var(fresh); let new_val = get_valuation(&valuation, &left, &right); program.add_column(); { let left = slp.term_to_index(&left); let right = slp.term_to_index(&right); let new = slp.term_to_index(&new_var); replace_by(&mut program, left, right, new); valuation.add_var(new_val); } defs.push((new_var, left, right)); } else { panic!("bug!"); } remove_achieved_goal(&valuation, &mut program, &mut slp); if slp.height() == 0 { return defs; } } } fn remove_achieved_goal(valuation: &SLP, program: &mut SLP, slp: &mut SLP) { let num_of_variables = valuation.height(); let latest_var = &valuation[num_of_variables - 1]; for i in (0..slp.height()).rev() { let val = &slp[i]; if val == latest_var { program.remove_row(i); slp.remove_row(i); break; } } }
which_var = Some(var); current_min = count; } } if let Some(var) = which_var { depends[valuation.num_of_original_constants() + var] = true; rest = bitvec_xor(&rest, &valuation[var]); } else { for idx in 0..rest.len() { if rest[idx] { depends[idx] = true; } } break; } } (depends, rest) } fn xor_pair_finder( valuation: &SLP, slp: &SLP, program: &mut SLP, gen_iter: fn(usize, usize) -> Vec<usize>, order: &SortOrder, ) -> Option<(Term, Term)> { use std::cmp::Ordering; let mut count_max = 0; let mut candidates = Vec::new(); for i in 0..slp.num_of_variables() { let goal = &slp[i]; let (depends, _) = build_syntax(valuation, &goal, gen_iter); if popcount(&depends) < popcount(&program[i]) { program[i] = depends; } } for i in 0..program.width() { for j in i + 1..program.width() { let count = count_occurences2(i, j, &program); match count_max.cmp(&count) { Ordering::Equal => {
random
[ { "content": "fn execute_slp_rec(slp: &SLP, var: usize, valuation: &mut HashMap<usize, Vec<bool>>) {\n\n if valuation.contains_key(&var) {\n\n // already visited\n\n return;\n\n }\n\n\n\n let num_constants = slp.num_of_original_constants();\n\n let mut val: Vec<bool> = vec![false; num_constants];\n\n\n\n let depends: &Vec<bool> = &slp[var];\n\n\n\n for (idx, b) in depends.iter().enumerate() {\n\n if *b {\n\n if idx < num_constants {\n\n val[idx] ^= true;\n\n } else {\n\n let depending_var = idx - num_constants;\n\n\n\n if !valuation.contains_key(&depending_var) {\n\n execute_slp_rec(slp, depending_var, valuation);\n", "file_path": "src/repair.rs", "rank": 0, "score": 280609.0370567966 }, { "content": "fn replace_by(m: &mut SLP, a: usize, b: usize, v: usize) {\n\n for i in 0..m.height() {\n\n if m[i][a] && m[i][b] {\n\n m[i][a] = false;\n\n m[i][b] = false;\n\n m[i][v] = true;\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/fast_repair.rs", "rank": 2, "score": 225574.75634520003 }, { "content": "pub fn var_size(var: &[bool]) -> usize {\n\n let count = popcount(var);\n\n if count <= 2 {\n\n 1\n\n } else {\n\n count - 1\n\n }\n\n}\n", "file_path": "src/slp.rs", "rank": 4, "score": 224704.533398538 }, { "content": "pub fn num_of_xor(var: &[bool]) -> usize {\n\n let count = popcount(var);\n\n assert!(count >= 1);\n\n count - 1\n\n}\n\n\n\n#[derive(Eq, PartialEq, Clone, Debug)]\n\n#[allow(clippy::upper_case_acronyms)]\n\npub struct SLP {\n\n pub repr: BitMatrix,\n\n pub num_of_variables: usize, // num of original variables\n\n pub num_of_constants: usize, // num of original constants\n\n}\n\n\n\nimpl Index<usize> for SLP {\n\n type Output = Vec<bool>;\n\n fn index(&self, index: usize) -> &Self::Output {\n\n &self.repr[index]\n\n }\n\n}\n", "file_path": "src/slp.rs", "rank": 5, "score": 213622.15978312163 }, { "content": "fn build_syntax(valuation: &HashMap<usize, Vec<bool>>, goal: &[bool]) -> (Vec<Term>, Vec<bool>) {\n\n let mut syntax: Vec<Term> = Vec::new();\n\n\n\n let mut goal = goal.to_vec();\n\n\n\n loop {\n\n let mut which_var = None;\n\n // let mut current_min = var_size(&goal);\n\n let mut current_min = popcount(&goal);\n\n\n\n for var in (0..valuation.keys().count()).rev() {\n\n let value = &valuation[&var];\n\n let count = bitvec_distance(&value, &goal);\n\n\n\n if count < current_min {\n\n which_var = Some(var);\n\n current_min = count;\n\n }\n\n }\n\n\n", "file_path": "src/repair.rs", "rank": 6, "score": 210054.46995940694 }, { "content": "fn count_occurences2(i: usize, j: usize, slp: &SLP) -> usize {\n\n let mut count = 0;\n\n for def in 0..slp.height() {\n\n if slp[def][i] && slp[def][j] {\n\n count += 1\n\n }\n\n }\n\n count\n\n}\n\n\n\n#[derive(Debug, Clone, Copy)]\n\npub enum SortOrder {\n\n LexSmall,\n\n LexLarge,\n\n}\n\n\n", "file_path": "src/fast_repair.rs", "rank": 8, "score": 202261.2519453239 }, { "content": "// https://en.wikipedia.org/wiki/Iverson_bracket\n\nfn iverson(b: bool) -> usize {\n\n if b {\n\n 1\n\n } else {\n\n 0\n\n }\n\n}\n\n\n", "file_path": "src/stat.rs", "rank": 9, "score": 173103.87815459882 }, { "content": "pub fn all_stat(original_slp: &slp::SLP, compress: bool) {\n\n let shrinked_slp = for_benchmark::shrink(original_slp);\n\n\n\n if shrinked_slp.is_empty() {\n\n println!(\"This is a trivial case: We need no computation, and there is no statistics\");\n\n return;\n\n }\n\n\n\n let slp = if compress {\n\n for_benchmark::xor_repair(&shrinked_slp)\n\n } else {\n\n shrinked_slp.to_trivial_graph()\n\n };\n\n\n\n let (orig_stat, _) = for_benchmark::graph_analyze(&shrinked_slp, &slp);\n\n let xor_num = orig_stat.nr_xors;\n\n let base_mem_num = orig_stat.nr_memacc;\n\n let naive_page = orig_stat.nr_page_transfer;\n\n\n\n let (fusion_stat, _) = for_benchmark::bench_fusion(&shrinked_slp, &slp);\n", "file_path": "src/comparison.rs", "rank": 10, "score": 167276.15607057518 }, { "content": "#[allow(non_snake_case)]\n\npub fn check_sub_SLP(sub: &SLP, sup: &SLP) -> bool {\n\n if sub.num_of_variables() > sup.num_of_variables() {\n\n return false;\n\n }\n\n\n\n for var in 0..sub.num_of_variables() {\n\n if sub[var] != sup[var] {\n\n return false;\n\n }\n\n }\n\n\n\n true\n\n}\n", "file_path": "src/optimize_slp.rs", "rank": 11, "score": 165735.0053402803 }, { "content": "pub fn popcount(v: &[bool]) -> usize {\n\n let mut count = 0;\n\n for b in v {\n\n if *b {\n\n count += 1;\n\n }\n\n }\n\n count\n\n}\n\n\n\nimpl BitMatrix {\n\n pub fn new(height: usize, width: usize) -> Self {\n\n let mut inner = Vec::new();\n\n\n\n for _ in 0..height {\n\n inner.push(vec![false; width]);\n\n }\n\n\n\n BitMatrix { inner }\n\n }\n", "file_path": "src/bitmatrix.rs", "rank": 12, "score": 164452.0760009198 }, { "content": "pub fn slp_to_valuation(slp: &SLP) -> Valuation {\n\n let mut valuation = Valuation::new();\n\n\n\n for v in 0..slp.num_of_variables() {\n\n let val = consts_to_val(&slp[v]);\n\n\n\n valuation.insert(Term::Var(v), val);\n\n }\n\n\n\n valuation\n\n}\n\n\n", "file_path": "src/validation.rs", "rank": 13, "score": 163939.90920724176 }, { "content": "pub fn is_ssa(slp: &Graph) -> bool {\n\n let mut map: BTreeSet<Term> = BTreeSet::new();\n\n\n\n for (target, _, _) in slp {\n\n if map.contains(target) {\n\n // we try to define one already defined\n\n return false;\n\n }\n\n map.insert(target.clone());\n\n }\n\n true\n\n}\n\n\n", "file_path": "src/fusion.rs", "rank": 15, "score": 159018.20340458176 }, { "content": "fn consts_to_val(v: &[bool]) -> BTreeSet<Term> {\n\n let mut set = BTreeSet::new();\n\n\n\n for (idx, val) in v.iter().enumerate() {\n\n if *val {\n\n set.insert(Term::Cst(idx));\n\n }\n\n }\n\n\n\n set\n\n}\n\n\n", "file_path": "src/validation.rs", "rank": 16, "score": 153478.185025968 }, { "content": "// Does slp_a \\models slp_b ??\n\n// return None if slp_a does not \\models slp_b\n\n// otherwise, if (x, y) in realize(...) then x of slp_a = y of slp_b\n\npub fn realizes(slp_a: &SLP, slp_b: &SLP) -> Option<Vec<(usize, usize)>> {\n\n let mut mapping = Vec::new();\n\n\n\n for var_b in 0..slp_b.num_of_variables() {\n\n let value_b = &slp_b[var_b];\n\n\n\n let mut found = false;\n\n for var_a in 0..slp_a.num_of_variables() {\n\n let value_a = &slp_a[var_a];\n\n\n\n if value_a == value_b {\n\n mapping.push((var_a, var_b));\n\n found = true;\n\n break;\n\n }\n\n }\n\n if !found {\n\n return None;\n\n }\n\n }\n\n\n\n Some(mapping)\n\n}\n", "file_path": "src/repair.rs", "rank": 17, "score": 147197.67032141978 }, { "content": "pub fn multislp_to_valuation(slp: &MultiSLP) -> Valuation {\n\n let mut valuation = Valuation::new();\n\n\n\n for (t, set) in slp {\n\n let mut val = BTreeSet::new();\n\n for e in set {\n\n let v = get_val(&valuation, e);\n\n val = xor_set(&val, &v);\n\n }\n\n valuation.insert(t.clone(), val);\n\n }\n\n\n\n valuation\n\n}\n\n\n", "file_path": "src/validation.rs", "rank": 18, "score": 146796.86814097644 }, { "content": "pub fn bitvec_xor(v1: &[bool], v2: &[bool]) -> Vec<bool> {\n\n debug_assert_eq!(v1.len(), v2.len());\n\n\n\n let mut v = vec![false; v1.len()];\n\n for i in 0..v1.len() {\n\n v[i] = v1[i] ^ v2[i];\n\n }\n\n v\n\n}\n\n\n", "file_path": "src/repair.rs", "rank": 19, "score": 142962.45913158648 }, { "content": "pub fn bitvec_distance(v1: &[bool], v2: &[bool]) -> usize {\n\n debug_assert_eq!(v1.len(), v2.len());\n\n\n\n let mut count = 0;\n\n\n\n for i in 0..v1.len() {\n\n if v1[i] != v2[i] {\n\n count += 1;\n\n }\n\n }\n\n\n\n count\n\n}\n\n\n", "file_path": "src/repair.rs", "rank": 20, "score": 138104.4952490922 }, { "content": "pub fn number_of_access2(slp: &MultiSLP) -> usize {\n\n let mut number = 0;\n\n\n\n for (_, value) in slp {\n\n number += 1 + value.len();\n\n }\n\n\n\n number\n\n}\n\n\n", "file_path": "src/fusion.rs", "rank": 21, "score": 135457.94199346926 }, { "content": "pub fn fusion(forest: &mut Forest, targets: &Vec<Term>) -> bool {\n\n let terms: Vec<Term> = forest.keys().cloned().collect();\n\n\n\n for x in terms {\n\n // if target <- x + ... and\n\n // x is just used once,\n\n // we expand it as target <- defs(x) + ...\n\n\n\n // if target is goal, we do not nothing.\n\n if targets.contains(&x) {\n\n continue;\n\n }\n\n\n\n if let Some(target) = expandable(forest, &x) {\n\n let l1 = forest.get(&target).unwrap().len();\n\n let l2 = forest.get(&x).unwrap().len();\n\n if l1 - 1 + l2 >= 8 {\n\n // continue;\n\n }\n\n let mut v = forest.remove(&x).unwrap();\n\n let defs = forest.get_mut(&target).unwrap();\n\n defs.remove(&x);\n\n defs.append(&mut v);\n\n return true;\n\n }\n\n }\n\n false\n\n}\n\n\n", "file_path": "src/fusion.rs", "rank": 22, "score": 135106.89923794838 }, { "content": "pub fn run_repair_trivial(goal: &SLP) -> Vec<(Term, Term, Term)> {\n\n run_repair(goal, repair_trivial)\n\n}\n\n\n", "file_path": "src/repair.rs", "rank": 23, "score": 133981.66931358352 }, { "content": "pub fn run_repair_long(goal: &SLP) -> Vec<(Term, Term, Term)> {\n\n run_repair(goal, repair_long)\n\n}\n\n\n", "file_path": "src/repair.rs", "rank": 24, "score": 133981.66931358352 }, { "content": "pub fn run_repair_distance(goal: &SLP) -> Vec<(Term, Term, Term)> {\n\n run_repair(goal, repair_distance)\n\n}\n\n\n", "file_path": "src/repair.rs", "rank": 25, "score": 133981.66931358352 }, { "content": "pub fn step1(slp: &SLP) -> SLP {\n\n // renaming vec\n\n // (shrinked_pos, original_pos) \\in v\n\n let mut v: Vec<(usize, usize)> = Vec::new();\n\n\n\n // non-trivial rows\n\n let mut bitmatrix: Vec<Vec<bool>> = Vec::new();\n\n\n\n for i in 0..slp.num_of_variables() {\n\n let def = &slp[i];\n\n if popcount(&def) > 1 {\n\n let current = bitmatrix.len();\n\n v.push((current, i));\n\n bitmatrix.push(def.clone());\n\n }\n\n }\n\n\n\n let num_of_variables = bitmatrix.len();\n\n let num_of_constants = if bitmatrix.is_empty() {\n\n 0\n", "file_path": "src/optimize_slp.rs", "rank": 26, "score": 131728.1744661376 }, { "content": "pub fn execute_slp(slp: &SLP) -> SLP {\n\n let mut valuation: HashMap<usize, Vec<bool>> = HashMap::new();\n\n let mut bitmatrix: Vec<Vec<bool>> = Vec::new();\n\n\n\n for i in 0..slp.num_of_variables() {\n\n execute_slp_rec(&slp, i, &mut valuation);\n\n bitmatrix.push(valuation[&i].clone());\n\n }\n\n\n\n let bitmatrix = BitMatrix::from_nested_vecs(bitmatrix);\n\n SLP::build_from_bitmatrix_not_depending_variables(&bitmatrix)\n\n}\n\n\n", "file_path": "src/repair.rs", "rank": 27, "score": 131728.1744661376 }, { "content": "pub fn is_strict_subvaluation(v1: &Valuation, v2: &Valuation) -> bool {\n\n for (var, val) in v1 {\n\n if val != v2.get(var).unwrap() {\n\n return false;\n\n }\n\n }\n\n true\n\n}\n", "file_path": "src/validation.rs", "rank": 30, "score": 129807.29260814258 }, { "content": "pub fn cache_misses_multislp_computation(slp: &MultiSLP) -> usize {\n\n cache_misses_pebble_computation(&multi_slp_to_pebble_computation(slp))\n\n}\n\n\n", "file_path": "src/reorder.rs", "rank": 31, "score": 129372.79094262753 }, { "content": "fn u8vec_to_bitvec(v: &[u8]) -> Vec<bool> {\n\n let mut bitv = Vec::new();\n\n\n\n for u in v {\n\n bitv.append(&mut u8_to_bitvec(*u));\n\n }\n\n\n\n bitv\n\n}\n\n\n", "file_path": "src/rsv_bitmatrix.rs", "rank": 32, "score": 128270.92834755781 }, { "content": "fn run_repair(goal: &SLP, pair_finder: PairFinder) -> Vec<(Term, Term, Term)> {\n\n let mut defs = Vec::new();\n\n let slp = goal.clone();\n\n\n\n let mut program = Vec::new();\n\n\n\n for i in 0..slp.num_of_variables() {\n\n let (def, _) = build_syntax(&HashMap::new(), &slp[i]);\n\n program.push(def);\n\n }\n\n\n\n loop {\n\n let pair = pair_finder(&program, defs.len(), &slp);\n\n\n\n if let Some((left, right)) = pair {\n\n let fresh = defs.len();\n\n let new_v = Term::Var(fresh);\n\n // println!(\"add {:?} <- {:?} + {:?}\", new_v, left, right);\n\n replace_program(&mut program, &left, &right, &new_v);\n\n defs.push((new_v, left, right));\n", "file_path": "src/repair.rs", "rank": 33, "score": 126470.93888909041 }, { "content": "pub fn shrink(original_slp: &SLP) -> SLP {\n\n optimize_slp::step1(original_slp)\n\n}\n\n\n", "file_path": "src/for_benchmark.rs", "rank": 34, "score": 124278.81555642428 }, { "content": "pub fn bitvec_to_intvec(bv: &[bool]) -> Vec<usize> {\n\n let mut v = vec![0; bv.len()];\n\n\n\n for (idx, b) in bv.iter().enumerate() {\n\n if *b {\n\n v[idx] = 1;\n\n } else {\n\n v[idx] = 0;\n\n }\n\n }\n\n\n\n v\n\n}\n\n\n", "file_path": "src/repair.rs", "rank": 35, "score": 123628.03247292731 }, { "content": "pub fn repair_comparison(slp: &SLP) {\n\n use crate::fast_repair::{self, SortOrder};\n\n use crate::xor_repair;\n\n\n\n let shrinked_slp = for_benchmark::shrink(slp);\n\n\n\n if slp.is_empty() {\n\n return;\n\n }\n\n\n\n let nr_original = shrinked_slp.to_trivial_graph().len();\n\n\n\n let nr_xor1 = fast_repair::run_repair2(&shrinked_slp, SortOrder::LexSmall).len();\n\n let nr_xor2 = fast_repair::run_repair2(&shrinked_slp, SortOrder::LexLarge).len();\n\n\n\n let nr_xor3 = xor_repair::run_xor_repair_forward(&shrinked_slp, SortOrder::LexSmall).len();\n\n let nr_xor4 = xor_repair::run_xor_repair_reverse(&shrinked_slp, SortOrder::LexSmall).len();\n\n\n\n let nr_xor5 = xor_repair::run_xor_repair_forward(&shrinked_slp, SortOrder::LexLarge).len();\n\n let nr_xor6 = xor_repair::run_xor_repair_reverse(&shrinked_slp, SortOrder::LexLarge).len();\n\n\n\n println!(\"Original = {} => R(<) = {}, R(>) = {}, X(<, <) = {}, X(<, >) = {}, X(>, <) = {}, X(>, >) = {}\",\n\n nr_original, nr_xor1, nr_xor2, nr_xor3, nr_xor4, nr_xor5, nr_xor6);\n\n}\n\n\n", "file_path": "src/comparison.rs", "rank": 36, "score": 123067.92496638784 }, { "content": "pub fn compress_stat(original_slp: &slp::SLP) {\n\n let shrinked_slp = for_benchmark::shrink(original_slp);\n\n\n\n if shrinked_slp.is_empty() {\n\n println!(\"This is a trivial case: We need no computation, and there is no statistics\");\n\n return;\n\n }\n\n\n\n let slp = shrinked_slp.to_trivial_graph();\n\n let (stat, _) = for_benchmark::graph_analyze(&shrinked_slp, &slp);\n\n let slp_xor_num = stat.nr_xors;\n\n\n\n let repaired_slp = for_benchmark::repair(&shrinked_slp);\n\n let (stat, _) = for_benchmark::graph_analyze(&shrinked_slp, &repaired_slp);\n\n let repaired_xor_num = stat.nr_xors;\n\n\n\n let xor_repaired_slp = for_benchmark::xor_repair(&shrinked_slp);\n\n let (stat, _) = for_benchmark::graph_analyze(&shrinked_slp, &xor_repaired_slp);\n\n let xor_repaired_xor_num = stat.nr_xors;\n\n\n\n println!(\n\n \" [NoComp] #XOR = {}, [RePair] #XOR = {}, [XorRePair] #XOR = {}\",\n\n slp_xor_num, repaired_xor_num, xor_repaired_xor_num\n\n );\n\n}\n\n\n", "file_path": "src/comparison.rs", "rank": 37, "score": 122172.18004209168 }, { "content": "pub fn sec75_stat(original_slp: &slp::SLP) {\n\n let shrinked_slp = for_benchmark::shrink(original_slp);\n\n\n\n if shrinked_slp.is_empty() {\n\n println!(\"This is a trivial case: We need no computation, and there is no statistics\");\n\n return;\n\n }\n\n\n\n // no compression\n\n let slp = shrinked_slp.to_trivial_graph();\n\n let (orig, _) = for_benchmark::graph_analyze(&shrinked_slp, &slp);\n\n\n\n let compressed = for_benchmark::xor_repair(&shrinked_slp);\n\n let (comp, _) = for_benchmark::graph_analyze(&shrinked_slp, &compressed);\n\n\n\n let (fusion, _) = for_benchmark::bench_fusion(&shrinked_slp, &compressed);\n\n\n\n let (_, _, _, sched, _) = for_benchmark::bench_pebble(&shrinked_slp, &compressed);\n\n\n\n println!(\" P Co(P) Fu(Co(P)) Dfs(Fu(Co(P)))\");\n", "file_path": "src/comparison.rs", "rank": 38, "score": 122172.18004209168 }, { "content": "pub fn run_repair2(goal: &SLP, sort_order: SortOrder) -> Vec<(Term, Term, Term)> {\n\n let mut defs = Vec::new();\n\n let slp = goal.clone();\n\n\n\n let mut program = slp.clone();\n\n\n\n loop {\n\n let pair = pair_finder2(&slp, &program, &sort_order);\n\n\n\n if let Some((left, right)) = pair {\n\n let fresh = defs.len();\n\n let new_var = Term::Var(fresh);\n\n // println!(\"add {:?} <- {:?} + {:?}\", new_v, left, right);\n\n program.add_column();\n\n {\n\n let left = slp.term_to_index(&left);\n\n let right = slp.term_to_index(&right);\n\n let new = slp.term_to_index(&new_var);\n\n replace_by(&mut program, left, right, new);\n\n }\n", "file_path": "src/fast_repair.rs", "rank": 39, "score": 119793.48329627563 }, { "content": "fn calc_candidates(dag: &DAG, alloc: &Alloc) -> Vec<(Term, bool, usize, usize)> {\n\n // (term, ready?, #hot, #children)\n\n let mut summary = Vec::new();\n\n\n\n for (t, children) in dag {\n\n let mut ready = true;\n\n let mut hot = 0;\n\n for c in children {\n\n if c.is_const() || alloc.get(c).is_some() {\n\n if alloc.is_hot(c) {\n\n hot += 1;\n\n }\n\n } else {\n\n ready = false;\n\n }\n\n }\n\n if !ready {\n\n summary.push((t.clone(), false, 0, 0));\n\n } else {\n\n summary.push((t.clone(), true, hot, children.len()));\n\n }\n\n }\n\n\n\n summary\n\n}\n\n\n", "file_path": "src/reorder2.rs", "rank": 42, "score": 116196.41263484428 }, { "content": "fn get_val(v: &Valuation, term: &Term) -> BTreeSet<Term> {\n\n if term.is_const() {\n\n BTreeSet::from_iter(vec![term.clone()])\n\n } else {\n\n v.get(term).unwrap().clone()\n\n }\n\n}\n\n\n", "file_path": "src/validation.rs", "rank": 43, "score": 116125.62978019274 }, { "content": "pub fn repair(shrinked_slp: &SLP) -> Graph {\n\n fast_repair::run_repair2(&shrinked_slp, SortOrder::LexSmall)\n\n}\n\n\n", "file_path": "src/for_benchmark.rs", "rank": 44, "score": 110505.69778955227 }, { "content": "pub fn to_ssa(shrinked_slp: &SLP) -> Graph {\n\n let shrinked_program = shrinked_slp.to_trivial_graph();\n\n\n\n fusion::slp_to_ssa(&shrinked_program)\n\n}\n\n\n", "file_path": "src/for_benchmark.rs", "rank": 45, "score": 110505.69778955227 }, { "content": "fn check_runnable(program: &Vec<(Pebble, Vec<Pebble>)>, capacity: usize) -> bool {\n\n let mut visited = BTreeSet::<Pebble>::new();\n\n let mut ru = reorder::RecentlyUse::new();\n\n\n\n // println!(\"trying... {}\", capacity);\n\n\n\n for (t, vars) in program {\n\n for v in vars {\n\n if visited.contains(v) && !ru.is_in(v, capacity) {\n\n return false;\n\n }\n\n ru.access(v.clone());\n\n visited.insert(v.clone());\n\n }\n\n ru.access(t.clone());\n\n visited.insert(t.clone());\n\n }\n\n\n\n true\n\n}\n", "file_path": "src/stat.rs", "rank": 46, "score": 109366.40998445627 }, { "content": "pub fn rename(var_a: usize, var_b: usize, term: &Term) -> Option<Term> {\n\n match term {\n\n Term::Cst(_) => None,\n\n Term::Var(v) => {\n\n if *v == var_a {\n\n Some(Term::Var(var_b))\n\n } else {\n\n None\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/renaming.rs", "rank": 47, "score": 108381.86642635307 }, { "content": "type PairFinder = fn(&[Vec<Term>], usize, &SLP) -> Option<(Term, Term)>;\n\n\n", "file_path": "src/repair.rs", "rank": 48, "score": 108308.68335385772 }, { "content": "pub fn xor_repair(shrinked_slp: &SLP) -> Graph {\n\n xor_repair::run_xor_repair_reverse(&shrinked_slp, SortOrder::LexSmall)\n\n}\n\n\n", "file_path": "src/for_benchmark.rs", "rank": 49, "score": 108270.2517380898 }, { "content": "pub fn multislp_to_dag(slp: &MultiSLP) -> DAG {\n\n let mut dag = DAG::new();\n\n\n\n for (t, children) in slp {\n\n dag.insert(t.clone(), children.clone());\n\n }\n\n\n\n dag\n\n}\n\n\n", "file_path": "src/reorder.rs", "rank": 50, "score": 108270.2517380898 }, { "content": "pub fn count_occurences(left: &Term, right: &Term, values: &[Vec<Term>]) -> usize {\n\n let mut cur = 0;\n\n\n\n for value in values {\n\n if value.contains(left) && value.contains(right) {\n\n cur += 1;\n\n }\n\n }\n\n\n\n cur\n\n}\n\n\n", "file_path": "src/repair.rs", "rank": 51, "score": 107538.12061236429 }, { "content": "pub fn slp_to_ssa(slp: &[(Term, Term, Term)]) -> Graph {\n\n let mut ssa = Graph::new();\n\n\n\n // map (`v` in slp) to (l that is the line `l` number defines `v`)\n\n let mut map: BTreeMap<Term, usize> = BTreeMap::new();\n\n\n\n let mut current_line = 1;\n\n for (target, left, right) in slp {\n\n let left = map.get_mut(&left).map_or(\n\n left.clone(), // if not found\n\n |v| Term::Var(*v), // if found\n\n );\n\n\n\n let right = map.get_mut(&right).map_or(\n\n right.clone(), // if not found\n\n |v| Term::Var(*v), // if found\n\n );\n\n\n\n ssa.push((Term::Var(current_line), left, right));\n\n\n", "file_path": "src/fusion.rs", "rank": 52, "score": 102090.56505771767 }, { "content": "pub fn programs_to_slp(program: &[(Term, Term, Term)]) -> SLP {\n\n let mut num_of_variables = 0;\n\n let mut num_of_constants = 0;\n\n\n\n for (var, left, right) in program {\n\n if let Term::Var(var) = var {\n\n num_of_variables = std::cmp::max(num_of_variables, *var);\n\n } else {\n\n panic!(\";-|\");\n\n }\n\n\n\n if let Term::Cst(left) = left {\n\n num_of_constants = std::cmp::max(num_of_constants, *left);\n\n }\n\n if let Term::Cst(right) = right {\n\n num_of_constants = std::cmp::max(num_of_constants, *right);\n\n }\n\n }\n\n\n\n num_of_variables += 1;\n", "file_path": "src/repair.rs", "rank": 53, "score": 102090.56505771767 }, { "content": "pub fn fill_by_random(ary: &mut [u8]) {\n\n for a in ary.iter_mut() {\n\n *a = rand::random::<u8>();\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 54, "score": 101339.65862284417 }, { "content": "fn u8_to_bitvec(u: u8) -> Vec<bool> {\n\n let mut v = vec![false; 8];\n\n\n\n for (i, v) in v.iter_mut().enumerate() {\n\n if (u >> (7 - i)) & 1 == 1 {\n\n *v = true;\n\n }\n\n }\n\n\n\n v\n\n}\n\n\n", "file_path": "src/rsv_bitmatrix.rs", "rank": 55, "score": 100910.7005749917 }, { "content": "pub fn multi_slp_to_pebble_computation(slp: &MultiSLP) -> Vec<(Pebble, Vec<Pebble>)> {\n\n let mut v = Vec::new();\n\n\n\n for (t, seq) in slp {\n\n let seq: Vec<_> = seq.iter().map(|t| Pebble::from_term(t)).collect();\n\n v.push((Pebble::from_term(t), seq));\n\n }\n\n\n\n v\n\n}\n\n\n", "file_path": "src/reorder.rs", "rank": 56, "score": 99481.99055903885 }, { "content": "fn remove_trivials(vec: &mut Vec<Vec<Term>>) {\n\n for i in (0..vec.len()).rev() {\n\n if vec[i].len() == 1 {\n\n vec.remove(i);\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/repair.rs", "rank": 57, "score": 96848.99806522185 }, { "content": "pub fn pebble_slp_to_term_slp(slp: &[(Pebble, Vec<Pebble>)]) -> Vec<(Term, Vec<Term>)> {\n\n let mut new_slp = Vec::new();\n\n\n\n for (p, body) in slp {\n\n let body: Vec<Term> = body.iter().map(|p| p.to_term()).collect();\n\n new_slp.push((p.to_term(), body));\n\n }\n\n\n\n new_slp\n\n}\n\n\n", "file_path": "src/reorder.rs", "rank": 58, "score": 94883.17550152843 }, { "content": "pub fn term_slp_to_pebble_slp(slp: &[(Term, Vec<Term>)]) -> Vec<(Pebble, Vec<Pebble>)> {\n\n let mut new_slp = Vec::new();\n\n\n\n for (p, body) in slp {\n\n let body: Vec<Pebble> = body.iter().map(|p| Pebble::from_term(p)).collect();\n\n new_slp.push((Pebble::from_term(p), body));\n\n }\n\n\n\n new_slp\n\n}\n\n\n", "file_path": "src/reorder.rs", "rank": 59, "score": 94883.17550152843 }, { "content": "pub fn graph_analyze(shrinked_slp: &SLP, graph: &Graph) -> (Stat, PebbleProgram) {\n\n let program: Vec<(Term, Vec<Term>)> = graph_to_multiterm_slp(&graph);\n\n let program: Vec<(Pebble, Vec<Pebble>)> = reorder::term_slp_to_pebble_slp(&program);\n\n let stat = stat::analyze(&program);\n\n\n\n let shrinked_valuation = validation::slp_to_valuation(&shrinked_slp);\n\n let renamed = rename(&shrinked_valuation, &program);\n\n\n\n (stat, renamed)\n\n}\n\n\n", "file_path": "src/for_benchmark.rs", "rank": 60, "score": 94817.91814987213 }, { "content": "pub fn bench_fusion(shrinked_slp: &SLP, graph: &Graph) -> (Stat, PebbleProgram) {\n\n let graph = if fusion::is_ssa(graph) {\n\n graph.clone()\n\n } else {\n\n fusion::slp_to_ssa(graph)\n\n };\n\n\n\n let evaluated = repair::evaluate_program(&graph);\n\n\n\n let targets: Vec<Term> = repair::realizes(&evaluated, &shrinked_slp)\n\n .unwrap()\n\n .iter()\n\n .map(|(a, _)| Term::Var(*a))\n\n .collect();\n\n\n\n let multislp = fusion::graph_to_multislp_by_fusion(graph.to_vec(), &targets);\n\n let multislp: Vec<(Term, Vec<Term>)> = multislp_to_multiterm_slp(&multislp);\n\n let multislp: Vec<(Pebble, Vec<Pebble>)> = reorder::term_slp_to_pebble_slp(&multislp);\n\n let multislp_stat = stat::analyze(&multislp);\n\n\n\n let shrinked_valuation = validation::slp_to_valuation(&shrinked_slp);\n\n let renamed = rename(&shrinked_valuation, &multislp);\n\n\n\n (multislp_stat, renamed)\n\n}\n\n\n", "file_path": "src/for_benchmark.rs", "rank": 61, "score": 94817.91814987213 }, { "content": "pub fn dump_valuation(valuation: &Valuation) {\n\n for (t, val) in valuation {\n\n let mut s: String = String::new();\n\n let mut iter = val.iter();\n\n s.push_str(&format!(\"{}\", iter.next().unwrap().cst_to_usize().unwrap()));\n\n while let Some(v) = iter.next() {\n\n s.push_str(&format!(\" + {}\", v.cst_to_usize().unwrap()));\n\n }\n\n println!(\"{} = {}\", t.var_to_usize().unwrap(), s);\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 62, "score": 94032.76426109092 }, { "content": "pub fn evaluate_program(program: &[(Term, Term, Term)]) -> SLP {\n\n assert!(crate::fusion::is_ssa(&program.to_vec()));\n\n // let slp = programs_to_slp(&crate::fusion::slp_to_ssa(program));\n\n let slp = programs_to_slp(&program);\n\n execute_slp(&slp)\n\n}\n\n\n", "file_path": "src/repair.rs", "rank": 63, "score": 91201.97963896813 }, { "content": "pub fn dag_visit(dag: &DAG, cur: &Term, visited: &mut BTreeSet<Term>) -> Vec<(Term, Vec<Term>)> {\n\n if dag.get(cur).is_none() {\n\n return Vec::new();\n\n }\n\n\n\n let defs: Vec<_> = dag.get(cur).unwrap().iter().cloned().collect();\n\n\n\n let mut order = Vec::new();\n\n for t in &defs {\n\n if !visited.contains(t) {\n\n order.append(&mut dag_visit(dag, t, visited));\n\n visited.insert(t.clone());\n\n }\n\n }\n\n order.push((cur.clone(), defs));\n\n visited.insert(cur.clone());\n\n\n\n order\n\n}\n\n\n", "file_path": "src/reorder.rs", "rank": 64, "score": 88728.687179275 }, { "content": "pub fn make_indegrees(dag: &DAG) -> BTreeMap<Term, usize> {\n\n let mut mapping = BTreeMap::new();\n\n\n\n for (t, v) in dag {\n\n mapping.insert(t.clone(), 0);\n\n\n\n for t in v {\n\n mapping.insert(t.clone(), 0);\n\n }\n\n }\n\n\n\n for t in dag.keys() {\n\n let r = mapping.get_mut(t).unwrap();\n\n *r += 1;\n\n }\n\n\n\n mapping\n\n}\n\n\n", "file_path": "src/reorder.rs", "rank": 66, "score": 88353.67243734919 }, { "content": "pub fn make_outdegrees(dag: &DAG) -> BTreeMap<Term, usize> {\n\n let mut mapping = BTreeMap::new();\n\n\n\n for (t, v) in dag {\n\n mapping.insert(t.clone(), 0);\n\n\n\n for t in v {\n\n mapping.insert(t.clone(), 0);\n\n }\n\n }\n\n\n\n for v in dag.values() {\n\n for t in v {\n\n let r = mapping.get_mut(t).unwrap();\n\n *r += 1;\n\n }\n\n }\n\n\n\n mapping\n\n}\n\n\n", "file_path": "src/reorder.rs", "rank": 67, "score": 88353.67243734919 }, { "content": "fn ceilup(data_size: usize, unit: usize) -> usize {\n\n if data_size % unit == 0 {\n\n data_size\n\n } else {\n\n ((data_size + unit) / unit) * unit\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 68, "score": 87404.060443138 }, { "content": "pub fn graph_to_valuations(g: &Graph) -> Valuation {\n\n let mut valuation = Valuation::new();\n\n\n\n for (t, t1, t2) in g {\n\n let v1 = get_val(&valuation, t1);\n\n let v2 = get_val(&valuation, t2);\n\n valuation.insert(t.clone(), xor_set(&v1, &v2));\n\n }\n\n\n\n valuation\n\n}\n\n\n", "file_path": "src/validation.rs", "rank": 69, "score": 87362.51362743521 }, { "content": "pub fn mapping_to_rewriting(mapping: &[(usize, usize)]) -> Vec<(usize, usize)> {\n\n let mut strong_components: Vec<VecDeque<usize>> = Vec::new();\n\n\n\n for (from, to) in mapping {\n\n let mut component = VecDeque::new();\n\n component.push_front(*from);\n\n component.push_back(*to);\n\n strong_components.push(component);\n\n }\n\n\n\n loop {\n\n let mut pair = None;\n\n for i in 0..strong_components.len() {\n\n for j in 0..strong_components.len() {\n\n if pair.is_some() {\n\n break;\n\n }\n\n\n\n if i == j {\n\n continue;\n", "file_path": "src/renaming.rs", "rank": 70, "score": 85981.70232940298 }, { "content": "pub fn bench_pebble(shrinked_slp: &SLP, graph: &Graph) -> (Stat, Stat, Stat, Stat, PebbleProgram) {\n\n let graph = if fusion::is_ssa(graph) {\n\n graph.clone()\n\n } else {\n\n fusion::slp_to_ssa(graph)\n\n };\n\n let evaluated = repair::evaluate_program(&graph);\n\n\n\n let targets: Vec<Term> = repair::realizes(&evaluated, &shrinked_slp)\n\n .unwrap()\n\n .iter()\n\n .map(|(a, _)| Term::Var(*a))\n\n .collect();\n\n\n\n let multislp = fusion::graph_to_multislp_by_fusion(graph.to_vec(), &targets);\n\n\n\n let nr_constants = shrinked_slp.num_of_original_constants();\n\n\n\n let scheduled1 =\n\n reorder::deal_multislp(&multislp, nr_constants, targets.clone(), Strategy::UseLRU);\n", "file_path": "src/for_benchmark.rs", "rank": 71, "score": 85743.45945855892 }, { "content": "pub fn pebble_computation_to_valuation(computation: &[(Pebble, Vec<Pebble>)]) -> Valuation {\n\n let mut valuation = Valuation::new();\n\n\n\n for (t, children) in computation {\n\n let mut val = BTreeSet::new();\n\n for c in children {\n\n let v = get_val(&valuation, &c.to_term());\n\n val = xor_set(&val, &v);\n\n }\n\n valuation.insert(t.to_term(), val);\n\n }\n\n\n\n valuation\n\n}\n\n\n", "file_path": "src/validation.rs", "rank": 72, "score": 76957.51534996838 }, { "content": "pub fn term_computation_to_valuation(computation: &[(Term, Vec<Term>)]) -> Valuation {\n\n let mut valuation = Valuation::new();\n\n\n\n for (t, children) in computation {\n\n let mut val = BTreeSet::new();\n\n for c in children {\n\n let v = get_val(&valuation, &c);\n\n val = xor_set(&val, &v);\n\n }\n\n valuation.insert(t.clone(), val);\n\n }\n\n\n\n valuation\n\n}\n\n\n", "file_path": "src/validation.rs", "rank": 73, "score": 76957.51534996838 }, { "content": "pub fn replace_program(program: &mut [Vec<Term>], left: &Term, right: &Term, new: &Term) {\n\n for def in program {\n\n *def = replace(def, left, right, new);\n\n }\n\n}\n\n\n", "file_path": "src/repair.rs", "rank": 74, "score": 76540.4581517021 }, { "content": "fn rename(valuation: &Valuation, program: &[(Pebble, Vec<Pebble>)]) -> PebbleProgram {\n\n let mapping = validation::is_subvaluation(\n\n &valuation,\n\n &validation::pebble_computation_to_valuation(program),\n\n );\n\n\n\n let mapping: Vec<(usize, usize)> = mapping\n\n .unwrap()\n\n .iter()\n\n .map(|(a, b)| (a.var_to_usize().unwrap(), b.var_to_usize().unwrap()))\n\n .collect();\n\n\n\n let renaming = renaming::mapping_to_rewriting(&mapping);\n\n let renamed =\n\n renaming::rename_multislp_by(&renaming, &reorder::pebble_slp_to_term_slp(program));\n\n\n\n assert!(validation::is_strict_subvaluation(\n\n &valuation,\n\n &validation::term_computation_to_valuation(&renamed)\n\n ));\n\n\n\n reorder::term_slp_to_pebble_slp(&renamed)\n\n}\n\n\n", "file_path": "src/for_benchmark.rs", "rank": 75, "score": 76242.33326689416 }, { "content": "pub fn rename_by_rules(renaming: &[(usize, usize)], term: &Term) -> Term {\n\n for (a, b) in renaming {\n\n if let Some(term) = rename(*a, *b, term) {\n\n return term;\n\n }\n\n }\n\n\n\n term.clone()\n\n}\n\n\n", "file_path": "src/renaming.rs", "rank": 76, "score": 75907.5035929366 }, { "content": "pub fn isa_rsv(data: usize, parity: usize) -> Matrix<GF_2_8> {\n\n let m = data + parity;\n\n let k = data;\n\n\n\n let mut a = Matrix::new(MatrixSize {\n\n height: m,\n\n width: k,\n\n });\n\n\n\n let mut gen = GF_2_8::ONE;\n\n\n\n for i in 0..k {\n\n a[i][i] = GF_2_8::ONE;\n\n }\n\n\n\n for i in k..m {\n\n let mut p = GF_2_8::ONE;\n\n for j in 0..k {\n\n a[i][j] = p;\n\n p = p * gen;\n", "file_path": "src/vandermonde.rs", "rank": 77, "score": 75907.5035929366 }, { "content": "pub fn rsv(data_fragments: usize, parity_fragments: usize) -> Matrix<GF_2_8> {\n\n let height = data_fragments + parity_fragments;\n\n\n\n let velems: Vec<GF_2_8> = (1..=height)\n\n .map(|i| GF_2_8::PRIMITIVE_ELEMENT.exp(i as u32))\n\n .collect();\n\n\n\n let m: Matrix<GF_2_8> = modified_systematic_vandermonde(\n\n MatrixSize {\n\n height,\n\n width: data_fragments,\n\n },\n\n &velems,\n\n )\n\n .unwrap();\n\n\n\n m\n\n}\n\n\n", "file_path": "src/vandermonde.rs", "rank": 78, "score": 74069.88726817019 }, { "content": "pub fn multislp_to_multiterm_slp(g: &MultiSLP) -> Vec<(Term, Vec<Term>)> {\n\n let mut slp = Vec::new();\n\n\n\n for (t, children) in g {\n\n slp.push((t.clone(), children.iter().cloned().collect()));\n\n }\n\n\n\n slp\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 79, "score": 73752.39902978495 }, { "content": "pub fn number_of_access(forest: &Forest) -> usize {\n\n let mut number = 0;\n\n\n\n for value in forest.values() {\n\n number += 1 + value.len();\n\n }\n\n\n\n number\n\n}\n\n\n", "file_path": "src/fusion.rs", "rank": 80, "score": 73619.57919741429 }, { "content": "pub fn graph_to_multislp(g: &Graph) -> MultiSLP {\n\n use std::iter::FromIterator;\n\n\n\n let mut slp = MultiSLP::new();\n\n\n\n for (t, l, r) in g {\n\n slp.push((t.clone(), BTreeSet::from_iter(vec![l.clone(), r.clone()])));\n\n }\n\n\n\n slp\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 81, "score": 73363.62099083215 }, { "content": "// v1 \\sqsubseteq v2\n\n// (a, b) \\in subvaluation <=> v1[b] = v1[a]\n\npub fn is_subvaluation(v1: &Valuation, v2: &Valuation) -> Option<Vec<(Term, Term)>> {\n\n let mut v2_to_v1 = Vec::new();\n\n for (b, val) in v1 {\n\n if let Some((a, _)) = v2.iter().find(|(_, v)| v == &val) {\n\n v2_to_v1.push((a.clone(), b.clone()));\n\n } else {\n\n return None;\n\n }\n\n }\n\n Some(v2_to_v1)\n\n}\n\n\n", "file_path": "src/validation.rs", "rank": 82, "score": 73140.5817399661 }, { "content": "pub fn nonsystematic_rsv(data_fragments: usize, parity_fragments: usize) -> Matrix<GF_2_8> {\n\n let height = data_fragments + parity_fragments;\n\n\n\n let velems: Vec<GF_2_8> = (1..=height)\n\n .map(|i| GF_2_8::PRIMITIVE_ELEMENT.exp(i as u32))\n\n .collect();\n\n\n\n let m: Matrix<GF_2_8> = vandermonde(\n\n MatrixSize {\n\n height,\n\n width: data_fragments,\n\n },\n\n &velems,\n\n )\n\n .unwrap();\n\n\n\n m\n\n}\n\n\n", "file_path": "src/vandermonde.rs", "rank": 83, "score": 72343.21298840945 }, { "content": "fn sd(v: &[f64], mean: f64) -> f64 {\n\n let mut sd: f64 = 0.0;\n\n for e in v {\n\n sd += (*e - mean) * (*e - mean);\n\n }\n\n sd /= v.len() as f64;\n\n sd.sqrt()\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 84, "score": 71659.21143929572 }, { "content": "pub fn rsv_bitmatrix(data_fragment: usize, parity_fragment: usize) -> BitMatrix {\n\n let rsvm = crate::vandermonde::rsv(data_fragment, parity_fragment);\n\n matrix_to_bitmatrix(&rsvm)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::vandermonde::*;\n\n use itertools::Itertools;\n\n\n\n #[test]\n\n fn test_m2bm1() {\n\n let rsvm = rsv(4, 4);\n\n matrix_to_bitmatrix(&rsvm);\n\n }\n\n\n\n #[test]\n\n fn test_bitmatrix_rsv1() {\n\n let m = rsv(10, 4);\n", "file_path": "src/rsv_bitmatrix.rs", "rank": 85, "score": 71432.68949111449 }, { "content": "pub fn cache_misses_graph(graph: &Graph) -> usize {\n\n let slp = graph_to_multislp(graph);\n\n cache_misses_pebble_computation(&multi_slp_to_pebble_computation(&slp))\n\n}\n\n\n", "file_path": "src/reorder.rs", "rank": 86, "score": 71343.20077576031 }, { "content": "pub fn gen_data(len: usize) -> Vec<u8> {\n\n let mut v: Vec<u8> = loop {\n\n let v = vec![0u8; len];\n\n if v.as_ptr() as usize % 32 == 0 {\n\n break v;\n\n }\n\n };\n\n\n\n for ptr in v.iter_mut() {\n\n *ptr = rand::random::<u8>();\n\n }\n\n\n\n v\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 87, "score": 70477.84348312383 }, { "content": "pub fn required_pebbles(seq: &[(Pebble, &[Pebble])]) -> usize {\n\n let mut set = BTreeSet::new();\n\n\n\n for (a, _) in seq {\n\n set.insert(a.clone());\n\n }\n\n\n\n set.iter()\n\n .filter_map(|t| match t {\n\n Pebble::Const(_) => None,\n\n Pebble::Var(v) => Some(*v),\n\n })\n\n .max()\n\n .unwrap()\n\n + 1\n\n}\n\n\n\npub struct PageAlignedArray {\n\n ptr: *const u8,\n\n size: usize,\n", "file_path": "src/run.rs", "rank": 88, "score": 70477.84348312383 }, { "content": "pub fn xor_set(b1: &BTreeSet<Term>, b2: &BTreeSet<Term>) -> BTreeSet<Term> {\n\n b1.symmetric_difference(b2).cloned().collect()\n\n}\n\n\n", "file_path": "src/validation.rs", "rank": 89, "score": 69444.12461548025 }, { "content": "fn expand(v: &[[u8; 8]]) -> Vec<Vec<u8>> {\n\n let mut w = Vec::new();\n\n\n\n for j in 0..8 {\n\n let mut tmp = Vec::new();\n\n for ve in v {\n\n tmp.push(ve[j]);\n\n }\n\n w.push(tmp);\n\n }\n\n\n\n w\n\n}\n\n\n", "file_path": "src/rsv_bitmatrix.rs", "rank": 90, "score": 68443.48402414487 }, { "content": "pub fn required_pebbles(seq: &[(Pebble, &[Pebble])]) -> usize {\n\n let mut set = BTreeSet::new();\n\n\n\n for (a, _) in seq {\n\n set.insert(a.clone());\n\n }\n\n\n\n set.iter()\n\n .filter_map(|t| match t {\n\n Pebble::Const(_) => None,\n\n Pebble::Var(v) => Some(*v),\n\n })\n\n .max()\n\n .unwrap()\n\n + 1\n\n}\n\n\n\npub struct PageAlignedArray {\n\n ptr: *const u8,\n\n size: usize,\n", "file_path": "src/run.modif.rs", "rank": 91, "score": 68379.70751922326 }, { "content": "pub fn required_pebbles(seq: &[(Pebble, &[Pebble])]) -> usize {\n\n let mut set = BTreeSet::new();\n\n\n\n for (a, _) in seq {\n\n set.insert(a.clone());\n\n }\n\n\n\n set.iter()\n\n .filter_map(|t| match t {\n\n Pebble::Const(_) => None,\n\n Pebble::Var(v) => Some(*v),\n\n })\n\n .max()\n\n .unwrap()\n\n + 1\n\n}\n\n\n\npub struct PageAlignedArray {\n\n ptr: *const u8,\n\n size: usize,\n", "file_path": "src/run.orig.rs", "rank": 92, "score": 68379.70751922326 }, { "content": " def average_ratio\n\n 100 * (self.sum / self.length)\n\n end\n\nend\n\n\n\nreg = /\n\n[WithOUT comp.].*?MemAcc\\ =\\ (\\d*),\\ \\#\\[Fusioned\\]MemAcc\\ =\\ (\\d*).*?\n\n[With comp.].*?MemAcc\\ =\\ (\\d*).*?,\\ \\#\\[Fusioned\\]MemAcc\\ =\\ (\\d*).*?\n\n/xm\n\n\n\nfname = ARGV[0]\n\n\n\nFile.open(fname) {|f|\n\n s = f.read\n\n r = s.scan(reg)\n\n\n\n coP_P = []\n\n fuP_P = []\n\n fuCoP_CoP = []\n\n fuCoP_P = []\n", "file_path": "reproducing/summarize_memacc.rb", "rank": 93, "score": 67549.43560394013 }, { "content": " def average_ratio\n\n 100 * (self.sum / self.length)\n\n end\n\nend\n\n\n\nreg1 = /\n\n[WithOUT comp.].*?Variables\\ =\\ (\\d*),\\ \\#\\[Fusioned\\]Variables\\ =\\ (\\d*).*?\n\n[With comp.].*?Variables\\ =\\ (\\d*),\\ \\#\\[Fusioned\\]Variables\\ =\\ (\\d*),\\ \\#\\[Fusioned\\&Scheduled\\]Variables\\ =\\ (\\d*)\n\n/xm\n\n\n\nreg2 = /\n\n[WithOUT comp.].*?Capacity\\ =\\ (\\d*),\\ \\#\\[Fusioned\\]Capacity\\ =\\ (\\d*).*?\n\n[With comp.].*?Capacity\\ =\\ (\\d*),\\ \\#\\[Fusioned\\]Capacity\\ =\\ (\\d*),\\ \\#\\[Fusioned\\&Scheduled\\]Capacity\\ =\\ (\\d*)\n\n/xm\n\n\n\nfname = ARGV[0]\n\n\n", "file_path": "reproducing/summarize_cache.rb", "rank": 94, "score": 67549.43560394013 }, { "content": "def ratios(r)\n\n _CoP_P = []\n\n _FuP_P = []\n\n _FuCoP_CoP = []\n\n _DfsFuCoP_CoP = []\n\n \n\n r.map {|array|\n\n vals = {}\n\n vals[:P] = array[0].to_f\n\n vals[:FuP] = array[1].to_f\n\n vals[:CoP] = array[2].to_f\n\n vals[:FuCoP] = array[3].to_f\n\n vals[:DfsFuCoP] = array[4].to_f\n\n \n\n _CoP_P << (vals[:CoP] / vals[:P])\n\n _FuP_P << (vals[:FuP] / vals[:P])\n\n _FuCoP_CoP << (vals[:FuCoP] / vals[:CoP])\n\n _DfsFuCoP_CoP << (vals[:DfsFuCoP] / vals[:CoP])\n\n }\n\n\n", "file_path": "reproducing/summarize_cache.rb", "rank": 95, "score": 67130.4412559548 }, { "content": " def average_ratio\n\n 100 * (self.sum / self.length)\n\n end\n\nend\n\n\n\nreg = /\n\n\\[NoComp\\]\\ \\#XOR\\ =\\ (\\d*).*?\\#XOR\\ =\\ (\\d*).*?\\#XOR\\ =\\ (\\d*)\n\n/xm\n\n\n\nfname = ARGV[0]\n\n\n\nFile.open(fname) {|f|\n\n s = f.read\n\n r = s.scan(reg)\n\n\n\n ratio_rep = []\n\n ratio_xor = []\n\n \n\n r.map {|array|\n\n no_comp = array[0].to_f\n", "file_path": "reproducing/summarize_comp_compare.rb", "rank": 96, "score": 66023.99407321258 }, { "content": "fn avg_throughput(prefix: &str, times: &[f64], data_size: usize) {\n\n let throughputs: Vec<_> = times.iter().map(|e| (data_size as f64) / e).collect();\n\n let m = mean(&throughputs);\n\n let sd = sd(&throughputs, m);\n\n println!(\"{}: avg = {} MB/s, sd = {}\", prefix, m, sd);\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 97, "score": 65654.75817288997 }, { "content": "pub fn graph_to_multiterm_slp(g: &Graph) -> Vec<(Term, Vec<Term>)> {\n\n let mut slp = Vec::new();\n\n\n\n for (t, l, r) in g {\n\n slp.push((t.clone(), vec![l.clone(), r.clone()]));\n\n }\n\n\n\n slp\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 98, "score": 64712.54789373672 }, { "content": "pub fn split(n: usize, data: Vec<u8>) -> Vec<Vec<u8>> {\n\n assert!(data.len() % n == 0);\n\n\n\n let width = data.len() / n;\n\n let mut matrix: Vec<Vec<u8>> = Vec::new();\n\n\n\n for i in 0..n {\n\n matrix.push(data[width * i..width * (i + 1)].to_vec());\n\n }\n\n\n\n matrix\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 99, "score": 63684.26152699831 } ]
Rust
netidx-netproto/src/glob.rs
dtolnay-contrib/netidx
40fd1189d0d6df684e3b575421186e135e9c3208
use anyhow::Result; use bytes::{Buf, BufMut}; use globset; use netidx_core::{ chars::Chars, pack::{Pack, PackError}, path::Path, pool::{Pool, Pooled}, utils, }; use std::{ cmp::{Eq, PartialEq}, ops::Deref, result, sync::Arc, }; use arcstr::ArcStr; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Scope { Subtree, Finite(usize), } impl Scope { pub fn contains(&self, levels: usize) -> bool { match self { Scope::Subtree => true, Scope::Finite(n) => levels <= *n, } } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Glob { raw: Chars, base: Path, scope: Scope, glob: globset::Glob, } impl Glob { pub fn is_glob(mut s: &str) -> bool { loop { if s.is_empty() { break false; } else { match s.find(&['?', '*', '{', '['][..]) { None => break false, Some(i) => { if utils::is_escaped(s, '\\', i) { s = &s[i + 1..]; } else { break true; } } } } } } pub fn new(raw: Chars) -> Result<Glob> { if !Path::is_absolute(&raw) { bail!("glob paths must be absolute") } let base = { let mut cur = "/"; let mut iter = Path::dirnames(&raw); loop { match iter.next() { None => break cur, Some(p) => { if Glob::is_glob(p) { break cur; } else { cur = p; } } } } }; let lvl = Path::levels(base); let base = Path::from(ArcStr::from(base)); let scope = if Path::dirnames(&raw).skip(lvl).any(|p| Path::basename(p) == Some("**")) { Scope::Subtree } else { Scope::Finite(Path::levels(&raw)) }; let glob = globset::Glob::new(&*raw)?; Ok(Glob { raw, base, scope, glob }) } pub fn base(&self) -> &str { &self.base } pub fn scope(&self) -> &Scope { &self.scope } pub fn glob(&self) -> &globset::Glob { &self.glob } pub fn into_glob(self) -> globset::Glob { self.glob } } impl Pack for Glob { fn encoded_len(&self) -> usize { <Chars as Pack>::encoded_len(&self.raw) } fn encode(&self, buf: &mut impl BufMut) -> result::Result<(), PackError> { <Chars as Pack>::encode(&self.raw, buf) } fn decode(buf: &mut impl Buf) -> result::Result<Self, PackError> { Glob::new(<Chars as Pack>::decode(buf)?).map_err(|_| PackError::InvalidFormat) } } #[derive(Debug)] struct GlobSetInner { raw: Pooled<Vec<Glob>>, published_only: bool, glob: globset::GlobSet, } #[derive(Debug, Clone)] pub struct GlobSet(Arc<GlobSetInner>); impl PartialEq for GlobSet { fn eq(&self, other: &Self) -> bool { &self.0.raw == &other.0.raw } } impl Eq for GlobSet {} impl GlobSet { pub fn new( published_only: bool, globs: impl IntoIterator<Item = Glob>, ) -> Result<GlobSet> { lazy_static! { static ref GLOB: Pool<Vec<Glob>> = Pool::new(10, 100); } let mut builder = globset::GlobSetBuilder::new(); let mut raw = GLOB.take(); for glob in globs { builder.add(glob.glob.clone()); raw.push(glob); } raw.sort_unstable_by(|g0, g1| g0.base().cmp(g1.base())); Ok(GlobSet(Arc::new(GlobSetInner { raw, published_only, glob: builder.build()?, }))) } pub fn is_match(&self, path: &Path) -> bool { self.0.glob.is_match(path.as_ref()) } pub fn published_only(&self) -> bool { self.0.published_only } } impl Deref for GlobSet { type Target = Vec<Glob>; fn deref(&self) -> &Self::Target { &*self.0.raw } } impl Pack for GlobSet { fn encoded_len(&self) -> usize { <bool as Pack>::encoded_len(&self.0.published_only) + <Pooled<Vec<Glob>> as Pack>::encoded_len(&self.0.raw) } fn encode(&self, buf: &mut impl BufMut) -> result::Result<(), PackError> { <bool as Pack>::encode(&self.0.published_only, buf)?; <Pooled<Vec<Glob>> as Pack>::encode(&self.0.raw, buf) } fn decode(buf: &mut impl Buf) -> result::Result<Self, PackError> { let published_only = <bool as Pack>::decode(buf)?; let mut raw = <Pooled<Vec<Glob>> as Pack>::decode(buf)?; let mut builder = globset::GlobSetBuilder::new(); for glob in raw.iter() { builder.add(glob.glob.clone()); } raw.sort_unstable_by(|g0, g1| g0.base().cmp(g1.base())); let glob = builder.build().map_err(|_| PackError::InvalidFormat)?; Ok(GlobSet(Arc::new(GlobSetInner { raw, published_only, glob }))) } }
use anyhow::Result; use bytes::{Buf, BufMut}; use globset; use netidx_core::{ chars::Chars, pack::{Pack, PackError}, path::Path, pool::{Pool, Pooled}, utils, }; use std::{ cmp::{Eq, PartialEq}, ops::Deref, result, sync::Arc, }; use arcstr::ArcStr; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Scope { Subtree, Finite(usize), } impl Scope { pub fn contains(&self, levels: usize) -> bool { match self { Scope::Subtree => true, Scope::Finite(n) => levels <= *n, } } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Glob { raw: Chars, base: Path, scope: Scope, glob: globset::Glob, } impl Glob { pub fn is_glob(mut s: &str) -> bool { loop { if s.is_empty() { break false; } else { match s.find(&['?', '*', '{', '['][..]) { None => break false, Some(i) => {
} } } } } pub fn new(raw: Chars) -> Result<Glob> { if !Path::is_absolute(&raw) { bail!("glob paths must be absolute") } let base = { let mut cur = "/"; let mut iter = Path::dirnames(&raw); loop { match iter.next() { None => break cur, Some(p) => { if Glob::is_glob(p) { break cur; } else { cur = p; } } } } }; let lvl = Path::levels(base); let base = Path::from(ArcStr::from(base)); let scope = if Path::dirnames(&raw).skip(lvl).any(|p| Path::basename(p) == Some("**")) { Scope::Subtree } else { Scope::Finite(Path::levels(&raw)) }; let glob = globset::Glob::new(&*raw)?; Ok(Glob { raw, base, scope, glob }) } pub fn base(&self) -> &str { &self.base } pub fn scope(&self) -> &Scope { &self.scope } pub fn glob(&self) -> &globset::Glob { &self.glob } pub fn into_glob(self) -> globset::Glob { self.glob } } impl Pack for Glob { fn encoded_len(&self) -> usize { <Chars as Pack>::encoded_len(&self.raw) } fn encode(&self, buf: &mut impl BufMut) -> result::Result<(), PackError> { <Chars as Pack>::encode(&self.raw, buf) } fn decode(buf: &mut impl Buf) -> result::Result<Self, PackError> { Glob::new(<Chars as Pack>::decode(buf)?).map_err(|_| PackError::InvalidFormat) } } #[derive(Debug)] struct GlobSetInner { raw: Pooled<Vec<Glob>>, published_only: bool, glob: globset::GlobSet, } #[derive(Debug, Clone)] pub struct GlobSet(Arc<GlobSetInner>); impl PartialEq for GlobSet { fn eq(&self, other: &Self) -> bool { &self.0.raw == &other.0.raw } } impl Eq for GlobSet {} impl GlobSet { pub fn new( published_only: bool, globs: impl IntoIterator<Item = Glob>, ) -> Result<GlobSet> { lazy_static! { static ref GLOB: Pool<Vec<Glob>> = Pool::new(10, 100); } let mut builder = globset::GlobSetBuilder::new(); let mut raw = GLOB.take(); for glob in globs { builder.add(glob.glob.clone()); raw.push(glob); } raw.sort_unstable_by(|g0, g1| g0.base().cmp(g1.base())); Ok(GlobSet(Arc::new(GlobSetInner { raw, published_only, glob: builder.build()?, }))) } pub fn is_match(&self, path: &Path) -> bool { self.0.glob.is_match(path.as_ref()) } pub fn published_only(&self) -> bool { self.0.published_only } } impl Deref for GlobSet { type Target = Vec<Glob>; fn deref(&self) -> &Self::Target { &*self.0.raw } } impl Pack for GlobSet { fn encoded_len(&self) -> usize { <bool as Pack>::encoded_len(&self.0.published_only) + <Pooled<Vec<Glob>> as Pack>::encoded_len(&self.0.raw) } fn encode(&self, buf: &mut impl BufMut) -> result::Result<(), PackError> { <bool as Pack>::encode(&self.0.published_only, buf)?; <Pooled<Vec<Glob>> as Pack>::encode(&self.0.raw, buf) } fn decode(buf: &mut impl Buf) -> result::Result<Self, PackError> { let published_only = <bool as Pack>::decode(buf)?; let mut raw = <Pooled<Vec<Glob>> as Pack>::decode(buf)?; let mut builder = globset::GlobSetBuilder::new(); for glob in raw.iter() { builder.add(glob.glob.clone()); } raw.sort_unstable_by(|g0, g1| g0.base().cmp(g1.base())); let glob = builder.build().map_err(|_| PackError::InvalidFormat)?; Ok(GlobSet(Arc::new(GlobSetInner { raw, published_only, glob }))) } }
if utils::is_escaped(s, '\\', i) { s = &s[i + 1..]; } else { break true; }
if_condition
[ { "content": "pub fn is_escaped(s: &str, esc: char, i: usize) -> bool {\n\n let b = s.as_bytes();\n\n !s.is_char_boundary(i) || {\n\n let mut res = false;\n\n for j in (0..i).rev() {\n\n if s.is_char_boundary(j) && b[j] == (esc as u8) {\n\n res = !res;\n\n } else {\n\n break;\n\n }\n\n }\n\n res\n\n }\n\n}\n\n\n", "file_path": "netidx-core/src/utils.rs", "rank": 0, "score": 376596.88917671714 }, { "content": "pub fn rsplit_escaped(s: &str, escape: char, sep: char) -> impl Iterator<Item = &str> {\n\n s.rsplit({\n\n let mut esc = false;\n\n move |c| is_sep(&mut esc, c, escape, sep)\n\n })\n\n}\n\n\n\nthread_local! {\n\n static BUF: RefCell<BytesMut> = RefCell::new(BytesMut::with_capacity(512));\n\n}\n\n\n", "file_path": "netidx-core/src/utils.rs", "rank": 1, "score": 342439.60046670644 }, { "content": "pub fn split_escaped(s: &str, escape: char, sep: char) -> impl Iterator<Item = &str> {\n\n s.split({\n\n let mut esc = false;\n\n move |c| is_sep(&mut esc, c, escape, sep)\n\n })\n\n}\n\n\n", "file_path": "netidx-core/src/utils.rs", "rank": 2, "score": 342439.6004667065 }, { "content": "pub fn is_sep(esc: &mut bool, c: char, escape: char, sep: char) -> bool {\n\n if c == sep {\n\n !*esc\n\n } else {\n\n *esc = c == escape && !*esc;\n\n false\n\n }\n\n}\n\n\n", "file_path": "netidx-core/src/utils.rs", "rank": 3, "score": 305185.70217950566 }, { "content": "fn table_rows(data: &sled::Tree, base: &Path) -> Result<Pooled<Vec<Path>>> {\n\n let base_levels = Path::levels(&base);\n\n let mut paths = PATHS.take();\n\n for r in data.scan_prefix(base.as_bytes()).keys() {\n\n let k = r?;\n\n if let Ok(path) = str::from_utf8(&*k) {\n\n if Path::is_parent(base, path) {\n\n let mut row = path;\n\n let mut level = Path::levels(row);\n\n while level > base_levels + 1 {\n\n row = Path::dirname(row).unwrap_or(\"/\");\n\n level -= 1;\n\n }\n\n match paths.last() {\n\n None => paths.push(Path::from(ArcStr::from(row))),\n\n Some(last) => {\n\n if last.as_ref() != row {\n\n paths.push(Path::from(ArcStr::from(row)));\n\n }\n\n }\n\n }\n\n }\n\n }\n\n }\n\n Ok(paths)\n\n}\n\n\n", "file_path": "netidx-tools/src/container/db.rs", "rank": 4, "score": 274237.4888693035 }, { "content": "/// unescape the specified string using the specified escape character\n\npub fn unescape<T>(s: &T, esc: char) -> Cow<str>\n\nwhere\n\n T: AsRef<str> + ?Sized,\n\n{\n\n let s = s.as_ref();\n\n if !s.contains(esc) {\n\n Cow::Borrowed(s.as_ref())\n\n } else {\n\n let mut res = String::with_capacity(s.len());\n\n let mut escaped = false;\n\n res.extend(s.chars().filter_map(|c| {\n\n if c == esc && !escaped {\n\n escaped = true;\n\n None\n\n } else {\n\n escaped = false;\n\n Some(c)\n\n }\n\n }));\n\n Cow::Owned(res)\n\n }\n\n}\n\n\n", "file_path": "netidx-core/src/utils.rs", "rank": 5, "score": 272727.47504317056 }, { "content": "fn is_locked(locked: &sled::Tree, path: &Path, parent_only: bool) -> Result<bool> {\n\n let mut iter = if parent_only {\n\n locked.range(..path.as_bytes())\n\n } else {\n\n locked.range(..=path.as_bytes())\n\n };\n\n loop {\n\n match iter.next_back() {\n\n None => break Ok(false),\n\n Some(r) => {\n\n let (k, v) = r?;\n\n let k = str::from_utf8(&k)?;\n\n if Path::is_parent(k, &path) {\n\n break Ok(&*v == &[1u8])\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "netidx-tools/src/container/db.rs", "rank": 6, "score": 265219.90561199206 }, { "content": "/// escape the specified string using the specified escape character\n\n/// and a slice of special characters that need escaping.\n\npub fn escape<'a, 'b, T>(s: &'a T, esc: char, spec: &'b [char]) -> Cow<'a, str>\n\nwhere\n\n T: AsRef<str> + ?Sized,\n\n 'a: 'b,\n\n{\n\n let s = s.as_ref();\n\n if s.find(|c: char| spec.contains(&c) || c == esc).is_none() {\n\n Cow::Borrowed(s.as_ref())\n\n } else {\n\n let mut out = String::with_capacity(s.len());\n\n for c in s.chars() {\n\n if spec.contains(&c) {\n\n out.push(esc);\n\n out.push(c);\n\n } else if c == esc {\n\n out.push(esc);\n\n out.push(c);\n\n } else {\n\n out.push(c);\n\n }\n\n }\n\n Cow::Owned(out)\n\n }\n\n}\n\n\n", "file_path": "netidx-core/src/utils.rs", "rank": 7, "score": 263829.9270928308 }, { "content": "fn is_canonical(s: &str) -> bool {\n\n for _ in Path::parts(s).filter(|p| *p == \"\") {\n\n return false;\n\n }\n\n true\n\n}\n\n\n", "file_path": "netidx-core/src/path.rs", "rank": 8, "score": 254910.92507924908 }, { "content": "pub fn parse_expr(s: &str) -> anyhow::Result<Expr> {\n\n expr()\n\n .easy_parse(position::Stream::new(s))\n\n .map(|(r, _)| r)\n\n .map_err(|e| anyhow::anyhow!(format!(\"{}\", e)))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn const_expr_parse() {\n\n assert_eq!(\n\n ExprKind::Constant(Value::U32(23)).to_expr(),\n\n parse_expr(\"u32:23\").unwrap()\n\n );\n\n assert_eq!(\n\n ExprKind::Constant(Value::V32(42)).to_expr(),\n\n parse_expr(\"v32:42\").unwrap()\n", "file_path": "netidx-bscript/src/parser.rs", "rank": 9, "score": 247922.0889797387 }, { "content": "pub fn decode_varint(buf: &mut impl Buf) -> Result<u64, PackError> {\n\n let mut value = 0;\n\n let mut i = 0;\n\n while i < 10 {\n\n let byte = buf.get_u8();\n\n value |= u64::from(byte & 0x7F) << (i * 7);\n\n if byte <= 0x7F {\n\n return Ok(value);\n\n }\n\n i += 1;\n\n }\n\n Err(PackError::InvalidFormat)\n\n}\n\n\n\nimpl Pack for u128 {\n\n fn const_encoded_len() -> Option<usize> {\n\n Some(mem::size_of::<u128>())\n\n }\n\n\n\n fn encoded_len(&self) -> usize {\n", "file_path": "netidx-core/src/pack.rs", "rank": 10, "score": 246713.85824904556 }, { "content": "fn constant<I>(typ: &'static str) -> impl Parser<I, Output = char>\n\nwhere\n\n I: RangeStream<Token = char>,\n\n I::Error: ParseError<I::Token, I::Range, I::Position>,\n\n I::Range: Range,\n\n{\n\n string(typ).with(token(':'))\n\n}\n\n\n", "file_path": "netidx-bscript/src/parser.rs", "rank": 11, "score": 231490.06859367987 }, { "content": "fn iter_paths(tree: &sled::Tree) -> impl Iterator<Item = Result<Path>> + 'static {\n\n tree.iter().keys().map(|res| Ok(Path::from(ArcStr::from(str::from_utf8(&res?)?))))\n\n}\n\n\n", "file_path": "netidx-tools/src/container/db.rs", "rank": 12, "score": 230344.7723382212 }, { "content": "pub fn pack<T: Pack>(t: &T) -> Result<BytesMut, PackError> {\n\n BUF.with(|buf| {\n\n let mut b = buf.borrow_mut();\n\n t.encode(&mut *b)?;\n\n Ok(b.split())\n\n })\n\n}\n\n\n", "file_path": "netidx-core/src/utils.rs", "rank": 13, "score": 228005.91604032353 }, { "content": "fn path() -> impl Strategy<Value = Path> {\n\n chars().prop_map(Path::from)\n\n}\n\n\n\nmod resolver {\n\n use super::*;\n\n use crate::resolver::{\n\n ClientAuthRead, ClientAuthWrite, ClientHello, ClientHelloWrite, CtxId, FromRead,\n\n FromWrite, ReadyForOwnershipCheck, Referral, Resolved, Secret, ServerAuthWrite,\n\n ServerHelloRead, ServerHelloWrite, Table, ToRead, ToWrite,\n\n };\n\n use fxhash::FxBuildHasher;\n\n use proptest::{collection, option};\n\n use std::{collections::HashMap, net::SocketAddr};\n\n\n\n fn client_auth_read() -> impl Strategy<Value = ClientAuthRead> {\n\n prop_oneof![\n\n Just(ClientAuthRead::Anonymous),\n\n any::<u64>().prop_map(|i| ClientAuthRead::Reuse(CtxId::mk(i))),\n\n bytes().prop_map(ClientAuthRead::Initiate)\n", "file_path": "netidx-netproto/src/test.rs", "rank": 14, "score": 221236.26831116798 }, { "content": "fn column_path_parts<S: AsRef<str>>(path: &S) -> Option<(&str, &str)> {\n\n let name = Path::basename(path)?;\n\n let root = Path::dirname(Path::dirname(path)?)?;\n\n Some((root, name))\n\n}\n\n\n\n#[derive(Debug)]\n\npub(crate) struct Store {\n\n by_path: HashMap<Path, Set<Addr>>,\n\n by_path_flags: HashMap<Path, u16>,\n\n by_addr: FxHashMap<SocketAddr, HashSet<Path>>,\n\n by_level: FxHashMap<usize, BTreeMap<Path, Z64>>,\n\n columns: HashMap<Path, HashMap<Path, Z64>>,\n\n defaults: BTreeSet<Path>,\n\n parent: Option<Referral>,\n\n children: BTreeMap<Path, Referral>,\n\n addrs: HCAddrs,\n\n}\n\n\n\nimpl Store {\n", "file_path": "netidx/src/resolver_store.rs", "rank": 15, "score": 214658.55494547007 }, { "content": "pub fn check_addr(ip: IpAddr, resolvers: &[SocketAddr]) -> Result<()> {\n\n match ip {\n\n IpAddr::V4(ip) if ip.is_link_local() => {\n\n bail!(\"addr is a link local address\");\n\n }\n\n IpAddr::V4(ip) if ip.is_broadcast() => {\n\n bail!(\"addr is a broadcast address\");\n\n }\n\n IpAddr::V4(ip) if ip.is_private() => {\n\n let ok = resolvers.iter().all(|a| match a.ip() {\n\n IpAddr::V4(ip) if ip.is_private() => true,\n\n IpAddr::V6(_) => true,\n\n _ => false,\n\n });\n\n if !ok {\n\n bail!(\"addr is a private address, and the resolver is not\")\n\n }\n\n }\n\n _ => (),\n\n }\n", "file_path": "netidx-core/src/utils.rs", "rank": 16, "score": 212629.90806707495 }, { "content": "fn pathname(invalid: &mut bool, path: Option<Value>) -> Option<Path> {\n\n *invalid = false;\n\n match path.map(|v| v.cast_to::<String>()) {\n\n None => None,\n\n Some(Ok(p)) => {\n\n if Path::is_absolute(&p) {\n\n Some(Path::from(p))\n\n } else {\n\n *invalid = true;\n\n None\n\n }\n\n }\n\n Some(Err(_)) => {\n\n *invalid = true;\n\n None\n\n }\n\n }\n\n}\n\n\n\npub struct Store {\n", "file_path": "netidx-bscript/src/stdfn.rs", "rank": 17, "score": 195157.42628432863 }, { "content": "pub fn splitn_escaped(\n\n s: &str,\n\n n: usize,\n\n escape: char,\n\n sep: char,\n\n) -> impl Iterator<Item = &str> {\n\n s.splitn(n, {\n\n let mut esc = false;\n\n move |c| is_sep(&mut esc, c, escape, sep)\n\n })\n\n}\n\n\n", "file_path": "netidx-core/src/utils.rs", "rank": 18, "score": 190603.30669072087 }, { "content": "pub fn encode_varint(mut value: u64, buf: &mut impl BufMut) {\n\n loop {\n\n if value < 0x80 {\n\n buf.put_u8(value as u8);\n\n break;\n\n } else {\n\n buf.put_u8(((value & 0x7F) | 0x80) as u8);\n\n value >>= 7;\n\n }\n\n }\n\n}\n\n\n", "file_path": "netidx-core/src/pack.rs", "rank": 19, "score": 189995.12343249097 }, { "content": "fn create_ctx(upn: Option<&str>, target_spn: &str) -> Result<(ClientCtx, Bytes)> {\n\n let ctx = os::create_client_ctx(upn, target_spn)?;\n\n match ctx.step(None)? {\n\n None => bail!(\"client ctx first step produced no token\"),\n\n Some(tok) => Ok((ctx, utils::bytes(&*tok))),\n\n }\n\n}\n\n\n\n// continue with timeout\n\nmacro_rules! cwt {\n\n ($msg:expr, $e:expr) => {\n\n try_cf!(\n\n $msg,\n\n continue,\n\n try_cf!($msg, continue, time::timeout(HELLO_TO, $e).await)\n\n )\n\n };\n\n}\n\n\n\nasync fn connect_read(\n", "file_path": "netidx/src/resolver_single.rs", "rank": 20, "score": 187794.61594831236 }, { "content": "fn remove(data: &sled::Tree, pending: &mut Update, path: Path) -> Result<()> {\n\n let key = path.as_bytes();\n\n let mut val = BUF.take();\n\n Datum::Deleted.encode(&mut *val)?;\n\n if let Some(data) = data.insert(key, &**val)? {\n\n match DatumKind::decode(&mut &*data) {\n\n DatumKind::Data => pending.data.push((path, UpdateKind::Deleted)),\n\n DatumKind::Formula => {\n\n pending.formula.push((path.clone(), UpdateKind::Deleted));\n\n pending.on_write.push((path, UpdateKind::Deleted));\n\n }\n\n DatumKind::Deleted | DatumKind::Invalid => (),\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "netidx-tools/src/container/db.rs", "rank": 21, "score": 187024.39377547614 }, { "content": "fn chars() -> impl Strategy<Value = Chars> {\n\n any::<String>().prop_map(Chars::from)\n\n}\n\n\n", "file_path": "netidx-netproto/src/test.rs", "rank": 22, "score": 184800.82597683134 }, { "content": "fn remove_subtree(data: &sled::Tree, pending: &mut Update, path: Path) -> Result<()> {\n\n use rayon::prelude::*;\n\n let mut paths = PATHS.take();\n\n for res in data.scan_prefix(path.as_ref()).keys() {\n\n let key = res?;\n\n let key = str::from_utf8(&key)?;\n\n if Path::is_parent(&path, &key) {\n\n paths.push(Path::from(ArcStr::from(key)));\n\n }\n\n }\n\n let (up, res) = paths\n\n .par_drain(..)\n\n .fold(\n\n || (Update::new(), Ok(())),\n\n |(mut pending, res), path| {\n\n let res = merge_err(remove(data, &mut pending, path), res);\n\n (pending, res)\n\n },\n\n )\n\n .reduce(\n\n || (Update::new(), Ok(())),\n\n |(u0, r0), (u1, r1)| (u0.merge(u1), merge_err(r0, r1)),\n\n );\n\n pending.merge_from(up);\n\n res\n\n}\n\n\n", "file_path": "netidx-tools/src/container/db.rs", "rank": 23, "score": 184720.41711663172 }, { "content": "fn set_unlocked(locked: &sled::Tree, pending: &mut Update, path: Path) -> Result<()> {\n\n if !is_locked(locked, &path, true)? {\n\n locked.remove(path.as_bytes())?;\n\n } else {\n\n locked.insert(path.as_bytes(), &[0u8])?;\n\n }\n\n pending.unlocked.push(path);\n\n Ok(())\n\n}\n\n\n", "file_path": "netidx-tools/src/container/db.rs", "rank": 24, "score": 184720.41711663172 }, { "content": "fn add_root(roots: &sled::Tree, pending: &mut Update, path: Path) -> Result<()> {\n\n let key = path.as_bytes();\n\n if let Some(r) = roots.range(..key).next_back() {\n\n let (prev, _) = r?;\n\n let prev = str::from_utf8(&prev)?;\n\n if Path::is_parent(prev, &path) {\n\n bail!(\"a parent path is already a root\")\n\n }\n\n }\n\n if !roots.contains_key(key)? {\n\n roots.insert(key, &[])?;\n\n pending.added_roots.push(path);\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "netidx-tools/src/container/db.rs", "rank": 25, "score": 184720.41711663172 }, { "content": "fn set_locked(locked: &sled::Tree, pending: &mut Update, path: Path) -> Result<()> {\n\n if is_locked(locked, &path, true)? {\n\n locked.remove(path.as_bytes())?;\n\n } else {\n\n locked.insert(path.as_bytes(), &[1u8])?;\n\n }\n\n pending.locked.push(path);\n\n Ok(())\n\n}\n\n\n", "file_path": "netidx-tools/src/container/db.rs", "rank": 26, "score": 184720.41711663172 }, { "content": "fn canonize(s: &str) -> String {\n\n let mut res = String::with_capacity(s.len());\n\n if s.len() > 0 {\n\n if s.starts_with(SEP) {\n\n res.push(SEP)\n\n }\n\n let mut first = true;\n\n for p in Path::parts(s).filter(|p| *p != \"\") {\n\n if first {\n\n first = false;\n\n } else {\n\n res.push(SEP)\n\n }\n\n res.push_str(p);\n\n }\n\n }\n\n res\n\n}\n\n\n\n/// A path in the namespace. Paths are immutable and reference\n", "file_path": "netidx-core/src/path.rs", "rank": 27, "score": 182912.7071483293 }, { "content": "pub fn bytes(t: &[u8]) -> Bytes {\n\n bytesmut(t).freeze()\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct ChanWrap<T>(pub mpsc::Sender<T>);\n\n\n\nimpl<T> PartialEq for ChanWrap<T> {\n\n fn eq(&self, other: &ChanWrap<T>) -> bool {\n\n self.0.same_receiver(&other.0)\n\n }\n\n}\n\n\n\nimpl<T> Eq for ChanWrap<T> {}\n\n\n\nimpl<T> Hash for ChanWrap<T> {\n\n fn hash<H: std::hash::Hasher>(&self, state: &mut H) {\n\n self.0.hash_receiver(state)\n\n }\n\n}\n", "file_path": "netidx-core/src/utils.rs", "rank": 28, "score": 175823.93102741736 }, { "content": "pub fn bytesmut(t: &[u8]) -> BytesMut {\n\n BUF.with(|buf| {\n\n let mut b = buf.borrow_mut();\n\n b.extend_from_slice(t);\n\n b.split()\n\n })\n\n}\n\n\n", "file_path": "netidx-core/src/utils.rs", "rank": 29, "score": 172488.70736640014 }, { "content": "pub fn varint_len(value: u64) -> usize {\n\n ((((value | 1).leading_zeros() ^ 63) * 9 + 73) / 64) as usize\n\n}\n\n\n", "file_path": "netidx-core/src/pack.rs", "rank": 30, "score": 169427.1277760253 }, { "content": "pub fn i64_uzz(n: u64) -> i64 {\n\n ((n >> 1) as i64) ^ (((n as i64) << 63) >> 63)\n\n}\n\n\n", "file_path": "netidx-core/src/pack.rs", "rank": 31, "score": 159468.95020664542 }, { "content": "pub fn i64_zz(n: i64) -> u64 {\n\n ((n << 1) ^ (n >> 63)) as u64\n\n}\n\n\n", "file_path": "netidx-core/src/pack.rs", "rank": 32, "score": 159468.95020664542 }, { "content": "pub fn i32_zz(n: i32) -> u32 {\n\n ((n << 1) ^ (n >> 31)) as u32\n\n}\n\n\n", "file_path": "netidx-core/src/pack.rs", "rank": 33, "score": 159468.95020664542 }, { "content": "pub fn i32_uzz(n: u32) -> i32 {\n\n ((n >> 1) as i32) ^ (((n as i32) << 31) >> 31)\n\n}\n\n\n", "file_path": "netidx-core/src/pack.rs", "rank": 34, "score": 159468.95020664542 }, { "content": "fn merge_err(e0: Result<()>, e1: Result<()>) -> Result<()> {\n\n match (e0, e1) {\n\n (Ok(()), Ok(())) => Ok(()),\n\n (Err(e), Err(_)) => Err(e),\n\n (Err(e), Ok(())) => Err(e),\n\n (Ok(()), Err(e)) => Err(e),\n\n }\n\n}\n\n\n", "file_path": "netidx-tools/src/container/db.rs", "rank": 35, "score": 156039.64058384008 }, { "content": "fn eval_op<T: PartialEq + PartialOrd>(op: &str, v0: T, v1: T) -> Value {\n\n match op {\n\n \"eq\" => {\n\n if v0 == v1 {\n\n Value::True\n\n } else {\n\n Value::False\n\n }\n\n }\n\n \"lt\" => {\n\n if v0 < v1 {\n\n Value::True\n\n } else {\n\n Value::False\n\n }\n\n }\n\n \"gt\" => {\n\n if v0 > v1 {\n\n Value::True\n\n } else {\n", "file_path": "netidx-bscript/src/stdfn.rs", "rank": 36, "score": 155919.96525905083 }, { "content": "#[derive(Debug, Clone)]\n\nstruct PathMapping(Path, Id);\n\n\n\nimpl Pack for PathMapping {\n\n fn encoded_len(&self) -> usize {\n\n <Path as Pack>::encoded_len(&self.0) + <Id as Pack>::encoded_len(&self.1)\n\n }\n\n\n\n fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {\n\n <Path as Pack>::encode(&self.0, buf)?;\n\n <Id as Pack>::encode(&self.1, buf)\n\n }\n\n\n\n fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {\n\n let path = <Path as Pack>::decode(buf)?;\n\n let id = <Id as Pack>::decode(buf)?;\n\n Ok(PathMapping(path, id))\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone)]\n", "file_path": "netidx-archive/src/lib.rs", "rank": 37, "score": 155789.96619840476 }, { "content": "fn pick(n: usize) -> usize {\n\n let mut rng = rand::thread_rng();\n\n rng.gen_range(0..n)\n\n}\n\n\n", "file_path": "netidx/src/subscriber.rs", "rank": 38, "score": 154270.9341135568 }, { "content": "fn lookup_value<P: AsRef<[u8]>>(tree: &sled::Tree, path: P) -> Result<Option<Datum>> {\n\n match tree.get(path.as_ref())? {\n\n None => Ok(None),\n\n Some(v) => Ok(Some(Datum::decode(&mut &*v)?)),\n\n }\n\n}\n\n\n", "file_path": "netidx-tools/src/container/db.rs", "rank": 39, "score": 153051.82668677822 }, { "content": "fn default_view(path: Path) -> view::View {\n\n view::View {\n\n variables: HashMap::new(),\n\n keybinds: Vec::new(),\n\n root: view::Widget {\n\n kind: view::WidgetKind::Table(view::Table {\n\n path: ExprKind::Constant(Value::String(Chars::from(String::from(\n\n &*path,\n\n ))))\n\n .to_expr(),\n\n default_sort_column: ExprKind::Constant(Value::Null).to_expr(),\n\n default_sort_column_direction: ExprKind::Constant(Value::from(\n\n \"descending\",\n\n ))\n\n .to_expr(),\n\n column_mode: ExprKind::Constant(Value::from(\"auto\")).to_expr(),\n\n column_list: ExprKind::Constant(Value::from(\"\")).to_expr(),\n\n row_filter: ExprKind::Constant(Value::Null).to_expr(),\n\n editable: ExprKind::Constant(Value::False).to_expr(),\n\n on_select: ExprKind::Constant(Value::Null).to_expr(),\n", "file_path": "netidx-browser/src/main.rs", "rank": 40, "score": 151539.51070403546 }, { "content": "fn varname(invalid: &mut bool, name: Option<Value>) -> Option<Chars> {\n\n *invalid = false;\n\n match name.map(|n| n.cast_to::<Chars>()) {\n\n None => None,\n\n Some(Err(_)) => {\n\n *invalid = true;\n\n None\n\n }\n\n Some(Ok(n)) => {\n\n if VNAME.is_match(&n) {\n\n Some(n)\n\n } else {\n\n *invalid = true;\n\n None\n\n }\n\n }\n\n }\n\n}\n\n\n\npub struct StoreVar {\n", "file_path": "netidx-bscript/src/stdfn.rs", "rank": 41, "score": 151243.3582389548 }, { "content": "pub fn make_sha3_token(salt: Option<u64>, secret: &[&[u8]]) -> Bytes {\n\n let salt = salt.unwrap_or_else(|| rand::thread_rng().gen::<u64>());\n\n let mut hash = Sha3_512::new();\n\n hash.update(&salt.to_be_bytes());\n\n for v in secret {\n\n hash.update(v);\n\n }\n\n BUF.with(|buf| {\n\n let mut b = buf.borrow_mut();\n\n b.put_u64(salt);\n\n b.extend(hash.finalize().into_iter());\n\n b.split().freeze()\n\n })\n\n}\n\n\n", "file_path": "netidx-core/src/utils.rs", "rank": 42, "score": 150352.87754002213 }, { "content": "fn val_to_bool(v: &Value) -> bool {\n\n match v {\n\n Value::False | Value::Null => false,\n\n _ => true,\n\n }\n\n}\n\n\n", "file_path": "netidx-browser/src/main.rs", "rank": 43, "score": 149802.48667572977 }, { "content": "fn str_to_wstr(s: &str) -> Vec<u16> {\n\n let mut v = OsString::from(s).encode_wide().collect::<Vec<_>>();\n\n v.push(0);\n\n v\n\n}\n\n\n", "file_path": "netidx/src/os/windows.rs", "rank": 44, "score": 144330.5724895848 }, { "content": "fn valid_typ(v: &Value) -> bool {\n\n v.is_number() || Typ::get(v) == Some(Typ::DateTime)\n\n}\n\n\n", "file_path": "netidx-browser/src/widgets.rs", "rank": 45, "score": 137959.6025196028 }, { "content": "fn unwrap_iov(ctx: &mut SecHandle, len: usize, msg: &mut BytesMut) -> Result<BytesMut> {\n\n task::block_in_place(|| {\n\n let mut bufs = [\n\n SecBuffer {\n\n BufferType: sspi::SECBUFFER_STREAM,\n\n cbBuffer: len as u32,\n\n pvBuffer: &mut msg[0..len] as *mut _ as *mut c_void,\n\n },\n\n SecBuffer {\n\n BufferType: sspi::SECBUFFER_DATA,\n\n cbBuffer: 0,\n\n pvBuffer: ptr::null_mut(),\n\n },\n\n ];\n\n let mut bufs_desc = SecBufferDesc {\n\n ulVersion: sspi::SECBUFFER_VERSION,\n\n cBuffers: 2,\n\n pBuffers: bufs.as_mut_ptr(),\n\n };\n\n let mut qop: u32 = 0;\n", "file_path": "netidx/src/os/windows.rs", "rank": 46, "score": 133478.17068303833 }, { "content": "fn alloc_krb5_buf() -> Result<Vec<u8>> {\n\n let mut ifo = ptr::null_mut::<SecPkgInfoW>();\n\n let mut pkg = str_to_wstr(\"Kerberos\");\n\n let res =\n\n unsafe { sspi::QuerySecurityPackageInfoW(pkg.as_mut_ptr(), &mut ifo as *mut _) };\n\n if !SUCCEEDED(res) {\n\n if ifo != ptr::null_mut() {\n\n unsafe {\n\n sspi::FreeContextBuffer(ifo as *mut _);\n\n }\n\n }\n\n bail!(\"failed to query pkg info for Kerberos {}\", format_error(res));\n\n }\n\n let max_len = unsafe { (*ifo).cbMaxToken };\n\n unsafe {\n\n sspi::FreeContextBuffer(ifo as *mut _);\n\n }\n\n let mut buf = Vec::with_capacity(max_len as usize);\n\n buf.extend((0..max_len).into_iter().map(|_| 0));\n\n Ok(buf)\n\n}\n\n\n", "file_path": "netidx/src/os/windows.rs", "rank": 47, "score": 133297.61794444927 }, { "content": "fn err(s: &'static str) -> Value {\n\n Value::Error(Chars::from(s))\n\n}\n\n\n", "file_path": "netidx-tools/src/container/rpcs.rs", "rank": 48, "score": 132306.08152059512 }, { "content": "fn bytes() -> impl Strategy<Value = Bytes> {\n\n any::<Vec<u8>>().prop_map(Bytes::from)\n\n}\n\n\n", "file_path": "netidx-netproto/src/test.rs", "rank": 49, "score": 132238.20619760957 }, { "content": "#[must_use = \"streams do nothing unless polled\"]\n\nstruct Roots(BTreeMap<Path, DefaultHandle>);\n\n\n\nimpl Deref for Roots {\n\n type Target = BTreeMap<Path, DefaultHandle>;\n\n\n\n fn deref(&self) -> &Self::Target {\n\n &self.0\n\n }\n\n}\n\n\n\nimpl DerefMut for Roots {\n\n fn deref_mut(&mut self) -> &mut Self::Target {\n\n &mut self.0\n\n }\n\n}\n\n\n\nimpl<'a> Stream for Roots {\n\n type Item = (Path, oneshot::Sender<()>);\n\n\n\n fn poll_next(\n", "file_path": "netidx-tools/src/container/mod.rs", "rank": 50, "score": 131855.4688222604 }, { "content": "fn remove_eid_from_set<K: Hash + Eq>(\n\n tbl: &mut FxHashMap<K, FxHashSet<ExprId>>,\n\n key: K,\n\n expr_id: &ExprId,\n\n) {\n\n if let Entry::Occupied(mut e) = tbl.entry(key) {\n\n let set = e.get_mut();\n\n set.remove(expr_id);\n\n if set.is_empty() {\n\n e.remove();\n\n }\n\n }\n\n}\n\n\n\nimpl Lc {\n\n fn new(\n\n db: db::Db,\n\n subscriber: Subscriber,\n\n publisher: Publisher,\n\n sub_updates: mpsc::Sender<Pooled<Vec<(SubId, Event)>>>,\n", "file_path": "netidx-tools/src/container/mod.rs", "rank": 51, "score": 131812.73374773114 }, { "content": "fn send_reply(reply: Reply, r: Result<()>) {\n\n match (r, reply) {\n\n (Ok(()), Some(reply)) => {\n\n reply.send(Value::Ok);\n\n }\n\n (Err(e), Some(reply)) => {\n\n let e = Value::Error(Chars::from(format!(\"{}\", e)));\n\n reply.send(e);\n\n }\n\n (_, None) => (),\n\n }\n\n}\n\n\n", "file_path": "netidx-tools/src/container/db.rs", "rank": 53, "score": 130018.01141589106 }, { "content": "pub fn uuid_string(id: Uuid) -> String {\n\n let mut buf = [0u8; SimpleRef::LENGTH];\n\n id.to_simple_ref().encode_lower(&mut buf).into()\n\n}\n\n\n\n/// Simple clustering based on netidx. Each member publishes a uuid to\n\n/// a common base path, which is used to discover all other\n\n/// members. Commands may be sent to and received from all other\n\n/// members as broadcasts. On initialization all members wait until\n\n/// there are at least `shards` other members before starting\n\n/// operations. There can be more than `shards` members at any time,\n\n/// and members can enter and leave the cluster at will. It is up to\n\n/// the user to ensure state integrity under these constraints.\n\n///\n\n/// Messages are encoded to json, so don't expect fantastic\n\n/// performance.\n\n///\n\n/// A random cluster member is elected 'primary' by an common\n\n/// algorithm, the primary may change as members join and leave the\n\n/// cluster, but with a stable member set all members will agree on\n", "file_path": "netidx-protocols/src/cluster.rs", "rank": 54, "score": 129901.71070325721 }, { "content": "fn convert_lifetime(lifetime: LARGE_INTEGER) -> Result<Duration> {\n\n let mut st = SYSTEMTIME::default();\n\n let mut lt = SYSTEMTIME::default();\n\n let mut ft = FILETIME::default();\n\n unsafe {\n\n GetSystemTime(&mut st as *mut _);\n\n if 0 == SystemTimeToTzSpecificLocalTime(\n\n ptr::null_mut(),\n\n &st as *const _,\n\n &mut lt as *mut _,\n\n ) {\n\n bail!(\n\n \"failed to convert to local time {}\",\n\n format_error(GetLastError() as i32)\n\n )\n\n }\n\n if 0 == SystemTimeToFileTime(&lt as *const _, &mut ft as *mut _) {\n\n bail!(\n\n \"failed to convert current time to a filetime: {}\",\n\n format_error(GetLastError() as i32)\n", "file_path": "netidx/src/os/windows.rs", "rank": 55, "score": 128019.55013753312 }, { "content": "fn flt<I>() -> impl Parser<I, Output = String>\n\nwhere\n\n I: RangeStream<Token = char>,\n\n I::Error: ParseError<I::Token, I::Range, I::Position>,\n\n I::Range: Range,\n\n{\n\n choice((\n\n attempt(recognize((\n\n optional(token('-')),\n\n take_while1(|c: char| c.is_digit(10)),\n\n optional(token('.')),\n\n take_while(|c: char| c.is_digit(10)),\n\n token('e'),\n\n int(),\n\n ))),\n\n attempt(recognize((\n\n optional(token('-')),\n\n take_while1(|c: char| c.is_digit(10)),\n\n token('.'),\n\n take_while(|c: char| c.is_digit(10)),\n\n ))),\n\n ))\n\n}\n\n\n", "file_path": "netidx-bscript/src/parser.rs", "rank": 56, "score": 126721.94489672339 }, { "content": "fn interpolated_<I>() -> impl Parser<I, Output = Expr>\n\nwhere\n\n I: RangeStream<Token = char>,\n\n I::Error: ParseError<I::Token, I::Range, I::Position>,\n\n I::Range: Range,\n\n{\n\n #[derive(Debug)]\n\n enum Intp {\n\n Lit(String),\n\n Expr(Expr),\n\n }\n\n impl Intp {\n\n fn to_expr(self) -> Expr {\n\n match self {\n\n Intp::Lit(s) => {\n\n Expr { id: ExprId::new(), kind: ExprKind::Constant(Value::from(s)) }\n\n }\n\n Intp::Expr(s) => s,\n\n }\n\n }\n", "file_path": "netidx-bscript/src/parser.rs", "rank": 57, "score": 126721.94489672339 }, { "content": "fn fname<I>() -> impl Parser<I, Output = String>\n\nwhere\n\n I: RangeStream<Token = char>,\n\n I::Error: ParseError<I::Token, I::Range, I::Position>,\n\n I::Range: Range,\n\n{\n\n recognize((\n\n take_while1(|c: char| c.is_alphabetic() && c.is_lowercase()),\n\n take_while(|c: char| {\n\n (c.is_alphanumeric() && (c.is_numeric() || c.is_lowercase())) || c == '_'\n\n }),\n\n ))\n\n}\n\n\n", "file_path": "netidx-bscript/src/parser.rs", "rank": 58, "score": 126721.94489672339 }, { "content": "fn expr_<I>() -> impl Parser<I, Output = Expr>\n\nwhere\n\n I: RangeStream<Token = char>,\n\n I::Error: ParseError<I::Token, I::Range, I::Position>,\n\n I::Range: Range,\n\n{\n\n spaces().with(choice((\n\n attempt(interpolated()),\n\n attempt(from_str(flt()).map(|v| ExprKind::Constant(Value::F64(v)).to_expr())),\n\n attempt(from_str(int()).map(|v| ExprKind::Constant(Value::I64(v)).to_expr())),\n\n attempt(\n\n string(\"true\")\n\n .skip(not_followed_by(none_of(\" ),]\".chars())))\n\n .map(|_| ExprKind::Constant(Value::True).to_expr()),\n\n ),\n\n attempt(\n\n string(\"false\")\n\n .skip(not_followed_by(none_of(\" ),]\".chars())))\n\n .map(|_| ExprKind::Constant(Value::False).to_expr()),\n\n ),\n", "file_path": "netidx-bscript/src/parser.rs", "rank": 59, "score": 126721.94489672339 }, { "content": "fn int<I>() -> impl Parser<I, Output = String>\n\nwhere\n\n I: RangeStream<Token = char>,\n\n I::Error: ParseError<I::Token, I::Range, I::Position>,\n\n I::Range: Range,\n\n{\n\n recognize((optional(token('-')), take_while1(|c: char| c.is_digit(10))))\n\n}\n\n\n", "file_path": "netidx-bscript/src/parser.rs", "rank": 60, "score": 126721.94489672339 }, { "content": "fn uint<I>() -> impl Parser<I, Output = String>\n\nwhere\n\n I: RangeStream<Token = char>,\n\n I::Error: ParseError<I::Token, I::Range, I::Position>,\n\n I::Range: Range,\n\n{\n\n many1(digit())\n\n}\n\n\n", "file_path": "netidx-bscript/src/parser.rs", "rank": 61, "score": 126721.94489672339 }, { "content": "fn quoted<I>() -> impl Parser<I, Output = String>\n\nwhere\n\n I: RangeStream<Token = char>,\n\n I::Error: ParseError<I::Token, I::Range, I::Position>,\n\n I::Range: Range,\n\n{\n\n spaces().with(between(token('\"'), token('\"'), escaped_string()))\n\n}\n\n\n", "file_path": "netidx-bscript/src/parser.rs", "rank": 62, "score": 126721.94489672339 }, { "content": "fn base64str<I>() -> impl Parser<I, Output = String>\n\nwhere\n\n I: RangeStream<Token = char>,\n\n I::Error: ParseError<I::Token, I::Range, I::Position>,\n\n I::Range: Range,\n\n{\n\n recognize((\n\n take_while(|c: char| c.is_ascii_alphanumeric() || c == '+' || c == '/'),\n\n take_while(|c: char| c == '='),\n\n ))\n\n}\n\n\n", "file_path": "netidx-bscript/src/parser.rs", "rank": 63, "score": 126721.94489672339 }, { "content": "#[derive(Clone, GBoxed)]\n\n#[gboxed(type_name = \"NetidxExprInspectorWrap\")]\n\nstruct ExprWrap(Arc<dyn Fn(&Value)>);\n\n\n\nstatic KINDS: [&'static str; 2] = [\"constant\", \"function\"];\n\n\n", "file_path": "netidx-browser/src/editor/expr_inspector.rs", "rank": 64, "score": 125214.85237099843 }, { "content": "fn escaped_string<I>() -> impl Parser<I, Output = String>\n\nwhere\n\n I: RangeStream<Token = char>,\n\n I::Error: ParseError<I::Token, I::Range, I::Position>,\n\n I::Range: Range,\n\n{\n\n recognize(escaped(\n\n take_while1(|c| !PATH_ESC.contains(&c)),\n\n '\\\\',\n\n one_of(PATH_ESC.iter().copied()),\n\n ))\n\n .map(|s| match utils::unescape(&s, '\\\\') {\n\n Cow::Borrowed(_) => s, // it didn't need unescaping, so just return it\n\n Cow::Owned(s) => s,\n\n })\n\n}\n\n\n", "file_path": "netidx-bscript/src/parser.rs", "rank": 65, "score": 124616.01581436276 }, { "content": "#[derive(Debug, Clone, Copy)]\n\nenum WidgetPath {\n\n Leaf,\n\n Box(usize),\n\n GridItem(usize, usize),\n\n GridRow(usize),\n\n}\n\n\n", "file_path": "netidx-browser/src/main.rs", "rank": 66, "score": 123495.95606817945 }, { "content": "fn try_flush(con: &mut WriteChannel<ClientCtx>) -> Result<()> {\n\n if con.bytes_queued() > 0 {\n\n con.try_flush()?;\n\n Ok(())\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "netidx/src/subscriber.rs", "rank": 67, "score": 123211.64132875536 }, { "content": "fn check<T: Pack + Debug + PartialEq>(t: T) {\n\n let mut bytes = pack(&t).expect(\"encode failed\");\n\n assert_eq!(t.encoded_len(), BytesMut::len(&bytes));\n\n let u = T::decode(&mut bytes).expect(\"decode failed\");\n\n assert_eq!(t, u)\n\n}\n\n\n", "file_path": "netidx-netproto/src/test.rs", "rank": 68, "score": 122935.8233392788 }, { "content": "type Result<T> = result::Result<T, PackError>;\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]\n\npub enum Typ {\n\n U32,\n\n V32,\n\n I32,\n\n Z32,\n\n U64,\n\n V64,\n\n I64,\n\n Z64,\n\n F32,\n\n F64,\n\n DateTime,\n\n Duration,\n\n Bool,\n\n String,\n\n Bytes,\n\n Result,\n", "file_path": "netidx-netproto/src/value.rs", "rank": 69, "score": 122530.01808386805 }, { "content": "type Result<T> = result::Result<T, PackError>;\n\n\n\natomic_id!(Id);\n\n\n\nimpl Pack for Id {\n\n fn encoded_len(&self) -> usize {\n\n pack::varint_len(self.0)\n\n }\n\n\n\n fn encode(&self, buf: &mut impl BufMut) -> Result<()> {\n\n Ok(pack::encode_varint(self.0, buf))\n\n }\n\n\n\n fn decode(buf: &mut impl Buf) -> Result<Self> {\n\n Ok(Id(pack::decode_varint(buf)?))\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub enum Hello {\n", "file_path": "netidx-netproto/src/publisher.rs", "rank": 70, "score": 122530.01808386805 }, { "content": "fn default_expr(id: Option<&str>) -> expr::Expr {\n\n match id {\n\n Some(\"constant\") | None => expr::ExprKind::Constant(Value::U64(42)).to_expr(),\n\n Some(\"function\") => {\n\n let args = vec![expr::ExprKind::Constant(Value::U64(42)).to_expr()];\n\n expr::ExprKind::Apply { function: \"any\".into(), args }.to_expr()\n\n }\n\n e => unreachable!(\"{:?}\", e),\n\n }\n\n}\n\n\n", "file_path": "netidx-browser/src/editor/expr_inspector.rs", "rank": 71, "score": 121575.41134626778 }, { "content": "pub trait Poolable {\n\n fn empty() -> Self;\n\n fn reset(&mut self);\n\n fn capacity(&self) -> usize;\n\n}\n\n\n\nimpl<K, V, R> Poolable for HashMap<K, V, R>\n\nwhere\n\n K: Hash + Eq,\n\n R: Default + BuildHasher,\n\n{\n\n fn empty() -> Self {\n\n HashMap::default()\n\n }\n\n\n\n fn reset(&mut self) {\n\n self.clear()\n\n }\n\n\n\n fn capacity(&self) -> usize {\n", "file_path": "netidx-core/src/pool.rs", "rank": 72, "score": 121076.68813451254 }, { "content": "enum DirNames<'a> {\n\n Root(bool),\n\n Path { cur: &'a str, all: &'a str, base: usize },\n\n}\n\n\n\nimpl<'a> Iterator for DirNames<'a> {\n\n type Item = &'a str;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n match self {\n\n DirNames::Root(false) => None,\n\n DirNames::Root(true) => {\n\n *self = DirNames::Root(false);\n\n Some(\"/\")\n\n }\n\n DirNames::Path { ref mut cur, ref all, ref mut base } => {\n\n if *base == all.len() {\n\n None\n\n } else {\n\n match Path::find_sep(cur) {\n", "file_path": "netidx-core/src/path.rs", "rank": 73, "score": 120893.20355142525 }, { "content": "fn to_chars(value: Value) -> Chars {\n\n value.cast_to::<Chars>().ok().unwrap_or_else(|| Chars::from(\"null\"))\n\n}\n\n\n", "file_path": "netidx-tools/src/container/mod.rs", "rank": 74, "score": 118597.80839744343 }, { "content": "fn read_task<C: Krb5Ctx + Clone + Debug + Send + Sync + 'static>(\n\n stop: oneshot::Receiver<()>,\n\n mut soc: ReadHalf<TcpStream>,\n\n mut set_ctx: oneshot::Receiver<C>,\n\n) -> Receiver<BytesMut> {\n\n let (mut tx, rx) = mpsc::channel(3);\n\n task::spawn(async move {\n\n let mut stop = stop.fuse();\n\n let mut ctx: Option<C> = None;\n\n let mut buf = BytesMut::with_capacity(BUF);\n\n let res: Result<()> = 'main: loop {\n\n while buf.remaining() >= mem::size_of::<u32>() {\n\n let (encrypted, len) = {\n\n let hdr = BigEndian::read_u32(&*buf);\n\n if hdr > LEN_MASK {\n\n (true, (hdr & LEN_MASK) as usize)\n\n } else {\n\n (false, hdr as usize)\n\n }\n\n };\n", "file_path": "netidx/src/channel.rs", "rank": 75, "score": 116898.30812546302 }, { "content": "fn collect_chars_vec(\n\n args: &mut Pooled<HashMap<Arc<str>, Pooled<Vec<Value>>>>,\n\n name: &str,\n\n) -> Result<Vec<Chars>> {\n\n match args.remove(name) {\n\n None => bail!(\"required argument {} is missing\", name),\n\n Some(mut rows) => {\n\n let mut res = Vec::new();\n\n for v in rows.drain(..) {\n\n match v.cast_to::<Chars>() {\n\n Err(_) => bail!(\"invalid rows type, expected string\"),\n\n Ok(row) => res.push(row),\n\n }\n\n }\n\n Ok(res)\n\n }\n\n }\n\n}\n\n\n\npub(super) fn start_create_table_rpc(\n", "file_path": "netidx-tools/src/container/rpcs.rs", "rank": 76, "score": 114915.651465397 }, { "content": "#[derive(Debug)]\n\nstruct PoolInner<T: Poolable + Send + Sync + 'static> {\n\n pool: ArrayQueue<T>,\n\n max_elt_capacity: usize,\n\n}\n\n\n\n/// a lock-free, thread-safe, dynamically-sized object pool.\n\n///\n\n/// this pool begins with an initial capacity and will continue\n\n/// creating new objects on request when none are available. pooled\n\n/// objects are returned to the pool on destruction (with an extra\n\n/// provision to optionally \"reset\" the state of an object for\n\n/// re-use).\n\n///\n\n/// if, during an attempted return, a pool already has\n\n/// `maximum_capacity` objects in the pool, the pool will throw away\n\n/// that object.\n\n#[derive(Clone, Debug)]\n\npub struct Pool<T: Poolable + Send + Sync + 'static>(Arc<PoolInner<T>>);\n\n\n\nimpl<T: Poolable + Sync + Send + 'static> Pool<T> {\n", "file_path": "netidx-core/src/pool.rs", "rank": 77, "score": 113982.70256292798 }, { "content": "fn choose_location(parent: &gtk::ApplicationWindow, save: bool) -> Option<ViewLoc> {\n\n enum W {\n\n File(gtk::FileChooserWidget),\n\n Netidx(gtk::Box),\n\n }\n\n let d = gtk::Dialog::with_buttons(\n\n Some(\"Choose Location\"),\n\n Some(parent),\n\n gtk::DialogFlags::MODAL | gtk::DialogFlags::USE_HEADER_BAR,\n\n &[(\"Cancel\", gtk::ResponseType::Cancel), (\"Choose\", gtk::ResponseType::Accept)],\n\n );\n\n let loc: Rc<RefCell<Option<ViewLoc>>> = Rc::new(RefCell::new(None));\n\n let mainw: Rc<RefCell<Option<W>>> = Rc::new(RefCell::new(None));\n\n let root = d.get_content_area();\n\n let cb = gtk::ComboBoxText::new();\n\n cb.append(Some(\"Netidx\"), \"Netidx\");\n\n cb.append(Some(\"File\"), \"File\");\n\n root.add(&cb);\n\n root.add(&gtk::Separator::new(gtk::Orientation::Vertical));\n\n cb.connect_changed(clone!(@weak root, @strong loc, @strong mainw => move |cb| {\n", "file_path": "netidx-browser/src/main.rs", "rank": 78, "score": 113378.12042985219 }, { "content": "fn start_path_arg_rpc(\n\n publisher: &Publisher,\n\n base_path: &Path,\n\n name: &'static str,\n\n doc: &'static str,\n\n argdoc: &'static str,\n\n f: fn(Path) -> RpcRequestKind,\n\n tx: mpsc::Sender<RpcRequest>,\n\n) -> Result<Proc> {\n\n Ok(Proc::new(\n\n publisher,\n\n base_path.append(name),\n\n Value::from(doc),\n\n vec![(Arc::from(\"path\"), (Value::Null, Value::from(argdoc)))]\n\n .into_iter()\n\n .collect(),\n\n Arc::new(move |_addr, mut args| {\n\n let mut tx = tx.clone();\n\n Box::pin(async move {\n\n match args.remove(\"path\") {\n", "file_path": "netidx-tools/src/container/rpcs.rs", "rank": 79, "score": 112609.76943451604 }, { "content": "fn query_pkg_sizes(ctx: &mut SecHandle, sz: &mut SecPkgContext_Sizes) -> Result<()> {\n\n let res = unsafe {\n\n sspi::QueryContextAttributesW(\n\n ctx as *mut _,\n\n SECPKG_ATTR_SIZES,\n\n sz as *mut _ as *mut c_void,\n\n )\n\n };\n\n if !SUCCEEDED(res) {\n\n bail!(\"failed to query package sizes {}\", format_error(res))\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "netidx/src/os/windows.rs", "rank": 80, "score": 108607.0383351685 }, { "content": "#[derive(Debug, Clone)]\n\nenum In {\n\n Add(Path),\n\n Drop(Path),\n\n Write(Path, Value),\n\n Call(Path, Vec<(String, Value)>),\n\n}\n\n\n\nimpl FromStr for In {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> Result<Self> {\n\n if s.starts_with(\"DROP|\") && s.len() > 5 {\n\n Ok(In::Drop(Path::from(ArcStr::from(&s[5..]))))\n\n } else if s.starts_with(\"ADD|\") && s.len() > 4 {\n\n Ok(In::Add(Path::from(ArcStr::from(&s[4..]))))\n\n } else if s.starts_with(\"WRITE|\") && s.len() > 6 {\n\n let mut parts = s[6..].splitn(3, \"|\");\n\n let path = parts.next().ok_or_else(|| anyhow!(\"expected | before path\"))?;\n\n let path = Path::from(ArcStr::from(path));\n\n let typ = parts\n", "file_path": "netidx-tools/src/subscriber.rs", "rank": 81, "score": 82222.73303597701 }, { "content": "#[derive(Debug)]\n\nenum ToCon {\n\n Subscribe(SubscribeValRequest),\n\n Unsubscribe(Id),\n\n Stream {\n\n id: Id,\n\n sub_id: SubId,\n\n tx: Sender<Pooled<Vec<(SubId, Event)>>>,\n\n flags: UpdatesFlags,\n\n },\n\n Write(Id, Value, Option<oneshot::Sender<Value>>),\n\n Flush(oneshot::Sender<()>),\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, PartialOrd)]\n\npub enum Event {\n\n Unsubscribed,\n\n Update(Value),\n\n}\n\n\n\nimpl Pack for Event {\n", "file_path": "netidx/src/subscriber.rs", "rank": 82, "score": 82217.57465298938 }, { "content": "struct Client {\n\n msg_queue: MsgQ,\n\n subscribed: HashMap<Id, Permissions, FxBuildHasher>,\n\n}\n\n\n", "file_path": "netidx/src/publisher.rs", "rank": 83, "score": 81270.5603158365 }, { "content": "#[derive(Debug)]\n\nstruct Router {\n\n cached: BTreeMap<Path, (Instant, Arc<Referral>)>,\n\n}\n\n\n\nimpl Router {\n\n fn new() -> Self {\n\n Router { cached: BTreeMap::new() }\n\n }\n\n\n\n fn route_batch<T>(\n\n &mut self,\n\n pool: &Pool<Vec<(usize, T)>>,\n\n batch: &Pooled<Vec<T>>,\n\n ) -> impl Iterator<Item = (Option<Arc<Referral>>, Pooled<Vec<(usize, T)>>)>\n\n where\n\n T: ToPath + Clone + Send + Sync + 'static,\n\n {\n\n let now = Instant::now();\n\n let mut batches = HashMap::new();\n\n let mut gc = Vec::new();\n", "file_path": "netidx/src/resolver.rs", "rank": 84, "score": 81270.5603158365 }, { "content": "struct Published {\n\n current: Value,\n\n subscribed: Subscribed,\n\n path: Path,\n\n}\n\n\n", "file_path": "netidx/src/publisher.rs", "rank": 85, "score": 81270.5603158365 }, { "content": "struct Sub {\n\n path: Path,\n\n sub_id: SubId,\n\n streams: Streams,\n\n last: Option<TArc<Mutex<Event>>>,\n\n}\n\n\n", "file_path": "netidx/src/subscriber.rs", "rank": 86, "score": 81270.5603158365 }, { "content": "#[derive(StructOpt, Debug)]\n\nenum Stress {\n\n #[structopt(name = \"publisher\", about = \"run a stress test publisher\")]\n\n Publisher {\n\n #[structopt(\n\n short = \"b\",\n\n long = \"bind\",\n\n help = \"configure the bind address e.g. 192.168.0.0/16, 127.0.0.1:5000\"\n\n )]\n\n bind: BindCfg,\n\n #[structopt(long = \"spn\", help = \"krb5 use <spn>\")]\n\n spn: Option<String>,\n\n #[structopt(\n\n long = \"delay\",\n\n help = \"time in ms to wait between batches\",\n\n default_value = \"100\"\n\n )]\n\n delay: u64,\n\n #[structopt(name = \"rows\", default_value = \"100\")]\n\n rows: usize,\n\n #[structopt(name = \"cols\", default_value = \"10\")]\n\n cols: usize,\n\n },\n\n #[structopt(name = \"subscriber\", about = \"run a stress test subscriber\")]\n\n Subscriber,\n\n}\n\n\n", "file_path": "netidx-tools/src/main.rs", "rank": 87, "score": 80820.05567380984 }, { "content": "#[derive(StructOpt, Debug)]\n\nenum Sub {\n\n #[structopt(name = \"resolver-server\", about = \"run a resolver\")]\n\n ResolverServer {\n\n #[structopt(short = \"f\", long = \"foreground\", help = \"don't daemonize\")]\n\n foreground: bool,\n\n #[structopt(\n\n long = \"delay-reads\",\n\n help = \"don't allow read clients until 1 writer ttl has passed\"\n\n )]\n\n delay_reads: bool,\n\n #[structopt(\n\n long = \"id\",\n\n help = \"index of the address to bind to\",\n\n default_value = \"0\"\n\n )]\n\n id: usize,\n\n #[structopt(\n\n short = \"p\",\n\n long = \"permissions\",\n\n help = \"location of the permissions file\"\n", "file_path": "netidx-tools/src/main.rs", "rank": 88, "score": 80820.05567380984 }, { "content": "#[derive(Debug, Clone)]\n\nenum ToClientMsg {\n\n Val(Id, Value),\n\n Unpublish(Id),\n\n}\n\n\n\nimpl ToClientMsg {\n\n fn id(&self) -> Id {\n\n match self {\n\n ToClientMsg::Val(id, _) => *id,\n\n ToClientMsg::Unpublish(id) => *id,\n\n }\n\n }\n\n}\n\n\n", "file_path": "netidx/src/publisher.rs", "rank": 89, "score": 80819.76367268029 }, { "content": "#[derive(Debug, Clone)]\n\nenum ToGui {\n\n View { loc: Option<ViewLoc>, spec: view::View, generated: bool },\n\n NavigateInWindow(ViewLoc),\n\n Highlight(Vec<WidgetPath>),\n\n Update(Batch),\n\n UpdateVar(Chars, Value),\n\n UpdateRpc(RpcCallId, Value),\n\n TableResolved(Path, resolver::Table),\n\n ShowError(String),\n\n SaveError(String),\n\n Terminate,\n\n}\n\n\n", "file_path": "netidx-browser/src/main.rs", "rank": 90, "score": 80819.76367268029 }, { "content": "#[derive(Debug)]\n\nenum DvState {\n\n Subscribed(Val),\n\n Dead(Box<DvDead>),\n\n}\n\n\n", "file_path": "netidx/src/subscriber.rs", "rank": 91, "score": 80814.60528969266 }, { "content": "#[derive(Debug)]\n\nenum FromGui {\n\n Navigate(ViewLoc),\n\n Render(view::View),\n\n ResolveTable(Path),\n\n Save(ViewLoc, view::View, oneshot::Sender<Result<()>>),\n\n CallRpc(Path, Vec<(Chars, Value)>, RpcCallId),\n\n Updated,\n\n Terminate,\n\n}\n\n\n", "file_path": "netidx-browser/src/main.rs", "rank": 92, "score": 80814.60528969266 }, { "content": "enum ToBackend {\n\n CreateCtx {\n\n to_gui: glib::Sender<ToGui>,\n\n raw_view: Arc<AtomicBool>,\n\n reply: OneShot<Ctx>,\n\n },\n\n Stop,\n\n}\n\n\n\n#[derive(Clone)]\n\npub(crate) struct Backend(mpsc::UnboundedSender<ToBackend>);\n\n\n\nimpl Backend {\n\n pub(crate) fn new(cfg: Config, auth: Auth) -> (thread::JoinHandle<()>, Backend) {\n\n let (tx_create_ctx, mut rx_create_ctx) = mpsc::unbounded();\n\n let join_handle = {\n\n thread::spawn(move || {\n\n let rt = Runtime::new().expect(\"failed to create tokio runtime\");\n\n rt.block_on(async move {\n\n let sub = Subscriber::new(cfg, auth).unwrap();\n", "file_path": "netidx-browser/src/backend.rs", "rank": 93, "score": 80814.60528969266 }, { "content": "enum Widget {\n\n Action(widgets::Action),\n\n Table(table::Table),\n\n Label(widgets::Label),\n\n Button(widgets::Button),\n\n LinkButton(widgets::LinkButton),\n\n Toggle(widgets::Toggle),\n\n Selector(widgets::Selector),\n\n Entry(widgets::Entry),\n\n Frame(containers::Frame),\n\n Box(containers::Box),\n\n Grid(containers::Grid),\n\n Paned(containers::Paned),\n\n Notebook(containers::Notebook),\n\n LinePlot(widgets::LinePlot),\n\n}\n\n\n\nimpl Widget {\n\n fn new(ctx: &BSCtx, spec: view::Widget, selected_path: gtk::Label) -> Widget {\n\n let w = match spec.kind {\n", "file_path": "netidx-browser/src/main.rs", "rank": 94, "score": 80814.60528969266 }, { "content": "#[derive(Debug)]\n\nenum SubStatus {\n\n Subscribed(ValWeak),\n\n Pending(Vec<oneshot::Sender<Result<Val>>>),\n\n}\n\n\n\nconst REMEBER_FAILED: Duration = Duration::from_secs(60);\n\n\n", "file_path": "netidx/src/subscriber.rs", "rank": 95, "score": 80814.60528969266 }, { "content": "#[derive(StructOpt, Debug)]\n\n#[structopt(name = \"netidx\")]\n\nstruct Opt {\n\n #[structopt(\n\n short = \"c\",\n\n long = \"config\",\n\n help = \"override the default config file location (~/.config/netidx.json)\"\n\n )]\n\n config: Option<String>,\n\n #[structopt(short = \"a\", long = \"anonymous\", help = \"disable Kerberos 5\")]\n\n anon: bool,\n\n #[structopt(long = \"upn\", help = \"krb5 use <upn> instead of the current user\")]\n\n upn: Option<String>,\n\n #[structopt(long = \"path\", help = \"navigate to <path> on startup\")]\n\n path: Option<Path>,\n\n #[structopt(long = \"file\", help = \"navigate to view file on startup\")]\n\n file: Option<PathBuf>,\n\n}\n\n\n", "file_path": "netidx-browser/src/main.rs", "rank": 96, "score": 79876.04292139992 }, { "content": "#[derive(StructOpt, Debug)]\n\n#[structopt(name = \"json-pubsub\")]\n\nstruct Opt {\n\n #[structopt(\n\n short = \"c\",\n\n long = \"config\",\n\n help = \"override the default config file location (~/.config/netidx.json)\"\n\n )]\n\n config: Option<String>,\n\n #[structopt(short = \"a\", long = \"anonymous\", help = \"disable Kerberos 5\")]\n\n anon: bool,\n\n #[structopt(long = \"upn\", help = \"krb5 use <upn> instead of the current user\")]\n\n upn: Option<String>,\n\n #[structopt(subcommand)]\n\n cmd: Sub,\n\n}\n\n\n", "file_path": "netidx-tools/src/main.rs", "rank": 97, "score": 79875.99504276479 }, { "content": "#[derive(Debug)]\n\nstruct DvDead {\n\n queued_writes: Vec<(Value, Option<oneshot::Sender<Value>>)>,\n\n tries: usize,\n\n next_try: Instant,\n\n}\n\n\n", "file_path": "netidx/src/subscriber.rs", "rank": 98, "score": 79870.74155658745 }, { "content": "#[derive(Debug)]\n\nstruct ValInner {\n\n sub_id: SubId,\n\n id: Id,\n\n conid: ConId,\n\n connection: BatchSender<ToCon>,\n\n last: TArc<Mutex<Event>>,\n\n}\n\n\n\nimpl Drop for ValInner {\n\n fn drop(&mut self) {\n\n self.connection.send(ToCon::Unsubscribe(self.id));\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct ValWeak(Weak<ValInner>);\n\n\n\nimpl ValWeak {\n\n pub fn upgrade(&self) -> Option<Val> {\n\n Weak::upgrade(&self.0).map(|r| Val(r))\n", "file_path": "netidx/src/subscriber.rs", "rank": 99, "score": 79870.74155658745 } ]
Rust
src/vendor/h3c/reply.rs
jiegec/netconf-rs
ea67624060fcf7f1ff29e58d38bfbd010297c1c0
use serde_derive::Deserialize; #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct RpcReply { pub data: Data, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Data { pub top: Option<Top>, #[serde(rename = "netconf-state")] pub netconf_state: Option<NetconfState>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Top { #[serde(rename = "Ifmgr")] pub ifmgr: Option<Ifmgr>, #[serde(rename = "MAC")] pub mac: Option<Mac>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Ifmgr { #[serde(rename = "Interfaces")] pub interfaces: Interfaces, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Interfaces { #[serde(rename = "Interface")] pub interface: Vec<Interface>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Interface { #[serde(rename = "IfIndex")] pub index: usize, #[serde(rename = "Description")] pub description: Option<String>, #[serde(rename = "PVID")] pub port_vlan_id: Option<usize>, #[serde(rename = "ConfigMTU")] pub mtu: Option<usize>, #[serde(rename = "LinkType")] pub link_type: Option<usize>, #[serde(rename = "PortLayer")] pub port_layer: Option<usize>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct NetconfState { pub capabilities: Capabilities, pub schemas: Schemas, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Capabilities { pub capability: Vec<String>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Schemas { pub schema: Vec<Schema>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Schema { pub identifier: String, pub version: String, pub format: String, pub namespace: String, pub location: String, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Mac { #[serde(rename = "MacUnicastTable")] pub table: MacUnicastTable, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct MacUnicastTable { #[serde(rename = "Unicast")] pub unicast: Vec<Unicast>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Unicast { #[serde(rename = "VLANID")] pub vlan_id: usize, #[serde(rename = "MacAddress")] pub mac_address: String, #[serde(rename = "PortIndex")] pub port_index: usize, #[serde(rename = "Status")] pub status: usize, #[serde(rename = "Aging")] pub aging: bool, } #[cfg(test)] mod tests { use super::*; use serde_xml_rs::from_str; #[test] fn parse_mac_table() { let resp = r#" <?xml version="1.0" encoding="UTF-8"?> <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="100"> <data> <top xmlns="http://www.h3c.com/netconf/data:1.0"> <MAC> <MacUnicastTable> <Unicast> <VLANID>1</VLANID> <MacAddress>12-34-56-78-90-AB</MacAddress> <PortIndex>634</PortIndex> <Status>2</Status> <Aging>true</Aging> </Unicast> <Unicast> <VLANID>2</VLANID> <MacAddress>11-11-11-11-11-11</MacAddress> <PortIndex>10</PortIndex> <Status>2</Status> <Aging>true</Aging> </Unicast> </MacUnicastTable> </MAC> </top> </data> </rpc-reply> "#; let reply: RpcReply = from_str(&resp).unwrap(); assert_eq!( reply, RpcReply { data: Data { top: Some(Top { ifmgr: None, mac: Some(Mac { table: MacUnicastTable { unicast: vec![ Unicast { vlan_id: 1, mac_address: String::from("12-34-56-78-90-AB"), port_index: 634, status: 2, aging: true }, Unicast { vlan_id: 2, mac_address: String::from("11-11-11-11-11-11"), port_index: 10, status: 2, aging: true } ] } }) }), netconf_state: None } } ); } }
use serde_derive::Deserialize; #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct RpcReply { pub data: Data, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Data { pub top: Option<Top>, #[serde(rename = "netconf-state")] pub netconf_state: Option<NetconfState>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Top { #[serde(rename = "Ifmgr")] pub ifmgr: Option<Ifmgr>, #[serde(rename = "MAC")] pub mac: Option<Mac>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Ifmgr { #[serde(rename = "Interfaces")] pub interfaces: Interfaces, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Interfaces { #[serde(rename = "Interface")] pub interface: Vec<Interface>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Interface { #[serde(rename = "IfIndex")] pub index: usize, #[serde(rename = "Description")] pub description: Option<String>, #[serde(rename = "PVID")] pub port_vlan_id: Option<usize>, #[serde(rename = "ConfigMTU")] pub mtu: Option<usize>, #[serde(rename = "LinkType")] pub link_type: Option<usize>, #[serde(rename = "PortLayer")] pub port_layer: Option<usize>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct NetconfState { pub capabilities: Capabilities, pub schemas: Schemas, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Capabilities { pub capability: Vec<String>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Schemas { pub schema: Vec<Schema>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Schema { pub identifier: String, pub version: String, pub format: String, pub namespace: String, pub location: String, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Mac { #[serde(rename = "MacUnicastTable")] pub table: MacUnicastTable, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct MacUnicastTable { #[serde(rename = "Unicast")] pub unicast: Vec<Unicast>, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Unicast { #[serde(rename = "VLANID")] pub vlan_id: usize, #[serde(rename = "MacAddress")] pub mac_address: String, #[serde(rename = "PortIndex")] pub port_index: usize, #[serde(rename = "Status")] pub status: usize, #[serde(rename = "Aging")] pub aging: bool, } #[cfg(test)] mod tests { use super::*; use serde_xml_rs::from_str; #[test] fn parse_mac_table() { let resp = r#" <?xml version="1.0" encoding="UTF-8"?> <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="100"> <data> <top xmlns="http://www.h3c.com/netconf/data:1.0"> <MAC> <MacUnicastTable> <Unicast> <VLANID>1</VLANID> <MacAddress>12-34-56-78-90-AB</MacAddress> <PortIndex>634</PortIndex> <Status>2</Status> <Aging>true</Aging> </Unicast> <Unicast> <VLANID>2</VLANID> <MacAddress>11-11-11-11-11-11</MacAddress> <PortIndex>10</PortIndex> <Status>2</Status> <Aging>true</Aging> </Unicast> </MacUnicastTable> </MAC> </top> </data> </rpc-reply> "#; let reply: RpcReply = from_str(&resp).unwrap(); assert_eq!( reply, RpcReply { data: Data { top: Some(Top { ifmgr: None, mac: Some(Mac { table: MacUnicastTable { unicast: vec![ Unicast { vlan_id:
}
1, mac_address: String::from("12-34-56-78-90-AB"), port_index: 634, status: 2, aging: true }, Unicast { vlan_id: 2, mac_address: String::from("11-11-11-11-11-11"), port_index: 10, status: 2, aging: true } ] } }) }), netconf_state: None } } ); }
function_block-function_prefixed
[ { "content": "#[derive(Debug, Deserialize)]\n\nstruct Capabilities {\n\n pub capability: Vec<String>,\n\n}\n\n\n\n/// A connection to NETCONF server\n\npub struct Connection {\n\n pub(crate) transport: Box<dyn Transport + Send + 'static>,\n\n}\n\n\n\nimpl Connection {\n\n pub fn new(transport: impl Transport + 'static) -> io::Result<Connection> {\n\n let mut res = Connection {\n\n transport: Box::from(transport),\n\n };\n\n res.hello()?;\n\n Ok(res)\n\n }\n\n\n\n fn hello(&mut self) -> io::Result<()> {\n\n debug!(\"Get capabilities of NetConf server\");\n", "file_path": "src/lib.rs", "rank": 0, "score": 33592.77774168742 }, { "content": "/// Trait for NETCONF transport\n\npub trait Transport: Send {\n\n fn read_xml(&mut self) -> io::Result<String>;\n\n fn write_xml(&mut self, data: &str) -> io::Result<()>;\n\n}\n", "file_path": "src/transport/mod.rs", "rank": 1, "score": 27303.004057242993 }, { "content": "fn main() {\n\n env_logger::init();\n\n let mut args = std::env::args();\n\n args.next();\n\n let addr = args.next().unwrap();\n\n info!(\"connecting to {}\", addr);\n\n let ssh = netconf_rs::transport::ssh::SSHTransport::connect(&addr, \"admin\", \"admin\").unwrap();\n\n let mut conn = Connection::new(ssh).unwrap();\n\n conn.get_config().unwrap();\n\n get_netconf_information(&mut conn).unwrap();\n\n //get_schema(&mut conn, \"openconfig-network-instance-l2\", \"2018-03-28\", \"yang\").unwrap();\n\n get_mac_table(&mut conn).unwrap();\n\n /*\n\n get_vlan_config(&mut conn).unwrap();\n\n\n\n // create vlan 10 and 11\n\n create_vlan(&mut conn, 10, \"Test VLAN 10\").unwrap();\n\n create_vlan(&mut conn, 11, \"Test VLAN 11\").unwrap();\n\n\n\n // assign access ports\n", "file_path": "examples/ssh.rs", "rank": 2, "score": 21460.25172767359 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct Hello {\n\n pub capabilities: Capabilities,\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 3, "score": 20221.806330938787 }, { "content": "//! Transports for NETCONF\n\n\n\nuse std::io;\n\n\n\npub mod ssh;\n\n\n\n/// Trait for NETCONF transport\n", "file_path": "src/transport/mod.rs", "rank": 4, "score": 12998.881152496391 }, { "content": "use crate::transport::Transport;\n\nuse log::*;\n\nuse serde_derive::Deserialize;\n\nuse serde_xml_rs::from_str;\n\nuse std::io;\n\n\n\npub mod transport;\n\npub mod vendor;\n\n\n\n#[derive(Debug, Deserialize)]\n", "file_path": "src/lib.rs", "rank": 5, "score": 6.811122894203692 }, { "content": " self.transport.write_xml(\n\n r#\"\n\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n\n <capabilities>\n\n <capability>\n\n urn:ietf:params:netconf:base:1.0\n\n </capability>\n\n </capabilities>\n\n</hello>\n\n]]>]]>\n\n \"#,\n\n )?;\n\n let resp = self.transport.read_xml()?;\n\n let hello: Hello = from_str(&resp).unwrap();\n\n debug!(\"{:#?}\", hello);\n\n Ok(())\n\n }\n\n\n\n pub fn get_config(&mut self) -> io::Result<String> {\n", "file_path": "src/lib.rs", "rank": 6, "score": 6.314155669903867 }, { "content": "impl Transport for SSHTransport {\n\n fn read_xml(&mut self) -> io::Result<String> {\n\n let mut buffer = [0u8; 128];\n\n let search = TwoWaySearcher::new(\"]]>]]>\".as_bytes());\n\n while search.search_in(&self.read_buffer).is_none() {\n\n let bytes = self.channel.read(&mut buffer)?;\n\n self.read_buffer.extend(&buffer[..bytes]);\n\n }\n\n let pos = search.search_in(&self.read_buffer).unwrap();\n\n let resp = String::from_utf8(self.read_buffer[..pos].to_vec()).unwrap();\n\n // 6: ]]>]]>\n\n self.read_buffer.drain(0..(pos + 6));\n\n Ok(resp)\n\n }\n\n\n\n fn write_xml(&mut self, data: &str) -> io::Result<()> {\n\n write!(&mut self.channel, r#\"{}]]>]]>\"#, data.trim())?;\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/transport/ssh.rs", "rank": 7, "score": 4.689924718591702 }, { "content": " self.transport.write_xml(\n\n r#\"\n\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<rpc message-id=\"100\"\n\n xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n\n <get-config>\n\n <source>\n\n <running/>\n\n </source>\n\n </get-config>\n\n</rpc>\n\n \"#,\n\n )?;\n\n let resp = self.transport.read_xml()?;\n\n Ok(resp)\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 8, "score": 3.796812819051194 }, { "content": "//! SSH transport\n\n\n\nuse crate::transport::Transport;\n\nuse memmem::{Searcher, TwoWaySearcher};\n\nuse ssh2::Channel;\n\nuse ssh2::Session;\n\nuse std::io;\n\nuse std::io::{Read, Write};\n\nuse std::net::TcpStream;\n\n\n\n/// NETCONF over SSH\n\npub struct SSHTransport {\n\n session: Session,\n\n channel: Channel,\n\n read_buffer: Vec<u8>,\n\n}\n\n\n\nimpl SSHTransport {\n\n pub fn connect(addr: &str, user_name: &str, password: &str) -> io::Result<SSHTransport> {\n\n let tcp = TcpStream::connect(addr)?;\n", "file_path": "src/transport/ssh.rs", "rank": 9, "score": 3.0086161753162086 }, { "content": "use log::*;\n\nuse netconf_rs;\n\nuse netconf_rs::vendor::h3c::*;\n\nuse netconf_rs::Connection;\n\n\n", "file_path": "examples/ssh.rs", "rank": 10, "score": 1.9252826241032726 }, { "content": " // port 1 access vlan 10\n\n set_vlan_access_port(&mut conn, 1, 10).unwrap();\n\n // port 2 access vlan 11\n\n set_vlan_access_port(&mut conn, 2, 11).unwrap();\n\n\n\n // assign trunk ports\n\n // port 9 trunk permit 1025 pvid 1025\n\n set_vlan_trunk_port(&mut conn, 9, &[1025], Some(1025)).unwrap();\n\n // port 10 trunk permit 1025 pvid 1025\n\n set_vlan_trunk_port(&mut conn, 10, &[1025], Some(1025)).unwrap();\n\n\n\n get_interfaces(&mut conn).unwrap();\n\n */\n\n info!(\"connected to {}\", addr);\n\n}\n", "file_path": "examples/ssh.rs", "rank": 11, "score": 1.745779377502811 }, { "content": "# netconf-rs\n\n\n\nA Rust library to configure devices with NETCONF(RFC 2641) protocol.\n\n\n\n## Transports\n\n\n\nCurrently, netconf-rs only supports NETCONF over SSH.\n\n\n\n## Vendors\n\n\n\nCurrently, netconf-rs supports the following vendors:\n\n\n\n- H3C: tested with S5024E-PWR-X\n\n\n\n## License\n\n\n\nSee LICENSE file.\n", "file_path": "README.md", "rank": 12, "score": 0.8855300709995875 }, { "content": " let mut sess = Session::new()?;\n\n sess.set_tcp_stream(tcp);\n\n sess.handshake()?;\n\n\n\n sess.userauth_password(user_name, password)?;\n\n if sess.authenticated() {\n\n let mut channel = sess.channel_session()?;\n\n channel.subsystem(\"netconf\")?;\n\n let res = SSHTransport {\n\n session: sess,\n\n channel,\n\n read_buffer: Vec::new(),\n\n };\n\n Ok(res)\n\n } else {\n\n Err(io::Error::last_os_error())\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/transport/ssh.rs", "rank": 13, "score": 0.7015358983165629 } ]
Rust
src/triple.rs
MattsSe/nom-sparql
c0ea67ba8c5aed5ebed46bb9f1bb6257c6c64d06
use nom::{ branch::alt, bytes::complete::{escaped, tag, tag_no_case, take_while1, take_while_m_n}, character::complete::char, character::is_digit, combinator::map_res, combinator::{map, opt}, multi::{many0, many1, separated_nonempty_list}, sequence::{delimited, pair, separated_pair, tuple}, sequence::{preceded, terminated}, IResult, }; use crate::{ expression::ArgList, graph::graph_node, node::{Collection, ObjectList, PropertyList, TriplesNode}, path::{triples_same_subject_path, TriplesSameSubjectPath}, terminals::{bracketted, sp, sp_enc, sp_sep, sp_sep1}, var::{var_or_iri, var_or_term, verb, VarOrIri, VarOrTerm, Verb, VerbList}, }; #[derive(Debug, Clone, Eq, PartialEq)] pub enum TriplesSameSubject { Term { var_or_term: VarOrTerm, property_list: PropertyList, }, Node { triples_node: TriplesNode, property_list: Option<PropertyList>, }, } #[derive(Debug, Clone, Eq, PartialEq)] pub struct ConstructTriples { pub first_triples: TriplesSameSubject, pub further_triples: Vec<TriplesSameSubject>, } #[derive(Debug, Clone, Eq, PartialEq)] pub struct TriplesBlock(pub Vec<TriplesSameSubjectPath>); pub type TriplesTemplate = Vec<TriplesSameSubject>; pub(crate) fn blank_node_property_list(i: &str) -> IResult<&str, PropertyList> { delimited( terminated(char('['), sp), property_list_not_empty, preceded(sp, char(']')), )(i) } pub(crate) fn collection(i: &str) -> IResult<&str, Collection> { map(bracketted(many1(sp_enc(graph_node))), Collection)(i) } pub(crate) fn object_list(i: &str) -> IResult<&str, ObjectList> { map( separated_nonempty_list(sp_enc(tag(",")), graph_node), ObjectList, )(i) } pub(crate) fn property_list_not_empty(i: &str) -> IResult<&str, PropertyList> { map( terminated( separated_nonempty_list( sp_enc(many1(sp_enc(char(';')))), map(separated_pair(verb, sp, object_list), |(v, l)| { VerbList::new(v, l) }), ), many0(preceded(sp, char(';'))), ), PropertyList, )(i) } #[inline] pub(crate) fn property_list(i: &str) -> IResult<&str, Option<PropertyList>> { opt(property_list_not_empty)(i) } pub(crate) fn triples_node(i: &str) -> IResult<&str, TriplesNode> { alt(( map(collection, TriplesNode::Collection), map(blank_node_property_list, TriplesNode::BlankNodePropertyList), ))(i) } pub(crate) fn triples_block(i: &str) -> IResult<&str, TriplesBlock> { map( separated_nonempty_list(many1(sp_enc(char('.'))), triples_same_subject_path), TriplesBlock, )(i) } pub(crate) fn triples_template(i: &str) -> IResult<&str, TriplesTemplate> { terminated( separated_nonempty_list(many1(sp_enc(char('.'))), triples_same_subject), opt(preceded(sp, char('.'))), )(i) } pub(crate) fn triples_same_subject(i: &str) -> IResult<&str, TriplesSameSubject> { alt(( map( sp_sep(triples_node, property_list), |(triples_node, property_list)| TriplesSameSubject::Node { triples_node, property_list, }, ), map( sp_sep1(var_or_term, property_list_not_empty), |(var_or_term, property_list)| TriplesSameSubject::Term { var_or_term, property_list, }, ), ))(i) } #[cfg(test)] mod tests { use super::*; use crate::graph::{GraphNode, GraphTerm}; #[test] fn is_triple_same_subject() { assert_eq!( triples_same_subject("() a true,()"), Ok(( "", TriplesSameSubject::Term { var_or_term: VarOrTerm::Term(GraphTerm::Nil), property_list: PropertyList(vec![VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(true))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), )]) } )) ); assert_eq!( triples_same_subject("(()())"), Ok(( "", TriplesSameSubject::Node { triples_node: TriplesNode::Collection(Collection(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)) ])), property_list: None } )) ); assert_eq!( triples_same_subject("[ a (),()\t] a false,()"), Ok(( "", TriplesSameSubject::Node { triples_node: TriplesNode::BlankNodePropertyList(PropertyList(vec![ VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), ) ])), property_list: Some(PropertyList(vec![VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(false))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), )])) } )) ); } #[test] fn is_triples_node() { assert_eq!( triples_node("(true ())"), Ok(( "", TriplesNode::Collection(Collection(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(true))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)) ])) )) ); assert_eq!( triples_node("[\na false,() \n]"), Ok(( "", TriplesNode::BlankNodePropertyList(PropertyList(vec![VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(false))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), )])) )) ); } #[test] fn is_triples_template() { let nil = TriplesSameSubject::Node { triples_node: TriplesNode::Collection(Collection(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(true))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ])), property_list: None, }; assert_eq!(triples_template("(true())."), Ok(("", vec![nil.clone()]))); assert_eq!( triples_template("(true()).(true())"), Ok(("", vec![nil.clone(), nil.clone()])) ); assert_eq!( triples_template("(true()).[ a (),()\t] a false,()"), Ok(( "", vec![ nil.clone(), TriplesSameSubject::Node { triples_node: TriplesNode::BlankNodePropertyList(PropertyList(vec![ VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), ) ])), property_list: Some(PropertyList(vec![VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral( false ))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), )])) } ] )) ); } }
use nom::{ branch::alt, bytes::complete::{escaped, tag, tag_no_case, take_while1, take_while_m_n}, character::complete::char, character::is_digit, combinator::map_res, combinator::{map, opt}, multi::{many0, many1, separated_nonempty_list}, sequence::{delimited, pair, separated_pair, tuple}, sequence::{preceded, terminated}, IResult, }; use crate::{ expression::ArgList, graph::graph_node, node::{Collection, ObjectList, PropertyList, TriplesNode}, path::{triples_same_subject_path, TriplesSameSubjectPath}, terminals::{bracketted, sp, sp_enc, sp_sep, sp_sep1}, var::{var_or_iri, var_or_term, verb, VarOrIri, VarOrTerm, Verb, VerbList}, }; #[derive(Debug, Clone, Eq, PartialEq)] pub enum TriplesSameSubject { Term { var_or_term: VarOrTerm, property_list: PropertyList, }, Node { triples_node: TriplesNode, property_list: Option<PropertyList>, }, } #[derive(Debug, Clone, Eq, PartialEq)] pub struct ConstructTriples { pub first_triples: TriplesSameSubject, pub further_triples: Vec<TriplesSameSubject>, } #[derive(Debug, Clone, Eq, PartialEq)] pub struct TriplesBlock(pub Vec<TriplesSameSubjectPath>); pub type TriplesTemplate = Vec<TriplesSameSubject>; pub(crate) fn blank_node_property_list(i: &str) -> IResult<&str, PropertyList> { delimited( terminated(char('['), sp), property_list_not_empty, preceded(sp, char(']')), )(i) } pub(crate) fn collection(i: &str) -> IResult<&str, Collection> { map(bracketted(many1(sp_enc(graph_node))), Collection)(i) } pub(crate) fn object_list(i: &str) -> IResult<&str, ObjectList> { map( separated_nonempty_list(sp_enc(tag(",")), graph_node), ObjectList, )(i) } pub(crate) fn property_list_not_empty(i: &str) -> IResult<&str, PropertyList> { map( terminated( separated_nonempty_list( sp_enc(many1(sp_enc(char(';')))), map(separated_pair(verb, sp, object_list), |(v, l)| { VerbList::new(v, l) }), ), many0(preceded(sp, char(';'))), ), PropertyList, )(i) } #[inline] pub(crate) fn property_list(i: &str) -> IResult<&str, Option<PropertyList>> { opt(property_list_not_empty)(i) } pub(crate) fn triples_node(i: &str) -> IResult<&str, TriplesNode> { alt(( map(collection, TriplesNode::Collection), map(blank_node_property_list, TriplesNode::BlankNodePropertyList), ))(i) } pub(crate) fn triples_block(i: &str) -> IResult<&str, TriplesBlock> { map( separated_nonempty_list(many1(sp_enc(char('.'))), triples_same_subject_path), TriplesBlock, )(i) } pub(crate) fn triples_template(i: &str) -> IResult<&str, TriplesTemplate> { terminated( separated_nonempty_list(many1(sp_enc(char('.'))), triples_same_subject), opt(preceded(sp, char('.'))), )(i) } pub(crate) fn triples_same_subject(i: &str) -> IResult<&str, TriplesSameSubject> { alt(( map( sp_sep(triples_node, property_list), |(triples_node, property_list)| TriplesSameSubject::Node { triples_node, property_list, }, ), map( sp_sep1(var_or_term, property_list_not_empty), |(var_or_term, property_list)| TriplesSameSubject::Term { var_or_term, property_list, }, ), ))(i) } #[cfg(test)] mod tests { use super::*; use crate::graph::{GraphNode, GraphTerm}; #[test] fn is_triple_same_subject() { assert_eq!( triples_same_subject("() a true,()"), Ok(( "", TriplesSameSubject::Term { var_or_term: VarOrTerm::Term(GraphTerm::Nil), property_list: PropertyList(vec![VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(true))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), )]) } )) ); assert_eq!( triples_same_subject("(()())"), Ok(( "", TriplesSameSubject::Node { triples_node: TriplesNode::Collection(Collection(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)) ])), property_list: None } )) ); assert_eq!( triples_same_subject("[ a (),()\t] a false,()"), Ok(( "", TriplesSameSubject::Node { triples_node: TriplesNode::BlankNodePropertyList(PropertyList(vec![ VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), ) ])), property_list: Some(PropertyList(vec![VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(false))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), )])) } )) ); } #[test] fn is_triples_node() { assert_eq!( triples_node("(true ())"), Ok(( "", TriplesNode::Collection(Collection(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(true))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)) ])) )) ); assert_eq!( triples_node("[\na false,() \n]"), Ok(( "", TriplesNode::BlankNodePropertyList(PropertyList(vec![VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(false))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), )])) )) ); } #[test] fn is_triples_template() {
assert_eq!(triples_template("(true())."), Ok(("", vec![nil.clone()]))); assert_eq!( triples_template("(true()).(true())"), Ok(("", vec![nil.clone(), nil.clone()])) ); assert_eq!( triples_template("(true()).[ a (),()\t] a false,()"), Ok(( "", vec![ nil.clone(), TriplesSameSubject::Node { triples_node: TriplesNode::BlankNodePropertyList(PropertyList(vec![ VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), ) ])), property_list: Some(PropertyList(vec![VerbList::new( Verb::A, ObjectList(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral( false ))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ]), )])) } ] )) ); } }
let nil = TriplesSameSubject::Node { triples_node: TriplesNode::Collection(Collection(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(true))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ])), property_list: None, };
assignment_statement
[ { "content": "fn plx(i: &str) -> IResult<&str, &str> {\n\n recognize(alt((\n\n pair(tag(\"%\"), hex_primary),\n\n pair(tag(\"\\\\\"), recognize(one_of(\"_~.-!$&'()*+,;=/?#@%\"))),\n\n )))(i)\n\n}\n\n\n\npub(crate) fn pn_local(i: &str) -> IResult<&str, &str> {\n\n recognize(pair(\n\n alt((\n\n pn_chars_u_one,\n\n tag(\":\"),\n\n take_while_m_n(1, 1, |c| is_digit(c as u8)),\n\n plx,\n\n )),\n\n recognize(pair(\n\n opt(take_while1(|c| c == '.')),\n\n separated_list(\n\n take_while1(|c| c == '.'),\n\n many0(alt((take_while1(|c| is_pn_char(c) || c == ':'), plx))),\n", "file_path": "src/terminals.rs", "rank": 0, "score": 125243.52746844402 }, { "content": "fn hex_primary(i: &str) -> IResult<&str, &str> {\n\n take_while_m_n(2, 2, is_hex_digit)(i)\n\n}\n\n\n", "file_path": "src/terminals.rs", "rank": 1, "score": 122193.68749501249 }, { "content": "pub fn sparql_query(i: &str) -> IResult<&str, SparqlQuery> {\n\n alt((\n\n map(select_query, SparqlQuery::Select),\n\n map(construct_query, SparqlQuery::Construct),\n\n map(describe_query, SparqlQuery::Describe),\n\n map(ask_query, SparqlQuery::Ask),\n\n ))(i)\n\n}\n", "file_path": "src/parser.rs", "rank": 2, "score": 115146.96256725704 }, { "content": "pub fn construct_query(i: &str) -> IResult<&str, ConstructQuery> {\n\n preceded_tag1(\n\n \"construct\",\n\n alt((\n\n map(sub_construct, ConstructQuery::SubConstruct),\n\n map(sub_triples, ConstructQuery::SubTriples),\n\n )),\n\n )(i)\n\n}\n\n\n\npub(crate) fn construct_template(i: &str) -> IResult<&str, ConstructTemplate> {\n\n map(\n\n delimited(\n\n terminated(char('{'), sp),\n\n separated_list(many1(sp_enc(char('.'))), triples_same_subject),\n\n preceded(sp, char('}')),\n\n ),\n\n ConstructTemplate,\n\n )(i)\n\n}\n", "file_path": "src/query/construct.rs", "rank": 3, "score": 112599.5593197072 }, { "content": "pub fn sub_triples(i: &str) -> IResult<&str, SubTriples> {\n\n map(\n\n tuple((\n\n terminated(separated_list(sp, data_set_clause), sp),\n\n terminated(tag_no_case(\"where\"), sp1),\n\n delimited(char('{'), sp_enc(opt(triples_template)), char('}')),\n\n preceded(sp, solution_modifier),\n\n )),\n\n |(dataset_clauses, _, triples_template, solution_modifier)| SubTriples {\n\n dataset_clauses,\n\n triples_template,\n\n solution_modifier,\n\n },\n\n )(i)\n\n}\n\n\n", "file_path": "src/query/construct.rs", "rank": 4, "score": 112599.5593197072 }, { "content": "pub fn ask_query(i: &str) -> IResult<&str, AskQuery> {\n\n map(\n\n tuple((\n\n terminated(tag_no_case(\"ask\"), sp1),\n\n terminated(separated_list(sp, data_set_clause), sp),\n\n terminated(where_clause, sp),\n\n solution_modifier,\n\n )),\n\n |(_, dataset_clauses, where_clause, solution_modifier)| AskQuery {\n\n dataset_clauses,\n\n where_clause,\n\n solution_modifier,\n\n },\n\n )(i)\n\n}\n", "file_path": "src/query/ask.rs", "rank": 5, "score": 112599.5593197072 }, { "content": "pub fn sub_construct(i: &str) -> IResult<&str, SubConstruct> {\n\n map(\n\n tuple((\n\n terminated(construct_template, sp1),\n\n terminated(separated_list(sp, data_set_clause), sp),\n\n terminated(where_clause, sp),\n\n solution_modifier,\n\n )),\n\n |(construct_template, dataset_clauses, where_clause, solution_modifier)| SubConstruct {\n\n construct_template,\n\n dataset_clauses,\n\n where_clause,\n\n solution_modifier,\n\n },\n\n )(i)\n\n}\n\n\n", "file_path": "src/query/construct.rs", "rank": 6, "score": 112599.5593197072 }, { "content": "pub fn describe_query(i: &str) -> IResult<&str, DescribeQuery> {\n\n map(\n\n tuple((\n\n tag_no_case(\"describe\"),\n\n sp_enc1(var_or_iris_or_all),\n\n terminated(separated_list(sp, data_set_clause), sp),\n\n opt(terminated(where_clause, sp)),\n\n solution_modifier,\n\n )),\n\n |(_, var_or_iris_or_all, dataset_clauses, where_clause, solution_modifier)| DescribeQuery {\n\n var_or_iris_or_all,\n\n dataset_clauses,\n\n where_clause,\n\n solution_modifier,\n\n },\n\n )(i)\n\n}\n", "file_path": "src/query/describe.rs", "rank": 7, "score": 112599.5593197072 }, { "content": "pub fn sparql_query_stmt(i: &str) -> IResult<&str, SparqlQueryStatement> {\n\n map(\n\n tuple((\n\n terminated(prologue, sp),\n\n sparql_query,\n\n opt(preceded(sp1, preceded_tag1(\"values\", datablock))),\n\n )),\n\n |(prologue, query, values)| SparqlQueryStatement {\n\n prologue,\n\n query,\n\n values,\n\n },\n\n )(i)\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 8, "score": 110224.18249795439 }, { "content": "fn is_hex_digit(c: char) -> bool {\n\n c.is_digit(16)\n\n}\n\n\n", "file_path": "src/terminals.rs", "rank": 9, "score": 101768.83118641209 }, { "content": "fn built_in_call_1(i: &str) -> IResult<&str, BuiltInCall> {\n\n alt((\n\n map(aggregate, BuiltInCall::Aggregate),\n\n map(preceded_bracketted(\"str\", expression), BuiltInCall::Str),\n\n map(preceded_bracketted(\"lang\", expression), BuiltInCall::Lang),\n\n map(\n\n preceded_bracketted(\n\n \"langmatches\",\n\n separated_pair(expression, sp_enc(char(',')), expression),\n\n ),\n\n BuiltInCall::LangMatches,\n\n ),\n\n map(\n\n preceded_bracketted(\"datatype\", expression),\n\n BuiltInCall::Datatype,\n\n ),\n\n map(preceded_bracketted(\"bound\", var), BuiltInCall::Bound),\n\n map(preceded_bracketted(\"iri\", expression), BuiltInCall::Iri),\n\n map(preceded_bracketted(\"uri\", expression), BuiltInCall::Uri),\n\n map(\n", "file_path": "src/call.rs", "rank": 10, "score": 88554.35232066328 }, { "content": "fn built_in_call_2(i: &str) -> IResult<&str, BuiltInCall> {\n\n alt((\n\n map(\n\n preceded_bracketted(\n\n \"strends\",\n\n separated_pair(expression, sp_enc(char(',')), expression),\n\n ),\n\n BuiltInCall::StrEnds,\n\n ),\n\n map(\n\n preceded_bracketted(\n\n \"strbefore\",\n\n separated_pair(expression, sp_enc(char(',')), expression),\n\n ),\n\n BuiltInCall::StrBefore,\n\n ),\n\n map(\n\n preceded_bracketted(\n\n \"strafter\",\n\n separated_pair(expression, sp_enc(char(',')), expression),\n", "file_path": "src/call.rs", "rank": 11, "score": 88554.35232066328 }, { "content": "fn from_hex(input: &str) -> Result<u8, std::num::ParseIntError> {\n\n u8::from_str_radix(input, 16)\n\n}\n", "file_path": "src/terminals.rs", "rank": 12, "score": 76095.12820699636 }, { "content": " LangTag(String),\n\n IriRef(Iri),\n\n}\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum BlankNode {\n\n Anon,\n\n Label(String),\n\n}\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum TriplesNode {\n\n Collection(Collection),\n\n BlankNodePropertyList(PropertyList),\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::graph::{blank_node, GraphTerm};\n", "file_path": "src/node.rs", "rank": 13, "score": 32117.658797732758 }, { "content": "\n\n use crate::triple::{\n\n blank_node_property_list, collection, object_list, property_list, property_list_not_empty,\n\n };\n\n use crate::var::{Var, VarOrIri, VarOrTerm, Verb};\n\n\n\n #[test]\n\n fn is_blank_node() {\n\n assert_eq!(blank_node(\"[]\"), Ok((\"\", BlankNode::Anon)));\n\n\n\n assert_eq!(\n\n blank_node(\"_:a.b.c\"),\n\n Ok((\"\", BlankNode::Label(\"a.b.c\".to_string())))\n\n );\n\n }\n\n\n\n #[test]\n\n fn is_collection() {\n\n assert_eq!(\n\n collection(\"(()())\"),\n", "file_path": "src/node.rs", "rank": 14, "score": 32111.704370147152 }, { "content": "use crate::expression::Iri;\n\nuse crate::graph::GraphNode;\n\n\n\nuse crate::var::VerbList;\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct ObjectList(pub Vec<GraphNode>);\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct PropertyList(pub Vec<VerbList>);\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct Collection(pub Vec<GraphNode>);\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct RdfLiteral {\n\n pub literal: String,\n\n pub descriptor: Option<RdfLiteralDescriptor>,\n\n}\n\n\n", "file_path": "src/node.rs", "rank": 15, "score": 32108.7761151076 }, { "content": " ))\n\n );\n\n }\n\n\n\n #[test]\n\n fn is_property_list() {\n\n assert_eq!(property_list(\"\"), Ok((\"\", None)));\n\n }\n\n\n\n #[test]\n\n fn is_property_list_not_empty() {\n\n let mut prop_list = PropertyList(vec![VerbList::new(\n\n Verb::A,\n\n ObjectList(vec![\n\n GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)),\n\n GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)),\n\n ]),\n\n )]);\n\n\n\n assert_eq!(\n", "file_path": "src/node.rs", "rank": 16, "score": 32104.72801205403 }, { "content": " property_list_not_empty(\"a (),()\"),\n\n Ok((\"\", prop_list.clone()))\n\n );\n\n\n\n assert_eq!(\n\n property_list_not_empty(\"a (),();;;\"),\n\n Ok((\"\", prop_list.clone()))\n\n );\n\n\n\n assert_eq!(\n\n property_list_not_empty(\"a () , () \\n; ; ;\"),\n\n Ok((\"\", prop_list.clone()))\n\n );\n\n\n\n prop_list.0.push(VerbList::new(\n\n Verb::VarOrIri(VarOrIri::Var(Var::QMark(\"z\".to_string()))),\n\n ObjectList(vec![\n\n GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(true))),\n\n GraphNode::VarOrTerm(VarOrTerm::Var(Var::QMark(\"name\".to_string()))),\n\n ]),\n", "file_path": "src/node.rs", "rank": 17, "score": 32104.10869947594 }, { "content": " <http://example.org/foaf/aliceFoaf> ;; ;\"#\n\n ),\n\n Ok((\"\", prop_list.clone()))\n\n );\n\n }\n\n\n\n #[test]\n\n fn is_blank_node_property_list() {\n\n assert_eq!(\n\n blank_node_property_list(\"[ a (),()\\t]\"),\n\n Ok((\n\n \"\",\n\n PropertyList(vec![VerbList::new(\n\n Verb::A,\n\n ObjectList(vec![\n\n GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)),\n\n GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)),\n\n ]),\n\n )])\n\n ))\n\n );\n\n }\n\n}\n", "file_path": "src/node.rs", "rank": 18, "score": 32104.099555116027 }, { "content": " Ok((\n\n \"\",\n\n Collection(vec![\n\n GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)),\n\n GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil))\n\n ])\n\n ))\n\n );\n\n }\n\n\n\n #[test]\n\n fn is_object_list() {\n\n assert_eq!(\n\n object_list(\"(),()\"),\n\n Ok((\n\n \"\",\n\n ObjectList(vec![\n\n GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)),\n\n GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil))\n\n ])\n", "file_path": "src/node.rs", "rank": 19, "score": 32101.2165250001 }, { "content": " ));\n\n\n\n assert_eq!(\n\n property_list_not_empty(\"a (),(); ?z true , ?name\"),\n\n Ok((\"\", prop_list.clone()))\n\n );\n\n\n\n prop_list.0.push(VerbList::new(\n\n Verb::VarOrIri(VarOrIri::Iri(Iri::Iri(\n\n \"http://example.org/foaf/aliceFoaf\".to_string(),\n\n ))),\n\n ObjectList(vec![GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Iri(\n\n Iri::Iri(\"http://example.org/foaf/aliceFoaf\".to_string()),\n\n )))]),\n\n ));\n\n\n\n assert_eq!(\n\n property_list_not_empty(\n\n r#\"a (),(); ?z true , ?name ;\n\n <http://example.org/foaf/aliceFoaf>\n", "file_path": "src/node.rs", "rank": 20, "score": 32101.07737855076 }, { "content": "impl RdfLiteral {\n\n /// creates a complete [`RdfLiteral`]\n\n pub fn new<T: ToString>(literal: T, descriptor: RdfLiteralDescriptor) -> Self {\n\n RdfLiteral {\n\n literal: literal.to_string(),\n\n descriptor: Some(descriptor),\n\n }\n\n }\n\n\n\n /// creates a new [`RdfLiteral`] with a `literal` only\n\n pub fn literal<T: ToString>(literal: T) -> Self {\n\n RdfLiteral {\n\n literal: literal.to_string(),\n\n descriptor: None,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum RdfLiteralDescriptor {\n", "file_path": "src/node.rs", "rank": 21, "score": 32093.05581425222 }, { "content": "\n\npub(crate) fn anon(i: &str) -> IResult<&str, &str> {\n\n preceded(char('['), cut(terminated(sp, char(']'))))(i)\n\n}\n\n\n\npub(crate) fn nil(i: &str) -> IResult<&str, &str> {\n\n preceded(char('('), cut(terminated(sp, char(')'))))(i)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn is_anon() {\n\n assert_eq!(anon(\"[]\"), Ok((\"\", \"\")));\n\n assert_eq!(anon(\"[ ]\"), Ok((\"\", \" \")));\n\n assert_eq!(anon(\"[a]\"), Err(Err::Failure((\"a]\", ErrorKind::Char))));\n\n }\n\n\n", "file_path": "src/terminals.rs", "rank": 22, "score": 31571.585585930192 }, { "content": "use nom::{\n\n branch::alt,\n\n bytes::complete::take_while,\n\n bytes::complete::{escaped, tag, tag_no_case, take_while1, take_while_m_n},\n\n character::complete::{anychar, char, digit1, none_of, one_of},\n\n character::{\n\n complete::{alpha1, alphanumeric1},\n\n is_alphabetic,\n\n },\n\n character::{is_alphanumeric, is_digit},\n\n combinator::recognize,\n\n combinator::{complete, cond, cut, map, map_res, not, opt, peek},\n\n error::ErrorKind,\n\n multi::{fold_many0, separated_list},\n\n multi::{many0, many1},\n\n sequence::{delimited, pair, preceded, separated_pair, terminated, tuple},\n\n AsChar, Err, IResult,\n\n};\n\n\n\nuse crate::{\n", "file_path": "src/terminals.rs", "rank": 23, "score": 31566.935350026684 }, { "content": "}\n\n\n\npub(crate) fn new_line(i: &str) -> IResult<&str, &str> {\n\n recognize(pair(\n\n opt(preceded(char('#'), many0(none_of(\"\\n\\r\")))),\n\n one_of(\"\\r\\n\"),\n\n ))(i)\n\n}\n\n\n\n#[inline]\n\npub(crate) fn sp_enc<'a, O1, F>(pat: F) -> impl Fn(&'a str) -> IResult<&'a str, O1>\n\nwhere\n\n F: Fn(&'a str) -> IResult<&'a str, O1>,\n\n{\n\n delimited(sp, pat, sp)\n\n}\n\n\n\n#[inline]\n\npub(crate) fn sp_enc1<'a, O1, F>(pat: F) -> impl Fn(&'a str) -> IResult<&'a str, O1>\n\nwhere\n", "file_path": "src/terminals.rs", "rank": 24, "score": 31566.525391936884 }, { "content": "\n\n#[inline]\n\npub(crate) fn preceded_tag<'a, O1, F>(\n\n tag: &'a str,\n\n pat: F,\n\n) -> impl Fn(&'a str) -> IResult<&'a str, O1>\n\nwhere\n\n F: Fn(&'a str) -> IResult<&'a str, O1>,\n\n{\n\n preceded(terminated(tag_no_case(tag), sp), pat)\n\n}\n\n\n\n#[inline]\n\npub(crate) fn sp(i: &str) -> IResult<&str, &str> {\n\n recognize(many0(alt((recognize(one_of(\" \\t\")), new_line))))(i)\n\n}\n\n\n\n#[inline]\n\npub(crate) fn sp1(i: &str) -> IResult<&str, &str> {\n\n recognize(many1(alt((recognize(one_of(\" \\t\")), new_line))))(i)\n", "file_path": "src/terminals.rs", "rank": 25, "score": 31565.482636118846 }, { "content": " ),\n\n )),\n\n ))(i)\n\n}\n\n\n\npub(crate) fn pn_prefix(i: &str) -> IResult<&str, &str> {\n\n recognize(pair(pn_chars_base_one, pn_chars_tail))(i)\n\n}\n\n\n\npub(crate) fn pname_ns(i: &str) -> IResult<&str, Option<String>> {\n\n terminated(opt(map(pn_prefix, String::from)), preceded(sp, char(':')))(i)\n\n}\n\n\n\npub(crate) fn pname_ln(i: &str) -> IResult<&str, (Option<String>, String)> {\n\n pair(pname_ns, preceded(sp, map(pn_local, String::from)))(i)\n\n}\n\n\n\n#[inline]\n\npub(crate) fn is_sp(c: char) -> bool {\n\n \" \\t\\n\\r\".contains(c)\n", "file_path": "src/terminals.rs", "rank": 26, "score": 31564.345515900906 }, { "content": "}\n\n\n\n#[inline]\n\npub(crate) fn bracketted<'a, O1, F>(pat: F) -> impl Fn(&'a str) -> IResult<&'a str, O1>\n\nwhere\n\n F: Fn(&'a str) -> IResult<&'a str, O1>,\n\n{\n\n delimited(char('('), pat, char(')'))\n\n}\n\n\n\n#[inline]\n\npub(crate) fn preceded_tag1<'a, O1, F>(\n\n tag: &'a str,\n\n pat: F,\n\n) -> impl Fn(&'a str) -> IResult<&'a str, O1>\n\nwhere\n\n F: Fn(&'a str) -> IResult<&'a str, O1>,\n\n{\n\n preceded(terminated(tag_no_case(tag), sp1), pat)\n\n}\n", "file_path": "src/terminals.rs", "rank": 27, "score": 31562.462555613078 }, { "content": " ),\n\n delimited(\n\n tag(\"\\\"\"),\n\n escaped(none_of(\"\\\"\\\\\"), '\\\\', one_of(r#\"\"tbnrf\\'\"#)),\n\n tag(\"\\\"\"),\n\n ),\n\n ))(i)\n\n}\n\n\n\npub(crate) fn rdf_literal(i: &str) -> IResult<&str, RdfLiteral> {\n\n map(\n\n pair(\n\n map(string_literal, String::from),\n\n opt(alt((\n\n map(\n\n map(language_tag, String::from),\n\n RdfLiteralDescriptor::LangTag,\n\n ),\n\n map(preceded(tag(\"^^\"), iri), RdfLiteralDescriptor::IriRef),\n\n ))),\n", "file_path": "src/terminals.rs", "rank": 28, "score": 31562.161553338276 }, { "content": " second: G,\n\n) -> impl Fn(&'a str) -> IResult<&'a str, (O1, O2)>\n\nwhere\n\n F: Fn(&'a str) -> IResult<&'a str, O1>,\n\n G: Fn(&'a str) -> IResult<&'a str, O2>,\n\n{\n\n separated_pair(first, sp, second)\n\n}\n\n\n\npub(crate) fn string_content(i: &str) -> IResult<&str, &str> {\n\n escaped(none_of(\"'\\\"\\\\\"), '\\\\', one_of(r#\"\"tbnrf\\'\"#))(i)\n\n}\n\n\n\n/// https://www.w3.org/TR/rdf-sparql-query/#QSynLiterals\n\npub(crate) fn string_literal(i: &str) -> IResult<&str, &str> {\n\n alt((\n\n delimited(\n\n tag(\"'\"),\n\n escaped(none_of(\"'\\\\\"), '\\\\', one_of(r#\"\"tbnrf\\'\"#)),\n\n tag(\"'\"),\n", "file_path": "src/terminals.rs", "rank": 29, "score": 31561.402802710985 }, { "content": " ),\n\n |(literal, descriptor)| RdfLiteral {\n\n literal,\n\n descriptor,\n\n },\n\n )(i)\n\n}\n\n\n\n// TODO refactor\n\npub(crate) fn language_tag(i: &str) -> IResult<&str, &str> {\n\n preceded(\n\n char('@'),\n\n recognize(pair(alpha1, many0(pair(tag(\"-\"), alphanumeric1)))),\n\n )(i)\n\n}\n\n\n\n#[inline]\n\npub(crate) fn echar(i: &str) -> IResult<&str, &str> {\n\n escaped(none_of(\"\\\\\"), '\\\\', one_of(r#\"\"tbnrf'\"#))(i)\n\n}\n", "file_path": "src/terminals.rs", "rank": 30, "score": 31559.306302939272 }, { "content": " aggregate::count,\n\n call::arg_list,\n\n clauses::values_clause,\n\n data::datablock,\n\n expression::{DefaultOrNamedIri, Iri, IriOrFunction, PrefixedName},\n\n graph::graph_term,\n\n node::{Collection, ObjectList, PropertyList, RdfLiteral, RdfLiteralDescriptor, TriplesNode},\n\n prologue::{BaseOrPrefixDecl, PrefixDecl, Prologue},\n\n var::{Var, VarOrIri, VarOrTerm, VerbList},\n\n};\n\n\n\n#[inline]\n\npub(crate) fn preceded_bracketted<'a, O1, F>(\n\n tag: &'a str,\n\n pat: F,\n\n) -> impl Fn(&'a str) -> IResult<&'a str, O1>\n\nwhere\n\n F: Fn(&'a str) -> IResult<&'a str, O1>,\n\n{\n\n preceded_tag(tag, bracketted(pat))\n", "file_path": "src/terminals.rs", "rank": 31, "score": 31558.732680175595 }, { "content": "\n\npub(crate) fn prefixed_name(i: &str) -> IResult<&str, PrefixedName> {\n\n alt((\n\n map(pname_ln, |(pn_prefix, pn_local)| PrefixedName::PnameLN {\n\n pn_prefix,\n\n pn_local,\n\n }),\n\n map(pname_ns, PrefixedName::PnameNS),\n\n ))(i)\n\n}\n\n\n\npub(crate) fn base_decl(i: &str) -> IResult<&str, &str> {\n\n preceded(terminated(tag_no_case(\"base\"), sp1), iri_ref)(i)\n\n}\n\n\n\npub(crate) fn prefix_decl(i: &str) -> IResult<&str, PrefixDecl> {\n\n map(\n\n tuple((\n\n tag_no_case(\"prefix\"),\n\n sp_enc(pname_ns),\n", "file_path": "src/terminals.rs", "rank": 32, "score": 31558.397972811523 }, { "content": " F: Fn(&'a str) -> IResult<&'a str, O1>,\n\n{\n\n delimited(sp1, pat, sp1)\n\n}\n\n\n\n#[inline]\n\npub(crate) fn sp_sep1<'a, O1, O2, F, G>(\n\n first: F,\n\n second: G,\n\n) -> impl Fn(&'a str) -> IResult<&'a str, (O1, O2)>\n\nwhere\n\n F: Fn(&'a str) -> IResult<&'a str, O1>,\n\n G: Fn(&'a str) -> IResult<&'a str, O2>,\n\n{\n\n separated_pair(first, sp1, second)\n\n}\n\n\n\n#[inline]\n\npub(crate) fn sp_sep<'a, O1, O2, F, G>(\n\n first: F,\n", "file_path": "src/terminals.rs", "rank": 33, "score": 31558.340116116295 }, { "content": "\n\n#[inline]\n\npub(crate) fn pn_chars_base_one(i: &str) -> IResult<&str, &str> {\n\n take_while_m_n(1, 1, is_pn_chars_base)(i)\n\n}\n\n\n\n#[inline]\n\npub(crate) fn pn_chars_base1(i: &str) -> IResult<&str, &str> {\n\n take_while1(is_pn_chars_base)(i)\n\n}\n\n\n\n#[inline]\n\npub(crate) fn is_pn_chars_u(i: char) -> bool {\n\n is_pn_chars_base(i) || i == '_'\n\n}\n\n\n\n#[inline]\n\npub(crate) fn pn_chars_u_one(i: &str) -> IResult<&str, &str> {\n\n alt((pn_chars_base_one, tag(\"_\")))(i)\n\n}\n", "file_path": "src/terminals.rs", "rank": 34, "score": 31558.128055130775 }, { "content": " pair(iri, opt(preceded(sp1, arg_list))),\n\n |(iri, arg_list)| IriOrFunction { iri, arg_list },\n\n )(i)\n\n}\n\n\n\n#[inline]\n\npub(crate) fn pn_chars_tail(i: &str) -> IResult<&str, &str> {\n\n // ((PN_CHARS|'.')* PN_CHARS)?\n\n recognize(pair(\n\n opt(take_while1(|c| c == '.')),\n\n separated_list(take_while1(|c| c == '.'), pn_chars1),\n\n ))(i)\n\n}\n\n\n", "file_path": "src/terminals.rs", "rank": 35, "score": 31555.585616786422 }, { "content": " delimited(\n\n tag(\"<\"),\n\n take_while(|c| {\n\n let chrs = \"<>\\\"{}|^\\\\`\";\n\n if chrs.contains(c) {\n\n false\n\n } else {\n\n c as u8 > 0x20\n\n }\n\n }),\n\n tag(\">\"),\n\n )(i)\n\n}\n\n\n\npub(crate) fn named_iri(i: &str) -> IResult<&str, Iri> {\n\n preceded_tag1(\n\n \"named\",\n\n alt((\n\n map(iri_ref, |i| Iri::Iri(i.to_string())),\n\n map(prefixed_name, Iri::PrefixedName),\n", "file_path": "src/terminals.rs", "rank": 36, "score": 31554.409222458075 }, { "content": "\n\n#[inline]\n\npub(crate) fn pn_chars_u1(i: &str) -> IResult<&str, &str> {\n\n take_while1(is_pn_chars_u)(i)\n\n}\n\n\n\n#[inline]\n\npub(crate) fn is_pn_char(i: char) -> bool {\n\n is_pn_chars_u(i) || i == '-' || i.is_dec_digit()\n\n}\n\n\n\n#[inline]\n\npub(crate) fn pn_chars_one(i: &str) -> IResult<&str, &str> {\n\n take_while_m_n(1, 1, is_pn_char)(i)\n\n}\n\n\n\n#[inline]\n\npub(crate) fn pn_chars1(i: &str) -> IResult<&str, &str> {\n\n take_while1(is_pn_char)(i)\n\n}\n", "file_path": "src/terminals.rs", "rank": 37, "score": 31554.068799907844 }, { "content": "pub(crate) fn is_illegal_char_lit_1(c: char) -> bool {\n\n match c {\n\n '\\u{0027}' | '\\u{005C}' | '\\u{000A}' | '\\u{000D}' => true,\n\n _ => false,\n\n }\n\n}\n\n\n\n#[inline]\n\npub(crate) fn is_illegal_char_lit_2(c: char) -> bool {\n\n if !is_illegal_char_lit_1(c) {\n\n c == '\\u{0022}'\n\n } else {\n\n true\n\n }\n\n}\n\n\n\n#[inline]\n\npub(crate) fn is_pn_chars_base(i: char) -> bool {\n\n is_alphabetic(i as u8) || is_unicode(i)\n\n}\n", "file_path": "src/terminals.rs", "rank": 38, "score": 31553.07510838114 }, { "content": " )),\n\n )(i)\n\n}\n\n\n\npub(crate) fn default_or_named_iri(i: &str) -> IResult<&str, DefaultOrNamedIri> {\n\n alt((\n\n map(named_iri, DefaultOrNamedIri::Named),\n\n map(iri, DefaultOrNamedIri::Default),\n\n ))(i)\n\n}\n\n\n\npub(crate) fn iri(i: &str) -> IResult<&str, Iri> {\n\n alt((\n\n map(iri_ref, |i| Iri::Iri(i.to_string())),\n\n map(prefixed_name, Iri::PrefixedName),\n\n ))(i)\n\n}\n\n\n\npub(crate) fn iri_or_fun(i: &str) -> IResult<&str, IriOrFunction> {\n\n map(\n", "file_path": "src/terminals.rs", "rank": 39, "score": 31551.48838018497 }, { "content": " map(iri_ref, String::from),\n\n )),\n\n |(_, pname_ns, iri_ref)| PrefixDecl { pname_ns, iri_ref },\n\n )(i)\n\n}\n\n\n\npub(crate) fn prologue(i: &str) -> IResult<&str, Prologue> {\n\n map(\n\n separated_list(\n\n sp1,\n\n alt((\n\n map(base_decl, |s| BaseOrPrefixDecl::Base(s.to_string())),\n\n map(prefix_decl, BaseOrPrefixDecl::Prefix),\n\n )),\n\n ),\n\n Prologue,\n\n )(i)\n\n}\n\n\n\npub(crate) fn iri_ref(i: &str) -> IResult<&str, &str> {\n", "file_path": "src/terminals.rs", "rank": 40, "score": 31549.82540198899 }, { "content": " #[test]\n\n fn is_pn_chars_base() {\n\n assert_eq!(pn_chars_base_one(\"a \"), Ok((\" \", \"a\")));\n\n assert_eq!(pn_chars_base_one(\"\\u{00C0} \"), Ok((\" \", \"\\u{00C0}\")));\n\n assert_eq!(pn_chars_base_one(\"\\u{03b1} \"), Ok((\" \", \"\\u{03b1}\")));\n\n assert_eq!(pn_chars_base_one(\"\\u{00D8} \"), Ok((\" \", \"\\u{00D8}\")));\n\n assert_eq!(pn_chars_base_one(\"\\u{FDF0} \"), Ok((\" \", \"\\u{FDF0}\")));\n\n assert_eq!(pn_chars_base_one(\"\\u{F900} \"), Ok((\" \", \"\\u{F900}\")));\n\n }\n\n\n\n #[test]\n\n fn is_iri_ref() {\n\n assert_eq!(\n\n iri(\"<http://education.data.gov.uk/def/school/>\"),\n\n Ok((\n\n \"\",\n\n Iri::Iri(\"http://education.data.gov.uk/def/school/\".to_string())\n\n ))\n\n );\n\n }\n", "file_path": "src/terminals.rs", "rank": 41, "score": 31549.387170183698 }, { "content": "}\n\n\n\npub(crate) fn is_unicode(c: char) -> bool {\n\n match c {\n\n '\\u{00C0}'..='\\u{00D6}' => true,\n\n '\\u{00D8}'..='\\u{00F6}' => true,\n\n '\\u{00F8}'..='\\u{02FF}' => true,\n\n '\\u{0370}'..='\\u{037D}' => true,\n\n '\\u{037F}'..='\\u{1FFF}' => true,\n\n '\\u{200C}'..='\\u{200D}' => true,\n\n '\\u{2070}'..='\\u{218F}' => true,\n\n '\\u{2C00}'..='\\u{2FEF}' => true,\n\n '\\u{3001}'..='\\u{D7FF}' => true,\n\n '\\u{F900}'..='\\u{FDCF}' => true,\n\n '\\u{FDF0}'..='\\u{FFFD}' => true,\n\n _ => false,\n\n }\n\n}\n\n\n\n#[inline]\n", "file_path": "src/terminals.rs", "rank": 42, "score": 31548.97432848232 }, { "content": " Ok((\"\", \"some string lit\"))\n\n );\n\n assert_eq!(\n\n string_literal(\"'some \\tstring\\n\\r\\\" lit'\"),\n\n Ok((\"\", \"some \\tstring\\n\\r\\\" lit\"))\n\n );\n\n }\n\n\n\n #[test]\n\n fn is_lang_tag() {\n\n assert_eq!(language_tag(\"@en\"), Ok((\"\", \"en\")));\n\n assert_eq!(language_tag(\"@some-lang-tag1\"), Ok((\"\", \"some-lang-tag1\")));\n\n assert_eq!(\n\n language_tag(\"@some-123lang-tag1\"),\n\n Ok((\"\", \"some-123lang-tag1\"))\n\n );\n\n assert_eq!(\n\n language_tag(\"@1lang\"),\n\n Err(Err::Error((\"1lang\", ErrorKind::Alpha)))\n\n );\n", "file_path": "src/terminals.rs", "rank": 43, "score": 31548.799614328538 }, { "content": " }\n\n\n\n #[test]\n\n fn is_rdf_literal() {\n\n assert_eq!(rdf_literal(\"'chat'\"), Ok((\"\", RdfLiteral::literal(\"chat\"))));\n\n\n\n assert_eq!(\n\n rdf_literal(\"'chat'@fr\"),\n\n Ok((\n\n \"\",\n\n RdfLiteral::new(\"chat\", RdfLiteralDescriptor::LangTag(\"fr\".to_string()))\n\n ))\n\n );\n\n assert_eq!(\n\n rdf_literal(\"'xyz'^^<http://example.org/ns/userDatatype>\"),\n\n Ok((\n\n \"\",\n\n RdfLiteral::new(\n\n \"xyz\",\n\n RdfLiteralDescriptor::IriRef(Iri::Iri(\n", "file_path": "src/terminals.rs", "rank": 44, "score": 31545.895365220174 }, { "content": "\n\n #[test]\n\n fn is_iri() {\n\n assert_eq!(\n\n iri(\"<http://education.data.gov.uk/def/school/>\"),\n\n Ok((\n\n \"\",\n\n Iri::Iri(\"http://education.data.gov.uk/def/school/\".to_string())\n\n ))\n\n );\n\n }\n\n\n\n #[test]\n\n fn is_string_literal() {\n\n assert_eq!(\n\n string_literal(r#\"\"some string lit\"\"#),\n\n Ok((\"\", r#\"some string lit\"#))\n\n );\n\n assert_eq!(\n\n string_literal(\"'some string lit'\"),\n", "file_path": "src/terminals.rs", "rank": 45, "score": 31544.98589318447 }, { "content": " \"http://example.org/ns/userDatatype\".to_string()\n\n ))\n\n )\n\n ))\n\n );\n\n assert_eq!(\n\n rdf_literal(r#\"\"abc\"^^appNS:1app.Data.Type\"#),\n\n Ok((\n\n \"\",\n\n RdfLiteral::new(\n\n \"abc\",\n\n RdfLiteralDescriptor::IriRef(Iri::PrefixedName(PrefixedName::PnameLN {\n\n pn_prefix: Some(\"appNS\".to_string()),\n\n pn_local: \"1app.Data.Type\".to_string()\n\n }))\n\n )\n\n ))\n\n );\n\n assert_eq!(\n\n rdf_literal(r#\"\"abc\"^^appNS:1...app.Data.Type\"#),\n", "file_path": "src/terminals.rs", "rank": 46, "score": 31543.38240456486 }, { "content": " Ok((\n\n \"\",\n\n RdfLiteral::new(\n\n \"abc\",\n\n RdfLiteralDescriptor::IriRef(Iri::PrefixedName(PrefixedName::PnameLN {\n\n pn_prefix: Some(\"appNS\".to_string()),\n\n pn_local: \"1...app.Data.Type\".to_string()\n\n }))\n\n )\n\n ))\n\n );\n\n }\n\n}\n", "file_path": "src/terminals.rs", "rank": 47, "score": 31540.33216892525 }, { "content": "\n\npub(crate) fn expression(i: &str) -> IResult<&str, Expression> {\n\n map(\n\n separated_nonempty_list(sp_enc(tag(\"||\")), conditional_and_expression),\n\n Expression,\n\n )(i)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use crate::terminals::iri;\n\n\n\n #[test]\n\n fn is_iri() {\n\n assert_eq!(\n\n iri(\"<http://example.org/book/book1>\"),\n\n Ok((\"\", Iri::Iri(\"http://example.org/book/book1\".to_string())))\n\n );\n\n\n", "file_path": "src/expression/mod.rs", "rank": 48, "score": 30204.779659434014 }, { "content": "use nom::{\n\n branch::alt,\n\n bytes::complete::{tag, tag_no_case},\n\n character::complete::char,\n\n combinator::{map, opt},\n\n multi::separated_nonempty_list,\n\n sequence::{delimited, pair, preceded, separated_pair, terminated, tuple},\n\n IResult,\n\n};\n\n\n\nuse crate::{\n\n arithmetic::{conditional_and_expression, ConditionalAndExpression},\n\n call::{built_in_call, function_call, BuiltInCall, FunctionCall},\n\n literal::{boolean, distinct, numeric_literal, NumericLiteral},\n\n node::RdfLiteral,\n\n terminals::{bracketted, iri_or_fun, nil, preceded_tag1, rdf_literal, sp1, sp_enc, sp_enc1},\n\n};\n\n\n\nuse crate::var::{var, Var};\n\n\n", "file_path": "src/expression/mod.rs", "rank": 49, "score": 30203.618197424552 }, { "content": ") -> IResult<&str, (Expression, Expression, Option<Expression>)> {\n\n bracketted3(i, expression)\n\n}\n\n\n\npub(crate) fn expression_as_var_opt(i: &str) -> IResult<&str, ExpressionAsVarOpt> {\n\n delimited(\n\n char('('),\n\n sp_enc(map(\n\n pair(expression, opt(preceded(sp_enc1(tag_no_case(\"as\")), var))),\n\n |(expression, var)| ExpressionAsVarOpt {\n\n expression: Box::new(expression),\n\n var,\n\n },\n\n )),\n\n char(')'),\n\n )(i)\n\n}\n\n\n\npub(crate) fn expression_as_var(i: &str) -> IResult<&str, ExpressionAsVar> {\n\n delimited(\n", "file_path": "src/expression/mod.rs", "rank": 50, "score": 30200.386023912848 }, { "content": "\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct ExpressionAsVarOpt {\n\n pub expression: Box<Expression>,\n\n pub var: Option<Var>,\n\n}\n\n\n\npub(crate) fn bracketted3<'a, O1, F>(i: &'a str, pat: F) -> IResult<&str, (O1, O1, Option<O1>)>\n\nwhere\n\n F: Fn(&'a str) -> IResult<&'a str, O1>,\n\n{\n\n bracketted(tuple((\n\n &pat,\n\n preceded(sp_enc(char(',')), &pat),\n\n opt(preceded(sp_enc(char(',')), &pat)),\n\n )))(i)\n\n}\n\n\n\npub(crate) fn bracketted_expr3(\n\n i: &str,\n", "file_path": "src/expression/mod.rs", "rank": 51, "score": 30199.720877026833 }, { "content": "pub(crate) fn distinct_expression(i: &str) -> IResult<&str, DistinctExpression> {\n\n map(\n\n pair(\n\n map(opt(terminated(distinct, sp1)), Option::unwrap_or_default),\n\n expression,\n\n ),\n\n |(distinct, expression)| DistinctExpression {\n\n distinct,\n\n expression,\n\n },\n\n )(i)\n\n}\n\n\n\npub(crate) fn bracketted_expression(i: &str) -> IResult<&str, Expression> {\n\n bracketted(sp_enc(expression))(i)\n\n}\n\n\n\npub(crate) fn bind(i: &str) -> IResult<&str, ExpressionAsVar> {\n\n preceded_tag1(\"bind\", expression_as_var)(i)\n\n}\n", "file_path": "src/expression/mod.rs", "rank": 52, "score": 30193.3365400501 }, { "content": " char('('),\n\n sp_enc(map(\n\n separated_pair(expression, sp_enc(tag_no_case(\"as\")), var),\n\n |(expression, var)| ExpressionAsVar {\n\n expression: Box::new(expression),\n\n var,\n\n },\n\n )),\n\n char(')'),\n\n )(i)\n\n}\n\n\n\npub(crate) fn primary_expression(i: &str) -> IResult<&str, PrimaryExpression> {\n\n alt((\n\n map(bracketted_expression, |expr| {\n\n PrimaryExpression::BrackettedExpression(Box::new(expr))\n\n }),\n\n map(built_in_call, PrimaryExpression::BuiltInCall),\n\n map(iri_or_fun, PrimaryExpression::IriOrFunction),\n\n map(rdf_literal, PrimaryExpression::RdfLiteral),\n", "file_path": "src/expression/mod.rs", "rank": 53, "score": 30193.283861173786 }, { "content": " map(numeric_literal, PrimaryExpression::NumericLiteral),\n\n map(boolean, PrimaryExpression::BooleanLiteral),\n\n map(var, PrimaryExpression::Var),\n\n ))(i)\n\n}\n\n\n\npub(crate) fn expression_list(i: &str) -> IResult<&str, ExpressionList> {\n\n alt((\n\n map(nil, |_| ExpressionList::Nil),\n\n map(\n\n delimited(\n\n char('('),\n\n separated_nonempty_list(sp_enc(char(',')), expression),\n\n char(')'),\n\n ),\n\n ExpressionList::List,\n\n ),\n\n ))(i)\n\n}\n\n\n", "file_path": "src/expression/mod.rs", "rank": 54, "score": 30192.878772098727 }, { "content": "use std::fmt;\n\n\n\nuse crate::data::DataBlock;\n\nuse crate::prologue::Prologue;\n\nuse crate::query::{\n\n ask::AskQuery, construct::ConstructQuery, describe::DescribeQuery, select::SelectQuery,\n\n};\n\n\n\npub mod ask;\n\npub mod construct;\n\npub mod describe;\n\npub mod select;\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct SparqlQueryStatement {\n\n pub prologue: Prologue,\n\n pub query: SparqlQuery,\n\n pub values: Option<DataBlock>,\n\n}\n\n\n", "file_path": "src/query/mod.rs", "rank": 55, "score": 30190.506456059487 }, { "content": "pub mod functions;\n\npub mod iri;\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct Expression(pub Vec<ConditionalAndExpression>);\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum ExpressionList {\n\n Nil,\n\n List(Vec<Expression>),\n\n}\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum PrimaryExpression {\n\n BrackettedExpression(Box<Expression>),\n\n BuiltInCall(BuiltInCall),\n\n IriOrFunction(IriOrFunction),\n\n RdfLiteral(RdfLiteral),\n\n NumericLiteral(NumericLiteral),\n\n BooleanLiteral(bool),\n", "file_path": "src/expression/mod.rs", "rank": 56, "score": 30184.98753831313 }, { "content": " assert_eq!(\n\n iri(\":book1\"),\n\n Ok((\n\n \"\",\n\n Iri::PrefixedName(PrefixedName::PnameLN {\n\n pn_prefix: None,\n\n pn_local: \"book1\".to_string()\n\n })\n\n ))\n\n );\n\n\n\n assert_eq!(\n\n iri(\":\"),\n\n Ok((\"\", Iri::PrefixedName(PrefixedName::PnameNS(None))))\n\n );\n\n }\n\n\n\n #[test]\n\n fn is_expression_as_var() {}\n\n}\n", "file_path": "src/expression/mod.rs", "rank": 57, "score": 30184.181862572532 }, { "content": "#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum ArgList {\n\n Nil,\n\n Expression {\n\n distinct: bool,\n\n expressions: Vec<Expression>,\n\n },\n\n}\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct DistinctExpression {\n\n pub distinct: bool,\n\n pub expression: Expression,\n\n}\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct ExpressionAsVar {\n\n pub expression: Box<Expression>,\n\n pub var: Var,\n\n}\n", "file_path": "src/expression/mod.rs", "rank": 58, "score": 30182.62737426446 }, { "content": "pub enum PrefixedName {\n\n PnameLN {\n\n pn_prefix: Option<String>,\n\n pn_local: String,\n\n },\n\n PnameNS(Option<String>),\n\n}\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum DefaultOrNamedIri {\n\n Default(Iri),\n\n Named(Iri),\n\n}\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct IriOrFunction {\n\n pub iri: Iri,\n\n pub arg_list: Option<ArgList>,\n\n}\n\n\n", "file_path": "src/expression/mod.rs", "rank": 59, "score": 30181.567646346317 }, { "content": " Var(Var),\n\n}\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum Iri {\n\n Iri(String),\n\n PrefixedName(PrefixedName),\n\n}\n\n\n\nimpl Iri {\n\n pub fn iri_ref<T: ToString>(iri_ref: T) -> Self {\n\n Iri::Iri(iri_ref.to_string())\n\n }\n\n\n\n pub fn prefixed_name<T: Into<PrefixedName>>(prefixed_name: T) -> Self {\n\n Iri::PrefixedName(prefixed_name.into())\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n", "file_path": "src/expression/mod.rs", "rank": 60, "score": 30180.926653889852 }, { "content": "#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum SparqlQuery {\n\n Ask(AskQuery),\n\n Select(SelectQuery),\n\n Describe(DescribeQuery),\n\n Construct(ConstructQuery),\n\n}\n\n\n\nimpl fmt::Display for SparqlQuery {\n\n fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {\n\n unimplemented!()\n\n }\n\n}\n", "file_path": "src/query/mod.rs", "rank": 61, "score": 30179.35708351375 }, { "content": "nom-sparql\n\n=====================\n\n[![Build Status](https://travis-ci.com/mattsse/nom-sparql.svg?branch=master)](https://travis-ci.com/mattsse/nom-sparql)\n\n[![Crates.io](https://img.shields.io/crates/v/nom-sparql.svg)](https://crates.io/crates/nom-sparql)\n\n[![Documentation](https://docs.rs/nom-spaqrql/badge.svg)](https://docs.rs/nom-sparql)\n\n\n\nA WIP rust [SPARQL v1.1](https://en.wikipedia.org/wiki/SPARQL) parser written using [nom](https://github.com/Geal/nom).\n\n\n\n## License\n\n\n\nLicensed under either of these:\n\n\n\n * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or\n\n https://www.apache.org/licenses/LICENSE-2.0)\n\n * MIT license ([LICENSE-MIT](LICENSE-MIT) or\n\n https://opensource.org/licenses/MIT)\n\n \n", "file_path": "README.md", "rank": 62, "score": 18888.145827189248 }, { "content": "use crate::expression::{expression_as_var, ExpressionAsVar, Iri};\n\nuse crate::graph::{graph_term, GraphTerm};\n\nuse crate::node::ObjectList;\n\nuse crate::terminals::{iri, is_pn_chars_u, sp};\n\nuse nom::branch::alt;\n\nuse nom::bytes::complete::take_while;\n\nuse nom::bytes::complete::{escaped, tag, tag_no_case, take_while1, take_while_m_n};\n\nuse nom::character::complete::{anychar, char, digit1, none_of, one_of};\n\nuse nom::combinator::recognize;\n\nuse nom::combinator::{complete, cond, cut, map, map_res, not, opt, peek};\n\nuse nom::multi::separated_nonempty_list;\n\nuse nom::sequence::{delimited, pair, preceded, separated_pair, terminated, tuple};\n\nuse nom::{AsChar, IResult};\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum VarOrIri {\n\n Var(Var),\n\n Iri(Iri),\n\n}\n\n\n", "file_path": "src/var.rs", "rank": 63, "score": 42.558906623365004 }, { "content": "use nom::branch::alt;\n\nuse nom::bytes::complete::{escaped, tag, tag_no_case, take_while1, take_while_m_n};\n\nuse nom::character::complete::{anychar, char, digit1, none_of, one_of};\n\nuse nom::combinator::{complete, cond, cut, map, map_res, not, opt, peek};\n\nuse nom::multi::{many1, separated_list};\n\nuse nom::sequence::{delimited, pair, preceded, separated_pair, terminated, tuple};\n\nuse nom::IResult;\n\n\n\nuse crate::clauses::{solution_modifier, values_clause, where_clause, SolutionModifier};\n\nuse crate::data::{data_set_clause, DataBlock, DataSetClause};\n\nuse crate::expression::{\n\n expression, expression_as_var, Expression, ExpressionAsVar, Iri, IriOrFunction, PrefixedName,\n\n};\n\nuse crate::graph::GroupGraphPattern;\n\n\n\nuse crate::terminals::{sp, sp1, sp_enc};\n\nuse crate::var::{var, var_or_expression_as_var, VarOrExpressionAsVar};\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct SelectQuery {\n", "file_path": "src/query/select.rs", "rank": 66, "score": 37.61143281927493 }, { "content": "use nom::{\n\n branch::alt,\n\n bytes::complete::{escaped, tag, tag_no_case, take_while1, take_while_m_n},\n\n character::complete::char,\n\n character::is_digit,\n\n combinator::map_res,\n\n combinator::{map, opt},\n\n multi::{many0, many1, separated_nonempty_list},\n\n sequence::{delimited, pair, separated_pair, tuple},\n\n sequence::{preceded, terminated},\n\n IResult,\n\n};\n\n\n\nuse crate::{\n\n expression::ArgList,\n\n graph::graph_node,\n\n node::{Collection, ObjectList, PropertyList, TriplesNode},\n\n path::{triples_same_subject_path, TriplesSameSubjectPath},\n\n terminals::{bracketted, sp, sp_enc, sp_sep, sp_sep1},\n\n triple::{triples_template, TriplesTemplate},\n", "file_path": "src/quads.rs", "rank": 67, "score": 37.0059232908909 }, { "content": "use std::str::FromStr;\n\n\n\nuse nom::character::complete::char;\n\nuse nom::combinator::{map, opt};\n\nuse nom::error::ErrorKind;\n\nuse nom::multi::{many0, many1, separated_nonempty_list};\n\nuse nom::sequence::{delimited, pair, separated_pair, tuple};\n\nuse nom::Err;\n\nuse nom::{\n\n branch::alt,\n\n bytes::complete::{escaped, tag, tag_no_case, take_while1, take_while_m_n},\n\n character::is_digit,\n\n combinator::map_res,\n\n sequence::{preceded, terminated},\n\n IResult, Needed,\n\n};\n\n\n\nuse crate::expression::iri::{iri_or_a_or_caret, IriOrAOrCaret};\n\nuse crate::expression::Iri;\n\nuse crate::node::ObjectList;\n", "file_path": "src/path.rs", "rank": 68, "score": 36.96717906698212 }, { "content": "use std::{fmt, str::FromStr};\n\n\n\nuse crate::expression::{expression_list, primary_expression, ExpressionList, PrimaryExpression};\n\nuse crate::literal::{numeric_literal, NumericLiteral};\n\nuse crate::terminals::{preceded_tag, sp, sp_enc, sp_enc1};\n\nuse nom::branch::alt;\n\nuse nom::bytes::complete::tag;\n\nuse nom::bytes::streaming::tag_no_case;\n\nuse nom::combinator::{map, opt};\n\nuse nom::multi::{separated_list, separated_nonempty_list};\n\nuse nom::sequence::{pair, preceded, terminated};\n\nuse nom::IResult;\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct RelationalExpression {\n\n pub lhs: AdditiveExpression,\n\n pub rhs: Option<OpExpression>,\n\n}\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n", "file_path": "src/arithmetic.rs", "rank": 69, "score": 36.76466482022549 }, { "content": " map(\n\n delimited(tag(\"(\"), many1(graph_node_path), tag(\")\")),\n\n TriplesNodePath::CollectionPath,\n\n ),\n\n ))(i)\n\n}\n\n\n\npub(crate) fn graph_node_path(i: &str) -> IResult<&str, GraphNodePath> {\n\n alt((\n\n map(var_or_term, GraphNodePath::VarOrTerm),\n\n map(triples_node_path, GraphNodePath::TriplesNodePath),\n\n ))(i)\n\n}\n\n\n\npub(crate) fn path_alternative(i: &str) -> IResult<&str, PathAlternative> {\n\n map(\n\n separated_nonempty_list(delimited(sp, tag(\"|\"), sp), path_sequence),\n\n PathAlternative,\n\n )(i)\n\n}\n", "file_path": "src/path.rs", "rank": 70, "score": 35.08348868544382 }, { "content": "}\n\n\n\n// TODO consider unicode cases in second\n\npub(crate) fn var_name(i: &str) -> IResult<&str, &str> {\n\n recognize(pair(\n\n take_while_m_n(1, 1, |c| is_pn_chars_u(c) || c.is_dec_digit()),\n\n take_while(|c| is_pn_chars_u(c) || c.is_dec_digit()),\n\n ))(i)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn is_verb() {\n\n assert_eq!(verb(\"a\"), Ok((\"\", Verb::A)));\n\n\n\n assert_eq!(\n\n verb(\"?name\"),\n", "file_path": "src/var.rs", "rank": 71, "score": 34.986812756506964 }, { "content": "pub(crate) fn delete_insert(i: &str) -> IResult<&str, DeleteInsert> {\n\n alt((\n\n map(\n\n pair(delete_clause, opt(preceded(sp, insert_clause))),\n\n |(delete, insert)| DeleteInsert::DeleteInsert { delete, insert },\n\n ),\n\n map(insert_clause, DeleteInsert::Insert),\n\n ))(i)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::expression::PrefixedName;\n\n\n\n #[test]\n\n fn is_drop_stmt() {\n\n assert_eq!(\n\n drop_stmt(\"drop graph :uri1\"),\n\n Ok((\n", "file_path": "src/operations.rs", "rank": 72, "score": 34.57820641814048 }, { "content": "use nom::combinator::{cut, opt, recognize};\n\nuse nom::error::{make_error, ErrorKind};\n\nuse nom::sequence::{pair, tuple};\n\nuse nom::{\n\n branch::alt,\n\n bytes::complete::{escaped, tag, tag_no_case, take_while1, take_while_m_n},\n\n character::{\n\n complete::{char, digit1},\n\n is_digit,\n\n },\n\n combinator::{map, map_res},\n\n error::ParseError,\n\n sequence::{preceded, terminated},\n\n Err, IResult, ParseTo,\n\n};\n\n\n\nuse crate::arithmetic::Sign;\n\nuse crate::terminals::{language_tag, rdf_literal, string_literal};\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n", "file_path": "src/literal.rs", "rank": 73, "score": 34.03882286106583 }, { "content": "use crate::{\n\n expression::{distinct_expression, expression, ArgList, DistinctExpression, Expression, Iri},\n\n literal::distinct,\n\n terminals::{bracketted, preceded_bracketted, preceded_tag, sp, sp1, sp_enc, string_literal},\n\n};\n\nuse nom::{\n\n branch::alt,\n\n bytes::complete::tag_no_case,\n\n character::complete::char,\n\n combinator::{map, opt},\n\n sequence::{pair, preceded, terminated, tuple},\n\n IResult,\n\n};\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum Aggregate {\n\n Count(Count),\n\n Sum(DistinctExpression),\n\n Min(DistinctExpression),\n\n Max(DistinctExpression),\n", "file_path": "src/aggregate.rs", "rank": 74, "score": 33.94525484810358 }, { "content": "\n\npub(crate) fn verb(i: &str) -> IResult<&str, Verb> {\n\n alt((\n\n map(var_or_iri, Verb::VarOrIri),\n\n map(tag_no_case(\"a\"), |_| Verb::A),\n\n ))(i)\n\n}\n\n\n\npub(crate) fn var_or_term(i: &str) -> IResult<&str, VarOrTerm> {\n\n alt((map(var, VarOrTerm::Var), map(graph_term, VarOrTerm::Term)))(i)\n\n}\n\n\n\npub(crate) fn var(i: &str) -> IResult<&str, Var> {\n\n alt((\n\n map(\n\n preceded(char('?'), preceded(sp, map(var_name, String::from))),\n\n Var::QMark,\n\n ),\n\n map(\n\n preceded(char('$'), preceded(sp, map(var_name, String::from))),\n", "file_path": "src/var.rs", "rank": 75, "score": 33.277071704393165 }, { "content": "\n\npub(crate) fn blank_node(i: &str) -> IResult<&str, BlankNode> {\n\n alt((\n\n map(\n\n sp_sep(\n\n tag(\"_:\"),\n\n recognize(pair(\n\n alt((pn_chars_u_one, take_while_m_n(1, 1, |c| is_digit(c as u8)))),\n\n pn_chars_tail,\n\n )),\n\n ),\n\n |(_, label)| BlankNode::Label(label.to_string()),\n\n ),\n\n map(anon, |_| BlankNode::Anon),\n\n ))(i)\n\n}\n\n\n\npub(crate) fn graph_node(i: &str) -> IResult<&str, GraphNode> {\n\n alt((\n\n map(var_or_term, GraphNode::VarOrTerm),\n", "file_path": "src/graph.rs", "rank": 76, "score": 33.181102336609165 }, { "content": " ),\n\n map(\n\n tuple((\n\n tag_no_case(\"not\"),\n\n sp_enc1(tag_no_case(\"exists\")),\n\n group_graph_pattern,\n\n )),\n\n |(_, _, graph)| BuiltInCall::NotExistsFunc(graph),\n\n ),\n\n ))(i)\n\n}\n\n\n\npub(crate) fn arg_list(i: &str) -> IResult<&str, ArgList> {\n\n alt((\n\n map(nil, |_| ArgList::Nil),\n\n map(\n\n delimited(\n\n terminated(char('('), sp),\n\n tuple((\n\n map(opt(terminated(distinct, sp1)), Option::unwrap_or_default),\n", "file_path": "src/call.rs", "rank": 77, "score": 33.0058264394677 }, { "content": " ))(i)\n\n}\n\n\n\npub(crate) fn blank_node_property_list_path(i: &str) -> IResult<&str, PropertyListPath> {\n\n delimited(\n\n terminated(tag(\"[\"), sp),\n\n property_list_path_not_empty,\n\n preceded(sp, tag(\"]\")),\n\n )(i)\n\n}\n\n\n\npub(crate) fn property_list_path_not_empty(i: &str) -> IResult<&str, PropertyListPath> {\n\n map(\n\n tuple((\n\n terminated(verb_path_or_simple, sp1),\n\n object_list_path,\n\n many0(preceded(many1(sp_enc(char(';'))), property_list_path_entry)),\n\n )),\n\n |(verb_path_or_simple, object_list_path, entries)| PropertyListPath {\n\n verb_path_or_simple,\n", "file_path": "src/path.rs", "rank": 78, "score": 32.99354313924751 }, { "content": " )(i)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::expression::{Iri, PrefixedName};\n\n use crate::graph::{GraphNode, GraphTerm};\n\n use crate::triple::TriplesSameSubject;\n\n use crate::var::{Var, Verb};\n\n\n\n #[test]\n\n fn is_quads_not_triples() {\n\n let _nil = TriplesSameSubject::Node {\n\n triples_node: TriplesNode::Collection(Collection(vec![\n\n GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(true))),\n\n GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)),\n\n ])),\n\n property_list: None,\n\n };\n", "file_path": "src/quads.rs", "rank": 79, "score": 32.64733018440777 }, { "content": "use crate::call::{built_in_call, function_call, BuiltInCall, FunctionCall};\n\nuse crate::expression::{bracketted_expr3, bracketted_expression, expression, Expression};\n\nuse crate::literal::StringLiteral;\n\nuse crate::terminals::{bracketted, preceded_tag1, sp_enc};\n\nuse nom::branch::alt;\n\nuse nom::character::complete::char;\n\nuse nom::combinator::{map, opt};\n\nuse nom::sequence::{preceded, tuple};\n\nuse nom::IResult;\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct RegexExpression {\n\n pub first: Expression,\n\n pub second: Expression,\n\n pub third: Option<Expression>,\n\n}\n\n\n\npub type SubstringExpression = RegexExpression;\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n", "file_path": "src/expression/functions.rs", "rank": 80, "score": 32.476817523098624 }, { "content": " DeleteInsert {\n\n delete: Quads,\n\n insert: Option<Quads>,\n\n },\n\n Insert(Quads),\n\n}\n\n\n\npub(crate) fn add_stmt(i: &str) -> IResult<&str, AddStatement> {\n\n map(\n\n pair(pair(tag_no_case(\"add\"), sp1), silent_from_to),\n\n |(_, (silent, from, to))| AddStatement { silent, from, to },\n\n )(i)\n\n}\n\n\n\npub(crate) fn modify_stmt(i: &str) -> IResult<&str, ModifyStatement> {\n\n map(\n\n tuple((\n\n opt(delimited(tag_no_case(\"where\"), iri, sp1)),\n\n terminated(delete_insert, sp),\n\n separated_list(sp, using_clause),\n", "file_path": "src/operations.rs", "rank": 84, "score": 31.80707982877948 }, { "content": "use nom::{\n\n branch::alt,\n\n bytes::complete::{tag, tag_no_case},\n\n character::complete::char,\n\n combinator::map,\n\n multi::{many0, many1, separated_list, separated_nonempty_list},\n\n sequence::{delimited, pair, preceded, tuple},\n\n IResult,\n\n};\n\n\n\nuse crate::{\n\n expression::{DefaultOrNamedIri, Iri},\n\n literal::{boolean, numeric_literal, NumericLiteral},\n\n node::RdfLiteral,\n\n terminals::{bracketted, default_or_named_iri, iri, preceded_tag1, rdf_literal, sp, sp_enc},\n\n var::{var, Var},\n\n};\n\n\n\n/// NAMED GraphClause = NAMED Iri\n\npub type DataSetClause = DefaultOrNamedIri;\n", "file_path": "src/data.rs", "rank": 85, "score": 31.426504120031424 }, { "content": " preceded(\n\n alt((char('e'), char('E'))),\n\n map_res(\n\n recognize(tuple((opt(alt((char('+'), char('-')))), cut(digit1)))),\n\n |s: &str| s.parse::<i64>(),\n\n ),\n\n )(i)\n\n}\n\n\n\npub(crate) fn recognize_spaqrql_float(i: &str) -> IResult<&str, &str> {\n\n recognize(pair(\n\n opt(alt((char('+'), char('-')))),\n\n alt((\n\n map(pair(digit1, opt(pair(char('.'), opt(digit1)))), |_| ()),\n\n map(tuple((char('.'), digit1)), |_| ()),\n\n )),\n\n ))(i)\n\n}\n\n\n\npub(crate) fn sparql_decimal(input: &str) -> IResult<&str, f64> {\n", "file_path": "src/literal.rs", "rank": 86, "score": 31.371414528213744 }, { "content": "use nom::branch::alt;\n\nuse nom::bytes::complete::tag_no_case;\n\nuse nom::combinator::map;\n\nuse nom::sequence::separated_pair;\n\nuse nom::IResult;\n\n\n\nuse crate::expression::functions::{constraint, Constraint};\n\nuse crate::expression::{bracketted_expression, Expression};\n\nuse crate::terminals::sp1;\n\nuse crate::var::{var, Var};\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum Order {\n\n Asc,\n\n Desc,\n\n}\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct OrderExpression {\n\n pub order: Order,\n", "file_path": "src/order.rs", "rank": 87, "score": 31.345838277862107 }, { "content": "use crate::clauses::{solution_modifier, where_clause, SolutionModifier};\n\nuse crate::data::{data_set_clause, DataSetClause};\n\nuse crate::graph::GroupGraphPattern;\n\nuse crate::terminals::{sp, sp_enc1};\n\nuse crate::var::{var_or_iri, var_or_iris_or_all, VarOrIri, VarOrIrisOrAll};\n\nuse nom::{\n\n branch::alt,\n\n bytes::complete::tag_no_case,\n\n character::complete::char,\n\n combinator::{map, opt},\n\n multi::{separated_list, separated_nonempty_list},\n\n sequence::{terminated, tuple},\n\n IResult,\n\n};\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct DescribeQuery {\n\n pub dataset_clauses: Vec<DataSetClause>,\n\n pub var_or_iris_or_all: VarOrIrisOrAll,\n\n pub where_clause: Option<GroupGraphPattern>,\n\n pub solution_modifier: SolutionModifier,\n\n}\n\n\n", "file_path": "src/query/describe.rs", "rank": 88, "score": 31.026509541967897 }, { "content": "use crate::expression::Iri;\n\nuse crate::terminals::iri;\n\nuse nom::branch::alt;\n\nuse nom::bytes::complete::tag_no_case;\n\nuse nom::character::complete::char;\n\nuse nom::combinator::map;\n\nuse nom::sequence::preceded;\n\nuse nom::IResult;\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum IriOrAOrCaret {\n\n IriOrA(IriOrA),\n\n /// [`IriOrA`] prefixed with a `^`\n\n Caret(IriOrA),\n\n}\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum IriOrA {\n\n Iri(Iri),\n\n A,\n\n}\n", "file_path": "src/expression/iri.rs", "rank": 89, "score": 30.913105686875785 }, { "content": " |(distinct, target)| Count { distinct, target },\n\n )(i)\n\n}\n\n\n\npub(crate) fn group_concat(i: &str) -> IResult<&str, GroupConcat> {\n\n map(\n\n preceded_tag(\n\n \"group_concat\",\n\n bracketted(pair(\n\n distinct_expression,\n\n opt(preceded(\n\n sp,\n\n preceded(\n\n tuple((\n\n char(';'),\n\n sp_enc(tag_no_case(\"separator\")),\n\n terminated(char('='), sp),\n\n )),\n\n map(string_literal, String::from),\n\n ),\n", "file_path": "src/aggregate.rs", "rank": 90, "score": 30.807225256461535 }, { "content": "pub(crate) fn service_graph_pattern(i: &str) -> IResult<&str, ServiceGraphPattern> {\n\n map(\n\n tuple((\n\n terminated(tag_no_case(\"service\"), sp1),\n\n map(opt(terminated(silent, sp1)), Option::unwrap_or_default),\n\n terminated(var_or_iri, sp),\n\n group_graph_pattern,\n\n )),\n\n |(_, silent, var_or_iri, graph_pattern)| ServiceGraphPattern {\n\n var_or_iri,\n\n silent,\n\n graph_pattern,\n\n },\n\n )(i)\n\n}\n\n\n\npub(crate) fn group_graph_pattern(i: &str) -> IResult<&str, GroupGraphPattern> {\n\n delimited(\n\n char('{'),\n\n sp_enc(alt((\n", "file_path": "src/graph.rs", "rank": 91, "score": 30.78106686105972 }, { "content": "pub(crate) fn path_negated_property_set(i: &str) -> IResult<&str, PathNegatedPropertySet> {\n\n map(\n\n delimited(\n\n terminated(tag(\"(\"), sp),\n\n separated_nonempty_list(delimited(sp, char('|'), sp), path_one_in_property_set),\n\n preceded(sp, tag(\")\")),\n\n ),\n\n PathNegatedPropertySet,\n\n )(i)\n\n}\n\n\n\npub(crate) fn path_one_in_property_set(i: &str) -> IResult<&str, PathOneInPropertySet> {\n\n map(iri_or_a_or_caret, PathOneInPropertySet)(i)\n\n}\n\n\n\npub(crate) fn path_mod(i: &str) -> IResult<&str, PathMod> {\n\n if i.is_empty() {\n\n Err(Err::Incomplete(Needed::Size(1)))\n\n } else if let Ok(path) = PathMod::from_str(&i[0..1]) {\n\n Ok((&i[1..], path))\n", "file_path": "src/path.rs", "rank": 92, "score": 30.68580808838465 }, { "content": "use nom::{\n\n branch::alt,\n\n character::complete::char,\n\n combinator::{map, opt},\n\n sequence::preceded,\n\n sequence::{pair, tuple},\n\n IResult,\n\n};\n\n\n\nuse crate::operations::{\n\n clear_stmt, copy_stmt, create_stmt, delete_data, delete_where_data, drop_stmt, insert_data,\n\n load_stmt, modify_stmt, AddStatement, ClearStatement, CopyStatement, CreateStatement,\n\n DropStatement, LoadStatement, ModifyStatement, MoveStatement,\n\n};\n\nuse crate::prologue::Prologue;\n\nuse crate::quads::Quads;\n\nuse crate::terminals::{prologue, sp, sp_enc};\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct Update {\n", "file_path": "src/update.rs", "rank": 93, "score": 30.67653238426695 }, { "content": "\n\npub(crate) fn inline_data(i: &str) -> IResult<&str, DataBlock> {\n\n preceded_tag1(\"values\", datablock)(i)\n\n}\n\n\n\n//delimited(tag(\"(\"), map(var,|x|vec![x]), tag(\")\")),\n\npub(crate) fn inline_data_full(i: &str) -> IResult<&str, InlineDataFull> {\n\n map(\n\n tuple((\n\n bracketted(preceded(sp, many0(sp_enc(var)))),\n\n delimited(\n\n sp_enc(char('{')),\n\n many0(sp_enc(bracketted(preceded(\n\n sp,\n\n many0(sp_enc(datablock_value)),\n\n )))),\n\n preceded(sp, char('}')),\n\n ),\n\n )),\n\n |(vars, data_block_values)| InlineDataFull {\n", "file_path": "src/data.rs", "rank": 94, "score": 30.584197509322678 }, { "content": " map(tag_no_case(\"silent\"), |_| true)(i)\n\n}\n\n\n\n#[inline]\n\npub(crate) fn distinct(i: &str) -> IResult<&str, bool> {\n\n map(tag_no_case(\"distinct\"), |_| true)(i)\n\n}\n\n\n\npub(crate) fn boolean(i: &str) -> IResult<&str, bool> {\n\n alt((\n\n map(tag_no_case(\"false\"), |_| false),\n\n map(tag_no_case(\"true\"), |_| true),\n\n ))(i)\n\n}\n\n\n\npub(crate) fn sign(i: &str) -> IResult<&str, Sign> {\n\n alt((map(char('+'), |_| Sign::POS), map(char('-'), |_| Sign::NEG)))(i)\n\n}\n\n\n\npub(crate) fn exponent(i: &str) -> IResult<&str, i64> {\n", "file_path": "src/literal.rs", "rank": 96, "score": 30.42277673345804 }, { "content": " } else {\n\n Err(Err::Error((i, ErrorKind::Char)))\n\n }\n\n}\n\n\n\n#[inline]\n\npub(crate) fn is_path_mod(c: char) -> bool {\n\n \"?*+\".contains(c)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn is_path_mode() {\n\n assert_eq!(path_mod(\"*\"), Ok((\"\", PathMod::Asterisk)));\n\n assert_eq!(path_mod(\"+\"), Ok((\"\", PathMod::Plus)));\n\n assert_eq!(path_mod(\"?\"), Ok((\"\", PathMod::QuestionMark)));\n\n }\n\n\n\n}\n", "file_path": "src/path.rs", "rank": 97, "score": 29.925086457608295 }, { "content": "use crate::terminals::{anon, iri, nil, pn_local, rdf_literal, sp, sp1, sp_enc, sp_sep, sp_sep1};\n\nuse crate::triple::object_list;\n\nuse crate::var::{var, var_or_term, Var, VarOrTerm};\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum GraphNodePath {\n\n VarOrTerm(VarOrTerm),\n\n TriplesNodePath(TriplesNodePath),\n\n}\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum TriplesNodePath {\n\n CollectionPath(Vec<GraphNodePath>),\n\n BlankNodePropertyListPath(PropertyListPath),\n\n}\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub enum TriplesSameSubjectPath {\n\n Term {\n\n var_or_term: VarOrTerm,\n\n property_list: PropertyListPath,\n", "file_path": "src/path.rs", "rank": 98, "score": 29.890725446864256 }, { "content": "use nom::{\n\n branch::alt,\n\n bytes::complete::tag_no_case,\n\n character::complete::char,\n\n combinator::{map, opt},\n\n multi::separated_nonempty_list,\n\n sequence::{delimited, preceded, separated_pair, terminated, tuple},\n\n IResult,\n\n};\n\n\n\nuse crate::expression::functions::{\n\n regex_expression, str_replace_expression, substring_expression, RegexExpression,\n\n StrReplaceExpression, SubstringExpression,\n\n};\n\nuse crate::{\n\n aggregate::{aggregate, Aggregate},\n\n expression::{\n\n bracketted_expression, expression, expression_list, ArgList, Expression, ExpressionList,\n\n Iri,\n\n },\n", "file_path": "src/call.rs", "rank": 99, "score": 29.755955411374487 } ]
Rust
basis-universal/src/transcoding/transcoding_tests.rs
fintelia/basis-universal-rs
4a23939034479de8119d52fd0eb1737cad5e46ee
use super::*; #[test] fn test_get_bytes_per_block_or_pixel() { assert_eq!( TranscoderTextureFormat::BC1_RGB.bytes_per_block_or_pixel(), 8 ); } #[test] fn test_get_format_name() { assert_eq!(TranscoderTextureFormat::BC1_RGB.format_name(), "BC1_RGB"); } #[test] fn test_transcoder_format_has_alpha() { assert_eq!(TranscoderTextureFormat::BC1_RGB.has_alpha(), false); assert_eq!(TranscoderTextureFormat::BC7_RGBA.has_alpha(), true); } #[test] fn test_get_texture_type_name() { assert_eq!(BasisTextureType::TextureType2D.texture_type_name(), "2D"); } #[test] fn test_new_transcoder() { let transcoder = Transcoder::new(); std::mem::drop(transcoder); } #[test] fn test_transcoder_get_total_images() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); let transcoder = Transcoder::new(); assert_eq!(transcoder.image_count(basis_file), 1); std::mem::drop(transcoder); } #[test] fn test_transcoder_info() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); let transcoder = Transcoder::new(); let file_info = transcoder.file_info(basis_file).unwrap(); assert!(transcoder.image_info(basis_file, 0).is_some()); assert!(transcoder .image_level_description(basis_file, 0, 0) .is_some()); assert!(transcoder.image_level_info(basis_file, 0, 0).is_some()); assert!(transcoder .image_info(basis_file, file_info.m_total_images + 1) .is_none()); assert!(transcoder .image_level_description(basis_file, file_info.m_total_images + 1, 0) .is_none()); assert!(transcoder .image_level_info(basis_file, file_info.m_total_images + 1, 0) .is_none()); assert!(transcoder .image_level_description(basis_file, 0, 100) .is_none()); assert!(transcoder.image_level_info(basis_file, 0, 100).is_none()); std::mem::drop(transcoder); } #[test] fn test_transcoder_get_tex_format() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); let transcoder = Transcoder::new(); assert_eq!( transcoder.basis_texture_format(basis_file), BasisTextureFormat::ETC1S ); std::mem::drop(transcoder); let basis_file = include_bytes!("../../test_assets/rust-logo-uastc.basis"); let transcoder = Transcoder::new(); assert_eq!( transcoder.basis_texture_format(basis_file), BasisTextureFormat::UASTC4x4 ); std::mem::drop(transcoder); } #[test] fn test_transcoder_get_total_image_levels() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); let transcoder = Transcoder::new(); assert_eq!(transcoder.image_level_count(basis_file, 0), 7); std::mem::drop(transcoder); } #[test] fn test_transcoder_transcode_etc() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); do_test_transcoder_transcode(basis_file, "test_assets/test_transcode_image_etc.png"); } #[test] fn test_transcoder_transcode_uastc() { let basis_file = include_bytes!("../../test_assets/rust-logo-uastc.basis"); do_test_transcoder_transcode(basis_file, "test_assets/test_transcode_image_uastc.png"); } fn do_test_transcoder_transcode( basis_file: &[u8], _out_path: &str, ) { let mut transcoder = Transcoder::new(); transcoder.prepare_transcoding(basis_file).unwrap(); transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::ETC1_RGB, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap(); transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::ASTC_4x4_RGBA, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap(); if transcoder.basis_texture_format(basis_file) == BasisTextureFormat::ETC1S { transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::FXT1_RGB, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap(); } let _result = transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::RGBA32, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap(); transcoder.end_transcoding(); std::mem::drop(transcoder); }
use super::*; #[test] fn test_get_bytes_per_block_or_pixel() { assert_eq!( TranscoderTextureFormat::BC1_RGB.bytes_per_block_or_pixel(), 8 ); } #[test] fn test_get_format_name() { assert_eq!(TranscoderTextureFormat::BC1_RGB.format_name(), "BC1_RGB"); } #[test] fn test_transcoder_format_has_alpha() { assert_eq!(TranscoderTextureFormat::BC1_RGB.has_alpha(), false); assert_eq!(TranscoderTextureFormat::BC7_RGBA.has_alpha(), true); } #[test] fn test_get_texture_type_name() { assert_eq!(BasisTextureType::TextureType2D.texture_type_name(), "2D"); } #[test] fn test_new_transcoder() { let transcoder = Transcoder::new(); std::mem::drop(transcoder); } #[test] fn test_transcoder_get_total_images() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); let transcoder = Transcoder::new(); assert_eq!(transcoder.image_count(basis_file), 1); std::mem::drop(transcoder); } #[test] fn test_transcoder_info() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); let transcoder = Transcoder::new(); let file_info = transcoder.file_info(basis_file).unwrap(); assert!(transcoder.image_info(basis_file, 0).is_some()); assert!(transcoder .image_level_description(basis_file, 0, 0) .is_some()); assert!(transcoder.image_level_info(basis_file, 0, 0).is_some()); assert!(transcoder .image_info(basis_file, file_info.m_total_images + 1) .is_none()); assert!(transcoder .image_level_description(basis_file, file_info.m_total_images + 1, 0) .is_none()); assert!(transcoder .image_level_info(basis_file, file_info.m_total_images + 1, 0) .is_none()); assert!(transcoder .image_level_description(basis_file, 0, 100) .is_none()); assert!(transcoder.image_level_info(basis_file, 0, 100).is_none()); std::mem::drop(transcoder); } #[test] fn test_transcoder_get_tex_format() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); let transcoder = Transcoder::new(); assert_eq!( transcoder.basis_texture_format(basis_file), BasisTextureFormat::ETC1S ); std::mem::drop(transcoder); let basis_file = include_bytes!("../../test_assets/rust-logo-uastc.basis"); let transcoder = Transcoder::new(); assert_eq!( transcoder.basis_texture_format(basis_file), BasisTextureFormat::UASTC4x4 ); std::mem::drop(transcoder); } #[test] fn test_transcoder_get_total_image_levels() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); let transcoder = Transcoder::new(); assert_eq!(transcoder.image_level_count(basis_file, 0), 7); std::mem::drop(transcoder); } #[test] fn test_transcoder_transcode_etc() { let basis_file = include_bytes!("../../test_assets/rust-logo-etc.basis"); do_test_transcoder_transcode(basis_file, "test_assets/test_transcode_image_etc.png"); } #[test] fn test_transcoder_transcode_uastc() { let basis_file = include_bytes!("../../test_assets/rust-logo-uastc.basis"); do_test_transcoder_transcode(basis_file, "test_assets/test_transcode_image_uastc.png"); } fn do_test_transcoder_transcode( basis_file: &[u8], _out_path: &str, ) { let mut transcoder = Transcoder::new(); transcoder.prepare_transcoding(basis_file).unwrap(); transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::ETC1_RGB, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap(); transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::ASTC_4x4_RGBA, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap();
let _result = transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::RGBA32, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap(); transcoder.end_transcoding(); std::mem::drop(transcoder); }
if transcoder.basis_texture_format(basis_file) == BasisTextureFormat::ETC1S { transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::FXT1_RGB, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap(); }
if_condition
[ { "content": "#[test]\n\nfn bindgen_test_layout_Transcoder() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Transcoder>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(Transcoder))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Transcoder>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Transcoder))\n\n );\n\n}\n\nextern \"C\" {\n\n pub fn transcoder_new() -> *mut Transcoder;\n\n}\n\nextern \"C\" {\n\n pub fn transcoder_delete(transcoder: *mut Transcoder);\n\n}\n\nextern \"C\" {\n\n pub fn transcoder_validate_file_checksums(\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 12, "score": 93653.40382468997 }, { "content": "#[test]\n\nfn bindgen_test_layout_basist_basisu_transcoder_state() {\n\n assert_eq!(\n\n ::std::mem::size_of::<basist_basisu_transcoder_state>(),\n\n 816usize,\n\n concat!(\"Size of: \", stringify!(basist_basisu_transcoder_state))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<basist_basisu_transcoder_state>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(basist_basisu_transcoder_state))\n\n );\n\n}\n\npub const basist_basisu_decode_flags_cDecodeFlagsPVRTCDecodeToNextPow2: basist_basisu_decode_flags =\n\n 2;\n\npub const basist_basisu_decode_flags_cDecodeFlagsTranscodeAlphaDataToOpaqueFormats:\n\n basist_basisu_decode_flags = 4;\n\npub const basist_basisu_decode_flags_cDecodeFlagsBC1ForbidThreeColorBlocks:\n\n basist_basisu_decode_flags = 8;\n\npub const basist_basisu_decode_flags_cDecodeFlagsOutputHasAlphaIndices: basist_basisu_decode_flags =\n\n 16;\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 13, "score": 87580.57657785625 }, { "content": "#[test]\n\nfn bindgen_test_layout_ColorU8() {\n\n assert_eq!(\n\n ::std::mem::size_of::<ColorU8>(),\n\n 4usize,\n\n concat!(\"Size of: \", stringify!(ColorU8))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<ColorU8>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(ColorU8))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<ColorU8>())).channels as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(ColorU8),\n\n \"::\",\n\n stringify!(channels)\n\n )\n", "file_path": "basis-universal-sys/src/encoding_bindings.rs", "rank": 14, "score": 86798.59637991987 }, { "content": "#[test]\n\nfn bindgen_test_layout_ColorU8_Channels() {\n\n assert_eq!(\n\n ::std::mem::size_of::<ColorU8_Channels>(),\n\n 4usize,\n\n concat!(\"Size of: \", stringify!(ColorU8_Channels))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<ColorU8_Channels>(),\n\n 1usize,\n\n concat!(\"Alignment of \", stringify!(ColorU8_Channels))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<ColorU8_Channels>())).r as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(ColorU8_Channels),\n\n \"::\",\n\n stringify!(r)\n\n )\n", "file_path": "basis-universal-sys/src/encoding_bindings.rs", "rank": 15, "score": 84646.31235247939 }, { "content": "#[test]\n\nfn bindgen_test_layout_basist_basisu_transcoder_state_block_preds() {\n\n assert_eq!(\n\n ::std::mem::size_of::<basist_basisu_transcoder_state_block_preds>(),\n\n 4usize,\n\n concat!(\n\n \"Size of: \",\n\n stringify!(basist_basisu_transcoder_state_block_preds)\n\n )\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<basist_basisu_transcoder_state_block_preds>(),\n\n 2usize,\n\n concat!(\n\n \"Alignment of \",\n\n stringify!(basist_basisu_transcoder_state_block_preds)\n\n )\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<basist_basisu_transcoder_state_block_preds>())).m_endpoint_index\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 16, "score": 84036.16869347439 }, { "content": "#[test]\n\nfn bindgen_test_layout_FileInfo() {\n\n assert_eq!(\n\n ::std::mem::size_of::<FileInfo>(),\n\n 72usize,\n\n concat!(\"Size of: \", stringify!(FileInfo))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<FileInfo>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(FileInfo))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<FileInfo>())).m_version as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(FileInfo),\n\n \"::\",\n\n stringify!(m_version)\n\n )\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 17, "score": 83607.44867516455 }, { "content": "#[test]\n\nfn bindgen_test_layout_basist_basisu_image_info() {\n\n assert_eq!(\n\n ::std::mem::size_of::<basist_basisu_image_info>(),\n\n 44usize,\n\n concat!(\"Size of: \", stringify!(basist_basisu_image_info))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<basist_basisu_image_info>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(basist_basisu_image_info))\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<basist_basisu_image_info>())).m_image_index as *const _ as usize\n\n },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(basist_basisu_image_info),\n\n \"::\",\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 18, "score": 79611.292034794 }, { "content": "#[test]\n\nfn bindgen_test_layout_basist_basisu_image_level_info() {\n\n assert_eq!(\n\n ::std::mem::size_of::<basist_basisu_image_level_info>(),\n\n 60usize,\n\n concat!(\"Size of: \", stringify!(basist_basisu_image_level_info))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<basist_basisu_image_level_info>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(basist_basisu_image_level_info))\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<basist_basisu_image_level_info>())).m_image_index as *const _\n\n as usize\n\n },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(basist_basisu_image_level_info),\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 19, "score": 77781.34870927266 }, { "content": "#[test]\n\nfn test_new_compressor() {\n\n let compressor = Compressor::default();\n\n std::mem::drop(compressor);\n\n}\n\n\n", "file_path": "basis-universal/src/encoding/encoding_tests.rs", "rank": 20, "score": 73799.41795672 }, { "content": "#[test]\n\nfn test_encode_image() {\n\n //\n\n // Read the PNG file from disk\n\n //\n\n let png_file = include_bytes!(\"../../test_assets/rust-logo.png\");\n\n let image_data =\n\n image::load_from_memory_with_format(png_file, image::ImageFormat::Png).unwrap();\n\n\n\n use image::ColorType;\n\n let channel_count = match &image_data.color() {\n\n ColorType::L8 => 1,\n\n ColorType::La8 => 2,\n\n ColorType::Rgb8 => 3,\n\n ColorType::Rgba8 => 4,\n\n ColorType::L16 => 1,\n\n ColorType::La16 => 2,\n\n ColorType::Rgb16 => 3,\n\n ColorType::Rgba16 => 4,\n\n ColorType::Bgr8 => 3,\n\n ColorType::Bgra8 => 4,\n", "file_path": "basis-universal/src/encoding/encoding_tests.rs", "rank": 21, "score": 73799.41795672 }, { "content": "#[test]\n\nfn test_compressor_init() {\n\n let compressor_params = CompressorParams::new();\n\n let mut compressor = Compressor::default();\n\n unsafe {\n\n compressor.init(&compressor_params);\n\n }\n\n std::mem::drop(compressor);\n\n std::mem::drop(compressor_params);\n\n}\n\n\n", "file_path": "basis-universal/src/encoding/encoding_tests.rs", "rank": 22, "score": 73799.41795672 }, { "content": "#[test]\n\nfn test_image_smoketest_bindings() {\n\n let mut compressor_params = CompressorParams::new();\n\n\n\n let mut image = compressor_params.source_image_mut(0);\n\n let color = image.pixel_at(50, 50);\n\n assert!(color.is_none());\n\n image.resize(100, 100);\n\n let color = image.pixel_at(50, 50);\n\n assert!(color.is_some());\n\n let _color = unsafe { image.pixel_at_unchecked(50, 50) };\n\n image.invalidate();\n\n}\n\n\n", "file_path": "basis-universal/src/encoding/encoding_tests.rs", "rank": 23, "score": 72269.46626354601 }, { "content": "#[test]\n\nfn test_new_compressor_params() {\n\n let compressor_params = CompressorParams::new();\n\n std::mem::drop(compressor_params);\n\n}\n\n\n", "file_path": "basis-universal/src/encoding/encoding_tests.rs", "rank": 24, "score": 72269.46626354601 }, { "content": "#[test]\n\nfn test_compressor_params_smoketest_bindings() {\n\n let mut compressor_params = CompressorParams::new();\n\n\n\n // Call every parameter just to smoketest the bindings\n\n compressor_params.source_image_mut(5);\n\n compressor_params.resize_source_image_list(8);\n\n compressor_params.clear_source_image_list();\n\n compressor_params.set_print_status_to_stdout(false);\n\n compressor_params.set_etc1s_quality_level(crate::ETC1S_QUALITY_DEFAULT);\n\n compressor_params.set_uastc_quality_level(crate::UASTC_QUALITY_DEFAULT);\n\n compressor_params.set_use_global_codebook(true);\n\n compressor_params.set_auto_use_global_codebook(true);\n\n compressor_params.set_basis_format(BasisTextureFormat::UASTC4x4);\n\n compressor_params.set_generate_mipmaps(true);\n\n\n\n compressor_params.reset();\n\n}\n\n\n", "file_path": "basis-universal/src/encoding/encoding_tests.rs", "rank": 25, "score": 70819.11975111437 }, { "content": "/// The underlying C++ library requires that transcoder_init() has been called before a .basis file\n\n/// can be encoded. This function allows a user to do this early in the application explicitly. It\n\n/// is protected by a lock and AtomicBool flag so it is safe and cheap to call multiple times, and\n\n/// correctly handles multiple threads trying to initialize at the same time.\n\npub fn transcoder_init() {\n\n unsafe {\n\n // Early out if it has been initialized\n\n if !TRANSCODER_INIT_CALLED.load(Ordering::Acquire) {\n\n // Lock and check again to ensure that exactly one thread runs the init code and that\n\n // all other threads wait for it to complete and don't re-run it.\n\n let lock = TRANSCODER_INIT_LOCK.lock().unwrap();\n\n if !TRANSCODER_INIT_CALLED.load(Ordering::Acquire) {\n\n // Run the init code\n\n sys::basisu_encoder_init();\n\n TRANSCODER_INIT_CALLED.store(true, Ordering::Release);\n\n }\n\n std::mem::drop(lock);\n\n }\n\n }\n\n}\n", "file_path": "basis-universal/src/transcoding/mod.rs", "rank": 26, "score": 69088.61711612104 }, { "content": "fn benchmark_transcode(\n\n image_data: &DynamicImage,\n\n channel_count: u8,\n\n basis_texture_format: BasisTextureFormat,\n\n quality: u32,\n\n rdo_scalar: Option<f32>,\n\n compressor_thread_count: u32,\n\n) {\n\n let mut compressor_params = CompressorParams::new();\n\n compressor_params.set_generate_mipmaps(false);\n\n compressor_params.set_basis_format(basis_texture_format);\n\n compressor_params.set_rdo_uastc(rdo_scalar);\n\n\n\n match basis_texture_format {\n\n BasisTextureFormat::ETC1S => compressor_params.set_etc1s_quality_level(quality),\n\n BasisTextureFormat::UASTC4x4 => compressor_params.set_uastc_quality_level(quality),\n\n }\n\n\n\n compressor_params.set_print_status_to_stdout(false);\n\n\n", "file_path": "basis-universal/examples/benchmark.rs", "rank": 27, "score": 67950.68035784068 }, { "content": "#[test]\n\nfn bindgen_test_layout_Compressor() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Compressor>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(Compressor))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Compressor>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Compressor))\n\n );\n\n}\n\nextern \"C\" {\n\n pub fn compressor_new(num_threads: ::std::os::raw::c_int) -> *mut Compressor;\n\n}\n\nextern \"C\" {\n\n pub fn compressor_delete(compressor: *mut Compressor);\n\n}\n\nextern \"C\" {\n\n pub fn compressor_init(\n", "file_path": "basis-universal-sys/src/encoding_bindings.rs", "rank": 28, "score": 63567.77867781425 }, { "content": "#[test]\n\nfn bindgen_test_layout_CompressorParams() {\n\n assert_eq!(\n\n ::std::mem::size_of::<CompressorParams>(),\n\n 8usize,\n\n concat!(\"Size of: \", stringify!(CompressorParams))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<CompressorParams>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(CompressorParams))\n\n );\n\n}\n\nextern \"C\" {\n\n pub fn compressor_params_new() -> *mut CompressorParams;\n\n}\n\nextern \"C\" {\n\n pub fn compressor_params_delete(params: *mut CompressorParams);\n\n}\n\nextern \"C\" {\n\n pub fn compressor_params_clear(params: *mut CompressorParams);\n", "file_path": "basis-universal-sys/src/encoding_bindings.rs", "rank": 29, "score": 62061.05911449065 }, { "content": "#[test]\n\nfn bindgen_test_layout_PixelData() {\n\n assert_eq!(\n\n ::std::mem::size_of::<PixelData>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(PixelData))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<PixelData>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(PixelData))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<PixelData>())).pData as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(PixelData),\n\n \"::\",\n\n stringify!(pData)\n\n )\n", "file_path": "basis-universal-sys/src/encoding_bindings.rs", "rank": 30, "score": 62061.05911449065 }, { "content": "#[test]\n\nfn bindgen_test_layout_basisu_image() {\n\n assert_eq!(\n\n ::std::mem::size_of::<basisu_image>(),\n\n 40usize,\n\n concat!(\"Size of: \", stringify!(basisu_image))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<basisu_image>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(basisu_image))\n\n );\n\n}\n\npub const basisu_TOTAL_PACK_UASTC_LEVELS: u32 = 5;\n\npub const basisu_BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION: u32 = 16384;\n\npub const basisu_BASISU_DEFAULT_ENDPOINT_RDO_THRESH: f32 = 1.5;\n\npub const basisu_BASISU_DEFAULT_SELECTOR_RDO_THRESH: f32 = 1.25;\n\npub const basisu_BASISU_DEFAULT_QUALITY: ::std::os::raw::c_int = 128;\n\npub const basisu_BASISU_DEFAULT_HYBRID_SEL_CB_QUALITY_THRESH: f32 = 2.0;\n\npub const basisu_BASISU_MAX_IMAGE_DIMENSION: u32 = 16384;\n\npub const basisu_BASISU_QUALITY_MIN: u32 = 1;\n", "file_path": "basis-universal-sys/src/encoding_bindings.rs", "rank": 31, "score": 62061.05911449065 }, { "content": "#[test]\n\nfn bindgen_test_layout_CompressorBasisFile() {\n\n assert_eq!(\n\n ::std::mem::size_of::<CompressorBasisFile>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(CompressorBasisFile))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<CompressorBasisFile>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(CompressorBasisFile))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<CompressorBasisFile>())).pData as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(CompressorBasisFile),\n\n \"::\",\n\n stringify!(pData)\n\n )\n", "file_path": "basis-universal-sys/src/encoding_bindings.rs", "rank": 36, "score": 60643.88845683464 }, { "content": "fn main() {\n\n // Compile this separately as c code\n\n build_with_common_settings()\n\n .file(\"vendor/basis_universal/encoder/apg_bmp.c\")\n\n .compile(\"basisuniversalc\");\n\n\n\n build_with_common_settings()\n\n .cpp(true)\n\n .flag_if_supported(\"--std=c++11\")\n\n .file(\"vendor/basis_universal/encoder/basisu_astc_decomp.cpp\")\n\n .file(\"vendor/basis_universal/encoder/basisu_backend.cpp\")\n\n .file(\"vendor/basis_universal/encoder/basisu_basis_file.cpp\")\n\n .file(\"vendor/basis_universal/encoder/basisu_bc7enc.cpp\")\n\n .file(\"vendor/basis_universal/encoder/basisu_comp.cpp\")\n\n .file(\"vendor/basis_universal/encoder/basisu_enc.cpp\")\n\n .file(\"vendor/basis_universal/encoder/basisu_etc.cpp\")\n\n .file(\"vendor/basis_universal/encoder/basisu_frontend.cpp\")\n\n .file(\"vendor/basis_universal/encoder/basisu_global_selector_palette_helpers.cpp\")\n\n .file(\"vendor/basis_universal/encoder/basisu_gpu_texture.cpp\")\n\n .file(\"vendor/basis_universal/encoder/basisu_kernels_sse.cpp\")\n", "file_path": "basis-universal-sys/build.rs", "rank": 37, "score": 43564.08734353841 }, { "content": "fn benchmark_encode(\n\n image_data: &DynamicImage,\n\n channel_count: u8,\n\n basis_texture_format: BasisTextureFormat,\n\n quality: u32,\n\n rdo_scalar: Option<f32>,\n\n compressor_thread_count: u32,\n\n) {\n\n let mut compressor_params = CompressorParams::new();\n\n compressor_params.set_generate_mipmaps(false);\n\n compressor_params.set_basis_format(basis_texture_format);\n\n compressor_params.set_rdo_uastc(rdo_scalar);\n\n\n\n match basis_texture_format {\n\n BasisTextureFormat::ETC1S => compressor_params.set_etc1s_quality_level(quality),\n\n BasisTextureFormat::UASTC4x4 => compressor_params.set_uastc_quality_level(quality),\n\n }\n\n\n\n compressor_params.set_print_status_to_stdout(false);\n\n\n", "file_path": "basis-universal/examples/benchmark.rs", "rank": 38, "score": 42508.20420585839 }, { "content": "// This example:\n\n// - Loads a PNG file\n\n// - Compresses it to basis-universal using UASTC basis format\n\n// - Transcodes the compresses basis format to ASTC_4x4_RGBA and RGBA32\n\npub fn main() {\n\n //\n\n // Read the PNG file from disk\n\n //\n\n let png_file = include_bytes!(\"../test_assets/rust-logo-256x256.png\");\n\n\n\n let t0 = std::time::Instant::now();\n\n let image_data =\n\n image::load_from_memory_with_format(png_file, image::ImageFormat::Png).unwrap();\n\n let t1 = std::time::Instant::now();\n\n\n\n println!(\n\n \"Using PNG file as source, decoded {} bytes in {} ms\",\n\n png_file.len(),\n\n (t1 - t0).as_secs_f64() * 1000.0\n\n );\n\n\n\n // We need to know how many color channels are in the image\n\n use image::ColorType;\n\n let channel_count = match &image_data.color() {\n", "file_path": "basis-universal/examples/example.rs", "rank": 39, "score": 39560.5220390173 }, { "content": "pub fn main() {\n\n //\n\n // Read the PNG file from disk\n\n //\n\n let source_file = include_bytes!(\"../test_assets/rust-logo-256x256.png\");\n\n let source_file_format = image::ImageFormat::Png;\n\n\n\n let t0 = std::time::Instant::now();\n\n let image_data = image::load_from_memory_with_format(source_file, source_file_format).unwrap();\n\n let t1 = std::time::Instant::now();\n\n\n\n let source_file_size = source_file.len();\n\n let source_file_decode_time = (t1 - t0).as_secs_f64() * 1000.0;\n\n let uncompressed_memory_size = image_data.as_bytes().len();\n\n\n\n println!(\n\n \"Using {:?} file as source, decoded {} bytes in {} ms\",\n\n source_file_format, source_file_size, source_file_decode_time\n\n );\n\n\n", "file_path": "basis-universal/examples/benchmark.rs", "rank": 40, "score": 39554.562250245566 }, { "content": "/// The underlying C++ library requires that encoder_init() has been called before a .basis file can\n\n/// be encoded. This function allows a user to do this early in the application explicitly. It is\n\n/// protected by a lock and AtomicBool flag so it is safe and cheap to call multiple times, and\n\n/// correctly handles multiple threads trying to initialize at the same time.\n\npub fn encoder_init() {\n\n unsafe {\n\n // Early out if it has been initialized\n\n if !ENCODER_INIT_CALLED.load(Ordering::Acquire) {\n\n // Lock and check again to ensure that exactly one thread runs the init code and that\n\n // all other threads wait for it to complete and don't re-run it.\n\n let lock = ENCODER_INIT_LOCK.lock().unwrap();\n\n if !ENCODER_INIT_CALLED.load(Ordering::Acquire) {\n\n // Run the init code\n\n sys::basisu_encoder_init();\n\n ENCODER_INIT_CALLED.store(true, Ordering::Release);\n\n }\n\n std::mem::drop(lock);\n\n }\n\n }\n\n}\n", "file_path": "basis-universal/src/encoding/mod.rs", "rank": 41, "score": 37656.455880691814 }, { "content": "// args from the basis cmake file\n\nfn build_with_common_settings() -> cc::Build {\n\n let mut build = cc::Build::new();\n\n build\n\n .flag_if_supported(\"-fvisibility=hidden\")\n\n .flag_if_supported(\"-fno-strict-aliasing\")\n\n .flag_if_supported(\"-Wall\")\n\n .flag_if_supported(\"-Wextra\")\n\n .flag_if_supported(\"-Wno-unused-local-typedefs\")\n\n .flag_if_supported(\"-Wno-unused-value\")\n\n .flag_if_supported(\"-Wno-unused-parameter\")\n\n .flag_if_supported(\"-Wno-unused-variable\");\n\n\n\n build\n\n}\n\n\n", "file_path": "basis-universal-sys/build.rs", "rank": 42, "score": 34853.97207869427 }, { "content": " .unwrap_or_else(DecodeFlags::empty);\n\n let output_row_pitch_in_blocks_or_pixels = transcode_parameters\n\n .output_row_pitch_in_blocks_or_pixels\n\n .unwrap_or(0);\n\n let output_rows_in_pixels = transcode_parameters.output_rows_in_pixels.unwrap_or(0);\n\n let transcoder_state = std::ptr::null_mut();\n\n\n\n //\n\n // Transcode\n\n //\n\n let mut output = vec![0_u8; required_buffer_bytes];\n\n let success = unsafe {\n\n sys::transcoder_transcode_image_level(\n\n self.0,\n\n data.as_ptr() as _,\n\n data.len() as u32,\n\n image_index,\n\n level_index,\n\n output.as_mut_ptr() as _,\n\n output.len() as u32,\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 43, "score": 33699.65373546601 }, { "content": "use super::*;\n\nuse crate::UserData;\n\nuse basis_universal_sys as sys;\n\n\n\n/// A transcoder that can convert compressed basis-universal data to compressed GPU formats or raw\n\n/// color data\n\npub struct Transcoder(*mut sys::Transcoder);\n\n\n\n/// Lightweight description of a mip level on a single image within basis data\n\n#[derive(Default, Debug, Copy, Clone)]\n\npub struct ImageLevelDescription {\n\n pub original_width: u32,\n\n pub original_height: u32,\n\n pub block_count: u32,\n\n}\n\n\n\n/// Info for an image within basis data\n\npub type ImageInfo = sys::basist_basisu_image_info;\n\n\n\n/// Info for a mip level of a single image within basis data\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 44, "score": 33696.71272553632 }, { "content": " sys::transcoder_get_tex_format(self.0, data.as_ptr() as _, data.len() as u32).into()\n\n }\n\n }\n\n\n\n pub fn user_data(\n\n &self,\n\n data: &[u8],\n\n ) -> Result<UserData, ()> {\n\n let mut userdata = UserData::default();\n\n let result = unsafe {\n\n sys::transcoder_get_userdata(\n\n self.0,\n\n data.as_ptr() as _,\n\n data.len() as u32,\n\n &mut userdata.userdata0,\n\n &mut userdata.userdata1,\n\n )\n\n };\n\n\n\n if result {\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 45, "score": 33696.2713090927 }, { "content": " }\n\n\n\n /// prepare_transcoding() must be called before calling transcode_slice() or transcode_image_level().\n\n /// This is `start_transcoding` in the original library\n\n /// For ETC1S files, this call decompresses the selector/endpoint codebooks, so ideally you would only call this once per .basis file (not each image/mipmap level).\n\n pub fn prepare_transcoding(\n\n &mut self,\n\n data: &[u8],\n\n ) -> Result<(), ()> {\n\n transcoder_init();\n\n unsafe {\n\n if sys::transcoder_start_transcoding(self.0, data.as_ptr() as _, data.len() as u32) {\n\n Ok(())\n\n } else {\n\n Err(())\n\n }\n\n }\n\n }\n\n\n\n /// Parallel with `prepare_transcoding()`, named `stop_transcoding` in the original library\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 46, "score": 33695.49183031932 }, { "content": " }\n\n\n\n /// Get a description of the basis file and low-level information about each slice.\n\n pub fn file_info(\n\n &self,\n\n data: &[u8],\n\n ) -> Option<FileInfo> {\n\n let mut file_info = unsafe { std::mem::zeroed::<FileInfo>() };\n\n unsafe {\n\n if sys::transcoder_get_file_info(\n\n self.0,\n\n data.as_ptr() as _,\n\n data.len() as u32,\n\n &mut file_info,\n\n ) {\n\n Some(file_info)\n\n } else {\n\n None\n\n }\n\n }\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 47, "score": 33694.92746855784 }, { "content": " &self,\n\n data: &[u8],\n\n image_index: u32,\n\n level_index: u32,\n\n ) -> Option<ImageLevelInfo> {\n\n let mut image_level_info = unsafe { std::mem::zeroed::<ImageLevelInfo>() };\n\n unsafe {\n\n if sys::transcoder_get_image_level_info(\n\n self.0,\n\n data.as_ptr() as _,\n\n data.len() as u32,\n\n &mut image_level_info,\n\n image_index,\n\n level_index,\n\n ) {\n\n Some(image_level_info)\n\n } else {\n\n None\n\n }\n\n }\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 48, "score": 33694.615126906196 }, { "content": " pub fn end_transcoding(&mut self) {\n\n unsafe {\n\n let result = sys::transcoder_stop_transcoding(self.0);\n\n // I think this function is actually infallible, so don't return a result\n\n debug_assert!(result);\n\n }\n\n }\n\n\n\n /// Returns true if prepare_transcoding() has been called.\n\n pub fn is_prepared_to_transcode(&self) -> bool {\n\n unsafe { sys::transcoder_get_ready_to_transcode(self.0) }\n\n }\n\n\n\n /// transcode_image_level() decodes a single mipmap level from the .basis file to any of the supported output texture formats.\n\n /// It'll first find the slice(s) to transcode, then call transcode_slice() one or two times to decode both the color and alpha texture data (or RG texture data from two slices for BC5).\n\n /// If the .basis file doesn't have alpha slices, the output alpha blocks will be set to fully opaque (all 255's).\n\n /// Currently, to decode to PVRTC1 the basis texture's dimensions in pixels must be a power of 2, due to PVRTC1 format requirements.\n\n /// output_blocks_buf_size_in_blocks_or_pixels should be at least the image level's total_blocks (num_blocks_x * num_blocks_y), or the total number of output pixels if fmt==cTFRGBA32.\n\n /// output_row_pitch_in_blocks_or_pixels: Number of blocks or pixels per row. If 0, the transcoder uses the slice's num_blocks_x or orig_width (NOT num_blocks_x * 4). Ignored for PVRTC1 (due to texture swizzling).\n\n /// output_rows_in_pixels: Ignored unless fmt is cRGBA32. The total number of output rows in the output buffer. If 0, the transcoder assumes the slice's orig_height (NOT num_blocks_y * 4).\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 49, "score": 33694.33207053315 }, { "content": " unsafe {\n\n sys::transcoder_get_total_image_levels(\n\n self.0,\n\n data.as_ptr() as _,\n\n data.len() as u32,\n\n image_index,\n\n )\n\n }\n\n }\n\n\n\n /// Returns basic information about an image. Note that orig_width/orig_height may not be a multiple of 4.\n\n pub fn image_level_description(\n\n &self,\n\n data: &[u8],\n\n image_index: u32,\n\n level_index: u32,\n\n ) -> Option<ImageLevelDescription> {\n\n let mut description = ImageLevelDescription::default();\n\n unsafe {\n\n if sys::transcoder_get_image_level_desc(\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 50, "score": 33694.21765179925 }, { "content": " /// Notes:\n\n /// - basisu_transcoder_init() must have been called first to initialize the transcoder lookup tables before calling this function.\n\n /// - This method assumes the output texture buffer is readable. In some cases to handle alpha, the transcoder will write temporary data to the output texture in\n\n /// a first pass, which will be read in a second pass.\n\n pub fn transcode_image_level(\n\n &self,\n\n data: &[u8],\n\n transcode_format: TranscoderTextureFormat,\n\n transcode_parameters: TranscodeParameters,\n\n ) -> Result<Vec<u8>, TranscodeError> {\n\n let image_index = transcode_parameters.image_index;\n\n let level_index = transcode_parameters.level_index;\n\n\n\n //\n\n // Check that the transcode format is supported for the stored texture's basis format\n\n //\n\n let basis_format = self.basis_texture_format(data);\n\n if !basis_format.can_transcode_to_format(transcode_format) {\n\n return Err(TranscodeError::TranscodeFormatNotSupported);\n\n }\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 51, "score": 33693.92439270975 }, { "content": " self.0,\n\n data.as_ptr() as _,\n\n data.len() as u32,\n\n image_index,\n\n level_index,\n\n &mut description.original_width,\n\n &mut description.original_height,\n\n &mut description.block_count,\n\n ) {\n\n Some(description)\n\n } else {\n\n None\n\n }\n\n }\n\n }\n\n\n\n /// Returns information about the specified image.\n\n pub fn image_info(\n\n &self,\n\n data: &[u8],\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 52, "score": 33693.53702930616 }, { "content": " // // transcode_slice() decodes a single slice from the .basis file. It's a low-level API - most likely you want to use transcode_image_level().\n\n // // This is a low-level API, and will be needed to be called multiple times to decode some texture formats (like BC3, BC5, or ETC2).\n\n // // output_blocks_buf_size_in_blocks_or_pixels is just used for verification to make sure the output buffer is large enough.\n\n // // output_blocks_buf_size_in_blocks_or_pixels should be at least the image level's total_blocks (num_blocks_x * num_blocks_y), or the total number of output pixels if fmt==cTFRGBA32.\n\n // // output_block_stride_in_bytes: Number of bytes between each output block.\n\n // // output_row_pitch_in_blocks_or_pixels: Number of blocks or pixels per row. If 0, the transcoder uses the slice's num_blocks_x or orig_width (NOT num_blocks_x * 4). Ignored for PVRTC1 (due to texture swizzling).\n\n // // output_rows_in_pixels: Ignored unless fmt is cRGBA32. The total number of output rows in the output buffer. If 0, the transcoder assumes the slice's orig_height (NOT num_blocks_y * 4).\n\n // // Notes:\n\n // // - basisu_transcoder_init() must have been called first to initialize the transcoder lookup tables before calling this function.\n\n // bool transcode_slice(const void *pData, uint32_t data_size, uint32_t slice_index,\n\n // void *pOutput_blocks, uint32_t output_blocks_buf_size_in_blocks_or_pixels,\n\n // block_format fmt, uint32_t output_block_stride_in_bytes, uint32_t decode_flags = 0, uint32_t output_row_pitch_in_blocks_or_pixels = 0, basisu_transcoder_state * pState = nullptr, void* pAlpha_blocks = nullptr,\n\n // uint32_t output_rows_in_pixels = 0, int channel0 = -1, int channel1 = -1) const;\n\n //\n\n // static void write_opaque_alpha_blocks(\n\n // uint32_t num_blocks_x, uint32_t num_blocks_y,\n\n // void* pOutput_blocks, block_format fmt,\n\n // uint32_t block_stride_in_bytes, uint32_t output_row_pitch_in_blocks_or_pixels);\n\n}\n\n\n\nimpl Drop for Transcoder {\n\n fn drop(&mut self) {\n\n unsafe {\n\n sys::transcoder_delete(self.0);\n\n }\n\n }\n\n}\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 53, "score": 33693.246850465264 }, { "content": " ) -> bool {\n\n unsafe { sys::transcoder_validate_header(self.0, data.as_ptr() as _, data.len() as u32) }\n\n }\n\n\n\n /// The type of texture represented by the basis data\n\n pub fn basis_texture_type(\n\n &self,\n\n data: &[u8],\n\n ) -> BasisTextureType {\n\n unsafe {\n\n sys::transcoder_get_texture_type(self.0, data.as_ptr() as _, data.len() as u32).into()\n\n }\n\n }\n\n\n\n /// The basis texture format of the basis data\n\n pub fn basis_texture_format(\n\n &self,\n\n data: &[u8],\n\n ) -> BasisTextureFormat {\n\n unsafe {\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 54, "score": 33693.21482916939 }, { "content": "\n\n //\n\n // Determine required size for the buffer\n\n //\n\n let description = self\n\n .image_level_description(data, image_index, level_index)\n\n .ok_or(TranscodeError::ImageLevelNotFound)?;\n\n let required_buffer_bytes = transcode_format.calculate_minimum_output_buffer_bytes(\n\n description.original_width,\n\n description.original_height,\n\n description.block_count,\n\n transcode_parameters.output_row_pitch_in_blocks_or_pixels,\n\n transcode_parameters.output_rows_in_pixels,\n\n ) as usize;\n\n\n\n //\n\n // unwrap_or() the optional parameters\n\n //\n\n let decode_flags = transcode_parameters\n\n .decode_flags\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 55, "score": 33692.984999120294 }, { "content": " Ok(userdata)\n\n } else {\n\n Err(())\n\n }\n\n }\n\n\n\n /// Number of images in the basis data\n\n pub fn image_count(\n\n &self,\n\n data: &[u8],\n\n ) -> u32 {\n\n unsafe { sys::transcoder_get_total_images(self.0, data.as_ptr() as _, data.len() as u32) }\n\n }\n\n\n\n /// Number of mipmap levels for the specified image in the basis data\n\n pub fn image_level_count(\n\n &self,\n\n data: &[u8],\n\n image_index: u32,\n\n ) -> u32 {\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 56, "score": 33692.734904717494 }, { "content": " /// Validates the .basis file. This computes a crc16 over the entire file, so it's slow.\n\n pub fn validate_file_checksums(\n\n &self,\n\n data: &[u8],\n\n full_validation: bool,\n\n ) -> bool {\n\n unsafe {\n\n sys::transcoder_validate_file_checksums(\n\n self.0,\n\n data.as_ptr() as _,\n\n data.len() as u32,\n\n full_validation,\n\n )\n\n }\n\n }\n\n\n\n /// Quick header validation - no crc16 checks.\n\n pub fn validate_header(\n\n &self,\n\n data: &[u8],\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 57, "score": 33692.734904717494 }, { "content": " image_index: u32,\n\n ) -> Option<ImageInfo> {\n\n let mut image_info = unsafe { std::mem::zeroed::<ImageInfo>() };\n\n unsafe {\n\n if sys::transcoder_get_image_info(\n\n self.0,\n\n data.as_ptr() as _,\n\n data.len() as u32,\n\n &mut image_info,\n\n image_index,\n\n ) {\n\n Some(image_info)\n\n } else {\n\n None\n\n }\n\n }\n\n }\n\n\n\n /// Returns information about the specified image's mipmap level.\n\n pub fn image_level_info(\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 58, "score": 33692.4693380828 }, { "content": "/// Error result from trying to transcode an image\n\n#[derive(Debug, Copy, Clone)]\n\npub enum TranscodeError {\n\n TranscodeFormatNotSupported,\n\n ImageLevelNotFound,\n\n TranscodeFailed,\n\n}\n\n\n\nimpl Default for Transcoder {\n\n fn default() -> Self {\n\n Self::new()\n\n }\n\n}\n\n\n\nimpl Transcoder {\n\n /// Create a transcoder\n\n pub fn new() -> Transcoder {\n\n unsafe { Transcoder(sys::transcoder_new()) }\n\n }\n\n\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 59, "score": 33691.61664086189 }, { "content": "pub type ImageLevelInfo = sys::basist_basisu_image_level_info;\n\n\n\n/// Info for the complete basis file\n\npub type FileInfo = sys::FileInfo;\n\n\n\n/// Extra parameters for transcoding an image\n\n#[derive(Default, Debug, Clone)]\n\npub struct TranscodeParameters {\n\n /// The image to transcode\n\n pub image_index: u32,\n\n /// The mip level of the image to transcode\n\n pub level_index: u32,\n\n /// Optional flags can affect transcoding in various ways\n\n pub decode_flags: Option<DecodeFlags>,\n\n /// Optional override for row pitch\n\n pub output_row_pitch_in_blocks_or_pixels: Option<u32>,\n\n /// Optional override for number of rows to transcode\n\n pub output_rows_in_pixels: Option<u32>,\n\n}\n\n\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 60, "score": 33690.87823656632 }, { "content": " transcode_format.into(),\n\n decode_flags.bits(),\n\n output_row_pitch_in_blocks_or_pixels,\n\n transcoder_state,\n\n output_rows_in_pixels,\n\n )\n\n };\n\n\n\n if success {\n\n Ok(output)\n\n } else {\n\n Err(TranscodeError::TranscodeFailed)\n\n }\n\n }\n\n\n\n // Not implemented\n\n //\n\n // // Finds the basis slice corresponding to the specified image/level/alpha params, or -1 if the slice can't be found.\n\n // int find_slice(const void *pData, uint32_t data_size, uint32_t image_index, uint32_t level_index, bool alpha_data) const;\n\n //\n", "file_path": "basis-universal/src/transcoding/transcoder.rs", "rank": 61, "score": 33690.82397611567 }, { "content": "use super::*;\n\nuse crate::BasisTextureFormat;\n\nuse image::GenericImageView;\n\n\n\n#[test]\n", "file_path": "basis-universal/src/encoding/encoding_tests.rs", "rank": 62, "score": 28183.345659396888 }, { "content": " let mut compressor = Compressor::default();\n\n unsafe {\n\n compressor.init(&compressor_params);\n\n }\n\n // Drop explicitly here to verify that borrowing rules allow this and that this doesn't cause a crash\n\n std::mem::drop(compressor_params);\n\n\n\n //\n\n // Do the compression\n\n //\n\n unsafe {\n\n compressor.process().unwrap();\n\n }\n\n\n\n // By default the test shouldn't write to disk, but this is a quick way to put it on disk to\n\n // check that it works with basisu\n\n let _basis_file = compressor.basis_file();\n\n //std::fs::write(\"test_assets/test_encode_image.basis\", basis_file).unwrap();\n\n\n\n std::mem::drop(compressor);\n\n}\n", "file_path": "basis-universal/src/encoding/encoding_tests.rs", "rank": 63, "score": 28180.579345896873 }, { "content": " _ => unimplemented!(),\n\n };\n\n\n\n let mut compressor_params = CompressorParams::new();\n\n compressor_params.set_generate_mipmaps(true);\n\n\n\n //\n\n // Set up the source image in the params\n\n //\n\n let mut compressor_image = compressor_params.source_image_mut(0);\n\n compressor_image.init(\n\n image_data.as_bytes(),\n\n image_data.width(),\n\n image_data.height(),\n\n channel_count,\n\n );\n\n\n\n //\n\n // Create the compressor\n\n //\n", "file_path": "basis-universal/src/encoding/encoding_tests.rs", "rank": 64, "score": 28178.402161532602 }, { "content": "use basis_universal_sys as sys;\n\nuse std::sync::atomic::{AtomicBool, Ordering};\n\nuse std::sync::Mutex;\n\n\n\nmod enums;\n\npub use enums::*;\n\n\n\nmod transcoder;\n\npub use transcoder::*;\n\n\n\n#[cfg(test)]\n\nmod transcoding_tests;\n\n\n\nstatic TRANSCODER_INIT_CALLED: AtomicBool = AtomicBool::new(false);\n\nlazy_static::lazy_static! {\n\n static ref TRANSCODER_INIT_LOCK: Mutex<()> = Mutex::default();\n\n}\n\n\n\n/// The underlying C++ library requires that transcoder_init() has been called before a .basis file\n\n/// can be encoded. This function allows a user to do this early in the application explicitly. It\n\n/// is protected by a lock and AtomicBool flag so it is safe and cheap to call multiple times, and\n\n/// correctly handles multiple threads trying to initialize at the same time.\n", "file_path": "basis-universal/src/transcoding/mod.rs", "rank": 65, "score": 26406.983489372065 }, { "content": "}\n\n\n\nimpl From<sys::basist_transcoder_texture_format> for TranscoderTextureFormat {\n\n fn from(value: sys::basist_transcoder_texture_format) -> Self {\n\n unsafe { std::mem::transmute(value as i32) }\n\n }\n\n}\n\n\n\nimpl TranscoderTextureFormat {\n\n /// For compressed texture formats, this returns the # of bytes per block. For uncompressed, it returns the # of bytes per pixel.\n\n /// NOTE: Previously, this function was called basis_get_bytes_per_block(), and it always returned 16*bytes_per_pixel for uncompressed formats which was confusing.\n\n pub fn bytes_per_block_or_pixel(self) -> u32 {\n\n unsafe { sys::basis_get_bytes_per_block_or_pixel(self.into()) }\n\n }\n\n\n\n /// Returns format's name in ASCII\n\n pub fn format_name(self) -> &'static str {\n\n unsafe {\n\n let value = sys::basis_get_format_name(self.into());\n\n CStr::from_ptr(value).to_str().unwrap()\n", "file_path": "basis-universal/src/transcoding/enums.rs", "rank": 66, "score": 26405.072952378167 }, { "content": " /// Opaque, RGB or alpha if cDecodeFlagsTranscodeAlphaDataToOpaqueFormats flag is specified. ATI ATC (GL_ATC_RGB_AMD)\n\n ATC_RGB = sys::basist_transcoder_texture_format_cTFATC_RGB,\n\n /// Opaque+alpha, alpha channel will be opaque for opaque .basis files. ATI ATC (GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD)\n\n ATC_RGBA = sys::basist_transcoder_texture_format_cTFATC_RGBA,\n\n\n\n //\n\n // FXT1 (desktop, Intel devices, this is a super obscure format)\n\n //\n\n /// Opaque only, uses exclusively CC_MIXED blocks. Notable for having a 8x4 block size. GL_3DFX_texture_compression_FXT1 is supported on Intel integrated GPU's (such as HD 630).\n\n /// Punch-through alpha is relatively easy to support, but full alpha is harder. This format is only here for completeness so opaque-only is fine for now.\n\n /// See the BASISU_USE_ORIGINAL_3DFX_FXT1_ENCODING macro in basisu_transcoder_internal.h.\n\n FXT1_RGB = sys::basist_transcoder_texture_format_cTFFXT1_RGB,\n\n\n\n /// Opaque-only, almost BC1 quality, much faster to transcode and supports arbitrary texture dimensions (unlike PVRTC1 RGB).\n\n PVRTC2_4_RGB = sys::basist_transcoder_texture_format_cTFPVRTC2_4_RGB,\n\n /// Opaque+alpha, slower to encode than cTFPVRTC2_4_RGB. Premultiplied alpha is highly recommended, otherwise the color channel can leak into the alpha channel on transparent blocks.\n\n PVRTC2_4_RGBA = sys::basist_transcoder_texture_format_cTFPVRTC2_4_RGBA,\n\n\n\n /// R only (ETC2 EAC R11 unsigned)\n\n ETC2_EAC_R11 = sys::basist_transcoder_texture_format_cTFETC2_EAC_R11,\n", "file_path": "basis-universal/src/transcoding/enums.rs", "rank": 67, "score": 26403.2748087156 }, { "content": " }\n\n }\n\n\n\n /// Returns true if the format supports an alpha channel.\n\n pub fn has_alpha(self) -> bool {\n\n unsafe { sys::basis_transcoder_format_has_alpha(self.into()) }\n\n }\n\n\n\n /// Returns true if the transcoder texture type is an uncompressed (raw pixel) format.\n\n pub fn is_compressed(self) -> bool {\n\n unsafe { !sys::basis_transcoder_format_is_uncompressed(self.into()) }\n\n }\n\n\n\n /// Returns the # of bytes per pixel for uncompressed formats, or 0 for block texture formats.\n\n pub fn uncompressed_bytes_per_pixel(self) -> u32 {\n\n unsafe { sys::basis_get_uncompressed_bytes_per_pixel(self.into()) }\n\n }\n\n\n\n /// Returns the block width for the specified texture format, which is currently either 4 or 8 for FXT1.\n\n pub fn block_width(self) -> u32 {\n", "file_path": "basis-universal/src/transcoding/enums.rs", "rank": 68, "score": 26403.095527129557 }, { "content": " /// RGB or RGBA, mode 5 for ETC1S, modes (1,2,3,5,6,7) for UASTC\n\n BC7_RGBA = sys::basist_transcoder_texture_format_cTFBC7_RGBA,\n\n\n\n //\n\n // PVRTC1 4bpp (mobile, PowerVR devices)\n\n //\n\n /// Opaque only, RGB or alpha if cDecodeFlagsTranscodeAlphaDataToOpaqueFormats flag is specified, nearly lowest quality of any texture format.\n\n PVRTC1_4_RGB = sys::basist_transcoder_texture_format_cTFPVRTC1_4_RGB,\n\n /// Opaque+alpha, most useful for simple opacity maps. If .basis file doesn't have alpha cTFPVRTC1_4_RGB will be used instead. Lowest quality of any supported texture format.\n\n PVRTC1_4_RGBA = sys::basist_transcoder_texture_format_cTFPVRTC1_4_RGBA,\n\n\n\n //\n\n // ASTC (mobile, Intel devices, hopefully all desktop GPU's one day)\n\n //\n\n /// Opaque+alpha, ASTC 4x4, alpha channel will be opaque for opaque .basis files. Transcoder uses RGB/RGBA/L/LA modes, void extent, and up to two ([0,47] and [0,255]) endpoint precisions.\n\n ASTC_4x4_RGBA = sys::basist_transcoder_texture_format_cTFASTC_4x4_RGBA,\n\n\n\n //\n\n // ATC (mobile, Adreno devices, this is a niche format)\n\n //\n", "file_path": "basis-universal/src/transcoding/enums.rs", "rank": 69, "score": 26403.06891653211 }, { "content": " }\n\n}\n\n\n\nimpl From<sys::basist_basis_tex_format> for BasisTextureFormat {\n\n fn from(value: sys::basist_basis_tex_format) -> Self {\n\n unsafe { std::mem::transmute(value as i32) }\n\n }\n\n}\n\n\n\nimpl BasisTextureFormat {\n\n /// Returns true if the specified format was enabled at compile time.\n\n pub fn can_transcode_to_format(\n\n self,\n\n transcoder_texture_format: TranscoderTextureFormat,\n\n ) -> bool {\n\n unsafe { sys::basis_is_format_supported(transcoder_texture_format.into(), self.into()) }\n\n }\n\n}\n\n\n\n/// The texture format to transcode basis-universal data into\n", "file_path": "basis-universal/src/transcoding/enums.rs", "rank": 70, "score": 26403.01537969915 }, { "content": " fn into(self) -> sys::basist_basis_texture_type {\n\n self as sys::basist_basis_texture_type\n\n }\n\n}\n\n\n\nimpl From<sys::basist_basis_texture_type> for BasisTextureType {\n\n fn from(value: sys::basist_basis_texture_type) -> Self {\n\n unsafe { std::mem::transmute(value as u32) }\n\n }\n\n}\n\n\n\nimpl BasisTextureType {\n\n /// Returns the texture type's name in ASCII.\n\n pub fn texture_type_name(self) -> &'static str {\n\n unsafe {\n\n let value = sys::basis_get_texture_type_name(self.into());\n\n CStr::from_ptr(value).to_str().unwrap()\n\n }\n\n }\n\n}\n", "file_path": "basis-universal/src/transcoding/enums.rs", "rank": 71, "score": 26402.666208559578 }, { "content": " unsafe { sys::basis_get_block_width(self.into()) }\n\n }\n\n\n\n /// Returns the block height for the specified texture format, which is currently always 4.\n\n pub fn block_height(self) -> u32 {\n\n unsafe { sys::basis_get_block_height(self.into()) }\n\n }\n\n\n\n /// Returns true if the specified format was enabled at compile time.\n\n pub fn can_transcode_from_format(\n\n self,\n\n basis_texture_format: BasisTextureFormat,\n\n ) -> bool {\n\n basis_texture_format.can_transcode_to_format(self)\n\n }\n\n\n\n /// Calculate the minimum output buffer required to store transcoded data in blocks for\n\n /// compressed formats and pixels for uncompressed formats\n\n pub fn calculate_minimum_output_buffer_blocks_or_pixels(\n\n self,\n", "file_path": "basis-universal/src/transcoding/enums.rs", "rank": 72, "score": 26402.169832481308 }, { "content": " original_width: u32,\n\n original_height: u32,\n\n total_slice_blocks: u32,\n\n output_row_pitch_in_blocks_or_pixels: Option<u32>,\n\n output_rows_in_pixels: Option<u32>,\n\n ) -> u32 {\n\n // Default of 0 is fine for these values\n\n let mut output_row_pitch_in_blocks_or_pixels =\n\n output_row_pitch_in_blocks_or_pixels.unwrap_or(0);\n\n let mut output_rows_in_pixels = output_rows_in_pixels.unwrap_or(0);\n\n\n\n // Derived from implementation of basis_validate_output_buffer_size\n\n let minimum_output_buffer_blocks_or_pixels = if !self.is_compressed() {\n\n // Assume the output buffer is orig_width by orig_height\n\n if output_row_pitch_in_blocks_or_pixels == 0 {\n\n output_row_pitch_in_blocks_or_pixels = original_width;\n\n }\n\n\n\n if output_rows_in_pixels == 0 {\n\n output_rows_in_pixels = original_height;\n", "file_path": "basis-universal/src/transcoding/enums.rs", "rank": 73, "score": 26402.086154188542 }, { "content": "\n\n /// Verify that the buffer size is large enough for the transcoded data\n\n pub fn validate_output_buffer_size(\n\n self,\n\n output_blocks_buf_size_in_blocks_or_pixels: u32,\n\n original_width: u32,\n\n original_height: u32,\n\n total_slice_blocks: u32,\n\n output_row_pitch_in_blocks_or_pixels: Option<u32>,\n\n output_rows_in_pixels: Option<u32>,\n\n ) -> bool {\n\n unsafe {\n\n sys::basis_validate_output_buffer_size(\n\n self.into(),\n\n output_blocks_buf_size_in_blocks_or_pixels,\n\n original_width,\n\n original_height,\n\n output_row_pitch_in_blocks_or_pixels.unwrap_or(0),\n\n output_rows_in_pixels.unwrap_or(0),\n\n total_slice_blocks,\n", "file_path": "basis-universal/src/transcoding/enums.rs", "rank": 74, "score": 26401.62820554749 }, { "content": " )\n\n }\n\n }\n\n}\n\n\n\nbitflags::bitflags! {\n\n /// Flags that affect transcoding\n\n pub struct DecodeFlags: u32 {\n\n /// PVRTC1: decode non-pow2 ETC1S texture level to the next larger power of 2 (not implemented yet, but we're going to support it). Ignored if the slice's dimensions are already a power of 2.\n\n const PVRTC_DECODE_TO_NEXT_POW_2 = sys::basist_basisu_decode_flags_cDecodeFlagsPVRTCDecodeToNextPow2;\n\n\n\n /// When decoding to an opaque texture format, if the basis file has alpha, decode the alpha slice instead of the color slice to the output texture format.\n\n /// This is primarily to allow decoding of textures with alpha to multiple ETC1 textures (one for color, another for alpha).\n\n const TRANSCODE_ALPHA_DATA_TO_OPAQUE_FORMATS = sys::basist_basisu_decode_flags_cDecodeFlagsTranscodeAlphaDataToOpaqueFormats;\n\n\n\n /// Forbid usage of BC1 3 color blocks (we don't support BC1 punchthrough alpha yet).\n\n /// This flag is used internally when decoding to BC3.\n\n const BC1_FORBID_THREE_COLOR_BLOCKS = sys::basist_basisu_decode_flags_cDecodeFlagsBC1ForbidThreeColorBlocks;\n\n\n\n /// The output buffer contains alpha endpoint/selector indices.\n\n /// Used internally when decoding formats like ASTC that require both color and alpha data to be available when transcoding to the output format.\n\n const OUTPUT_HAS_ALPHA_INDICES = sys::basist_basisu_decode_flags_cDecodeFlagsOutputHasAlphaIndices;\n\n\n\n const HIGH_QULITY = sys::basist_basisu_decode_flags_cDecodeFlagsHighQuality;\n\n }\n\n}\n", "file_path": "basis-universal/src/transcoding/enums.rs", "rank": 75, "score": 26401.453863577794 }, { "content": "#[allow(non_camel_case_types)]\n\n#[derive(Copy, Clone, Debug, PartialEq)]\n\n#[repr(i32)]\n\npub enum TranscoderTextureFormat {\n\n /// Opaque only, returns RGB or alpha data if cDecodeFlagsTranscodeAlphaDataToOpaqueFormats flag is specified\n\n ETC1_RGB = sys::basist_transcoder_texture_format_cTFETC1_RGB,\n\n /// Opaque+alpha, ETC2_EAC_A8 block followed by a ETC1 block, alpha channel will be opaque for opaque .basis files\n\n ETC2_RBG = sys::basist_transcoder_texture_format_cTFETC2_RGBA,\n\n\n\n //\n\n // BC1-5, BC7 (desktop, some mobile devices)\n\n //\n\n /// Opaque only, no punchthrough alpha support yet, transcodes alpha slice if cDecodeFlagsTranscodeAlphaDataToOpaqueFormats flag is specified\n\n BC1_RGB = sys::basist_transcoder_texture_format_cTFBC1_RGB,\n\n /// Opaque+alpha, BC4 followed by a BC1 block, alpha channel will be opaque for opaque .basis files\n\n BC3_RGBA = sys::basist_transcoder_texture_format_cTFBC3_RGBA,\n\n /// Red only, alpha slice is transcoded to output if cDecodeFlagsTranscodeAlphaDataToOpaqueFormats flag is specified\n\n BC4_R = sys::basist_transcoder_texture_format_cTFBC4_R,\n\n /// XY: Two BC4 blocks, X=R and Y=Alpha, .basis file should have alpha data (if not Y will be all 255's)\n\n BC5_RG = sys::basist_transcoder_texture_format_cTFBC5_RG,\n", "file_path": "basis-universal/src/transcoding/enums.rs", "rank": 76, "score": 26400.897482530298 }, { "content": " /// RG only (ETC2 EAC RG11 unsigned), R=opaque.r, G=alpha - for tangent space normal maps\n\n ETC2_EAC_RG11 = sys::basist_transcoder_texture_format_cTFETC2_EAC_RG11,\n\n\n\n //\n\n // Uncompressed (raw pixel) formats\n\n //\n\n /// 32bpp RGBA image stored in raster (not block) order in memory, R is first byte, A is last byte.\n\n RGBA32 = sys::basist_transcoder_texture_format_cTFRGBA32,\n\n /// 16bpp RGB image stored in raster (not block) order in memory, R at bit position 11\n\n RGB565 = sys::basist_transcoder_texture_format_cTFRGB565,\n\n /// 16bpp RGB image stored in raster (not block) order in memory, R at bit position 0\n\n BGR565 = sys::basist_transcoder_texture_format_cTFBGR565,\n\n /// 16bpp RGBA image stored in raster (not block) order in memory, R at bit position 12, A at bit position 0\n\n RGBA4444 = sys::basist_transcoder_texture_format_cTFRGBA4444,\n\n}\n\n\n\nimpl Into<sys::basist_transcoder_texture_format> for TranscoderTextureFormat {\n\n fn into(self) -> sys::basist_transcoder_texture_format {\n\n self as sys::basist_transcoder_texture_format\n\n }\n", "file_path": "basis-universal/src/transcoding/enums.rs", "rank": 77, "score": 26400.868617758097 }, { "content": "use basis_universal_sys as sys;\n\nuse std::ffi::CStr;\n\n\n\n/// The type of data stored\n\n#[derive(Copy, Clone, Debug, PartialEq)]\n\n#[repr(u32)]\n\npub enum BasisTextureType {\n\n /// An arbitrary array of 2D RGB or RGBA images with optional mipmaps, array size = # images, each image may have a different resolution and # of mipmap levels\n\n TextureType2D = sys::basist_basis_texture_type_cBASISTexType2D,\n\n /// An array of 2D RGB or RGBA images with optional mipmaps, array size = # images, each image has the same resolution and mipmap levels\n\n TextureType2DArray = sys::basist_basis_texture_type_cBASISTexType2DArray,\n\n /// an array of cubemap levels, total # of images must be divisable by 6, in X+, X-, Y+, Y-, Z+, Z- order, with optional mipmaps\n\n TextureTypeCubemapArray = sys::basist_basis_texture_type_cBASISTexTypeCubemapArray,\n\n /// An array of 2D video frames, with optional mipmaps, # frames = # images, each image has the same resolution and # of mipmap levels\n\n TextureTypeVideoFrames = sys::basist_basis_texture_type_cBASISTexTypeVideoFrames,\n\n /// A 3D texture with optional mipmaps, Z dimension = # images, each image has the same resolution and # of mipmap levels\n\n TextureTypeVolume = sys::basist_basis_texture_type_cBASISTexTypeVolume,\n\n}\n\n\n\nimpl Into<sys::basist_basis_texture_type> for BasisTextureType {\n", "file_path": "basis-universal/src/transcoding/enums.rs", "rank": 78, "score": 26399.988188563722 }, { "content": " }\n\n\n\n output_rows_in_pixels * output_row_pitch_in_blocks_or_pixels\n\n } else if self == TranscoderTextureFormat::FXT1_RGB {\n\n let num_blocks_fxt1_x = (original_width + 7) / 8;\n\n let num_blocks_fxt1_y = (original_height + 3) / 4;\n\n num_blocks_fxt1_x * num_blocks_fxt1_y\n\n } else {\n\n total_slice_blocks\n\n };\n\n\n\n debug_assert!(self.validate_output_buffer_size(\n\n minimum_output_buffer_blocks_or_pixels,\n\n original_width,\n\n original_height,\n\n total_slice_blocks,\n\n Some(output_row_pitch_in_blocks_or_pixels),\n\n Some(output_rows_in_pixels),\n\n ));\n\n\n", "file_path": "basis-universal/src/transcoding/enums.rs", "rank": 79, "score": 26399.0861997379 }, { "content": " minimum_output_buffer_blocks_or_pixels\n\n }\n\n\n\n /// Calculate the minimum output buffer required to store transcoded data in bytes\n\n pub fn calculate_minimum_output_buffer_bytes(\n\n self,\n\n original_width: u32,\n\n original_height: u32,\n\n total_slice_blocks: u32,\n\n output_row_pitch_in_blocks_or_pixels: Option<u32>,\n\n output_rows_in_pixels: Option<u32>,\n\n ) -> u32 {\n\n self.calculate_minimum_output_buffer_blocks_or_pixels(\n\n original_width,\n\n original_height,\n\n total_slice_blocks,\n\n output_row_pitch_in_blocks_or_pixels,\n\n output_rows_in_pixels,\n\n ) * self.bytes_per_block_or_pixel()\n\n }\n", "file_path": "basis-universal/src/transcoding/enums.rs", "rank": 80, "score": 26398.93490362678 }, { "content": "\n\n/// The compression mode/format to use\n\n#[allow(non_camel_case_types)]\n\n#[derive(Copy, Clone, Debug, PartialEq)]\n\n#[repr(i32)]\n\npub enum BasisTextureFormat {\n\n /// A lower quality mode which is based off a subset of ETC1 called \"ETC1S\". Includes built-in\n\n /// data compression\n\n ETC1S = sys::basist_basis_tex_format_cETC1S,\n\n\n\n /// Enable UASTC compression mode instead of the default ETC1S mode. Significantly higher\n\n /// texture quality, but larger files. UASTC supports an optional Rate Distortion Optimization\n\n /// (RDO) post-process stage that conditions the encoded UASTC texture data in the .basis file\n\n /// so it can be more effectively LZ compressed by the end user.\n\n UASTC4x4 = sys::basist_basis_tex_format_cUASTC4x4,\n\n}\n\n\n\nimpl Into<sys::basist_basis_tex_format> for BasisTextureFormat {\n\n fn into(self) -> sys::basist_basis_tex_format {\n\n self as sys::basist_basis_tex_format\n", "file_path": "basis-universal/src/transcoding/enums.rs", "rank": 81, "score": 26398.604863455777 }, { "content": " ) -> bool;\n\n}\n\nextern \"C\" {\n\n pub fn transcoder_get_file_info(\n\n transcoder: *mut Transcoder,\n\n pData: *const ::std::os::raw::c_void,\n\n data_size: u32,\n\n file_info: *mut FileInfo,\n\n ) -> bool;\n\n}\n\nextern \"C\" {\n\n pub fn transcoder_start_transcoding(\n\n transcoder: *mut Transcoder,\n\n pData: *const ::std::os::raw::c_void,\n\n data_size: u32,\n\n ) -> bool;\n\n}\n\nextern \"C\" {\n\n pub fn transcoder_stop_transcoding(transcoder: *mut Transcoder) -> bool;\n\n}\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 82, "score": 25450.526871996277 }, { "content": "extern \"C\" {\n\n pub fn transcoder_get_ready_to_transcode(transcoder: *const Transcoder) -> bool;\n\n}\n\nextern \"C\" {\n\n pub fn transcoder_transcode_image_level(\n\n transcoder: *mut Transcoder,\n\n pData: *const ::std::os::raw::c_void,\n\n data_size: u32,\n\n image_index: u32,\n\n level_index: u32,\n\n pOutput_blocks: *mut ::std::os::raw::c_void,\n\n output_blocks_buf_size_in_blocks_or_pixels: u32,\n\n fmt: basist_transcoder_texture_format,\n\n decode_flags: basist_basisu_decode_flags,\n\n output_row_pitch_in_blocks_or_pixels: u32,\n\n pState: *mut basist_basisu_transcoder_state,\n\n output_rows_in_pixels: u32,\n\n ) -> bool;\n\n}\n\nextern \"C\" {\n\n pub fn basisu_transcoder_init();\n\n}\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 83, "score": 25449.62118990415 }, { "content": "extern \"C\" {\n\n pub fn transcoder_get_userdata(\n\n transcoder: *const Transcoder,\n\n pData: *const ::std::os::raw::c_void,\n\n data_size: u32,\n\n userdata0: *mut u32,\n\n userdata1: *mut u32,\n\n ) -> bool;\n\n}\n\nextern \"C\" {\n\n pub fn transcoder_get_total_images(\n\n transcoder: *const Transcoder,\n\n pData: *const ::std::os::raw::c_void,\n\n data_size: u32,\n\n ) -> u32;\n\n}\n\nextern \"C\" {\n\n pub fn transcoder_get_tex_format(\n\n transcoder: *const Transcoder,\n\n pData: *const ::std::os::raw::c_void,\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 84, "score": 25449.608852630772 }, { "content": " total_blocks: *mut u32,\n\n ) -> bool;\n\n}\n\nextern \"C\" {\n\n pub fn transcoder_get_image_info(\n\n transcoder: *const Transcoder,\n\n pData: *const ::std::os::raw::c_void,\n\n data_size: u32,\n\n image_info: *mut basist_basisu_image_info,\n\n image_index: u32,\n\n ) -> bool;\n\n}\n\nextern \"C\" {\n\n pub fn transcoder_get_image_level_info(\n\n transcoder: *const Transcoder,\n\n pData: *const ::std::os::raw::c_void,\n\n data_size: u32,\n\n level_info: *mut basist_basisu_image_level_info,\n\n image_index: u32,\n\n level_index: u32,\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 85, "score": 25449.541336787555 }, { "content": " data_size: u32,\n\n ) -> basist_basis_tex_format;\n\n}\n\nextern \"C\" {\n\n pub fn transcoder_get_total_image_levels(\n\n transcoder: *const Transcoder,\n\n pData: *const ::std::os::raw::c_void,\n\n data_size: u32,\n\n image_index: u32,\n\n ) -> u32;\n\n}\n\nextern \"C\" {\n\n pub fn transcoder_get_image_level_desc(\n\n transcoder: *const Transcoder,\n\n pData: *const ::std::os::raw::c_void,\n\n data_size: u32,\n\n image_index: u32,\n\n level_index: u32,\n\n orig_width: *mut u32,\n\n orig_height: *mut u32,\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 86, "score": 25449.165152515925 }, { "content": "pub const basist_transcoder_texture_format_cTFBC4: basist_transcoder_texture_format = 4;\n\npub const basist_transcoder_texture_format_cTFBC5: basist_transcoder_texture_format = 5;\n\npub const basist_transcoder_texture_format_cTFBC7_M6_RGB: basist_transcoder_texture_format = 6;\n\npub const basist_transcoder_texture_format_cTFBC7_M5_RGBA: basist_transcoder_texture_format = 6;\n\npub const basist_transcoder_texture_format_cTFBC7_M6_OPAQUE_ONLY: basist_transcoder_texture_format =\n\n 6;\n\npub const basist_transcoder_texture_format_cTFBC7_M5: basist_transcoder_texture_format = 6;\n\npub const basist_transcoder_texture_format_cTFBC7_ALT: basist_transcoder_texture_format = 7;\n\npub const basist_transcoder_texture_format_cTFASTC_4x4: basist_transcoder_texture_format = 10;\n\npub const basist_transcoder_texture_format_cTFATC_RGBA_INTERPOLATED_ALPHA:\n\n basist_transcoder_texture_format = 12;\n\npub type basist_transcoder_texture_format = ::std::os::raw::c_int;\n\n#[repr(C)]\n\n#[repr(align(8))]\n\npub struct basist_basisu_transcoder_state {\n\n pub _bindgen_opaque_blob: [u64; 102usize],\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy, Clone)]\n\npub struct basist_basisu_transcoder_state_block_preds {\n\n pub m_endpoint_index: u16,\n\n pub m_pred_bits: u8,\n\n}\n\n#[test]\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 87, "score": 25449.073786599623 }, { "content": "pub const basist_transcoder_texture_format_cTFPVRTC1_4_RGB: basist_transcoder_texture_format = 8;\n\npub const basist_transcoder_texture_format_cTFPVRTC1_4_RGBA: basist_transcoder_texture_format = 9;\n\npub const basist_transcoder_texture_format_cTFASTC_4x4_RGBA: basist_transcoder_texture_format = 10;\n\npub const basist_transcoder_texture_format_cTFATC_RGB: basist_transcoder_texture_format = 11;\n\npub const basist_transcoder_texture_format_cTFATC_RGBA: basist_transcoder_texture_format = 12;\n\npub const basist_transcoder_texture_format_cTFFXT1_RGB: basist_transcoder_texture_format = 17;\n\npub const basist_transcoder_texture_format_cTFPVRTC2_4_RGB: basist_transcoder_texture_format = 18;\n\npub const basist_transcoder_texture_format_cTFPVRTC2_4_RGBA: basist_transcoder_texture_format = 19;\n\npub const basist_transcoder_texture_format_cTFETC2_EAC_R11: basist_transcoder_texture_format = 20;\n\npub const basist_transcoder_texture_format_cTFETC2_EAC_RG11: basist_transcoder_texture_format = 21;\n\npub const basist_transcoder_texture_format_cTFRGBA32: basist_transcoder_texture_format = 13;\n\npub const basist_transcoder_texture_format_cTFRGB565: basist_transcoder_texture_format = 14;\n\npub const basist_transcoder_texture_format_cTFBGR565: basist_transcoder_texture_format = 15;\n\npub const basist_transcoder_texture_format_cTFRGBA4444: basist_transcoder_texture_format = 16;\n\npub const basist_transcoder_texture_format_cTFTotalTextureFormats:\n\n basist_transcoder_texture_format = 22;\n\npub const basist_transcoder_texture_format_cTFETC1: basist_transcoder_texture_format = 0;\n\npub const basist_transcoder_texture_format_cTFETC2: basist_transcoder_texture_format = 1;\n\npub const basist_transcoder_texture_format_cTFBC1: basist_transcoder_texture_format = 2;\n\npub const basist_transcoder_texture_format_cTFBC3: basist_transcoder_texture_format = 3;\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 88, "score": 25446.889079032517 }, { "content": " transcoder: *const Transcoder,\n\n pData: *const ::std::os::raw::c_void,\n\n data_size: u32,\n\n full_validation: bool,\n\n ) -> bool;\n\n}\n\nextern \"C\" {\n\n pub fn transcoder_validate_header(\n\n transcoder: *const Transcoder,\n\n pData: *const ::std::os::raw::c_void,\n\n data_size: u32,\n\n ) -> bool;\n\n}\n\nextern \"C\" {\n\n pub fn transcoder_get_texture_type(\n\n transcoder: *const Transcoder,\n\n pData: *const ::std::os::raw::c_void,\n\n data_size: u32,\n\n ) -> basist_basis_texture_type;\n\n}\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 89, "score": 25446.692793019563 }, { "content": " as *const _ as usize\n\n },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(basist_basisu_transcoder_state_block_preds),\n\n \"::\",\n\n stringify!(m_endpoint_index)\n\n )\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<basist_basisu_transcoder_state_block_preds>())).m_pred_bits\n\n as *const _ as usize\n\n },\n\n 2usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(basist_basisu_transcoder_state_block_preds),\n\n \"::\",\n\n stringify!(m_pred_bits)\n\n )\n\n );\n\n}\n\npub const basist_basisu_transcoder_state_cMaxPrevFrameLevels: ::std::os::raw::c_uint = 16;\n\npub type basist_basisu_transcoder_state__bindgen_ty_1 = ::std::os::raw::c_uint;\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 90, "score": 25446.15599353614 }, { "content": "pub const basist_block_format_cRGBA4444: basist_block_format = 29;\n\npub const basist_block_format_cTotalBlockFormats: basist_block_format = 30;\n\npub type basist_block_format = ::std::os::raw::c_int;\n\npub const basist_basis_texture_type_cBASISTexType2D: basist_basis_texture_type = 0;\n\npub const basist_basis_texture_type_cBASISTexType2DArray: basist_basis_texture_type = 1;\n\npub const basist_basis_texture_type_cBASISTexTypeCubemapArray: basist_basis_texture_type = 2;\n\npub const basist_basis_texture_type_cBASISTexTypeVideoFrames: basist_basis_texture_type = 3;\n\npub const basist_basis_texture_type_cBASISTexTypeVolume: basist_basis_texture_type = 4;\n\npub const basist_basis_texture_type_cBASISTexTypeTotal: basist_basis_texture_type = 5;\n\npub type basist_basis_texture_type = ::std::os::raw::c_uint;\n\npub const basist_basis_tex_format_cETC1S: basist_basis_tex_format = 0;\n\npub const basist_basis_tex_format_cUASTC4x4: basist_basis_tex_format = 1;\n\npub type basist_basis_tex_format = ::std::os::raw::c_int;\n\npub const basist_transcoder_texture_format_cTFETC1_RGB: basist_transcoder_texture_format = 0;\n\npub const basist_transcoder_texture_format_cTFETC2_RGBA: basist_transcoder_texture_format = 1;\n\npub const basist_transcoder_texture_format_cTFBC1_RGB: basist_transcoder_texture_format = 2;\n\npub const basist_transcoder_texture_format_cTFBC3_RGBA: basist_transcoder_texture_format = 3;\n\npub const basist_transcoder_texture_format_cTFBC4_R: basist_transcoder_texture_format = 4;\n\npub const basist_transcoder_texture_format_cTFBC5_RG: basist_transcoder_texture_format = 5;\n\npub const basist_transcoder_texture_format_cTFBC7_RGBA: basist_transcoder_texture_format = 6;\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 91, "score": 25446.128296082054 }, { "content": "extern \"C\" {\n\n pub fn basis_get_bytes_per_block_or_pixel(fmt: basist_transcoder_texture_format) -> u32;\n\n}\n\nextern \"C\" {\n\n pub fn basis_get_format_name(\n\n fmt: basist_transcoder_texture_format\n\n ) -> *const ::std::os::raw::c_char;\n\n}\n\nextern \"C\" {\n\n pub fn basis_get_block_format_name(fmt: basist_block_format) -> *const ::std::os::raw::c_char;\n\n}\n\nextern \"C\" {\n\n pub fn basis_transcoder_format_has_alpha(fmt: basist_transcoder_texture_format) -> bool;\n\n}\n\nextern \"C\" {\n\n pub fn basis_get_basisu_texture_format(\n\n fmt: basist_transcoder_texture_format\n\n ) -> basisu_texture_format;\n\n}\n\nextern \"C\" {\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 92, "score": 25446.044837101774 }, { "content": " pub fn basis_get_texture_type_name(\n\n tex_type: basist_basis_texture_type\n\n ) -> *const ::std::os::raw::c_char;\n\n}\n\nextern \"C\" {\n\n pub fn basis_transcoder_format_is_uncompressed(\n\n tex_type: basist_transcoder_texture_format\n\n ) -> bool;\n\n}\n\nextern \"C\" {\n\n pub fn basis_get_uncompressed_bytes_per_pixel(fmt: basist_transcoder_texture_format) -> u32;\n\n}\n\nextern \"C\" {\n\n pub fn basis_get_block_width(tex_type: basist_transcoder_texture_format) -> u32;\n\n}\n\nextern \"C\" {\n\n pub fn basis_get_block_height(tex_type: basist_transcoder_texture_format) -> u32;\n\n}\n\nextern \"C\" {\n\n pub fn basis_is_format_supported(\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 93, "score": 25446.034089691493 }, { "content": " tex_type: basist_transcoder_texture_format,\n\n fmt: basist_basis_tex_format,\n\n ) -> bool;\n\n}\n\nextern \"C\" {\n\n pub fn basis_validate_output_buffer_size(\n\n target_format: basist_transcoder_texture_format,\n\n output_blocks_buf_size_in_blocks_or_pixels: u32,\n\n orig_width: u32,\n\n orig_height: u32,\n\n output_row_pitch_in_blocks_or_pixels: u32,\n\n output_rows_in_pixels: u32,\n\n total_slice_blocks: u32,\n\n ) -> bool;\n\n}\n\n#[repr(C)]\n\n#[repr(align(8))]\n\n#[derive(Debug, Copy, Clone)]\n\npub struct Transcoder {\n\n pub _bindgen_opaque_blob: [u64; 2usize],\n\n}\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 94, "score": 25445.5911538715 }, { "content": "pub const basisu_texture_format_cETC2_R11_EAC: basisu_texture_format = 17;\n\npub const basisu_texture_format_cETC2_RG11_EAC: basisu_texture_format = 18;\n\npub const basisu_texture_format_cUASTC4x4: basisu_texture_format = 19;\n\npub const basisu_texture_format_cBC1_NV: basisu_texture_format = 20;\n\npub const basisu_texture_format_cBC1_AMD: basisu_texture_format = 21;\n\npub const basisu_texture_format_cRGBA32: basisu_texture_format = 22;\n\npub const basisu_texture_format_cRGB565: basisu_texture_format = 23;\n\npub const basisu_texture_format_cBGR565: basisu_texture_format = 24;\n\npub const basisu_texture_format_cRGBA4444: basisu_texture_format = 25;\n\npub const basisu_texture_format_cABGR4444: basisu_texture_format = 26;\n\npub type basisu_texture_format = ::std::os::raw::c_int;\n\npub const basist_block_format_cETC1: basist_block_format = 0;\n\npub const basist_block_format_cETC2_RGBA: basist_block_format = 1;\n\npub const basist_block_format_cBC1: basist_block_format = 2;\n\npub const basist_block_format_cBC3: basist_block_format = 3;\n\npub const basist_block_format_cBC4: basist_block_format = 4;\n\npub const basist_block_format_cBC5: basist_block_format = 5;\n\npub const basist_block_format_cPVRTC1_4_RGB: basist_block_format = 6;\n\npub const basist_block_format_cPVRTC1_4_RGBA: basist_block_format = 7;\n\npub const basist_block_format_cBC7: basist_block_format = 8;\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 95, "score": 25442.4761519823 }, { "content": "pub const basist_basisu_decode_flags_cDecodeFlagsHighQuality: basist_basisu_decode_flags = 32;\n\npub type basist_basisu_decode_flags = ::std::os::raw::c_uint;\n\n#[repr(C)]\n\n#[derive(Debug, Copy, Clone)]\n\npub struct basist_basisu_image_info {\n\n pub m_image_index: u32,\n\n pub m_total_levels: u32,\n\n pub m_orig_width: u32,\n\n pub m_orig_height: u32,\n\n pub m_width: u32,\n\n pub m_height: u32,\n\n pub m_num_blocks_x: u32,\n\n pub m_num_blocks_y: u32,\n\n pub m_total_blocks: u32,\n\n pub m_first_slice_index: u32,\n\n pub m_alpha_flag: bool,\n\n pub m_iframe_flag: bool,\n\n}\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 96, "score": 25442.4761519823 }, { "content": "pub const basist_block_format_cBC7_M5_COLOR: basist_block_format = 9;\n\npub const basist_block_format_cBC7_M5_ALPHA: basist_block_format = 10;\n\npub const basist_block_format_cETC2_EAC_A8: basist_block_format = 11;\n\npub const basist_block_format_cASTC_4x4: basist_block_format = 12;\n\npub const basist_block_format_cATC_RGB: basist_block_format = 13;\n\npub const basist_block_format_cATC_RGBA_INTERPOLATED_ALPHA: basist_block_format = 14;\n\npub const basist_block_format_cFXT1_RGB: basist_block_format = 15;\n\npub const basist_block_format_cPVRTC2_4_RGB: basist_block_format = 16;\n\npub const basist_block_format_cPVRTC2_4_RGBA: basist_block_format = 17;\n\npub const basist_block_format_cETC2_EAC_R11: basist_block_format = 18;\n\npub const basist_block_format_cETC2_EAC_RG11: basist_block_format = 19;\n\npub const basist_block_format_cIndices: basist_block_format = 20;\n\npub const basist_block_format_cRGB32: basist_block_format = 21;\n\npub const basist_block_format_cRGBA32: basist_block_format = 22;\n\npub const basist_block_format_cA32: basist_block_format = 23;\n\npub const basist_block_format_cRGB565: basist_block_format = 24;\n\npub const basist_block_format_cBGR565: basist_block_format = 25;\n\npub const basist_block_format_cRGBA4444_COLOR: basist_block_format = 26;\n\npub const basist_block_format_cRGBA4444_ALPHA: basist_block_format = 27;\n\npub const basist_block_format_cRGBA4444_COLOR_OPAQUE: basist_block_format = 28;\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 97, "score": 25442.4761519823 }, { "content": "/* automatically generated by rust-bindgen 0.57.0 */\n\n\n\npub const basisu_texture_format_cInvalidTextureFormat: basisu_texture_format = -1;\n\npub const basisu_texture_format_cETC1: basisu_texture_format = 0;\n\npub const basisu_texture_format_cETC1S: basisu_texture_format = 1;\n\npub const basisu_texture_format_cETC2_RGB: basisu_texture_format = 2;\n\npub const basisu_texture_format_cETC2_RGBA: basisu_texture_format = 3;\n\npub const basisu_texture_format_cETC2_ALPHA: basisu_texture_format = 4;\n\npub const basisu_texture_format_cBC1: basisu_texture_format = 5;\n\npub const basisu_texture_format_cBC3: basisu_texture_format = 6;\n\npub const basisu_texture_format_cBC4: basisu_texture_format = 7;\n\npub const basisu_texture_format_cBC5: basisu_texture_format = 8;\n\npub const basisu_texture_format_cBC7: basisu_texture_format = 9;\n\npub const basisu_texture_format_cASTC4x4: basisu_texture_format = 10;\n\npub const basisu_texture_format_cPVRTC1_4_RGB: basisu_texture_format = 11;\n\npub const basisu_texture_format_cPVRTC1_4_RGBA: basisu_texture_format = 12;\n\npub const basisu_texture_format_cATC_RGB: basisu_texture_format = 13;\n\npub const basisu_texture_format_cATC_RGBA_INTERPOLATED_ALPHA: basisu_texture_format = 14;\n\npub const basisu_texture_format_cFXT1_RGB: basisu_texture_format = 15;\n\npub const basisu_texture_format_cPVRTC2_4_RGBA: basisu_texture_format = 16;\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 98, "score": 25442.4761519823 }, { "content": " stringify!(m_image_index)\n\n )\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<basist_basisu_image_info>())).m_total_levels as *const _ as usize\n\n },\n\n 4usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(basist_basisu_image_info),\n\n \"::\",\n\n stringify!(m_total_levels)\n\n )\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<basist_basisu_image_info>())).m_orig_width as *const _ as usize\n\n },\n\n 8usize,\n", "file_path": "basis-universal-sys/src/transcoding_bindings.rs", "rank": 99, "score": 25442.4761519823 } ]
Rust
src/macros.rs
activeledger/SDK-Rust-TxBuilder
505e9a7a4b2240a08dcb01786bcf7d92d7f60a49
/* * MIT License (MIT) * Copyright (c) 2019 Activeledger * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! input_str { ($e:expr) => { $crate::PacketValue::String($e.to_string()) }; } #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! input_array { ($e:expr) => { $crate::PacketValue::Array($e) }; } #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! input_map { ($e:expr) => { $crate::PacketValue::Object($e) }; } #[macro_export] macro_rules! signees { [$({$streamid: expr => $key:expr}),+] => {{ let mut signees = $crate::Signees::new(); $( signees.add($key, $streamid); )* signees }}; ($key:expr) => {{ let mut s = $crate::Signees::new(); s.add_selfsign($key); s.clone() }}; () => {{ let s = $crate::Signees::new(); s.clone() }}; } #[macro_export(local_inner_macros)] macro_rules! packet_data { ($($data:tt)+) => { packet_data_internal!($($data)+) }; } #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! packet_data_internal { (@object $object:ident () () ()) => {}; (@object $object:ident [$($key:tt)+] ($value:expr), $($tail:tt)*) => { let _ = $object.insert(($($key)+).into(), $value); packet_data_internal!(@object $object () ($($tail)*) ($($tail)*)); }; (@object $object:ident [$($key:tt)+] ($value:expr)) => { let _ = $object.insert(($($key)+).into(), $value); }; (@object $object:ident ($($key:tt)+) (: {$($map:tt)*} $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object [$($key)+] (packet_data_internal!({$($map)*})) $($tail)*); }; (@object $object:ident ($($key:tt)+) (: [$($array:tt)*] $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object [$($key)+] (packet_data_internal!([$($array)*])) $($tail)*); }; (@object $object:ident ($($key:tt)+) (: $value:expr, $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object [$($key)+] (packet_data_internal!($value)) , $($tail)*); }; (@object $object:ident ($($key:tt)+) (: $value:expr) $copy:tt) => { packet_data_internal!(@object $object [$($key)+] (packet_data_internal!($value))); }; (@object $object:ident () (($key:expr) : $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object ($key) (: $($tail)*) (: $($tail)*)); }; (@object $object:ident ($($key:tt)*) ($data:tt $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object ($($key)* $data) ($($tail)*) ($($tail)*)); }; (@object $object:ident [$($key:tt)+] ($value:expr) $unexpected:tt $($tail:tt)*) => { input_unexpected!($unexpected); }; (@array [$($elems:expr,)*]) => { packet_data_internal_vec![$($elems,)*] }; (@array [$($elems:expr),*]) => { packet_data_internal_vec![$($elems),*] }; (@array [$($elems:expr,)*] $next:expr, $($tail:tt)*) => { packet_data_internal!(@array [$($elems,)* packet_data_internal!($next),] $($tail)*) }; (@array [$($elems:expr,)*] $last:expr) => { packet_data_internal!(@array [$($elems,)* packet_data_internal!($last)]) }; (@array [$($elems:expr,)*] , $($tail:tt)*) => { packet_data_internal!(@array [$($elems,)*] $($tail:tt)*) }; (@array [$($elems:expr),*] $unexpected:tt $($tail:tt)*) => { input_unexpected!($unexpected) }; ({}) => {{ $crate::PacketValue::Object(std::collections::HashMap::new()) }}; ({ $($data:tt)+ }) => { $crate::PacketValue::Object({ let mut object = std::collections::HashMap::new(); packet_data_internal!(@object object () ($($data)+) ($($data)+)); object }) }; ([]) => { $crate::PacketValue::Array(packet_data_internal_vec![]) }; ([ $($data:tt)+ ]) => { $crate::PacketValue::Array(packet_data_internal!(@array [] $($data)+)) }; ($other:expr) => { input_str!(&$other) } } #[macro_export] #[doc(hidden)] macro_rules! packet_data_internal_vec { ($($data:tt)*) => { vec![$($data)*] }; } #[macro_export] #[doc(hidden)] macro_rules! input_unexpected { () => {}; }
/* * MIT License (MIT) * Copyright (c) 2019 Activeledger * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! input_str { ($e:expr) => { $crate::PacketValue::String($e.to_string()) }; } #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! input_array { ($e:expr) => { $crate::PacketValue::Array($e) }; } #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! input_map { ($e:
c![$($data)*] }; } #[macro_export] #[doc(hidden)] macro_rules! input_unexpected { () => {}; }
expr) => { $crate::PacketValue::Object($e) }; } #[macro_export] macro_rules! signees { [$({$streamid: expr => $key:expr}),+] => {{ let mut signees = $crate::Signees::new(); $( signees.add($key, $streamid); )* signees }}; ($key:expr) => {{ let mut s = $crate::Signees::new(); s.add_selfsign($key); s.clone() }}; () => {{ let s = $crate::Signees::new(); s.clone() }}; } #[macro_export(local_inner_macros)] macro_rules! packet_data { ($($data:tt)+) => { packet_data_internal!($($data)+) }; } #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! packet_data_internal { (@object $object:ident () () ()) => {}; (@object $object:ident [$($key:tt)+] ($value:expr), $($tail:tt)*) => { let _ = $object.insert(($($key)+).into(), $value); packet_data_internal!(@object $object () ($($tail)*) ($($tail)*)); }; (@object $object:ident [$($key:tt)+] ($value:expr)) => { let _ = $object.insert(($($key)+).into(), $value); }; (@object $object:ident ($($key:tt)+) (: {$($map:tt)*} $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object [$($key)+] (packet_data_internal!({$($map)*})) $($tail)*); }; (@object $object:ident ($($key:tt)+) (: [$($array:tt)*] $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object [$($key)+] (packet_data_internal!([$($array)*])) $($tail)*); }; (@object $object:ident ($($key:tt)+) (: $value:expr, $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object [$($key)+] (packet_data_internal!($value)) , $($tail)*); }; (@object $object:ident ($($key:tt)+) (: $value:expr) $copy:tt) => { packet_data_internal!(@object $object [$($key)+] (packet_data_internal!($value))); }; (@object $object:ident () (($key:expr) : $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object ($key) (: $($tail)*) (: $($tail)*)); }; (@object $object:ident ($($key:tt)*) ($data:tt $($tail:tt)*) $copy:tt) => { packet_data_internal!(@object $object ($($key)* $data) ($($tail)*) ($($tail)*)); }; (@object $object:ident [$($key:tt)+] ($value:expr) $unexpected:tt $($tail:tt)*) => { input_unexpected!($unexpected); }; (@array [$($elems:expr,)*]) => { packet_data_internal_vec![$($elems,)*] }; (@array [$($elems:expr),*]) => { packet_data_internal_vec![$($elems),*] }; (@array [$($elems:expr,)*] $next:expr, $($tail:tt)*) => { packet_data_internal!(@array [$($elems,)* packet_data_internal!($next),] $($tail)*) }; (@array [$($elems:expr,)*] $last:expr) => { packet_data_internal!(@array [$($elems,)* packet_data_internal!($last)]) }; (@array [$($elems:expr,)*] , $($tail:tt)*) => { packet_data_internal!(@array [$($elems,)*] $($tail:tt)*) }; (@array [$($elems:expr),*] $unexpected:tt $($tail:tt)*) => { input_unexpected!($unexpected) }; ({}) => {{ $crate::PacketValue::Object(std::collections::HashMap::new()) }}; ({ $($data:tt)+ }) => { $crate::PacketValue::Object({ let mut object = std::collections::HashMap::new(); packet_data_internal!(@object object () ($($data)+) ($($data)+)); object }) }; ([]) => { $crate::PacketValue::Array(packet_data_internal_vec![]) }; ([ $($data:tt)+ ]) => { $crate::PacketValue::Array(packet_data_internal!(@array [] $($data)+)) }; ($other:expr) => { input_str!(&$other) } } #[macro_export] #[doc(hidden)] macro_rules! packet_data_internal_vec { ($($data:tt)*) => { ve
random
[ { "content": "# Activeledger - Transaction Helper\n\n\n\n<img src=\"https://www.activeledger.io/wp-content/uploads/2018/09/Asset-23.png\" alt=\"Activeledger\" width=\"300\"/>\n\n\n\nActiveledger is a powerful distributed ledger technology.\n\nThink about it as a single ledger, which is updated simultaneously in multiple locations.\n\nAs the data is written to a ledger, it is approved and confirmed by all other locations.\n\n\n\n[GitHub](https://github.com/activeledger/activeledger)\n\n\n\n[NPM](https://www.npmjs.com/package/@activeledger/activeledger)\n\n\n\n---\n\n\n\n## This Crate\n\n\n\nThis crate acts as a helper for creating JSON transactions. It can be used in addition to the main [Activeledger Rust SDK](https://crates.io/crates/activeledger) or on its own.\n\nThis crate provides Rust developers an easy way to build up transactions without needing other crates, such as Serde.\n\n\n\nThis crate provides macros as well as builders that help create a transaction with the correct structure.\n\nAdditionally it provides two methods of creating a complete onboarding transaction. With and without a provided key.\n\n\n\n## Additional Activeledger crates\n\nAdhearing to the Rust mentality of keeping things small we have created other crates that can be used in conjunction\n\nwith this one to add additional functionality.\n\n\n\nThese crates are:\n\n* [activeledger](https://github.com/activeledger/SDK-Rust) - The main SDK. ([Crate](https://crates.io/crates/activeledger))\n\n* [active_sse](https://github.com/activeledger/SDK-Rust-Events) - To build transactions without worrying about the JSON. ([Crate](https://crates.io/crates/active_sse))\n\n\n", "file_path": "README.md", "rank": 0, "score": 15202.732533865214 }, { "content": "# Changelog\n\n\n\nAll notable changes to this project will be documented in this file.\n\n\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\n\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n\n\n## [0.1.0] - 24-09-2019\n\n\n\n### Initial release\n\n\n\n- Activeledger TX Helper\n", "file_path": "CHANGELOG.md", "rank": 1, "score": 15198.189346632573 }, { "content": "## Links\n\n[Visit Activeledger.io](https://activeledger.io/)\n\n\n\n[Read Activeledgers documentation](https://github.com/activeledger/activeledger/blob/master/docs/en-gb/README.md)\n\n\n\n[Activeledger Developers portal](https://developers.activeledger.io)\n\n\n\n[Activeledger on GitHub](https://github.com/activeledger/activeledger)\n\n\n\n[Activeledger on NPM](https://www.npmjs.com/package/@activeledger/activeledger)\n\n\n\n[This SDK on GitHub](https://github.com/activeledger/SDK-Rust-TxBuilder)\n\n\n\n[Report Issues](https://github.com/activeledger/SDK-Rust-TxBuilder/issues)\n\n\n\n## License\n\n\n\n---\n\n\n\nThis project is licensed under the [MIT](https://github.com/activeledger/activeledger/blob/master/LICENSE) License\n", "file_path": "README.md", "rank": 2, "score": 15198.013663501302 }, { "content": "/*\n\n * MIT License (MIT)\n\n * Copyright (c) 2019 Activeledger\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n *\n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n", "file_path": "src/transaction_builder/signee.rs", "rank": 3, "score": 98.73331870068765 }, { "content": "/*\n\n * MIT License (MIT)\n\n * Copyright (c) 2019 Activeledger\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n *\n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n", "file_path": "src/packet_builder/builder.rs", "rank": 4, "score": 98.73331870068766 }, { "content": "/*\n\n * MIT License (MIT)\n\n * Copyright (c) 2019 Activeledger\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n *\n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n", "file_path": "src/error.rs", "rank": 5, "score": 98.73331870068769 }, { "content": "/*\n\n * MIT License (MIT)\n\n * Copyright (c) 2019 Activeledger\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n *\n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n", "file_path": "src/transaction_builder/builder.rs", "rank": 7, "score": 98.73331870068768 }, { "content": "/*\n\n * MIT License (MIT)\n\n * Copyright (c) 2019 Activeledger\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n *\n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n", "file_path": "src/lib.rs", "rank": 8, "score": 98.73331870068769 }, { "content": "/*\n\n * MIT License (MIT)\n\n * Copyright (c) 2019 Activeledger\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n *\n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n", "file_path": "src/transaction_builder/body.rs", "rank": 9, "score": 98.73331870068768 }, { "content": "/*\n\n * MIT License (MIT)\n\n * Copyright (c) 2019 Activeledger\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n *\n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n", "file_path": "src/transaction_builder/mod.rs", "rank": 10, "score": 98.73331870068768 }, { "content": "/*\n\n * MIT License (MIT)\n\n * Copyright (c) 2019 Activeledger\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n *\n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n", "file_path": "src/packet_builder/mod.rs", "rank": 11, "score": 98.73331870068766 }, { "content": " * SOFTWARE.\n\n */\n\n\n\n//! # Activeledger Transaction Helper\n\n//!\n\n//! <img src=\"https://www.activeledger.io/wp-content/uploads/2018/09/Asset-23.png\" alt=\"Activeledger\" width=\"300\"/>\n\n//!\n\n//! Activeledger is a powerful distributed ledger technology.\n\n//! Think about it as a single ledger, which is updated simultaneously in multiple locations.\n\n//! As the data is written to a ledger, it is approved and confirmed by all other locations.\n\n//!\n\n//! ## This Crate\n\n//!\n\n//! This crate provides Rust developers an easy way to build up transactions without needing other crates, such as Serde.\n\n//!\n\n//! This crate provides macros as well as builders that help create a transaction with the correct structure.\n\n//! Additionally it provides two methods of creating a complete onboarding transaction. With and without a provided key.\n\n//!\n\n//! ## Additional Activeledger crates\n\n//! Adhearing to the Rust mentality of keeping things small we have created other crates that can be used in conjunction\n", "file_path": "src/lib.rs", "rank": 12, "score": 13.05638511421109 }, { "content": " * SOFTWARE.\n\n */\n\n\n\n//! # Transaction Builder\n\n//!\n\n//! The transaction builder provides methods to aid with building up a transaction correctly.\n\n//!\n\n//! ## Example\n\n//!\n\n//! ```\n\n//! # use active_tx::{PacketBuilder, TransactionBuilder, Key, packet_data, signees};\n\n//! # use activeledger::key::EllipticCurve;\n\n//! # fn main() {\n\n//! let input = packet_data!({\"[streamid]\": {\"input\": \"data\"}});\n\n//!\n\n//! let input_data = PacketBuilder::new(input).build().unwrap();\n\n//! \n\n//! let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n//! #\n\n//! # let streamid = \"\";\n", "file_path": "src/transaction_builder/mod.rs", "rank": 13, "score": 10.100771286793938 }, { "content": "//! with this one to add additional functionality.\n\n//!\n\n//! These crates are:\n\n//! * [activeledger](https://github.com/activeledger/SDK-Rust) - The main SDK. ([Crate](https://crates.io/crates/activeledger))\n\n//! * [active_sse](https://github.com/activeledger/SDK-Rust-Events) - To build transactions without worrying about the JSON. ([Crate](https://crates.io/crates/active-events))\n\n//!\n\n//! ## Links\n\n//!\n\n//! [Activeledger](https://activeledger.io)\n\n//!\n\n//! [Activeledger Developers portal](https://developers.activeledger.io)\n\n//!\n\n//! [Activeledger on GitHub](https://github.com/activeledger/activeledger)\n\n//!\n\n//! [Activeledger on NPM](https://www.npmjs.com/package/@activeledger/activeledger)\n\n//!\n\n//! [This SDK on GitHub](https://github.com/activeledger/SDK-Rust)\n\n//!\n\n//! [Report Issues](https://github.com/activeledger/SDK-Rust/issues)\n\n//!\n", "file_path": "src/lib.rs", "rank": 14, "score": 7.683381919978986 }, { "content": "///\n\n/// **Transaction**\n\n/// * Territoriality\n\n/// * Selfsign\n\n///\n\n/// Adding in this extra data is straight forward. It goes without saying that they should be added\n\n/// before calling the build method.\n\n///\n\n/// **Note:** For the sake of space the required data has not been added to the following examples.\n\n///\n\n/// #### Packet\n\n/// ##### Output\n\n/// The output can be generated using the exact same method as the input in the full example\n\n/// ```\n\n/// # use active_tx::{packet_data, PacketBuilder, TransactionBuilder};\n\n/// let output_data = packet_data!({\"\": \"\"});\n\n/// let output = PacketBuilder::new(output_data).build().unwrap();\n\n///\n\n/// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n/// tx_builder.output(output);\n", "file_path": "src/transaction_builder/builder.rs", "rank": 15, "score": 7.443854076257493 }, { "content": " /// ```\n\n /// # use active_tx::{TransactionBuilder, packet_data, PacketBuilder, Key};\n\n /// # use activeledger::key::EllipticCurve;\n\n /// # let key = Key::Ec(EllipticCurve::new(\"keyname\").unwrap());\n\n /// # let input = PacketBuilder::new(packet_data!({\"data\": \"data\"})).build().unwrap();\n\n ///\n\n /// let mut tx_builder = TransactionBuilder::new_blank();\n\n ///\n\n /// tx_builder.contract(\"contract\");\n\n /// ```\n\n pub fn contract(&mut self, contract: &str) -> &mut Self {\n\n self.packet_data\n\n .insert(String::from(\"contract\"), json!(contract.to_string()));\n\n\n\n self\n\n }\n\n\n\n /// # Namespace\n\n ///\n\n /// Set the namespace value\n", "file_path": "src/transaction_builder/builder.rs", "rank": 16, "score": 7.34748700016276 }, { "content": " * SOFTWARE.\n\n */\n\n\n\nuse serde_json::{json, Value};\n\n\n\n// STD\n\nuse std::collections::HashMap;\n\n\n\n// Internal\n\nuse super::PacketValue;\n\nuse crate::error::{TxBuilderError, TxBuilderResult};\n\n\n\n/// Provides build methods\n\n#[derive(Clone)]\n\npub struct PacketBuilder {\n\n data: PacketData,\n\n}\n\n\n\n/// Stores the data built by PacketBuilder\n\n#[derive(Clone, Debug)]\n", "file_path": "src/packet_builder/builder.rs", "rank": 17, "score": 7.234806151207696 }, { "content": " * SOFTWARE.\n\n */\n\n\n\n// STD\n\nuse std::collections::HashMap;\n\n\n\n// External imports\n\nuse activeledger::key::{EllipticCurve, RSA};\n\nuse serde_json::{json, Value};\n\n\n\n// Internal imports\n\nuse super::body::TransactionBody;\n\nuse crate::error::{TxBuilderError, TxBuilderResult};\n\nuse crate::packet_builder::{Input, Output, Readonly};\n\nuse crate::Signees;\n\nuse crate::{packet_data, signees};\n\n\n\n/// Holds the key to use when signing the transaction packet\n\n#[derive(Clone)]\n\npub enum Key {\n", "file_path": "src/transaction_builder/builder.rs", "rank": 18, "score": 6.9513773051847805 }, { "content": " tx_data: HashMap<String, Value>,\n\n\n\n // Generation and storage holders\n\n packet: Option<TransactionBody>,\n\n tx: Option<Value>,\n\n sigs: HashMap<String, String>,\n\n}\n\n\n\n// Public functions\n\nimpl TransactionBuilder {\n\n /// # Builder with namespace and contract\n\n ///\n\n /// Create a builder with predetermined namespace and contract.\n\n ///\n\n /// Required data: Input\n\n ///\n\n /// ```\n\n /// # use active_tx::TransactionBuilder;\n\n /// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n /// ```\n", "file_path": "src/transaction_builder/builder.rs", "rank": 19, "score": 6.777672756711789 }, { "content": " /// # use active_tx::{TransactionBuilder, packet_data, PacketBuilder, Key};\n\n /// # use activeledger::key::EllipticCurve;\n\n /// # let key = Key::Ec(EllipticCurve::new(\"keyname\").unwrap());\n\n /// # let input = PacketBuilder::new(packet_data!({\"data\": \"data\"})).build().unwrap();\n\n ///\n\n /// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n ///\n\n /// tx_builder.entry(\"entry\");\n\n /// ```\n\n pub fn entry(&mut self, entry: &str) -> &mut Self {\n\n self.packet_data\n\n .insert(String::from(\"entry\"), json!(entry.to_string()));\n\n\n\n self\n\n }\n\n\n\n /// # Contract\n\n ///\n\n /// Set the contract value\n\n ///\n", "file_path": "src/transaction_builder/builder.rs", "rank": 20, "score": 6.761654390600896 }, { "content": " tx: None,\n\n sigs: HashMap::new(),\n\n }\n\n }\n\n\n\n /// # Blank Builder\n\n ///\n\n /// Create a builder that has no data.\n\n ///\n\n /// Required data: Input, Contract, Namespace\n\n ///\n\n /// ```\n\n /// # use active_tx::TransactionBuilder;\n\n /// let mut tx_builder = TransactionBuilder::new_blank();\n\n /// ```\n\n ///\n\n /// It is required that contract, namespace, and input data be added to the builder before it will build the transaction.\n\n ///\n\n /// All data can be added by the other methods provided by the builder.\n\n ///\n", "file_path": "src/transaction_builder/builder.rs", "rank": 21, "score": 6.665236236567452 }, { "content": " * SOFTWARE.\n\n */\n\n\n\nuse serde_json::{json, Value};\n\n\n\nuse crate::error::{TxBuilderError, TxBuilderResult};\n\n\n\n/// Holds the transactions data\n\n#[derive(Debug, Clone)]\n\npub struct TransactionBody {\n\n entry: Option<Value>,\n\n contract: Value,\n\n namespace: Value,\n\n input: Value,\n\n output: Option<Value>,\n\n readonly: Option<Value>,\n\n json: Option<Value>,\n\n}\n\n\n\nimpl TransactionBody {\n", "file_path": "src/transaction_builder/body.rs", "rank": 22, "score": 6.56140634179463 }, { "content": " json[\"$sigs\"] = json!(self.sigs.clone());\n\n\n\n self.tx.replace(json.clone());\n\n\n\n Ok(self)\n\n }\n\n\n\n /// # Build\n\n ///\n\n /// Using the data provided, compile it into the correct form for a transaction.\n\n /// Returns a transaction in the form of a string.\n\n ///\n\n /// ```\n\n /// # use active_tx::{TransactionBuilder, packet_data, PacketBuilder, Key, signees};\n\n /// # use activeledger::key::EllipticCurve;\n\n /// # let input = PacketBuilder::new(packet_data!({\"data\": \"data\"})).build().unwrap();\n\n ///\n\n /// let streamid = \"id\";\n\n /// let key = Key::Ec(EllipticCurve::new(streamid).unwrap());\n\n ///\n", "file_path": "src/transaction_builder/builder.rs", "rank": 23, "score": 6.434315062634275 }, { "content": "/// ```\n\n///\n\n/// ##### Readonly\n\n/// The readonly data can be generated using the exact same method as the input in the full example\n\n/// ```\n\n/// # use active_tx::{packet_data, PacketBuilder, TransactionBuilder};\n\n/// let readonly_data = packet_data!({\"\": \"\"});\n\n/// let readonly = PacketBuilder::new(readonly_data).build().unwrap();\n\n///\n\n/// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n/// tx_builder.readonly(readonly);\n\n/// ```\n\n///\n\n/// ##### Entry\n\n/// As the entry value is a string we can pass it directly into the entry method without needing to\n\n/// use the [`PacketBuilder`].\n\n///\n\n/// ```\n\n/// # use active_tx::{packet_data, PacketBuilder, TransactionBuilder};\n\n/// #\n", "file_path": "src/transaction_builder/builder.rs", "rank": 24, "score": 6.248715901894833 }, { "content": "\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::*;\n\n use activeledger::key::EllipticCurve;\n\n\n\n #[test]\n\n fn tx_min() {\n\n let input = packet_data!({\"input\": \"data\"});\n\n\n\n let built_input = PacketBuilder::new(input).build().unwrap();\n\n\n\n let mut transaction_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n\n\n let streamid = \"test\";\n\n let key = Key::Ec(EllipticCurve::new(streamid).unwrap());\n\n\n\n let signees = signees![{streamid => key}];\n\n\n\n let tx = transaction_builder\n", "file_path": "src/transaction_builder/mod.rs", "rank": 25, "score": 6.1289577738702885 }, { "content": " * SOFTWARE.\n\n */\n\n\n\n//! # Transaction Builder Error definitions\n\n\n\nuse std::error::Error;\n\nuse std::fmt;\n\n\n\n/// KeyResult definition - Shorthand for: Result<T, TxBuilderError>\n\npub type TxBuilderResult<T> = Result<T, TxBuilderError>;\n\n\n\n/// KeyError data holder\n\n#[derive(Debug)]\n\npub enum TxBuilderError {\n\n BuildError(u16), // 1000\n\n JsonError(u16), // 2000\n\n PacketError(u16), // 3000\n\n TxBodyError(u16), // 4000\n\n TxBuildError(u16), // 5000\n\n TxGenerateError(u16), // 6000\n", "file_path": "src/error.rs", "rank": 26, "score": 5.953143011174786 }, { "content": " }\n\n\n\n /// # Transaction JSON\n\n ///\n\n /// Get the built transaction as a Serde JSON value\n\n ///\n\n /// ```\n\n /// # use active_tx::{TransactionBuilder, packet_data, PacketBuilder, Key, signees};\n\n /// # use activeledger::key::EllipticCurve;\n\n ///\n\n /// let key = Key::Ec(EllipticCurve::new(\"keyname\").unwrap());\n\n ///\n\n /// let input = PacketBuilder::new(packet_data!({\"data\": \"data\"})).build().unwrap();\n\n ///\n\n /// let signees = signees![{\"streamid\" => key}];\n\n ///\n\n /// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n /// tx_builder\n\n /// .input(input)\n\n /// .unwrap()\n", "file_path": "src/transaction_builder/builder.rs", "rank": 27, "score": 5.837469057797702 }, { "content": "/// above.\n\n/// However, it is useful to know how that structure is broken down in terms of this helper.\n\n///\n\n/// This helper breaks the above structure down into two sections.\n\n/// 1. The overall transaction - Everything in the object\n\n/// 2. The transaction packet - everything inside the $tx object, this gets signed\n\n///\n\n/// When using this helper to create a transaction you must first create the packet as that is passed\n\n/// to the main builder. You can create three packets for the three sub objects inside of the packet:\n\n/// $i (input), $o (output), and $r (readonly).\n\n///\n\n/// ## Examples\n\n/// ### Minimal\n\n/// This example will go over creating the most minimal transaction.\n\n///\n\n/// **Note:** This example does include some bootstrapping as we need to generate a key.\n\n/// You may already have a key and very likely will want to reuse it.\n\n/// ```\n\n/// use activeledger::key::EllipticCurve;\n\n/// use active_tx::{PacketBuilder, TransactionBuilder, Key, packet_data, signees};\n", "file_path": "src/transaction_builder/builder.rs", "rank": 28, "score": 5.725312859036356 }, { "content": "//! ## Example usage\n\n//!\n\n//! ```\n\n//! # use active_tx::{PacketBuilder, TransactionBuilder, Key, packet_data, signees};\n\n//! # use activeledger::key::EllipticCurve;\n\n//! # fn main() {\n\n//! let input = packet_data!({\"[streamid]\": {\"input\": \"data\"}});\n\n//!\n\n//! let input_data = PacketBuilder::new(input).build().unwrap();\n\n//! \n\n//! let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n//!\n\n//! let streamid = \"streamid\";\n\n//! let key = Key::Ec(EllipticCurve::new(streamid).unwrap());\n\n//!\n\n//! let signees = signees![{streamid => key}];\n\n//!\n\n//! let tx = tx_builder\n\n//! .input(input_data)\n\n//! .unwrap()\n", "file_path": "src/lib.rs", "rank": 29, "score": 5.721076307490616 }, { "content": "\n\n Ok(self)\n\n }\n\n\n\n /// # Readonly\n\n ///\n\n /// Set the input value\n\n ///\n\n /// ```\n\n /// # use active_tx::{TransactionBuilder, packet_data, PacketBuilder, Key};\n\n /// # use activeledger::key::EllipticCurve;\n\n /// # let key = Key::Ec(EllipticCurve::new(\"keyname\").unwrap());\n\n ///\n\n /// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n ///\n\n /// let input = PacketBuilder::new(packet_data!({\"data\": \"data\"})).build().unwrap();\n\n /// tx_builder.input(input);\n\n /// ```\n\n pub fn readonly(&mut self, readonly: Readonly) -> TxBuilderResult<&mut Self> {\n\n match readonly.get() {\n", "file_path": "src/transaction_builder/builder.rs", "rank": 30, "score": 5.683329487357227 }, { "content": " Ok(data) => self.packet_data.insert(\"readonly\".to_string(), data),\n\n Err(_) => return Err(TxBuilderError::TxBuildError(5003)),\n\n };\n\n\n\n Ok(self)\n\n }\n\n\n\n /// # Selfsign\n\n ///\n\n /// Set selfsign to true\n\n ///\n\n /// ```\n\n /// # use active_tx::{TransactionBuilder, packet_data, PacketBuilder, Key};\n\n /// # use activeledger::key::EllipticCurve;\n\n /// # let key = Key::Ec(EllipticCurve::new(\"keyname\").unwrap());\n\n /// # let input = PacketBuilder::new(packet_data!({\"data\": \"data\"})).build().unwrap();\n\n ///\n\n /// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n /// tx_builder.input(input).unwrap();\n\n ///\n", "file_path": "src/transaction_builder/builder.rs", "rank": 33, "score": 5.537313170511123 }, { "content": " Rsa(RSA),\n\n Ec(EllipticCurve),\n\n}\n\n\n\n/// Key Type for generating a key and onboarding it\n\npub enum KeyType {\n\n RSA,\n\n EC,\n\n}\n\n\n\n/// # Transaction builder\n\n///\n\n/// The transaction builder is used to help build a compatible Activeledger transaction object.\n\n/// To read more about Activeledger transactions you can read the documentation [here.](https://github.com/activeledger/activeledger/blob/master/docs/en-gb/transactions.md)\n\n///\n\n/// This section will guide you through the creation of transaction using this crate.\n\n///\n\n/// ## Transaction structure\n\n/// Lets first have a look at the structure of a transaction.\n\n/// ```json\n", "file_path": "src/transaction_builder/builder.rs", "rank": 34, "score": 5.466298358812745 }, { "content": "\n\n /// # Output\n\n ///\n\n /// Set the input value\n\n ///\n\n /// ```\n\n /// # use active_tx::{TransactionBuilder, packet_data, PacketBuilder, Key};\n\n /// # use activeledger::key::EllipticCurve;\n\n /// # let key = Key::Ec(EllipticCurve::new(\"keyname\").unwrap());\n\n ///\n\n /// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n ///\n\n /// let input = PacketBuilder::new(packet_data!({\"data\": \"data\"})).build().unwrap();\n\n /// tx_builder.input(input);\n\n /// ```\n\n pub fn output(&mut self, output: Output) -> TxBuilderResult<&mut Self> {\n\n match output.get() {\n\n Ok(data) => self.packet_data.insert(\"output\".to_string(), data),\n\n Err(_) => return Err(TxBuilderError::TxBuildError(5002)),\n\n };\n", "file_path": "src/transaction_builder/builder.rs", "rank": 35, "score": 5.172675698884 }, { "content": " /// Set the input value\n\n ///\n\n /// ```\n\n /// # use active_tx::{TransactionBuilder, packet_data, PacketBuilder, Key};\n\n /// # use activeledger::key::EllipticCurve;\n\n /// # let key = Key::Ec(EllipticCurve::new(\"keyname\").unwrap());\n\n ///\n\n /// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n ///\n\n /// let input = PacketBuilder::new(packet_data!({\"data\": \"data\"})).build().unwrap();\n\n /// tx_builder.input(input);\n\n /// ```\n\n pub fn input(&mut self, input: Input) -> TxBuilderResult<&mut Self> {\n\n match input.get() {\n\n Ok(data) => self.packet_data.insert(\"input\".to_string(), data),\n\n Err(_) => return Err(TxBuilderError::TxBuildError(5001)),\n\n };\n\n\n\n Ok(self)\n\n }\n", "file_path": "src/transaction_builder/builder.rs", "rank": 36, "score": 5.172675698884 }, { "content": "/// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n/// tx_builder.entry(\"entry point\");\n\n/// ```\n\n///\n\n/// #### Transaction\n\n/// ##### Territoriality\n\n/// ```\n\n/// # use active_tx::{packet_data, PacketBuilder, TransactionBuilder};\n\n/// #\n\n/// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n/// tx_builder.territoriality(\"territory\");\n\n/// ```\n\n///\n\n/// ##### Selfsign\n\n/// Calling this function will set the selfsign value of the transaction to true\n\n/// ```\n\n/// # use active_tx::{packet_data, PacketBuilder, TransactionBuilder};\n\n/// #\n\n/// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n/// tx_builder.selfsign();\n", "file_path": "src/transaction_builder/builder.rs", "rank": 38, "score": 5.022803500601226 }, { "content": " * SOFTWARE.\n\n */\n\n\n\nuse crate::Key;\n\n\n\n/// Holds an array of Signees\n\n#[derive(Clone)]\n\npub struct Signees {\n\n keys: Vec<Signee>,\n\n}\n\n\n\n/// Holds the key and stream ID for use when signing the transaction packet.\n\n#[derive(Clone)]\n\npub struct Signee {\n\n pub streamid: String,\n\n pub key: Key,\n\n}\n\n\n\n/// # Signees\n\n///\n", "file_path": "src/transaction_builder/signee.rs", "rank": 39, "score": 5.015768803840649 }, { "content": " * SOFTWARE.\n\n */\n\n\n\n// External\n\nuse serde::Serialize;\n\n\n\n// STD\n\nuse std::collections::HashMap;\n\n\n\npub type Input = PacketData;\n\npub type Output = PacketData;\n\npub type Readonly = PacketData;\n\n\n\nmod builder;\n\n\n\npub use builder::{PacketBuilder, PacketData};\n\n\n\n/// Holds recursive values for the $i (input), $o (output), and $r (readonly) objects of a transaction packet.\n\n#[derive(Serialize, PartialEq, Eq, Debug, Clone)]\n\npub enum PacketValue {\n", "file_path": "src/packet_builder/mod.rs", "rank": 41, "score": 4.775762260091666 }, { "content": " /// tx_builder.selfsign();\n\n /// ```\n\n pub fn selfsign(&mut self) -> &mut Self {\n\n self.tx_data\n\n .insert(String::from(\"selfsign\"), json!(String::from(\"true\")));\n\n\n\n self\n\n }\n\n\n\n /// # Sign\n\n ///\n\n /// Using a given key and stream ID sign the transaction data packet.\n\n /// Generally this is used to add more signatures to a transaction, as it requires the build\n\n /// method to be run first.\n\n ///\n\n /// ```\n\n /// # use active_tx::{TransactionBuilder, packet_data, PacketBuilder, Key, signees};\n\n /// # use activeledger::key::EllipticCurve;\n\n /// # let input = PacketBuilder::new(packet_data!({\"data\": \"data\"})).build().unwrap();\n\n ///\n", "file_path": "src/transaction_builder/builder.rs", "rank": 42, "score": 4.59256045844319 }, { "content": " json[key] = data.clone();\n\n }\n\n }\n\n\n\n self.tx.replace(json.clone());\n\n\n\n Ok(json.to_string())\n\n }\n\n\n\n /// # Onboard transaction\n\n ///\n\n /// Given a key, generate a transaction to onboard the key to the ledger.\n\n ///\n\n /// ```\n\n /// # use activeledger::key::EllipticCurve;\n\n /// # use active_tx::{TransactionBuilder, Key};\n\n ///\n\n /// let key = Key::Ec(EllipticCurve::new(\"keyname\").unwrap());\n\n ///\n\n /// let tx = TransactionBuilder::onboard_tx(key).unwrap();\n", "file_path": "src/transaction_builder/builder.rs", "rank": 43, "score": 4.4454160343657225 }, { "content": "///\n\n/// // Bootstrapping, we need a key to sign the transaction packet\n\n/// let key = EllipticCurve::new(\"name\").unwrap();\n\n/// let key = Key::Ec(key);\n\n///\n\n/// // You can also wrap the creation call in the Key value\n\n/// // let key = Key::Ec(EllipticCurve::new(\"name\").unwrap());\n\n///\n\n/// // Using the signees macro we can create a Signees struct\n\n/// // This stores a map of keys and the assigned streamid and is used to sign\n\n/// // the packet later.\n\n/// let signees = signees![{\"streamid\" => key}];\n\n///\n\n/// // Next we need to create the input data, this is the data that will be inside $i: {}\n\n/// // To do this we use the included packet_data macro\n\n/// let input = packet_data!(\n\n/// {\n\n/// \"[streamid]\" : {\"input\": \"data\"}\n\n/// }\n\n/// );\n", "file_path": "src/transaction_builder/builder.rs", "rank": 45, "score": 4.322877835156357 }, { "content": " /// Most of the methods can be chained\n\n pub fn new_blank() -> TransactionBuilder {\n\n TransactionBuilder {\n\n packet_data: HashMap::new(),\n\n tx_data: HashMap::new(),\n\n packet: None,\n\n tx: None,\n\n sigs: HashMap::new(),\n\n }\n\n }\n\n\n\n /// # Transaction String\n\n ///\n\n /// Get the built transaction as a string.\n\n /// Note that the build method returns the same data.\n\n ///\n\n /// ```\n\n /// # use active_tx::{TransactionBuilder, packet_data, PacketBuilder, Key, signees};\n\n /// # use activeledger::key::EllipticCurve;\n\n ///\n", "file_path": "src/transaction_builder/builder.rs", "rank": 46, "score": 4.2093976811400236 }, { "content": " /// .build(signees)\n\n /// .unwrap();\n\n /// \n\n /// let tx = tx_builder.get_json().unwrap();\n\n /// ```\n\n pub fn get_json(&self) -> TxBuilderResult<Value> {\n\n match &self.tx {\n\n Some(tx) => Ok(tx.clone()),\n\n None => Err(TxBuilderError::TxBuildError(5000)),\n\n }\n\n }\n\n\n\n /// # Territoriality\n\n ///\n\n /// Set the territoriality value\n\n ///\n\n /// ```\n\n /// # use active_tx::{TransactionBuilder, packet_data, PacketBuilder, Key};\n\n /// # use activeledger::key::EllipticCurve;\n\n /// # let key = Key::Ec(EllipticCurve::new(\"keyname\").unwrap());\n", "file_path": "src/transaction_builder/builder.rs", "rank": 48, "score": 4.127427449352735 }, { "content": " ///\n\n /// It is required that input data be added to the builder before it will build the transaction.\n\n ///\n\n /// Additional data can be added using the other transaction builder methods.\n\n /// Once any additional data has been added, as well as the required input data,\n\n /// the build function can be run to generate the transaction and return a string of\n\n /// the transaction.\n\n /// The get method can be run to get the string again.\n\n ///\n\n /// Most of the methods can be chained\n\n pub fn new(namespace: &str, contract: &str) -> TransactionBuilder {\n\n let mut packet_data = HashMap::new();\n\n\n\n packet_data.insert(\"namespace\".to_string(), json!(namespace));\n\n packet_data.insert(\"contract\".to_string(), json!(contract));\n\n\n\n TransactionBuilder {\n\n packet_data,\n\n tx_data: HashMap::new(),\n\n packet: None,\n", "file_path": "src/transaction_builder/builder.rs", "rank": 49, "score": 4.062904584519438 }, { "content": " ///\n\n /// ```\n\n /// # use active_tx::{TransactionBuilder, packet_data, PacketBuilder, Key};\n\n /// # use activeledger::key::EllipticCurve;\n\n /// # let key = Key::Ec(EllipticCurve::new(\"keyname\").unwrap());\n\n /// # let input = PacketBuilder::new(packet_data!({\"data\": \"data\"})).build().unwrap();\n\n ///\n\n /// let mut tx_builder = TransactionBuilder::new_blank();\n\n ///\n\n /// tx_builder.namespace(\"namespace\");\n\n /// ```\n\n pub fn namespace(&mut self, namespace: &str) -> &mut Self {\n\n self.packet_data\n\n .insert(String::from(\"namespace\"), json!(namespace.to_string()));\n\n\n\n self\n\n }\n\n\n\n /// # Input\n\n ///\n", "file_path": "src/transaction_builder/builder.rs", "rank": 50, "score": 4.048684641279033 }, { "content": " /// It takes a key and a stream id, the stream id must match one provided in the input ($i) of\n\n /// the transaction packet.\n\n pub fn add(&mut self, key: Key, streamid: &str) -> &mut Self {\n\n let signee = Signee {\n\n streamid: streamid.to_string(),\n\n key,\n\n };\n\n\n\n self.keys.push(signee);\n\n\n\n self\n\n }\n\n\n\n /// # Selfsign\n\n ///\n\n /// This method is use for transactions that will be selfsigned.\n\n /// Instead of storing a related stream id it will use the keys name. This must still have a\n\n /// corresponding match in the input of the transaction packet.\n\n pub fn add_selfsign(&mut self, key: Key) -> &mut Self {\n\n let name = match &key {\n", "file_path": "src/transaction_builder/signee.rs", "rank": 51, "score": 4.042355050937646 }, { "content": "///\n\n/// // Now we need to take the PacketValue created by the macro and pass it to the builder\n\n/// // The builder will convert it to a String and a serde_json Value and store both.\n\n/// // Should you wish to do something with this data after it is built you can retrieve it\n\n/// // using the corresponding methods.\n\n/// let mut input_builder = PacketBuilder::new(input);\n\n/// let input_data = input_builder.build().unwrap();\n\n///\n\n/// // The build method can also be chained onto the creation call\n\n/// // let input_data = PacketBuilder::new(input).build().unwrap();\n\n///\n\n/// // Now that we have the packet sorted out we need to pass the data to the transaction builder.\n\n/// // The transaction must contain a namespace and contract so these are passed directly into\n\n/// // the creation method.\n\n/// // To add the input data we call the input() method and pass it the input_data from earlier.\n\n/// //\n\n/// // Now the builder has all the data it needs to build the contract.\n\n/// // Calling the build function we pass it the signees we defined earlier, the keys will be used\n\n/// // to sign the packet once it has been built.\n\n/// // Calling the .build() method will return a string of the transaction.\n", "file_path": "src/transaction_builder/builder.rs", "rank": 52, "score": 3.7911453695212125 }, { "content": "/// {\n\n/// \"$territoriality\" : \"\",\n\n/// \"$tx\": {\n\n/// \"$namespace\": \"[contract namespace location]\"\n\n/// \"$contract\": \"[contract id]\"\n\n/// \"$entry\": \"[contract entry point]\"\n\n/// \"$i\": {\n\n/// \"[streamid]\": {\"input data\": \"here\"}\n\n/// },\n\n/// \"$o\": {},\n\n/// \"$r\": {}\n\n/// },\n\n/// \"$selfsign\" : false,\n\n/// \"$sigs\": {\n\n/// \"[streamid]\" : \"key public pem\"\n\n/// }\n\n///\n\n/// }\n\n/// ```\n\n/// We won't go into much detail about all of the separate parts here as that is in documentation linked\n", "file_path": "src/transaction_builder/builder.rs", "rank": 53, "score": 3.457343373852415 }, { "content": "pub struct PacketData {\n\n data: Option<PacketValue>,\n\n json: Option<Value>,\n\n is_json: bool,\n\n built: Option<String>,\n\n}\n\n\n\nimpl PacketBuilder {\n\n /// # New\n\n ///\n\n /// Generate a new builder and pass it an [`PacketValue`] for consumption.\n\n pub fn new(data: PacketValue) -> PacketBuilder {\n\n let mut ior_data = PacketData::new();\n\n\n\n // If the data provided is an object (PacketValue::Object(HashMap)) use the add_map function\n\n // to add it.\n\n if let PacketValue::Object(data) = data {\n\n ior_data.add_map(data);\n\n } else {\n\n ior_data.add(data);\n", "file_path": "src/packet_builder/builder.rs", "rank": 54, "score": 3.3535571659128784 }, { "content": " /// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n /// tx_builder.input(input).unwrap();\n\n ///\n\n /// let signees = signees![{streamid => key}];\n\n ///\n\n /// let tx = tx_builder.build(signees).unwrap();\n\n ///\n\n /// ```\n\n pub fn build(&mut self, signees: Signees) -> TxBuilderResult<String> {\n\n let mut json = json!({});\n\n\n\n // Contract, namespace and input are all required, if any are missing throw an error\n\n let contract = match self.packet_data.get(\"contract\") {\n\n Some(contract) => contract,\n\n None => return Err(TxBuilderError::TxBuildError(5006)),\n\n };\n\n\n\n let namespace = match self.packet_data.get(\"namespace\") {\n\n Some(namespace) => namespace,\n\n None => return Err(TxBuilderError::TxBuildError(5007)),\n", "file_path": "src/transaction_builder/builder.rs", "rank": 55, "score": 3.293822703800454 }, { "content": " pub fn new(contract: Value, namespace: Value, input: Value) -> TransactionBody {\n\n // Init all as None to create base\n\n TransactionBody {\n\n entry: None,\n\n contract: contract,\n\n namespace: namespace,\n\n input: input,\n\n output: None,\n\n readonly: None,\n\n json: None,\n\n }\n\n }\n\n\n\n pub fn add(&mut self, key: &str, data: Value) -> &mut Self {\n\n match key {\n\n \"entry\" => self.entry = Some(data),\n\n \"output\" => self.output = Some(data),\n\n \"readonly\" => self.readonly = Some(data),\n\n _ => unreachable!(),\n\n };\n", "file_path": "src/transaction_builder/body.rs", "rank": 56, "score": 2.9710252554603294 }, { "content": "\n\n self\n\n }\n\n\n\n pub fn build(&mut self) -> Value {\n\n let mut json = json!({});\n\n\n\n json[\"$contract\"] = json!(self.contract.clone());\n\n json[\"$namespace\"] = json!(self.namespace.clone());\n\n json[\"$i\"] = self.input.clone();\n\n\n\n if let Some(entry) = &self.entry {\n\n json[\"$entry\"] = json!(entry);\n\n }\n\n\n\n if let Some(output) = &self.output {\n\n json[\"$o\"] = json!(output);\n\n }\n\n\n\n if let Some(readonly) = &self.readonly {\n", "file_path": "src/transaction_builder/body.rs", "rank": 57, "score": 2.887336371001325 }, { "content": "//! .build(signees)\n\n//! .unwrap();\n\n//! # }\n\n//! ```\n\n//!\n\n//! For more information on the usage of this crate see the [`TransactionBuilder`] documentation.\n\n\n\nmod error;\n\nmod macros;\n\nmod packet_builder;\n\nmod transaction_builder;\n\n\n\npub use error::{TxBuilderError, TxBuilderResult};\n\npub use packet_builder::{PacketBuilder, PacketData, PacketValue};\n\npub use transaction_builder::{Key, KeyType, Signees, TransactionBuilder};\n", "file_path": "src/lib.rs", "rank": 58, "score": 2.7690907536864957 }, { "content": " holder.push(data);\n\n }\n\n }\n\n _ => return Err(TxBuilderError::JsonError(2000)),\n\n };\n\n Ok(json!(holder))\n\n }\n\n\n\n /// Walk an object value and convert it to a JSON Value\n\n fn object_tojson(map: &HashMap<String, PacketValue>) -> TxBuilderResult<Value> {\n\n let mut json = json!({});\n\n\n\n for (key, value) in map.iter() {\n\n let data = match value {\n\n PacketValue::String(value) => json!(value),\n\n PacketValue::Object(object) => {\n\n let data = match PacketBuilder::object_tojson(object) {\n\n Ok(data) => data,\n\n Err(_) => return Err(TxBuilderError::JsonError(2001)),\n\n };\n", "file_path": "src/packet_builder/builder.rs", "rank": 59, "score": 2.635732931549373 }, { "content": "//! # let key = Key::Ec(EllipticCurve::new(\"\").unwrap());\n\n//! #\n\n//!\n\n//! let signees = signees![{streamid => key}];\n\n//!\n\n//! let tx = tx_builder\n\n//! .input(input_data)\n\n//! .unwrap()\n\n//! .build(signees)\n\n//! .unwrap();\n\n//! # }\n\n//! ```\n\n//!\n\n\n\nmod body;\n\nmod builder;\n\nmod signee;\n\n\n\npub use builder::{Key, KeyType, TransactionBuilder};\n\npub use signee::Signees;\n", "file_path": "src/transaction_builder/mod.rs", "rank": 61, "score": 2.5708798502579455 }, { "content": "/// // This string can be sent to the ledger!\n\n/// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n/// tx_builder.input(input_data).unwrap();\n\n/// let tx = tx_builder.build(signees).unwrap();\n\n///\n\n/// // To generate the transaction all in one go you can chain the methods like so\n\n/// // let tx = TransactionBuilder::new(\"namespace\", \"contract\")\n\n/// // .input(input_data)\n\n/// // .unwrap()\n\n/// // .build(signees)\n\n/// // .unwrap();\n\n/// ```\n\n/// ### Additional data\n\n///\n\n/// The additional data is:\n\n///\n\n/// **Packet**\n\n/// * Output\n\n/// * Readonly\n\n/// * Entry\n", "file_path": "src/transaction_builder/builder.rs", "rank": 62, "score": 2.564788634971817 }, { "content": " };\n\n\n\n let input = match self.packet_data.get(\"input\") {\n\n Some(input) => input,\n\n None => return Err(TxBuilderError::TxBuildError(5008)),\n\n };\n\n\n\n let mut tx = TransactionBody::new(contract.clone(), namespace.clone(), input.clone());\n\n\n\n let checked = [\"contract\", \"namespace\", \"input\"];\n\n\n\n // Loop packet_data map and add additional data\n\n for (key, val) in self.packet_data.iter() {\n\n // Ignore if key in checked\n\n if !checked.iter().any(|v| v == &key) {\n\n tx.add(key, val.clone());\n\n }\n\n }\n\n\n\n self.packet.replace(tx.clone());\n", "file_path": "src/transaction_builder/builder.rs", "rank": 63, "score": 2.4951058344048196 }, { "content": " String(String),\n\n Array(Vec<PacketValue>),\n\n Object(HashMap<String, PacketValue>),\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\n\n use crate::*;\n\n use serde_json::json;\n\n\n\n #[test]\n\n fn input_macro() {\n\n let object = packet_data!({\"array\": [\"array\", \"of\", \"strings\"], \"subobj\": {\"object style\" : \"in brackets\"}});\n\n let mut builder = PacketBuilder::new(object);\n\n\n\n let input = builder.build().unwrap();\n\n\n\n println!(\"Macro: \\n{}\\n\", input.get().unwrap());\n\n }\n", "file_path": "src/packet_builder/mod.rs", "rank": 64, "score": 2.4520179881895734 }, { "content": "/// ```\n\n///\n\n/// [`PacketBuilder`]: struct.PacketBuilder.html\n\n\n\npub struct TransactionBuilder {\n\n /*\n\n Data for $tx object\n\n entry,\n\n contract,\n\n namespace,\n\n input,\n\n output,\n\n readonly\n\n */\n\n packet_data: HashMap<String, Value>,\n\n\n\n /*\n\n territoriality,\n\n selfsign,\n\n */\n", "file_path": "src/transaction_builder/builder.rs", "rank": 65, "score": 2.410756304648827 }, { "content": "\n\n let signees = signees!(key);\n\n\n\n let mut tx_builder = TransactionBuilder::new(\"default\", \"onboard\");\n\n let tx = tx_builder.selfsign().input(input)?.build(signees)?;\n\n\n\n Ok(tx.to_string())\n\n }\n\n\n\n /// # Onboard transaction\n\n ///\n\n /// Given a key type and name, generate a key and use it to build a transaction to onboard that key to the ledger.\n\n ///\n\n /// Returns the generated key and the transaction\n\n /// ```\n\n /// # use active_tx::{TransactionBuilder, KeyType};\n\n ///\n\n /// let (key, tx) = TransactionBuilder::generate_onboard_tx(KeyType::EC, \"keyname\").unwrap();\n\n /// ```\n\n pub fn generate_onboard_tx(\n", "file_path": "src/transaction_builder/builder.rs", "rank": 67, "score": 2.256412714556305 }, { "content": " /// # let input = PacketBuilder::new(packet_data!({\"data\": \"data\"})).build().unwrap();\n\n ///\n\n /// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n ///\n\n /// tx_builder.territoriality(\"territory\");\n\n /// ```\n\n pub fn territoriality(&mut self, territoriality: &str) -> &mut Self {\n\n self.tx_data.insert(\n\n String::from(\"territoriality\"),\n\n json!(territoriality.to_string()),\n\n );\n\n\n\n self\n\n }\n\n\n\n /// # Entry\n\n ///\n\n /// Set the entry value\n\n ///\n\n /// ```\n", "file_path": "src/transaction_builder/builder.rs", "rank": 69, "score": 2.0456077194625677 }, { "content": " 5005 => \"Packet data not built yet\",\n\n 5006 => \"Contract not set\",\n\n 5007 => \"Namespace not set\",\n\n 5008 => \"Input not set\",\n\n _ => \"Unknown Error\",\n\n }\n\n }\n\n\n\n fn get_txgenerate_error(code: &u16) -> &str {\n\n match code {\n\n 6000 => \"Error generating RSA key\",\n\n 6001 => \"Error generating Elliptic Curve key\",\n\n _ => \"Unknown Error\",\n\n }\n\n }\n\n\n\n fn get_key_error(code: &u16) -> &str {\n\n match code {\n\n 7000 => \"Error signing data with Elliptic Curve key\",\n\n 7001 => \"Error signing data with RSA key\",\n\n 7002 => \"Error getting keys PEM\",\n\n _ => \"Unknown Error\",\n\n }\n\n }\n\n}\n", "file_path": "src/error.rs", "rank": 71, "score": 1.8044488572183175 }, { "content": " /// let streamid = \"id\";\n\n /// let streamid2 = \"id2\";\n\n ///\n\n /// let key = Key::Ec(EllipticCurve::new(streamid).unwrap());\n\n /// let key2 = Key::Ec(EllipticCurve::new(streamid2).unwrap());\n\n ///\n\n /// let signees = signees![{streamid => key}];\n\n ///\n\n /// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n /// tx_builder.input(input)\n\n /// .unwrap()\n\n /// .build(signees)\n\n /// .unwrap();\n\n ///\n\n /// let signees2 = signees![{streamid2 => key2}];\n\n ///\n\n /// tx_builder.sign(signees2);\n\n /// ```\n\n pub fn sign(&mut self, signees: Signees) -> TxBuilderResult<&mut Self> {\n\n let signees_array = signees.get();\n", "file_path": "src/transaction_builder/builder.rs", "rank": 72, "score": 1.7231894069610139 }, { "content": " /// let key = Key::Ec(EllipticCurve::new(\"keyname\").unwrap());\n\n ///\n\n /// let input = PacketBuilder::new(packet_data!({\"data\": \"data\"})).build().unwrap();\n\n ///\n\n /// let signees = signees![{\"streamid\" => key}];\n\n ///\n\n /// let mut tx_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n /// tx_builder\n\n /// .input(input)\n\n /// .unwrap()\n\n /// .build(signees)\n\n /// .unwrap();\n\n ///\n\n /// let tx = tx_builder.get().unwrap();\n\n /// ```\n\n pub fn get(&self) -> TxBuilderResult<String> {\n\n match &self.tx {\n\n Some(tx) => Ok(tx.to_string()),\n\n None => Err(TxBuilderError::TxBuildError(5000)),\n\n }\n", "file_path": "src/transaction_builder/builder.rs", "rank": 73, "score": 1.710352403618935 }, { "content": " let signees = signees![{streamid => Key::Ec(key)}, {streamid2 => Key::Ec(key2)}];\n\n\n\n let built_input = PacketBuilder::new(input).build().unwrap();\n\n let built_output = PacketBuilder::new(output).build().unwrap();\n\n let built_readonly = PacketBuilder::new(readonly).build().unwrap();\n\n\n\n let mut transaction_builder = TransactionBuilder::new(\"namespace\", \"contract\");\n\n\n\n let tx = transaction_builder\n\n .entry(\"entry\")\n\n .territoriality(\"terry\")\n\n .selfsign()\n\n .input(built_input)\n\n .unwrap()\n\n .output(built_output)\n\n .unwrap()\n\n .readonly(built_readonly)\n\n .unwrap()\n\n .build(signees)\n\n .unwrap();\n", "file_path": "src/transaction_builder/mod.rs", "rank": 74, "score": 1.6852437537951888 }, { "content": " /// # From string\n\n /// Consumes a string reference and converts it into a [`PacketValue`]\n\n pub fn from_string(data: &str) -> PacketValue {\n\n PacketValue::String(data.to_string())\n\n }\n\n}\n\n\n\n// Private functions\n\nimpl PacketBuilder {\n\n /// Walk an array value and convert it to a JSON Value\n\n fn array_tojson(array: &PacketValue) -> TxBuilderResult<Value> {\n\n let mut holder: Vec<Value> = Vec::new();\n\n match array {\n\n PacketValue::Array(array) => {\n\n for elem in array.iter() {\n\n let data = match elem {\n\n PacketValue::String(value) => json!(value),\n\n PacketValue::Object(object) => PacketBuilder::object_tojson(object)?,\n\n PacketValue::Array(_) => PacketBuilder::array_tojson(elem)?,\n\n };\n", "file_path": "src/packet_builder/builder.rs", "rank": 75, "score": 1.68302830727057 }, { "content": "/// These structs are intended to make it simpler to sign transaction packets.\n\n///\n\n/// The Signees object holds a vector of Signee's, the Signee object contains the streamid and key.\n\n/// *Note:* The streamid could also be the key name for a selfsign transaction e.g onboarding.\n\n///\n\n/// It is recommended that the macro [signees!][macro] is used to generate these structures.\n\n/// To see example usage the macro please see its relevant documentation [here][macro]\n\n///\n\n/// [macro]: macro.signees.html\n\nimpl Signees {\n\n /// # New\n\n ///\n\n /// This method generates a new Signees struct\n\n pub fn new() -> Signees {\n\n Signees { keys: vec![] }\n\n }\n\n\n\n /// # Add\n\n ///\n\n /// This method is the general add method.\n", "file_path": "src/transaction_builder/signee.rs", "rank": 76, "score": 1.628888939997191 }, { "content": " let signature = match key.sign(&tx.to_string()) {\n\n Ok(sig) => sig,\n\n Err(_) => return Err(TxBuilderError::KeyError(7000)),\n\n };\n\n\n\n Ok(signature)\n\n }\n\n\n\n /// Sign data using RSA\n\n fn sign_rsa(tx: &str, key: RSA) -> TxBuilderResult<String> {\n\n let signature = match key.sign(&tx.to_string()) {\n\n Ok(sig) => sig,\n\n Err(_) => return Err(TxBuilderError::KeyError(7001)),\n\n };\n\n\n\n Ok(signature)\n\n }\n\n\n\n /// Get the keys public PEM string\n\n fn get_pem(key: Key) -> TxBuilderResult<String> {\n", "file_path": "src/transaction_builder/builder.rs", "rank": 77, "score": 1.5922121953876425 }, { "content": " };\n\n\n\n let tx = TransactionBuilder::onboard_tx(key.clone())?;\n\n\n\n Ok((key, tx))\n\n }\n\n}\n\n\n\n// Private functions\n\nimpl TransactionBuilder {\n\n /// Match key type then pass to signing function\n\n fn sign_internal(data: &str, key: Key) -> TxBuilderResult<String> {\n\n match key {\n\n Key::Rsa(key) => TransactionBuilder::sign_rsa(data, key),\n\n Key::Ec(key) => TransactionBuilder::sign_ec(data, key),\n\n }\n\n }\n\n\n\n /// Sign data using elliptic curve\n\n fn sign_ec(tx: &str, key: EllipticCurve) -> TxBuilderResult<String> {\n", "file_path": "src/transaction_builder/builder.rs", "rank": 78, "score": 1.5458042293648067 } ]
Rust
src/librand/distributions/normal.rs
oxidation/rust
f1bb6c2f46f08c1d7b6d695f5b3cf93142cb8860
use core::num::Float; use {Rng, Rand, Open01}; use distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample}; #[derive(Copy)] pub struct StandardNormal(pub f64); impl Rand for StandardNormal { fn rand<R:Rng>(rng: &mut R) -> StandardNormal { #[inline] fn pdf(x: f64) -> f64 { (-x*x/2.0).exp() } #[inline] fn zero_case<R:Rng>(rng: &mut R, u: f64) -> f64 { let mut x = 1.0f64; let mut y = 0.0f64; while -2.0 * y < x * x { let Open01(x_) = rng.gen::<Open01<f64>>(); let Open01(y_) = rng.gen::<Open01<f64>>(); x = x_.ln() / ziggurat_tables::ZIG_NORM_R; y = y_.ln(); } if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x } } StandardNormal(ziggurat( rng, true, &ziggurat_tables::ZIG_NORM_X, &ziggurat_tables::ZIG_NORM_F, pdf, zero_case)) } } #[derive(Copy)] pub struct Normal { mean: f64, std_dev: f64, } impl Normal { pub fn new(mean: f64, std_dev: f64) -> Normal { assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0"); Normal { mean: mean, std_dev: std_dev } } } impl Sample<f64> for Normal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Normal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(n) = rng.gen::<StandardNormal>(); self.mean + self.std_dev * n } } #[derive(Copy)] pub struct LogNormal { norm: Normal } impl LogNormal { pub fn new(mean: f64, std_dev: f64) -> LogNormal { assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0"); LogNormal { norm: Normal::new(mean, std_dev) } } } impl Sample<f64> for LogNormal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for LogNormal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.norm.ind_sample(rng).exp() } } #[cfg(test)] mod tests { use std::prelude::v1::*; use distributions::{Sample, IndependentSample}; use super::{Normal, LogNormal}; #[test] fn test_normal() { let mut norm = Normal::new(10.0, 10.0); let mut rng = ::test::rng(); for _ in 0..1000 { norm.sample(&mut rng); norm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_normal_invalid_sd() { Normal::new(10.0, -1.0); } #[test] fn test_log_normal() { let mut lnorm = LogNormal::new(10.0, 10.0); let mut rng = ::test::rng(); for _ in 0..1000 { lnorm.sample(&mut rng); lnorm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_log_normal_invalid_sd() { LogNormal::new(10.0, -1.0); } } #[cfg(test)] mod bench { extern crate test; use std::prelude::v1::*; use self::test::Bencher; use std::mem::size_of; use distributions::{Sample}; use super::Normal; #[bench] fn rand_normal(b: &mut Bencher) { let mut rng = ::test::weak_rng(); let mut normal = Normal::new(-2.71828, 3.14159); b.iter(|| { for _ in 0..::RAND_BENCH_N { normal.sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } }
use core::num::Float; use {Rng, Rand, Open01}; use distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample}; #[derive(Copy)] pub struct StandardNormal(pub f64); impl Rand for StandardNormal { fn rand<R:Rng>(rng: &mut R) -> StandardNormal { #[inline] fn pdf(
} #[derive(Copy)] pub struct Normal { mean: f64, std_dev: f64, } impl Normal { pub fn new(mean: f64, std_dev: f64) -> Normal { assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0"); Normal { mean: mean, std_dev: std_dev } } } impl Sample<f64> for Normal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Normal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(n) = rng.gen::<StandardNormal>(); self.mean + self.std_dev * n } } #[derive(Copy)] pub struct LogNormal { norm: Normal } impl LogNormal { pub fn new(mean: f64, std_dev: f64) -> LogNormal { assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0"); LogNormal { norm: Normal::new(mean, std_dev) } } } impl Sample<f64> for LogNormal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for LogNormal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.norm.ind_sample(rng).exp() } } #[cfg(test)] mod tests { use std::prelude::v1::*; use distributions::{Sample, IndependentSample}; use super::{Normal, LogNormal}; #[test] fn test_normal() { let mut norm = Normal::new(10.0, 10.0); let mut rng = ::test::rng(); for _ in 0..1000 { norm.sample(&mut rng); norm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_normal_invalid_sd() { Normal::new(10.0, -1.0); } #[test] fn test_log_normal() { let mut lnorm = LogNormal::new(10.0, 10.0); let mut rng = ::test::rng(); for _ in 0..1000 { lnorm.sample(&mut rng); lnorm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_log_normal_invalid_sd() { LogNormal::new(10.0, -1.0); } } #[cfg(test)] mod bench { extern crate test; use std::prelude::v1::*; use self::test::Bencher; use std::mem::size_of; use distributions::{Sample}; use super::Normal; #[bench] fn rand_normal(b: &mut Bencher) { let mut rng = ::test::weak_rng(); let mut normal = Normal::new(-2.71828, 3.14159); b.iter(|| { for _ in 0..::RAND_BENCH_N { normal.sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } }
x: f64) -> f64 { (-x*x/2.0).exp() } #[inline] fn zero_case<R:Rng>(rng: &mut R, u: f64) -> f64 { let mut x = 1.0f64; let mut y = 0.0f64; while -2.0 * y < x * x { let Open01(x_) = rng.gen::<Open01<f64>>(); let Open01(y_) = rng.gen::<Open01<f64>>(); x = x_.ln() / ziggurat_tables::ZIG_NORM_R; y = y_.ln(); } if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x } } StandardNormal(ziggurat( rng, true, &ziggurat_tables::ZIG_NORM_X, &ziggurat_tables::ZIG_NORM_F, pdf, zero_case)) }
function_block-function_prefixed
[ { "content": "/// Randomly sample up to `amount` elements from an iterator.\n\n///\n\n/// # Example\n\n///\n\n/// ```rust\n\n/// use std::rand::{thread_rng, sample};\n\n///\n\n/// let mut rng = thread_rng();\n\n/// let sample = sample(&mut rng, 1..100, 5);\n\n/// println!(\"{:?}\", sample);\n\n/// ```\n\npub fn sample<T, I: Iterator<Item=T>, R: Rng>(rng: &mut R,\n\n mut iter: I,\n\n amount: usize) -> Vec<T> {\n\n let mut reservoir: Vec<T> = iter.by_ref().take(amount).collect();\n\n for (i, elem) in iter.enumerate() {\n\n let k = rng.gen_range(0, i + 1 + amount);\n\n if k < amount {\n\n reservoir[k] = elem;\n\n }\n\n }\n\n return reservoir;\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use prelude::v1::*;\n\n use super::{Rng, thread_rng, random, SeedableRng, StdRng, sample};\n\n use iter::{order, repeat};\n\n\n\n struct ConstRng { i: u64 }\n", "file_path": "src/libstd/rand/mod.rs", "rank": 0, "score": 630131.5019250188 }, { "content": "fn random_gradient<R: Rng>(r: &mut R) -> Vec2 {\n\n let v = PI * 2.0 * r.gen();\n\n Vec2 { x: v.cos(), y: v.sin() }\n\n}\n\n\n", "file_path": "src/test/bench/noise.rs", "rank": 1, "score": 457699.63579594606 }, { "content": "/// Copies the entire contents of a reader into a writer.\n\n///\n\n/// This function will continuously read data from `r` and then write it into\n\n/// `w` in a streaming fashion until `r` returns EOF.\n\n///\n\n/// On success the total number of bytes that were copied from `r` to `w` is\n\n/// returned.\n\n///\n\n/// # Errors\n\n///\n\n/// This function will return an error immediately if any call to `read` or\n\n/// `write` returns an error. All instances of `ErrorKind::Interrupted` are\n\n/// handled by this function and the underlying operation is retried.\n\npub fn copy<R: Read, W: Write>(r: &mut R, w: &mut W) -> io::Result<u64> {\n\n let mut buf = [0; super::DEFAULT_BUF_SIZE];\n\n let mut written = 0;\n\n loop {\n\n let len = match r.read(&mut buf) {\n\n Ok(0) => return Ok(written),\n\n Ok(len) => len,\n\n Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,\n\n Err(e) => return Err(e),\n\n };\n\n try!(w.write_all(&buf[..len]));\n\n written += len as u64;\n\n }\n\n}\n\n\n\n/// A reader which is always at EOF.\n\npub struct Empty { _priv: () }\n\n\n", "file_path": "src/libstd/io/util.rs", "rank": 2, "score": 417371.35095676593 }, { "content": "/// Copies all data from a `Reader` to a `Writer`.\n\npub fn copy<R: Reader, W: Writer>(r: &mut R, w: &mut W) -> old_io::IoResult<()> {\n\n let mut buf = [0; super::DEFAULT_BUF_SIZE];\n\n loop {\n\n let len = match r.read(&mut buf) {\n\n Ok(len) => len,\n\n Err(ref e) if e.kind == old_io::EndOfFile => return Ok(()),\n\n Err(e) => return Err(e),\n\n };\n\n try!(w.write_all(&buf[..len]));\n\n }\n\n}\n\n\n\n/// An adaptor converting an `Iterator<u8>` to a `Reader`.\n\n#[derive(Clone, Debug)]\n\npub struct IterReader<T> {\n\n iter: T,\n\n}\n\n\n\nimpl<T: Iterator<Item=u8>> IterReader<T> {\n\n /// Creates a new `IterReader` which will read from the specified\n", "file_path": "src/libstd/old_io/util.rs", "rank": 3, "score": 414799.67045214283 }, { "content": "pub fn main() { let mut r: R<int> = R {v: Vec::new()}; r.v = f(); }\n", "file_path": "src/test/run-pass/alloca-from-derived-tydesc.rs", "rank": 4, "score": 396703.40391599794 }, { "content": "struct YCombinator<F,A,R> {\n\n func: F,\n\n marker: CovariantType<(A,R)>,\n\n}\n\n\n\nimpl<F,A,R> YCombinator<F,A,R> {\n\n fn new(f: F) -> YCombinator<F,A,R> {\n\n YCombinator { func: f, marker: CovariantType }\n\n }\n\n}\n\n\n\nimpl<A,R,F : FnMut(&mut FnMut(A) -> R, A) -> R> FnMut<(A,)> for YCombinator<F,A,R> {\n\n type Output = R;\n\n\n\n extern \"rust-call\" fn call_mut(&mut self, (arg,): (A,)) -> R {\n\n (self.func)(self, arg)\n\n //~^ ERROR cannot borrow `*self` as mutable more than once at a time\n\n }\n\n}\n\n\n", "file_path": "src/test/compile-fail/unboxed-closures-recursive-fn-using-fn-mut.rs", "rank": 5, "score": 390758.71560984524 }, { "content": "fn mult_AtAv(v: &[f64], out: &mut [f64], tmp: &mut [f64]) {\n\n mult_Av(v, tmp);\n\n mult_Atv(tmp, out);\n\n}\n\n\n", "file_path": "src/test/bench/shootout-spectralnorm.rs", "rank": 6, "score": 376061.31573052856 }, { "content": "pub fn expand_deriving_rand<F>(cx: &mut ExtCtxt,\n\n span: Span,\n\n mitem: &MetaItem,\n\n item: &Item,\n\n push: F) where\n\n F: FnOnce(P<Item>),\n\n{\n\n cx.span_warn(span,\n\n \"`#[derive(Rand)]` is deprecated in favour of `#[derive_Rand]` from \\\n\n `rand_macros` on crates.io\");\n\n\n\n if !cx.use_std {\n\n // FIXME(#21880): lift this requirement.\n\n cx.span_err(span, \"this trait cannot be derived with #![no_std]\");\n\n return;\n\n }\n\n\n\n let trait_def = TraitDef {\n\n span: span,\n\n attributes: Vec::new(),\n", "file_path": "src/libsyntax/ext/deriving/rand.rs", "rank": 7, "score": 375325.8496181396 }, { "content": "pub fn read<T, L, R>(fd: sock_t, deadline: u64, mut lock: L, mut read: R) -> IoResult<uint> where\n\n L: FnMut() -> T,\n\n R: FnMut(bool) -> libc::c_int,\n\n{\n\n let mut ret = -1;\n\n if deadline == 0 {\n\n ret = retry(|| read(false));\n\n }\n\n\n\n if deadline != 0 || (ret == -1 && wouldblock()) {\n\n let deadline = match deadline {\n\n 0 => None,\n\n n => Some(n),\n\n };\n\n loop {\n\n // With a timeout, first we wait for the socket to become\n\n // readable using select(), specifying the relevant timeout for\n\n // our previously set deadline.\n\n try!(await(&[fd], deadline, Readable));\n\n\n", "file_path": "src/libstd/sys/common/net.rs", "rank": 8, "score": 374858.0072281785 }, { "content": "/// The most general form of the `finally` functions. The function\n\n/// `try_fn` will be invoked first; whether or not it panics, the\n\n/// function `finally_fn` will be invoked next. The two parameters\n\n/// `mutate` and `drop` are used to thread state through the two\n\n/// closures. `mutate` is used for any shared, mutable state that both\n\n/// closures require access to; `drop` is used for any state that the\n\n/// `try_fn` requires ownership of.\n\n///\n\n/// **WARNING:** While shared, mutable state between the try and finally\n\n/// function is often necessary, one must be very careful; the `try`\n\n/// function could have panicked at any point, so the values of the shared\n\n/// state may be inconsistent.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use std::finally::try_finally;\n\n///\n\n/// struct State<'a> { buffer: &'a mut [u8], len: usize }\n\n/// # let mut buf = [];\n\n/// let mut state = State { buffer: &mut buf, len: 0 };\n\n/// try_finally(\n\n/// &mut state, (),\n\n/// |state, ()| {\n\n/// // use state.buffer, state.len\n\n/// },\n\n/// |state| {\n\n/// // use state.buffer, state.len to cleanup\n\n/// })\n\n/// ```\n\npub fn try_finally<T, U, R, F, G>(mutate: &mut T, drop: U, try_fn: F, finally_fn: G) -> R where\n\n F: FnOnce(&mut T, U) -> R,\n\n G: FnMut(&mut T),\n\n{\n\n let f = Finallyalizer {\n\n mutate: mutate,\n\n dtor: finally_fn,\n\n };\n\n try_fn(&mut *f.mutate, drop)\n\n}\n\n\n", "file_path": "src/libcore/finally.rs", "rank": 9, "score": 367485.2659272542 }, { "content": "/// Retrieve the lazily-initialized thread-local random number\n\n/// generator, seeded by the system. Intended to be used in method\n\n/// chaining style, e.g. `thread_rng().gen::<int>()`.\n\n///\n\n/// The RNG provided will reseed itself from the operating system\n\n/// after generating a certain amount of randomness.\n\n///\n\n/// The internal RNG used is platform and architecture dependent, even\n\n/// if the operating system random number generator is rigged to give\n\n/// the same sequence always. If absolute consistency is required,\n\n/// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.\n\npub fn thread_rng() -> ThreadRng {\n\n // used to make space in TLS for a random number generator\n\n thread_local!(static THREAD_RNG_KEY: Rc<RefCell<ThreadRngInner>> = {\n\n let r = match StdRng::new() {\n\n Ok(r) => r,\n\n Err(e) => panic!(\"could not initialize thread_rng: {}\", e)\n\n };\n\n let rng = reseeding::ReseedingRng::new(r,\n\n THREAD_RNG_RESEED_THRESHOLD,\n\n ThreadRngReseeder);\n\n Rc::new(RefCell::new(rng))\n\n });\n\n\n\n ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.clone()) }\n\n}\n\n\n\nimpl Rng for ThreadRng {\n\n fn next_u32(&mut self) -> u32 {\n\n self.rng.borrow_mut().next_u32()\n\n }\n", "file_path": "src/libstd/rand/mod.rs", "rank": 10, "score": 363384.747107976 }, { "content": "/// Create a weak random number generator with a default algorithm and seed.\n\n///\n\n/// It returns the fastest `Rng` algorithm currently available in Rust without\n\n/// consideration for cryptography or security. If you require a specifically\n\n/// seeded `Rng` for consistency over time you should pick one algorithm and\n\n/// create the `Rng` yourself.\n\n///\n\n/// This will read randomness from the operating system to seed the\n\n/// generator.\n\npub fn weak_rng() -> XorShiftRng {\n\n match OsRng::new() {\n\n Ok(mut r) => r.gen(),\n\n Err(e) => panic!(\"weak_rng: failed to create seeded RNG: {:?}\", e)\n\n }\n\n}\n\n\n", "file_path": "src/libstd/rand/mod.rs", "rank": 11, "score": 358279.3600666014 }, { "content": "/// Return the next token from the TtReader.\n\n/// EFFECT: advances the reader's token field\n\npub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan {\n\n // FIXME(pcwalton): Bad copy?\n\n let ret_val = TokenAndSpan {\n\n tok: r.cur_tok.clone(),\n\n sp: r.cur_span.clone(),\n\n };\n\n loop {\n\n match r.crate_name_next.take() {\n\n None => (),\n\n Some(sp) => {\n\n r.cur_span = sp;\n\n r.cur_tok = token::Ident(r.imported_from.unwrap(), token::Plain);\n\n return ret_val;\n\n },\n\n }\n\n let should_pop = match r.stack.last() {\n\n None => {\n\n assert_eq!(ret_val.tok, token::Eof);\n\n return ret_val;\n\n }\n", "file_path": "src/libsyntax/ext/tt/transcribe.rs", "rank": 12, "score": 354569.60261212965 }, { "content": "pub fn walk_inlined_item<'v,V>(visitor: &mut V, item: &'v InlinedItem)\n\n where V: Visitor<'v> {\n\n match *item {\n\n IIItem(ref i) => visitor.visit_item(&**i),\n\n IIForeign(ref i) => visitor.visit_foreign_item(&**i),\n\n IITraitItem(_, ref ti) => visitor.visit_trait_item(ti),\n\n IIImplItem(_, MethodImplItem(ref m)) => {\n\n walk_method_helper(visitor, &**m)\n\n }\n\n IIImplItem(_, TypeImplItem(ref typedef)) => {\n\n visitor.visit_ident(typedef.span, typedef.ident);\n\n visitor.visit_ty(&*typedef.typ);\n\n }\n\n }\n\n}\n\n\n\n\n", "file_path": "src/libsyntax/visit.rs", "rank": 13, "score": 353196.9058245681 }, { "content": "pub fn main() {\n\n let _x = inline_dtor::Foo;\n\n}\n", "file_path": "src/test/run-pass/use_inline_dtor.rs", "rank": 14, "score": 353030.5802766742 }, { "content": "fn mult_Av(v: &[f64], out: &mut [f64]) {\n\n parallel(out, |start, out| mult(v, out, start, |i, j| A(i, j)));\n\n}\n\n\n", "file_path": "src/test/bench/shootout-spectralnorm.rs", "rank": 15, "score": 352990.9226944759 }, { "content": "fn mult_Atv(v: &[f64], out: &mut [f64]) {\n\n parallel(out, |start, out| mult(v, out, start, |i, j| A(j, i)));\n\n}\n\n\n", "file_path": "src/test/bench/shootout-spectralnorm.rs", "rank": 16, "score": 352990.9226944759 }, { "content": "pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt,\n\n span: Span,\n\n token_tree: &[TokenTree])\n\n -> Box<MacResult+'cx> {\n\n let code = match token_tree {\n\n [ast::TtToken(_, token::Ident(code, _))] => code,\n\n _ => unreachable!()\n\n };\n\n with_used_diagnostics(|diagnostics| {\n\n match diagnostics.insert(code.name, span) {\n\n Some(previous_span) => {\n\n ecx.span_warn(span, &format!(\n\n \"diagnostic code {} already used\", &token::get_ident(code)\n\n )[]);\n\n ecx.span_note(previous_span, \"previous invocation\");\n\n },\n\n None => ()\n\n }\n\n ()\n\n });\n\n with_registered_diagnostics(|diagnostics| {\n\n if !diagnostics.contains_key(&code.name) {\n\n ecx.span_err(span, &format!(\n\n \"used diagnostic code {} not registered\", &token::get_ident(code)\n\n )[]);\n\n }\n\n });\n\n MacExpr::new(quote_expr!(ecx, ()))\n\n}\n\n\n", "file_path": "src/libsyntax/diagnostics/plugin.rs", "rank": 17, "score": 351732.125348975 }, { "content": "pub fn each_impl<F>(cdata: Cmd, mut callback: F) where\n\n F: FnMut(ast::DefId),\n\n{\n\n let impls_doc = reader::get_doc(rbml::Doc::new(cdata.data()), tag_impls);\n\n let _ = reader::tagged_docs(impls_doc, tag_impls_impl, |impl_doc| {\n\n callback(item_def_id(impl_doc, cdata));\n\n true\n\n });\n\n}\n\n\n", "file_path": "src/librustc/metadata/decoder.rs", "rank": 18, "score": 349899.0803943559 }, { "content": "pub fn walk_struct_field<'v, V: Visitor<'v>>(visitor: &mut V,\n\n struct_field: &'v StructField) {\n\n if let NamedField(name, _) = struct_field.node.kind {\n\n visitor.visit_ident(struct_field.span, name);\n\n }\n\n\n\n visitor.visit_ty(&*struct_field.node.ty);\n\n\n\n for attr in &struct_field.node.attrs {\n\n visitor.visit_attribute(attr);\n\n }\n\n}\n\n\n", "file_path": "src/libsyntax/visit.rs", "rank": 19, "score": 349530.7297937599 }, { "content": "pub fn walk_struct_def<'v, V: Visitor<'v>>(visitor: &mut V,\n\n struct_definition: &'v StructDef) {\n\n for field in &struct_definition.fields {\n\n visitor.visit_struct_field(field)\n\n }\n\n}\n\n\n", "file_path": "src/libsyntax/visit.rs", "rank": 20, "score": 349530.7297937599 }, { "content": "pub fn noop_fold_struct_field<T: Folder>(f: StructField, fld: &mut T) -> StructField {\n\n let StructField {node: StructField_ {id, kind, ty, attrs}, span} = f;\n\n Spanned {\n\n node: StructField_ {\n\n id: fld.new_id(id),\n\n kind: kind,\n\n ty: fld.fold_ty(ty),\n\n attrs: fold_attrs(attrs, fld),\n\n },\n\n span: fld.new_span(span)\n\n }\n\n}\n\n\n", "file_path": "src/libsyntax/fold.rs", "rank": 21, "score": 349489.9205729647 }, { "content": "fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<()> {\n\n loop {\n\n if buf.capacity() == buf.len() {\n\n buf.reserve(DEFAULT_BUF_SIZE);\n\n }\n\n match with_end_to_cap(buf, |b| r.read(b)) {\n\n Ok(0) => return Ok(()),\n\n Ok(_) => {}\n\n Err(ref e) if e.kind() == ErrorKind::Interrupted => {}\n\n Err(e) => return Err(e),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/libstd/io/mod.rs", "rank": 22, "score": 345904.2593539184 }, { "content": "#[inline]\n\npub fn random<T: Rand>() -> T {\n\n thread_rng().gen()\n\n}\n\n\n", "file_path": "src/libstd/rand/mod.rs", "rank": 23, "score": 345854.23797883646 }, { "content": "#[inline]\n\n#[unstable(feature = \"std_misc\", reason = \"may be removed or relocated\")]\n\npub fn to_string(num: f64) -> String {\n\n let (r, _) = strconv::float_to_str_common(\n\n num, 10, true, SignNeg, DigAll, ExpNone, false);\n\n r\n\n}\n\n\n\n/// Converts a float to a string in hexadecimal format\n\n///\n\n/// # Arguments\n\n///\n\n/// * num - The float value\n", "file_path": "src/libstd/num/f64.rs", "rank": 24, "score": 345828.08084810677 }, { "content": "// same as cci_iter_lib, more-or-less, but not marked inline\n\npub fn iter<F>(v: Vec<uint> , mut f: F) where F: FnMut(uint) {\n\n let mut i = 0u;\n\n let n = v.len();\n\n while i < n {\n\n f(v[i]);\n\n i += 1u;\n\n }\n\n}\n", "file_path": "src/test/auxiliary/cci_no_inline_lib.rs", "rank": 25, "score": 345491.28975399357 }, { "content": "#[inline]\n\n#[unstable(feature = \"std_misc\", reason = \"may be removed or relocated\")]\n\npub fn to_str_hex(num: f64) -> String {\n\n let (r, _) = strconv::float_to_str_common(\n\n num, 16, true, SignNeg, DigAll, ExpNone, false);\n\n r\n\n}\n\n\n\n/// Converts a float to a string in a given radix, and a flag indicating\n\n/// whether it's a special value\n\n///\n\n/// # Arguments\n\n///\n\n/// * num - The float value\n\n/// * radix - The base to use\n", "file_path": "src/libstd/num/f64.rs", "rank": 26, "score": 342083.92590459244 }, { "content": "/// Winsorize a set of samples, replacing values above the `100-pct` percentile and below the `pct`\n\n/// percentile with those percentiles themselves. This is a way of minimizing the effect of\n\n/// outliers, at the cost of biasing the sample. It differs from trimming in that it does not\n\n/// change the number of samples, just changes the values of those that are outliers.\n\n///\n\n/// See: http://en.wikipedia.org/wiki/Winsorising\n\npub fn winsorize<T: Float + FromPrimitive>(samples: &mut [T], pct: T) {\n\n let mut tmp = samples.to_vec();\n\n local_sort(&mut tmp);\n\n let lo = percentile_of_sorted(&tmp, pct);\n\n let hundred: T = FromPrimitive::from_uint(100).unwrap();\n\n let hi = percentile_of_sorted(&tmp, hundred-pct);\n\n for samp in samples {\n\n if *samp > hi {\n\n *samp = hi\n\n } else if *samp < lo {\n\n *samp = lo\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/libtest/stats.rs", "rank": 27, "score": 340407.3921272076 }, { "content": "fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)\n\n -> Result<()> {\n\n loop {\n\n let (done, used) = {\n\n let available = match r.fill_buf() {\n\n Ok(n) => n,\n\n Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,\n\n Err(e) => return Err(e)\n\n };\n\n match available.position_elem(&delim) {\n\n Some(i) => {\n\n buf.push_all(&available[..i + 1]);\n\n (true, i + 1)\n\n }\n\n None => {\n\n buf.push_all(available);\n\n (false, available.len())\n\n }\n\n }\n\n };\n\n r.consume(used);\n\n if done || used == 0 {\n\n return Ok(());\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/libstd/io/mod.rs", "rank": 28, "score": 339272.9492679372 }, { "content": "pub fn noop_fold_impl_item<T: Folder>(i: ImplItem, folder: &mut T) -> SmallVector<ImplItem> {\n\n match i {\n\n MethodImplItem(ref x) => {\n\n folder.fold_method((*x).clone()).into_iter().map(|m| MethodImplItem(m)).collect()\n\n }\n\n TypeImplItem(ref t) => {\n\n SmallVector::one(TypeImplItem(\n\n P(folder.fold_typedef((**t).clone()))))\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/libsyntax/fold.rs", "rank": 29, "score": 338375.64297336125 }, { "content": "#[inline]\n\n#[stable(feature = \"rust1\", since = \"1.0.0\")]\n\npub fn null_mut<T>() -> *mut T { 0 as *mut T }\n\n\n\n/// Zeroes out `count * size_of::<T>` bytes of memory at `dst`. `count` may be\n\n/// `0`.\n\n///\n\n/// # Safety\n\n///\n\n/// Beyond accepting a raw pointer, this is unsafe because it will not drop the\n\n/// contents of `dst`, and may be used to create invalid instances of `T`.\n\n#[inline]\n\n#[unstable(feature = \"core\",\n\n reason = \"may play a larger role in std::ptr future extensions\")]\n\npub unsafe fn zero_memory<T>(dst: *mut T, count: usize) {\n\n set_memory(dst, 0, count);\n\n}\n\n\n\n/// Swaps the values at two mutable locations of the same type, without\n\n/// deinitialising either. They may overlap, unlike `mem::swap` which is\n\n/// otherwise equivalent.\n\n///\n", "file_path": "src/libcore/ptr.rs", "rank": 30, "score": 338102.12816102384 }, { "content": "pub fn indent<R, F>(op: F) -> R where\n\n R: Debug,\n\n F: FnOnce() -> R,\n\n{\n\n // Use in conjunction with the log post-processor like `src/etc/indenter`\n\n // to make debug output more readable.\n\n debug!(\">>\");\n\n let r = op();\n\n debug!(\"<< (Result = {:?})\", r);\n\n r\n\n}\n\n\n\npub struct Indenter {\n\n _cannot_construct_outside_of_this_module: ()\n\n}\n\n\n\nimpl Drop for Indenter {\n\n fn drop(&mut self) { debug!(\"<<\"); }\n\n}\n\n\n", "file_path": "src/librustc/util/common.rs", "rank": 31, "score": 335888.6274501262 }, { "content": "#[unstable(feature = \"core\")]\n\npub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {\n\n unsafe {\n\n let ptr: *const A = transmute(s);\n\n transmute(RawSlice { data: ptr, len: 1 })\n\n }\n\n}\n\n\n\n/// Forms a slice from a pointer and a length.\n\n///\n\n/// The `len` argument is the number of **elements**, not the number of bytes.\n\n///\n\n/// This function is unsafe as there is no guarantee that the given pointer is\n\n/// valid for `len` elements, nor whether the lifetime inferred is a suitable\n\n/// lifetime for the returned slice.\n\n///\n\n/// # Caveat\n\n///\n\n/// The lifetime for the returned slice is inferred from its usage. To\n\n/// prevent accidental misuse, it's suggested to tie the lifetime to whichever\n\n/// source lifetime is safe in the context, such as by providing a helper\n", "file_path": "src/libcore/slice.rs", "rank": 32, "score": 335777.92168384494 }, { "content": "pub fn foo(arr: &mut Arr) {\n\n let x: &mut [uint] = &mut **arr;\n\n assert!(x[0] == 1);\n\n assert!(x[1] == 2);\n\n assert!(x[2] == 3);\n\n}\n\n\n", "file_path": "src/test/run-pass/dst-deref-mut.rs", "rank": 33, "score": 334444.9202612803 }, { "content": "#[inline]\n\n#[stable(feature = \"rust1\", since = \"1.0.0\")]\n\npub fn swap<T>(x: &mut T, y: &mut T) {\n\n unsafe {\n\n // Give ourselves some scratch space to work with\n\n let mut t: T = uninitialized();\n\n\n\n // Perform the swap, `&mut` pointers never alias\n\n ptr::copy_nonoverlapping_memory(&mut t, &*x, 1);\n\n ptr::copy_nonoverlapping_memory(x, &*y, 1);\n\n ptr::copy_nonoverlapping_memory(y, &t, 1);\n\n\n\n // y and t now point to the same thing, but we need to completely forget `t`\n\n // because it's no longer relevant.\n\n forget(t);\n\n }\n\n}\n\n\n\n/// Replace the value at a mutable location with a new one, returning the old value, without\n\n/// deinitialising or copying either one.\n\n///\n\n/// This is primarily used for transferring and swapping ownership of a value in a mutable\n", "file_path": "src/libcore/mem.rs", "rank": 34, "score": 333737.1395658762 }, { "content": "fn f<'r>(p: &'r mut fn(p: &mut ())) {\n\n (*p)(()) //~ ERROR mismatched types\n\n //~| expected `&mut ()`\n\n //~| found `()`\n\n //~| expected &-ptr\n\n //~| found ()\n\n}\n\n\n", "file_path": "src/test/compile-fail/issue-17033.rs", "rank": 35, "score": 333045.1174398401 }, { "content": "pub fn noop_fold_struct_def<T: Folder>(struct_def: P<StructDef>, fld: &mut T) -> P<StructDef> {\n\n struct_def.map(|StructDef { fields, ctor_id }| StructDef {\n\n fields: fields.move_map(|f| fld.fold_struct_field(f)),\n\n ctor_id: ctor_id.map(|cid| fld.new_id(cid)),\n\n })\n\n}\n\n\n", "file_path": "src/libsyntax/fold.rs", "rank": 36, "score": 332817.5429249221 }, { "content": "#[allow(unused)]\n\npub fn parse_summary<R: Reader>(_: R, _: &Path) {\n\n let path_from_root = Path::new(\"\");\n\n Path::new(iter::repeat(\"../\")\n\n .take(path_from_root.components().count() - 1)\n\n .collect::<String>());\n\n }\n\n\n", "file_path": "src/test/run-pass/issue-20644.rs", "rank": 37, "score": 332429.63223735604 }, { "content": "#[inline(always)]\n\nfn ziggurat<R: Rng, P, Z>(\n\n rng: &mut R,\n\n symmetric: bool,\n\n x_tab: ziggurat_tables::ZigTable,\n\n f_tab: ziggurat_tables::ZigTable,\n\n mut pdf: P,\n\n mut zero_case: Z)\n\n -> f64 where P: FnMut(f64) -> f64, Z: FnMut(&mut R, f64) -> f64 {\n\n static SCALE: f64 = (1u64 << 53) as f64;\n\n loop {\n\n // reimplement the f64 generation as an optimisation suggested\n\n // by the Doornik paper: we have a lot of precision-space\n\n // (i.e. there are 11 bits of the 64 of a u64 to use after\n\n // creating a f64), so we might as well reuse some to save\n\n // generating a whole extra random number. (Seems to be 15%\n\n // faster.)\n\n //\n\n // This unfortunately misses out on the benefits of direct\n\n // floating point generation if an RNG like dSMFT is\n\n // used. (That is, such RNGs create floats directly, highly\n", "file_path": "src/librand/distributions/mod.rs", "rank": 38, "score": 332122.2627224065 }, { "content": "pub fn sin<T:Trig<R>, R>(theta: &T) -> R { theta.sin() }\n\n\n", "file_path": "src/test/auxiliary/issue-4208-cc.rs", "rank": 39, "score": 332042.60980198276 }, { "content": "#[no_mangle]\n\npub fn test(a: &Struct,\n\n b: &Struct,\n\n c: &Struct,\n\n d: &Struct,\n\n e: &Struct) -> int {\n\n a.method(b.method(c.method(d.method(e.method(1)))))\n\n}\n", "file_path": "src/test/codegen/static-method-call-multi.rs", "rank": 40, "score": 331891.5890030096 }, { "content": "#[unstable(feature = \"core\", reason = \"likely to be removed\")]\n\npub fn from_f64<A: FromPrimitive>(n: f64) -> Option<A> {\n\n FromPrimitive::from_f64(n)\n\n}\n\n\n\nmacro_rules! impl_from_primitive {\n\n ($T:ty, $to_ty:ident) => (\n\n impl FromPrimitive for $T {\n\n #[inline] fn from_int(n: int) -> Option<$T> { n.$to_ty() }\n\n #[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() }\n\n #[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() }\n\n #[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() }\n\n #[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() }\n\n\n\n #[inline] fn from_uint(n: uint) -> Option<$T> { n.$to_ty() }\n\n #[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() }\n\n #[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() }\n\n #[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() }\n\n #[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() }\n\n\n\n #[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() }\n", "file_path": "src/libcore/num/mod.rs", "rank": 41, "score": 326943.99223482335 }, { "content": "pub fn record(resolver: &mut Resolver) {\n\n let mut recorder = ExportRecorder { resolver: resolver };\n\n let root_module = recorder.graph_root.get_module();\n\n recorder.record_exports_for_module_subtree(root_module);\n\n}\n", "file_path": "src/librustc_resolve/record_exports.rs", "rank": 42, "score": 325005.76359471673 }, { "content": "/// Reads all remaining bytes from the stream.\n\nfn read_to_end<R: Reader>(r: &mut R) -> IoResult<Vec<u8>> {\n\n // As reading the input stream in memory is a bottleneck, we tune\n\n // Reader::read_to_end() with a fast growing policy to limit\n\n // recopies. If MREMAP_RETAIN is implemented in the linux kernel\n\n // and jemalloc use it, this trick will become useless.\n\n const CHUNK: uint = 64 * 1024;\n\n\n\n let mut vec = Vec::with_capacity(CHUNK);\n\n loop {\n\n // workaround: very fast growing\n\n let len = vec.len();\n\n if vec.capacity() - len < CHUNK {\n\n let cap = vec.capacity();\n\n let mult = if cap < 256 * 1024 * 1024 {\n\n 16\n\n } else {\n\n 2\n\n };\n\n vec.reserve_exact(mult * cap - len);\n\n }\n\n match r.push_at_least(1, CHUNK, &mut vec) {\n\n Ok(_) => {}\n\n Err(ref e) if e.kind == EndOfFile => break,\n\n Err(e) => return Err(e)\n\n }\n\n }\n\n Ok(vec)\n\n}\n\n\n", "file_path": "src/test/bench/shootout-reverse-complement.rs", "rank": 43, "score": 324946.70731993497 }, { "content": "#[no_mangle]\n\npub fn test(s: &Struct) -> int {\n\n s.method()\n\n}\n", "file_path": "src/test/codegen/static-method-call.rs", "rank": 44, "score": 324378.62164162786 }, { "content": "fn scan<R, F, G>(st: &mut PState, mut is_last: F, op: G) -> R where\n\n F: FnMut(char) -> bool,\n\n G: FnOnce(&[u8]) -> R,\n\n{\n\n let start_pos = st.pos;\n\n debug!(\"scan: '{}' (start)\", st.data[st.pos] as char);\n\n while !is_last(st.data[st.pos] as char) {\n\n st.pos += 1;\n\n debug!(\"scan: '{}'\", st.data[st.pos] as char);\n\n }\n\n let end_pos = st.pos;\n\n st.pos += 1;\n\n return op(&st.data[start_pos..end_pos]);\n\n}\n\n\n", "file_path": "src/librustc/metadata/tydecode.rs", "rank": 45, "score": 323579.72706329275 }, { "content": "fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {\n\n let mut res = Vec::new();\n\n for l in r.lines().map(|l| l.ok().unwrap())\n\n .skip_while(|l| key != &l[..key.len()]).skip(1)\n\n {\n\n res.push_all(l.trim().as_bytes());\n\n }\n\n res.into_ascii_uppercase()\n\n}\n\n\n", "file_path": "src/test/bench/shootout-k-nucleotide.rs", "rank": 46, "score": 323307.853136066 }, { "content": "fn conspirator<F>(mut f: F) where F: FnMut(&mut R, bool) {\n\n let mut r = R {c: box f};\n\n f(&mut r, false) //~ ERROR use of moved value\n\n}\n\n\n", "file_path": "src/test/compile-fail/moves-based-on-type-no-recursive-stack-closure.rs", "rank": 47, "score": 322444.7838005483 }, { "content": "#[inline]\n\n#[unstable(feature = \"std_misc\", reason = \"may be removed or relocated\")]\n\npub fn to_str_exact(num: f64, dig: uint) -> String {\n\n let (r, _) = strconv::float_to_str_common(\n\n num, 10, true, SignNeg, DigExact(dig), ExpNone, false);\n\n r\n\n}\n\n\n\n/// Converts a float to a string with a maximum number of\n\n/// significant digits\n\n///\n\n/// # Arguments\n\n///\n\n/// * num - The float value\n\n/// * digits - The number of significant digits\n", "file_path": "src/libstd/num/f64.rs", "rank": 48, "score": 321896.6834736557 }, { "content": "#[inline]\n\n#[unstable(feature = \"std_misc\", reason = \"may be removed or relocated\")]\n\npub fn to_str_digits(num: f64, dig: uint) -> String {\n\n let (r, _) = strconv::float_to_str_common(\n\n num, 10, true, SignNeg, DigMax(dig), ExpNone, false);\n\n r\n\n}\n\n\n\n/// Converts a float to a string using the exponential notation with exactly the number of\n\n/// provided digits after the decimal point in the significand\n\n///\n\n/// # Arguments\n\n///\n\n/// * num - The float value\n\n/// * digits - The number of digits after the decimal point\n\n/// * upper - Use `E` instead of `e` for the exponent sign\n", "file_path": "src/libstd/num/f64.rs", "rank": 49, "score": 321896.6834736557 }, { "content": "pub fn enc_region(w: &mut SeekableMemWriter, cx: &ctxt, r: ty::Region) {\n\n match r {\n\n ty::ReLateBound(id, br) => {\n\n mywrite!(w, \"b[{}|\", id.depth);\n\n enc_bound_region(w, cx, br);\n\n mywrite!(w, \"]\");\n\n }\n\n ty::ReEarlyBound(node_id, space, index, name) => {\n\n mywrite!(w, \"B[{}|{}|{}|{}]\",\n\n node_id,\n\n space.to_uint(),\n\n index,\n\n token::get_name(name));\n\n }\n\n ty::ReFree(ref fr) => {\n\n mywrite!(w, \"f[\");\n\n enc_destruction_scope_data(w, fr.scope);\n\n mywrite!(w, \"|\");\n\n enc_bound_region(w, cx, fr.bound_region);\n\n mywrite!(w, \"]\");\n", "file_path": "src/librustc/metadata/tyencode.rs", "rank": 50, "score": 321417.110282937 }, { "content": "#[plugin_registrar]\n\npub fn plugin_registrar(_: &mut Registry) { }\n", "file_path": "src/test/auxiliary/plugin_with_plugin_lib.rs", "rank": 51, "score": 321187.6480839796 }, { "content": "#[plugin_registrar]\n\npub fn plugin_registrar(_: &mut Registry) {}\n", "file_path": "src/test/auxiliary/rlib_crate_test.rs", "rank": 52, "score": 321187.6480839796 }, { "content": "#[plugin_registrar]\n\npub fn plugin_registrar(reg: &mut Registry) {\n\n reg.register_macro(\"rn\", expand_rn);\n\n}\n", "file_path": "src/test/auxiliary/roman_numerals.rs", "rank": 53, "score": 321187.6480839796 }, { "content": "#[plugin_registrar]\n\npub fn plugin_registrar(reg: &mut Registry) {\n\n let args = reg.args().clone();\n\n reg.register_syntax_extension(token::intern(\"plugin_args\"),\n\n NormalTT(box Expander { args: args, }, None));\n\n}\n", "file_path": "src/test/auxiliary/plugin_args.rs", "rank": 54, "score": 321187.6480839796 }, { "content": "#[inline]\n\n#[stable(feature = \"rust1\", since = \"1.0.0\")]\n\npub fn replace<T>(dest: &mut T, mut src: T) -> T {\n\n swap(dest, &mut src);\n\n src\n\n}\n\n\n\n/// Disposes of a value.\n\n///\n\n/// This function can be used to destroy any value by allowing `drop` to take ownership of its\n\n/// argument.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use std::cell::RefCell;\n\n///\n\n/// let x = RefCell::new(1);\n\n///\n\n/// let mut mutable_borrow = x.borrow_mut();\n\n/// *mutable_borrow = 1;\n\n///\n\n/// drop(mutable_borrow); // relinquish the mutable borrow on this slot\n\n///\n\n/// let borrow = x.borrow();\n\n/// println!(\"{}\", *borrow);\n\n/// ```\n", "file_path": "src/libcore/mem.rs", "rank": 55, "score": 318583.1470289515 }, { "content": "/// Generates the documentation for `crate` into the directory `dst`\n\npub fn run(mut krate: clean::Crate,\n\n external_html: &ExternalHtml,\n\n dst: Path,\n\n passes: HashSet<String>) -> old_io::IoResult<()> {\n\n let mut cx = Context {\n\n dst: dst,\n\n src_root: krate.src.dir_path(),\n\n passes: passes,\n\n current: Vec::new(),\n\n root_path: String::new(),\n\n sidebar: HashMap::new(),\n\n layout: layout::Layout {\n\n logo: \"\".to_string(),\n\n favicon: \"\".to_string(),\n\n external_html: external_html.clone(),\n\n krate: krate.name.clone(),\n\n playground_url: \"\".to_string(),\n\n },\n\n include_sources: true,\n\n render_redirect_pages: false,\n", "file_path": "src/librustdoc/html/render.rs", "rank": 56, "score": 318156.8979812177 }, { "content": "#[plugin_registrar]\n\npub fn plugin_registrar(reg: &mut Registry) {\n\n reg.register_lint_pass(box Pass as LintPassObject);\n\n}\n", "file_path": "src/test/auxiliary/lint_plugin_test.rs", "rank": 57, "score": 317533.36130566394 }, { "content": "/// Extract comma-separated expressions from `tts`. If there is a\n\n/// parsing error, emit a non-fatal error and return None.\n\npub fn get_exprs_from_tts(cx: &mut ExtCtxt,\n\n sp: Span,\n\n tts: &[ast::TokenTree]) -> Option<Vec<P<ast::Expr>>> {\n\n let mut p = cx.new_parser_from_tts(tts);\n\n let mut es = Vec::new();\n\n while p.token != token::Eof {\n\n es.push(cx.expander().fold_expr(p.parse_expr()));\n\n if p.eat(&token::Comma) {\n\n continue;\n\n }\n\n if p.token != token::Eof {\n\n cx.span_err(sp, \"expected token: `,`\");\n\n return None;\n\n }\n\n }\n\n Some(es)\n\n}\n\n\n\n/// In order to have some notion of scoping for macros,\n\n/// we want to implement the notion of a transformation\n", "file_path": "src/libsyntax/ext/base.rs", "rank": 58, "score": 317533.36130566394 }, { "content": "pub fn expand_quote_ty(cx: &mut ExtCtxt,\n\n sp: Span,\n\n tts: &[ast::TokenTree])\n\n -> Box<base::MacResult+'static> {\n\n let expanded = expand_parse_call(cx, sp, \"parse_ty\", vec!(), tts);\n\n base::MacExpr::new(expanded)\n\n}\n\n\n", "file_path": "src/libsyntax/ext/quote.rs", "rank": 59, "score": 317533.36130566394 }, { "content": "pub fn expand_quote_arm(cx: &mut ExtCtxt,\n\n sp: Span,\n\n tts: &[ast::TokenTree])\n\n -> Box<base::MacResult+'static> {\n\n let expanded = expand_parse_call(cx, sp, \"parse_arm\", vec!(), tts);\n\n base::MacExpr::new(expanded)\n\n}\n\n\n", "file_path": "src/libsyntax/ext/quote.rs", "rank": 60, "score": 317533.36130566394 }, { "content": "pub fn expand_quote_method(cx: &mut ExtCtxt,\n\n sp: Span,\n\n tts: &[ast::TokenTree])\n\n -> Box<base::MacResult+'static> {\n\n let expanded = expand_parse_call(cx, sp, \"parse_method_with_outer_attributes\",\n\n vec!(), tts);\n\n base::MacExpr::new(expanded)\n\n}\n\n\n", "file_path": "src/libsyntax/ext/quote.rs", "rank": 61, "score": 317533.36130566394 }, { "content": "pub fn expand_quote_stmt(cx: &mut ExtCtxt,\n\n sp: Span,\n\n tts: &[ast::TokenTree])\n\n -> Box<base::MacResult+'static> {\n\n let e_attrs = cx.expr_vec_ng(sp);\n\n let expanded = expand_parse_call(cx, sp, \"parse_stmt\",\n\n vec!(e_attrs), tts);\n\n base::MacExpr::new(expanded)\n\n}\n\n\n", "file_path": "src/libsyntax/ext/quote.rs", "rank": 62, "score": 317533.36130566394 }, { "content": "#[plugin_registrar]\n\npub fn registrar(_: &mut Registry) {\n\n thread_local!(static FOO: RefCell<Option<Box<Any+Send>>> = RefCell::new(None));\n\n FOO.with(|s| *s.borrow_mut() = Some(box Foo { foo: 10 } as Box<Any+Send>));\n\n}\n\n\n", "file_path": "src/test/auxiliary/plugin_crate_outlive_expansion_phase.rs", "rank": 63, "score": 317533.36130566394 }, { "content": "#[plugin_registrar]\n\npub fn plugin_registrar(reg: &mut Registry) {\n\n reg.register_macro(\"make_a_1\", expand_make_a_1);\n\n reg.register_macro(\"forged_ident\", expand_forged_ident);\n\n reg.register_macro(\"identity\", expand_identity);\n\n reg.register_syntax_extension(\n\n token::intern(\"into_foo\"),\n\n Modifier(box expand_into_foo));\n\n reg.register_syntax_extension(\n\n token::intern(\"into_multi_foo\"),\n\n MultiModifier(box expand_into_foo_multi));\n\n}\n\n\n", "file_path": "src/test/auxiliary/macro_crate_test.rs", "rank": 64, "score": 317533.36130566394 }, { "content": "fn write_line(init_i: f64, vec_init_r: &[f64], res: &mut Vec<u8>) {\n\n let v_init_i : f64x2 = f64x2(init_i, init_i);\n\n let v_2 : f64x2 = f64x2(2.0, 2.0);\n\n const LIMIT_SQUARED: f64 = LIMIT * LIMIT;\n\n\n\n for chunk_init_r in vec_init_r.chunks(8) {\n\n let mut cur_byte = 0xff;\n\n let mut i = 0;\n\n\n\n while i < 8 {\n\n let v_init_r = f64x2(chunk_init_r[i], chunk_init_r[i + 1]);\n\n let mut cur_r = v_init_r;\n\n let mut cur_i = v_init_i;\n\n let mut r_sq = v_init_r * v_init_r;\n\n let mut i_sq = v_init_i * v_init_i;\n\n\n\n let mut b = 0;\n\n for _ in 0..ITER {\n\n let r = cur_r;\n\n let i = cur_i;\n", "file_path": "src/test/bench/shootout-mandelbrot.rs", "rank": 65, "score": 316422.1079749522 }, { "content": "fn mult<F>(v: &[f64], out: &mut [f64], start: uint, a: F)\n\n where F: Fn(uint, uint) -> f64 {\n\n for (i, slot) in out.iter_mut().enumerate().map(|(i, s)| (i + start, s)) {\n\n let mut sum = f64x2(0.0, 0.0);\n\n for (j, chunk) in v.chunks(2).enumerate().map(|(j, s)| (2 * j, s)) {\n\n let top = f64x2(chunk[0], chunk[1]);\n\n let bot = f64x2(a(i, j), a(i, j + 1));\n\n sum += top / bot;\n\n }\n\n let f64x2(a, b) = sum;\n\n *slot = a + b;\n\n }\n\n}\n\n\n", "file_path": "src/test/bench/shootout-spectralnorm.rs", "rank": 66, "score": 316373.32592412154 }, { "content": "pub fn go_mut<G:GoMut>(this: &mut G, arg: int) {\n\n this.go_mut(arg)\n\n}\n\n\n", "file_path": "src/test/auxiliary/go_trait.rs", "rank": 67, "score": 314633.7632040832 }, { "content": "#[inline(never)]\n\npub fn foo(f: &mut Foo) -> Foo {\n\n let ret = *f;\n\n f.f1 = 0;\n\n ret\n\n}\n\n\n", "file_path": "src/test/run-pass/out-pointer-aliasing.rs", "rank": 68, "score": 314346.2730824328 }, { "content": "#[cfg(all(target_os = \"ios\", target_arch = \"arm\"))]\n\n#[inline(never)]\n\npub fn write(w: &mut Writer) -> IoResult<()> {\n\n use result;\n\n\n\n extern {\n\n fn backtrace(buf: *mut *mut libc::c_void,\n\n sz: libc::c_int) -> libc::c_int;\n\n }\n\n\n\n // while it doesn't requires lock for work as everything is\n\n // local, it still displays much nicer backtraces when a\n\n // couple of tasks panic simultaneously\n\n static LOCK: StaticMutex = MUTEX_INIT;\n\n let _g = unsafe { LOCK.lock() };\n\n\n\n try!(writeln!(w, \"stack backtrace:\"));\n\n // 100 lines should be enough\n\n const SIZE: uint = 100;\n\n let mut buf: [*mut libc::c_void; SIZE] = unsafe {mem::zeroed()};\n\n let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE as libc::c_int) as uint};\n\n\n\n // skipping the first one as it is write itself\n\n let iter = (1..cnt).map(|i| {\n\n print(w, i as int, buf[i])\n\n });\n\n result::fold(iter, (), |_, _| ())\n\n}\n\n\n\n#[cfg(not(all(target_os = \"ios\", target_arch = \"arm\")))]\n\n#[inline(never)] // if we know this is a function call, we can skip it when\n", "file_path": "src/libstd/sys/unix/backtrace.rs", "rank": 69, "score": 314345.6666616311 }, { "content": "pub fn write(w: &mut Writer) -> IoResult<()> {\n\n // According to windows documentation, all dbghelp functions are\n\n // single-threaded.\n\n static LOCK: StaticMutex = MUTEX_INIT;\n\n let _g = LOCK.lock();\n\n\n\n // Open up dbghelp.dll, we don't link to it explicitly because it can't\n\n // always be found. Additionally, it's nice having fewer dependencies.\n\n let path = Path::new(\"dbghelp.dll\");\n\n let lib = match DynamicLibrary::open(Some(&path)) {\n\n Ok(lib) => lib,\n\n Err(..) => return Ok(()),\n\n };\n\n\n\n macro_rules! sym{ ($e:expr, $t:ident) => (unsafe {\n\n match lib.symbol($e) {\n\n Ok(f) => mem::transmute::<*mut u8, $t>(f),\n\n Err(..) => return Ok(())\n\n }\n\n }) }\n", "file_path": "src/libstd/sys/windows/backtrace.rs", "rank": 70, "score": 314338.78247048054 }, { "content": "#[plugin_registrar]\n\npub fn plugin_registrar(reg: &mut Registry) {\n\n reg.register_macro(\"foo\", expand_foo);\n\n}\n\n\n", "file_path": "src/test/auxiliary/syntax_extension_with_dll_deps_2.rs", "rank": 71, "score": 314032.5803182487 }, { "content": "pub fn expand_trace_macros(cx: &mut ExtCtxt,\n\n sp: Span,\n\n tt: &[ast::TokenTree])\n\n -> Box<base::MacResult+'static> {\n\n match tt {\n\n [ast::TtToken(_, ref tok)] if tok.is_keyword(keywords::True) => {\n\n cx.set_trace_macros(true);\n\n }\n\n [ast::TtToken(_, ref tok)] if tok.is_keyword(keywords::False) => {\n\n cx.set_trace_macros(false);\n\n }\n\n _ => cx.span_err(sp, \"trace_macros! accepts only `true` or `false`\"),\n\n }\n\n\n\n base::DummyResult::any(sp)\n\n}\n", "file_path": "src/libsyntax/ext/trace_macros.rs", "rank": 72, "score": 314032.5803182487 }, { "content": "pub fn ordering_collapsed(cx: &mut ExtCtxt,\n\n span: Span,\n\n self_arg_tags: &[ast::Ident]) -> P<ast::Expr> {\n\n let lft = cx.expr_ident(span, self_arg_tags[0]);\n\n let rgt = cx.expr_addr_of(span, cx.expr_ident(span, self_arg_tags[1]));\n\n cx.expr_method_call(span, lft, cx.ident_of(\"cmp\"), vec![rgt])\n\n}\n\n\n", "file_path": "src/libsyntax/ext/deriving/cmp/totalord.rs", "rank": 73, "score": 314032.5803182487 }, { "content": "pub fn expand_meta_derive(cx: &mut ExtCtxt,\n\n _span: Span,\n\n mitem: &MetaItem,\n\n item: &Item,\n\n push: &mut FnMut(P<Item>)) {\n\n match mitem.node {\n\n MetaNameValue(_, ref l) => {\n\n cx.span_err(l.span, \"unexpected value in `derive`\");\n\n }\n\n MetaWord(_) => {\n\n cx.span_warn(mitem.span, \"empty trait list in `derive`\");\n\n }\n\n MetaList(_, ref titems) if titems.len() == 0 => {\n\n cx.span_warn(mitem.span, \"empty trait list in `derive`\");\n\n }\n\n MetaList(_, ref titems) => {\n\n for titem in titems.iter().rev() {\n\n match titem.node {\n\n MetaNameValue(ref tname, _) |\n\n MetaList(ref tname, _) |\n", "file_path": "src/libsyntax/ext/deriving/mod.rs", "rank": 74, "score": 314032.5803182487 }, { "content": "pub fn mk_subregion_due_to_dereference(rcx: &mut Rcx,\n\n deref_span: Span,\n\n minimum_lifetime: ty::Region,\n\n maximum_lifetime: ty::Region) {\n\n rcx.fcx.mk_subr(infer::DerefPointer(deref_span),\n\n minimum_lifetime, maximum_lifetime)\n\n}\n\n\n", "file_path": "src/librustc_typeck/check/regionck.rs", "rank": 75, "score": 314032.5803182487 }, { "content": "#[plugin_registrar]\n\npub fn plugin_registrar(reg: &mut Registry) {\n\n reg.register_lint_pass(box Pass as LintPassObject);\n\n reg.register_lint_group(\"lint_me\", vec![TEST_LINT, PLEASE_LINT]);\n\n}\n", "file_path": "src/test/auxiliary/lint_group_plugin_test.rs", "rank": 76, "score": 314032.5803182487 }, { "content": "pub fn expand_deprecated_deriving(cx: &mut ExtCtxt,\n\n span: Span,\n\n _: &MetaItem,\n\n _: &Item,\n\n _: &mut FnMut(P<Item>)) {\n\n cx.span_err(span, \"`deriving` has been renamed to `derive`\");\n\n}\n\n\n", "file_path": "src/libsyntax/ext/deriving/mod.rs", "rank": 77, "score": 314032.5803182487 }, { "content": "pub fn some_ordering_collapsed(cx: &mut ExtCtxt,\n\n span: Span,\n\n op: OrderingOp,\n\n self_arg_tags: &[ast::Ident]) -> P<ast::Expr> {\n\n let lft = cx.expr_ident(span, self_arg_tags[0]);\n\n let rgt = cx.expr_addr_of(span, cx.expr_ident(span, self_arg_tags[1]));\n\n let op_str = match op {\n\n PartialCmpOp => \"partial_cmp\",\n\n LtOp => \"lt\", LeOp => \"le\",\n\n GtOp => \"gt\", GeOp => \"ge\",\n\n };\n\n cx.expr_method_call(span, lft, cx.ident_of(op_str), vec![rgt])\n\n}\n\n\n", "file_path": "src/libsyntax/ext/deriving/cmp/ord.rs", "rank": 78, "score": 314032.5803182487 }, { "content": "/// Extract the string literal from the first token of `tts`. If this\n\n/// is not a string literal, emit an error and return None.\n\npub fn get_single_str_from_tts(cx: &mut ExtCtxt,\n\n sp: Span,\n\n tts: &[ast::TokenTree],\n\n name: &str)\n\n -> Option<String> {\n\n let mut p = cx.new_parser_from_tts(tts);\n\n if p.token == token::Eof {\n\n cx.span_err(sp, &format!(\"{} takes 1 argument\", name)[]);\n\n return None\n\n }\n\n let ret = cx.expander().fold_expr(p.parse_expr());\n\n if p.token != token::Eof {\n\n cx.span_err(sp, &format!(\"{} takes 1 argument\", name)[]);\n\n }\n\n expr_to_string(cx, ret, \"argument must be a string literal\").map(|(s, _)| {\n\n s.to_string()\n\n })\n\n}\n\n\n", "file_path": "src/libsyntax/ext/base.rs", "rank": 79, "score": 314032.5803182487 }, { "content": "pub fn walk_fn<'v, V: Visitor<'v>>(visitor: &mut V,\n\n function_kind: FnKind<'v>,\n\n function_declaration: &'v FnDecl,\n\n function_body: &'v Block,\n\n _span: Span) {\n\n walk_fn_decl(visitor, function_declaration);\n\n\n\n match function_kind {\n\n FkItemFn(_, generics, _, _) => {\n\n visitor.visit_generics(generics);\n\n }\n\n FkMethod(_, generics, method) => {\n\n visitor.visit_generics(generics);\n\n match method.node {\n\n MethDecl(_, _, _, ref explicit_self, _, _, _, _) =>\n\n visitor.visit_explicit_self(explicit_self),\n\n MethMac(ref mac) =>\n\n visitor.visit_mac(mac)\n\n }\n\n }\n\n FkFnBlock(..) => {}\n\n }\n\n\n\n visitor.visit_block(function_body)\n\n}\n\n\n", "file_path": "src/libsyntax/visit.rs", "rank": 80, "score": 313254.92761770636 }, { "content": "fn render_impl(w: &mut fmt::Formatter, i: &Impl) -> fmt::Result {\n\n try!(write!(w, \"<h3 class='impl'>{}<code>impl{} \",\n\n ConciseStability(&i.stability),\n\n i.impl_.generics));\n\n match i.impl_.polarity {\n\n Some(clean::ImplPolarity::Negative) => try!(write!(w, \"!\")),\n\n _ => {}\n\n }\n\n match i.impl_.trait_ {\n\n Some(ref ty) => try!(write!(w, \"{} for \", *ty)),\n\n None => {}\n\n }\n\n try!(write!(w, \"{}{}</code></h3>\", i.impl_.for_, WhereClause(&i.impl_.generics)));\n\n match i.dox {\n\n Some(ref dox) => {\n\n try!(write!(w, \"<div class='docblock'>{}</div>\",\n\n Markdown(dox)));\n\n }\n\n None => {}\n\n }\n", "file_path": "src/librustdoc/html/render.rs", "rank": 81, "score": 312580.61245260027 }, { "content": "#[inline]\n\n#[unstable(feature = \"core\")]\n\npub fn encode_utf16_raw(mut ch: u32, dst: &mut [u16]) -> Option<usize> {\n\n // Marked #[inline] to allow llvm optimizing it away\n\n if (ch & 0xFFFF_u32) == ch && dst.len() >= 1 {\n\n // The BMP falls through (assuming non-surrogate, as it should)\n\n dst[0] = ch as u16;\n\n Some(1)\n\n } else if dst.len() >= 2 {\n\n // Supplementary planes break into surrogates.\n\n ch -= 0x1_0000_u32;\n\n dst[0] = 0xD800_u16 | ((ch >> 10) as u16);\n\n dst[1] = 0xDC00_u16 | ((ch as u16) & 0x3FF_u16);\n\n Some(2)\n\n } else {\n\n None\n\n }\n\n}\n\n\n\n/// An iterator over the characters that represent a `char`, as escaped by\n\n/// Rust's unicode escaping rules.\n\n#[derive(Clone)]\n\n#[stable(feature = \"rust1\", since = \"1.0.0\")]\n\npub struct EscapeUnicode {\n\n c: char,\n\n state: EscapeUnicodeState\n\n}\n\n\n", "file_path": "src/libcore/char.rs", "rank": 82, "score": 312294.1370475649 }, { "content": "#[inline]\n\n#[unstable(feature = \"alloc\")]\n\npub fn get_mut<'a, T>(rc: &'a mut Rc<T>) -> Option<&'a mut T> {\n\n if is_unique(rc) {\n\n let inner = unsafe { &mut **rc._ptr };\n\n Some(&mut inner.value)\n\n } else {\n\n None\n\n }\n\n}\n\n\n\nimpl<T: Clone> Rc<T> {\n\n /// Make a mutable reference from the given `Rc<T>`.\n\n ///\n\n /// This is also referred to as a copy-on-write operation because the inner data is cloned if\n\n /// the reference count is greater than one.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use std::rc::Rc;\n\n ///\n", "file_path": "src/liballoc/rc.rs", "rank": 83, "score": 311311.028674213 }, { "content": "pub fn append_configuration(cfg: &mut ast::CrateConfig,\n\n name: InternedString) {\n\n if !cfg.iter().any(|mi| mi.name() == name) {\n\n cfg.push(attr::mk_word_item(name))\n\n }\n\n}\n\n\n", "file_path": "src/librustc/session/config.rs", "rank": 84, "score": 310684.4956921649 }, { "content": "pub fn expand_cfg<'cx>(cx: &mut ExtCtxt,\n\n sp: Span,\n\n tts: &[ast::TokenTree])\n\n -> Box<base::MacResult+'static> {\n\n let mut p = cx.new_parser_from_tts(tts);\n\n let cfg = p.parse_meta_item();\n\n\n\n if !p.eat(&token::Eof) {\n\n cx.span_err(sp, \"expected 1 cfg-pattern\");\n\n return DummyResult::expr(sp);\n\n }\n\n\n\n let matches_cfg = attr::cfg_matches(&cx.parse_sess.span_diagnostic, &cx.cfg, &*cfg);\n\n MacExpr::new(cx.expr_bool(sp, matches_cfg))\n\n}\n", "file_path": "src/libsyntax/ext/cfg.rs", "rank": 85, "score": 310684.4956921649 }, { "content": "#[plugin_registrar]\n\npub fn plugin_registrar(reg: &mut Registry) {\n\n reg.register_syntax_extension(token::intern(\"bogus\"), MacroRulesTT);\n\n}\n", "file_path": "src/test/auxiliary/macro_crate_MacroRulesTT.rs", "rank": 86, "score": 310675.831611707 }, { "content": "#[plugin_registrar]\n\npub fn plugin_registrar(reg: &mut Registry) {\n\n reg.register_macro(\"multiple_items\", expand)\n\n}\n\n\n", "file_path": "src/test/auxiliary/issue_16723_multiple_items_syntax_ext.rs", "rank": 87, "score": 310675.831611707 }, { "content": "pub fn list_database<F>(mut f: F) where F: FnMut(&CrateId) {\n\n let stuff = [\"foo\", \"bar\"];\n\n\n\n for l in &stuff {\n\n f(&CrateId::new(*l));\n\n }\n\n}\n\n\n", "file_path": "src/test/compile-fail/issue-7573.rs", "rank": 88, "score": 309806.66045520076 }, { "content": "#[inline]\n\n#[unstable(feature = \"std_misc\", reason = \"may be removed or relocated\")]\n\npub fn to_str_radix_special(num: f64, rdx: u32) -> (String, bool) {\n\n strconv::float_to_str_common(num, rdx, true, SignNeg, DigAll, ExpNone, false)\n\n}\n\n\n\n/// Converts a float to a string with exactly the number of\n\n/// provided significant digits\n\n///\n\n/// # Arguments\n\n///\n\n/// * num - The float value\n\n/// * digits - The number of significant digits\n", "file_path": "src/libstd/num/f64.rs", "rank": 89, "score": 309616.4425153987 }, { "content": "/// Compute canonical or compatible Unicode decomposition for character\n\npub fn decompose_compatible<F>(c: char, mut i: F) where F: FnMut(char) { d(c, &mut i, true); }\n\n\n", "file_path": "src/libunicode/normalize.rs", "rank": 90, "score": 308963.1166913465 }, { "content": "/// Compute canonical Unicode decomposition for character\n\npub fn decompose_canonical<F>(c: char, mut i: F) where F: FnMut(char) { d(c, &mut i, false); }\n\n\n", "file_path": "src/libunicode/normalize.rs", "rank": 91, "score": 308963.1166913465 }, { "content": "#[rustc_move_fragments]\n\npub fn test_move_field_mut_to_local(mut p: Pair<D, D>) {\n\n //~^ ERROR parent_of_fragments: `$(local mut p)`\n\n //~| ERROR moved_leaf_path: `$(local mut p).x`\n\n //~| ERROR unmoved_fragment: `$(local mut p).y`\n\n //~| ERROR assigned_leaf_path: `$(local _x)`\n\n let _x = p.x;\n\n}\n\n\n", "file_path": "src/test/compile-fail/move-fragments-5.rs", "rank": 92, "score": 308750.64159752 }, { "content": "pub fn f<T, F>((b1, b2): (T, T), mut f: F) -> Partial<T> where F: FnMut(T) -> T {\n\n let p = Partial { x: b1, y: b2 };\n\n\n\n // Move of `p` is legal even though we are also moving `p.y`; the\n\n // `..p` moves all fields *except* `p.y` in this context.\n\n Partial { y: f(p.y), ..p }\n\n}\n\n\n", "file_path": "src/test/run-pass/struct-partial-move-1.rs", "rank": 93, "score": 308745.5996851177 }, { "content": "pub fn main() {\n\n let _foo: Foo = Foo {\n\n name: 0\n\n };\n\n}\n", "file_path": "src/test/run-pass/pub-use-xcrate.rs", "rank": 94, "score": 308704.3881887174 }, { "content": "pub fn main() {\n\n #[derive(Copy)]\n\n enum x { foo }\n\n impl ::std::cmp::PartialEq for x {\n\n fn eq(&self, other: &x) -> bool {\n\n (*self) as int == (*other) as int\n\n }\n\n fn ne(&self, other: &x) -> bool { !(*self).eq(other) }\n\n }\n\n}\n", "file_path": "src/test/run-pass/coherence-impl-in-fn.rs", "rank": 95, "score": 308326.51665774884 }, { "content": "/// Like with walk_method_helper this doesn't correspond to a method\n\n/// in Visitor, and so it gets a _helper suffix.\n\npub fn walk_trait_ref<'v,V>(visitor: &mut V,\n\n trait_ref: &'v TraitRef)\n\n where V: Visitor<'v>\n\n{\n\n visitor.visit_path(&trait_ref.path, trait_ref.ref_id)\n\n}\n\n\n", "file_path": "src/libsyntax/visit.rs", "rank": 96, "score": 308084.7815036535 }, { "content": "struct TupleStruct (f64, int);\n\n\n\n\n", "file_path": "src/test/debuginfo/destructured-fn-argument.rs", "rank": 97, "score": 307824.81613825844 }, { "content": "fn one_struct_destructured_one_not((Struct { a: p, b: q }, r): (Struct, Struct)) {\n\n zzz(); // #break\n\n}\n\n\n", "file_path": "src/test/debuginfo/destructured-fn-argument.rs", "rank": 98, "score": 307639.0636658997 } ]
Rust
fuzzy_log_packets/src/storeables.rs
JLockerman/delos-rust
400a458c28524040b790e33f8e58809c60a948c5
use std::{mem, ptr, slice}; pub trait Storeable { fn size(&self) -> usize; unsafe fn ref_to_bytes(&self) -> &u8; unsafe fn ref_to_slice(&self) -> &[u8]; unsafe fn bytes_to_ref(&u8, usize) -> &Self; unsafe fn slice_to_ref(val: &[u8], size: usize) -> &Self; unsafe fn bytes_to_mut(&mut u8, usize) -> &mut Self; unsafe fn clone_box(&self) -> Box<Self>; unsafe fn copy_to_mut(&self, &mut Self) -> usize; } pub trait UnStoreable: Storeable { fn size_from_bytes(bytes: &u8) -> usize; fn size_from_slice(bytes: &[u8]) -> usize; unsafe fn unstore(bytes: &[u8]) -> &Self { let size = <Self as UnStoreable>::size_from_slice(bytes); <Self as Storeable>::slice_to_ref(bytes, size) } unsafe fn unstore_mut(bytes: &mut u8) -> &mut Self { let size = <Self as UnStoreable>::size_from_bytes(bytes); <Self as Storeable>::bytes_to_mut(bytes, size) } } impl<V> Storeable for V { fn size(&self) -> usize { mem::size_of::<Self>() } unsafe fn ref_to_bytes(&self) -> &u8 { mem::transmute(self) } unsafe fn ref_to_slice(&self) -> &[u8] { let ptr = self as *const V as *const u8; let size = self.size(); slice::from_raw_parts(ptr, size) } unsafe fn bytes_to_ref(val: &u8, _size: usize) -> &Self { mem::transmute(val) } unsafe fn slice_to_ref(val: &[u8], size: usize) -> &Self { assert_eq!(val.len(), size); mem::transmute(val.as_ptr()) } unsafe fn bytes_to_mut(val: &mut u8, size: usize) -> &mut Self { assert_eq!(size, mem::size_of::<Self>()); mem::transmute(val) } unsafe fn clone_box(&self) -> Box<Self> { let mut b = Box::new(mem::uninitialized()); ptr::copy_nonoverlapping(self, &mut *b, 1); b } unsafe fn copy_to_mut(&self, out: &mut Self) -> usize { ptr::copy(self, out, 1); mem::size_of::<Self>() } } impl<V> Storeable for [V] { fn size(&self) -> usize { mem::size_of::<V>() * self.len() } unsafe fn ref_to_bytes(&self) -> &u8 { mem::transmute(self.as_ptr()) } unsafe fn ref_to_slice(&self) -> &[u8] { let ptr = self as *const _ as *const u8; let size = self.size(); slice::from_raw_parts(ptr, size) } unsafe fn bytes_to_ref(val: &u8, size: usize) -> &Self { assert_eq!(size % mem::size_of::<V>(), 0); slice::from_raw_parts(val as *const _ as *const _, size / mem::size_of::<V>()) } unsafe fn slice_to_ref(val: &[u8], size: usize) -> &Self { assert_eq!(size % mem::size_of::<V>(), 0); assert_eq!(val.len(), size); slice::from_raw_parts(val.as_ptr() as *const V, size / mem::size_of::<V>()) } unsafe fn bytes_to_mut(val: &mut u8, size: usize) -> &mut Self { assert_eq!(size % mem::size_of::<V>(), 0); slice::from_raw_parts_mut(val as *mut _ as *mut _, size / mem::size_of::<V>()) } unsafe fn clone_box(&self) -> Box<Self> { let mut v = Vec::with_capacity(self.len()); v.set_len(self.len()); let mut b = v.into_boxed_slice(); ptr::copy_nonoverlapping(self.as_ptr(), b.as_mut_ptr(), self.len()); b } unsafe fn copy_to_mut(&self, out: &mut Self) -> usize { let to_copy = ::std::cmp::min(self.len(), out.len()); ptr::copy(self.as_ptr(), out.as_mut_ptr(), to_copy); to_copy * mem::size_of::<V>() } } impl<V> UnStoreable for V { fn size_from_bytes(_: &u8) -> usize { mem::size_of::<Self>() } fn size_from_slice(_: &[u8]) -> usize { mem::size_of::<Self>() } } impl<V> UnStoreable for [V] { fn size_from_bytes(_: &u8) -> usize { unimplemented!() } fn size_from_slice(bytes: &[u8]) -> usize { bytes.len() } } #[test] fn store_u8() { unsafe { assert_eq!(32u8.ref_to_slice(), &[32]); assert_eq!(0u8.ref_to_slice(), &[0]); assert_eq!(255u8.ref_to_slice(), &[255]); } } #[test] fn round_u32() { unsafe { assert_eq!(32u32.ref_to_slice().len(), 4); assert_eq!(0u32.ref_to_slice().len(), 4); assert_eq!(255u32.ref_to_slice().len(), 4); assert_eq!(0xff0fbedu32.ref_to_slice().len(), 4); assert_eq!(u32::unstore(&32u32.ref_to_slice()), &32); assert_eq!(u32::unstore(&0u32.ref_to_slice()), &0); assert_eq!(u32::unstore(&255u32.ref_to_slice()), &255); assert_eq!(u32::unstore(&0xff0fbedu32.ref_to_slice()), &0xff0fbedu32); } }
use std::{mem, ptr, slice}; pub trait Storeable { fn size(&self) -> usize; unsafe fn ref_to_bytes(&self) -> &u8; unsafe fn ref_to_slice(&self) -> &[u8]; unsafe fn bytes_to_ref(&u8, usize) -> &Self; unsafe fn slice_to_ref(val: &[u8], size: usize) -> &Self; unsafe fn bytes_to_mut(&mut u8, usize) -> &mut Self; unsafe fn clone_box(&self) -> Box<Self>; unsafe fn copy_to_mut(&self, &mut Self) -> usize; } pub trait UnStoreable: Storeable { fn size_from_bytes(bytes: &u8) -> usize; fn size_from_slice(bytes: &[u8]) -> usize; unsafe fn unstore(bytes: &[u8]) -> &Self { let size = <Self as UnStoreable>::size_from_slice(bytes); <Self as Storeable>::slice_to_ref(bytes, size) } unsafe fn unstore_mut(bytes: &mut u8) -> &mut Self { let size = <Self as UnStoreable>::size_from_bytes(bytes);
pl<V> Storeable for [V] { fn size(&self) -> usize { mem::size_of::<V>() * self.len() } unsafe fn ref_to_bytes(&self) -> &u8 { mem::transmute(self.as_ptr()) } unsafe fn ref_to_slice(&self) -> &[u8] { let ptr = self as *const _ as *const u8; let size = self.size(); slice::from_raw_parts(ptr, size) } unsafe fn bytes_to_ref(val: &u8, size: usize) -> &Self { assert_eq!(size % mem::size_of::<V>(), 0); slice::from_raw_parts(val as *const _ as *const _, size / mem::size_of::<V>()) } unsafe fn slice_to_ref(val: &[u8], size: usize) -> &Self { assert_eq!(size % mem::size_of::<V>(), 0); assert_eq!(val.len(), size); slice::from_raw_parts(val.as_ptr() as *const V, size / mem::size_of::<V>()) } unsafe fn bytes_to_mut(val: &mut u8, size: usize) -> &mut Self { assert_eq!(size % mem::size_of::<V>(), 0); slice::from_raw_parts_mut(val as *mut _ as *mut _, size / mem::size_of::<V>()) } unsafe fn clone_box(&self) -> Box<Self> { let mut v = Vec::with_capacity(self.len()); v.set_len(self.len()); let mut b = v.into_boxed_slice(); ptr::copy_nonoverlapping(self.as_ptr(), b.as_mut_ptr(), self.len()); b } unsafe fn copy_to_mut(&self, out: &mut Self) -> usize { let to_copy = ::std::cmp::min(self.len(), out.len()); ptr::copy(self.as_ptr(), out.as_mut_ptr(), to_copy); to_copy * mem::size_of::<V>() } } impl<V> UnStoreable for V { fn size_from_bytes(_: &u8) -> usize { mem::size_of::<Self>() } fn size_from_slice(_: &[u8]) -> usize { mem::size_of::<Self>() } } impl<V> UnStoreable for [V] { fn size_from_bytes(_: &u8) -> usize { unimplemented!() } fn size_from_slice(bytes: &[u8]) -> usize { bytes.len() } } #[test] fn store_u8() { unsafe { assert_eq!(32u8.ref_to_slice(), &[32]); assert_eq!(0u8.ref_to_slice(), &[0]); assert_eq!(255u8.ref_to_slice(), &[255]); } } #[test] fn round_u32() { unsafe { assert_eq!(32u32.ref_to_slice().len(), 4); assert_eq!(0u32.ref_to_slice().len(), 4); assert_eq!(255u32.ref_to_slice().len(), 4); assert_eq!(0xff0fbedu32.ref_to_slice().len(), 4); assert_eq!(u32::unstore(&32u32.ref_to_slice()), &32); assert_eq!(u32::unstore(&0u32.ref_to_slice()), &0); assert_eq!(u32::unstore(&255u32.ref_to_slice()), &255); assert_eq!(u32::unstore(&0xff0fbedu32.ref_to_slice()), &0xff0fbedu32); } }
<Self as Storeable>::bytes_to_mut(bytes, size) } } impl<V> Storeable for V { fn size(&self) -> usize { mem::size_of::<Self>() } unsafe fn ref_to_bytes(&self) -> &u8 { mem::transmute(self) } unsafe fn ref_to_slice(&self) -> &[u8] { let ptr = self as *const V as *const u8; let size = self.size(); slice::from_raw_parts(ptr, size) } unsafe fn bytes_to_ref(val: &u8, _size: usize) -> &Self { mem::transmute(val) } unsafe fn slice_to_ref(val: &[u8], size: usize) -> &Self { assert_eq!(val.len(), size); mem::transmute(val.as_ptr()) } unsafe fn bytes_to_mut(val: &mut u8, size: usize) -> &mut Self { assert_eq!(size, mem::size_of::<Self>()); mem::transmute(val) } unsafe fn clone_box(&self) -> Box<Self> { let mut b = Box::new(mem::uninitialized()); ptr::copy_nonoverlapping(self, &mut *b, 1); b } unsafe fn copy_to_mut(&self, out: &mut Self) -> usize { ptr::copy(self, out, 1); mem::size_of::<Self>() } } im
random
[ { "content": "pub fn slice_to_multi(bytes: &mut [u8]) {\n\n bytes[0] = unsafe { ::std::mem::transmute(EntryKind::Multiput) };\n\n unsafe { debug_assert!(EntryContents::try_ref(bytes).is_ok()) }\n\n}\n\n\n", "file_path": "fuzzy_log_packets/src/lib.rs", "rank": 0, "score": 302795.3422425555 }, { "content": "pub fn slice_to_skeens1_sentirep(bytes: &mut [u8]) {\n\n bytes[0] = unsafe { ::std::mem::transmute(EntryKind::SentinelToReplica) };\n\n unsafe { debug_assert!(EntryContents::try_ref(bytes).is_ok()) }\n\n}\n\n\n\n///////////////////////////////////////\n\n///////////////////////////////////////\n\n///////////////////////////////////////\n\n///////////////////////////////////////\n\n\n\n#[cfg(test)]\n\nmod test {\n\n\n\n use super::*;\n\n\n\n use byteorder::{ByteOrder, LittleEndian};\n\n\n\n //use std::marker::PhantomData;\n\n\n\n //#[test]\n", "file_path": "fuzzy_log_packets/src/lib.rs", "rank": 1, "score": 297711.0110105971 }, { "content": "pub fn slice_to_skeens1_multirep(bytes: &mut [u8]) {\n\n bytes[0] = unsafe { ::std::mem::transmute(EntryKind::MultiputToReplica) };\n\n unsafe { debug_assert!(EntryContents::try_ref(bytes).is_ok()) }\n\n}\n\n\n", "file_path": "fuzzy_log_packets/src/lib.rs", "rank": 2, "score": 297711.0110105971 }, { "content": "pub fn slice_to_sentinel(bytes: &mut [u8]) -> bool {\n\n let old_kind: EntryKind::Kind = unsafe { ::std::mem::transmute(bytes[0]) };\n\n bytes[0] = unsafe { ::std::mem::transmute(EntryKind::Sentinel) };\n\n unsafe { debug_assert!(EntryContents::try_ref(bytes).is_ok()) }\n\n old_kind == EntryKind::Multiput || old_kind == EntryKind::MultiputToReplica\n\n}\n\n\n", "file_path": "fuzzy_log_packets/src/lib.rs", "rank": 3, "score": 290591.2063760455 }, { "content": "fn fill_buffer(buffer: &mut VecDeque<u8>, from: &[u8], used: &mut usize) -> usize {\n\n let in_from = from.len() - *used;\n\n let to_copy = min(in_from, remaining_space);\n\n let copy_end = *used + to_copy;\n\n //TODO manual memcopy?\n\n self.buf.extend(from[*used..copy_end]);\n\n *used += to_copy;\n\n to_copy\n\n}\n", "file_path": "tokio_server/src/buf_writer.rs", "rank": 4, "score": 284343.3519768334 }, { "content": "pub fn data_to_slice<V: ?Sized + Storeable>(data: &V) -> &[u8] {\n\n unsafe { <V as Storeable>::ref_to_slice(data) }\n\n}\n\n\n", "file_path": "fuzzy_log_packets/src/lib.rs", "rank": 5, "score": 281831.9935771423 }, { "content": "pub fn slice_to_data<V: ?Sized + UnStoreable + Storeable>(data: &[u8]) -> &V {\n\n unsafe { <V as UnStoreable>::unstore(data) }\n\n}\n\n\n", "file_path": "fuzzy_log_packets/src/lib.rs", "rank": 6, "score": 281232.92299381236 }, { "content": "pub fn bytes_as_entry_mut(bytes: &mut [u8]) -> EntryContentsMut {\n\n unsafe { Packet::Mut::try_mut(bytes).unwrap().0 }\n\n}\n\n\n\npub unsafe fn data_bytes(bytes: &[u8]) -> &[u8] {\n\n /*match Entry::<[u8]>::wrap_bytes(bytes).contents() {\n\n EntryContents::Data(data, ..) | EntryContents::Multiput{data, ..} => data,\n\n EntryContents::Sentinel(..) => &[],\n\n }*/\n\n use self::Packet::Ref::*;\n\n match bytes_as_entry(bytes) {\n\n Read{..} | Senti{..} | SentiToReplica{..} | Skeens2ToReplica{..}\n\n | GC{..}\n\n | FenceClient{..} | UpdateRecovery{..} | CheckSkeens1{..}\n\n | Snapshot{..} | SnapshotToReplica{..} => unreachable!(),\n\n\n\n Single{data, ..} | Multi{data, ..}\n\n | SingleToReplica{data, ..} | MultiToReplica{data, ..} => data,\n\n }\n\n}\n\n\n", "file_path": "fuzzy_log_packets/src/lib.rs", "rank": 7, "score": 262145.3354558446 }, { "content": "pub fn blocking_read<R: Read>(r: &mut R, mut buffer: &mut [u8]) -> io::Result<()> {\n\n //like Read::read_exact but doesn't die on WouldBlock\n\n 'recv: while !buffer.is_empty() {\n\n match r.read(buffer) {\n\n Ok(i) => { let tmp = buffer; buffer = &mut tmp[i..]; }\n\n Err(e) => match e.kind() {\n\n io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted | io::ErrorKind::NotConnected => {\n\n thread::yield_now();\n\n continue 'recv\n\n },\n\n _ => { return Err(e) }\n\n }\n\n }\n\n }\n\n if !buffer.is_empty() {\n\n return Err(io::Error::new(io::ErrorKind::UnexpectedEof,\n\n \"failed to fill whole buffer\"))\n\n }\n\n else {\n\n return Ok(())\n\n }\n\n}\n\n\n", "file_path": "fuzzy_log_server/src/tcp/mod.rs", "rank": 8, "score": 234404.09058698587 }, { "content": "pub fn blocking_write<W: Write>(w: &mut W, mut buffer: &[u8]) -> io::Result<()> {\n\n //like Write::write_all but doesn't die on WouldBlock\n\n 'recv: while !buffer.is_empty() {\n\n match w.write(buffer) {\n\n Ok(i) => { let tmp = buffer; buffer = &tmp[i..]; }\n\n Err(e) => match e.kind() {\n\n io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted | io::ErrorKind::NotConnected => {\n\n thread::yield_now();\n\n continue 'recv\n\n },\n\n _ => { return Err(e) }\n\n }\n\n }\n\n }\n\n if !buffer.is_empty() {\n\n return Err(io::Error::new(io::ErrorKind::WriteZero,\n\n \"failed to fill whole buffer\"))\n\n }\n\n else {\n\n return Ok(())\n", "file_path": "fuzzy_log_server/src/tcp/mod.rs", "rank": 9, "score": 227111.70042374608 }, { "content": "#[allow(dead_code)]\n\nfn alloc_seg2() -> *mut u8 {\n\n let b: Box<[u8; LEVEL_BYTES]> = Box::new([0; LEVEL_BYTES]);\n\n let b = Box::into_raw(b);\n\n unsafe { &mut (*b)[0] }\n\n}\n\n\n", "file_path": "fuzzy_log_server/src/trie.rs", "rank": 10, "score": 217272.87876431376 }, { "content": "pub fn get_allocation_for(handle: &mut Handle, key: &[u8]) -> Option<Vec<order>> {\n\n let mut alloc = Allocator::new();\n\n handle.rewind(OrderIndex(alloc.alloc_color, 0.into()));\n\n alloc.update_allocations(handle).get_allocation_for(key)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n #[test]\n\n fn it_works() {\n\n }\n\n}\n", "file_path": "fuzzy_views/color_alloc/src/lib.rs", "rank": 11, "score": 214298.66227963148 }, { "content": "#[bench]\n\npub fn create(b: &mut Bencher) {\n\n message::set_client_id(101);\n\n let my_root = \"/abcd/\".into();\n\n let mut roots = HashMap::new();\n\n roots.insert(\"abcd\".into(), 101.into());\n\n let mut files = FileSystem::new(my_root, roots);\n\n let mut i = 0u64;\n\n b.iter(|| {\n\n files.apply_mutation(\n\n Create {\n\n id: Id::new(),\n\n create_mode: CreateMode::persistent(),\n\n path: format!(\"/abcd/{}\", i).into(),\n\n data: vec![0, 1, 2, i as u8],\n\n },\n\n WhichPath::Path1,\n\n |id, r, m0, m1| {\n\n black_box((id, r, m0, m1));\n\n i += 1\n\n },\n\n );\n\n })\n\n}\n\n\n", "file_path": "examples/zookeeper/benches/lib.rs", "rank": 13, "score": 207358.98592419433 }, { "content": "pub fn allocate(handle: &mut Handle, num_colors: u64, key: &[u8]) -> Vec<order> {\n\n let mut alloc = Allocator::new();\n\n handle.rewind(OrderIndex(alloc.alloc_color, 0.into()));\n\n alloc.allocate(handle, num_colors, key)\n\n}\n\n\n", "file_path": "fuzzy_views/color_alloc/src/lib.rs", "rank": 14, "score": 207281.1801055704 }, { "content": "#[bench]\n\npub fn create_rename(b: &mut Bencher) {\n\n let my_root = \"/abcd/\".into();\n\n let mut roots = HashMap::new();\n\n roots.insert(\"abcd\".into(), 101.into());\n\n let mut files = FileSystem::new(my_root, roots);\n\n let mut i = 0u64;\n\n b.iter(|| {\n\n files.apply_mutation(\n\n Create {\n\n id: Id::new(),\n\n create_mode: CreateMode::persistent(),\n\n path: format!(\"/abcd/{}\", i).into(),\n\n data: vec![0, 1, 2, i as u8],\n\n },\n\n WhichPath::Path1,\n\n |id, r, m0, m1| {\n\n black_box((id, r, m0, m1));\n\n },\n\n );\n\n let rename_id = Id::new();\n", "file_path": "examples/zookeeper/benches/lib.rs", "rank": 16, "score": 203761.34384778995 }, { "content": "pub fn bytes_as_entry(bytes: &[u8]) -> EntryContents {\n\n unsafe { Packet::Ref::try_ref(bytes).unwrap().0 }\n\n}\n\n\n", "file_path": "fuzzy_log_packets/src/lib.rs", "rank": 17, "score": 194255.88215288706 }, { "content": "fn blocking_read<R: Read>(r: &mut R, mut buffer: &mut [u8]) -> io::Result<()> {\n\n use std::thread;\n\n //like Read::read_exact but doesn't die on WouldBlock\n\n 'recv: while !buffer.is_empty() {\n\n match r.read(buffer) {\n\n Ok(i) => { let tmp = buffer; buffer = &mut tmp[i..]; }\n\n Err(e) => match e.kind() {\n\n io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted | io::ErrorKind::NotConnected => {\n\n thread::yield_now();\n\n continue 'recv\n\n },\n\n _ => { return Err(e) }\n\n }\n\n }\n\n }\n\n if !buffer.is_empty() {\n\n return Err(io::Error::new(io::ErrorKind::UnexpectedEof,\n\n \"failed to fill whole buffer\"))\n\n }\n\n else {\n\n return Ok(())\n\n }\n\n}\n", "file_path": "fuzzy_log_client/src/store.rs", "rank": 18, "score": 191506.55952066078 }, { "content": "fn blocking_write<W: Write>(w: &mut W, mut buffer: &[u8]) -> io::Result<()> {\n\n //like Write::write_all but doesn't die on WouldBlock\n\n 'recv: while !buffer.is_empty() {\n\n match w.write(buffer) {\n\n Ok(i) => { let tmp = buffer; buffer = &tmp[i..]; }\n\n Err(e) => match e.kind() {\n\n io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted => {\n\n thread::yield_now();\n\n continue 'recv\n\n },\n\n _ => { return Err(e) }\n\n }\n\n }\n\n }\n\n if !buffer.is_empty() {\n\n return Err(io::Error::new(io::ErrorKind::WriteZero,\n\n \"failed to fill whole buffer\"))\n\n }\n\n else {\n\n return Ok(())\n\n }\n\n}\n\n\n", "file_path": "benchers/failure/src/main.rs", "rank": 19, "score": 185683.02480246968 }, { "content": "fn blocking_write<W: Write>(w: &mut W, mut buffer: &[u8]) -> io::Result<()> {\n\n //like Write::write_all but doesn't die on WouldBlock\n\n 'recv: while !buffer.is_empty() {\n\n match w.write(buffer) {\n\n Ok(i) => { let tmp = buffer; buffer = &tmp[i..]; }\n\n Err(e) => match e.kind() {\n\n io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted => {\n\n thread::yield_now();\n\n continue 'recv\n\n },\n\n _ => { return Err(e) }\n\n }\n\n }\n\n }\n\n if !buffer.is_empty() {\n\n return Err(io::Error::new(io::ErrorKind::WriteZero,\n\n \"failed to fill whole buffer\"))\n\n }\n\n else {\n\n return Ok(())\n\n }\n\n}\n\n\n", "file_path": "benchers/replicated_failure/src/main.rs", "rank": 20, "score": 183232.3987107229 }, { "content": "fn blocking_write<W: Write>(w: &mut W, mut buffer: &[u8]) -> io::Result<()> {\n\n use std::thread;\n\n //like Write::write_all but doesn't die on WouldBlock\n\n 'recv: while !buffer.is_empty() {\n\n match w.write(buffer) {\n\n Ok(i) => { let tmp = buffer; buffer = &tmp[i..]; }\n\n Err(e) => match e.kind() {\n\n io::ErrorKind::WouldBlock\n\n | io::ErrorKind::Interrupted\n\n | io::ErrorKind::NotConnected => {\n\n thread::yield_now();\n\n continue 'recv\n\n },\n\n _ => { return Err(e) }\n\n }\n\n }\n\n }\n\n if !buffer.is_empty() {\n\n return Err(io::Error::new(io::ErrorKind::WriteZero,\n\n \"failed to fill whole buffer\"))\n\n }\n\n else {\n\n return Ok(())\n\n }\n\n}\n\n\n", "file_path": "fuzzy_log_client/src/store.rs", "rank": 21, "score": 183232.3987107229 }, { "content": "pub trait Mergeable: Sized + Eq {\n\n #[allow(unused_variables)]\n\n fn can_be_replaced_with(&self, other: &Self) -> bool { true }\n\n\n\n fn can_merge_with_prior(self, other: &Self) -> Result<Self, Self> {\n\n if &self == other { Ok(self) } else { Err(self) }\n\n }\n\n\n\n fn can_merge_with_next(self, other: &Self) -> Result<Self, Self> {\n\n self.can_merge_with_prior(other)\n\n }\n\n}\n\n\n\nimpl<V> RangeTree<V> {\n\n pub fn with_default_val(v: V) -> Self {\n\n let mut map = BTreeMap::new();\n\n map.insert(Range::new(0, u64::MAX.into()), v);\n\n RangeTree {\n\n inner: map,\n\n }\n", "file_path": "fuzzy_log_util/src/range_tree.rs", "rank": 22, "score": 179856.7600144202 }, { "content": "pub fn append_message<V: ?Sized>(chain: order, data: &V, deps: &[OrderIndex]) -> Vec<u8>\n\nwhere V: Storeable {\n\n //TODO no-alloc?\n\n let id = Uuid::new_v4();\n\n let mut buffer = Vec::new();\n\n EntryContents::Single {\n\n id: &id,\n\n flags: &EntryFlag::Nothing,\n\n loc: &OrderIndex(chain, 0.into()),\n\n deps: deps,\n\n data: data_to_slice(data),\n\n timestamp: &0, //TODO\n\n }.fill_vec(&mut buffer);\n\n buffer\n\n}\n\n\n", "file_path": "fuzzy_log_client/src/fuzzy_log/log_handle.rs", "rank": 23, "score": 173863.44410045963 }, { "content": "pub fn multiappend_message<V: ?Sized>(chains: &[order], data: &V, deps: &[OrderIndex]) -> Vec<u8>\n\nwhere V: Storeable {\n\n //TODO no-alloc?\n\n assert!(chains.len() > 1);\n\n let mut locs: Vec<_> = chains.into_iter().map(|&o| OrderIndex(o, 0.into())).collect();\n\n locs.sort();\n\n locs.dedup();\n\n let id = Uuid::new_v4();\n\n let mut buffer = Vec::new();\n\n EntryContents::Multi {\n\n id: &id,\n\n flags: &(EntryFlag::NewMultiPut | EntryFlag::NoRemote),\n\n lock: &0,\n\n locs: &locs,\n\n deps: deps,\n\n data: data_to_slice(data),\n\n }.fill_vec(&mut buffer);\n\n buffer\n\n}\n\n\n", "file_path": "fuzzy_log_client/src/fuzzy_log/log_handle.rs", "rank": 24, "score": 173863.44410045963 }, { "content": "pub fn add_contents(io: &mut TcpWriter, contents: EntryContents) {\n\n io.add_contents_to_write(contents, &[])\n\n}\n\n\n\npub struct PacketReader {\n\n buffer_cache: VecDeque<Buffer>,\n\n is_replica: bool,\n\n}\n\n\n\nimpl MessageReader for PacketReader {\n\n type Message = (Buffer, Ipv4SocketAddr, Option<u64>);\n\n type Error = ErrorKind;\n\n\n\n fn deserialize_message(\n\n &mut self,\n\n bytes: &[u8]\n\n ) -> Result<(Self::Message, usize), MessageReaderError<Self::Error>> {\n\n use self::MessageReaderError::*;\n\n use packets::Packet::WrapErr;\n\n\n", "file_path": "fuzzy_log_server/src/tcp/per_socket.rs", "rank": 25, "score": 171084.951099358 }, { "content": "fn recv_packet(buffer: &mut Buffer, mut stream: &TcpStream, mut read: usize) -> RecvRes {\n\n use std::io::ErrorKind;\n\n let bhs = base_header_size();\n\n if read < bhs {\n\n let r = stream.read(&mut buffer[read..bhs])\n\n .or_else(|e| if e.kind() == ErrorKind::WouldBlock { Ok(read) } else { Err(e) } )\n\n .ok();\n\n match r {\n\n Some(i) => read += i,\n\n None => return RecvRes::Error,\n\n }\n\n if read < bhs {\n\n return RecvRes::NeedsMore(read)\n\n }\n\n }\n\n\n\n let header_size = buffer.entry().header_size();\n\n assert!(header_size >= base_header_size());\n\n if read < header_size {\n\n let r = stream.read(&mut buffer[read..header_size])\n", "file_path": "benchers/trivial_server/src/main.rs", "rank": 26, "score": 170042.90566800267 }, { "content": "fn write_all<W: Write>(w: &mut W, mut buf: &[u8], done: &AtomicBool) -> Result<bool, IoError> {\n\n let mut finished_normal = true;\n\n while !buf.is_empty() {\n\n if done.load(Ordering::Relaxed) {\n\n finished_normal = false;\n\n break\n\n }\n\n match w.write(buf) {\n\n Ok(0) => return Err(IoError::new(IoErrorKind::WriteZero, \"failed to write whole buffer\")),\n\n Ok(n) => buf = &buf[n..],\n\n Err(ref e) if e.kind() == IoErrorKind::Interrupted => {}\n\n Err(e) => return Err(e),\n\n }\n\n }\n\n Ok(finished_normal)\n\n}\n\n\n\n/////////////////////////\n\n\n\nconst WAIT_CHAIN: u32 = 10_000;\n\n\n", "file_path": "fuzzy_views/ml/src/main.rs", "rank": 27, "score": 166499.1958405796 }, { "content": "pub trait Wakeable {\n\n fn init(&mut self, token: mio::Token, poll: &mut mio::Poll);\n\n fn needs_to_mark_as_staying_awake(&mut self, token: mio::Token) -> bool;\n\n fn mark_as_staying_awake(&mut self, token: mio::Token);\n\n fn is_marked_as_staying_awake(&self, token: mio::Token) -> bool;\n\n}\n\n\n", "file_path": "reactor/src/lib.rs", "rank": 29, "score": 163554.288909416 }, { "content": "trait NullablePtr: Sized {\n\n type Output;\n\n type Load;\n\n\n\n unsafe fn atomic_load(&self, order: Ordering) -> Self::Load {\n\n <Self as NullablePtr>::to_loaded_form(to_atom(self).load(order))\n\n }\n\n\n\n unsafe fn to_loaded_form(ptr: *mut Self::Output) -> Self::Load;\n\n}\n\n\n\nimpl<T> NullablePtr for Box<T> {\n\n type Output = T;\n\n type Load = *const T;\n\n\n\n unsafe fn to_loaded_form(ptr: *mut Self::Output) -> Self::Load {\n\n mem::transmute(ptr)\n\n }\n\n}\n\nimpl<T> NullablePtr for Option<Box<T>> {\n", "file_path": "fuzzy_log_server/src/trie.rs", "rank": 30, "score": 162212.94065039503 }, { "content": "pub trait MessageReader {\n\n type Message;\n\n\n\n type Error: ::std::fmt::Debug;\n\n\n\n fn deserialize_message(&mut self, bytes: &[u8])\n\n -> Result<(Self::Message, usize), MessageReaderError<Self::Error>>;\n\n\n\n fn deserialize_messages<'s>(&'s mut self, bytes: &'s [u8], size_out: &'s mut usize)\n\n -> Messages<'s, Self> {\n\n Messages {\n\n bytes,\n\n read: 0,\n\n size_out,\n\n reader: self,\n\n done: false,\n\n }\n\n }\n\n}\n\n\n\n///////////////////\n\n\n", "file_path": "reactor/src/lib.rs", "rank": 31, "score": 160659.8976666746 }, { "content": "#[inline(always)]\n\nfn level_index_for_key(key: u64, depth: u8) -> usize {\n\n ((key >> (ROOT_SHIFT - (SHIFT_LEN * depth))) & MASK) as usize\n\n}\n\n\n\nmacro_rules! index {\n\n ($array:ident, $k:expr, $depth:expr) => {\n\n {\n\n let index = level_index_for_key($k, $depth);\n\n //let index = (($k >> (ROOT_SHIFT - (SHIFT_LEN * $depth))) & MASK) as usize;\n\n assert!(index < ARRAY_SIZE, \"index: {}\", index);\n\n match *$array {\n\n None => return None,\n\n Some(ref ptr) => &(**ptr)[index],\n\n }\n\n }\n\n };\n\n}\n\n\n\nmacro_rules! index_mut {\n\n ($array:ident, $k:expr, $depth:expr) => {\n", "file_path": "fuzzy_log_server/src/trie.rs", "rank": 32, "score": 159878.61898558354 }, { "content": "fn append(handle: &mut LogHandle<[u8]>, args: &Args, chain: u32, i: u32) {\n\n match args.experiment {\n\n Experiment::NoLink => {\n\n handle.async_append(chain.into(), &BYTES[..], &[]);\n\n }\n\n Experiment::ZigZag => {\n\n let index = i + 1;\n\n if chain == args.first_chain() {\n\n if args.num_chains > 1 && index > 1 {\n\n handle.async_append(\n\n chain.into(), &BYTES[..], &[(args.last_chain(), index-1).into()]\n\n );\n\n } else {\n\n handle.async_append(chain.into(), &BYTES[..], &[]);\n\n }\n\n } else {\n\n assert!(chain > 1);\n\n handle.async_append(\n\n chain.into(), &BYTES[..], &[(chain-1, index).into()]\n\n );\n\n }\n\n },\n\n }\n\n}\n", "file_path": "benchers/read_latency/src/main.rs", "rank": 33, "score": 159652.58286657825 }, { "content": "/// Start a fuzzy log TCP server.\n\n///\n\n/// This function takes over the current thread and never returns.\n\n/// It will spawn at least two additional threads, one to perform ordering and\n\n/// at least one worker.\n\n///\n\n/// # Args\n\n/// * `addr` the address on which the server should accept connection.\n\n/// * `server_num` the the number which this server is in it's server group\n\n/// must be in `0..group_size`.\n\n/// * `group_size` the number of servers in this servers server-group,\n\n/// must be at least 1.\n\n/// * `prev_server` the server which precedes this one in the replication chain,\n\n/// if it exists.\n\n/// * `next_server` the server which comes after this one in the replication chain,\n\n/// if it exists.\n\n/// * `num_worker_threads` the number of workers that should be spawned,\n\n/// must be at least 1.\n\n/// * `started` an atomic counter which will be incremented once the server starts.\n\n///\n\npub fn run_server(\n\n addr: std::net::SocketAddr,\n\n server_num: u32,\n\n group_size: u32,\n\n prev_server: Option<std::net::SocketAddr>,\n\n next_server: Option<std::net::IpAddr>,\n\n num_worker_threads: usize,\n\n started: &std::sync::atomic::AtomicUsize,\n\n) -> ! {\n\n let acceptor = mio::tcp::TcpListener::bind(&addr)\n\n .expect(\"Bind error\");\n\n servers2::tcp::run_with_replication(\n\n acceptor, server_num, group_size, prev_server, next_server, num_worker_threads, started\n\n )\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 34, "score": 159248.71714522637 }, { "content": "fn update_local<K, V>(local_view: &mut HashMap<K, V>, data: &[u8])\n\nwhere\n\n K: for<'de> Deserialize<'de> + Hash + Eq,\n\n V: for<'de> Deserialize<'de>, {\n\n match deserialize(data).unwrap() {\n\n Op::Put(key, val) => { local_view.insert(key, val); },\n\n Op::Rem(key) => { local_view.remove(&key); },\n\n Op::PutOnNotFound(key, val) => {\n\n local_view.entry(key).or_insert(val);\n\n },\n\n }\n\n}\n\n\n\nimpl<K, V> Map<K, V>\n\nwhere K: Hash + Eq {\n\n pub fn from_log_handle(log: LogHandle<[u8]>, append_to: order) -> Self {\n\n (log, append_to).into()\n\n }\n\n}\n\n\n", "file_path": "examples/simple_map/src/lib.rs", "rank": 35, "score": 158005.77683163018 }, { "content": "pub trait MutationAck {\n\n fn ack(&mut self, id: Uuid);\n\n}\n\n\n\nimpl MutationAck for () {\n\n fn ack(&mut self, _: Uuid) {}\n\n}\n\n\n\nimpl<F> MutationAck for F\n\nwhere\n\n F: FnMut(Uuid),\n\n{\n\n fn ack(&mut self, id: Uuid) {\n\n self(id)\n\n }\n\n}\n\n\n\nimpl MutationAck for Sender<Uuid> {\n\n fn ack(&mut self, id: Uuid) {\n\n let _ = self.send(id);\n", "file_path": "examples/redblue/src/lib.rs", "rank": 36, "score": 157941.6102976018 }, { "content": "#[inline(always)]\n\nfn min_recv_size() -> usize {\n\n Packet::min_len() + mem::size_of::<ClientId>()\n\n}\n\n\n", "file_path": "tokio_server/src/lib.rs", "rank": 37, "score": 157891.2332175469 }, { "content": "#[inline(always)]\n\nfn client_id_size() -> usize {\n\n mem::size_of::<ClientId>()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n // use fuzzy_log_packets::*;\n\n\n\n use std::collections::HashMap;\n\n\n\n use tokio::net::TcpStream;\n\n\n\n macro_rules! read_packet {\n\n ($order: expr, $index:expr) => (\n\n EntryContents::Read {\n\n id: &Uuid::nil(),\n\n flags: &EntryFlag::Nothing,\n\n data_bytes: &0,\n\n dependency_bytes: &0,\n", "file_path": "tokio_server/src/lib.rs", "rank": 38, "score": 157891.2332175469 }, { "content": "pub fn add_response(msg: ToWorker<u64>, write_buffer: &mut BufferStream, worker_num: u64)\n\n-> Option<Buffer> {\n\n //TODO downstream?\n\n worker_thread::handle_to_worker2(msg, worker_num as usize, /*continue_replication*/ false, |to_send, _, _| {\n\n use worker_thread::ToSend;\n\n match to_send {\n\n ToSend::Nothing => return,\n\n ToSend::OldReplication(..) => unreachable!(),\n\n\n\n ToSend::Contents(to_send) | ToSend::OldContents(to_send, _) => write_buffer.add_contents(to_send),\n\n\n\n ToSend::Slice(to_send) => write_buffer.add_slice(to_send),\n\n\n\n ToSend::StaticSlice(to_send) | ToSend::Read(to_send) => write_buffer.add_slice(to_send),\n\n }\n\n }).0\n\n}\n", "file_path": "tokio_server/src/worker.rs", "rank": 39, "score": 157744.86833096927 }, { "content": "#[inline(never)]\n\npub fn run_server(addr: SocketAddr, num_workers: usize) -> ! {\n\n // let mut event_loop = EventLoop::new().unwrap();\n\n // let server = TcpServer::new(&addr, 0, 1, &mut event_loop);\n\n // if let Ok(mut server) = server {\n\n // let _ = event_loop.run(&mut server);\n\n // panic!(\"server should never return\")\n\n // }\n\n // else { panic!(\"socket in use\") }\n\n let acceptor = mio::tcp::TcpListener::bind(&addr);\n\n if let Ok(acceptor) = acceptor {\n\n servers2::tcp::run(acceptor, 0, 1, num_workers, &AtomicUsize::new(0))\n\n }\n\n else {\n\n panic!(\"socket in use\")\n\n }\n\n}\n\n\n", "file_path": "benchers/trivial_server/src/main.rs", "rank": 40, "score": 156814.9847120787 }, { "content": "pub fn run(\n\n port: u16,\n\n workers: usize,\n\n upstream: Option<SocketAddr>,\n\n downstream: Option<IpAddr>,\n\n group: Option<(u32, u32)>,\n\n) -> ! {\n\n let a = AtomicUsize::new(0);\n\n let (server_num, group_size) = group.unwrap_or((0, 1));\n\n let replicated = upstream.is_some() || downstream.is_some();\n\n let ip_addr = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0));\n\n let addr = SocketAddr::new(ip_addr, port);\n\n let acceptor = mio::tcp::TcpListener::bind(&addr);\n\n match acceptor {\n\n Ok(accept) => if replicated {\n\n servers2::tcp::run_with_replication(accept, server_num, group_size,\n\n upstream, downstream, workers, &a)\n\n } else {\n\n servers2::tcp::run(accept, server_num, group_size, workers, &a)\n\n },\n\n Err(e) => panic!(\"Could not start server due to {}.\", e),\n\n }\n\n}\n", "file_path": "benchers/throughput/src/servers.rs", "rank": 41, "score": 156372.26593564608 }, { "content": "pub fn run(\n\n listener: TcpListener,\n\n sender: mpsc::Sender<ToLog<u64>>,\n\n log_reader: ChainReader<u64>,\n\n replication: Option<bool>,\n\n) {\n\n let mut next = 0;\n\n let server = listener\n\n .incoming()\n\n .for_each(move |tcp| {\n\n use ::std::time::Duration;\n\n let _ = tcp.set_nodelay(true);\n\n let _ = tcp.set_keepalive(Some(Duration::from_secs(1)));\n\n let client = next;\n\n next += 1;\n\n let (to_client, receiver) = mpsc::channel(100);\n\n //FIXME no wait?\n\n let sender = sender.clone();\n\n let sender = sender\n\n .send(ToLog::NewClient(client, to_client))\n", "file_path": "tokio_server/src/lib.rs", "rank": 42, "score": 156372.26593564608 }, { "content": "fn aligned_len(len: usize) -> usize {\n\n 1 + (len + size_of::<AtomicUsize>() - 1) / size_of::<AtomicUsize>()\n\n}\n\n\n\n//Clone and Drop based on Arc\n\nimpl Clone for RcSlice {\n\n fn clone(&self) -> Self {\n\n self.ptr.count.fetch_add(1, Ordering::Relaxed);\n\n unsafe { ptr::read(self) }\n\n }\n\n}\n\n\n\nimpl Drop for RcSlice {\n\n fn drop(&mut self) {\n\n unsafe {\n\n if self.ptr.count.fetch_sub(1, Ordering::Release) != 1 {\n\n return\n\n }\n\n\n\n atomic::fence(Ordering::Acquire);\n", "file_path": "fuzzy_log_server/src/shared_slice.rs", "rank": 43, "score": 155837.13582711018 }, { "content": "pub trait AfterWrite<Inner> {\n\n fn after_write(\n\n &mut self,\n\n io: &mut TcpWriter,\n\n inner: &mut Inner,\n\n token: mio::Token,\n\n wrote: usize\n\n );\n\n}\n\n\n\nimpl<Inner> AfterWrite<Inner> for () {\n\n fn after_write(&mut self, _: &mut TcpWriter, _: &mut Inner, _: mio::Token, _: usize) {}\n\n}\n\n\n\n///////////////////\n\n\n\n#[derive(Debug)]\n\npub struct Messages<'r, Reader: 'r + ?Sized> {\n\n bytes: &'r [u8],\n\n read: usize,\n", "file_path": "reactor/src/lib.rs", "rank": 44, "score": 154948.2059901024 }, { "content": "pub fn work(addr: SocketAddr, window: usize, read: Arc<AtomicUsize>) {\n\n use std::io::ErrorKind;\n\n\n\n thread::sleep(Duration::from_secs(1));\n\n\n\n // let mut stream = mio::net::TcpStream::connect(&addr);\n\n // let stream = loop {\n\n // let reconnect = match stream {\n\n // Ok(s) => break s,\n\n // Err(ref e) if e.kind() != ErrorKind::WouldBlock =>\n\n // true,\n\n // Err(..) => {thread::yield_now(); false},\n\n // };\n\n // if reconnect {\n\n // stream = mio::net::TcpStream::connect(&addr)\n\n // }\n\n\n\n // };\n\n\n\n let stream = mio::net::TcpStream::connect(&addr).expect(\"work gen cannot connect\");\n", "file_path": "examples/zookeeper/view2/src/read_gen.rs", "rank": 45, "score": 154503.70882214847 }, { "content": "pub fn main() {\n\n let _ = env_logger::init();\n\n let Args {port_number, group, num_worker_threads, upstream, downstream}\n\n = parse_args();\n\n let ip_addr = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0));\n\n let addr = SocketAddr::new(ip_addr, port_number);\n\n let (server_num, group_size) = match group {\n\n Group::Singleton | Group::LockServer => (0, 1),\n\n Group::InGroup(server_num, group_size) => (server_num, group_size),\n\n };\n\n let replicated = upstream.is_some() || downstream.is_some();\n\n let print_start = |addr| match group {\n\n Group::Singleton =>\n\n println!(\"Starting singleton server at {} with {} worker threads\",\n\n addr, num_worker_threads),\n\n Group::LockServer =>\n\n println!(\"Starting lock server at {} with {} worker threads\",\n\n addr, num_worker_threads),\n\n Group::InGroup(..) =>\n\n println!(\"Starting server {} out of {} at {} with {} worker threads\",\n", "file_path": "servers/tokio_server/src/main.rs", "rank": 46, "score": 153674.55977782316 }, { "content": "pub fn run_pool(\n\n listener: TcpListener,\n\n sender: mpsc::Sender<ToServer>,\n\n num_threads: usize,\n\n // receiver: Box<FnMut(usize) -> mpsc::UnboundedReceiver<Vec<u8>> + Send + Sync>,\n\n) {\n\n let mut to_workers = Vec::with_capacity(num_threads);\n\n for _ in 0..num_threads {\n\n let (to_thread, from_acceptor) = mpsc::channel(10);\n\n to_workers.push(Some(to_thread));\n\n thread::spawn(move || {\n\n let accept_new = from_acceptor.for_each(|connection| {\n\n let (socket, to_log, from_log, client): (\n\n TcpStream,\n\n mpsc::Sender<_>,\n\n mpsc::Receiver<ReadBuffer>,\n\n _,\n\n ) = connection;\n\n let (reader, writer) = socket.split();\n\n\n", "file_path": "tokio_server/src/lib.rs", "rank": 47, "score": 153674.55977782316 }, { "content": "pub fn dependent_cost(\n\n server_addr: SocketAddr,\n\n jobsize: usize,\n\n num_writes: u32,\n\n non_dep_portion: u32,\n\n random_seed: Option<[u32; 4]>\n\n) {\n\n println!(\n\n \"# Starting dependent cost with jobsize {} for {} iterations running against:\\n#\\t{:?}\",\n\n jobsize, num_writes, server_addr,\n\n );\n\n\n\n if let Some(seed) = random_seed {\n\n println!(\"# with random spray, seed: {:?}.\", seed);\n\n }\n\n\n\n let mut handle = {\n\n let chains = (1..3).map(Into::into);\n\n LogHandle::new_tcp_log(iter::once(server_addr), chains)\n\n\n", "file_path": "benchers/throughput/src/workloads.rs", "rank": 48, "score": 153674.55977782316 }, { "content": "pub fn main() {\n\n let _ = env_logger::init();\n\n let Args {port_number, group, num_worker_threads, upstream, downstream}\n\n = parse_args();\n\n let ip_addr = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0));\n\n let addr = SocketAddr::new(ip_addr, port_number);\n\n let (server_num, group_size) = match group {\n\n Group::Singleton | Group::LockServer => (0, 1),\n\n Group::InGroup(server_num, group_size) => (server_num, group_size),\n\n };\n\n let acceptor = mio::tcp::TcpListener::bind(&addr);\n\n let a = AtomicUsize::new(0);\n\n let replicated = upstream.is_some() || downstream.is_some();\n\n let print_start = |addr| match group {\n\n Group::Singleton =>\n\n println!(\"Starting singleton server at {} with {} worker threads\",\n\n addr, num_worker_threads),\n\n Group::LockServer =>\n\n println!(\"Starting lock server at {} with {} worker threads\",\n\n addr, num_worker_threads),\n", "file_path": "servers/tcp_server/src/main.rs", "rank": 49, "score": 153674.55977782316 }, { "content": "pub trait OnRead {\n\n type Error: ::std::fmt::Debug;\n\n\n\n fn send(&mut self, res: Result<Vec<u8>, Error>) -> Result<(), Self::Error>;\n\n}\n\n\n", "file_path": "fuzzy_log_client/src/fuzzy_log/mod.rs", "rank": 50, "score": 152972.74605951173 }, { "content": "pub trait AsyncStoreClient {\n\n //TODO nocopy?\n\n fn on_finished_read(&mut self, read_loc: OrderIndex, read_packet: Vec<u8>) -> Result<(), ()>;\n\n //TODO what info is needed?\n\n fn on_finished_write(&mut self, write_id: Uuid, write_locs: Vec<OrderIndex>) -> Result<(), ()>;\n\n\n\n fn on_io_error(&mut self, err: io::Error, server: usize) -> Result<(), ()>;\n\n\n\n //TODO fn should_shutdown(&mut self) -> bool { false }\n\n}\n\n\n\npub type FromClient = mio::channel::Receiver<Vec<u8>>;\n\npub type ToSelf = mio::channel::Sender<Vec<u8>>;\n", "file_path": "fuzzy_log_client/src/store.rs", "rank": 51, "score": 152972.74605951173 }, { "content": "pub trait OnWrote {\n\n type Error: ::std::fmt::Debug;\n\n\n\n fn send(&mut self, res: Result<(Uuid, Vec<OrderIndex>), Error>) -> Result<(), Self::Error>;\n\n}\n\n\n\nimpl OnRead for mpsc::Sender<Result<Vec<u8>, Error>> {\n\n type Error = mpsc::SendError<Result<Vec<u8>, Error>>;\n\n\n\n fn send(&mut self, res: Result<Vec<u8>, Error>) -> Result<(), Self::Error> {\n\n mpsc::Sender::send(self, res)\n\n }\n\n}\n\n\n\nimpl OnWrote for mpsc::Sender<Result<(Uuid, Vec<OrderIndex>), Error>> {\n\n type Error = mpsc::SendError<Result<(Uuid, Vec<OrderIndex>), Error>>;\n\n\n\n fn send(&mut self, res: Result<(Uuid, Vec<OrderIndex>), Error>) -> Result<(), Self::Error> {\n\n mpsc::Sender::send(self, res)\n\n }\n", "file_path": "fuzzy_log_client/src/fuzzy_log/mod.rs", "rank": 52, "score": 152972.74605951173 }, { "content": "fn send_packet(buffer: &Buffer, mut stream: &TcpStream, sent: usize) -> Option<usize> {\n\n use std::io::ErrorKind;\n\n //TODO\n\n let bytes_to_write = 40;\n\n //match stream.write(&buffer.entry_slice()[sent..]) {\n\n match stream.write(&buffer[sent..bytes_to_write]) {\n\n Ok(i) if (sent + i) < bytes_to_write => Some(sent + i),\n\n Err(e) => if e.kind() == ErrorKind::WouldBlock { Some(sent) } else { None },\n\n _ => {\n\n None\n\n }\n\n }\n\n}\n\n\n", "file_path": "benchers/trivial_server/src/main.rs", "rank": 53, "score": 152492.41432538378 }, { "content": "pub fn run(set: &mut OrSet, interval: u64, duration: u64) -> (Vec<f64>, Vec<u64>) {\n\n let quit = &AtomicBool::new(false);\n\n let num_elapsed = &AtomicUsize::new(0);\n\n ::crossbeam_utils::thread::scope(move |scope| {\n\n let gets_per_snapshot = scope.spawn(move || do_run(set, num_elapsed, quit));\n\n let samples = do_measurement(interval, duration, num_elapsed, quit);\n\n (samples, gets_per_snapshot.join().unwrap())\n\n })\n\n}\n\n\n", "file_path": "examples/or_set/src/getter.rs", "rank": 54, "score": 151880.31322071428 }, { "content": "#[inline(never)]\n\npub fn run_trivial_server(addr: SocketAddr, server_ready: &AtomicUsize) -> ! {\n\n //let mut event_loop = EventLoop::new().unwrap();\n\n //let server = Server::new(&addr, &mut event_loop);\n\n //if let Ok(mut server) = server {\n\n // server_ready.fetch_add(1, Ordering::Release);\n\n // event_loop.run(&mut server).expect(\"should never return\");\n\n // panic!(\"server should never return\")\n\n //}\n\n //else { panic!(\"socket in use\") }\n\n Server::run(&addr)\n\n}\n\n\n", "file_path": "benchers/trivial_server/src/main.rs", "rank": 55, "score": 151722.84284521188 }, { "content": "pub fn run(\n\n acceptor: TcpListener,\n\n this_server_num: u32,\n\n total_chain_servers: u32,\n\n num_workers: usize,\n\n ready: &AtomicUsize,\n\n) -> ! {\n\n run_with_replication(acceptor, this_server_num, total_chain_servers, None, None, num_workers, ready)\n\n}\n\n\n", "file_path": "fuzzy_log_server/src/tcp/mod.rs", "rank": 56, "score": 151136.1446695886 }, { "content": "#[inline(never)]\n\npub fn run_log(\n\n to_store: mio::channel::Sender<Vec<u8>>,\n\n from_outside: mpsc::Receiver<Message>,\n\n ready_reads_s: mpsc::Sender<Vec<u8>>,\n\n finished_writes_s: mpsc::Sender<(Uuid, Vec<OrderIndex>)>,\n\n) {\n\n let log = ThreadLog::new(to_store, from_outside, ready_reads_s, finished_writes_s,\n\n [order::from(5)].into_iter().cloned());\n\n log.run()\n\n}\n\n\n\n///////////////////////////////////////\n\n\n", "file_path": "benchers/trivial_server/src/main.rs", "rank": 57, "score": 151136.1446695886 }, { "content": "#[inline(never)]\n\npub fn run_store(\n\n addr: SocketAddr,\n\n client: mpsc::Sender<Message>,\n\n tsm: Arc<Mutex<Option<mio::channel::Sender<Vec<u8>>>>>\n\n) {\n\n let mut event_loop = mio::Poll::new().unwrap();\n\n let (store, to_store) = AsyncTcpStore::tcp(addr,\n\n iter::once(addr),\n\n client, &mut event_loop).expect(\"\");\n\n *tsm.lock().unwrap() = Some(to_store);\n\n store.run(event_loop)\n\n}\n\n\n", "file_path": "benchers/trivial_server/src/main.rs", "rank": 58, "score": 151136.1446695886 }, { "content": "pub fn start_log_thread(\n\n this_server_num: u32,\n\n total_chain_servers: u32,\n\n chains: ChainStore<u64>,\n\n) -> mpsc::Sender<ToLog<u64>> {\n\n let (p, c) = oneshot::channel();\n\n thread::spawn(move || {\n\n\n\n let to_workers = ToWorkers::default();\n\n let log = ServerLog::new(this_server_num, total_chain_servers, to_workers, chains);\n\n let (to_log, from_clients) = mpsc::channel(100);\n\n p.send(to_log).unwrap_or_else(|_| panic!());\n\n let log = from_clients\n\n .fold(log, |mut log, msg| {\n\n match msg {\n\n ToLog::New(buffer, storage, st) => log.handle_op(buffer, storage, st),\n\n ToLog::Replication(tr, st) => log.handle_replication(tr, st),\n\n ToLog::Recovery(r, st) => log.handle_recovery(r, st),\n\n ToLog::NewClient(client, channel) => {\n\n log.to_workers.0.insert(client, channel);\n", "file_path": "tokio_server/src/lib.rs", "rank": 59, "score": 151136.1446695886 }, { "content": "pub trait PerSocket {\n\n fn return_buffer(&mut self, buffer: Buffer);\n\n}\n\n\n\nimpl PerSocket for PerStream {\n\n fn return_buffer(&mut self, _buffer: Buffer) {}\n\n}\n\n\n", "file_path": "fuzzy_log_server/src/tcp/per_socket.rs", "rank": 60, "score": 150696.0921273934 }, { "content": "fn buffer_can_hold_bytes(buffer: &Vec<u8>, bytes: usize) -> bool {\n\n buffer.capacity() - buffer.len() >= bytes\n\n}\n", "file_path": "fuzzy_log_packets/src/double_buffer.rs", "rank": 61, "score": 148977.9494090383 }, { "content": "pub fn run_server(\n\n addr: SocketAddr,\n\n server_num: u32,\n\n group_size: u32,\n\n prev_server: Option<SocketAddr>,\n\n next_server: Option<IpAddr>,\n\n num_worker_threads: usize,\n\n started: &AtomicUsize,\n\n) -> ! {\n\n let acceptor = mio::tcp::TcpListener::bind(&addr)\n\n .expect(\"Bind error\");\n\n run_with_replication(\n\n acceptor, server_num, group_size, prev_server, next_server, num_worker_threads, started\n\n )\n\n}\n\n\n", "file_path": "fuzzy_log_server/src/tcp/mod.rs", "rank": 62, "score": 148743.31674406925 }, { "content": "pub fn run_unreplicated_write_read(\n\n server_addrs: Box<[SocketAddr]>,\n\n clients_to_run: usize,\n\n total_clients: usize,\n\n jobsize: usize,\n\n num_writes: u32,\n\n write_window: u32,\n\n random_seed: Option<[u32; 4]>\n\n) {\n\n println!(\n\n \"# Starting {}/{} clients with jobsize {} for {} iterations running against:\\n#\\t{:?}\",\n\n clients_to_run, total_clients, jobsize, num_writes, server_addrs,\n\n );\n\n\n\n if let Some(seed) = random_seed {\n\n println!(\"# with random spray, seed: {:?}.\", seed);\n\n }\n\n\n\n let clients = (0..clients_to_run).map(|_| {\n\n let admin_chain = (u32::MAX-1).into();\n", "file_path": "benchers/throughput/src/workloads.rs", "rank": 63, "score": 148743.31674406925 }, { "content": "pub fn run_with_replication(\n\n acceptor: TcpListener,\n\n this_server_num: u32,\n\n total_chain_servers: u32,\n\n prev_server: Option<SocketAddr>,\n\n next_server: Option<IpAddr>,\n\n num_workers: usize,\n\n ready: &AtomicUsize,\n\n) -> ! {\n\n use std::cmp::max;\n\n\n\n //let (dist_to_workers, recv_from_dist) = spmc::channel();\n\n //let (log_to_workers, recv_from_log) = spmc::channel();\n\n //TODO or sync channel?\n\n let (workers_to_log, recv_from_workers) = mpsc::channel();\n\n let (workers_to_dist, dist_from_workers) = mio::channel::channel();\n\n if num_workers == 0 {\n\n warn!(\"SERVER {} started with 0 workers.\", this_server_num);\n\n }\n\n\n", "file_path": "fuzzy_log_server/src/tcp/mod.rs", "rank": 64, "score": 148743.31674406925 }, { "content": "pub fn run_replicated_write_read(\n\n lock_addr: Option<SocketAddr>,\n\n server_addrs: Vec<(SocketAddr, SocketAddr)>,\n\n clients_to_run: usize,\n\n total_clients: usize,\n\n jobsize: usize,\n\n num_writes: u32,\n\n write_window: u32,\n\n random_seed: Option<[u32; 4]>\n\n) {\n\n println!(\n\n \"# Starting {}/{} clients with jobsize {} for {} iterations running against:\\n#\\t{:?}\",\n\n clients_to_run, total_clients, jobsize, num_writes, server_addrs,\n\n );\n\n\n\n if let Some(seed) = random_seed {\n\n println!(\"# with random spray, seed: {:?}.\", seed);\n\n }\n\n\n\n let clients = (0..clients_to_run).map(|_| {\n", "file_path": "benchers/throughput/src/workloads.rs", "rank": 65, "score": 148743.31674406925 }, { "content": "pub trait Handler<Inner>: Wakeable {\n\n type Error;\n\n\n\n fn on_event(&mut self, inner: &mut Inner, token: mio::Token, event: mio::Event)\n\n -> Result<(), Self::Error>;\n\n\n\n fn on_poll(&mut self, inner: &mut Inner, token: mio::Token) -> Result<(), Self::Error>;\n\n\n\n fn on_error(&mut self, error: Self::Error, poll: &mut mio::Poll) -> ShouldRemove;\n\n\n\n //FIXME should be own trait\n\n fn after_work(&mut self, _inner: &mut Inner) {}\n\n}\n\n\n\n///////////////////////////////////////\n\n\n\n#[derive(Debug)]\n\npub struct Reactor<PerStream, Inner> {\n\n events: mio::Events,\n\n io_state: IoState<PerStream>,\n", "file_path": "reactor/src/lib.rs", "rank": 66, "score": 147365.39432818003 }, { "content": "pub fn run_unreplicated_server<CallBack: FnOnce()>(\n\n addr: &SocketAddr, this_server_num: u32, total_chain_servers: u32, callback: CallBack\n\n) -> Result<(), IoError> {\n\n let (store, log_reader) = fuzzy_log_server::new_chain_store_and_reader();\n\n let to_log = start_log_thread(this_server_num, total_chain_servers, store);\n\n let listener = TcpListener::bind(&addr)?;\n\n callback();\n\n Ok(run(listener, to_log, log_reader, Some(false)))\n\n}\n\n\n", "file_path": "tokio_server/src/lib.rs", "rank": 67, "score": 147068.60795240424 }, { "content": "pub fn new_stream(\n\n stream: TcpStream, token: mio::Token, is_replica: bool, upstream: Option<mio::Token>\n\n) -> PerStream {\n\n let reader = PacketReader{\n\n buffer_cache: Default::default(),\n\n is_replica,\n\n };\n\n let ps = (stream, reader, PacketHandler{ token }, WriteHandler{ upstream }).into();\n\n let _: &Handler<_, Error=io::Error> = &ps as &Handler<_, Error=io::Error>;\n\n ps\n\n}\n\n\n\nimpl MessageHandler<WorkerInner, (Buffer, Ipv4SocketAddr, Option<u64>)> for PacketHandler {\n\n fn handle_message(\n\n &mut self,\n\n io: &mut TcpWriter,\n\n inner: &mut WorkerInner,\n\n (msg, addr, storage_loc): (Buffer, Ipv4SocketAddr, Option<u64>),\n\n ) -> Result<(), ()> {\n\n // trace!(\"{} {:?}\", addr, storage_loc);\n", "file_path": "fuzzy_log_server/src/tcp/per_socket.rs", "rank": 68, "score": 146483.90024462744 }, { "content": "pub fn client_id() -> u64 {\n\n let id = CLIENT_ID.load(Relaxed) as u64;\n\n assert!(id != 0, \"{}\", id);\n\n id\n\n}\n\n\n", "file_path": "examples/zookeeper/src/message.rs", "rank": 69, "score": 145713.7062307342 }, { "content": "pub trait MessageHandler<Inner, Message> {\n\n fn handle_message(&mut self, io: &mut TcpWriter, inner: &mut Inner, msg: Message)\n\n -> Result<(), ()>;\n\n}\n\n\n\n///////////////////\n\n\n\n#[derive(Debug)]\n\npub enum MessageReaderError<OtherError> {\n\n NeedMoreBytes(usize),\n\n Other(OtherError)\n\n}\n\n\n", "file_path": "reactor/src/lib.rs", "rank": 70, "score": 144807.6132643795 }, { "content": "fn recv_packet(buffer: &mut Buffer, mut stream: &TcpStream) {\n\n use fuzzy_log::packets::Packet::WrapErr;\n\n let mut read = 0;\n\n loop {\n\n let to_read = buffer.finished_at(read);\n\n let size = match to_read {\n\n Err(WrapErr::NotEnoughBytes(needs)) => needs,\n\n Err(err) => panic!(\"{:?}\", err),\n\n Ok(size) if read < size => size,\n\n Ok(..) => return,\n\n };\n\n let r = stream.read(&mut buffer[read..size]);\n\n match r {\n\n Ok(i) => read += i,\n\n\n\n Err(e) => match e.kind() {\n\n io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted => {\n\n thread::yield_now();\n\n continue\n\n },\n\n _ => panic!(\"recv error {:?}\", e),\n\n }\n\n }\n\n }\n\n}\n", "file_path": "benchers/failure/src/main.rs", "rank": 71, "score": 143895.00844922572 }, { "content": "fn recv_packet(buffer: &mut Buffer, mut stream: &TcpStream) {\n\n use fuzzy_log::packets::Packet::WrapErr;\n\n let mut read = 0;\n\n loop {\n\n let to_read = buffer.finished_at(read);\n\n let size = match to_read {\n\n Err(WrapErr::NotEnoughBytes(needs)) => needs,\n\n Err(err) => panic!(\"{:?}\", err),\n\n Ok(size) if read < size => size,\n\n Ok(..) => return,\n\n };\n\n let r = stream.read(&mut buffer[read..size]);\n\n match r {\n\n Ok(i) => read += i,\n\n\n\n Err(e) => match e.kind() {\n\n io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted => {\n\n thread::yield_now();\n\n continue\n\n },\n", "file_path": "benchers/replicated_failure/src/main.rs", "rank": 72, "score": 142135.03108714687 }, { "content": "fn issue_request(set: &mut OrSet, request: &mut Op) -> Uuid {\n\n match request {\n\n Op::Add(val) => set.async_add(*val),\n\n Op::Rem(val) => set.async_remove(*val),\n\n }\n\n}\n\n\n", "file_path": "examples/or_set/src/tester.rs", "rank": 73, "score": 141127.83937732977 }, { "content": "fn do_run(set: &mut OrSet, num_elapsed: &AtomicUsize, quit: &AtomicBool) -> Vec<u64> {\n\n let mut gets_per_snapshot = vec![];\n\n let mut local_num_elapsed = 0;\n\n while !quit.load(Relaxed) {\n\n let gets = set.get_remote();\n\n local_num_elapsed += gets;\n\n num_elapsed.store(local_num_elapsed, Relaxed);\n\n gets_per_snapshot.push(gets as u64);\n\n }\n\n gets_per_snapshot\n\n}\n\n\n", "file_path": "examples/or_set/src/getter.rs", "rank": 74, "score": 139194.94661979418 }, { "content": "pub fn start_server_thread(server_ip: &str) {\n\n use std::sync::atomic::{AtomicUsize, Ordering};\n\n let server_started = AtomicUsize::new(0);\n\n let started = unsafe {\n\n //This should be safe since the while loop at the of the function\n\n //prevents it from exiting until the server is started and\n\n //server_started is no longer used\n\n (extend_lifetime(&server_started))\n\n };\n\n\n\n let addr = server_ip.parse().unwrap();\n\n ::std::thread::spawn(move || {\n\n run_server(addr, 0, 1, None, None, 1, &started)\n\n });\n\n while !server_started.load(Ordering::SeqCst) < 1 {}\n\n\n\n unsafe fn extend_lifetime<'a, 'b, T>(r: &'a T) -> &'b T {\n\n ::std::mem::transmute(r)\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 75, "score": 138702.70474019527 }, { "content": "pub fn set_client_id(id: u32) {\n\n CLIENT_ID.store(id as usize, Relaxed);\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize, Copy, Clone, PartialEq, Eq, Hash)]\n\npub struct Id {\n\n pub client: ClientId,\n\n pub count: Count,\n\n}\n\n\n\nimpl Id {\n\n pub fn new() -> Self {\n\n Id {\n\n client: client_id(),\n\n count: COUNTER.fetch_add(1, Relaxed) as u64,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize, Clone)]\n", "file_path": "examples/zookeeper/src/message.rs", "rank": 76, "score": 136443.28824075343 }, { "content": "pub trait DistributeToWorkers<T: Send + Sync> {\n\n fn send_to_worker(&mut self, msg: ToWorker<T>);\n\n}\n\n\n\nimpl<T: Send + Sync> DistributeToWorkers<T> for spmc::Sender<ToWorker<T>> {\n\n fn send_to_worker(&mut self, msg: ToWorker<T>) {\n\n self.send(msg)\n\n }\n\n}\n\n\n\nimpl DistributeToWorkers<()> for VecDeque<ToWorker<()>> {\n\n fn send_to_worker(&mut self, msg: ToWorker<()>) {\n\n self.push_front(msg);\n\n }\n\n}\n\n\n\n//TODO\n\npub type BufferSlice = Buffer;\n\n\n\npub enum ToWorker<T: Send + Sync> {\n", "file_path": "fuzzy_log_server/src/lib.rs", "rank": 77, "score": 133773.88979582948 }, { "content": "fn alloc_level() -> Box<[u8; LEVEL_BYTES]> {\n\n unsafe { Box::new(mem::zeroed()) }\n\n}\n\n\n", "file_path": "fuzzy_log_server/src/byte_trie.rs", "rank": 78, "score": 132643.41525780418 }, { "content": "fn local_log_handle(chains: Vec<order>) -> LogHandle<[u8]> {\n\n start_tcp_servers();\n\n LogHandle::unreplicated_with_servers(Some(&ADDR_STR1.parse().unwrap()))\n\n .chains(chains)\n\n .build()\n\n}\n\n\n", "file_path": "src/replication_tests.rs", "rank": 79, "score": 125158.3008863641 }, { "content": "fn remote_log_handle(chains: Vec<order>) -> LogHandle<[u8]> {\n\n start_tcp_servers();\n\n LogHandle::unreplicated_with_servers(Some(&ADDR_STR2.parse().unwrap()))\n\n .chains(chains)\n\n .build()\n\n}\n\n\n", "file_path": "src/replication_tests.rs", "rank": 80, "score": 125158.3008863641 }, { "content": "pub fn handle_to_worker2<T: Send + Sync + Clone, U, SendFn>(\n\n msg: ToWorker<T>, worker_num: usize, continue_replication: bool, mut send: SendFn\n\n) -> (Option<BufferSlice>, U)\n\nwhere SendFn: for<'a> FnMut(ToSend<'a>, bool, T) -> U {\n\n match msg {\n\n\n\n ReturnBuffer(buffer, t) => {\n\n trace!(\"WORKER {} return buffer\", worker_num);\n\n let u = send(ToSend::Nothing, false, t);\n\n (Some(buffer), u)\n\n //ServerResponse::None(buffer, t)\n\n //(Some(buffer), &[], t, 0, true)\n\n },\n\n\n\n Reply(buffer, t) => {\n\n trace!(\"WORKER {} finish reply\", worker_num);\n\n let u = send(ToSend::Slice(buffer.entry_slice()), false, t);\n\n (Some(buffer), u)\n\n //ServerResponse::Echo(buffer, t)\n\n //(Some(buffer), &[], t, 0, false)\n", "file_path": "fuzzy_log_server/src/worker_thread.rs", "rank": 81, "score": 125052.35902793685 }, { "content": "pub fn handle_read<U, V: Send + Sync + Copy, SendFn>(\n\n chains: &ChainReader<V>, buffer: &BufferSlice, worker_num: usize, mut send: SendFn\n\n) -> U\n\nwhere SendFn: for<'a> FnMut(Result<&'a [u8], EntryContents<'a>>) -> U {\n\n let OrderIndex(chain, index) = buffer.contents().locs()[0];\n\n debug_assert!(index > entry::from(0)); //TODO return error on index < GC\n\n let res = chains.get_and(&chain, |logs| {\n\n let log = unsafe {&*UnsafeCell::get(&logs[0])};\n\n match log.trie.atomic_get(u64::from(index)) {\n\n Some(packet) => {\n\n trace!(\"WORKER {:?} read occupied entry {:?} {:?}\",\n\n worker_num, (chain, index), packet.contents().id());\n\n Ok(send(Ok(packet.bytes())))\n\n }\n\n\n\n None => Err(log.trie.bounds()),\n\n }\n\n })\n\n .unwrap_or_else(|| Err(0..0));\n\n match res {\n", "file_path": "fuzzy_log_server/src/worker_thread.rs", "rank": 82, "score": 125052.35902793685 }, { "content": "fn get_chain_mut<T: Copy>(log: &mut ChainStore<T>, chain: order) -> Option<&mut Chain<T>> {\n\n log.get_and(&chain, |chains| unsafe { &mut *UnsafeCell::get(&chains[0]) })\n\n}\n\n\n", "file_path": "fuzzy_log_server/src/ordering_thread.rs", "rank": 83, "score": 124485.49589897797 }, { "content": "pub trait RBStruct<RedMessage, BlueMessage, Observation, ObservationResult> {\n\n fn update_red(&mut self, msg: RedMessage) -> Option<ObservationResult>; //TODO should be mutation result?\n\n fn update_blue(&mut self, msg: BlueMessage) -> Option<ObservationResult>; //TODO should be mutation result?\n\n fn observe(&mut self, _: Observation) -> ObservationResult;\n\n}\n\n\n\npub struct Materializer<RedMessage, BlueMessage, Observation, ObservationResult, Structure>\n\nwhere\n\n Structure: RBStruct<RedMessage, BlueMessage, Observation, ObservationResult>,\n\n{\n\n data: Structure,\n\n from_client: Receiver<ToSync<Observation>>,\n\n loopback: Sender<ToSync<Observation>>,\n\n to_client: Sender<ObservationResult>,\n\n\n\n handle: ReadHandle<[u8]>,\n\n my_chain: order,\n\n red_chain: order,\n\n all_chains: Vec<order>,\n\n causes: Arc<Mutex<HashMap<order, entry>>>,\n", "file_path": "examples/redblue/src/lib.rs", "rank": 84, "score": 124311.17189933122 }, { "content": "fn use_idle_cycles() {\n\n ::std::thread::yield_now()\n\n}\n\n\n", "file_path": "examples/or_set/src/tester.rs", "rank": 85, "score": 121507.98327292761 }, { "content": "//SAFETY: log is single writer and Chain refs never escape this thread\n\nfn ensure_chain<T: Copy>(log: &mut ChainStore<T>, chain: order) -> &mut Chain<T> {\n\n let c = log.get_and(&chain, |chains| unsafe { &mut *UnsafeCell::get(&chains[0]) });\n\n if let Some(chain) = c {\n\n return chain\n\n }\n\n\n\n let mut t = Trie::new();\n\n //FIXME remove for GC\n\n unsafe {\n\n t.partial_append(1).write_byte(mem::transmute(EntryKind::Read));\n\n };\n\n let contents = TrivialEqArc::new(Chain{ trie: t, skeens: SkeensState::new()});\n\n log.insert(chain, contents);\n\n log.refresh();\n\n get_chain_mut(log, chain).unwrap()\n\n}\n\n\n", "file_path": "fuzzy_log_server/src/ordering_thread.rs", "rank": 87, "score": 121382.20544929428 }, { "content": "fn round_to_10(time: usize) -> usize {\n\n if time % 10 == 0 {\n\n time\n\n } else if time % 10 >= 5 {\n\n (10 - time % 10) + time\n\n } else {\n\n time - time % 10\n\n }\n\n}\n\n\n", "file_path": "benchers/append_lat2/src/main.rs", "rank": 88, "score": 121289.31500908479 }, { "content": "fn packetsize_for_jobsize(jobsize: usize) -> usize {\n\n let data = vec![0u8; jobsize];\n\n SingletonBuilder(&data[..], &[]).clone_entry().entry_size()\n\n}\n\n\n\n///////////////////////////////////////\n\n\n\n// fn leak<T: ?Sized>(b: Box<T>) -> &'static T {\n\n // unsafe { &*Box::into_raw(b) }\n\n// }\n", "file_path": "benchers/throughput/src/workloads.rs", "rank": 89, "score": 121289.31500908479 }, { "content": "#[proc_macro_derive(packet_macro_impl)]\n\npub fn packet_macro_impl(input: TokenStream) -> TokenStream {\n\n let input = input.to_string();\n\n let input = extract_input(&input);\n\n let parsed = match parser::packet_body(input) {\n\n IResult::Done(mut rest, t) => {\n\n rest = space::skip_whitespace(rest);\n\n if rest.is_empty() {\n\n t\n\n } else if rest.len() == input.len() {\n\n // parsed nothing\n\n panic!(\"failed to parse {:?}\", rest)\n\n } else {\n\n panic!(\"unparsed tokens after {:?}\", rest)\n\n }\n\n }\n\n IResult::Error => panic!(\"failed to parse: {:?}\", input),\n\n };\n\n let body = impl_ref(parsed);\n\n //let tokens = quote!{\n\n\n", "file_path": "packet-macro2/packet-macro-impl/src/lib.rs", "rank": 90, "score": 121172.65489852792 }, { "content": "fn get_next_token(token: &mut mio::Token) -> mio::Token {\n\n let next = token.0.wrapping_add(1);\n\n if next == 0 { *token = mio::Token(2) }\n\n else { *token = mio::Token(next) };\n\n *token\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n use test::Bencher;\n\n\n\n #[bench]\n\n fn bench_read(b: &mut Bencher) {\n\n let _ = env_logger::init();\n\n static SERVER_READY: AtomicUsize = ATOMIC_USIZE_INIT;\n\n\n\n let handle = thread::spawn(|| {\n\n run_trivial_server(&SERVER_READY)\n", "file_path": "benchers/trivial_server/src/main.rs", "rank": 91, "score": 118217.89317344927 }, { "content": "fn tx_chain(rand: &mut Option<(Rand, u32)>) -> Option<order> {\n\n rand.as_mut().and_then(|&mut (ref mut rand, one_in)| {\n\n if !rand.gen_weighted_bool(one_in) { return None }\n\n let chain = rand.gen_range(10_000, 10_020);\n\n Some(chain.into())\n\n })\n\n}\n\n\n\n\n\n/////////////////////////\n\n\n", "file_path": "benchers/scaling/src/main.rs", "rank": 92, "score": 117336.41296522765 }, { "content": "pub fn channel<V: Send>() -> (Sender<V>, Receiver<V>) {\n\n let (worker, stealer) = deque::new();\n\n let (send, recv) = mpsc::channel();\n\n let sender = Sender { inner: worker, sleepers: recv };\n\n let reciever = Receiver {\n\n inner: stealer,\n\n registration: LazyCell::new(),\n\n notifier: Arc::new(AtomicLazyCell::new()),\n\n sleepers: send\n\n };\n\n (sender, reciever)\n\n}\n\n\n\npub struct Sender<V: Send> {\n\n inner: Worker<V>,\n\n sleepers: mpsc::Receiver<Arc<Notifier>>,\n\n}\n\n\n\npub struct Receiver<V: Send> {\n\n inner: Stealer<V>,\n\n registration: LazyCell<Registration>,\n\n notifier: Arc<Notifier>,\n\n sleepers: mpsc::Sender<Arc<Notifier>>,\n\n}\n\n\n", "file_path": "fuzzy_log_server/src/spmc.rs", "rank": 93, "score": 117172.52834562576 }, { "content": "pub fn channel<V: Send>() -> (Sender<V>, Receiver<V>) {\n\n let (worker, stealer) = deque::new();\n\n let ctl = Arc::new(Ctl {\n\n pending: AtomicUsize::new(0),\n\n set_readiness: AtomicLazyCell::new()\n\n });\n\n let receiver = Receiver {\n\n inner: stealer,\n\n registration: LazyCell::new(),\n\n ctl: ctl.clone()\n\n };\n\n let sender = Sender { inner: worker, ctl: ctl };\n\n (sender, receiver)\n\n}\n\n\n\npub struct Sender<V: Send> {\n\n inner: Worker<V>,\n\n ctl: Arc<Ctl>,\n\n}\n\n\n\npub struct Receiver<V: Send> {\n\n inner: Stealer<V>,\n\n registration: LazyCell<Registration>,\n\n ctl: Arc<Ctl>,\n\n}\n\n\n", "file_path": "fuzzy_log_server/src/spsc.rs", "rank": 94, "score": 117172.52834562576 }, { "content": "fn ack_vw(mut from_vw: TcpStream, done: &AtomicBool) -> u64 {\n\n let mut finished_rounds = 0u64;\n\n\n\n // let mut buffer = String::with_capacity(1024);\n\n let mut buffer = vec![0u8; 1024].into_boxed_slice();\n\n let mut pos = 0;\n\n let mut len = 0;\n\n let end_of_ack = &[b\"\\n\\n\"];\n\n let searcher = AcAutomaton::new(end_of_ack).into_full();\n\n while !done.load(Ordering::Relaxed) {\n\n for Match{end, ..} in searcher.find(&buffer[pos..len]) {\n\n pos = end;\n\n finished_rounds += 1\n\n }\n\n if pos >= len {\n\n pos = 0;\n\n len = match from_vw.read(&mut buffer) {\n\n Ok(s) => s,\n\n Err(ref e) if e.kind() == IoErrorKind::Interrupted => 0,\n\n Err(ref e) if e.kind() == IoErrorKind::WouldBlock => 0,\n", "file_path": "fuzzy_views/ml/src/main.rs", "rank": 95, "score": 116482.92498809201 }, { "content": "fn get_next_token(token: &mut mio::Token) -> mio::Token {\n\n *token = mio::Token(token.0.checked_add(1).unwrap());\n\n *token\n\n}\n\n\n", "file_path": "fuzzy_log_server/src/tcp/mod.rs", "rank": 96, "score": 116482.92498809201 }, { "content": "fn horizon_or_add_blank(trie: &mut Trie, chain: order) -> u64 {\n\n let horizon = trie.horizon();\n\n if horizon > 0 {\n\n return horizon\n\n }\n\n\n\n let blank = EntryContents::Senti {\n\n id: &Uuid::nil(),\n\n flags: &EntryFlag::ReadSuccess,\n\n locs: &[OrderIndex(chain, 1.into())],\n\n lock: &0,\n\n data_bytes: &0,\n\n deps: &[],\n\n };\n\n unsafe {\n\n trie.partial_append(blank.len()).finish_append_with_contents(blank);\n\n }\n\n trie.horizon()\n\n}\n\n\n", "file_path": "fuzzy_log_server/src/ordering_thread.rs", "rank": 97, "score": 116482.92498809201 }, { "content": "fn to_atomic_usize<T>(t: &T) -> &AtomicUsize {\n\n assert_eq!(mem::size_of::<T>(), mem::size_of::<AtomicUsize>());\n\n unsafe { mem::transmute(t) }\n\n}\n\n\n\nimpl ValEdge {\n\n pub fn end_from_ptr(ptr: *const u8) -> Self {\n\n assert!(ptr as usize & 1 == 0);\n\n ValEdge((ptr as usize | 1) as *mut _)\n\n }\n\n\n\n pub fn mid_from_ptr(ptr: *const u8) -> Self {\n\n assert!(ptr as usize & 1 == 0);\n\n ValEdge(ptr as *mut _)\n\n }\n\n\n\n pub fn null() -> Self {\n\n ValEdge(ptr::null_mut())\n\n }\n\n\n", "file_path": "fuzzy_log_server/src/trie.rs", "rank": 98, "score": 115268.17453600868 }, { "content": "fn channel() -> (ToSelf, FromClient) {\n\n mio::channel::channel()\n\n}\n\n\n\npub struct AsyncTcpStore<C: AsyncStoreClient> {\n\n reactor: Reactor<PerStream, StoreInner<C>>,\n\n}\n\n\n", "file_path": "fuzzy_log_client/src/store.rs", "rank": 99, "score": 113294.84467134901 } ]
Rust
crates/ra_ide_api_light/src/typing.rs
hdhoang/rust-analyzer
da3802b2ce4796461a9fff22f4e9c6fd890879b2
use ra_syntax::{ AstNode, SourceFile, SyntaxKind::*, SyntaxNode, TextUnit, TextRange, algo::{find_node_at_offset, find_leaf_at_offset, LeafAtOffset}, ast::{self, AstToken}, }; use crate::{LocalEdit, TextEditBuilder, formatting::leading_indent}; pub fn on_enter(file: &SourceFile, offset: TextUnit) -> Option<LocalEdit> { let comment = find_leaf_at_offset(file.syntax(), offset) .left_biased() .and_then(ast::Comment::cast)?; if let ast::CommentFlavor::Multiline = comment.flavor() { return None; } let prefix = comment.prefix(); if offset < comment.syntax().range().start() + TextUnit::of_str(prefix) + TextUnit::from(1) { return None; } let indent = node_indent(file, comment.syntax())?; let inserted = format!("\n{}{} ", indent, prefix); let cursor_position = offset + TextUnit::of_str(&inserted); let mut edit = TextEditBuilder::default(); edit.insert(offset, inserted); Some(LocalEdit { label: "on enter".to_string(), edit: edit.finish(), cursor_position: Some(cursor_position), }) } fn node_indent<'a>(file: &'a SourceFile, node: &SyntaxNode) -> Option<&'a str> { let ws = match find_leaf_at_offset(file.syntax(), node.range().start()) { LeafAtOffset::Between(l, r) => { assert!(r == node); l } LeafAtOffset::Single(n) => { assert!(n == node); return Some(""); } LeafAtOffset::None => unreachable!(), }; if ws.kind() != WHITESPACE { return None; } let text = ws.leaf_text().unwrap(); let pos = text.as_str().rfind('\n').map(|it| it + 1).unwrap_or(0); Some(&text[pos..]) } pub fn on_eq_typed(file: &SourceFile, eq_offset: TextUnit) -> Option<LocalEdit> { assert_eq!(file.syntax().text().char_at(eq_offset), Some('=')); let let_stmt: &ast::LetStmt = find_node_at_offset(file.syntax(), eq_offset)?; if let_stmt.has_semi() { return None; } if let Some(expr) = let_stmt.initializer() { let expr_range = expr.syntax().range(); if expr_range.contains(eq_offset) && eq_offset != expr_range.start() { return None; } if file .syntax() .text() .slice(eq_offset..expr_range.start()) .contains('\n') { return None; } } else { return None; } let offset = let_stmt.syntax().range().end(); let mut edit = TextEditBuilder::default(); edit.insert(offset, ";".to_string()); Some(LocalEdit { label: "add semicolon".to_string(), edit: edit.finish(), cursor_position: None, }) } pub fn on_dot_typed(file: &SourceFile, dot_offset: TextUnit) -> Option<LocalEdit> { assert_eq!(file.syntax().text().char_at(dot_offset), Some('.')); let whitespace = find_leaf_at_offset(file.syntax(), dot_offset) .left_biased() .and_then(ast::Whitespace::cast)?; let current_indent = { let text = whitespace.text(); let newline = text.rfind('\n')?; &text[newline + 1..] }; let current_indent_len = TextUnit::of_str(current_indent); let field_expr = whitespace .syntax() .parent() .and_then(ast::FieldExpr::cast)?; let prev_indent = leading_indent(field_expr.syntax())?; let target_indent = format!(" {}", prev_indent); let target_indent_len = TextUnit::of_str(&target_indent); if current_indent_len == target_indent_len { return None; } let mut edit = TextEditBuilder::default(); edit.replace( TextRange::from_to(dot_offset - current_indent_len, dot_offset), target_indent.into(), ); let res = LocalEdit { label: "reindent dot".to_string(), edit: edit.finish(), cursor_position: Some( dot_offset + target_indent_len - current_indent_len + TextUnit::of_char('.'), ), }; Some(res) } #[cfg(test)] mod tests { use crate::test_utils::{add_cursor, assert_eq_text, extract_offset}; use super::*; #[test] fn test_on_eq_typed() { fn type_eq(before: &str, after: &str) { let (offset, before) = extract_offset(before); let mut edit = TextEditBuilder::default(); edit.insert(offset, "=".to_string()); let before = edit.finish().apply(&before); let file = SourceFile::parse(&before); if let Some(result) = on_eq_typed(&file, offset) { let actual = result.edit.apply(&before); assert_eq_text!(after, &actual); } else { assert_eq_text!(&before, after) }; } type_eq( r" fn foo() { let foo <|> 1 + 1 } ", r" fn foo() { let foo = 1 + 1; } ", ); } fn type_dot(before: &str, after: &str) { let (offset, before) = extract_offset(before); let mut edit = TextEditBuilder::default(); edit.insert(offset, ".".to_string()); let before = edit.finish().apply(&before); let file = SourceFile::parse(&before); if let Some(result) = on_dot_typed(&file, offset) { let actual = result.edit.apply(&before); assert_eq_text!(after, &actual); } else { assert_eq_text!(&before, after) }; } #[test] fn indents_new_chain_call() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) . } ", ); type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) . } ", ) } #[test] fn indents_new_chain_call_with_semi() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) <|>; } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .; } ", ); type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) <|>; } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .; } ", ) } #[test] fn indents_continued_chain_call() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() . } ", ); type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() . } ", ); } #[test] fn indents_middle_of_chain_call() { type_dot( r" fn source_impl() { let var = enum_defvariant_list().unwrap() <|> .nth(92) .unwrap(); } ", r" fn source_impl() { let var = enum_defvariant_list().unwrap() . .nth(92) .unwrap(); } ", ); type_dot( r" fn source_impl() { let var = enum_defvariant_list().unwrap() <|> .nth(92) .unwrap(); } ", r" fn source_impl() { let var = enum_defvariant_list().unwrap() . .nth(92) .unwrap(); } ", ); } #[test] fn dont_indent_freestanding_dot() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { . } ", ); type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { . } ", ); } #[test] fn test_on_enter() { fn apply_on_enter(before: &str) -> Option<String> { let (offset, before) = extract_offset(before); let file = SourceFile::parse(&before); let result = on_enter(&file, offset)?; let actual = result.edit.apply(&before); let actual = add_cursor(&actual, result.cursor_position.unwrap()); Some(actual) } fn do_check(before: &str, after: &str) { let actual = apply_on_enter(before).unwrap(); assert_eq_text!(after, &actual); } fn do_check_noop(text: &str) { assert!(apply_on_enter(text).is_none()) } do_check( r" /// Some docs<|> fn foo() { } ", r" /// Some docs /// <|> fn foo() { } ", ); do_check( r" impl S { /// Some<|> docs. fn foo() {} } ", r" impl S { /// Some /// <|> docs. fn foo() {} } ", ); do_check_noop(r"<|>//! docz"); } }
use ra_syntax::{ AstNode, SourceFile, SyntaxKind::*, SyntaxNode, TextUnit, TextRange, algo::{find_node_at_offset, find_leaf_at_offset, LeafAtOffset}, ast::{self, AstToken}, }; use crate::{LocalEdit, TextEditBuilder, formatting::leading_indent}; pub fn on_enter(file: &SourceFile, offset: TextUnit) -> Option<LocalEdit> { let comment = find_leaf_at_offset(file.syntax(), offset) .left_biased() .and_then(ast::Comment::cast)?; if let ast::CommentFlavor::Multiline = comment.flavor() { return None; } let prefix = comment.prefix(); if offset < comment.syntax().range().start() + TextUnit::of_str(prefix) + TextUnit::from(1) { return None; } let indent = node_indent(file, comment.syntax())?; let inserted = format!("\n{}{} ", indent, prefix); let cursor_position = offset + TextUnit::of_str(&inserted); let mut edit = TextEditBuilder::default(); edit.insert(offset, inserted); Some(LocalEdit { label: "on enter".to_string(), edit: edit.finish(), cursor_position: Some(cursor_position), }) } fn node_indent<'a>(file: &'a SourceFile, node: &SyntaxNode) -> Option<&'a str> { let ws = match find_leaf_at_offset(file.syntax(), node.range().start()) { LeafAtOffset::Between(l, r) => { assert!(r == node); l } LeafAtOffset::Single(n) => { assert!(n == node); return Some(""); } LeafAtOffset::None => unreachable!(), }; if ws.kind() != WHITESPACE { return None; } let text = ws.leaf_text().unwrap(); let pos = text.as_str().rfind('\n').map(|it| it + 1).unwrap_or(0); Some(&text[pos..]) } pub fn on_eq_typed(file: &SourceFile, eq_offset: TextUnit) -> Option<LocalEdit> { assert_eq!(file.syntax().text().char_at(eq_offset), Some('=')); let let_stmt: &ast::LetStmt = find_node_at_offset(file.syntax(), eq_offset)?; if let_stmt.has_semi() { return None; } if let Some(expr) = let_stmt.initializer() { let expr_range = expr.syntax().range(); if expr_range.contains(eq_offset) && eq_offset != expr_range.start() { return None; } if file .syntax() .text() .slice(eq_offset..expr_range.start()) .contains('\n') { return None; } } else { return None; } let offset = let_stmt.syntax().range().end(); let mut edit = TextEditBuilder::default(); edit.insert(offset, ";".to_string()); Some(LocalEdit { label: "add semicolon".to_string(), edit: edit.finish(), cursor_position: None, }) } pub fn on_dot_typed(file: &SourceFile, dot_offset: TextUnit) -> Option<LocalEdit> { assert_eq!(file.syntax().text().char_at(dot_offset), Some('.')); let whitespace = find_leaf_at_offset(file.syntax(), dot_offset) .left_biased() .and_then(ast::Whitespace::cast)?; let current_indent = { let text = whitespace.text(); let newline = text.rfind('\n')?; &text[newline + 1..] }; let current_indent_len = TextUnit::of_str(current_indent); let field_expr = whitespace .syntax() .parent() .and_then(ast::FieldExpr::cast)?; let prev_indent = leading_indent(field_expr.syntax())?; let target_indent = format!(" {}", prev_indent); let target_indent_len = TextUnit::of_str(&target_indent); if current_indent_len == target_indent_len { return None; } let mut edit = TextEditBuilder::default(); edit.replace( TextRange::from_to(dot_offset - current_indent_len, dot_offset), target_indent.into(), ); let res = LocalEdit { label: "reindent dot".to_string(), edit: edit.finish(), cursor_position: Some( dot_offset + target_indent_len - current_indent_len + TextUnit::of_char('.'), ), }; Some(res) } #[cfg(test)] mod tests { use crate::test_utils::{add_cursor, assert_eq_text, extract_offset}; use super::*; #[test] fn test_on_eq_typed() { fn type_eq(before: &str, after: &str) { let (offset, before) = extract_offset(before); let mut edit = TextEditBuilder::default(); edit.insert(offset, "=".to_string()); let before = edit.finish().apply(&before); let file = SourceFile::parse(&before); if let Some(result) = on_eq_typed(&file, offset) { let actual = result.edit.apply(&before); assert_eq_text!(after, &actual); } else { assert_eq_text!(&before, after) }; } type_eq( r" fn foo() { let foo <|> 1 + 1 } ", r" fn foo() { let foo = 1 + 1; } ", ); } fn type_dot(before: &str, after: &str) { let (offset, before) = extract_offset(before); let mut edit = TextEditBuilder::default(); edit.insert(offset, ".".to_string()); let before = edit.finish().apply(&before); let file = SourceFile::parse(&before); if let Some(result) = on_dot_typed(&file, offset) { let actual = result.edit.apply(&before); assert_eq_text!(after, &actual); } else { assert_eq_text!(&before, after) }; } #[test] fn indents_new_chain_call() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) . } ", ); type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) . } ", ) } #[test] fn indents_new_chain_call_with_semi() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) <|>; } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .; } ", ); type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) <|>; } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .; } ", ) } #[test]
#[test] fn indents_middle_of_chain_call() { type_dot( r" fn source_impl() { let var = enum_defvariant_list().unwrap() <|> .nth(92) .unwrap(); } ", r" fn source_impl() { let var = enum_defvariant_list().unwrap() . .nth(92) .unwrap(); } ", ); type_dot( r" fn source_impl() { let var = enum_defvariant_list().unwrap() <|> .nth(92) .unwrap(); } ", r" fn source_impl() { let var = enum_defvariant_list().unwrap() . .nth(92) .unwrap(); } ", ); } #[test] fn dont_indent_freestanding_dot() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { . } ", ); type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { . } ", ); } #[test] fn test_on_enter() { fn apply_on_enter(before: &str) -> Option<String> { let (offset, before) = extract_offset(before); let file = SourceFile::parse(&before); let result = on_enter(&file, offset)?; let actual = result.edit.apply(&before); let actual = add_cursor(&actual, result.cursor_position.unwrap()); Some(actual) } fn do_check(before: &str, after: &str) { let actual = apply_on_enter(before).unwrap(); assert_eq_text!(after, &actual); } fn do_check_noop(text: &str) { assert!(apply_on_enter(text).is_none()) } do_check( r" /// Some docs<|> fn foo() { } ", r" /// Some docs /// <|> fn foo() { } ", ); do_check( r" impl S { /// Some<|> docs. fn foo() {} } ", r" impl S { /// Some /// <|> docs. fn foo() {} } ", ); do_check_noop(r"<|>//! docz"); } }
fn indents_continued_chain_call() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() . } ", ); type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() <|> } ", r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() . } ", ); }
function_block-full_function
[]
Rust
vm_control/src/client.rs
google/crosvm
df929efce3261ca5383f66eea6c7041b3439eb77
use crate::*; use base::{info, validate_raw_descriptor, RawDescriptor, Tube, UnixSeqpacket}; use remain::sorted; use thiserror::Error; use std::fs::OpenOptions; use std::num::ParseIntError; use std::path::{Path, PathBuf}; #[sorted] #[derive(Error, Debug)] enum ModifyBatError { #[error("{0}")] BatControlErr(BatControlResult), } #[sorted] #[derive(Error, Debug)] pub enum ModifyUsbError { #[error("argument missing: {0}")] ArgMissing(&'static str), #[error("failed to parse argument {0} value `{1}`")] ArgParse(&'static str, String), #[error("failed to parse integer argument {0} value `{1}`: {2}")] ArgParseInt(&'static str, String, ParseIntError), #[error("failed to validate file descriptor: {0}")] FailedDescriptorValidate(base::Error), #[error("path `{0}` does not exist")] PathDoesNotExist(PathBuf), #[error("socket failed")] SocketFailed, #[error("unexpected response: {0}")] UnexpectedResponse(VmResponse), #[error("unknown command: `{0}`")] UnknownCommand(String), #[error("{0}")] UsbControl(UsbControlResult), } pub type ModifyUsbResult<T> = std::result::Result<T, ModifyUsbError>; fn raw_descriptor_from_path(path: &Path) -> ModifyUsbResult<RawDescriptor> { if !path.exists() { return Err(ModifyUsbError::PathDoesNotExist(path.to_owned())); } let raw_descriptor = path .file_name() .and_then(|fd_osstr| fd_osstr.to_str()) .map_or( Err(ModifyUsbError::ArgParse( "USB_DEVICE_PATH", path.to_string_lossy().into_owned(), )), |fd_str| { fd_str.parse::<libc::c_int>().map_err(|e| { ModifyUsbError::ArgParseInt("USB_DEVICE_PATH", fd_str.to_owned(), e) }) }, )?; validate_raw_descriptor(raw_descriptor).map_err(ModifyUsbError::FailedDescriptorValidate) } pub type VmsRequestResult = std::result::Result<(), ()>; pub fn vms_request(request: &VmRequest, socket_path: &Path) -> VmsRequestResult { let response = handle_request(request, socket_path)?; info!("request response was {}", response); Ok(()) } pub fn do_usb_attach( socket_path: &Path, bus: u8, addr: u8, vid: u16, pid: u16, dev_path: &Path, ) -> ModifyUsbResult<UsbControlResult> { let usb_file: File = if dev_path.parent() == Some(Path::new("/proc/self/fd")) { unsafe { File::from_raw_descriptor(raw_descriptor_from_path(dev_path)?) } } else { OpenOptions::new() .read(true) .write(true) .open(dev_path) .map_err(|_| ModifyUsbError::UsbControl(UsbControlResult::FailedToOpenDevice))? }; let request = VmRequest::UsbCommand(UsbControlCommand::AttachDevice { bus, addr, vid, pid, file: usb_file, }); let response = handle_request(&request, socket_path).map_err(|_| ModifyUsbError::SocketFailed)?; match response { VmResponse::UsbResponse(usb_resp) => Ok(usb_resp), r => Err(ModifyUsbError::UnexpectedResponse(r)), } } pub fn do_usb_detach(socket_path: &Path, port: u8) -> ModifyUsbResult<UsbControlResult> { let request = VmRequest::UsbCommand(UsbControlCommand::DetachDevice { port }); let response = handle_request(&request, socket_path).map_err(|_| ModifyUsbError::SocketFailed)?; match response { VmResponse::UsbResponse(usb_resp) => Ok(usb_resp), r => Err(ModifyUsbError::UnexpectedResponse(r)), } } pub fn do_usb_list(socket_path: &Path) -> ModifyUsbResult<UsbControlResult> { let mut ports: [u8; USB_CONTROL_MAX_PORTS] = Default::default(); for (index, port) in ports.iter_mut().enumerate() { *port = index as u8 } let request = VmRequest::UsbCommand(UsbControlCommand::ListDevice { ports }); let response = handle_request(&request, socket_path).map_err(|_| ModifyUsbError::SocketFailed)?; match response { VmResponse::UsbResponse(usb_resp) => Ok(usb_resp), r => Err(ModifyUsbError::UnexpectedResponse(r)), } } pub type DoModifyBatteryResult = std::result::Result<(), ()>; pub fn do_modify_battery( socket_path: &Path, battery_type: &str, property: &str, target: &str, ) -> DoModifyBatteryResult { let response = match battery_type.parse::<BatteryType>() { Ok(type_) => match BatControlCommand::new(property.to_string(), target.to_string()) { Ok(cmd) => { let request = VmRequest::BatCommand(type_, cmd); Ok(handle_request(&request, socket_path)?) } Err(e) => Err(ModifyBatError::BatControlErr(e)), }, Err(e) => Err(ModifyBatError::BatControlErr(e)), }; match response { Ok(response) => { println!("{}", response); Ok(()) } Err(e) => { println!("error {}", e); Err(()) } } } pub type HandleRequestResult = std::result::Result<VmResponse, ()>; pub fn handle_request(request: &VmRequest, socket_path: &Path) -> HandleRequestResult { match UnixSeqpacket::connect(&socket_path) { Ok(s) => { let socket = Tube::new(s); if let Err(e) = socket.send(request) { error!( "failed to send request to socket at '{:?}': {}", socket_path, e ); return Err(()); } match socket.recv() { Ok(response) => Ok(response), Err(e) => { error!( "failed to send request to socket at '{:?}': {}", socket_path, e ); Err(()) } } } Err(e) => { error!("failed to connect to socket at '{:?}': {}", socket_path, e); Err(()) } } }
use crate::*; use base::{info, validate_raw_descriptor, RawDescriptor, Tube, UnixSeqpacket}; use remain::sorted; use thiserror::Error; use std::fs::OpenOptions; use std::num::ParseIntError; use std::path::{Path, PathBuf}; #[sorted] #[derive(Error, Debug)] enum ModifyBatError { #[error("{0}")] BatControlErr(BatControlResult), } #[sorted] #[derive(Error, Debug)] pub enum ModifyUsbError { #[error("argument missing: {0}")] ArgMissing(&'static str), #[error("failed to parse argument {0} value `{1}`")] ArgParse(&'static str, String), #[error("failed to parse integer argument {0} value `{1}`: {2}")] ArgParseInt(&'static str, String, ParseIntError), #[error("failed to validate file descriptor: {0}")] FailedDescriptorValidate(base::Error), #[error("path `{0}` does not exist")] PathDoesNotExist(PathBuf), #[error("socket failed")] SocketFailed, #[error("unexpected response: {0}")] UnexpectedResponse(VmResponse), #[error("unknown command: `{0}`")] UnknownCommand(String), #[error("{0}")] UsbControl(UsbControlResult), } pub type ModifyUsbResult<T> = std::result::Result<T, ModifyUsbError>; fn raw_descriptor_from_path(path: &Path) -> ModifyUsbResult<RawDescriptor> { if !path.exists() { return Err(ModifyUsbError::PathDoesNotExist(path.to_owned())); } let raw_descriptor = path .file_name() .and_then(|fd_osstr| fd_osstr.to_str()) .map_or( Err(ModifyUsbError::ArgParse( "USB_DEVICE_PATH", path.to_string_lossy().into_owned(), )), |fd_str| { fd_str.parse::<libc::c_int>().map_err(|e| { ModifyUsbError::ArgParseInt("USB_DEVICE_PATH", fd_str.to_owned(), e) }) }, )?; validate_raw_descriptor(raw_descriptor).map_err(ModifyUsbError::FailedDescriptorValidate) } pub type VmsRequestResult = std::result::Result<(), ()>; pub fn vms_request(request: &VmRequest, socket_path: &Path) -> VmsRequestResult { let response = handle_request(request, socket_path)?; info!("request response was {}", response); Ok(()) } pub fn do_usb_attach( socket_path: &Path, bus: u8, addr: u8, vid: u16, pid: u16, dev_path: &Path, ) -> ModifyUsbResult<UsbControlResult> { let usb_file: File = if dev_path.parent() == Some(Path::new("/proc/self/fd")) { unsafe { File::from_raw_descriptor(raw_descriptor_from_path(dev_path)?) } } else { OpenOptions::new() .read(true) .write(true) .open(dev_path) .map_err(|_| ModifyUsbError::UsbControl(UsbControlResult::FailedToOpenDevice))? }; let request = VmRequest::UsbCommand(UsbControlCommand::AttachDevice { bus, addr, vid, pid, file: usb_file, }); let response = handle_request(&request, socket_path).map_err(|_| ModifyUsbError::SocketFailed)?; match response { VmResponse::UsbResponse(usb_resp) => Ok(usb_resp), r => Err(ModifyUsbError::UnexpectedResponse(r)), } } pub fn do_usb_detach(socket_path: &Path, port: u8) -> ModifyUsbResult<UsbControlResult> { let request = VmRequest::UsbCommand(UsbControlCommand::DetachDevice { port }); let response = handle_request(&request, socket_path).map_err(|_| ModifyUsbError::SocketFailed)?; match response { VmResponse::UsbResponse(usb_resp) => Ok(usb_resp), r => Err(ModifyUsbError::UnexpectedResponse(r)), } } pub fn do_usb_list(socket_path: &Path) -> ModifyUsbResult<UsbControlResult> { let mut ports: [u8; USB_CONTROL_MAX_PORTS] = Default::default(); for (index, port) in ports.iter_mut().enumerate() { *port = index as u8 } let request = VmRequest::UsbCommand(UsbControlCommand::ListDevice { ports }); let response = handle_request(&request, socket_path).map_err(|_| ModifyUsbError::SocketFailed)?; match response { VmResponse::UsbResponse(usb_resp) => Ok(usb_resp), r => Err(ModifyUsbError::UnexpectedResponse(r)), } } pub type DoModifyBatteryResult = std::result::Result<(), ()>; pub fn do_modify_battery( socket_path: &Path, battery_type: &str, property: &str, target: &str, ) -> DoModifyBatteryResult { let response = match battery_type.parse::<Batte
let request = VmRequest::BatCommand(type_, cmd); Ok(handle_request(&request, socket_path)?) } Err(e) => Err(ModifyBatError::BatControlErr(e)), }, Err(e) => Err(ModifyBatError::BatControlErr(e)), }; match response { Ok(response) => { println!("{}", response); Ok(()) } Err(e) => { println!("error {}", e); Err(()) } } } pub type HandleRequestResult = std::result::Result<VmResponse, ()>; pub fn handle_request(request: &VmRequest, socket_path: &Path) -> HandleRequestResult { match UnixSeqpacket::connect(&socket_path) { Ok(s) => { let socket = Tube::new(s); if let Err(e) = socket.send(request) { error!( "failed to send request to socket at '{:?}': {}", socket_path, e ); return Err(()); } match socket.recv() { Ok(response) => Ok(response), Err(e) => { error!( "failed to send request to socket at '{:?}': {}", socket_path, e ); Err(()) } } } Err(e) => { error!("failed to connect to socket at '{:?}': {}", socket_path, e); Err(()) } } }
ryType>() { Ok(type_) => match BatControlCommand::new(property.to_string(), target.to_string()) { Ok(cmd) => {
function_block-random_span
[ { "content": "pub fn win32_wide_string(value: &str) -> Vec<u16> {\n\n OsStr::new(value).encode_wide().chain(once(0)).collect()\n\n}\n\n\n\n/// Returns the length, in u16 words (*not* UTF-16 chars), of a null-terminated u16 string.\n\n/// Safe when `wide` is non-null and points to a u16 string terminated by a null character.\n\nunsafe fn strlen_ptr_u16(wide: *const u16) -> usize {\n\n assert!(!wide.is_null());\n\n for i in 0.. {\n\n if *wide.offset(i) == 0 {\n\n return i as usize;\n\n }\n\n }\n\n unreachable!()\n\n}\n\n\n\n/// Converts a UTF-16 null-terminated string to an owned `String`. Any invalid code points are\n\n/// converted to `std::char::REPLACEMENT_CHARACTER`.\n\n/// Safe when `wide` is non-null and points to a u16 string terminated by a null character.\n\npub unsafe fn from_ptr_win32_wide_string(wide: *const u16) -> String {\n\n assert!(!wide.is_null());\n\n let len = strlen_ptr_u16(wide);\n\n let slice = slice::from_raw_parts(wide, len);\n\n String::from_utf16_lossy(slice)\n\n}\n\n\n", "file_path": "win_util/src/lib.rs", "rank": 1, "score": 383935.82777037204 }, { "content": "fn parse_bus_id_addr(v: &str) -> ModifyUsbResult<(u8, u8, u16, u16)> {\n\n debug!(\"parse_bus_id_addr: {}\", v);\n\n let mut ids = v.split(':');\n\n match (ids.next(), ids.next(), ids.next(), ids.next()) {\n\n (Some(bus_id), Some(addr), Some(vid), Some(pid)) => {\n\n let bus_id = bus_id\n\n .parse::<u8>()\n\n .map_err(|e| ModifyUsbError::ArgParseInt(\"bus_id\", bus_id.to_owned(), e))?;\n\n let addr = addr\n\n .parse::<u8>()\n\n .map_err(|e| ModifyUsbError::ArgParseInt(\"addr\", addr.to_owned(), e))?;\n\n let vid = u16::from_str_radix(vid, 16)\n\n .map_err(|e| ModifyUsbError::ArgParseInt(\"vid\", vid.to_owned(), e))?;\n\n let pid = u16::from_str_radix(pid, 16)\n\n .map_err(|e| ModifyUsbError::ArgParseInt(\"pid\", pid.to_owned(), e))?;\n\n Ok((bus_id, addr, vid, pid))\n\n }\n\n _ => Err(ModifyUsbError::ArgParse(\n\n \"BUS_ID_ADDR_BUS_NUM_DEV_NUM\",\n\n v.to_owned(),\n\n )),\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 3, "score": 372884.2766254208 }, { "content": "/// Verifies that |raw_descriptor| is actually owned by this process and duplicates it\n\n/// to ensure that we have a unique handle to it.\n\npub fn validate_raw_descriptor(raw_descriptor: RawDescriptor) -> Result<RawDescriptor> {\n\n validate_raw_fd(raw_descriptor)\n\n}\n\n\n", "file_path": "base/src/sys/unix/mod.rs", "rank": 5, "score": 352670.5158547285 }, { "content": "fn set_argument(cfg: &mut Config, name: &str, value: Option<&str>) -> argument::Result<()> {\n\n match name {\n\n \"\" => {\n\n if cfg.executable_path.is_some() {\n\n return Err(argument::Error::TooManyArguments(format!(\n\n \"A VM executable was already specified: {:?}\",\n\n cfg.executable_path\n\n )));\n\n }\n\n let kernel_path = PathBuf::from(value.unwrap());\n\n if !kernel_path.exists() {\n\n return Err(argument::Error::InvalidValue {\n\n value: value.unwrap().to_owned(),\n\n expected: String::from(\"this kernel path does not exist\"),\n\n });\n\n }\n\n cfg.executable_path = Some(Executable::Kernel(kernel_path));\n\n }\n\n \"kvm-device\" => {\n\n let kvm_device_path = PathBuf::from(value.unwrap());\n", "file_path": "src/main.rs", "rank": 6, "score": 343095.9742708369 }, { "content": "pub fn win32_string(value: &str) -> CString {\n\n CString::new(value).unwrap()\n\n}\n\n\n", "file_path": "win_util/src/lib.rs", "rank": 7, "score": 337657.3558715797 }, { "content": "/// Parses the given `args` against the list of know arguments `arg_list` and calls `f` with each\n\n/// present argument and value if required.\n\n///\n\n/// This function guarantees that only valid long argument names from `arg_list` are sent to the\n\n/// callback `f`. It is also guaranteed that if an arg requires a value (i.e.\n\n/// `arg.value.is_some()`), the value will be `Some` in the callbacks arguments. If the callback\n\n/// returns `Err`, this function will end parsing and return that `Err`.\n\n///\n\n/// See the [module level](index.html) example for a usage example.\n\npub fn set_arguments<I, R, F>(args: I, arg_list: &[Argument], mut f: F) -> Result<()>\n\nwhere\n\n I: Iterator<Item = R>,\n\n R: AsRef<str>,\n\n F: FnMut(&str, Option<&str>) -> Result<()>,\n\n{\n\n parse_arguments(args, |name, value| {\n\n let mut matches = None;\n\n for arg in arg_list {\n\n if let Some(short) = arg.short {\n\n if name.len() == 1 && name.starts_with(short) {\n\n if value.is_some() != arg.value.is_some() {\n\n return Err(Error::ExpectedValue(short.to_string()));\n\n }\n\n matches = Some(arg.long);\n\n }\n\n }\n\n if matches.is_none() && arg.long == name {\n\n if value.is_none() && arg.value_mode == ArgumentValueMode::Required {\n\n return Err(Error::ExpectedValue(arg.long.to_owned()));\n", "file_path": "src/argument.rs", "rank": 8, "score": 335056.67809551803 }, { "content": "// Reads the next u16 from the file.\n\nfn read_u16_from_file(mut f: &File) -> Result<u16> {\n\n let mut value = [0u8; 2];\n\n (&mut f)\n\n .read_exact(&mut value)\n\n .map_err(Error::ReadingHeader)?;\n\n Ok(u16::from_be_bytes(value))\n\n}\n\n\n", "file_path": "disk/src/qcow/mod.rs", "rank": 9, "score": 333667.99742163694 }, { "content": "// Compile a single proto file located at $input_path, placing the generated\n\n// code at $OUT_DIR/$module and emitting the right `pub mod $module` into the\n\n// output file.\n\nfn protoc<P: AsRef<Path>>(module: &str, input_path: P, mut out: &File) -> Result<()> {\n\n let input_path = input_path.as_ref();\n\n let input_dir = input_path.parent().unwrap();\n\n\n\n // Place output in a subdirectory so that different protos with the same\n\n // common filename (like interface.proto) do not conflict.\n\n let out_dir = format!(\"{}/{}\", env::var(\"OUT_DIR\")?, module);\n\n fs::create_dir_all(&out_dir)?;\n\n\n\n // Invoke protobuf compiler.\n\n protoc_rust::Codegen::new()\n\n .input(input_path.as_os_str().to_str().unwrap())\n\n .include(input_dir.as_os_str().to_str().unwrap())\n\n .out_dir(&out_dir)\n\n .run()\n\n .expect(\"protoc\");\n\n\n\n // Write out a `mod` that refers to the generated module.\n\n //\n\n // The lint suppression is because protoc-rust emits\n", "file_path": "protos/build.rs", "rank": 10, "score": 332194.68765056925 }, { "content": "/// Cross platform stub to create a platform specific IoBuf.\n\npub fn create_iobuf(addr: *mut u8, len: usize) -> IoBuf {\n\n iovec {\n\n iov_base: addr as *mut c_void,\n\n iov_len: len,\n\n }\n\n}\n\n\n\n/// This type is essentialy `std::io::IoBufMut`, and guaranteed to be ABI-compatible with\n\n/// `libc::iovec`; however, it does NOT automatically deref to `&mut [u8]`, which is critical\n\n/// because it can point to guest memory. (Guest memory is implicitly mutably borrowed by the\n\n/// guest, so another mutable borrow would violate Rust assumptions about references.)\n\n#[derive(Copy, Clone)]\n\n#[repr(transparent)]\n\npub struct IoBufMut<'a> {\n\n iov: iovec,\n\n phantom: PhantomData<&'a mut [u8]>,\n\n}\n\n\n\nimpl<'a> IoBufMut<'a> {\n\n pub fn new(buf: &mut [u8]) -> IoBufMut<'a> {\n", "file_path": "common/data_model/src/sys/unix.rs", "rank": 11, "score": 330468.0841441027 }, { "content": "/// Cross platform stub to create a platform specific IoBuf.\n\npub fn create_iobuf(addr: *mut u8, len: usize) -> IoBuf {\n\n WSABUF {\n\n buf: addr as *mut i8,\n\n len: len as u32,\n\n }\n\n}\n\n\n\n/// This type is essentialy `std::io::IoBufMut`, and guaranteed to be ABI-compatible with\n\n/// `WSABUF`; however, it does NOT automatically deref to `&mut [u8]`, which is critical\n\n/// because it can point to guest memory. (Guest memory is implicitly mutably borrowed by the\n\n/// guest, so another mutable borrow would violate Rust assumptions about references.)\n\n#[derive(Copy, Clone)]\n\n#[repr(transparent)]\n\npub struct IoBufMut<'a> {\n\n buf: WSABUF,\n\n phantom: PhantomData<&'a mut [u8]>,\n\n}\n\n\n\nimpl<'a> IoBufMut<'a> {\n\n pub fn new(buf: &mut [u8]) -> IoBufMut<'a> {\n", "file_path": "common/data_model/src/sys/windows.rs", "rank": 12, "score": 330468.0841441027 }, { "content": "/// Prints command line usage information to stdout.\n\n///\n\n/// Usage information is printed according to the help fields in `args` with a leading usage line.\n\n/// The usage line is of the format \"`program_name` \\[ARGUMENTS\\] `required_arg`\".\n\npub fn print_help(program_name: &str, required_arg: &str, args: &[Argument]) {\n\n println!(\n\n \"Usage: {} {}{}\\n\",\n\n program_name,\n\n if args.is_empty() { \"\" } else { \"[ARGUMENTS] \" },\n\n required_arg\n\n );\n\n if args.is_empty() {\n\n return;\n\n }\n\n\n\n let indent_depth = 30;\n\n let minimum_width_of_help = DEFAULT_COLUMNS - 1 - indent_depth;\n\n let columns = get_columns();\n\n let columns = minimum_width_of_help.max(columns - indent_depth);\n\n\n\n println!(\"Argument{}:\", if args.len() > 1 { \"s\" } else { \"\" });\n\n for arg in args {\n\n let leading_part = get_leading_part(arg);\n\n if leading_part.len() <= indent_depth {\n", "file_path": "src/argument.rs", "rank": 13, "score": 321610.12992335454 }, { "content": "/// Retrieves the file descriptors owned by the global syslogger.\n\n///\n\n/// Does nothing if syslog was never initialized. If their are any file descriptors, they will be\n\n/// pushed into `fds`.\n\n///\n\n/// Note that the `stderr` file descriptor is never added, as it is not owned by syslog.\n\npub fn push_descriptors(fds: &mut Vec<RawDescriptor>) {\n\n let state = syslog_lock!();\n\n state.syslog.push_descriptors(fds);\n\n fds.extend(state.file.iter().map(|f| f.as_raw_descriptor()));\n\n}\n\n\n\nmacro_rules! CHRONO_TIMESTAMP_FIXED_FMT {\n\n () => {\n\n \"%F %T%.9f\"\n\n };\n\n}\n\n\n", "file_path": "base/src/syslog.rs", "rank": 14, "score": 316582.25473051297 }, { "content": "/// Detect the type of an image file by checking for a valid header of the supported formats.\n\npub fn detect_image_type(file: &File) -> Result<ImageType> {\n\n let mut f = file;\n\n let disk_size = f.get_len().map_err(Error::SeekingFile)?;\n\n let orig_seek = f.seek(SeekFrom::Current(0)).map_err(Error::SeekingFile)?;\n\n f.seek(SeekFrom::Start(0)).map_err(Error::SeekingFile)?;\n\n\n\n info!(\"disk size {}, \", disk_size);\n\n log_host_fs_type(f)?;\n\n // Try to read the disk in a nicely-aligned block size unless the whole file is smaller.\n\n const MAGIC_BLOCK_SIZE: usize = 4096;\n\n #[repr(align(4096))]\n\n struct BlockAlignedBuffer {\n\n data: [u8; MAGIC_BLOCK_SIZE],\n\n }\n\n let mut magic = BlockAlignedBuffer {\n\n data: [0u8; MAGIC_BLOCK_SIZE],\n\n };\n\n let magic_read_len = if disk_size > MAGIC_BLOCK_SIZE as u64 {\n\n MAGIC_BLOCK_SIZE\n\n } else {\n", "file_path": "disk/src/disk.rs", "rank": 15, "score": 309951.5095673045 }, { "content": "pub fn parse_hex_or_decimal(maybe_hex_string: &str) -> Result<u64> {\n\n // Parse string starting with 0x as hex and others as numbers.\n\n if let Some(hex_string) = maybe_hex_string.strip_prefix(\"0x\") {\n\n u64::from_str_radix(hex_string, 16)\n\n } else if let Some(hex_string) = maybe_hex_string.strip_prefix(\"0X\") {\n\n u64::from_str_radix(hex_string, 16)\n\n } else {\n\n u64::from_str(maybe_hex_string)\n\n }\n\n .map_err(|e| Error::InvalidValue {\n\n value: maybe_hex_string.to_string(),\n\n expected: e.to_string(),\n\n })\n\n}\n\n\n\npub struct KeyValuePair<'a> {\n\n context: &'a str,\n\n key: &'a str,\n\n value: Option<&'a str>,\n\n}\n", "file_path": "src/argument.rs", "rank": 16, "score": 308986.42702610727 }, { "content": "/// Returns a stable path based on the label, pid, and tid. If the label isn't provided the\n\n/// current_exe is used instead.\n\npub fn get_temp_path(label: Option<&str>) -> PathBuf {\n\n if let Some(label) = label {\n\n temp_dir().join(format!(\"{}-{}-{}\", label, getpid(), gettid()))\n\n } else {\n\n get_temp_path(Some(\n\n current_exe()\n\n .unwrap()\n\n .file_name()\n\n .unwrap()\n\n .to_str()\n\n .unwrap(),\n\n ))\n\n }\n\n}\n\n\n\n/// Automatically deletes the path it contains when it goes out of scope unless it is a test and\n\n/// drop is called after a panic!.\n\n///\n\n/// This is particularly useful for creating temporary directories for use with tests.\n\npub struct ScopedPath<P: AsRef<Path>>(P);\n", "file_path": "base/src/sys/unix/scoped_path.rs", "rank": 17, "score": 306999.3838352597 }, { "content": "/// Deserializes a Tube packet by calling the supplied read function. This function MUST\n\n/// assert that the buffer was filled.\n\npub fn deserialize_and_recv<T: DeserializeOwned, F: Fn(&mut [u8]) -> io::Result<usize>>(\n\n read_fn: F,\n\n) -> Result<T> {\n\n let mut header_bytes = vec![0u8; mem::size_of::<MsgHeader>()];\n\n perform_read(&read_fn, header_bytes.as_mut_slice()).map_err(Error::Recv)?;\n\n\n\n // Safe because the header is always written by the send function, and only that function\n\n // writes to this channel.\n\n let header =\n\n MsgHeader::from_slice(header_bytes.as_slice()).expect(\"Tube header failed to deserialize.\");\n\n\n\n let mut msg_json = vec![0u8; header.msg_json_size];\n\n perform_read(&read_fn, msg_json.as_mut_slice()).map_err(Error::Recv)?;\n\n\n\n if msg_json.is_empty() {\n\n // This means we got a message header, but there is no json body (due to a zero size in\n\n // the header). This should never happen because it means the receiver is getting no\n\n // data whatsoever from the sender.\n\n return Err(Error::RecvUnexpectedEmptyBody);\n\n }\n", "file_path": "base/src/sys/windows/tube.rs", "rank": 18, "score": 305192.16141945927 }, { "content": "/// Allows the use of any serde deserializer within a closure while providing access to the a set of\n\n/// descriptors for use in `deserialize_descriptor`.\n\n///\n\n/// This is the corresponding call to use deserialize after using `SerializeDescriptors`.\n\n///\n\n/// If `deserialize_with_descriptors` is called anywhere within the given closure, it return an\n\n/// error.\n\npub fn deserialize_with_descriptors<F, T, E>(\n\n f: F,\n\n descriptors: &mut Vec<Option<SafeDescriptor>>,\n\n) -> Result<T, E>\n\nwhere\n\n F: FnOnce() -> Result<T, E>,\n\n E: de::Error,\n\n{\n\n let swap_descriptors = std::mem::take(descriptors);\n\n set_descriptor_src(swap_descriptors).map_err(E::custom)?;\n\n\n\n // catch_unwind is used to ensure that set_descriptor_src is always balanced with a call to\n\n // take_descriptor_src afterwards.\n\n let res = catch_unwind(AssertUnwindSafe(f));\n\n\n\n // unwrap is used because set_descriptor_src is always called before this, so it should never\n\n // panic.\n\n *descriptors = take_descriptor_src().unwrap();\n\n\n\n match res {\n", "file_path": "base/src/descriptor_reflection.rs", "rank": 19, "score": 297627.8224172584 }, { "content": "/// Obtain file system type of the file system that the file is served from.\n\npub fn get_filesystem_type(file: &File) -> Result<i64> {\n\n let mut statfs_buf = MaybeUninit::<libc::statfs>::uninit();\n\n // Safe because we just got the memory space with exact required amount and\n\n // passing that on.\n\n syscall!(unsafe { fstatfs(file.as_raw_fd(), statfs_buf.as_mut_ptr()) })?;\n\n // Safe because the kernel guarantees the struct is initialized.\n\n let statfs_buf = unsafe { statfs_buf.assume_init() };\n\n Ok(statfs_buf.f_type as i64)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n #[test]\n\n fn simple_test() {\n\n let file = File::open(\"/dev/null\").unwrap();\n\n let _fstype = get_filesystem_type(&file).unwrap();\n\n }\n\n}\n", "file_path": "base/src/sys/unix/get_filesystem_type.rs", "rank": 20, "score": 296698.0607524957 }, { "content": "/// Construct a bmRequestType value for a control request.\n\npub fn control_request_type(\n\n type_: ControlRequestType,\n\n dir: ControlRequestDataPhaseTransferDirection,\n\n recipient: ControlRequestRecipient,\n\n) -> u8 {\n\n ((type_ as u8) << CONTROL_REQUEST_TYPE_OFFSET)\n\n | ((dir as u8) << DATA_PHASE_DIRECTION_OFFSET)\n\n | (recipient as u8)\n\n}\n\n\n\n#[cfg(test)]\n\n#[allow(clippy::unusual_byte_groupings)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn control_request_types() {\n\n assert_eq!(\n\n control_request_type(\n\n ControlRequestType::Standard,\n", "file_path": "usb_util/src/types.rs", "rank": 21, "score": 293413.5726514129 }, { "content": "pub fn gdb_thread(mut gdbstub: GdbStub, port: u32) {\n\n let addr = format!(\"0.0.0.0:{}\", port);\n\n let listener = match TcpListener::bind(addr.clone()) {\n\n Ok(s) => s,\n\n Err(e) => {\n\n error!(\"Failed to create a TCP listener: {}\", e);\n\n return;\n\n }\n\n };\n\n info!(\"Waiting for a GDB connection on {:?}...\", addr);\n\n\n\n let (stream, addr) = match listener.accept() {\n\n Ok(v) => v,\n\n Err(e) => {\n\n error!(\"Failed to accept a connection from GDB: {}\", e);\n\n return;\n\n }\n\n };\n\n info!(\"GDB connected from {}\", addr);\n\n\n", "file_path": "src/gdb.rs", "rank": 22, "score": 293196.4883138031 }, { "content": "/// Check if log is enabled for given optional path and Priority\n\npub fn log_enabled(pri: Priority, file_path: Option<&str>) -> bool {\n\n let log_level = match (crate::syslog::lock(), file_path) {\n\n (Ok(state), Some(file_path)) => {\n\n let parsed_path = Path::new(file_path);\n\n // Since path_log_levels is sorted with longest prefixes first, this will yield the\n\n // longest matching prefix if one exists.\n\n state\n\n .path_log_levels\n\n .iter()\n\n .find_map(|filter| {\n\n if parsed_path.starts_with(filter.path_prefix.as_path()) {\n\n Some(filter.level)\n\n } else {\n\n None\n\n }\n\n })\n\n .unwrap_or(state.log_level)\n\n }\n\n (Ok(state), None) => state.log_level,\n\n _ => return false,\n\n };\n\n match log_level {\n\n PriorityFilter::ShowAll => true,\n\n PriorityFilter::Silent => false,\n\n PriorityFilter::Priority(log_level) => (pri as u8) <= (log_level as u8),\n\n }\n\n}\n\n\n", "file_path": "base/src/syslog.rs", "rank": 23, "score": 292290.72866422415 }, { "content": "/// Returns a string representation of the given virtio device type number.\n\npub fn type_to_str(type_: u32) -> Option<&'static str> {\n\n Some(match type_ {\n\n TYPE_NET => \"net\",\n\n TYPE_BLOCK => \"block\",\n\n TYPE_CONSOLE => \"console\",\n\n TYPE_RNG => \"rng\",\n\n TYPE_BALLOON => \"balloon\",\n\n TYPE_RPMSG => \"rpmsg\",\n\n TYPE_SCSI => \"scsi\",\n\n TYPE_9P => \"9p\",\n\n TYPE_RPROC_SERIAL => \"rproc-serial\",\n\n TYPE_CAIF => \"caif\",\n\n TYPE_INPUT => \"input\",\n\n TYPE_GPU => \"gpu\",\n\n TYPE_VSOCK => \"vsock\",\n\n TYPE_CRYPTO => \"crypto\",\n\n TYPE_IOMMU => \"iommu\",\n\n TYPE_VHOST_USER => \"vhost-user\",\n\n TYPE_SOUND => \"snd\",\n\n TYPE_FS => \"fs\",\n\n TYPE_PMEM => \"pmem\",\n\n TYPE_WL => \"wl\",\n\n TYPE_TPM => \"tpm\",\n\n TYPE_VIDEO_DEC => \"video-decoder\",\n\n TYPE_VIDEO_ENC => \"video-encoder\",\n\n _ => return None,\n\n })\n\n}\n\n\n", "file_path": "devices/src/virtio/mod.rs", "rank": 24, "score": 291123.5664948953 }, { "content": "/// Fills `output` completely with random bytes from the specified `source`.\n\npub fn rand_bytes(mut output: &mut [u8], source: Source) -> Result<()> {\n\n if output.is_empty() {\n\n return Ok(());\n\n }\n\n\n\n loop {\n\n // Safe because output is mutable and the writes are limited by output.len().\n\n let bytes = handle_eintr_errno!(unsafe {\n\n libc::getrandom(\n\n output.as_mut_ptr() as *mut c_void,\n\n output.len(),\n\n source.to_getrandom_flags(),\n\n )\n\n });\n\n\n\n if bytes < 0 {\n\n return errno_result();\n\n }\n\n if bytes as usize == output.len() {\n\n return Ok(());\n\n }\n\n\n\n // Wait for more entropy and try again for the remaining bytes.\n\n sleep(POLL_INTERVAL);\n\n output = &mut output[bytes as usize..];\n\n }\n\n}\n\n\n", "file_path": "base/src/sys/unix/rand.rs", "rank": 25, "score": 290548.47774684656 }, { "content": "// Creates a file with `name` in `dir` and fills it with random\n\n// content.\n\nfn create_local_file<P: AsRef<Path>>(dir: P, name: &str) -> Vec<u8> {\n\n let mut content = Vec::new();\n\n File::open(\"/dev/urandom\")\n\n .and_then(|f| f.take(LOCAL_FILE_LEN).read_to_end(&mut content))\n\n .expect(\"failed to read from /dev/urandom\");\n\n\n\n let f = DirEntry::File {\n\n name,\n\n content: &content,\n\n };\n\n f.create(&mut Cow::from(dir.as_ref()));\n\n\n\n content\n\n}\n\n\n", "file_path": "common/p9/src/server/tests.rs", "rank": 26, "score": 288097.48634124204 }, { "content": "/// Returns a `fd` for an opened rendernode device, while filtering out specified\n\n/// undesired drivers.\n\npub fn open_device(undesired: &[&str]) -> RutabagaResult<File> {\n\n const DRM_DIR_NAME: &str = \"/dev/dri\";\n\n const DRM_MAX_MINOR: u32 = 15;\n\n const RENDER_NODE_START: u32 = 128;\n\n\n\n for n in RENDER_NODE_START..=RENDER_NODE_START + DRM_MAX_MINOR {\n\n let path = Path::new(DRM_DIR_NAME).join(format!(\"renderD{}\", n));\n\n\n\n if let Ok(fd) = OpenOptions::new().read(true).write(true).open(path) {\n\n if let Ok(name) = get_drm_device_name(&fd) {\n\n if !undesired.iter().any(|item| *item == name) {\n\n return Ok(fd);\n\n }\n\n }\n\n }\n\n }\n\n\n\n Err(RutabagaError::SpecViolation(\"no DRM rendernode opened\"))\n\n}\n", "file_path": "rutabaga_gfx/src/rutabaga_gralloc/rendernode.rs", "rank": 27, "score": 286439.6663471008 }, { "content": "pub fn get_virtio_direction_name(dir: u8) -> &'static str {\n\n match dir {\n\n VIRTIO_SND_D_OUTPUT => \"VIRTIO_SND_D_OUTPUT\",\n\n VIRTIO_SND_D_INPUT => \"VIRTIO_SND_D_INPUT\",\n\n _ => unreachable!(),\n\n }\n\n}\n", "file_path": "devices/src/virtio/snd/common.rs", "rank": 28, "score": 286384.0969033685 }, { "content": "/// Open the file with the given path, or if it is of the form `/proc/self/fd/N` then just use the\n\n/// file descriptor.\n\n///\n\n/// Note that this will not work properly if the same `/proc/self/fd/N` path is used twice in\n\n/// different places, as the metadata (including the offset) will be shared between both file\n\n/// descriptors.\n\npub fn open_file<P: AsRef<Path>>(path: P, options: &OpenOptions) -> Result<File> {\n\n let path = path.as_ref();\n\n // Special case '/proc/self/fd/*' paths. The FD is already open, just use it.\n\n Ok(if let Some(fd) = safe_descriptor_from_path(path)? {\n\n fd.into()\n\n } else {\n\n options.open(path)?\n\n })\n\n}\n\n\n", "file_path": "base/src/sys/unix/mod.rs", "rank": 29, "score": 284761.3852396017 }, { "content": "/// Grabs an event device (see EVIOCGGRAB ioctl for details). After this function succeeds the given\n\n/// descriptor has exclusive access to the device, effectively making it unusable for any other process in\n\n/// the host.\n\npub fn grab_evdev<T: AsRawDescriptor>(descriptor: &mut T) -> Result<()> {\n\n let val: u32 = 1;\n\n let ret = unsafe {\n\n // Safe because the kernel only read the value of the ptr and we check the return value\n\n ioctl_with_ref(\n\n &Descriptor(descriptor.as_raw_descriptor()),\n\n EVIOCGRAB(),\n\n &val,\n\n )\n\n };\n\n if ret == 0 {\n\n Ok(())\n\n } else {\n\n Err(InputError::EvdevGrabError(errno()))\n\n }\n\n}\n\n\n", "file_path": "devices/src/virtio/input/evdev.rs", "rank": 30, "score": 283843.8537278961 }, { "content": "pub fn ungrab_evdev<T: AsRawDescriptor>(descriptor: &mut T) -> Result<()> {\n\n let ret = unsafe {\n\n // Safe because the kernel only reads the value of the ptr (doesn't dereference) and\n\n // we check the return value\n\n ioctl_with_ptr(\n\n &Descriptor(descriptor.as_raw_descriptor()),\n\n EVIOCGRAB(),\n\n null::<u32>(),\n\n )\n\n };\n\n if ret == 0 {\n\n Ok(())\n\n } else {\n\n Err(InputError::EvdevGrabError(errno()))\n\n }\n\n}\n", "file_path": "devices/src/virtio/input/evdev.rs", "rank": 31, "score": 283837.99212815333 }, { "content": "/// Read raw bytes from stdin.\n\n///\n\n/// This will block depending on the underlying mode of stdin. This will ignore the usual lock\n\n/// around stdin that the stdlib usually uses. If other code is using stdin, it is undefined who\n\n/// will get the underlying bytes.\n\npub fn read_raw_stdin(out: &mut [u8]) -> Result<usize> {\n\n // Safe because reading from stdin shouldn't have any safety implications.\n\n unsafe { read_raw(STDIN_FILENO, out) }\n\n}\n\n\n\n/// Trait for file descriptors that are TTYs, according to `isatty(3)`.\n\n///\n\n/// This is marked unsafe because the implementation must promise that the returned RawFd is a valid\n\n/// fd and that the lifetime of the returned fd is at least that of the trait object.\n\npub unsafe trait Terminal {\n\n /// Gets the file descriptor of the TTY.\n\n fn tty_fd(&self) -> RawFd;\n\n\n\n /// Set this terminal's mode to canonical mode (`ICANON | ECHO | ISIG`).\n\n fn set_canon_mode(&self) -> Result<()> {\n\n modify_mode(self.tty_fd(), |t| t.c_lflag |= ICANON | ECHO | ISIG)\n\n }\n\n\n\n /// Set this terminal's mode to raw mode (`!(ICANON | ECHO | ISIG)`).\n\n fn set_raw_mode(&self) -> Result<()> {\n", "file_path": "base/src/sys/unix/terminal.rs", "rank": 32, "score": 283219.77598759416 }, { "content": "fn create_aml_string(v: &str) -> Vec<u8> {\n\n let mut data = vec![STRINGOP];\n\n data.extend_from_slice(v.as_bytes());\n\n data.push(0x0); /* NullChar */\n\n data\n\n}\n\n\n\n/// implement Aml trait for 'str' so that 'str' can be directly append to the aml vector\n\npub type AmlStr = &'static str;\n\n\n\nimpl Aml for AmlStr {\n\n fn to_aml_bytes(&self, bytes: &mut Vec<u8>) {\n\n bytes.append(&mut create_aml_string(self));\n\n }\n\n}\n\n\n\n/// implement Aml trait for 'String'. So purpose with str.\n\npub type AmlString = String;\n\n\n\nimpl Aml for AmlString {\n", "file_path": "acpi_tables/src/aml.rs", "rank": 33, "score": 283031.7435880961 }, { "content": "/// Open the file with the given path.\n\n///\n\n/// Note that on POSIX< this wrapper handles opening existing FDs via /proc/self/fd/N. On Windows,\n\n/// this functionality doesn't exist, but we preserve this seemingly not very useful function to\n\n/// simplify cross platform code.\n\npub fn open_file<P: AsRef<Path>>(path: P, options: &OpenOptions) -> Result<File> {\n\n Ok(options.open(path)?)\n\n}\n\n\n", "file_path": "base/src/sys/windows/win/mod.rs", "rank": 34, "score": 281196.55092261004 }, { "content": "/// Given `data` containing a full set of descriptors as provided by the Linux kernel\n\n/// usbdevfs `descriptors` file, parse the descriptors into a tree data structure.\n\npub fn parse_usbfs_descriptors(data: &[u8]) -> Result<DeviceDescriptorTree> {\n\n let mut offset = 0;\n\n\n\n // Find the next descriptor of type T and return it and its offset.\n\n // Any other descriptors encountered while searching for the expected type are skipped.\n\n // The `offset` parameter will be advanced to point to the next byte after the returned\n\n // descriptor.\n\n fn next_descriptor<T: Descriptor + DataInit>(\n\n data: &[u8],\n\n offset: &mut usize,\n\n ) -> Result<(T, usize)> {\n\n let desc_type = T::descriptor_type() as u8;\n\n loop {\n\n let hdr = DescriptorHeader::from_slice(\n\n data.get(*offset..*offset + size_of::<DescriptorHeader>())\n\n .ok_or(Error::DescriptorParse)?,\n\n )\n\n .ok_or(Error::DescriptorParse)?;\n\n if hdr.bDescriptorType == desc_type {\n\n if usize::from(hdr.bLength) < size_of::<DescriptorHeader>() + size_of::<T>() {\n", "file_path": "usb_util/src/descriptor.rs", "rank": 35, "score": 280139.9489200356 }, { "content": "/// Takes a descriptor at the given index from the thread local source of descriptors.\n\n//\n\n/// Returns None if the thread local source was not already initialized.\n\nfn take_descriptor(index: usize) -> Result<SafeDescriptor, &'static str> {\n\n DESCRIPTOR_SRC.with(|d| {\n\n d.borrow_mut()\n\n .as_mut()\n\n .ok_or(\"attempt to deserialize descriptor without descriptor source\")?\n\n .get_mut(index)\n\n .ok_or(\"attempt to deserialize out of bounds descriptor\")?\n\n .take()\n\n .ok_or(\"attempt to deserialize descriptor that was already taken\")\n\n })\n\n}\n\n\n", "file_path": "base/src/descriptor_reflection.rs", "rank": 36, "score": 280008.42622156674 }, { "content": "pub fn get_filesystem_type(_file: &File) -> Result<i64> {\n\n // TODO (b/203574110): create a windows equivalent to get the filesystem type like fstatfs\n\n Ok(0)\n\n}\n", "file_path": "base/src/sys/windows/win/get_filesystem_type.rs", "rank": 37, "score": 279526.8055984034 }, { "content": "/// Gets the name of an event device (see EVIOCGNAME ioctl for details).\n\npub fn name<T: AsRawDescriptor>(descriptor: &T) -> Result<Vec<u8>> {\n\n let mut name = evdev_buffer::new();\n\n let len = unsafe {\n\n // Safe because the kernel won't write more than size of evdev_buffer and we check the\n\n // return value\n\n ioctl_with_mut_ref(\n\n &Descriptor(descriptor.as_raw_descriptor()),\n\n EVIOCGNAME(),\n\n &mut name,\n\n )\n\n };\n\n if len < 0 {\n\n return Err(InputError::EvdevNameError(errno()));\n\n }\n\n Ok(name.buffer[0..len as usize].to_vec())\n\n}\n\n\n", "file_path": "devices/src/virtio/input/evdev.rs", "rank": 38, "score": 277923.7119706626 }, { "content": "/// Parse a string of delimiter-separated key-value options. This is intended to simplify parsing\n\n/// of command-line options that take a bunch of parameters encoded into the argument, e.g. for\n\n/// setting up an emulated hardware device. Returns an Iterator of KeyValuePair, which provides\n\n/// convenience functions to parse numeric values and performs appropriate error handling.\n\n///\n\n/// `flagname` - name of the command line parameter, used as context in error messages\n\n/// `s` - the string to parse\n\n/// `delimiter` - the character that separates individual pairs\n\n///\n\n/// Usage example:\n\n/// ```\n\n/// # use crosvm::argument::{Result, parse_key_value_options};\n\n///\n\n/// fn parse_turbo_button_parameters(s: &str) -> Result<(String, u32, bool)> {\n\n/// let mut color = String::new();\n\n/// let mut speed = 0u32;\n\n/// let mut turbo = false;\n\n///\n\n/// for opt in parse_key_value_options(\"turbo-button\", s, ',') {\n\n/// match opt.key() {\n\n/// \"color\" => color = opt.value()?.to_string(),\n\n/// \"speed\" => speed = opt.parse_numeric::<u32>()?,\n\n/// \"turbo\" => turbo = opt.parse_or::<bool>(true)?,\n\n/// _ => return Err(opt.invalid_key_err()),\n\n/// }\n\n/// }\n\n///\n\n/// Ok((color, speed, turbo))\n\n/// }\n\n///\n\n/// assert_eq!(parse_turbo_button_parameters(\"color=red,speed=0xff,turbo\").unwrap(),\n\n/// (\"red\".to_string(), 0xff, true))\n\n/// ```\n\n///\n\n/// TODO: upgrade `delimiter` to generic Pattern support once that has been stabilized\n\n/// at <https://github.com/rust-lang/rust/issues/27721>.\n\npub fn parse_key_value_options<'a>(\n\n flagname: &'a str,\n\n s: &'a str,\n\n delimiter: char,\n\n) -> impl Iterator<Item = KeyValuePair<'a>> {\n\n s.split(delimiter)\n\n .map(|frag| frag.splitn(2, '='))\n\n .map(move |mut kv| KeyValuePair {\n\n context: flagname,\n\n key: kv.next().unwrap_or(\"\"),\n\n value: kv.next(),\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn request_help() {\n", "file_path": "src/argument.rs", "rank": 39, "score": 277681.75402243226 }, { "content": "/// Replaces the optional `File` to echo log messages to.\n\n///\n\n/// The default behavior is to not echo to a file. Passing `None` to this function restores that\n\n/// behavior.\n\n///\n\n/// Does nothing if syslog was never initialized.\n\n///\n\n/// # Arguments\n\n/// * `file` - `Some(file)` to echo to `file`, `None` to disable echoing to the file previously passed to `echo_file`.\n\npub fn echo_file(file: Option<File>) {\n\n let mut state = syslog_lock!();\n\n state.file = file;\n\n}\n\n\n", "file_path": "base/src/syslog.rs", "rank": 40, "score": 275790.2690527858 }, { "content": "/// If the given path is of the form /proc/self/fd/N for some N, returns `Ok(Some(N))`. Otherwise\n\n/// returns `Ok(None)`.\n\npub fn safe_descriptor_from_path<P: AsRef<Path>>(path: P) -> Result<Option<SafeDescriptor>> {\n\n let path = path.as_ref();\n\n if path.parent() == Some(Path::new(\"/proc/self/fd\")) {\n\n let raw_descriptor = path\n\n .file_name()\n\n .and_then(|fd_osstr| fd_osstr.to_str())\n\n .and_then(|fd_str| fd_str.parse::<RawFd>().ok())\n\n .ok_or_else(|| Error::new(EINVAL))?;\n\n let validated_fd = validate_raw_fd(raw_descriptor)?;\n\n Ok(Some(\n\n // Safe because nothing else has access to validated_fd after this call.\n\n unsafe { SafeDescriptor::from_raw_descriptor(validated_fd) },\n\n ))\n\n } else {\n\n Ok(None)\n\n }\n\n}\n\n\n", "file_path": "base/src/sys/unix/mod.rs", "rank": 42, "score": 274414.57459285087 }, { "content": "/// Gets the unique (serial) name of an event device (see EVIOCGUNIQ ioctl for details).\n\npub fn serial_name<T: AsRawDescriptor>(descriptor: &T) -> Result<Vec<u8>> {\n\n let mut uniq = evdev_buffer::new();\n\n let len = unsafe {\n\n // Safe because the kernel won't write more than size of evdev_buffer and we check the\n\n // return value\n\n ioctl_with_mut_ref(\n\n &Descriptor(descriptor.as_raw_descriptor()),\n\n EVIOCGUNIQ(),\n\n &mut uniq,\n\n )\n\n };\n\n if len < 0 {\n\n return Err(InputError::EvdevSerialError(errno()));\n\n }\n\n Ok(uniq.buffer[0..len as usize].to_vec())\n\n}\n\n\n", "file_path": "devices/src/virtio/input/evdev.rs", "rank": 43, "score": 273869.198902179 }, { "content": "/// Reads a part of a Tube packet asserting that it was correctly read. This means:\n\n/// * Treats partial \"message\" (transport framing) reads are Ok, as long as we filled our buffer.\n\n/// We use this to ignore errors when reading the message header, which has the lengths we need\n\n/// to allocate our buffers for the remainder of the message.\n\n/// * We filled the supplied buffer.\n\nfn perform_read<F: Fn(&mut [u8]) -> io::Result<usize>>(\n\n read_fn: &F,\n\n buf: &mut [u8],\n\n) -> io::Result<usize> {\n\n let res = match read_fn(buf) {\n\n Ok(s) => Ok(s),\n\n Err(e)\n\n if e.raw_os_error()\n\n .map_or(false, |errno| errno == ERROR_MORE_DATA as i32) =>\n\n {\n\n Ok(buf.len())\n\n }\n\n Err(e) => Err(e),\n\n };\n\n\n\n let bytes_read = res?;\n\n if bytes_read != buf.len() {\n\n Err(io::Error::new(\n\n io::ErrorKind::UnexpectedEof,\n\n \"failed to fill whole buffer\",\n\n ))\n\n } else {\n\n Ok(bytes_read)\n\n }\n\n}\n\n\n", "file_path": "base/src/sys/windows/tube.rs", "rank": 44, "score": 273839.71352212573 }, { "content": "fn parse_arguments<I, R, F>(args: I, mut f: F) -> Result<()>\n\nwhere\n\n I: Iterator<Item = R>,\n\n R: AsRef<str>,\n\n F: FnMut(&str, Option<&str>) -> Result<()>,\n\n{\n\n enum State {\n\n // Initial state at the start and after finishing a single argument/value.\n\n Top,\n\n // The remaining arguments are all positional.\n\n Positional,\n\n // The next string is the value for the argument `name`.\n\n Value { name: String },\n\n }\n\n let mut s = State::Top;\n\n for arg in args {\n\n let arg = arg.as_ref();\n\n loop {\n\n let mut arg_consumed = true;\n\n s = match s {\n", "file_path": "src/argument.rs", "rank": 45, "score": 272960.66440273623 }, { "content": "/// Creates a flattened device tree containing all of the parameters used\n\n/// by Android.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `fdt` - The DTB to modify. The top-most node should be open.\n\n/// * `android-fstab` - A text file of Android fstab entries to add to the DTB\n\npub fn create_android_fdt(fdt: &mut FdtWriter, fstab: File) -> Result<()> {\n\n let vecs = BufReader::new(fstab)\n\n .lines()\n\n .map(|l| parse_fstab_line(&l.map_err(Error::FdtIoError)?))\n\n .collect::<Result<Vec<Vec<String>>>>()?;\n\n let firmware_node = fdt.begin_node(\"firmware\")?;\n\n let android_node = fdt.begin_node(\"android\")?;\n\n fdt.property_string(\"compatible\", \"android,firmware\")?;\n\n\n\n let (dtprop, fstab): (_, Vec<_>) = vecs.into_iter().partition(|x| x[0] == \"#dt-vendor\");\n\n let vendor_node = fdt.begin_node(\"vendor\")?;\n\n for vec in dtprop {\n\n let content = std::fs::read_to_string(&vec[2]).map_err(Error::FdtIoError)?;\n\n fdt.property_string(&vec[1], &content)?;\n\n }\n\n fdt.end_node(vendor_node)?;\n\n let fstab_node = fdt.begin_node(\"fstab\")?;\n\n fdt.property_string(\"compatible\", \"android,fstab\")?;\n\n for vec in fstab {\n\n let partition = &vec[1][1..];\n", "file_path": "arch/src/android.rs", "rank": 46, "score": 272029.00114750303 }, { "content": "/// Poor man's reflowing function for string. This function will unsplit the\n\n/// lines, an empty line splits a paragraph.\n\nfn reflow(s: &str, offset: usize, width: usize) -> String {\n\n let mut lines: Vec<String> = vec![];\n\n let mut prev = \"\";\n\n let filler = \" \".repeat(offset);\n\n for line in s.lines() {\n\n let line = line.trim();\n\n if line.is_empty() {\n\n // Skip the empty line, the paragraph delimiter.\n\n } else if prev.is_empty() {\n\n // Start a new paragraph if the previous line was empty.\n\n lines.push(line.to_string());\n\n } else if let Some(last) = lines.last_mut() {\n\n *last += \" \";\n\n *last += line;\n\n }\n\n prev = line;\n\n }\n\n let mut lines = lines.into_iter().flat_map(|line| {\n\n let mut output = vec![];\n\n // Split the line with the last space found, or if the word exceeds\n", "file_path": "src/argument.rs", "rank": 47, "score": 271455.3049315645 }, { "content": "fn download_file(url: &str, destination: &Path) -> Result<()> {\n\n let status = Command::new(\"curl\")\n\n .arg(\"--fail\")\n\n .arg(\"--location\")\n\n .args(&[\"--output\", destination.to_str().unwrap()])\n\n .arg(url)\n\n .status();\n\n match status {\n\n Ok(exit_code) => {\n\n if !exit_code.success() {\n\n Err(anyhow!(\"Cannot download {}\", url))\n\n } else {\n\n Ok(())\n\n }\n\n }\n\n Err(error) => Err(anyhow!(error)),\n\n }\n\n}\n\n\n", "file_path": "integration_tests/tests/fixture.rs", "rank": 48, "score": 271129.71439798374 }, { "content": "fn crosvm_command(command: &str, args: &[&str]) -> Result<()> {\n\n println!(\"$ crosvm {} {:?}\", command, &args.join(\" \"));\n\n let status = Command::new(find_crosvm_binary())\n\n .arg(command)\n\n .args(args)\n\n .status()?;\n\n\n\n if !status.success() {\n\n Err(anyhow!(\"Command failed with exit code {}\", status))\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n\n/// Test fixture to spin up a VM running a guest that can be communicated with.\n\n///\n\n/// After creation, commands can be sent via exec_in_guest. The VM is stopped\n\n/// when this instance is dropped.\n\npub struct TestVm {\n\n /// Maintain ownership of test_dir until the vm is destroyed.\n", "file_path": "integration_tests/tests/fixture.rs", "rank": 49, "score": 270691.44165714295 }, { "content": "/// Check if the image file type can be used for async disk access.\n\npub fn async_ok(raw_image: &File) -> Result<bool> {\n\n let image_type = detect_image_type(raw_image)?;\n\n Ok(match image_type {\n\n ImageType::Raw => true,\n\n ImageType::Qcow2 | ImageType::AndroidSparse | ImageType::CompositeDisk => false,\n\n })\n\n}\n\n\n", "file_path": "disk/src/disk.rs", "rank": 50, "score": 270050.24601408845 }, { "content": "/// Copy virtio device configuration data from a subslice of `src` to a subslice of `dst`.\n\n/// Unlike std::slice::copy_from_slice(), this function copies as much as possible within\n\n/// the common subset of the two slices, truncating the requested range instead of\n\n/// panicking if the slices do not match in size.\n\n///\n\n/// `dst_offset` and `src_offset` specify the starting indexes of the `dst` and `src`\n\n/// slices, respectively; if either index is out of bounds, this function is a no-op\n\n/// rather than panicking. This makes it safe to call with arbitrary user-controlled\n\n/// inputs.\n\npub fn copy_config(dst: &mut [u8], dst_offset: u64, src: &[u8], src_offset: u64) {\n\n if let Ok(dst_offset) = usize::try_from(dst_offset) {\n\n if let Ok(src_offset) = usize::try_from(src_offset) {\n\n if let Some(dst_slice) = dst.get_mut(dst_offset..) {\n\n if let Some(src_slice) = src.get(src_offset..) {\n\n let len = cmp::min(dst_slice.len(), src_slice.len());\n\n let dst_subslice = &mut dst_slice[0..len];\n\n let src_subslice = &src_slice[0..len];\n\n dst_subslice.copy_from_slice(src_subslice);\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "devices/src/virtio/mod.rs", "rank": 51, "score": 268464.3620421688 }, { "content": "/// Obtain the leading part of the help message. The output is later processed\n\n/// to reflow. Depending on how short this, newline is used.\n\nfn get_leading_part(arg: &Argument) -> String {\n\n [\n\n match arg.short {\n\n Some(s) => format!(\" -{}, \", s),\n\n None => \" \".to_string(),\n\n },\n\n if arg.long.is_empty() {\n\n \" \".to_string()\n\n } else {\n\n \"--\".to_string()\n\n },\n\n format!(\"{:<12}\", arg.long),\n\n if let Some(v) = arg.value {\n\n format!(\"{}{:<9} \", if arg.long.is_empty() { \" \" } else { \"=\" }, v)\n\n } else {\n\n \" \".to_string()\n\n },\n\n ]\n\n .join(\"\")\n\n}\n\n\n", "file_path": "src/argument.rs", "rank": 52, "score": 268364.9397168319 }, { "content": "/// Clones `descriptor`, returning a new `RawDescriptor` that refers to the same open file\n\n/// description as `descriptor`. The cloned descriptor will have the `FD_CLOEXEC` flag set but will\n\n/// not share any other file descriptor flags with `descriptor`.\n\npub fn clone_descriptor(descriptor: &dyn AsRawDescriptor) -> Result<RawDescriptor> {\n\n clone_fd(&descriptor.as_raw_descriptor())\n\n}\n\n\n", "file_path": "base/src/sys/unix/descriptor.rs", "rank": 53, "score": 267811.0962841465 }, { "content": "fn parse_file_backed_mapping(s: Option<&str>) -> argument::Result<FileBackedMappingParameters> {\n\n let s = s.ok_or(argument::Error::ExpectedValue(String::from(\n\n \"file-backed-mapping: memory mapping option value required\",\n\n )))?;\n\n\n\n let mut address = None;\n\n let mut size = None;\n\n let mut path = None;\n\n let mut offset = None;\n\n let mut writable = false;\n\n let mut sync = false;\n\n let mut align = false;\n\n for opt in argument::parse_key_value_options(\"file-backed-mapping\", s, ',') {\n\n match opt.key() {\n\n \"addr\" => address = Some(opt.parse_numeric::<u64>()?),\n\n \"size\" => size = Some(opt.parse_numeric::<u64>()?),\n\n \"path\" => path = Some(PathBuf::from(opt.value()?)),\n\n \"offset\" => offset = Some(opt.parse_numeric::<u64>()?),\n\n \"ro\" => writable = !opt.parse_or::<bool>(true)?,\n\n \"rw\" => writable = opt.parse_or::<bool>(true)?,\n", "file_path": "src/main.rs", "rank": 54, "score": 267123.9519962475 }, { "content": "#[cfg(feature = \"gpu\")]\n\nfn parse_gpu_options(s: Option<&str>, gpu_params: &mut GpuParameters) -> argument::Result<()> {\n\n #[cfg(feature = \"gfxstream\")]\n\n let mut vulkan_specified = false;\n\n #[cfg(feature = \"gfxstream\")]\n\n let mut syncfd_specified = false;\n\n #[cfg(feature = \"gfxstream\")]\n\n let mut angle_specified = false;\n\n\n\n let mut display_w: Option<u32> = None;\n\n let mut display_h: Option<u32> = None;\n\n\n\n if let Some(s) = s {\n\n let opts = s\n\n .split(',')\n\n .map(|frag| frag.split('='))\n\n .map(|mut kv| (kv.next().unwrap_or(\"\"), kv.next().unwrap_or(\"\")));\n\n\n\n for (k, v) in opts {\n\n match k {\n\n // Deprecated: Specifying --gpu=<mode> Not great as the mode can be set multiple\n", "file_path": "src/main.rs", "rank": 55, "score": 267061.03026812075 }, { "content": "fn validate_arguments(cfg: &mut Config) -> std::result::Result<(), argument::Error> {\n\n if cfg.executable_path.is_none() {\n\n return Err(argument::Error::ExpectedArgument(\"`KERNEL`\".to_owned()));\n\n }\n\n if cfg.host_ip.is_some() || cfg.netmask.is_some() || cfg.mac_address.is_some() {\n\n if cfg.host_ip.is_none() {\n\n return Err(argument::Error::ExpectedArgument(\n\n \"`host_ip` missing from network config\".to_owned(),\n\n ));\n\n }\n\n if cfg.netmask.is_none() {\n\n return Err(argument::Error::ExpectedArgument(\n\n \"`netmask` missing from network config\".to_owned(),\n\n ));\n\n }\n\n if cfg.mac_address.is_none() {\n\n return Err(argument::Error::ExpectedArgument(\n\n \"`mac` missing from network config\".to_owned(),\n\n ));\n\n }\n", "file_path": "src/main.rs", "rank": 56, "score": 266776.76218891435 }, { "content": "fn parse_plugin_mount_option(value: &str) -> argument::Result<BindMount> {\n\n let components: Vec<&str> = value.split(':').collect();\n\n if components.is_empty() || components.len() > 3 || components[0].is_empty() {\n\n return Err(argument::Error::InvalidValue {\n\n value: value.to_owned(),\n\n expected: String::from(\n\n \"`plugin-mount` should be in a form of: <src>[:[<dst>][:<writable>]]\",\n\n ),\n\n });\n\n }\n\n\n\n let src = PathBuf::from(components[0]);\n\n if src.is_relative() {\n\n return Err(argument::Error::InvalidValue {\n\n value: components[0].to_owned(),\n\n expected: String::from(\"the source path for `plugin-mount` must be absolute\"),\n\n });\n\n }\n\n if !src.exists() {\n\n return Err(argument::Error::InvalidValue {\n", "file_path": "src/main.rs", "rank": 57, "score": 266145.8663858992 }, { "content": "fn parse_battery_options(s: Option<&str>) -> argument::Result<BatteryType> {\n\n let mut battery_type: BatteryType = Default::default();\n\n\n\n if let Some(s) = s {\n\n let opts = s\n\n .split(',')\n\n .map(|frag| frag.split('='))\n\n .map(|mut kv| (kv.next().unwrap_or(\"\"), kv.next().unwrap_or(\"\")));\n\n\n\n for (k, v) in opts {\n\n match k {\n\n \"type\" => match v.parse::<BatteryType>() {\n\n Ok(type_) => battery_type = type_,\n\n Err(e) => {\n\n return Err(argument::Error::InvalidValue {\n\n value: v.to_string(),\n\n expected: e.to_string(),\n\n });\n\n }\n\n },\n", "file_path": "src/main.rs", "rank": 58, "score": 265434.1100064998 }, { "content": "fn create_integer(v: usize, bytes: &mut Vec<u8>) {\n\n if v <= u8::max_value().into() {\n\n (v as u8).to_aml_bytes(bytes);\n\n } else if v <= u16::max_value().into() {\n\n (v as u16).to_aml_bytes(bytes);\n\n } else if v <= u32::max_value() as usize {\n\n (v as u32).to_aml_bytes(bytes);\n\n } else {\n\n (v as u64).to_aml_bytes(bytes);\n\n }\n\n}\n\n\n\npub type Usize = usize;\n\n\n\nimpl Aml for Usize {\n\n fn to_aml_bytes(&self, bytes: &mut Vec<u8>) {\n\n create_integer(*self, bytes);\n\n }\n\n}\n\n\n", "file_path": "acpi_tables/src/aml.rs", "rank": 59, "score": 265318.0903966683 }, { "content": "/// Helper function for validating slot_id.\n\npub fn valid_slot_id(slot_id: u8) -> bool {\n\n // slot id count from 1.\n\n slot_id > 0 && slot_id <= MAX_SLOTS\n\n}\n\n\n\n/// XhciRegs hold all xhci registers.\n\npub struct XhciRegs {\n\n pub usbcmd: Register<u32>,\n\n pub usbsts: Register<u32>,\n\n pub dnctrl: Register<u32>,\n\n pub crcr: Register<u64>,\n\n pub dcbaap: Register<u64>,\n\n pub config: Register<u64>,\n\n pub portsc: Vec<Register<u32>>,\n\n pub doorbells: Vec<Register<u32>>,\n\n pub iman: Register<u32>,\n\n pub imod: Register<u32>,\n\n pub erstsz: Register<u32>,\n\n pub erstba: Register<u64>,\n\n pub erdp: Register<u64>,\n\n}\n\n\n", "file_path": "devices/src/usb/xhci/xhci_regs.rs", "rank": 60, "score": 262139.90219217283 }, { "content": "fn parse_plugin_gid_map_option(value: &str) -> argument::Result<GidMap> {\n\n let components: Vec<&str> = value.split(':').collect();\n\n if components.is_empty() || components.len() > 3 || components[0].is_empty() {\n\n return Err(argument::Error::InvalidValue {\n\n value: value.to_owned(),\n\n expected: String::from(\n\n \"`plugin-gid-map` must have exactly 3 components: <inner>[:[<outer>][:<count>]]\",\n\n ),\n\n });\n\n }\n\n\n\n let inner: libc::gid_t = components[0]\n\n .parse()\n\n .map_err(|_| argument::Error::InvalidValue {\n\n value: components[0].to_owned(),\n\n expected: String::from(\"the <inner> component for `plugin-gid-map` is not valid gid\"),\n\n })?;\n\n\n\n let outer: libc::gid_t = match components.get(1) {\n\n None | Some(&\"\") => inner,\n", "file_path": "src/main.rs", "rank": 61, "score": 261366.14163197437 }, { "content": "/// Attempts to deserialize `T` from the key-values string `input`.\n\npub fn from_key_values<'a, T>(input: &'a str) -> Result<T>\n\nwhere\n\n T: Deserialize<'a>,\n\n{\n\n let mut deserializer = KeyValueDeserializer::from(input);\n\n let t = T::deserialize(&mut deserializer)?;\n\n if deserializer.input.is_empty() {\n\n Ok(t)\n\n } else {\n\n Err(deserializer.error_here(ErrorKind::TrailingCharacters))\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::path::PathBuf;\n\n\n\n use super::*;\n\n\n\n #[derive(Deserialize, PartialEq, Debug)]\n", "file_path": "serde_keyvalue/src/key_values.rs", "rank": 62, "score": 261071.1424970102 }, { "content": "#[inline(always)]\n\npub fn getpid() -> Pid {\n\n // Safe because this syscall can never fail and we give it a valid syscall number.\n\n unsafe { syscall(SYS_getpid as c_long) as Pid }\n\n}\n\n\n", "file_path": "base/src/sys/unix/mod.rs", "rank": 63, "score": 260447.74360629614 }, { "content": "/// Safe wrapper for the gettid Linux systemcall.\n\npub fn gettid() -> Pid {\n\n // Calling the gettid() sycall is always safe.\n\n unsafe { syscall(SYS_gettid as c_long) as Pid }\n\n}\n\n\n", "file_path": "base/src/sys/unix/mod.rs", "rank": 64, "score": 260447.74360629614 }, { "content": "#[cfg(any(feature = \"video-decoder\", feature = \"video-encoder\"))]\n\nfn parse_video_options(s: Option<&str>) -> argument::Result<VideoBackendType> {\n\n const VALID_VIDEO_BACKENDS: &[&str] = &[\n\n #[cfg(feature = \"libvda\")]\n\n \"libvda\",\n\n ];\n\n\n\n match s {\n\n None => {\n\n cfg_if::cfg_if! {\n\n if #[cfg(feature = \"libvda\")] {\n\n Ok(VideoBackendType::Libvda)\n\n }\n\n }\n\n }\n\n #[cfg(feature = \"libvda\")]\n\n Some(\"libvda\") => Ok(VideoBackendType::Libvda),\n\n #[cfg(feature = \"libvda\")]\n\n Some(\"libvda-vd\") => Ok(VideoBackendType::LibvdaVd),\n\n Some(s) => Err(argument::Error::InvalidValue {\n\n value: s.to_owned(),\n\n expected: format!(\"should be one of ({})\", VALID_VIDEO_BACKENDS.join(\"|\")),\n\n }),\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 65, "score": 260380.29672433922 }, { "content": "/// Safe wrapper for `getsid(2)`.\n\npub fn getsid(pid: Option<Pid>) -> Result<Pid> {\n\n // Calling the getsid() sycall is always safe.\n\n syscall!(unsafe { libc::getsid(pid.unwrap_or(0)) } as Pid)\n\n}\n\n\n", "file_path": "base/src/sys/unix/mod.rs", "rank": 66, "score": 260041.03247944952 }, { "content": "/// Gets the absolute axes of an event device (see EVIOCGABS ioctl for details).\n\npub fn abs_info<T: AsRawDescriptor>(descriptor: &T) -> BTreeMap<u16, virtio_input_absinfo> {\n\n let mut map: BTreeMap<u16, virtio_input_absinfo> = BTreeMap::new();\n\n\n\n for abs in 0..ABS_MAX {\n\n // Create a new one, zero-ed out every time to avoid carry-overs.\n\n let mut abs_info = evdev_abs_info::new();\n\n let ret = unsafe {\n\n // Safe because the kernel won't write more than size of evdev_buffer and we check the\n\n // return value\n\n ioctl_with_mut_ref(\n\n &Descriptor(descriptor.as_raw_descriptor()),\n\n EVIOCGABS(abs as c_uint),\n\n &mut abs_info,\n\n )\n\n };\n\n if ret == 0 {\n\n map.insert(abs, virtio_input_absinfo::from(abs_info));\n\n }\n\n }\n\n map\n\n}\n\n\n", "file_path": "devices/src/virtio/input/evdev.rs", "rank": 67, "score": 259479.72197506583 }, { "content": "/// Set alias pid for use with a DuplicateHandleTube.\n\npub fn set_alias_pid(alias_pid: u32) {\n\n ALIAS_PID.lock().replace(alias_pid);\n\n}\n\n\n\nimpl Tube {\n\n /// Create a pair of connected tubes. Request is sent in one direction while response is\n\n /// received in the other direction.\n\n /// The result is in the form (server, client).\n\n pub fn pair() -> Result<(Tube, Tube)> {\n\n let (socket1, socket2) = StreamChannel::pair(BlockingMode::Blocking, FramingMode::Message)\n\n .map_err(|e| Error::Pair(io::Error::from_raw_os_error(e.errno())))?;\n\n\n\n Ok((Tube::new(socket1), Tube::new(socket2)))\n\n }\n\n\n\n /// Create a pair of connected tubes with the specified buffer size.\n\n /// Request is sent in one direction while response is received in the other direction.\n\n /// The result is in the form (server, client).\n\n pub fn pair_with_buffer_size(buffer_size: usize) -> Result<(Tube, Tube)> {\n\n let (socket1, socket2) = StreamChannel::pair_with_buffer_size(\n", "file_path": "base/src/sys/windows/tube.rs", "rank": 68, "score": 259322.8694281169 }, { "content": "/// Automatically build the hypervisor Segment struct for set_sregs from the kernel bit fields.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `entry` - The gdt entry.\n\n/// * `table_index` - Index of the entry in the gdt table.\n\npub fn segment_from_gdt(entry: u64, table_index: u8) -> Segment {\n\n Segment {\n\n base: get_base(entry),\n\n limit: get_limit(entry),\n\n selector: (table_index * 8) as u16,\n\n type_: get_type(entry),\n\n present: get_p(entry),\n\n dpl: get_dpl(entry),\n\n db: get_db(entry),\n\n s: get_s(entry),\n\n l: get_l(entry),\n\n g: get_g(entry),\n\n avl: get_avl(entry),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n", "file_path": "x86_64/src/gdt.rs", "rank": 69, "score": 259258.9335583897 }, { "content": "// Converts the input bytes to an output string in the format \"0x01,0x02,0x03...\".\n\nfn format_as_hex(data: &[u8]) -> String {\n\n let mut out = String::new();\n\n for (i, d) in data.iter().enumerate() {\n\n out.push_str(&format!(\"0x{:02x}\", d));\n\n if i < data.len() - 1 {\n\n out.push(',')\n\n }\n\n }\n\n out\n\n}\n\n\n", "file_path": "tests/plugins.rs", "rank": 70, "score": 257704.6381204301 }, { "content": "/// Test-only function used to create a pipe that is full. The pipe is created, has its size set to\n\n/// the minimum and then has that much data written to it. Use `new_pipe_full` to test handling of\n\n/// blocking `write` calls in unit tests.\n\npub fn new_pipe_full() -> Result<(File, File)> {\n\n use std::io::Write;\n\n\n\n let (rx, mut tx) = pipe(true)?;\n\n // The smallest allowed size of a pipe is the system page size on linux.\n\n let page_size = set_pipe_size(tx.as_raw_fd(), round_up_to_page_size(1))?;\n\n\n\n // Fill the pipe with page_size zeros so the next write call will block.\n\n let buf = vec![0u8; page_size];\n\n tx.write_all(&buf)?;\n\n\n\n Ok((rx, tx))\n\n}\n\n\n\n/// Used to attempt to clean up a named pipe after it is no longer used.\n\npub struct UnlinkUnixDatagram(pub UnixDatagram);\n\nimpl AsRef<UnixDatagram> for UnlinkUnixDatagram {\n\n fn as_ref(&self) -> &UnixDatagram {\n\n &self.0\n\n }\n", "file_path": "base/src/sys/unix/mod.rs", "rank": 71, "score": 256459.43750891183 }, { "content": "pub fn serialize_and_send<T: Serialize, F: Fn(&[u8]) -> io::Result<usize>>(\n\n write_fn: F,\n\n msg: &T,\n\n target_pid: Option<u32>,\n\n) -> Result<()> {\n\n let msg_serialize = SerializeDescriptors::new(&msg);\n\n let msg_json = serde_json::to_vec(&msg_serialize).map_err(Error::Json)?;\n\n let msg_descriptors = msg_serialize.into_descriptors();\n\n\n\n let mut duped_descriptors = Vec::with_capacity(msg_descriptors.len());\n\n for desc in msg_descriptors {\n\n // Safe because these handles are guaranteed to be valid. Details:\n\n // 1. They come from base::descriptor_reflection::with_as_descriptor.\n\n // 2. with_as_descriptor is intended to be applied to owned descriptor types (e.g. File,\n\n // SafeDescriptor).\n\n // 3. The owning object is borrowed by msg until sending is complete.\n\n duped_descriptors.push(duplicate_handle(desc, target_pid)? as usize)\n\n }\n\n\n\n let descriptor_json = if duped_descriptors.is_empty() {\n", "file_path": "base/src/sys/windows/tube.rs", "rank": 72, "score": 255852.12697648478 }, { "content": "fn parse_userspace_msr_options(value: &str) -> argument::Result<(u32, MsrConfig)> {\n\n let mut msr_config = MsrConfig::new();\n\n\n\n let mut options = argument::parse_key_value_options(\"userspace-msr\", value, ',');\n\n let index: u32 = options\n\n .next()\n\n .ok_or(argument::Error::ExpectedValue(String::from(\n\n \"userspace-msr: expected index\",\n\n )))?\n\n .key_numeric()?;\n\n\n\n for opt in options {\n\n match opt.key() {\n\n \"type\" => match opt.value()? {\n\n \"r\" => msr_config.rw_type.read_allow = true,\n\n \"w\" => msr_config.rw_type.write_allow = true,\n\n \"rw\" | \"wr\" => {\n\n msr_config.rw_type.read_allow = true;\n\n msr_config.rw_type.write_allow = true;\n\n }\n", "file_path": "src/main.rs", "rank": 73, "score": 255622.576949444 }, { "content": "fn write_to_file(buf: &[u8], len: usize, state: &mut State) {\n\n if let Some(file) = state.file.as_mut() {\n\n let _ = file.write_all(&buf[..len]);\n\n }\n\n if state.stderr {\n\n let _ = stderr().write_all(&buf[..len]);\n\n }\n\n}\n\nimpl log::Log for InternalSyslog {\n\n fn enabled(&self, metadata: &log::Metadata) -> bool {\n\n log_enabled(metadata.level().into(), None)\n\n }\n\n\n\n fn log(&self, record: &log::Record) {\n\n log(\n\n record.level().into(),\n\n Facility::User,\n\n match (record.file(), record.line()) {\n\n (Some(f), Some(l)) => Some((f, l)),\n\n _ => None,\n", "file_path": "base/src/syslog.rs", "rank": 74, "score": 255149.94438902556 }, { "content": "fn parse_cpu_capacity(s: &str, cpu_capacity: &mut BTreeMap<usize, u32>) -> argument::Result<()> {\n\n for cpu_pair in s.split(',') {\n\n let assignment: Vec<&str> = cpu_pair.split('=').collect();\n\n if assignment.len() != 2 {\n\n return Err(argument::Error::InvalidValue {\n\n value: cpu_pair.to_owned(),\n\n expected: String::from(\"invalid CPU capacity syntax\"),\n\n });\n\n }\n\n let cpu = assignment[0]\n\n .parse()\n\n .map_err(|_| argument::Error::InvalidValue {\n\n value: assignment[0].to_owned(),\n\n expected: String::from(\"CPU index must be a non-negative integer\"),\n\n })?;\n\n let capacity = assignment[1]\n\n .parse()\n\n .map_err(|_| argument::Error::InvalidValue {\n\n value: assignment[1].to_owned(),\n\n expected: String::from(\"CPU capacity must be a non-negative integer\"),\n", "file_path": "src/main.rs", "rank": 76, "score": 253320.78168195963 }, { "content": "/// Records a log message with the given details.\n\n///\n\n/// Note that this will fail silently if syslog was not initialized.\n\n///\n\n/// # Arguments\n\n/// * `pri` - The `Priority` (i.e. severity) of the log message.\n\n/// * `fac` - The `Facility` of the log message. Usually `Facility::User` should be used.\n\n/// * `file_line` - Optional tuple of the name of the file that generated the\n\n/// log and the line number within that file.\n\n/// * `args` - The log's message to record, in the form of `format_args!()` return value\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// # use base::syslog;\n\n/// # if let Err(e) = syslog::init() {\n\n/// # println!(\"failed to initiailize syslog: {}\", e);\n\n/// # return;\n\n/// # }\n\n/// syslog::log(syslog::Priority::Error,\n\n/// syslog::Facility::User,\n\n/// Some((file!(), line!())),\n\n/// &format_args!(\"hello syslog\"));\n\n/// ```\n\npub fn log(pri: Priority, fac: Facility, file_line: Option<(&str, u32)>, args: &fmt::Arguments) {\n\n if !log_enabled(pri, file_line.map(|(f, _)| f)) {\n\n return;\n\n }\n\n\n\n let mut state = syslog_lock!();\n\n let mut buf = [0u8; 2048];\n\n\n\n state.syslog.log(\n\n state.proc_name.as_ref().map(|s| s.as_ref()),\n\n pri,\n\n fac,\n\n file_line,\n\n args,\n\n );\n\n\n\n let res = {\n\n let mut buf_cursor = Cursor::new(&mut buf[..]);\n\n if cfg!(windows) {\n\n let now = chrono::Local::now()\n", "file_path": "base/src/syslog.rs", "rank": 77, "score": 253281.61917840297 }, { "content": "/// Gets the properties of an event device (see EVIOCGPROP ioctl for details).\n\npub fn properties<T: AsRawDescriptor>(descriptor: &T) -> Result<virtio_input_bitmap> {\n\n let mut props = evdev_buffer::new();\n\n let len = unsafe {\n\n // Safe because the kernel won't write more than size of evdev_buffer and we check the\n\n // return value\n\n ioctl_with_mut_ref(\n\n &Descriptor(descriptor.as_raw_descriptor()),\n\n EVIOCGPROP(),\n\n &mut props,\n\n )\n\n };\n\n if len < 0 {\n\n return Err(InputError::EvdevPropertiesError(errno()));\n\n }\n\n Ok(virtio_input_bitmap::new(props.buffer))\n\n}\n\n\n", "file_path": "devices/src/virtio/input/evdev.rs", "rank": 78, "score": 252779.05190649122 }, { "content": "/// Write a protective MBR for a disk of the given total size (in bytes).\n\n///\n\n/// This should be written at the start of the disk, before the GPT header. It is one `SECTOR_SIZE`\n\n/// long.\n\npub fn write_protective_mbr(file: &mut impl Write, disk_size: u64) -> Result<(), Error> {\n\n // Bootstrap code\n\n file.write_all(&[0; 446]).map_err(Error::WritingData)?;\n\n\n\n // Partition status\n\n file.write_all(&[0x00]).map_err(Error::WritingData)?;\n\n // Begin CHS\n\n file.write_all(&[0; 3]).map_err(Error::WritingData)?;\n\n // Partition type\n\n file.write_all(&[0xEE]).map_err(Error::WritingData)?;\n\n // End CHS\n\n file.write_all(&[0; 3]).map_err(Error::WritingData)?;\n\n let first_lba: u32 = 1;\n\n file.write_all(&first_lba.to_le_bytes())\n\n .map_err(Error::WritingData)?;\n\n let number_of_sectors: u32 = (disk_size / SECTOR_SIZE)\n\n .try_into()\n\n .map_err(Error::InvalidDiskSize)?;\n\n file.write_all(&number_of_sectors.to_le_bytes())\n\n .map_err(Error::WritingData)?;\n", "file_path": "disk/src/gpt.rs", "rank": 79, "score": 252361.77290086675 }, { "content": "// Joins `path` to `buf`. If `path` is '..', removes the last component from `buf`\n\n// only if `buf` != `root` but does nothing if `buf` == `root`. Pushes `path` onto\n\n// `buf` if it is a normal path component.\n\n//\n\n// Returns an error if `path` is absolute, has more than one component, or contains\n\n// a '.' component.\n\nfn join_path<P: AsRef<Path>, R: AsRef<Path>>(\n\n mut buf: PathBuf,\n\n path: P,\n\n root: R,\n\n) -> io::Result<PathBuf> {\n\n let path = path.as_ref();\n\n let root = root.as_ref();\n\n debug_assert!(buf.starts_with(root));\n\n\n\n if path.components().count() > 1 {\n\n return Err(io::Error::from_raw_os_error(libc::EINVAL));\n\n }\n\n\n\n for component in path.components() {\n\n match component {\n\n // Prefix should only appear on windows systems.\n\n Component::Prefix(_) => return Err(io::Error::from_raw_os_error(libc::EINVAL)),\n\n // Absolute paths are not allowed.\n\n Component::RootDir => return Err(io::Error::from_raw_os_error(libc::EINVAL)),\n\n // '.' elements are not allowed.\n", "file_path": "common/p9/src/server/tests.rs", "rank": 80, "score": 250345.4467802683 }, { "content": "// Advance the internal cursor of the slices.\n\n// This is same with a nightly API `IoSliceMut::advance_slices` but for `&mut [u8]`.\n\nfn advance_slices_mut(bufs: &mut &mut [&mut [u8]], mut count: usize) {\n\n use std::mem::take;\n\n\n\n let mut idx = 0;\n\n for b in bufs.iter() {\n\n if count < b.len() {\n\n break;\n\n }\n\n count -= b.len();\n\n idx += 1;\n\n }\n\n *bufs = &mut take(bufs)[idx..];\n\n if !bufs.is_empty() {\n\n let slice = take(&mut bufs[0]);\n\n let (_, remaining) = slice.split_at_mut(count);\n\n bufs[0] = remaining;\n\n }\n\n}\n\n\n", "file_path": "third_party/vmm_vhost/src/connection.rs", "rank": 81, "score": 250343.5321777045 }, { "content": "pub fn create_vinput_device(cfg: &Config, dev_path: &Path) -> DeviceResult {\n\n let dev_file = OpenOptions::new()\n\n .read(true)\n\n .write(true)\n\n .open(dev_path)\n\n .with_context(|| format!(\"failed to open vinput device {}\", dev_path.display()))?;\n\n\n\n let dev = virtio::new_evdev(dev_file, virtio::base_features(cfg.protected_vm))\n\n .context(\"failed to set up input device\")?;\n\n\n\n Ok(VirtioDeviceStub {\n\n dev: Box::new(dev),\n\n jail: simple_jail(&cfg.jail_config, \"input_device\")?,\n\n })\n\n}\n\n\n", "file_path": "src/linux/device_helpers.rs", "rank": 82, "score": 250139.8435085437 }, { "content": "fn get_target_path() -> PathBuf {\n\n current_exe()\n\n .ok()\n\n .map(|mut path| {\n\n path.pop();\n\n path\n\n })\n\n .expect(\"failed to get crosvm binary directory\")\n\n}\n\n\n", "file_path": "tests/plugins.rs", "rank": 83, "score": 250055.24243742044 }, { "content": "// Searches for the given protocol in both the system wide and bundles protocols path.\n\nfn find_protocol(name: &str) -> PathBuf {\n\n let protocols_path = pkg_config::get_variable(\"wayland-protocols\", \"pkgdatadir\")\n\n .unwrap_or_else(|_| \"/usr/share/wayland-protocols\".to_owned());\n\n let protocol_file_name = PathBuf::from(format!(\"{}.xml\", name));\n\n\n\n // Prioritize the systems wayland protocols before using the bundled ones.\n\n if let Some(found) = scan_path(protocols_path, &protocol_file_name) {\n\n return found;\n\n }\n\n\n\n // Use bundled protocols as a fallback.\n\n let protocol_path = Path::new(\"protocol\").join(protocol_file_name);\n\n assert!(\n\n protocol_path.is_file(),\n\n \"unable to locate wayland protocol specification for `{}`\",\n\n name\n\n );\n\n protocol_path\n\n}\n\n\n", "file_path": "gpu_display/build.rs", "rank": 84, "score": 248357.8330316136 }, { "content": "// Like `CStr::from_bytes_with_nul` but strips any bytes starting from first '\\0'-byte and\n\n// returns &str. Panics if `b` doesn't contain any '\\0' bytes.\n\nfn strip_padding(b: &[u8]) -> &str {\n\n // It would be nice if we could use memchr here but that's locked behind an unstable gate.\n\n let pos = b\n\n .iter()\n\n .position(|&c| c == 0)\n\n .expect(\"`b` doesn't contain any nul bytes\");\n\n\n\n str::from_utf8(&b[..pos]).unwrap()\n\n}\n\n\n\npub struct NetlinkGenericRead {\n\n allocation: LayoutAllocation,\n\n len: usize,\n\n}\n\n\n\nimpl NetlinkGenericRead {\n\n pub fn iter(&self) -> NetlinkMessageIter {\n\n // Safe because the data in allocation was initialized up to `self.len` by `recv()` and is\n\n // sufficiently aligned.\n\n let data = unsafe { &self.allocation.as_slice(self.len) };\n", "file_path": "base/src/sys/unix/netlink.rs", "rank": 85, "score": 248228.9633773995 }, { "content": "/// Wrapper for `setsid(2)`.\n\npub fn setsid() -> Result<Pid> {\n\n // Safe because the return code is checked.\n\n syscall!(unsafe { libc::setsid() as Pid })\n\n}\n\n\n\n/// Safe wrapper for `geteuid(2)`.\n", "file_path": "base/src/sys/unix/mod.rs", "rank": 86, "score": 247103.67723615514 }, { "content": "pub fn tframe_decode(bytes: &[u8]) {\n\n let mut cursor = Cursor::new(bytes);\n\n\n\n while Tframe::decode(&mut cursor).is_ok() {}\n\n}\n", "file_path": "common/p9/src/fuzzing.rs", "rank": 87, "score": 246924.40883678818 }, { "content": "// Advance the internal cursor of the slices.\n\n// This is same with a nightly API `IoSlice::advance_slices` but for `&[u8]`.\n\nfn advance_slices(bufs: &mut &mut [&[u8]], mut count: usize) {\n\n use std::mem::take;\n\n\n\n let mut idx = 0;\n\n for b in bufs.iter() {\n\n if count < b.len() {\n\n break;\n\n }\n\n count -= b.len();\n\n idx += 1;\n\n }\n\n *bufs = &mut take(bufs)[idx..];\n\n if !bufs.is_empty() {\n\n bufs[0] = &bufs[0][count..];\n\n }\n\n}\n\n\n", "file_path": "third_party/vmm_vhost/src/connection.rs", "rank": 88, "score": 246101.97538929642 }, { "content": "/// Takes assembly source code and returns the resulting assembly code.\n\nfn build_assembly(src: &str) -> Vec<u8> {\n\n // Creates a file with the assembly source code in it.\n\n let mut in_file = tempfile().expect(\"failed to create tempfile\");\n\n keep_fd_on_exec(&in_file);\n\n in_file.write_all(src.as_bytes()).unwrap();\n\n\n\n // Creates a file that will hold the nasm output.\n\n let mut out_file = tempfile().expect(\"failed to create tempfile\");\n\n keep_fd_on_exec(&out_file);\n\n\n\n // Runs nasm with the input and output files set to the FDs of the above shared memory regions,\n\n // which we have preserved accross exec.\n\n let status = Command::new(\"nasm\")\n\n .arg(format!(\"/proc/self/fd/{}\", in_file.as_raw_descriptor()))\n\n .args(&[\"-f\", \"bin\", \"-o\"])\n\n .arg(format!(\"/proc/self/fd/{}\", out_file.as_raw_descriptor()))\n\n .status()\n\n .expect(\"failed to spawn assembler\");\n\n assert!(status.success());\n\n\n\n let mut out_bytes = Vec::new();\n\n out_file.read_to_end(&mut out_bytes).unwrap();\n\n out_bytes\n\n}\n\n\n", "file_path": "tests/plugins.rs", "rank": 89, "score": 245139.73213027683 }, { "content": "fn compile_protocol<P: AsRef<Path>>(name: &str, out: P) -> PathBuf {\n\n let in_protocol = find_protocol(name);\n\n println!(\"cargo:rerun-if-changed={}\", in_protocol.display());\n\n let out_code = out.as_ref().join(format!(\"{}.c\", name));\n\n let out_header = out.as_ref().join(format!(\"{}.h\", name));\n\n eprintln!(\"building protocol: {}\", name);\n\n Command::new(\"wayland-scanner\")\n\n .arg(\"code\")\n\n .arg(&in_protocol)\n\n .arg(&out_code)\n\n .output()\n\n .expect(\"wayland-scanner code failed\");\n\n Command::new(\"wayland-scanner\")\n\n .arg(\"client-header\")\n\n .arg(&in_protocol)\n\n .arg(&out_header)\n\n .output()\n\n .expect(\"wayland-scanner client-header failed\");\n\n out_code\n\n}\n\n\n", "file_path": "gpu_display/build.rs", "rank": 90, "score": 244880.76831370062 }, { "content": "/// Helper function to wrap up a closure with fail handle. The fail handle will be triggered if the\n\n/// closure returns an error.\n\npub fn fallible_closure<E: std::fmt::Display, C: FnMut() -> Result<(), E> + 'static + Send>(\n\n fail_handle: Arc<dyn FailHandle>,\n\n mut callback: C,\n\n) -> impl FnMut() + 'static + Send {\n\n move || match callback() {\n\n Ok(()) => {}\n\n Err(e) => {\n\n error!(\"callback failed {}\", e);\n\n fail_handle.fail();\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::sync::{Arc, Mutex};\n\n\n\n fn task(_: RingBufferStopCallback) {}\n\n\n", "file_path": "devices/src/usb/xhci/ring_buffer_stop_cb.rs", "rank": 91, "score": 244834.91811499398 }, { "content": "/// Adds a new per-path log level filter.\n\npub fn add_path_log_level<T: Into<PriorityFilter>>(path_prefix: &str, log_level: T) {\n\n // Insert filter so that path_log_levels is always sorted with longer prefixes first\n\n let mut state = syslog_lock!();\n\n let index = state\n\n .path_log_levels\n\n .binary_search_by_key(&path_prefix.len(), |p| {\n\n std::usize::MAX - p.path_prefix.as_os_str().len()\n\n })\n\n .unwrap_or_else(|e| e);\n\n state.path_log_levels.insert(\n\n index,\n\n PathFilter {\n\n path_prefix: PathBuf::from(path_prefix),\n\n level: log_level.into(),\n\n },\n\n );\n\n}\n\n\n", "file_path": "base/src/syslog.rs", "rank": 92, "score": 244416.76843473365 }, { "content": "// Like `CStr::from_bytes_with_nul` but strips any bytes starting from first '\\0'-byte and\n\n// returns &str. Panics if `b` doesn't contain any '\\0' bytes.\n\nfn strip_padding(b: &[u8]) -> &str {\n\n // It would be nice if we could use memchr here but that's locked behind an unstable gate.\n\n let pos = b\n\n .iter()\n\n .position(|&c| c == 0)\n\n .expect(\"`b` doesn't contain any nul bytes\");\n\n\n\n str::from_utf8(&b[..pos]).unwrap()\n\n}\n", "file_path": "base/src/sys/unix/acpi_event.rs", "rank": 93, "score": 243971.92553985948 }, { "content": "/// Reaps a child process that has terminated.\n\n///\n\n/// Returns `Ok(pid)` where `pid` is the process that was reaped or `Ok(0)` if none of the children\n\n/// have terminated. An `Error` is with `errno == ECHILD` if there are no children left to reap.\n\n///\n\n/// # Examples\n\n///\n\n/// Reaps all child processes until there are no terminated children to reap.\n\n///\n\n/// ```\n\n/// fn reap_children() {\n\n/// loop {\n\n/// match base::platform::reap_child() {\n\n/// Ok(0) => println!(\"no children ready to reap\"),\n\n/// Ok(pid) => {\n\n/// println!(\"reaped {}\", pid);\n\n/// continue\n\n/// },\n\n/// Err(e) if e.errno() == libc::ECHILD => println!(\"no children left\"),\n\n/// Err(e) => println!(\"error reaping children: {}\", e),\n\n/// }\n\n/// break\n\n/// }\n\n/// }\n\n/// ```\n\npub fn reap_child() -> Result<Pid> {\n\n // Safe because we pass in no memory, prevent blocking with WNOHANG, and check for error.\n\n let ret = unsafe { waitpid(-1, ptr::null_mut(), WNOHANG) };\n\n if ret == -1 {\n\n errno_result()\n\n } else {\n\n Ok(ret)\n\n }\n\n}\n\n\n", "file_path": "base/src/sys/unix/mod.rs", "rank": 94, "score": 242878.5847299343 }, { "content": "/// Takes the thread local storage for descriptor serialization. Fails if there wasn't a prior call\n\n/// to `init_descriptor_dst` on this thread.\n\nfn take_descriptor_dst() -> Result<Vec<RawDescriptor>, &'static str> {\n\n match DESCRIPTOR_DST.with(|d| d.replace(None)) {\n\n Some(d) => Ok(d),\n\n None => Err(\"attempt to take descriptor destination before it was initialized\"),\n\n }\n\n}\n\n\n", "file_path": "base/src/descriptor_reflection.rs", "rank": 95, "score": 242864.6942444414 }, { "content": "/// Trait describing USB descriptors.\n\npub trait Descriptor {\n\n /// Get the expected bDescriptorType value for this type of descriptor.\n\n fn descriptor_type() -> DescriptorType;\n\n}\n\n\n\n/// Standard USB descriptor header common to all descriptor types.\n\n#[allow(non_snake_case)]\n\n#[derive(Copy, Clone, Debug, Default)]\n\n#[repr(C, packed)]\n\npub struct DescriptorHeader {\n\n pub bLength: u8,\n\n pub bDescriptorType: u8,\n\n}\n\n\n\n// Safe because it only has data and has no implicit padding.\n\nunsafe impl DataInit for DescriptorHeader {}\n\n\n", "file_path": "usb_util/src/types.rs", "rank": 96, "score": 241867.81829218002 }, { "content": "// Reads the next u32 from the file.\n\nfn read_u32_from_file(mut f: &File) -> Result<u32> {\n\n let mut value = [0u8; 4];\n\n (&mut f)\n\n .read_exact(&mut value)\n\n .map_err(Error::ReadingHeader)?;\n\n Ok(u32::from_be_bytes(value))\n\n}\n\n\n", "file_path": "disk/src/qcow/mod.rs", "rank": 97, "score": 241588.42398381216 }, { "content": "// Reads the next u64 from the file.\n\nfn read_u64_from_file(mut f: &File) -> Result<u64> {\n\n let mut value = [0u8; 8];\n\n (&mut f)\n\n .read_exact(&mut value)\n\n .map_err(Error::ReadingHeader)?;\n\n Ok(u64::from_be_bytes(value))\n\n}\n\n\n\nimpl QcowHeader {\n\n /// Creates a QcowHeader from a reference to a file.\n\n pub fn new(f: &mut File) -> Result<QcowHeader> {\n\n f.seek(SeekFrom::Start(0)).map_err(Error::ReadingHeader)?;\n\n\n\n let magic = read_u32_from_file(f)?;\n\n if magic != QCOW_MAGIC {\n\n return Err(Error::InvalidMagic);\n\n }\n\n\n\n let mut header = QcowHeader {\n\n magic,\n", "file_path": "disk/src/qcow/mod.rs", "rank": 98, "score": 241588.42398381216 }, { "content": "fn get_thread_file(descriptors: Vec<Descriptor>) -> ManuallyDrop<File> {\n\n // Safe because all callers must exit *before* these handles will be closed (guaranteed by\n\n // HandleSource's Drop impl.).\n\n unsafe {\n\n ManuallyDrop::new(File::from_raw_descriptor(\n\n descriptors[GetCurrentThreadId() as usize % descriptors.len()].0,\n\n ))\n\n }\n\n}\n\n\n\n#[async_trait(?Send)]\n\nimpl<F: AsRawDescriptor> ReadAsync for HandleSource<F> {\n\n /// Reads from the iosource at `file_offset` and fill the given `vec`.\n\n async fn read_to_vec<'a>(\n\n &'a self,\n\n file_offset: Option<u64>,\n\n mut vec: Vec<u8>,\n\n ) -> AsyncResult<(usize, Vec<u8>)> {\n\n let handles = HandleWrapper::new(self.as_descriptors());\n\n let descriptors = self.source_descriptors.clone();\n", "file_path": "cros_async/src/sys/windows/handle_source.rs", "rank": 99, "score": 241084.33884374774 } ]
Rust
glib/src/wrapper.rs
abdulrehman-git/gtk-rs
068311ececbb9d84e3697412e789add054f33f83
#[macro_export] macro_rules! glib_wrapper { ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, } ) => { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, get_type => || $get_type_expr:expr, } ) => { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr, @get_type $get_type_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, init => |$init_arg:ident| $init_expr:expr, clear => |$clear_arg:ident| $clear_expr:expr, } ) => { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr, @init $init_arg $init_expr, @clear $clear_arg $clear_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, init => |$init_arg:ident| $init_expr:expr, clear => |$clear_arg:ident| $clear_expr:expr, get_type => || $get_type_expr:expr, } ) => { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr, @init $init_arg $init_expr, @clear $clear_arg $clear_expr, @get_type $get_type_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Shared<$ffi_name:ty>); match fn { ref => |$ref_arg:ident| $ref_expr:expr, unref => |$unref_arg:ident| $unref_expr:expr, } ) => { $crate::glib_shared_wrapper!([$($attr)*] $name, $ffi_name, @ref $ref_arg $ref_expr, @unref $unref_arg $unref_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Shared<$ffi_name:ty>); match fn { ref => |$ref_arg:ident| $ref_expr:expr, unref => |$unref_arg:ident| $unref_expr:expr, get_type => || $get_type_expr:expr, } ) => { $crate::glib_shared_wrapper!([$($attr)*] $name, $ffi_name, @ref $ref_arg $ref_expr, @unref $unref_arg $unref_expr, @get_type $get_type_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>); match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, ::std::os::raw::c_void, @get_type $get_type_expr, @extends [], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty, $ffi_class_name:ty>); match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr, @extends [], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>) @extends $($extends:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, ::std::os::raw::c_void, @get_type $get_type_expr, @extends [$($extends),+], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty, $ffi_class_name:ty>) @extends $($extends:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr, @extends [$($extends),+], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>) @implements $($implements:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, ::std::os::raw::c_void, @get_type $get_type_expr, @extends [], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty, $ffi_class_name:ty>) @implements $($implements:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr, @extends [], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>) @extends $($extends:path),+, @implements $($implements:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, ::std::os::raw::c_void, @get_type $get_type_expr, @extends [$($extends),+], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty, $ffi_class_name:ty>) @extends $($extends:path),+, @implements $($implements:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr, @extends [$($extends),+], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(ObjectSubclass<$subclass:ty>); ) => { use glib::translate::ToGlib; $crate::glib_object_wrapper!(@object [$($attr)*] $name, <$subclass as $crate::subclass::types::ObjectSubclass>::Instance, <$subclass as $crate::subclass::types::ObjectSubclass>::Class, @get_type $crate::translate::ToGlib::to_glib(&<$subclass as $crate::subclass::types::ObjectSubclass>::get_type()), @extends [], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(ObjectSubclass<$subclass:ty>) @implements $($implements:path),+; ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, <$subclass as $crate::subclass::types::ObjectSubclass>::Instance, <$subclass as $crate::subclass::types::ObjectSubclass>::Class, @get_type $crate::translate::ToGlib::to_glib(&<$subclass as $crate::subclass::types::ObjectSubclass>::get_type()), @extends [], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(ObjectSubclass<$subclass:ty>) @extends $($extends:path),+; ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, <$subclass as $crate::subclass::types::ObjectSubclass>::Instance, <$subclass as $crate::subclass::types::ObjectSubclass>::Class, @get_type $crate::translate::ToGlib::to_glib(&<$subclass as $crate::subclass::types::ObjectSubclass>::get_type()), @extends [$($extends),+], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(ObjectSubclass<$subclass:ty>) @extends $($extends:path),+, @implements $($implements:path),+; ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, <$subclass as $crate::subclass::types::ObjectSubclass>::Instance, <$subclass as $crate::subclass::types::ObjectSubclass>::Class, @get_type $crate::translate::ToGlib::to_glib(&<$subclass as $crate::subclass::types::ObjectSubclass>::get_type()), @extends [$($extends),+], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Interface<$ffi_name:ty>); match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@interface [$($attr)*] $name, $ffi_name, @get_type $get_type_expr, @requires []); }; ( $(#[$attr:meta])* pub struct $name:ident(Interface<$ffi_name:ty>) @requires $($requires:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@interface [$($attr)*] $name, $ffi_name, @get_type $get_type_expr, @requires [$($requires),+]); }; }
#[macro_export] macro_rules! glib_wrapper { ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, } ) => { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, get_type => || $get_type_expr:expr, } )
name, $ffi_class_name, @get_type $get_type_expr, @extends [], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>) @extends $($extends:path),+, @implements $($implements:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, ::std::os::raw::c_void, @get_type $get_type_expr, @extends [$($extends),+], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty, $ffi_class_name:ty>) @extends $($extends:path),+, @implements $($implements:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr, @extends [$($extends),+], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(ObjectSubclass<$subclass:ty>); ) => { use glib::translate::ToGlib; $crate::glib_object_wrapper!(@object [$($attr)*] $name, <$subclass as $crate::subclass::types::ObjectSubclass>::Instance, <$subclass as $crate::subclass::types::ObjectSubclass>::Class, @get_type $crate::translate::ToGlib::to_glib(&<$subclass as $crate::subclass::types::ObjectSubclass>::get_type()), @extends [], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(ObjectSubclass<$subclass:ty>) @implements $($implements:path),+; ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, <$subclass as $crate::subclass::types::ObjectSubclass>::Instance, <$subclass as $crate::subclass::types::ObjectSubclass>::Class, @get_type $crate::translate::ToGlib::to_glib(&<$subclass as $crate::subclass::types::ObjectSubclass>::get_type()), @extends [], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(ObjectSubclass<$subclass:ty>) @extends $($extends:path),+; ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, <$subclass as $crate::subclass::types::ObjectSubclass>::Instance, <$subclass as $crate::subclass::types::ObjectSubclass>::Class, @get_type $crate::translate::ToGlib::to_glib(&<$subclass as $crate::subclass::types::ObjectSubclass>::get_type()), @extends [$($extends),+], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(ObjectSubclass<$subclass:ty>) @extends $($extends:path),+, @implements $($implements:path),+; ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, <$subclass as $crate::subclass::types::ObjectSubclass>::Instance, <$subclass as $crate::subclass::types::ObjectSubclass>::Class, @get_type $crate::translate::ToGlib::to_glib(&<$subclass as $crate::subclass::types::ObjectSubclass>::get_type()), @extends [$($extends),+], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Interface<$ffi_name:ty>); match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@interface [$($attr)*] $name, $ffi_name, @get_type $get_type_expr, @requires []); }; ( $(#[$attr:meta])* pub struct $name:ident(Interface<$ffi_name:ty>) @requires $($requires:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@interface [$($attr)*] $name, $ffi_name, @get_type $get_type_expr, @requires [$($requires),+]); }; }
=> { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr, @get_type $get_type_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, init => |$init_arg:ident| $init_expr:expr, clear => |$clear_arg:ident| $clear_expr:expr, } ) => { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr, @init $init_arg $init_expr, @clear $clear_arg $clear_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, init => |$init_arg:ident| $init_expr:expr, clear => |$clear_arg:ident| $clear_expr:expr, get_type => || $get_type_expr:expr, } ) => { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr, @init $init_arg $init_expr, @clear $clear_arg $clear_expr, @get_type $get_type_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Shared<$ffi_name:ty>); match fn { ref => |$ref_arg:ident| $ref_expr:expr, unref => |$unref_arg:ident| $unref_expr:expr, } ) => { $crate::glib_shared_wrapper!([$($attr)*] $name, $ffi_name, @ref $ref_arg $ref_expr, @unref $unref_arg $unref_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Shared<$ffi_name:ty>); match fn { ref => |$ref_arg:ident| $ref_expr:expr, unref => |$unref_arg:ident| $unref_expr:expr, get_type => || $get_type_expr:expr, } ) => { $crate::glib_shared_wrapper!([$($attr)*] $name, $ffi_name, @ref $ref_arg $ref_expr, @unref $unref_arg $unref_expr, @get_type $get_type_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>); match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, ::std::os::raw::c_void, @get_type $get_type_expr, @extends [], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty, $ffi_class_name:ty>); match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr, @extends [], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>) @extends $($extends:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, ::std::os::raw::c_void, @get_type $get_type_expr, @extends [$($extends),+], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty, $ffi_class_name:ty>) @extends $($extends:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr, @extends [$($extends),+], @implements []); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>) @implements $($implements:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_name, ::std::os::raw::c_void, @get_type $get_type_expr, @extends [], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty, $ffi_class_name:ty>) @implements $($implements:path),+; match fn { get_type => || $get_type_expr:expr, } ) => { $crate::glib_object_wrapper!(@object [$($attr)*] $name, $ffi_
random
[ { "content": "/// Same as [`set_prgname()`].\n\n///\n\n/// [`set_prgname()`]: fn.set_prgname.html\n\npub fn set_program_name(name: Option<&str>) {\n\n set_prgname(name)\n\n}\n\n\n", "file_path": "glib/src/utils.rs", "rank": 0, "score": 251826.54139678564 }, { "content": "pub fn accelerator_name(\n\n accelerator_key: u32,\n\n accelerator_mods: gdk::ModifierType,\n\n) -> Option<GString> {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n from_glib_full(gtk_sys::gtk_accelerator_name(\n\n accelerator_key,\n\n accelerator_mods.to_glib(),\n\n ))\n\n }\n\n}\n\n\n", "file_path": "gtk/src/auto/functions.rs", "rank": 1, "score": 242186.56185636035 }, { "content": "pub fn set_prgname(name: Option<&str>) {\n\n unsafe { glib_sys::g_set_prgname(name.to_glib_none().0) }\n\n}\n\n\n", "file_path": "glib/src/utils.rs", "rank": 2, "score": 239886.26949783333 }, { "content": "pub fn accelerator_name_with_keycode(\n\n display: Option<&gdk::Display>,\n\n accelerator_key: u32,\n\n keycode: u32,\n\n accelerator_mods: gdk::ModifierType,\n\n) -> Option<GString> {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n from_glib_full(gtk_sys::gtk_accelerator_name_with_keycode(\n\n display.to_glib_none().0,\n\n accelerator_key,\n\n keycode,\n\n accelerator_mods.to_glib(),\n\n ))\n\n }\n\n}\n\n\n", "file_path": "gtk/src/auto/functions.rs", "rank": 3, "score": 237454.2157895685 }, { "content": "pub fn bus_own_name_on_connection<NameAcquired, NameLost>(\n\n connection: &DBusConnection,\n\n name: &str,\n\n flags: BusNameOwnerFlags,\n\n name_acquired: NameAcquired,\n\n name_lost: NameLost,\n\n) -> OwnerId\n\nwhere\n\n NameAcquired: Fn(DBusConnection, &str) + Send + Sync + 'static,\n\n NameLost: Fn(DBusConnection, &str) + Send + Sync + 'static,\n\n{\n\n unsafe {\n\n let id = gio_sys::g_bus_own_name_on_connection_with_closures(\n\n connection.to_glib_none().0,\n\n name.to_glib_none().0,\n\n flags.to_glib(),\n\n own_closure(name_acquired).to_glib_none().0,\n\n own_closure(name_lost).to_glib_none().0,\n\n );\n\n OwnerId(NonZeroU32::new_unchecked(id))\n\n }\n\n}\n\n\n", "file_path": "gio/src/dbus.rs", "rank": 4, "score": 233938.9012709654 }, { "content": "pub fn bus_watch_name<NameAppeared, NameVanished>(\n\n bus_type: BusType,\n\n name: &str,\n\n flags: BusNameWatcherFlags,\n\n name_appeared: NameAppeared,\n\n name_vanished: NameVanished,\n\n) -> WatcherId\n\nwhere\n\n NameAppeared: Fn(DBusConnection, &str, &str) + Send + Sync + 'static,\n\n NameVanished: Fn(DBusConnection, &str, &str) + Send + Sync + 'static,\n\n{\n\n unsafe {\n\n let id = gio_sys::g_bus_watch_name_with_closures(\n\n bus_type.to_glib(),\n\n name.to_glib_none().0,\n\n flags.to_glib(),\n\n watch_closure(name_appeared).to_glib_none().0,\n\n watch_closure(name_vanished).to_glib_none().0,\n\n );\n\n WatcherId(NonZeroU32::new_unchecked(id))\n\n }\n\n}\n\n\n", "file_path": "gio/src/dbus.rs", "rank": 5, "score": 233938.9012709654 }, { "content": "pub fn bus_watch_name_on_connection<NameAppeared, NameVanished>(\n\n connection: &DBusConnection,\n\n name: &str,\n\n flags: BusNameWatcherFlags,\n\n name_appeared: NameAppeared,\n\n name_vanished: NameVanished,\n\n) -> WatcherId\n\nwhere\n\n NameAppeared: Fn(DBusConnection, &str, &str) + Send + Sync + 'static,\n\n NameVanished: Fn(DBusConnection, &str, &str) + Send + Sync + 'static,\n\n{\n\n unsafe {\n\n let id = gio_sys::g_bus_watch_name_on_connection_with_closures(\n\n connection.to_glib_none().0,\n\n name.to_glib_none().0,\n\n flags.to_glib(),\n\n watch_closure(name_appeared).to_glib_none().0,\n\n watch_closure(name_vanished).to_glib_none().0,\n\n );\n\n WatcherId(NonZeroU32::new_unchecked(id))\n\n }\n\n}\n\n\n", "file_path": "gio/src/dbus.rs", "rank": 6, "score": 230451.9687196501 }, { "content": "pub fn set_application_name(application_name: &str) {\n\n unsafe {\n\n glib_sys::g_set_application_name(application_name.to_glib_none().0);\n\n }\n\n}\n\n\n\n//pub fn set_error(domain: Quark, code: i32, format: &str, : /*Unknown conversion*//*Unimplemented*/Fundamental: VarArgs) -> Error {\n\n// unsafe { TODO: call glib_sys:g_set_error() }\n\n//}\n\n\n\n//pub fn set_print_handler<P: Fn(&str) + Send + Sync + 'static>(func: P) -> Fn(&str) + 'static {\n\n// unsafe { TODO: call glib_sys:g_set_print_handler() }\n\n//}\n\n\n\n//pub fn set_printerr_handler<P: Fn(&str) + Send + Sync + 'static>(func: P) -> Fn(&str) + 'static {\n\n// unsafe { TODO: call glib_sys:g_set_printerr_handler() }\n\n//}\n\n\n", "file_path": "glib/src/auto/functions.rs", "rank": 7, "score": 225843.57638961787 }, { "content": "pub fn bus_own_name<BusAcquired, NameAcquired, NameLost>(\n\n bus_type: BusType,\n\n name: &str,\n\n flags: BusNameOwnerFlags,\n\n bus_acquired: BusAcquired,\n\n name_acquired: NameAcquired,\n\n name_lost: NameLost,\n\n) -> OwnerId\n\nwhere\n\n BusAcquired: Fn(DBusConnection, &str) + Send + Sync + 'static,\n\n NameAcquired: Fn(DBusConnection, &str) + Send + Sync + 'static,\n\n NameLost: Fn(Option<DBusConnection>, &str) + Send + Sync + 'static,\n\n{\n\n unsafe {\n\n let id = gio_sys::g_bus_own_name_with_closures(\n\n bus_type.to_glib(),\n\n name.to_glib_none().0,\n\n flags.to_glib(),\n\n own_closure(bus_acquired).to_glib_none().0,\n\n own_closure(name_acquired).to_glib_none().0,\n", "file_path": "gio/src/dbus.rs", "rank": 8, "score": 224960.44316928275 }, { "content": "pub fn keyval_from_name(keyval_name: &str) -> u32 {\n\n assert_initialized_main_thread!();\n\n unsafe { gdk_sys::gdk_keyval_from_name(keyval_name.to_glib_none().0) }\n\n}\n\n\n", "file_path": "gdk/src/auto/functions.rs", "rank": 9, "score": 220352.05083925056 }, { "content": "pub fn get_host_name() -> GString {\n\n unsafe { from_glib_none(glib_sys::g_get_host_name()) }\n\n}\n\n\n", "file_path": "glib/src/auto/functions.rs", "rank": 10, "score": 220261.76207918482 }, { "content": "pub fn setting_get(name: &str) -> Option<glib::Value> {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n let mut value = glib::Value::uninitialized();\n\n let done: bool = from_glib(gdk_sys::gdk_setting_get(\n\n name.to_glib_none().0,\n\n value.to_glib_none_mut().0,\n\n ));\n\n if done == true {\n\n Some(value)\n\n } else {\n\n None\n\n }\n\n }\n\n}\n\n\n", "file_path": "gdk/src/functions.rs", "rank": 11, "score": 218906.26482219354 }, { "content": "/// Same as [`get_prgname()`].\n\n///\n\n/// [`get_prgname()`]: fn.get_prgname.html\n\npub fn get_program_name() -> Option<String> {\n\n get_prgname()\n\n}\n\n\n", "file_path": "glib/src/utils.rs", "rank": 12, "score": 217756.97966077374 }, { "content": "pub fn on_error_query(prg_name: &str) {\n\n unsafe {\n\n glib_sys::g_on_error_query(prg_name.to_glib_none().0);\n\n }\n\n}\n\n\n", "file_path": "glib/src/auto/functions.rs", "rank": 13, "score": 213515.88699584012 }, { "content": "pub fn get_real_name() -> Option<OsString> {\n\n #[cfg(not(all(windows, target_arch = \"x86\")))]\n\n use glib_sys::g_get_real_name;\n\n #[cfg(all(windows, target_arch = \"x86\"))]\n\n use glib_sys::g_get_real_name_utf8 as g_get_real_name;\n\n\n\n unsafe { from_glib_none(g_get_real_name()) }\n\n}\n\n\n", "file_path": "glib/src/utils.rs", "rank": 14, "score": 213515.88699584012 }, { "content": "pub fn get_user_name() -> Option<OsString> {\n\n #[cfg(not(all(windows, target_arch = \"x86\")))]\n\n use glib_sys::g_get_user_name;\n\n #[cfg(all(windows, target_arch = \"x86\"))]\n\n use glib_sys::g_get_user_name_utf8 as g_get_user_name;\n\n\n\n unsafe { from_glib_none(g_get_user_name()) }\n\n}\n\n\n", "file_path": "glib/src/utils.rs", "rank": 15, "score": 213515.88699584012 }, { "content": "pub fn get_application_name() -> Option<GString> {\n\n unsafe { from_glib_none(glib_sys::g_get_application_name()) }\n\n}\n\n\n", "file_path": "glib/src/auto/functions.rs", "rank": 16, "score": 209501.80284054173 }, { "content": "pub fn on_error_stack_trace(prg_name: &str) {\n\n unsafe {\n\n glib_sys::g_on_error_stack_trace(prg_name.to_glib_none().0);\n\n }\n\n}\n\n\n\n//pub fn parse_debug_string(string: Option<&str>, keys: /*Ignored*/&[&DebugKey]) -> u32 {\n\n// unsafe { TODO: call glib_sys:g_parse_debug_string() }\n\n//}\n\n\n", "file_path": "glib/src/auto/functions.rs", "rank": 17, "score": 209501.80284054173 }, { "content": "pub fn get_language_names() -> Vec<GString> {\n\n unsafe { FromGlibPtrContainer::from_glib_none(glib_sys::g_get_language_names()) }\n\n}\n\n\n", "file_path": "glib/src/auto/functions.rs", "rank": 18, "score": 209501.80284054173 }, { "content": "pub fn bus_unown_name(owner_id: OwnerId) {\n\n unsafe {\n\n gio_sys::g_bus_unown_name(owner_id.0.into());\n\n }\n\n}\n\n\n", "file_path": "gio/src/dbus.rs", "rank": 19, "score": 209501.80284054173 }, { "content": "pub fn bus_unwatch_name(watcher_id: WatcherId) {\n\n unsafe {\n\n gio_sys::g_bus_unwatch_name(watcher_id.0.into());\n\n }\n\n}\n", "file_path": "gio/src/dbus.rs", "rank": 20, "score": 209501.80284054173 }, { "content": "pub fn dbus_is_name(string: &str) -> bool {\n\n unsafe { from_glib(gio_sys::g_dbus_is_name(string.to_glib_none().0)) }\n\n}\n\n\n", "file_path": "gio/src/auto/functions.rs", "rank": 21, "score": 208024.3614454728 }, { "content": "pub fn get_display_arg_name() -> Option<GString> {\n\n assert_initialized_main_thread!();\n\n unsafe { from_glib_none(gdk_sys::gdk_get_display_arg_name()) }\n\n}\n\n\n", "file_path": "gdk/src/auto/functions.rs", "rank": 22, "score": 205691.08280549874 }, { "content": "pub fn x11_get_xatom_by_name(atom_name: &str) -> xlib::Atom {\n\n assert_initialized_main_thread!();\n\n unsafe { gdk_x11_sys::gdk_x11_get_xatom_by_name(atom_name.to_glib_none().0) }\n\n}\n\n\n", "file_path": "gdkx11/src/auto/functions.rs", "rank": 23, "score": 205277.85305722672 }, { "content": "pub fn dbus_is_interface_name(string: &str) -> bool {\n\n unsafe { from_glib(gio_sys::g_dbus_is_interface_name(string.to_glib_none().0)) }\n\n}\n\n\n", "file_path": "gio/src/auto/functions.rs", "rank": 24, "score": 204010.2772901744 }, { "content": "pub fn dbus_is_unique_name(string: &str) -> bool {\n\n unsafe { from_glib(gio_sys::g_dbus_is_unique_name(string.to_glib_none().0)) }\n\n}\n\n\n", "file_path": "gio/src/auto/functions.rs", "rank": 25, "score": 204010.2772901744 }, { "content": "pub fn dbus_is_member_name(string: &str) -> bool {\n\n unsafe { from_glib(gio_sys::g_dbus_is_member_name(string.to_glib_none().0)) }\n\n}\n\n\n", "file_path": "gio/src/auto/functions.rs", "rank": 26, "score": 204010.2772901744 }, { "content": "#[cfg(any(feature = \"v2_58\", feature = \"dox\"))]\n\npub fn get_language_names_with_category(category_name: &str) -> Vec<GString> {\n\n unsafe {\n\n FromGlibPtrContainer::from_glib_none(glib_sys::g_get_language_names_with_category(\n\n category_name.to_glib_none().0,\n\n ))\n\n }\n\n}\n\n\n", "file_path": "glib/src/auto/functions.rs", "rank": 27, "score": 202069.90906185555 }, { "content": "pub fn init() {\n\n assert_not_initialized!();\n\n unsafe {\n\n gdk_sys::gdk_init(ptr::null_mut(), ptr::null_mut());\n\n set_initialized();\n\n }\n\n}\n", "file_path": "gdk/src/rt.rs", "rank": 28, "score": 192969.71238158987 }, { "content": "// Parse attribute such as:\n\n// #[genum(type_name = \"TestAnimalType\")]\n\npub fn parse_type_name(input: &DeriveInput, attr_name: &str) -> Result<String> {\n\n let meta = match find_attribute_meta(&input.attrs, attr_name)? {\n\n Some(meta) => meta,\n\n _ => bail!(\"Missing '{}' attribute\", attr_name),\n\n };\n\n\n\n let meta = match find_nested_meta(&meta, \"type_name\") {\n\n Some(meta) => meta,\n\n _ => bail!(\"Missing meta 'type_name'\"),\n\n };\n\n\n\n match parse_enum_attribute(&meta)? {\n\n EnumAttribute::TypeName(n) => Ok(n),\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum ItemAttribute {\n\n Name(String),\n\n Nick(String),\n\n}\n\n\n", "file_path": "glib-macros/src/utils.rs", "rank": 29, "score": 191875.1187749608 }, { "content": "pub fn signal_stop_emission_by_name<T: ObjectType>(instance: &T, signal_name: &str) {\n\n unsafe {\n\n gobject_sys::g_signal_stop_emission_by_name(\n\n instance.as_object_ref().to_glib_none().0,\n\n signal_name.to_glib_none().0,\n\n );\n\n }\n\n}\n", "file_path": "glib/src/signal.rs", "rank": 30, "score": 191868.17043732363 }, { "content": "pub fn unsetenv<K: AsRef<OsStr>>(variable_name: K) {\n\n #[cfg(not(windows))]\n\n use glib_sys::g_unsetenv;\n\n #[cfg(windows)]\n\n use glib_sys::g_unsetenv_utf8 as g_unsetenv;\n\n\n\n unsafe { g_unsetenv(variable_name.as_ref().to_glib_none().0) }\n\n}\n\n\n", "file_path": "glib/src/utils.rs", "rank": 31, "score": 191799.54332139692 }, { "content": "pub fn dngettext(\n\n domain: Option<&str>,\n\n msgid: &str,\n\n msgid_plural: &str,\n\n n: libc::c_ulong,\n\n) -> GString {\n\n unsafe {\n\n from_glib_none(glib_sys::g_dngettext(\n\n domain.to_glib_none().0,\n\n msgid.to_glib_none().0,\n\n msgid_plural.to_glib_none().0,\n\n n,\n\n ))\n\n }\n\n}\n\n\n\n//pub fn double_equal(v1: /*Unimplemented*/Fundamental: Pointer, v2: /*Unimplemented*/Fundamental: Pointer) -> bool {\n\n// unsafe { TODO: call glib_sys:g_double_equal() }\n\n//}\n\n\n\n//pub fn double_hash(v: /*Unimplemented*/Fundamental: Pointer) -> u32 {\n\n// unsafe { TODO: call glib_sys:g_double_hash() }\n\n//}\n\n\n", "file_path": "glib/src/auto/functions.rs", "rank": 32, "score": 189424.81960404082 }, { "content": "pub fn shape_full(\n\n item_text: &str,\n\n paragraph_text: Option<&str>,\n\n analysis: &Analysis,\n\n glyphs: &mut GlyphString,\n\n) {\n\n let paragraph_length = match paragraph_text {\n\n Some(s) => s.len(),\n\n None => 0,\n\n } as i32;\n\n let paragraph_text = paragraph_text.to_glib_none();\n\n let item_length = item_text.len() as i32;\n\n unsafe {\n\n pango_sys::pango_shape_full(\n\n item_text.to_glib_none().0,\n\n item_length,\n\n paragraph_text.0,\n\n paragraph_length,\n\n analysis.to_glib_none().0,\n\n glyphs.to_glib_none_mut().0,\n\n );\n\n }\n\n}\n\n\n", "file_path": "pango/src/functions.rs", "rank": 33, "score": 189424.81960404082 }, { "content": "pub fn main_quit() {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n if gtk_sys::gtk_main_level() > 0 {\n\n gtk_sys::gtk_main_quit();\n\n } else if cfg!(debug_assertions) {\n\n panic!(\"Attempted to quit a GTK main loop when none is running.\");\n\n }\n\n }\n\n}\n\n\n", "file_path": "gtk/src/rt.rs", "rank": 34, "score": 189424.81960404082 }, { "content": "pub fn property_change(\n\n window: &super::Window,\n\n property: &super::Atom,\n\n type_: &super::Atom,\n\n format: i32,\n\n mode: super::PropMode,\n\n data: super::ChangeData,\n\n) {\n\n skip_assert_initialized!();\n\n let nelements = data.len();\n\n unsafe {\n\n gdk_sys::gdk_property_change(\n\n window.to_glib_none().0,\n\n property.to_glib_none().0,\n\n type_.to_glib_none().0,\n\n format,\n\n mode.to_glib(),\n\n data.to_glib(),\n\n nelements as i32,\n\n );\n\n }\n\n}\n", "file_path": "gdk/src/functions.rs", "rank": 35, "score": 189424.81960404082 }, { "content": "pub fn itemize(\n\n context: &Context,\n\n text: &str,\n\n start_index: i32,\n\n length: i32,\n\n attrs: &AttrList,\n\n cached_iter: Option<&AttrIterator>,\n\n) -> Vec<Item> {\n\n unsafe {\n\n FromGlibPtrContainer::from_glib_full(pango_sys::pango_itemize(\n\n context.to_glib_none().0,\n\n text.to_glib_none().0,\n\n start_index,\n\n length,\n\n attrs.to_glib_none().0,\n\n mut_override(cached_iter.to_glib_none().0),\n\n ))\n\n }\n\n}\n\n\n", "file_path": "pango/src/auto/functions.rs", "rank": 36, "score": 189424.81960404082 }, { "content": "pub fn main() {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n gtk_sys::gtk_main();\n\n }\n\n}\n\n\n", "file_path": "gtk/src/auto/functions.rs", "rank": 37, "score": 189424.81960404082 }, { "content": "pub fn check_version(\n\n required_major: u32,\n\n required_minor: u32,\n\n required_micro: u32,\n\n) -> Option<String> {\n\n skip_assert_initialized!();\n\n unsafe {\n\n from_glib_none(gtk_sys::gtk_check_version(\n\n required_major as c_uint,\n\n required_minor as c_uint,\n\n required_micro as c_uint,\n\n ))\n\n }\n\n}\n", "file_path": "gtk/src/rt.rs", "rank": 38, "score": 189424.81960404082 }, { "content": "#[cfg(any(feature = \"v1_44\", feature = \"dox\"))]\n\npub fn shape_with_flags(\n\n item_text: &str,\n\n paragraph_text: Option<&str>,\n\n analysis: &Analysis,\n\n glyphs: &mut GlyphString,\n\n flags: ShapeFlags,\n\n) {\n\n let item_length = item_text.len() as i32;\n\n let paragraph_length = paragraph_text.map(|t| t.len() as i32).unwrap_or_default();\n\n unsafe {\n\n pango_sys::pango_shape_with_flags(\n\n item_text.to_glib_none().0,\n\n item_length,\n\n paragraph_text.to_glib_none().0,\n\n paragraph_length,\n\n analysis.to_glib_none().0,\n\n glyphs.to_glib_none_mut().0,\n\n flags.to_glib(),\n\n );\n\n }\n\n}\n", "file_path": "pango/src/functions.rs", "rank": 39, "score": 189424.81960404082 }, { "content": "pub fn flush() {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n gdk_sys::gdk_flush();\n\n }\n\n}\n\n\n", "file_path": "gdk/src/auto/functions.rs", "rank": 40, "score": 189424.81960404082 }, { "content": "pub fn beep() {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n gdk_sys::gdk_beep();\n\n }\n\n}\n\n\n", "file_path": "gdk/src/auto/functions.rs", "rank": 41, "score": 189424.81960404082 }, { "content": "#[cfg(any(feature = \"v2_64\", feature = \"dox\"))]\n\npub fn get_os_info(key_name: &str) -> Option<GString> {\n\n unsafe { from_glib_full(glib_sys::g_get_os_info(key_name.to_glib_none().0)) }\n\n}\n\n\n", "file_path": "glib/src/auto/functions.rs", "rank": 42, "score": 188572.09985144134 }, { "content": "pub fn pattern_match_simple(pattern: &str, string: &str) -> bool {\n\n unsafe {\n\n from_glib(glib_sys::g_pattern_match_simple(\n\n pattern.to_glib_none().0,\n\n string.to_glib_none().0,\n\n ))\n\n }\n\n}\n\n\n\n//pub fn pattern_match_string(pspec: /*Ignored*/&mut PatternSpec, string: &str) -> bool {\n\n// unsafe { TODO: call glib_sys:g_pattern_match_string() }\n\n//}\n\n\n\n//pub fn pointer_bit_lock(address: /*Unimplemented*/Fundamental: Pointer, lock_bit: i32) {\n\n// unsafe { TODO: call glib_sys:g_pointer_bit_lock() }\n\n//}\n\n\n\n//pub fn pointer_bit_trylock(address: /*Unimplemented*/Fundamental: Pointer, lock_bit: i32) -> bool {\n\n// unsafe { TODO: call glib_sys:g_pointer_bit_trylock() }\n\n//}\n", "file_path": "glib/src/auto/functions.rs", "rank": 43, "score": 188196.44256743218 }, { "content": "#[cfg_attr(feature = \"v1_38\", deprecated)]\n\npub fn parse_enum(\n\n type_: glib::types::Type,\n\n str: Option<&str>,\n\n warn: bool,\n\n) -> Option<(i32, GString)> {\n\n unsafe {\n\n let mut value = mem::MaybeUninit::uninit();\n\n let mut possible_values = ptr::null_mut();\n\n let ret = from_glib(pango_sys::pango_parse_enum(\n\n type_.to_glib(),\n\n str.to_glib_none().0,\n\n value.as_mut_ptr(),\n\n warn.to_glib(),\n\n &mut possible_values,\n\n ));\n\n let value = value.assume_init();\n\n if ret {\n\n Some((value, from_glib_full(possible_values)))\n\n } else {\n\n None\n\n }\n\n }\n\n}\n\n\n", "file_path": "pango/src/auto/functions.rs", "rank": 44, "score": 186085.56603623967 }, { "content": "pub fn bus_get<\n\n P: IsA<Cancellable>,\n\n Q: FnOnce(Result<DBusConnection, glib::Error>) + Send + 'static,\n\n>(\n\n bus_type: BusType,\n\n cancellable: Option<&P>,\n\n callback: Q,\n\n) {\n\n let user_data: Box_<Q> = Box_::new(callback);\n\n unsafe extern \"C\" fn bus_get_trampoline<\n\n Q: FnOnce(Result<DBusConnection, glib::Error>) + Send + 'static,\n\n >(\n\n _source_object: *mut gobject_sys::GObject,\n\n res: *mut gio_sys::GAsyncResult,\n\n user_data: glib_sys::gpointer,\n\n ) {\n\n let mut error = ptr::null_mut();\n\n let ret = gio_sys::g_bus_get_finish(res, &mut error);\n\n let result = if error.is_null() {\n\n Ok(from_glib_full(ret))\n", "file_path": "gio/src/auto/functions.rs", "rank": 45, "score": 186085.56603623967 }, { "content": "#[cfg_attr(feature = \"v2_46\", deprecated)]\n\npub fn mem_profile() {\n\n unsafe {\n\n glib_sys::g_mem_profile();\n\n }\n\n}\n\n\n\n//#[cfg_attr(feature = \"v2_46\", deprecated)]\n\n//pub fn mem_set_vtable(vtable: /*Ignored*/&mut MemVTable) {\n\n// unsafe { TODO: call glib_sys:g_mem_set_vtable() }\n\n//}\n\n\n\n//pub fn memdup(mem: /*Unimplemented*/Option<Fundamental: Pointer>, byte_size: u32) -> /*Unimplemented*/Option<Fundamental: Pointer> {\n\n// unsafe { TODO: call glib_sys:g_memdup() }\n\n//}\n\n\n", "file_path": "glib/src/auto/functions.rs", "rank": 46, "score": 186085.56603623967 }, { "content": "pub fn parse_markup(\n\n markup_text: &str,\n\n accel_marker: char,\n\n) -> Result<(AttrList, GString, char), glib::Error> {\n\n let length = markup_text.len() as i32;\n\n unsafe {\n\n let mut attr_list = ptr::null_mut();\n\n let mut text = ptr::null_mut();\n\n let mut accel_char = mem::MaybeUninit::uninit();\n\n let mut error = ptr::null_mut();\n\n let _ = pango_sys::pango_parse_markup(\n\n markup_text.to_glib_none().0,\n\n length,\n\n accel_marker.to_glib(),\n\n &mut attr_list,\n\n &mut text,\n\n accel_char.as_mut_ptr(),\n\n &mut error,\n\n );\n\n let accel_char = accel_char.assume_init();\n", "file_path": "pango/src/auto/functions.rs", "rank": 47, "score": 186085.56603623967 }, { "content": "/// To set the default print handler, use the [`set_print_handler`] function.\n\npub fn unset_print_handler() {\n\n *PRINT_HANDLER\n\n .lock()\n\n .expect(\"Failed to lock PRINT_HANDLER to remove callback\") = None;\n\n unsafe { glib_sys::g_set_print_handler(None) };\n\n}\n\n\n\nstatic PRINTERR_HANDLER: Lazy<Mutex<Option<Arc<PrintCallback>>>> = Lazy::new(|| Mutex::new(None));\n\n\n", "file_path": "glib/src/log.rs", "rank": 48, "score": 186085.56603623967 }, { "content": "pub fn warn_message(\n\n domain: Option<&str>,\n\n file: &str,\n\n line: i32,\n\n func: &str,\n\n warnexpr: Option<&str>,\n\n) {\n\n unsafe {\n\n glib_sys::g_warn_message(\n\n domain.to_glib_none().0,\n\n file.to_glib_none().0,\n\n line,\n\n func.to_glib_none().0,\n\n warnexpr.to_glib_none().0,\n\n );\n\n }\n\n}\n", "file_path": "glib/src/auto/functions.rs", "rank": 49, "score": 186085.56603623967 }, { "content": "pub fn networking_init() {\n\n unsafe {\n\n gio_sys::g_networking_init();\n\n }\n\n}\n\n\n", "file_path": "gio/src/auto/functions.rs", "rank": 50, "score": 186085.56603623967 }, { "content": "pub fn version_check(\n\n required_major: i32,\n\n required_minor: i32,\n\n required_micro: i32,\n\n) -> Option<GString> {\n\n unsafe {\n\n from_glib_none(pango_sys::pango_version_check(\n\n required_major,\n\n required_minor,\n\n required_micro,\n\n ))\n\n }\n\n}\n\n\n", "file_path": "pango/src/auto/functions.rs", "rank": 51, "score": 186085.56603623967 }, { "content": "/// To set the default print handler, use the [`set_printerr_handler`] function.\n\npub fn unset_printerr_handler() {\n\n *PRINTERR_HANDLER\n\n .lock()\n\n .expect(\"Failed to lock PRINTERR_HANDLER to remove callback\") = None;\n\n unsafe { glib_sys::g_set_printerr_handler(None) };\n\n}\n\n\n", "file_path": "glib/src/log.rs", "rank": 52, "score": 186085.56603623967 }, { "content": "#[cfg(not(windows))]\n\npub fn spawn_async_with_pipes<\n\n P: AsRef<std::path::Path>,\n\n T: FromRawFd,\n\n U: FromRawFd,\n\n V: FromRawFd,\n\n>(\n\n working_directory: P,\n\n argv: &[&std::path::Path],\n\n envp: &[&std::path::Path],\n\n flags: SpawnFlags,\n\n child_setup: Option<Box_<dyn FnOnce() + 'static>>,\n\n) -> Result<(Pid, T, U, V), Error> {\n\n let child_setup_data: Box_<Option<Box_<dyn FnOnce() + 'static>>> = Box_::new(child_setup);\n\n unsafe extern \"C\" fn child_setup_func<P: AsRef<std::path::Path>>(\n\n user_data: glib_sys::gpointer,\n\n ) {\n\n let callback: Box_<Option<Box_<dyn FnOnce() + 'static>>> =\n\n Box_::from_raw(user_data as *mut _);\n\n let callback = (*callback).expect(\"cannot get closure...\");\n\n callback()\n", "file_path": "glib/src/functions.rs", "rank": 53, "score": 186085.56603623967 }, { "content": "pub fn show_uri(\n\n screen: Option<&gdk::Screen>,\n\n uri: &str,\n\n timestamp: u32,\n\n) -> Result<(), glib::Error> {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n let mut error = ptr::null_mut();\n\n let _ = gtk_sys::gtk_show_uri(\n\n screen.to_glib_none().0,\n\n uri.to_glib_none().0,\n\n timestamp,\n\n &mut error,\n\n );\n\n if error.is_null() {\n\n Ok(())\n\n } else {\n\n Err(from_glib_full(error))\n\n }\n\n }\n\n}\n\n\n", "file_path": "gtk/src/auto/functions.rs", "rank": 54, "score": 186085.56603623967 }, { "content": "pub fn assert_warning(\n\n log_domain: &str,\n\n file: &str,\n\n line: i32,\n\n pretty_function: &str,\n\n expression: &str,\n\n) {\n\n unsafe {\n\n glib_sys::g_assert_warning(\n\n log_domain.to_glib_none().0,\n\n file.to_glib_none().0,\n\n line,\n\n pretty_function.to_glib_none().0,\n\n expression.to_glib_none().0,\n\n );\n\n }\n\n}\n\n\n", "file_path": "glib/src/auto/functions.rs", "rank": 55, "score": 186085.56603623967 }, { "content": "pub fn disable_setlocale() {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n gtk_sys::gtk_disable_setlocale();\n\n }\n\n}\n\n\n\n//pub fn distribute_natural_allocation(extra_space: i32, n_requested_sizes: u32, sizes: /*Ignored*/&mut RequestedSize) -> i32 {\n\n// unsafe { TODO: call gtk_sys:gtk_distribute_natural_allocation() }\n\n//}\n\n\n", "file_path": "gtk/src/auto/functions.rs", "rank": 56, "score": 186085.56603623967 }, { "content": "pub fn x11_get_xatom_by_name_for_display(display: &X11Display, atom_name: &str) -> xlib::Atom {\n\n skip_assert_initialized!();\n\n unsafe {\n\n gdk_x11_sys::gdk_x11_get_xatom_by_name_for_display(\n\n display.to_glib_none().0,\n\n atom_name.to_glib_none().0,\n\n )\n\n }\n\n}\n\n\n", "file_path": "gdkx11/src/auto/functions.rs", "rank": 57, "score": 186084.69380029975 }, { "content": "pub fn find_nested_meta<'a>(meta: &'a MetaList, name: &str) -> Option<&'a NestedMeta> {\n\n meta.nested.iter().find(|n| match n {\n\n NestedMeta::Meta(m) => m.path().is_ident(name),\n\n _ => false,\n\n })\n\n}\n\n\n", "file_path": "glib-macros/src/utils.rs", "rank": 58, "score": 185260.16028484554 }, { "content": "/// Adds a closure to be called by the main loop the return `Source` is attached to when it's idle.\n\n///\n\n/// `func` will be called repeatedly until it returns `Continue(false)`.\n\npub fn idle_source_new<F>(name: Option<&str>, priority: Priority, func: F) -> Source\n\nwhere\n\n F: FnMut() -> Continue + Send + 'static,\n\n{\n\n unsafe {\n\n let source = glib_sys::g_idle_source_new();\n\n glib_sys::g_source_set_callback(\n\n source,\n\n Some(trampoline::<F>),\n\n into_raw(func),\n\n Some(destroy_closure::<F>),\n\n );\n\n glib_sys::g_source_set_priority(source, priority.to_glib());\n\n\n\n if let Some(name) = name {\n\n glib_sys::g_source_set_name(source, name.to_glib_none().0);\n\n }\n\n\n\n from_glib_full(source)\n\n }\n\n}\n\n\n", "file_path": "glib/src/source.rs", "rank": 59, "score": 185260.16028484554 }, { "content": "#[cfg_attr(feature = \"v3_16\", deprecated)]\n\npub fn pre_parse_libgtk_only() {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n gdk_sys::gdk_pre_parse_libgtk_only();\n\n }\n\n}\n\n\n", "file_path": "gdk/src/auto/functions.rs", "rank": 60, "score": 182934.562361204 }, { "content": "pub fn notify_startup_complete() {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n gdk_sys::gdk_notify_startup_complete();\n\n }\n\n}\n\n\n", "file_path": "gdk/src/auto/functions.rs", "rank": 61, "score": 182934.562361204 }, { "content": "pub fn error_trap_push() {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n gdk_sys::gdk_error_trap_push();\n\n }\n\n}\n\n\n", "file_path": "gdk/src/auto/functions.rs", "rank": 62, "score": 182934.562361204 }, { "content": "pub fn resources_open_stream(\n\n path: &str,\n\n lookup_flags: ResourceLookupFlags,\n\n) -> Result<InputStream, glib::Error> {\n\n unsafe {\n\n let mut error = ptr::null_mut();\n\n let ret = gio_sys::g_resources_open_stream(\n\n path.to_glib_none().0,\n\n lookup_flags.to_glib(),\n\n &mut error,\n\n );\n\n if error.is_null() {\n\n Ok(from_glib_full(ret))\n\n } else {\n\n Err(from_glib_full(error))\n\n }\n\n }\n\n}\n\n\n", "file_path": "gio/src/auto/functions.rs", "rank": 63, "score": 182934.562361204 }, { "content": "pub fn dbus_gvalue_to_gvariant(\n\n gvalue: &glib::Value,\n\n type_: &glib::VariantTy,\n\n) -> Option<glib::Variant> {\n\n unsafe {\n\n from_glib_full(gio_sys::g_dbus_gvalue_to_gvariant(\n\n gvalue.to_glib_none().0,\n\n type_.to_glib_none().0,\n\n ))\n\n }\n\n}\n\n\n", "file_path": "gio/src/auto/functions.rs", "rank": 64, "score": 182934.562361204 }, { "content": "pub fn accelerator_get_label(\n\n accelerator_key: u32,\n\n accelerator_mods: gdk::ModifierType,\n\n) -> Option<GString> {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n from_glib_full(gtk_sys::gtk_accelerator_get_label(\n\n accelerator_key,\n\n accelerator_mods.to_glib(),\n\n ))\n\n }\n\n}\n\n\n", "file_path": "gtk/src/auto/functions.rs", "rank": 65, "score": 182934.562361204 }, { "content": "pub fn return_if_fail_warning(\n\n log_domain: Option<&str>,\n\n pretty_function: &str,\n\n expression: Option<&str>,\n\n) {\n\n unsafe {\n\n glib_sys::g_return_if_fail_warning(\n\n log_domain.to_glib_none().0,\n\n pretty_function.to_glib_none().0,\n\n expression.to_glib_none().0,\n\n );\n\n }\n\n}\n\n\n", "file_path": "glib/src/auto/functions.rs", "rank": 66, "score": 182934.562361204 }, { "content": "pub fn x11_ungrab_server() {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n gdk_x11_sys::gdk_x11_ungrab_server();\n\n }\n\n}\n\n\n", "file_path": "gdkx11/src/auto/functions.rs", "rank": 67, "score": 182934.562361204 }, { "content": "pub fn pixbuf_get_from_surface(\n\n surface: &cairo::Surface,\n\n src_x: i32,\n\n src_y: i32,\n\n width: i32,\n\n height: i32,\n\n) -> Option<gdk_pixbuf::Pixbuf> {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n from_glib_full(gdk_sys::gdk_pixbuf_get_from_surface(\n\n mut_override(surface.to_glib_none().0),\n\n src_x,\n\n src_y,\n\n width,\n\n height,\n\n ))\n\n }\n\n}\n\n\n", "file_path": "gdk/src/auto/functions.rs", "rank": 68, "score": 182934.562361204 }, { "content": "pub fn bus_get_future(\n\n bus_type: BusType,\n\n) -> Pin<Box_<dyn std::future::Future<Output = Result<DBusConnection, glib::Error>> + 'static>> {\n\n Box_::pin(crate::GioFuture::new(&(), move |_obj, send| {\n\n let cancellable = Cancellable::new();\n\n bus_get(bus_type, Some(&cancellable), move |res| {\n\n send.resolve(res);\n\n });\n\n\n\n cancellable\n\n }))\n\n}\n\n\n", "file_path": "gio/src/auto/functions.rs", "rank": 69, "score": 182934.562361204 }, { "content": "pub fn resources_enumerate_children(\n\n path: &str,\n\n lookup_flags: ResourceLookupFlags,\n\n) -> Result<Vec<GString>, glib::Error> {\n\n unsafe {\n\n let mut error = ptr::null_mut();\n\n let ret = gio_sys::g_resources_enumerate_children(\n\n path.to_glib_none().0,\n\n lookup_flags.to_glib(),\n\n &mut error,\n\n );\n\n if error.is_null() {\n\n Ok(FromGlibPtrContainer::from_glib_full(ret))\n\n } else {\n\n Err(from_glib_full(error))\n\n }\n\n }\n\n}\n\n\n", "file_path": "gio/src/auto/functions.rs", "rank": 70, "score": 182934.562361204 }, { "content": "pub fn resources_lookup_data(\n\n path: &str,\n\n lookup_flags: ResourceLookupFlags,\n\n) -> Result<glib::Bytes, glib::Error> {\n\n unsafe {\n\n let mut error = ptr::null_mut();\n\n let ret = gio_sys::g_resources_lookup_data(\n\n path.to_glib_none().0,\n\n lookup_flags.to_glib(),\n\n &mut error,\n\n );\n\n if error.is_null() {\n\n Ok(from_glib_full(ret))\n\n } else {\n\n Err(from_glib_full(error))\n\n }\n\n }\n\n}\n\n\n", "file_path": "gio/src/auto/functions.rs", "rank": 71, "score": 182934.562361204 }, { "content": "pub fn test_register_all_types() {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n gtk_sys::gtk_test_register_all_types();\n\n }\n\n}\n\n\n", "file_path": "gtk/src/auto/functions.rs", "rank": 72, "score": 182934.562361204 }, { "content": "/// Create a `Future` that will resolve after the given number of milliseconds.\n\n///\n\n/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.\n\npub fn timeout_future_with_priority(\n\n priority: Priority,\n\n value: Duration,\n\n) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>> {\n\n Box::pin(SourceFuture::new(move |send| {\n\n let mut send = Some(send);\n\n ::timeout_source_new(value, None, priority, move || {\n\n let _ = send.take().unwrap().send(());\n\n Continue(false)\n\n })\n\n }))\n\n}\n\n\n", "file_path": "glib/src/source_futures.rs", "rank": 73, "score": 182934.562361204 }, { "content": "pub fn assertion_message_cmpstr(\n\n domain: &str,\n\n file: &str,\n\n line: i32,\n\n func: &str,\n\n expr: &str,\n\n arg1: &str,\n\n cmp: &str,\n\n arg2: &str,\n\n) {\n\n unsafe {\n\n glib_sys::g_assertion_message_cmpstr(\n\n domain.to_glib_none().0,\n\n file.to_glib_none().0,\n\n line,\n\n func.to_glib_none().0,\n\n expr.to_glib_none().0,\n\n arg1.to_glib_none().0,\n\n cmp.to_glib_none().0,\n\n arg2.to_glib_none().0,\n\n );\n\n }\n\n}\n\n\n", "file_path": "glib/src/auto/functions.rs", "rank": 74, "score": 182934.562361204 }, { "content": "/// Create a `Stream` that will provide a value every given number of milliseconds.\n\n///\n\n/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.\n\npub fn interval_stream_with_priority(\n\n priority: Priority,\n\n value: Duration,\n\n) -> Pin<Box<dyn Stream<Item = ()> + Send + 'static>> {\n\n Box::pin(SourceStream::new(move |send| {\n\n ::timeout_source_new(value, None, priority, move || {\n\n if send.unbounded_send(()).is_err() {\n\n Continue(false)\n\n } else {\n\n Continue(true)\n\n }\n\n })\n\n }))\n\n}\n\n\n", "file_path": "glib/src/source_futures.rs", "rank": 75, "score": 182934.562361204 }, { "content": "/// To set the default print handler, use the [`log_set_default_handler`] function.\n\npub fn log_unset_default_handler() {\n\n *DEFAULT_HANDLER\n\n .lock()\n\n .expect(\"Failed to lock DEFAULT_HANDLER to remove callback\") = None;\n\n unsafe {\n\n glib_sys::g_log_set_default_handler(\n\n Some(glib_sys::g_log_default_handler),\n\n ::std::ptr::null_mut(),\n\n )\n\n };\n\n}\n\n\n", "file_path": "glib/src/log.rs", "rank": 76, "score": 182934.562361204 }, { "content": "pub fn resources_get_info(\n\n path: &str,\n\n lookup_flags: ResourceLookupFlags,\n\n) -> Result<(usize, u32), glib::Error> {\n\n unsafe {\n\n let mut size = mem::MaybeUninit::uninit();\n\n let mut flags = mem::MaybeUninit::uninit();\n\n let mut error = ptr::null_mut();\n\n let _ = gio_sys::g_resources_get_info(\n\n path.to_glib_none().0,\n\n lookup_flags.to_glib(),\n\n size.as_mut_ptr(),\n\n flags.as_mut_ptr(),\n\n &mut error,\n\n );\n\n let size = size.assume_init();\n\n let flags = flags.assume_init();\n\n if error.is_null() {\n\n Ok((size, flags))\n\n } else {\n\n Err(from_glib_full(error))\n\n }\n\n }\n\n}\n\n\n", "file_path": "gio/src/auto/functions.rs", "rank": 77, "score": 182934.562361204 }, { "content": "/// Create a `Future` that will resolve once the child process with the given pid exits\n\n///\n\n/// The `Future` will resolve to the pid of the child process and the exit code.\n\n///\n\n/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.\n\npub fn child_watch_future(\n\n pid: ::Pid,\n\n) -> Pin<Box<dyn Future<Output = (::Pid, i32)> + Send + 'static>> {\n\n child_watch_future_with_priority(::PRIORITY_DEFAULT, pid)\n\n}\n\n\n", "file_path": "glib/src/source_futures.rs", "rank": 78, "score": 182934.562361204 }, { "content": "pub fn itemize_with_base_dir(\n\n context: &Context,\n\n base_dir: Direction,\n\n text: &str,\n\n start_index: i32,\n\n length: i32,\n\n attrs: &AttrList,\n\n cached_iter: Option<&AttrIterator>,\n\n) -> Vec<Item> {\n\n unsafe {\n\n FromGlibPtrContainer::from_glib_full(pango_sys::pango_itemize_with_base_dir(\n\n context.to_glib_none().0,\n\n base_dir.to_glib(),\n\n text.to_glib_none().0,\n\n start_index,\n\n length,\n\n attrs.to_glib_none().0,\n\n mut_override(cached_iter.to_glib_none().0),\n\n ))\n\n }\n", "file_path": "pango/src/auto/functions.rs", "rank": 79, "score": 182934.562361204 }, { "content": "pub fn x11_grab_server() {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n gdk_x11_sys::gdk_x11_grab_server();\n\n }\n\n}\n\n\n", "file_path": "gdkx11/src/auto/functions.rs", "rank": 80, "score": 182934.562361204 }, { "content": "pub fn content_type_get_generic_icon_name(type_: &str) -> Option<GString> {\n\n unsafe {\n\n from_glib_full(gio_sys::g_content_type_get_generic_icon_name(\n\n type_.to_glib_none().0,\n\n ))\n\n }\n\n}\n\n\n", "file_path": "gio/src/auto/functions.rs", "rank": 81, "score": 182152.39377160821 }, { "content": "pub fn x11_get_xatom_name(xatom: xlib::Atom) -> Option<GString> {\n\n assert_initialized_main_thread!();\n\n unsafe { from_glib_none(gdk_x11_sys::gdk_x11_get_xatom_name(xatom)) }\n\n}\n\n\n", "file_path": "gdkx11/src/auto/functions.rs", "rank": 82, "score": 181443.93844924722 }, { "content": "#[inline]\n\npub fn is_initialized() -> bool {\n\n skip_assert_initialized!();\n\n INITIALIZED.load(Ordering::Acquire)\n\n}\n\n\n\n/// Returns `true` if GTK has been initialized and this is the main thread.\n", "file_path": "gtk/src/rt.rs", "rank": 83, "score": 180939.41428608386 }, { "content": "#[inline]\n\npub fn is_initialized() -> bool {\n\n skip_assert_initialized!();\n\n INITIALIZED.load(Ordering::Acquire)\n\n}\n\n\n\n/// Returns `true` if GDK has been initialized and this is the main thread.\n", "file_path": "gdkx11/src/rt.rs", "rank": 84, "score": 180939.41428608386 }, { "content": "#[inline]\n\npub fn is_initialized() -> bool {\n\n skip_assert_initialized!();\n\n INITIALIZED.load(Ordering::Acquire)\n\n}\n\n\n\n/// Returns `true` if GDK has been initialized and this is the main thread.\n", "file_path": "gdk/src/rt.rs", "rank": 85, "score": 180939.41428608386 }, { "content": "/// Create a `Stream` that will provide a value every given number of seconds.\n\n///\n\n/// The `Stream` must be spawned on an `Executor` backed by a `glib::MainContext`.\n\npub fn interval_stream_seconds_with_priority(\n\n priority: Priority,\n\n value: u32,\n\n) -> Pin<Box<dyn Stream<Item = ()> + Send + 'static>> {\n\n Box::pin(SourceStream::new(move |send| {\n\n ::timeout_source_new_seconds(value, None, priority, move || {\n\n if send.unbounded_send(()).is_err() {\n\n Continue(false)\n\n } else {\n\n Continue(true)\n\n }\n\n })\n\n }))\n\n}\n\n\n\n#[cfg(any(unix, feature = \"dox\"))]\n", "file_path": "glib/src/source_futures.rs", "rank": 86, "score": 179956.32615164836 }, { "content": "pub fn io_scheduler_cancel_all_jobs() {\n\n unsafe {\n\n gio_sys::g_io_scheduler_cancel_all_jobs();\n\n }\n\n}\n\n\n\n//pub fn io_scheduler_push_job<P: IsA<Cancellable>>(job_func: /*Unimplemented*/Fn(/*Ignored*/IOSchedulerJob, Option<&Cancellable>) -> bool, user_data: /*Unimplemented*/Option<Fundamental: Pointer>, io_priority: i32, cancellable: Option<&P>) {\n\n// unsafe { TODO: call gio_sys:g_io_scheduler_push_job() }\n\n//}\n\n\n", "file_path": "gio/src/auto/functions.rs", "rank": 87, "score": 179956.32615164836 }, { "content": "/// Create a `Future` that will resolve once the child process with the given pid exits\n\n///\n\n/// The `Future` will resolve to the pid of the child process and the exit code.\n\n///\n\n/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.\n\npub fn child_watch_future_with_priority(\n\n priority: Priority,\n\n pid: ::Pid,\n\n) -> Pin<Box<dyn Future<Output = (::Pid, i32)> + Send + 'static>> {\n\n Box::pin(SourceFuture::new(move |send| {\n\n let mut send = Some(send);\n\n ::child_watch_source_new(pid, None, priority, move |pid, code| {\n\n let _ = send.take().unwrap().send((pid, code));\n\n })\n\n }))\n\n}\n\n\n\n#[cfg(any(unix, feature = \"dox\"))]\n", "file_path": "glib/src/source_futures.rs", "rank": 88, "score": 179956.32615164836 }, { "content": "pub fn accelerator_get_label_with_keycode(\n\n display: Option<&gdk::Display>,\n\n accelerator_key: u32,\n\n keycode: u32,\n\n accelerator_mods: gdk::ModifierType,\n\n) -> Option<GString> {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n from_glib_full(gtk_sys::gtk_accelerator_get_label_with_keycode(\n\n display.to_glib_none().0,\n\n accelerator_key,\n\n keycode,\n\n accelerator_mods.to_glib(),\n\n ))\n\n }\n\n}\n\n\n", "file_path": "gtk/src/auto/functions.rs", "rank": 89, "score": 179956.32615164836 }, { "content": "/// Create a `Future` that will resolve after the given number of seconds.\n\n///\n\n/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.\n\npub fn timeout_future_seconds_with_priority(\n\n priority: Priority,\n\n value: u32,\n\n) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>> {\n\n Box::pin(SourceFuture::new(move |send| {\n\n let mut send = Some(send);\n\n ::timeout_source_new_seconds(value, None, priority, move || {\n\n let _ = send.take().unwrap().send(());\n\n Continue(false)\n\n })\n\n }))\n\n}\n\n\n", "file_path": "glib/src/source_futures.rs", "rank": 90, "score": 179956.32615164836 }, { "content": "/// Create a `Stream` that will provide a value whenever the given UNIX signal is raised\n\n///\n\n/// The `Stream` must be spawned on an `Executor` backed by a `glib::MainContext`.\n\npub fn unix_signal_stream_with_priority(\n\n priority: Priority,\n\n signum: i32,\n\n) -> Pin<Box<dyn Stream<Item = ()> + Send + 'static>> {\n\n Box::pin(SourceStream::new(move |send| {\n\n ::unix_signal_source_new(signum, None, priority, move || {\n\n if send.unbounded_send(()).is_err() {\n\n Continue(false)\n\n } else {\n\n Continue(true)\n\n }\n\n })\n\n }))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::thread;\n\n use std::time::Duration;\n", "file_path": "glib/src/source_futures.rs", "rank": 91, "score": 179956.32615164836 }, { "content": "pub fn pango_layout_get_clip_region(\n\n layout: &pango::Layout,\n\n x_origin: i32,\n\n y_origin: i32,\n\n index_ranges: &[GRange],\n\n) -> Option<cairo::Region> {\n\n assert_initialized_main_thread!();\n\n\n\n let ptr: *const i32 = index_ranges.as_ptr() as _;\n\n unsafe {\n\n from_glib_full(gdk_sys::gdk_pango_layout_get_clip_region(\n\n layout.to_glib_none().0,\n\n x_origin,\n\n y_origin,\n\n ptr,\n\n index_ranges.len() as i32,\n\n ))\n\n }\n\n}\n\n\n", "file_path": "gdk/src/functions.rs", "rank": 92, "score": 179956.32615164836 }, { "content": "pub fn keyfile_settings_backend_new(\n\n filename: &str,\n\n root_path: &str,\n\n root_group: Option<&str>,\n\n) -> Option<SettingsBackend> {\n\n unsafe {\n\n from_glib_full(gio_sys::g_keyfile_settings_backend_new(\n\n filename.to_glib_none().0,\n\n root_path.to_glib_none().0,\n\n root_group.to_glib_none().0,\n\n ))\n\n }\n\n}\n\n\n", "file_path": "gio/src/auto/functions.rs", "rank": 93, "score": 179956.32615164836 }, { "content": "pub fn error_trap_pop_ignored() {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n gdk_sys::gdk_error_trap_pop_ignored();\n\n }\n\n}\n\n\n", "file_path": "gdk/src/auto/functions.rs", "rank": 94, "score": 179956.32615164836 }, { "content": "/// Create a `Future` that will resolve once the given UNIX signal is raised\n\n///\n\n/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.\n\npub fn unix_signal_future_with_priority(\n\n priority: Priority,\n\n signum: i32,\n\n) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>> {\n\n Box::pin(SourceFuture::new(move |send| {\n\n let mut send = Some(send);\n\n ::unix_signal_source_new(signum, None, priority, move || {\n\n let _ = send.take().unwrap().send(());\n\n Continue(false)\n\n })\n\n }))\n\n}\n\n\n\n/// Represents a `Stream` around a `glib::Source`. The stream will\n\n/// be provide all values that are provided by the source\n\npub struct SourceStream<F, T> {\n\n create_source: Option<F>,\n\n source: Option<(Source, mpsc::UnboundedReceiver<T>)>,\n\n}\n\n\n", "file_path": "glib/src/source_futures.rs", "rank": 95, "score": 179956.32615164836 }, { "content": "pub fn dbus_address_get_stream<\n\n P: IsA<Cancellable>,\n\n Q: FnOnce(Result<(IOStream, GString), glib::Error>) + Send + 'static,\n\n>(\n\n address: &str,\n\n cancellable: Option<&P>,\n\n callback: Q,\n\n) {\n\n let user_data: Box_<Q> = Box_::new(callback);\n\n unsafe extern \"C\" fn dbus_address_get_stream_trampoline<\n\n Q: FnOnce(Result<(IOStream, GString), glib::Error>) + Send + 'static,\n\n >(\n\n _source_object: *mut gobject_sys::GObject,\n\n res: *mut gio_sys::GAsyncResult,\n\n user_data: glib_sys::gpointer,\n\n ) {\n\n let mut error = ptr::null_mut();\n\n let mut out_guid = ptr::null_mut();\n\n let ret = gio_sys::g_dbus_address_get_stream_finish(res, &mut out_guid, &mut error);\n\n let result = if error.is_null() {\n", "file_path": "gio/src/auto/functions.rs", "rank": 96, "score": 179956.32615164836 }, { "content": "#[inline]\n\npub fn from_glib<G: Copy, T: FromGlib<G>>(val: G) -> T {\n\n FromGlib::from_glib(val)\n\n}\n\n\n\nimpl FromGlib<glib_sys::gboolean> for bool {\n\n #[inline]\n\n fn from_glib(val: glib_sys::gboolean) -> bool {\n\n val != glib_sys::GFALSE\n\n }\n\n}\n\n\n\nimpl FromGlib<i32> for Ordering {\n\n #[inline]\n\n fn from_glib(val: i32) -> Ordering {\n\n val.cmp(&0)\n\n }\n\n}\n\n\n", "file_path": "glib/src/translate.rs", "rank": 97, "score": 179592.84576138481 }, { "content": "pub fn false_() -> bool {\n\n assert_initialized_main_thread!();\n\n unsafe { from_glib(gtk_sys::gtk_false()) }\n\n}\n\n\n", "file_path": "gtk/src/auto/functions.rs", "rank": 98, "score": 177600.16071828268 }, { "content": "pub fn version() -> i32 {\n\n unsafe { pango_sys::pango_version() }\n\n}\n\n\n", "file_path": "pango/src/auto/functions.rs", "rank": 99, "score": 177600.16071828268 } ]
Rust
src/parser/values.rs
ithinuel/async-gcode
0f7ee3efc4fa0023766e3f436472573ef1fb0f5b
#![allow(clippy::useless_conversion)] use futures::{Stream, StreamExt}; #[cfg(all(not(feature = "std"), feature = "string-value"))] use alloc::string::String; use crate::{ stream::PushBackable, types::{Literal, ParseResult}, utils::skip_whitespaces, Error, }; #[cfg(not(feature = "parse-expressions"))] use crate::types::RealValue; #[cfg(any(feature = "parse-parameters", feature = "parse-expressions"))] pub use crate::types::expressions::{Expression, Operator}; pub(crate) async fn parse_number<S, E>(input: &mut S) -> Option<Result<(u32, u32), E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let mut n = 0; let mut order = 1; let res = loop { let b = match input.next().await? { Ok(b) => b, Err(e) => return Some(Err(e)), }; match b { b'0'..=b'9' => { let digit = u32::from(b - b'0'); n = n * 10 + digit; order *= 10; } _ => { input.push_back(b); break Ok((n, order)); } } }; Some(res) } async fn parse_real_literal<S, E>(input: &mut S) -> Option<ParseResult<f64, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let mut b = try_result!(input.next()); let mut negativ = false; if b == b'-' || b == b'+' { negativ = b == b'-'; try_result!(skip_whitespaces(input)); b = try_result!(input.next()); } let int = if b != b'.' { input.push_back(b); let (v, _) = try_result!(parse_number(input)); try_result!(skip_whitespaces(input)); b = try_result!(input.next()); Some(v) } else { None }; let dec = if b == b'.' { try_result!(skip_whitespaces(input)); Some(try_result!(parse_number(input))) } else { input.push_back(b); None }; let res = if int.is_none() && dec.is_none() { ParseResult::Parsing(Error::BadNumberFormat.into()) } else { let int = int.map(f64::from).unwrap_or(0.); let (dec, ord) = dec .map(|(dec, ord)| (dec.into(), ord.into())) .unwrap_or((0., 1.)); ParseResult::Ok((if negativ { -1. } else { 1. }) * (int + dec / ord)) }; Some(res) } #[cfg(feature = "string-value")] async fn parse_string_literal<S, E>(input: &mut S) -> Option<ParseResult<String, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { #[cfg(not(feature = "std"))] use alloc::vec::Vec; let mut array = Vec::new(); loop { match try_result!(input.next()) { b'"' => break, b'\\' => { array.push(try_result!(input.next())); } b => array.push(b), } } match String::from_utf8(array) { Ok(string) => Some(ParseResult::Ok(string)), Err(_) => Some(Error::InvalidUTF8String.into()), } } pub(crate) async fn parse_literal<S, E>(input: &mut S) -> Option<ParseResult<Literal, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let b = try_result!(input.next()); Some(match b { b'+' | b'-' | b'.' | b'0'..=b'9' => { input.push_back(b); ParseResult::Ok(Literal::from(try_parse!(parse_real_literal(input)))) } #[cfg(feature = "string-value")] b'"' => ParseResult::Ok(Literal::from(try_parse!(parse_string_literal(input)))), _ => Error::UnexpectedByte(b).into(), }) } #[cfg(not(feature = "parse-expressions"))] pub(crate) async fn parse_real_value<S, E>(input: &mut S) -> Option<ParseResult<RealValue, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let b = try_result!(input.next()); let res = match b { b'+' | b'-' | b'.' | b'0'..=b'9' => { input.push_back(b); ParseResult::Ok(RealValue::from(try_parse!(parse_literal(input)))) } #[cfg(feature = "string-value")] b'"' => { input.push_back(b); ParseResult::Ok(RealValue::from(try_parse!(parse_literal(input)))) } #[cfg(feature = "parse-parameters")] b'#' => { #[cfg(not(feature = "std"))] use alloc::vec::Vec; let mut n = 1; let literal = loop { try_result!(skip_whitespaces(input)); let b = try_result!(input.next()); if b != b'#' { input.push_back(b); break try_parse!(parse_literal(input)); } n += 1; }; let vec: Vec<_> = core::iter::once(literal.into()) .chain(core::iter::repeat(Operator::GetParameter.into()).take(n)) .collect(); ParseResult::Ok(Expression(vec).into()) } #[cfg(feature = "optional-value")] b => { input.push_back(b); ParseResult::Ok(RealValue::None) } #[cfg(not(feature = "optional-value"))] b => Error::UnexpectedByte(b).into(), }; Some(res) }
#![allow(clippy::useless_conversion)] use futures::{Stream, StreamExt}; #[cfg(all(not(feature = "std"), feature = "string-value"))] use alloc::string::String; use crate::{ stream::PushBackable, types::{Literal, ParseResult}, utils::skip_whitespaces, Error, }; #[cfg(not(feature = "parse-expressions"))] use crate::types::RealValue; #[cfg(any(feature = "parse-parameters", feature = "parse-expressions"))] pub use crate::types::expressions::{Expression, Operator};
async fn parse_real_literal<S, E>(input: &mut S) -> Option<ParseResult<f64, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let mut b = try_result!(input.next()); let mut negativ = false; if b == b'-' || b == b'+' { negativ = b == b'-'; try_result!(skip_whitespaces(input)); b = try_result!(input.next()); } let int = if b != b'.' { input.push_back(b); let (v, _) = try_result!(parse_number(input)); try_result!(skip_whitespaces(input)); b = try_result!(input.next()); Some(v) } else { None }; let dec = if b == b'.' { try_result!(skip_whitespaces(input)); Some(try_result!(parse_number(input))) } else { input.push_back(b); None }; let res = if int.is_none() && dec.is_none() { ParseResult::Parsing(Error::BadNumberFormat.into()) } else { let int = int.map(f64::from).unwrap_or(0.); let (dec, ord) = dec .map(|(dec, ord)| (dec.into(), ord.into())) .unwrap_or((0., 1.)); ParseResult::Ok((if negativ { -1. } else { 1. }) * (int + dec / ord)) }; Some(res) } #[cfg(feature = "string-value")] async fn parse_string_literal<S, E>(input: &mut S) -> Option<ParseResult<String, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { #[cfg(not(feature = "std"))] use alloc::vec::Vec; let mut array = Vec::new(); loop { match try_result!(input.next()) { b'"' => break, b'\\' => { array.push(try_result!(input.next())); } b => array.push(b), } } match String::from_utf8(array) { Ok(string) => Some(ParseResult::Ok(string)), Err(_) => Some(Error::InvalidUTF8String.into()), } } pub(crate) async fn parse_literal<S, E>(input: &mut S) -> Option<ParseResult<Literal, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let b = try_result!(input.next()); Some(match b { b'+' | b'-' | b'.' | b'0'..=b'9' => { input.push_back(b); ParseResult::Ok(Literal::from(try_parse!(parse_real_literal(input)))) } #[cfg(feature = "string-value")] b'"' => ParseResult::Ok(Literal::from(try_parse!(parse_string_literal(input)))), _ => Error::UnexpectedByte(b).into(), }) } #[cfg(not(feature = "parse-expressions"))] pub(crate) async fn parse_real_value<S, E>(input: &mut S) -> Option<ParseResult<RealValue, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let b = try_result!(input.next()); let res = match b { b'+' | b'-' | b'.' | b'0'..=b'9' => { input.push_back(b); ParseResult::Ok(RealValue::from(try_parse!(parse_literal(input)))) } #[cfg(feature = "string-value")] b'"' => { input.push_back(b); ParseResult::Ok(RealValue::from(try_parse!(parse_literal(input)))) } #[cfg(feature = "parse-parameters")] b'#' => { #[cfg(not(feature = "std"))] use alloc::vec::Vec; let mut n = 1; let literal = loop { try_result!(skip_whitespaces(input)); let b = try_result!(input.next()); if b != b'#' { input.push_back(b); break try_parse!(parse_literal(input)); } n += 1; }; let vec: Vec<_> = core::iter::once(literal.into()) .chain(core::iter::repeat(Operator::GetParameter.into()).take(n)) .collect(); ParseResult::Ok(Expression(vec).into()) } #[cfg(feature = "optional-value")] b => { input.push_back(b); ParseResult::Ok(RealValue::None) } #[cfg(not(feature = "optional-value"))] b => Error::UnexpectedByte(b).into(), }; Some(res) }
pub(crate) async fn parse_number<S, E>(input: &mut S) -> Option<Result<(u32, u32), E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let mut n = 0; let mut order = 1; let res = loop { let b = match input.next().await? { Ok(b) => b, Err(e) => return Some(Err(e)), }; match b { b'0'..=b'9' => { let digit = u32::from(b - b'0'); n = n * 10 + digit; order *= 10; } _ => { input.push_back(b); break Ok((n, order)); } } }; Some(res) }
function_block-full_function
[ { "content": "#[derive(Debug)]\n\nenum Error {\n\n Io(std::io::Error),\n\n Parse(async_gcode::Error),\n\n}\n\nimpl From<async_gcode::Error> for Error {\n\n fn from(f: async_gcode::Error) -> Self {\n\n Self::Parse(f)\n\n }\n\n}\n", "file_path": "examples/cli.rs", "rank": 0, "score": 46838.70850890484 }, { "content": "#[cfg(not(feature = \"parse-comments\"))]\n\nfn to_gcode_comment(_msg: &str) -> [Result<GCode, Error>; 0] {\n\n []\n\n}\n", "file_path": "src/parser/test.rs", "rank": 1, "score": 28731.43789218122 }, { "content": "#[cfg(feature = \"parse-comments\")]\n\nfn to_gcode_comment(msg: &str) -> [Result<GCode, Error>; 1] {\n\n [Ok(GCode::Comment(msg.to_string()))]\n\n}\n\n\n", "file_path": "src/parser/test.rs", "rank": 2, "score": 28731.43789218122 }, { "content": "#[cfg(feature = \"parse-checksum\")]\n\ntype PushBack<T> = crate::stream::xorsum_pushback::XorSumPushBack<T>;\n\n\n\nasync fn parse_eol<S, E>(\n\n state: &mut AsyncParserState,\n\n input: &mut PushBack<S>,\n\n) -> Option<ParseResult<GCode, E>>\n\nwhere\n\n S: Stream<Item = Result<u8, E>> + Unpin,\n\n{\n\n Some(loop {\n\n let b = try_result!(input.next());\n\n match b {\n\n b'\\r' | b'\\n' => {\n\n *state = AsyncParserState::Start(true);\n\n #[cfg(feature = \"parse-checksum\")]\n\n {\n\n input.reset_sum(0);\n\n }\n\n break ParseResult::Ok(GCode::Execute);\n\n }\n", "file_path": "src/parser.rs", "rank": 3, "score": 27084.830645321614 }, { "content": "fn block_on<T: Iterator<Item = u8>>(it: T) -> Vec<Result<GCode, Error>> {\n\n let mut parser = Parser::new(stream::iter(it).map(Result::<_, Error>::Ok));\n\n\n\n futures_executor::block_on(\n\n stream::unfold(\n\n &mut parser,\n\n |p| async move { p.next().await.map(|w| (w, p)) },\n\n )\n\n .collect(),\n\n )\n\n}\n", "file_path": "src/parser/test.rs", "rank": 4, "score": 24336.123454738256 }, { "content": "#[test]\n\nfn operator_name_are_case_insensitive() {\n\n let input = \"g [ Cos [ 90 ] ** 2 + sIn [ 90 ] ]\".bytes();\n\n assert_eq!(\n\n block_on(input),\n\n &[Ok(GCode::Word(\n\n 'g',\n\n Expression(vec![\n\n Literal::from(90).into(),\n\n Operator::Cos.into(),\n\n Literal::from(2).into(),\n\n Operator::Power.into(),\n\n Literal::from(90).into(),\n\n Operator::Sin.into(),\n\n Operator::Add.into(),\n\n ])\n\n .into()\n\n ))]\n\n )\n\n}\n\n\n", "file_path": "src/parser/test/parse_expressions.rs", "rank": 5, "score": 20645.974284060117 }, { "content": "#[test]\n\nfn unary_have_higher_precedence_on_power_operator() {\n\n let input = \"g [ cos [ 90 ] ** 2 ]\".bytes();\n\n assert_eq!(\n\n block_on(input),\n\n &[Ok(GCode::Word(\n\n 'g',\n\n Expression(vec![\n\n Literal::from(90).into(),\n\n Operator::Cos.into(),\n\n Literal::from(2).into(),\n\n Operator::Power.into()\n\n ])\n\n .into()\n\n ))]\n\n )\n\n}\n\n\n", "file_path": "src/parser/test/parse_expressions.rs", "rank": 6, "score": 19822.480787133405 }, { "content": "#[test]\n\nfn parse_binary_operator_with_appropriate_precedence() {\n\n let input = \"g [ 2 - 9 * [7 * 5] ** 2 * 4 + 8 / 4 ]\".bytes();\n\n assert_eq!(\n\n block_on(input),\n\n &[Ok(GCode::Word(\n\n 'g',\n\n Expression(vec![\n\n Literal::from(2).into(),\n\n Literal::from(9).into(),\n\n Literal::from(7).into(),\n\n Literal::from(5).into(),\n\n Operator::Multiply.into(),\n\n Literal::from(2).into(),\n\n Operator::Power.into(),\n\n Operator::Multiply.into(),\n\n Literal::from(4).into(),\n\n Operator::Multiply.into(),\n\n Operator::Substract.into(),\n\n Literal::from(8).into(),\n\n Literal::from(4).into(),\n\n Operator::Divide.into(),\n\n Operator::Add.into(),\n\n ])\n\n .into()\n\n ))]\n\n )\n\n}\n\n\n", "file_path": "src/parser/test/parse_expressions.rs", "rank": 7, "score": 19822.480787133405 }, { "content": "#[test]\n\n#[cfg(all(feature = \"optional-value\", feature = \"parse-expressions\"))]\n\nfn word_may_not_have_a_value_but_ambiguous_sequence_will_error() {\n\n // T following a value less Z will be read as the start of «Tan» and the expression will err\n\n // on the unexpected '4' that follows.\n\n let input = \"G75 Z T48 S P.3\\n\".bytes();\n\n assert_eq!(\n\n block_on(input),\n\n &[\n\n Ok(GCode::Word('g', (75.0).into())),\n\n Ok(GCode::Word('z', RealValue::None)),\n\n Err(Error::UnexpectedByte(b'4')),\n\n Ok(GCode::Execute)\n\n ]\n\n );\n\n}\n\n\n", "file_path": "src/parser/test.rs", "rank": 8, "score": 19737.209244375626 }, { "content": "#[test]\n\nfn error_in_underlying_stream_are_passed_through_and_parser_recovers_on_execute() {\n\n #[derive(Debug, Copy, Clone, PartialEq)]\n\n enum TestError {\n\n SomeError,\n\n ParseError(Error),\n\n }\n\n impl From<Error> for TestError {\n\n fn from(from: Error) -> Self {\n\n TestError::ParseError(from)\n\n }\n\n }\n\n\n\n let string = b\"g12 h12 b32\\n\";\n\n let input = string[0..6]\n\n .iter()\n\n .copied()\n\n .map(Result::Ok)\n\n .chain([Err(TestError::SomeError)].iter().copied())\n\n .chain(string[6..].iter().copied().map(Result::Ok));\n\n\n", "file_path": "src/parser/test.rs", "rank": 9, "score": 19733.768583943838 }, { "content": "use crate::{\n\n types::{\n\n expressions::{Expression, Operator},\n\n Literal,\n\n },\n\n GCode,\n\n};\n\n\n\n#[cfg(feature = \"optional-value\")]\n\nuse crate::{types::RealValue, Error};\n\n\n\nuse super::block_on;\n\n\n\n#[test]\n", "file_path": "src/parser/test/parse_parameters.rs", "rank": 10, "score": 13.694720143500916 }, { "content": "use either::Either;\n\nuse futures::stream::{Stream, StreamExt};\n\n\n\n#[cfg(all(\n\n not(feature = \"std\"),\n\n any(feature = \"parse-parameters\", feature = \"parse-expressions\")\n\n))]\n\nuse alloc::vec::Vec;\n\n#[cfg(feature = \"std\")]\n\nuse std::vec::Vec;\n\n\n\nuse crate::{\n\n stream::PushBackable,\n\n types::{\n\n expressions::{Associativity, ExprItem, Expression, OpType, Operator},\n\n Literal, ParseResult, RealValue,\n\n },\n\n utils::skip_whitespaces,\n\n Error,\n\n};\n\n\n\n#[derive(PartialEq, Debug, Clone)]\n", "file_path": "src/parser/expressions.rs", "rank": 11, "score": 13.617380009192523 }, { "content": " use either::Either;\n\n\n\n #[cfg(not(feature = \"std\"))]\n\n use alloc::vec::Vec;\n\n\n\n pub(crate) type ExprItem = Either<Operator, Literal>;\n\n pub(crate) type ExprInner = Vec<ExprItem>;\n\n\n\n #[derive(Debug, PartialEq, Clone, Copy)]\n\n pub enum OpType {\n\n Unary,\n\n Binary,\n\n }\n\n #[derive(Debug, PartialEq, Clone, Copy)]\n\n pub enum Associativity {\n\n Left,\n\n #[cfg(feature = \"parse-parameters\")]\n\n Right,\n\n }\n\n #[derive(Debug, Clone, Copy, PartialOrd, PartialEq)]\n", "file_path": "src/types.rs", "rank": 12, "score": 12.894050042014573 }, { "content": "pub use parser::Parser;\n\npub use types::Literal;\n\npub use types::RealValue;\n\n\n\n#[cfg(any(feature = \"parse-expressions\", feature = \"parse-parameters\"))]\n\npub use types::expressions::Expression;\n\n\n\n#[derive(Debug, PartialEq, Clone, Copy)]\n\npub enum Error {\n\n /// Error no the gcode syntax\n\n UnexpectedByte(u8),\n\n\n\n /// The parsed number excedded the expected range.\n\n NumberOverflow,\n\n\n\n /// Format error during number parsing. Typically a dot without digits (at least one is\n\n /// required).\n\n BadNumberFormat,\n\n\n\n #[cfg(any(feature = \"parse-comments\", feature = \"string-value\"))]\n", "file_path": "src/lib.rs", "rank": 13, "score": 11.600829789374668 }, { "content": "#[cfg(all(\n\n not(feature = \"std\"),\n\n any(feature = \"parse-comments\", feature = \"string-value\")\n\n))]\n\nuse alloc::string::String;\n\n\n\n#[derive(Debug)]\n\npub(crate) enum ParseResult<G, E> {\n\n Input(E),\n\n Parsing(crate::Error),\n\n Ok(G),\n\n}\n\nimpl<O, E> From<core::result::Result<O, E>> for ParseResult<O, E> {\n\n fn from(f: core::result::Result<O, E>) -> Self {\n\n match f {\n\n Ok(o) => ParseResult::Ok(o),\n\n Err(e) => ParseResult::Input(e),\n\n }\n\n }\n\n}\n", "file_path": "src/types.rs", "rank": 15, "score": 11.136395121881861 }, { "content": " #[cfg(any(feature = \"parse-parameters\", feature = \"parse-expressions\"))]\n\n Expression(expressions::Expression),\n\n #[cfg(feature = \"optional-value\")]\n\n None,\n\n}\n\nimpl Default for RealValue {\n\n fn default() -> Self {\n\n Self::from(0.)\n\n }\n\n}\n\nimpl<T: Into<Literal>> From<T> for RealValue {\n\n fn from(from: T) -> Self {\n\n RealValue::Literal(from.into())\n\n }\n\n}\n\n\n\n#[cfg(any(feature = \"parse-parameters\", feature = \"parse-expressions\"))]\n\npub(crate) mod expressions {\n\n use super::{Literal, RealValue};\n\n use crate::Error;\n", "file_path": "src/types.rs", "rank": 16, "score": 11.080702505045746 }, { "content": "\n\nimpl<O, E> From<crate::Error> for ParseResult<O, E> {\n\n fn from(f: crate::Error) -> Self {\n\n ParseResult::Parsing(f)\n\n }\n\n}\n\n\n\n#[cfg(not(feature = \"parse-comments\"))]\n\npub type Comment = ();\n\n#[cfg(feature = \"parse-comments\")]\n\npub type Comment = String;\n\n\n\n#[derive(Debug, PartialEq, Clone)]\n\npub enum Literal {\n\n RealNumber(f64),\n\n #[cfg(feature = \"string-value\")]\n\n String(String),\n\n}\n\nimpl Literal {\n\n pub fn as_real_number(&self) -> Option<f64> {\n", "file_path": "src/types.rs", "rank": 17, "score": 10.641439640267638 }, { "content": " any(\n\n feature = \"parse-expressions\",\n\n feature = \"parse-parameters\",\n\n feature = \"parse-comments\",\n\n feature = \"string-value\"\n\n )\n\n))]\n\nextern crate alloc;\n\n\n\n#[cfg(all(not(feature = \"std\"), feature = \"parse-comments\"))]\n\nuse alloc::string::String;\n\n\n\n#[macro_use]\n\nmod utils;\n\n\n\nmod stream;\n\nmod types;\n\n\n\nmod parser;\n\n\n", "file_path": "src/lib.rs", "rank": 18, "score": 10.362104533480062 }, { "content": " }\n\n b'(' => break Some(Error::UnexpectedByte(b'(').into()),\n\n b')' => {\n\n break Some(match String::from_utf8(v) {\n\n Ok(s) => ParseResult::Ok(s),\n\n Err(_) => Error::InvalidUTF8String.into(),\n\n })\n\n }\n\n b => v.push(b),\n\n }\n\n }\n\n}\n\n\n\n// use a different struct to compute checksum\n\n#[cfg(not(feature = \"parse-checksum\"))]\n\nuse crate::stream::pushback::PushBack;\n", "file_path": "src/parser.rs", "rank": 20, "score": 9.526007239633095 }, { "content": " }\n\n }\n\n}\n\n\n\n#[cfg(feature = \"parse-checksum\")]\n\npub(crate) mod xorsum_pushback {\n\n use futures::{Stream, TryStream};\n\n use pin_project_lite::pin_project;\n\n\n\n use core::pin::Pin;\n\n use core::task::{Context, Poll};\n\n\n\n use super::PushBackable;\n\n\n\n pin_project! {\n\n pub(crate) struct XorSumPushBack<S: TryStream> {\n\n #[pin]\n\n stream: S,\n\n head: Option<S::Ok>,\n\n sum: S::Ok\n", "file_path": "src/stream.rs", "rank": 21, "score": 9.50541077109244 }, { "content": "use futures::stream;\n\n\n\nuse super::{Error, GCode, Parser, StreamExt};\n\n\n\n#[cfg(feature = \"optional-value\")]\n\nuse crate::types::RealValue;\n\n\n\n#[cfg(feature = \"parse-checksum\")]\n\nmod parse_checksum;\n\n#[cfg(feature = \"parse-expressions\")]\n\nmod parse_expressions;\n\n#[cfg(feature = \"parse-parameters\")]\n\nmod parse_parameters;\n\n#[cfg(feature = \"parse-trailing-comment\")]\n\nmod parse_trailing_comment;\n\n\n", "file_path": "src/parser/test.rs", "rank": 22, "score": 9.353236112556306 }, { "content": "use super::{block_on, GCode};\n\nuse crate::types::{\n\n expressions::{Expression, Operator},\n\n Literal,\n\n};\n\n\n\n#[test]\n", "file_path": "src/parser/test/parse_expressions.rs", "rank": 23, "score": 9.112554687744597 }, { "content": " | Self::Fup\n\n | Self::Ln\n\n | Self::Round\n\n | Self::Sqrt => Precedence::Group5,\n\n }\n\n }\n\n }\n\n\n\n #[derive(Debug, PartialEq, Clone)]\n\n pub struct Expression(pub(crate) ExprInner);\n\n impl Expression {\n\n /// Evaluates the expressions to a single literal. Math error may occur during the\n\n /// expression's resolution (e.g. division by 0).\n\n ///\n\n /// When `parse-parameters` is enabled, this method takes a closure as an argument.\n\n /// This closure is used to resolve parameters get.\n\n pub fn evaluate(\n\n &self,\n\n #[cfg(feature = \"parse-parameters\")] _cbk: &mut dyn FnMut(Literal) -> Literal,\n\n ) -> Result<Literal, Error> {\n", "file_path": "src/types.rs", "rank": 24, "score": 9.069756835432365 }, { "content": " xorsum_pushback::XorSumPushBack::new(self, initial_sum)\n\n }\n\n}\n\nimpl<T: ?Sized> MyTryStreamExt for T where T: TryStream {}\n\n\n\npub(crate) trait PushBackable {\n\n type Item;\n\n fn push_back(&mut self, v: Self::Item) -> Option<Self::Item>;\n\n}\n\n\n\n#[cfg(not(feature = \"parse-checksum\"))]\n\npub(crate) mod pushback {\n\n use futures::{Stream, TryStream};\n\n use pin_project_lite::pin_project;\n\n\n\n use core::pin::Pin;\n\n use core::task::{Context, Poll};\n\n\n\n use super::PushBackable;\n\n\n", "file_path": "src/stream.rs", "rank": 25, "score": 8.817858469483914 }, { "content": "\n\n#[cfg(feature = \"parse-expressions\")]\n\nmod expressions;\n\n\n\n#[cfg(test)]\n\nmod test;\n\n\n\nuse futures::{Stream, StreamExt};\n\n\n\nuse crate::{\n\n stream::{MyTryStreamExt, PushBackable},\n\n types::{Comment, ParseResult},\n\n utils::skip_whitespaces,\n\n Error, GCode,\n\n};\n\n\n\nuse values::parse_number;\n\n\n\n#[cfg(not(feature = \"parse-expressions\"))]\n\nuse values::parse_real_value;\n\n\n\n#[cfg(feature = \"parse-expressions\")]\n\nuse expressions::parse_real_value;\n\n\n\n#[derive(PartialEq, Debug, Clone, Copy)]\n", "file_path": "src/parser.rs", "rank": 26, "score": 8.680665878089595 }, { "content": "//! Dev-dependencies currently leak features to dependencies.\n\n//! This crate requires rust-nightly to build with no_std until `-Z features=dev_dep` makes it to\n\n//! stable.\n\n//!\n\n//! ## Note for future development\n\n//! It might be interesting to have a look at ISO 6983 and/or ISO 14649.\n\n//!\n\n//! During development fixed arithmetics was considered to be made available as an alternative to\n\n//! the floating point arithmetics especially for small target. After investigation, it does not\n\n//! seem to be a significant gain for the precision required by the gcode standard.\n\n//!\n\n//! Ideally all arithmetics triggered by a theoritically valid input should be caught and not\n\n//! trigger a panic. For an excessive number of digit in a number may exceed the capacity of the\n\n//! variable used internally.\n\n//!\n\n//! [RS274/NGC interpreter version 3]: https://www.nist.gov/publications/nist-rs274ngc-interpreter-version-3?pub_id=823374\n\n#![cfg_attr(not(feature = \"std\"), no_std)]\n\n\n\n#[cfg(all(\n\n not(feature = \"std\"),\n", "file_path": "src/lib.rs", "rank": 27, "score": 8.613087371521399 }, { "content": "#[cfg(feature = \"parse-trailing-comment\")]\n\nuse super::to_gcode_comment;\n\nuse super::{block_on, Error, GCode};\n\n\n\n#[test]\n", "file_path": "src/parser/test/parse_checksum.rs", "rank": 28, "score": 8.296765445092074 }, { "content": " pub enum Precedence {\n\n Group1,\n\n Group2,\n\n Group3,\n\n #[cfg(feature = \"parse-parameters\")]\n\n Group4,\n\n Group5,\n\n }\n\n\n\n #[derive(Debug, PartialEq, Clone, Copy)]\n\n pub enum Operator {\n\n // Binary operators\n\n Add,\n\n Substract,\n\n Multiply,\n\n Divide,\n\n Power,\n\n\n\n And,\n\n Or,\n", "file_path": "src/types.rs", "rank": 29, "score": 8.124505351695369 }, { "content": " b'-' => { Operator::Substract }\n\n b'*' => {\n\n b'*' => { Operator::Power }\n\n b => {{\n\n input.push_back(b);\n\n Token::Operator(Operator::Multiply)\n\n }}\n\n }\n\n b'/' => { Operator::Divide }\n\n b'a' => { b\"nd\" => Operator::And }\n\n b'o' => { b\"r\" => Operator::Or }\n\n b'x' => { b\"or\" => Operator::Xor }\n\n b'm' => { b\"od\" => Operator::Modulus }\n\n b']' => {{ Token::CloseBracket }}\n\n #[cfg(not(feature = \"parse-parameters\"))]\n\n _ => {{ return Some(ParseResult::Parsing(Error::UnexpectedByte(b))) }}\n\n }\n\n }\n\n Expect::Expr => match b {\n\n b'[' => Token::OpenBracket,\n", "file_path": "src/parser/expressions.rs", "rank": 30, "score": 7.519129165572313 }, { "content": "//! This crate implements a GCode (RS-274) parser.\n\n//!\n\n//! The default dialect is taken from NIST's [RS274/NGC interpreter version 3].\n\n//! Some expensive part of that dialect such as parameters and expressions are gated behind feature\n\n//! – respectively `parse-parameters` and `parse-expressions` – in order to avoid dependency on\n\n//! dynamic allocation.\n\n//!\n\n//! Some extension to this dialect such as checksum, trailing comments, optional values are also\n\n//! supported and gated behind features.\n\n//!\n\n//! ## 🔩 Example\n\n//!\n\n//! ```\n\n//! use futures::stream;\n\n//! use futures_executor::block_on;\n\n//! use async_gcode::{Parser, Error};\n\n//! let input = r\"\n\n//! G21 H21. I21.098\n\n//! J-21 K-21. L-21.098\n\n//! M+21 N+21. P+21.098\n", "file_path": "src/lib.rs", "rank": 31, "score": 7.284129953186586 }, { "content": "//! The ebnf representatio following [https://bottlecaps.de/rr/ui]'s syntax\n\n//! ```ebnf\n\n//! line ::= '/'? ( [Nn] [0-9]+ )?\n\n//! ( [a-zA-Z] real_value? | '#' real_value '=' real_value? | '(' [^)] ')' )*\n\n//! ( '*' [0-9]+ /* 0 to 255 */ )?\n\n//! ( ';' [^\\n]* )? '\\n'\n\n//! real_value ::= '#'* ( real_number\n\n//! | '\"' [^\"] '\"'\n\n//! | 'atan' expression '/' expression\n\n//! | ( 'abs' | 'acos' | 'asin' | 'cos' | 'exp' | 'fix' | 'fup' | 'ln' | 'round' | 'sin' | 'sqrt' | 'tan' ) expression )\n\n//! expression ::= '[' real_value ( ( '**' | '/' | 'mod' | '*' | 'and' | 'xor' | '-' | 'or' | '+' ) real_value )* ']'\n\n//! real_number ::= ( '+' | '-' )? ( [0-9]+ ( '.' [0-9]* )? | '.' [0-9]+ )\n\n//! ```\n\n//!\n\n#[cfg(all(not(feature = \"std\"), feature = \"parse-comments\"))]\n\nuse alloc::string::String;\n\n#[cfg(all(not(feature = \"std\"), any(feature = \"parse-comments\")))]\n\nuse alloc::vec::Vec;\n\n\n\nmod values;\n", "file_path": "src/parser.rs", "rank": 32, "score": 6.94472519378275 }, { "content": " _ => return Some(ParseResult::Parsing(Error::UnexpectedByte(b))),\n\n },\n\n Expect::ATanDiv => match b {\n\n b'/' => Token::Operator(Operator::Divide),\n\n _ => return Some(ParseResult::Parsing(Error::UnexpectedByte(b))),\n\n },\n\n };\n\n Some(ParseResult::Ok(token))\n\n}\n\n\n\npub(crate) async fn parse_real_value<S, E>(input: &mut S) -> Option<ParseResult<RealValue, E>>\n\nwhere\n\n S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>,\n\n{\n\n /*\n\n Begin\n\n initially push some special character say # into the stack\n\n for each character tok from infix expression, do\n\n literal => add tok to postfix expression\n\n openBracket => push ( into stack\n", "file_path": "src/parser/expressions.rs", "rank": 33, "score": 6.70275187584044 }, { "content": "use futures::TryStream;\n\n\n\npub(crate) trait MyTryStreamExt: TryStream {\n\n #[cfg(not(feature = \"parse-checksum\"))]\n\n fn push_backable(self) -> pushback::PushBack<Self>\n\n where\n\n Self: Sized,\n\n {\n\n pushback::PushBack::new(self)\n\n }\n\n\n\n #[cfg(feature = \"parse-checksum\")]\n\n fn xor_summed_push_backable(\n\n self,\n\n initial_sum: Self::Ok,\n\n ) -> xorsum_pushback::XorSumPushBack<Self>\n\n where\n\n Self: Sized,\n\n Self::Ok: Copy + core::ops::BitXorAssign,\n\n {\n", "file_path": "src/stream.rs", "rank": 34, "score": 6.6834283981312375 }, { "content": "use futures::stream;\n\nuse futures_executor::block_on;\n\nuse std::io::Read;\n\n\n\n#[derive(Debug)]\n", "file_path": "examples/cli.rs", "rank": 35, "score": 6.606848301657283 }, { "content": "//! On parsing error the `Parser` can no longer trust its input and enters an error recovery state.\n\n//! No `GCode` or `Error` will be emitted until a new line character (`\\n`) is received. Then a\n\n//! `GCode::Execute` is emitted and the parser restarts in a reliable known state.\n\n//!\n\n//! ## ⚙ Features\n\n//! - `std` : Enabled by default. Allows for the use of dynamic allocation.\n\n//! - `parse-comments` : enables the parser to return `GCode::Comment(String)`; requires an allocator.\n\n//! - `parse-trailing-comment`: allows line to end with a `; comment`.\n\n//! - `parse-checksum` : Enables the use of xorsum.\n\n//! - `parse-parameters` : Enables the use of `#` parameters ; requires an allocator.\n\n//! If `string-value` is enabled then parameters may use string index.\n\n//! If `optional-value` is enabled then parameters value may be omitted but **NOT** the indices.\n\n//! - `parse-expressions` : Enables parsing infix expressions ; requires an allocator.\n\n//! - `optional-value` : Allows to omit in `RealValue` in word and parameter value positions.\n\n//! Parameter indices cannot be omitted nor can be literals in expressions.\n\n//! - `string-value` : Allows `RealValue` to be a string. Any character preceded with `\\` will be\n\n//! used as is (useful for `\"`, `)` or new line).\n\n//!\n\n//! ## ⚠ Warning\n\n//!\n", "file_path": "src/lib.rs", "rank": 36, "score": 6.543998387016215 }, { "content": " Some(Ok(()))\n\n}\n\n\n\n#[cfg(itest)]\n\nmod test {\n\n use super::{skip_whitespaces, stream, StreamExt};\n\n\n\n #[cfg(not(feature = \"parse-checksum\"))]\n\n use crate::stream::pushback::PushBack;\n\n #[cfg(feature = \"parse-checksum\")]\n\n use crate::stream::xorsum_pushback::XorSumPushBack;\n\n\n\n #[test]\n\n fn skips_white_spaces_and_pushes_back_the_first_non_space_byte() {\n\n let mut data = PushBack::new(stream::iter(\n\n b\" d\"\n\n .iter()\n\n .copied()\n\n .map(Result::<_, core::convert::Infallible>::Ok),\n\n ));\n\n futures_executor::block_on(async move {\n\n skip_whitespaces(&mut data).await;\n\n assert_eq!(Some(Ok(b'd')), data.next().await);\n\n });\n\n }\n\n}\n", "file_path": "src/utils.rs", "rank": 38, "score": 6.322917567298216 }, { "content": "# GCode Parser\n\n\n\nThis crate aims at providing a gcode parser to the rusty printer project (and other if it can fit).\n\n\n\nThe minimal footprint is achieved with all features disabled and is in the order of **~80B** of\n\nRAM and around **2kB** of Flash memory. The typical set of features\n\n`[\"parse-trailing-comment\", \"parse-checksum\", \"optional-value\"]` has a footprint of around **4kB**\n\nof flash memory for around **80B** of RAM.\n\nFinally with all features, the memory footprint reaches around **7kB** in flash and around **170B**\n\nin RAM.\n\n\n\n## Features\n\n\n\n- `std` : Enabled by default\n\n- `parse-comments` : enables the parser to return `GCode::Comment(String)`; requires an allocator.\n\n- `parse-trailing-comment`: allows line to end with a `; comment`.\n\n- `parse-checksum` : Enables the use of xorsum.\n\n- `parse-parameters` : Enables the use of `#` parameters ; requires an allocator.\n\n If `string-value` is enabled then parameters may use string index.\n\n If `optional-value` is enabled then parameters value may be omitted but **NOT** the indices.\n\n- `parse-expressions` : Enables parsing infix expressions ; requires an allocator.\n\n- `optional-value` : Allows to omit in `RealValue` in word and parameter value positions.\n\n Parameter indices cannot be omitted nor can be literals in expressions.\n\n- `string-value` : Allows `RealValue` to be a string. Any character preceded with `\\` will be\n\n used as is (useful for `\"`, `)` or new line).\n\n\n\n## Design\n\n### Constraints\n\n- No recursion.\n\n- Reduced RAM footprint\n\n- Reduced ROM footprint\n\n\n", "file_path": "README.md", "rank": 41, "score": 5.83691175792857 }, { "content": " Ok(b) => b,\n\n Err(e) => return Some(ParseResult::Input(e)),\n\n };\n\n // println!(\"{:?}\", b as char);\n\n let token = match expect {\n\n Expect::UnaryOrLiteralOrExpr => {\n\n match_operator! { input, b,\n\n #[cfg(feature = \"parse-parameters\")]\n\n b'#' => { Operator::GetParameter }\n\n b'[' => {{ Token::OpenBracket }}\n\n b'a' => {\n\n b'b' => { b\"s\" => Operator::Abs }\n\n b'c' => { b\"os\" => Operator::ACos }\n\n b's' => { b\"in\" => Operator::ASin }\n\n b't' => { b\"an\" => Operator::ATan }\n\n }\n\n b'c' => { b\"os\" => Operator::Cos }\n\n b'e' => { b\"xp\" => Operator::Exp }\n\n b'f' => {\n\n b'i' => { b\"x\" => Operator::Fix }\n", "file_path": "src/parser/expressions.rs", "rank": 42, "score": 5.604394085049839 }, { "content": " _ => unreachable!(),\n\n }\n\n .into(),\n\n )\n\n }\n\n\n\n match op {\n\n #[cfg(feature = \"parse-parameters\")]\n\n Operator::GetParameter => {\n\n stack.push(Stacked::Operator(Operator::GetParameter));\n\n expects = Expect::UnaryOrLiteralOrExpr;\n\n }\n\n Operator::ATan => {\n\n stack.push(Stacked::ATan);\n\n expects = Expect::Expr;\n\n }\n\n _ => {\n\n stack.push(Stacked::Operator(op));\n\n\n\n if op.op_type() == OpType::Unary {\n", "file_path": "src/parser/expressions.rs", "rank": 43, "score": 5.229140666246482 }, { "content": " #[cfg(feature = \"parse-parameters\")]\n\n GetParameter,\n\n }\n\n impl Operator {\n\n pub fn op_type(&self) -> OpType {\n\n match self {\n\n Self::Add\n\n | Self::Substract\n\n | Self::Multiply\n\n | Self::Divide\n\n | Self::Modulus\n\n | Self::Power\n\n | Self::And\n\n | Self::Or\n\n | Self::Xor\n\n | Self::ATan => OpType::Binary,\n\n Self::Cos\n\n | Self::Sin\n\n | Self::Tan\n\n | Self::ACos\n", "file_path": "src/types.rs", "rank": 44, "score": 5.197916334008765 }, { "content": " /// The string or comment received contained an invalid UTF-8 character sequence.\n\n InvalidUTF8String,\n\n\n\n #[cfg(feature = \"parse-checksum\")]\n\n /// Checksum verification failed. The error contains the computed value.\n\n BadChecksum(u8),\n\n\n\n #[cfg(feature = \"parse-expressions\")]\n\n /// The expressions received was invalid.\n\n InvalidExpression,\n\n}\n\n\n\n#[derive(Debug, PartialEq, Clone)]\n\npub enum GCode {\n\n BlockDelete,\n\n LineNumber(u32),\n\n #[cfg(feature = \"parse-comments\")]\n\n Comment(String),\n\n Word(char, RealValue),\n\n #[cfg(feature = \"parse-parameters\")]\n\n /// When `optional-value` is enabled, the index cannot be `RealValue::None`.\n\n ParameterSet(RealValue, RealValue),\n\n Execute,\n\n}\n", "file_path": "src/lib.rs", "rank": 45, "score": 5.163367360804471 }, { "content": " b'\\r' | b'\\n' => {\n\n self.input.push_back(b);\n\n break Ok(try_await!(parse_eol(&mut self.state, &mut self.input)));\n\n }\n\n // param support feature\n\n #[cfg(feature = \"parse-parameters\")]\n\n b'#' => {\n\n try_await_result!(skip_whitespaces(&mut self.input));\n\n #[allow(clippy::match_single_binding)]\n\n let param_id = match try_await!(parse_real_value(&mut self.input)) {\n\n #[cfg(feature = \"optional-value\")]\n\n crate::RealValue::None => {\n\n let b = try_await_result!((&mut self.input).next());\n\n break Err(Error::UnexpectedByte(b).into());\n\n }\n\n id => id,\n\n };\n\n // println!(\"param_id: {:?}\", param_id);\n\n try_await_result!(skip_whitespaces(&mut self.input));\n\n let b = try_await_result!((&mut self.input).next());\n", "file_path": "src/parser.rs", "rank": 47, "score": 4.850510243072849 }, { "content": " .unwrap_or(false)\n\n {\n\n //TODO: this loop on expecting an ATan, let's use a stack specific Type and\n\n //keep track there wether we already got our atandiv or not\n\n expects = Expect::ATanDiv;\n\n } else if depth != 0 {\n\n expects = Expect::BinOpOrCloseBracket;\n\n } else {\n\n break;\n\n }\n\n }\n\n Token::Operator(Operator::Divide) if expects == Expect::ATanDiv => {\n\n stack.pop(); // this is known to be Stacked::ATan\n\n stack.push(Stacked::Operator(Operator::ATan));\n\n expects = Expect::Expr\n\n }\n\n Token::Operator(op) => {\n\n /*\n\n * while !stack.is_empty AND\n\n * precedence(op) < precedence(stack.top) OR\n", "file_path": "src/parser/expressions.rs", "rank": 48, "score": 4.735478485428013 }, { "content": " break Err(Error::BadChecksum(sum).into());\n\n } else {\n\n try_await_result!(skip_whitespaces(&mut self.input));\n\n #[cfg(not(feature = \"parse-trailing-comment\"))]\n\n {\n\n self.state = AsyncParserState::EndOfLine;\n\n }\n\n #[cfg(feature = \"parse-trailing-comment\")]\n\n {\n\n self.state = AsyncParserState::EoLOrTrailingComment;\n\n }\n\n }\n\n }\n\n // comment support features\n\n #[cfg(not(feature = \"parse-comments\"))]\n\n b'(' => {\n\n try_await!(parse_inline_comment(&mut self.input));\n\n }\n\n #[cfg(feature = \"parse-comments\")]\n\n b'(' => {\n", "file_path": "src/parser.rs", "rank": 49, "score": 4.684243499653682 }, { "content": " (Err(e), _) => return Some(ParseResult::Input(e))\n\n }\n\n }\n\n\n\n Token::Operator($op)\n\n }};\n\n (@ $input:expr, $( $(#[$($m:tt)*])* $p:pat => { $($rest:tt)* } )*) => {{\n\n let b = match $input.next().await? {\n\n Ok(b) => b,\n\n Err(e) => return Some(ParseResult::Input(e)),\n\n };\n\n match b.to_ascii_lowercase() {\n\n $(\n\n $p => {\n\n match_operator!(@ $input, $($rest)*)\n\n }\n\n )*\n\n #[allow(unreachable_patterns)]\n\n _ => return Some(ParseResult::Parsing(Error::UnexpectedByte(b))),\n\n }\n", "file_path": "src/parser/expressions.rs", "rank": 50, "score": 4.526347540233266 }, { "content": " match self {\n\n Literal::RealNumber(rn) => Some(*rn),\n\n #[cfg(feature = \"string-value\")]\n\n _ => None,\n\n }\n\n }\n\n #[cfg(feature = \"string-value\")]\n\n pub fn as_string(&self) -> Option<&str> {\n\n match self {\n\n Literal::String(string) => Some(string),\n\n _ => None,\n\n }\n\n }\n\n}\n\nimpl From<i32> for Literal {\n\n fn from(from: i32) -> Self {\n\n Self::RealNumber(from as f64)\n\n }\n\n}\n\nimpl From<u32> for Literal {\n", "file_path": "src/types.rs", "rank": 51, "score": 4.443482561816488 }, { "content": " Err(err) => break Err(err.into()),\n\n }\n\n };\n\n}\n\n\n\npub struct Parser<S, E>\n\nwhere\n\n S: Stream<Item = Result<u8, E>> + Unpin,\n\n{\n\n input: PushBack<S>,\n\n state: AsyncParserState,\n\n}\n\n\n\nimpl<S, E> Parser<S, E>\n\nwhere\n\n S: Stream<Item = Result<u8, E>> + Unpin,\n\n E: From<Error>,\n\n{\n\n pub fn new(input: S) -> Self {\n\n Self {\n", "file_path": "src/parser.rs", "rank": 52, "score": 4.225634177702897 }, { "content": " if b'=' != b {\n\n break Err(Error::UnexpectedByte(b).into());\n\n }\n\n\n\n try_await_result!(skip_whitespaces(&mut self.input));\n\n let value = try_await!(parse_real_value(&mut self.input));\n\n // println!(\"param_id: {:?}\", value);\n\n\n\n break Ok(GCode::ParameterSet(param_id, value));\n\n }\n\n // checksum support feature\n\n #[cfg(feature = \"parse-checksum\")]\n\n b'*' => {\n\n let sum = self.input.sum() ^ b'*';\n\n try_await_result!(skip_whitespaces(&mut self.input));\n\n let (n, _) = try_await_result!(parse_number(&mut self.input));\n\n // println!(\"{} {}\", sum, n);\n\n if n >= 256 {\n\n break Err(Error::NumberOverflow.into());\n\n } else if (n as u8) != sum {\n", "file_path": "src/parser.rs", "rank": 53, "score": 4.208477290789512 }, { "content": " break Ok(GCode::Comment(try_await!(parse_inline_comment(\n\n &mut self.input\n\n ))));\n\n }\n\n #[cfg(all(\n\n feature = \"parse-trailing-comment\",\n\n not(feature = \"parse-comments\")\n\n ))]\n\n b';' => {\n\n try_await_result!(parse_eol_comment(&mut self.input));\n\n self.state = AsyncParserState::EndOfLine;\n\n }\n\n #[cfg(all(feature = \"parse-trailing-comment\", feature = \"parse-comments\"))]\n\n b';' => {\n\n let s = try_await!(parse_eol_comment(&mut self.input));\n\n self.state = AsyncParserState::EndOfLine;\n\n break Ok(GCode::Comment(s));\n\n }\n\n _ => break Err(Error::UnexpectedByte(b).into()),\n\n },\n", "file_path": "src/parser.rs", "rank": 54, "score": 4.206859419383363 }, { "content": "use crate::stream::PushBackable;\n\nuse futures::{Stream, StreamExt};\n\n\n\n#[doc(hidden)]\n\n#[macro_export]\n\nmacro_rules! try_parse {\n\n ($input:expr) => {\n\n match $input.await? {\n\n ParseResult::Ok(b) => b,\n\n ParseResult::Input(e) => return Some(ParseResult::Input(e)),\n\n ParseResult::Parsing(e) => return Some(ParseResult::Parsing(e)),\n\n }\n\n };\n\n}\n\n\n\n#[doc(hidden)]\n\n#[macro_export]\n\nmacro_rules! try_result {\n\n ($input:expr) => {\n\n match $input.await? {\n", "file_path": "src/utils.rs", "rank": 55, "score": 4.157181059501345 }, { "content": " b'u' => { b\"p\" => Operator::Fup }\n\n }\n\n b'l' => { b\"n\" => Operator::Ln }\n\n b'r' => { b\"ound\" => Operator::Round }\n\n b's' => {\n\n b'i' => { b\"n\" => Operator::Sin }\n\n b'q' => { b\"rt\" => Operator::Sqrt }\n\n }\n\n b't' => { b\"an\" => Operator::Tan }\n\n _ => {{\n\n input.push_back(b);\n\n let lit = try_parse!(super::values::parse_literal(input));\n\n Token::Literal(lit)\n\n\n\n }}\n\n }\n\n }\n\n Expect::BinOpOrCloseBracket => {\n\n match_operator! { input, b,\n\n b'+' => { Operator::Add }\n", "file_path": "src/parser/expressions.rs", "rank": 56, "score": 3.9907610240860496 }, { "content": " | Self::ASin\n\n | Self::Abs\n\n | Self::Exp\n\n | Self::Fix\n\n | Self::Fup\n\n | Self::Ln\n\n | Self::Round\n\n | Self::Sqrt => OpType::Unary,\n\n #[cfg(feature = \"parse-parameters\")]\n\n Self::GetParameter => OpType::Unary,\n\n }\n\n }\n\n\n\n pub fn associativity(&self) -> Associativity {\n\n #[allow(clippy::match_single_binding)]\n\n match self {\n\n #[cfg(feature = \"parse-parameters\")]\n\n Self::GetParameter => Associativity::Right,\n\n _ => Associativity::Left,\n\n }\n", "file_path": "src/types.rs", "rank": 57, "score": 3.9376188299615493 }, { "content": " pin_project! {\n\n pub(crate) struct PushBack<S: TryStream> {\n\n #[pin]\n\n stream: S,\n\n val: Option<S::Ok>,\n\n }\n\n }\n\n\n\n impl<S: TryStream> PushBack<S> {\n\n pub fn new(stream: S) -> Self {\n\n Self { stream, val: None }\n\n }\n\n }\n\n impl<S> PushBackable for PushBack<S>\n\n where\n\n S: TryStream,\n\n {\n\n type Item = S::Ok;\n\n fn push_back(&mut self, v: S::Ok) -> Option<S::Ok> {\n\n self.val.replace(v)\n", "file_path": "src/stream.rs", "rank": 58, "score": 3.896642240855795 }, { "content": " Expression(vec![\n\n Literal::from(180).into(),\n\n Literal::from(2).into(),\n\n Operator::Divide.into(),\n\n Literal::from(75).into(),\n\n Literal::from(2).into(),\n\n Operator::Add.into(),\n\n Operator::ATan.into(),\n\n Operator::GetParameter.into(),\n\n ])\n\n .into()\n\n )),\n\n Ok(GCode::Execute)\n\n ]\n\n );\n\n}\n", "file_path": "src/parser/test/parse_expressions.rs", "rank": 59, "score": 3.85576215106452 }, { "content": " fn from(from: u32) -> Self {\n\n Self::RealNumber(from as f64)\n\n }\n\n}\n\nimpl From<f64> for Literal {\n\n fn from(from: f64) -> Self {\n\n Self::RealNumber(from)\n\n }\n\n}\n\n\n\n#[cfg(feature = \"string-value\")]\n\nimpl From<String> for Literal {\n\n fn from(from: String) -> Self {\n\n Self::String(from)\n\n }\n\n}\n\n\n\n#[derive(Debug, PartialEq, Clone)]\n\npub enum RealValue {\n\n Literal(Literal),\n", "file_path": "src/types.rs", "rank": 60, "score": 3.7871123625751526 }, { "content": " expects = Expect::Expr\n\n } else {\n\n expects = Expect::UnaryOrLiteralOrExpr\n\n }\n\n }\n\n }\n\n }\n\n }\n\n }\n\n\n\n /*\n\n while the stack contains some remaining characters, do\n\n pop and add to the postfix expression\n\n done\n\n return postfix\n\n */\n\n while let Some(stacked) = stack.pop() {\n\n match stacked {\n\n Stacked::Operator(op) => postfix.push(op.into()),\n\n Stacked::OpenBracket => return Some(ParseResult::Parsing(Error::InvalidExpression)),\n", "file_path": "src/parser/expressions.rs", "rank": 61, "score": 3.7160535028925232 }, { "content": " todo!()\n\n }\n\n }\n\n\n\n impl From<Operator> for Either<Operator, Literal> {\n\n fn from(from: Operator) -> Self {\n\n Self::Left(from)\n\n }\n\n }\n\n impl From<Literal> for Either<Operator, Literal> {\n\n fn from(from: Literal) -> Self {\n\n Self::Right(from)\n\n }\n\n }\n\n\n\n impl From<Expression> for Either<Literal, Expression> {\n\n fn from(from: Expression) -> Self {\n\n Self::Right(from)\n\n }\n\n }\n", "file_path": "src/types.rs", "rank": 62, "score": 3.643098217206202 }, { "content": " Ok(b) => b,\n\n Err(e) => return Some(ParseResult::Input(e)),\n\n }\n\n };\n\n}\n\n\n\npub(crate) async fn skip_whitespaces<S, E>(input: &mut S) -> Option<Result<(), E>>\n\nwhere\n\n S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>,\n\n{\n\n loop {\n\n let b = match input.next().await? {\n\n Ok(b) => b,\n\n Err(e) => return Some(Err(e)),\n\n };\n\n if b != b' ' {\n\n input.push_back(b);\n\n break;\n\n }\n\n }\n", "file_path": "src/utils.rs", "rank": 63, "score": 3.6408092567587733 }, { "content": " block_on(input),\n\n &[\n\n Ok(GCode::Word(\n\n 'g',\n\n Expression(vec![\n\n Literal::from(32).into(),\n\n Literal::from(-25).into(),\n\n Operator::Add.into(),\n\n Literal::from(-8.32).into(),\n\n Operator::GetParameter.into(),\n\n Operator::Add.into(),\n\n Operator::GetParameter.into(),\n\n ])\n\n .into()\n\n )),\n\n Ok(GCode::Execute)\n\n ]\n\n );\n\n let input = \"G#Cos[90]\\n\".bytes();\n\n assert_eq!(\n", "file_path": "src/parser/test/parse_expressions.rs", "rank": 64, "score": 3.577329213700476 }, { "content": " 'g',\n\n Expression(vec![Literal::from(2.718281828).into(), Operator::Ln.into()]).into()\n\n )),\n\n Ok(GCode::Word(\n\n 'g',\n\n Expression(vec![Literal::from(4.8).into(), Operator::Round.into()]).into()\n\n )),\n\n Ok(GCode::Word(\n\n 'g',\n\n Expression(vec![Literal::from(4).into(), Operator::Sqrt.into()]).into()\n\n )),\n\n ]\n\n );\n\n}\n\n\n", "file_path": "src/parser/test/parse_expressions.rs", "rank": 66, "score": 3.5178369876211546 }, { "content": " 'g',\n\n Expression(vec![Literal::from(90).into(), Operator::Tan.into()]).into()\n\n )),\n\n Ok(GCode::Execute),\n\n Ok(GCode::Word(\n\n 'g',\n\n Expression(vec![Literal::from(0.5).into(), Operator::ACos.into()]).into()\n\n )),\n\n Ok(GCode::Word(\n\n 'g',\n\n Expression(vec![Literal::from(-0.5).into(), Operator::ASin.into()]).into()\n\n )),\n\n Ok(GCode::Word(\n\n 'g',\n\n Expression(vec![\n\n Literal::from(2.3).into(),\n\n Literal::from(28).into(),\n\n Operator::ATan.into()\n\n ])\n\n .into()\n", "file_path": "src/parser/test/parse_expressions.rs", "rank": 67, "score": 3.452666934412481 }, { "content": "#[test]\n\n#[cfg(all(feature = \"optional-value\", not(feature = \"parse-expressions\")))]\n\nfn word_may_not_have_a_value() {\n\n let input = \"G75 Z T48 S P.3\\n\".bytes();\n\n assert_eq!(\n\n block_on(input),\n\n &[\n\n Ok(GCode::Word('g', (75.0).into())),\n\n Ok(GCode::Word('z', RealValue::None)),\n\n Ok(GCode::Word('t', (48.0).into())),\n\n Ok(GCode::Word('s', RealValue::None)),\n\n Ok(GCode::Word('p', (0.3).into())),\n\n Ok(GCode::Execute)\n\n ]\n\n );\n\n}\n\n\n", "file_path": "src/parser/test.rs", "rank": 68, "score": 3.440660431787152 }, { "content": " expects = Expect::BinOpOrCloseBracket;\n\n } else {\n\n break;\n\n }\n\n }\n\n Token::CloseBracket => {\n\n loop {\n\n match stack.pop() {\n\n Some(Stacked::Operator(op)) => postfix.push(op.into()),\n\n Some(Stacked::OpenBracket) => break,\n\n Some(_) | None => unreachable!(),\n\n };\n\n }\n\n // println!(\"CloseBracket: {:?} {:?}\", postfix, stack);\n\n // TODO: use checked arithmetic to prevent panic if depth == 0\n\n depth -= 1;\n\n\n\n if stack\n\n .last()\n\n .map(|&stacked| stacked == Stacked::ATan)\n", "file_path": "src/parser/expressions.rs", "rank": 69, "score": 3.4019542222283587 }, { "content": "//! Q.098 R-.098 S+.098\n\n//! t - 21 . 33 \"\n\n//! // mapping to `Result<u8, Error>` to render error conversion transparent.\n\n//! .bytes().map(Result::<_, Error>::Ok);\n\n//!\n\n//! block_on(async {\n\n//! let mut parser = Parser::new(stream::iter(input));\n\n//!\n\n//! loop {\n\n//! if let Some(res) = parser.next().await {\n\n//! println!(\"{:?}\", res);\n\n//! } else {\n\n//! break;\n\n//! }\n\n//! }\n\n//! });\n\n//! ```\n\n//!\n\n//! ## Error management\n\n//!\n", "file_path": "src/lib.rs", "rank": 70, "score": 3.3954828363538803 }, { "content": " self.state = AsyncParserState::EndOfLine;\n\n break Ok(GCode::Comment(s));\n\n }\n\n _ => {\n\n self.input.push_back(b);\n\n break Ok(try_await!(parse_eol(&mut self.state, &mut self.input)));\n\n }\n\n },\n\n #[cfg(any(feature = \"parse-trailing-comment\", feature = \"parse-checksum\"))]\n\n AsyncParserState::EndOfLine => {\n\n self.input.push_back(b);\n\n break Ok(try_await!(parse_eol(&mut self.state, &mut self.input)));\n\n }\n\n AsyncParserState::ErrorRecovery => match b {\n\n b'\\r' | b'\\n' => {\n\n self.input.push_back(b);\n\n break Ok(try_await!(parse_eol(&mut self.state, &mut self.input)));\n\n }\n\n _ => {}\n\n },\n", "file_path": "src/parser.rs", "rank": 71, "score": 3.3495155493855964 }, { "content": " #[cfg(feature = \"parse-checksum\")]\n\n input: input.xor_summed_push_backable(0),\n\n #[cfg(not(feature = \"parse-checksum\"))]\n\n input: input.push_backable(),\n\n state: AsyncParserState::Start(true),\n\n }\n\n }\n\n pub async fn next(&mut self) -> Option<Result<GCode, E>> {\n\n let res = loop {\n\n let b = match self.input.next().await? {\n\n Ok(b) => b,\n\n Err(err) => return Some(Err(err)),\n\n };\n\n\n\n // println!(\"{:?}: {:?}\", self.state, char::from(b));\n\n match self.state {\n\n AsyncParserState::Start(ref mut first_byte) => match b {\n\n b'\\n' => {\n\n self.input.push_back(b);\n\n break Ok(try_await!(parse_eol(&mut self.state, &mut self.input)));\n", "file_path": "src/parser.rs", "rank": 72, "score": 3.2870828609122795 }, { "content": " )),\n\n Ok(GCode::Execute),\n\n Ok(GCode::Word(\n\n 'g',\n\n Expression(vec![Literal::from(-0.3).into(), Operator::Abs.into()]).into()\n\n )),\n\n Ok(GCode::Word(\n\n 'g',\n\n Expression(vec![Literal::from(32).into(), Operator::Exp.into()]).into()\n\n )),\n\n Ok(GCode::Word(\n\n 'g',\n\n Expression(vec![Literal::from(5.8).into(), Operator::Fix.into()]).into()\n\n )),\n\n Ok(GCode::Word(\n\n 'g',\n\n Expression(vec![Literal::from(4.3).into(), Operator::Fup.into()]).into()\n\n )),\n\n Ok(GCode::Execute),\n\n Ok(GCode::Word(\n", "file_path": "src/parser/test/parse_expressions.rs", "rank": 73, "score": 3.245330098621971 }, { "content": " #[cfg(all(\n\n feature = \"parse-trailing-comment\",\n\n not(feature = \"parse-comments\"),\n\n feature = \"parse-checksum\"\n\n ))]\n\n AsyncParserState::EoLOrTrailingComment => match b {\n\n b';' => try_await_result!(parse_eol_comment(&mut self.input)),\n\n _ => {\n\n self.input.push_back(b);\n\n break Ok(try_await!(parse_eol(&mut self.state, &mut self.input)));\n\n }\n\n },\n\n #[cfg(all(\n\n feature = \"parse-trailing-comment\",\n\n feature = \"parse-comments\",\n\n feature = \"parse-checksum\"\n\n ))]\n\n AsyncParserState::EoLOrTrailingComment => match b {\n\n b';' => {\n\n let s = try_await!(parse_eol_comment(&mut self.input));\n", "file_path": "src/parser.rs", "rank": 74, "score": 3.1752386832436716 }, { "content": " }};\n\n ($input:expr, $b:expr, $($(#[$($m:tt)*])* $p:pat => { $($rest:tt)* })* ) => {{\n\n match $b.to_ascii_lowercase() {\n\n $(\n\n $(#[$($m)*])*\n\n $p => {\n\n match_operator!(@ $input, $($rest)*)\n\n }\n\n )*\n\n #[allow(unreachable_patterns)]\n\n b => return Some(ParseResult::Parsing(Error::UnexpectedByte(b))),\n\n }\n\n }}\n\n}\n\n\n\nasync fn tokenize<S, E>(input: &mut S, expect: Expect) -> Option<ParseResult<Token, E>>\n\nwhere\n\n S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>,\n\n{\n\n let b = match input.next().await? {\n", "file_path": "src/parser/expressions.rs", "rank": 75, "score": 3.1558492196844687 }, { "content": " closeBracket =>\n\n while stack is not empty and stack top ≠ (,\n\n do pop and add item from stack to postfix expression\n\n done\n\n\n\n if stack.is_empty => error !\n\n\n\n pop ( also from the stack\n\n operator(op) =>\n\n while !stack.is_empty AND\n\n precedence(op) < precedence(stack.top) OR\n\n (precedence(op) == precedence(stack.top) AND !op.is_right_associative) do\n\n pop and add into postfix expression\n\n done\n\n\n\n stack.push(op)\n\n done\n\n\n\n while the stack contains some remaining token, do\n\n pop and add to the postfix expression\n", "file_path": "src/parser/expressions.rs", "rank": 76, "score": 3.122228951180225 }, { "content": " b'\\r' | b'\\n' => {\n\n input.push_back(b);\n\n break Some(match String::from_utf8(v) {\n\n Ok(s) => ParseResult::Ok(s),\n\n Err(_) => Error::InvalidUTF8String.into(),\n\n });\n\n }\n\n b => v.push(b),\n\n }\n\n }\n\n}\n\n\n\n#[cfg(not(feature = \"parse-comments\"))]\n\nasync fn parse_inline_comment<S, E>(input: &mut S) -> Option<ParseResult<Comment, E>>\n\nwhere\n\n S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>,\n\n{\n\n loop {\n\n match try_result!(input.next()) {\n\n b'\\\\' => {\n", "file_path": "src/parser.rs", "rank": 77, "score": 3.076253542367254 }, { "content": " }\n\n\n\n pub fn precedence(&self) -> Precedence {\n\n match *self {\n\n Self::Add | Self::Substract | Self::And | Self::Or | Self::Xor => {\n\n Precedence::Group1\n\n }\n\n Self::Multiply | Self::Divide | Self::Modulus => Precedence::Group2,\n\n Self::Power => Precedence::Group3,\n\n #[cfg(feature = \"parse-parameters\")]\n\n Self::GetParameter => Precedence::Group4,\n\n Self::Cos\n\n | Self::Sin\n\n | Self::Tan\n\n | Self::ACos\n\n | Self::ASin\n\n | Self::ATan\n\n | Self::Abs\n\n | Self::Exp\n\n | Self::Fix\n", "file_path": "src/types.rs", "rank": 78, "score": 3.0608966719001507 }, { "content": " try_result!(input.next());\n\n }\n\n b'(' => break Some(Error::UnexpectedByte(b'(').into()),\n\n b')' => break Some(ParseResult::Ok(())),\n\n _ => {}\n\n }\n\n }\n\n}\n\n\n\n#[cfg(feature = \"parse-comments\")]\n\nasync fn parse_inline_comment<S, E>(input: &mut S) -> Option<ParseResult<Comment, E>>\n\nwhere\n\n S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>,\n\n{\n\n let mut v = Vec::new();\n\n loop {\n\n let b = try_result!(input.next());\n\n match b {\n\n b'\\\\' => {\n\n v.push(try_result!(input.next()));\n", "file_path": "src/parser.rs", "rank": 79, "score": 3.043128338643029 }, { "content": "#[test]\n\n#[cfg(feature = \"optional-value\")]\n\nfn parameter_set_may_have_no_value() {\n\n let input = \"#12= g\\n#34=\\n\".bytes();\n\n assert_eq!(\n\n block_on(input),\n\n &[\n\n Ok(GCode::ParameterSet(\n\n Literal::from(12.).into(),\n\n RealValue::None\n\n )),\n\n Ok(GCode::Word('g', RealValue::None)),\n\n Ok(GCode::Execute),\n\n Ok(GCode::ParameterSet(\n\n Literal::from(34.).into(),\n\n RealValue::None\n\n )),\n\n Ok(GCode::Execute),\n\n ]\n\n );\n\n}\n\n\n", "file_path": "src/parser/test/parse_parameters.rs", "rank": 80, "score": 3.0119248392497315 }, { "content": "#[test]\n\n#[cfg(feature = \"string-value\")]\n\nfn parse_param_with_string_index() {\n\n let input = r#\"#\"hello\"=\"world\" g#\"hello\"\"#.bytes();\n\n assert_eq!(\n\n block_on(input),\n\n &[\n\n Ok(GCode::ParameterSet(\n\n Literal::from(\"hello\".to_owned()).into(),\n\n Literal::from(\"world\".to_owned()).into()\n\n )),\n\n Ok(GCode::Word(\n\n 'g',\n\n Expression(vec![\n\n Literal::from(\"hello\".to_owned()).into(),\n\n Operator::GetParameter.into()\n\n ])\n\n .into()\n\n )),\n\n ]\n\n );\n\n}\n", "file_path": "src/parser/test/parse_parameters.rs", "rank": 81, "score": 3.0119248392497315 }, { "content": "#[test]\n\n#[cfg(feature = \"optional-value\")]\n\nfn values_are_always_required_for_parameters_id() {\n\n let input = \"G#\\n\".bytes();\n\n assert_eq!(block_on(input), &[Err(Error::UnexpectedByte(b'\\n'))]);\n\n\n\n let input = \"#=\".bytes();\n\n assert_eq!(block_on(input), &[Err(Error::UnexpectedByte(b'='))]);\n\n}\n\n\n", "file_path": "src/parser/test/parse_parameters.rs", "rank": 82, "score": 3.0119248392497315 }, { "content": "#[test]\n\n#[cfg(feature = \"string-value\")]\n\nfn value_may_be_strings() {\n\n let input = r#\"G \"Hello\\\"World\\\"\" \"#.bytes();\n\n assert_eq!(\n\n block_on(input),\n\n &[Ok(GCode::Word('g', \"Hello\\\"World\\\"\".to_string().into()))]\n\n )\n\n}\n", "file_path": "src/parser/test.rs", "rank": 83, "score": 3.0119248392497315 }, { "content": "#[test]\n\n#[cfg(feature = \"parse-parameters\")]\n\nfn parse_expressions_with_parameter_get() {\n\n let input = \"G#[32+25]\\n\".bytes();\n\n assert_eq!(\n\n block_on(input),\n\n &[\n\n Ok(GCode::Word(\n\n 'g',\n\n Expression(vec![\n\n Literal::from(32).into(),\n\n Literal::from(25).into(),\n\n Operator::Add.into(),\n\n Operator::GetParameter.into(),\n\n ])\n\n .into()\n\n )),\n\n Ok(GCode::Execute)\n\n ]\n\n );\n\n let input = \"G # [ + 32 + - 25 + # - 8.32 ] \\n\".bytes();\n\n assert_eq!(\n", "file_path": "src/parser/test/parse_expressions.rs", "rank": 84, "score": 3.0119248392497315 }, { "content": "use super::{block_on, to_gcode_comment, GCode};\n\n\n\n#[test]\n", "file_path": "src/parser/test/parse_trailing_comment.rs", "rank": 85, "score": 3.0061246779838373 }, { "content": "#[test]\n\n#[cfg(feature = \"parse-trailing-comment\")]\n\nfn trailing_comment_are_not_covered_by_checksum() {\n\n let msg = \" trailing comments may contain (or have?) parenthesis\";\n\n let input = format!(\"G0* 119 ;{}\\n\", msg);\n\n let input = input.bytes();\n\n\n\n let mut expected_output = vec![Ok(GCode::Word('g', (0.).into()))];\n\n expected_output.extend(to_gcode_comment(msg).iter().cloned());\n\n expected_output.push(Ok(GCode::Execute));\n\n assert_eq!(block_on(input), expected_output)\n\n}\n", "file_path": "src/parser/test/parse_checksum.rs", "rank": 86, "score": 2.94766010591773 }, { "content": " block_on(input),\n\n &[\n\n Ok(GCode::Word(\n\n 'g',\n\n Expression(vec![\n\n Literal::from(90).into(),\n\n Operator::Cos.into(),\n\n Operator::GetParameter.into(),\n\n ])\n\n .into()\n\n )),\n\n Ok(GCode::Execute)\n\n ]\n\n );\n\n let input = \"G # atan [ 180 / 2 ] / [ 75 + 2 ] \\n\".bytes();\n\n assert_eq!(\n\n block_on(input),\n\n &[\n\n Ok(GCode::Word(\n\n 'g',\n", "file_path": "src/parser/test/parse_expressions.rs", "rank": 87, "score": 2.9054091943253724 }, { "content": " done\n\n return postfix\n\n End\n\n */\n\n\n\n let mut expects = Expect::UnaryOrLiteralOrExpr;\n\n let mut stack: Vec<Stacked> = Vec::new();\n\n let mut postfix: Vec<ExprItem> = Vec::new();\n\n let mut depth = 0;\n\n\n\n loop {\n\n try_result!(skip_whitespaces(input));\n\n //println!(\"{:?}: {:?} {:?}\", expects, postfix, stack);\n\n\n\n // lexical analysis\n\n let token = match tokenize(input, expects).await? {\n\n ParseResult::Ok(tok) => tok,\n\n #[cfg(feature = \"optional-value\")]\n\n ParseResult::Parsing(Error::UnexpectedByte(b))\n\n if postfix.is_empty() && stack.is_empty() =>\n", "file_path": "src/parser/expressions.rs", "rank": 88, "score": 2.8017717442316785 }, { "content": " let mut parser = Parser::new(stream::iter(input));\n\n\n\n assert_eq!(\n\n futures_executor::block_on(\n\n stream::unfold(\n\n &mut parser,\n\n |p| async move { p.next().await.map(|w| (w, p)) },\n\n )\n\n .collect::<Vec<_>>()\n\n ),\n\n [\n\n Ok(GCode::Word('g', (12).into())),\n\n Err(TestError::SomeError),\n\n Ok(GCode::Execute)\n\n ]\n\n )\n\n}\n\n\n", "file_path": "src/parser/test.rs", "rank": 89, "score": 2.692505403798392 }, { "content": " }\n\n };\n\n // eprintln!(\"{}:{} {:?}\", file!(), line!(), res);\n\n if res.is_err() {\n\n self.state = AsyncParserState::ErrorRecovery;\n\n }\n\n Some(res)\n\n }\n\n}\n", "file_path": "src/parser.rs", "rank": 90, "score": 2.681735064825144 }, { "content": " }\n\n }\n\n\n\n impl<S> XorSumPushBack<S>\n\n where\n\n S: TryStream,\n\n S::Ok: core::ops::BitXorAssign + Copy,\n\n {\n\n pub fn new(stream: S, initial_sum: S::Ok) -> Self {\n\n Self {\n\n stream,\n\n head: None,\n\n sum: initial_sum,\n\n }\n\n }\n\n\n\n pub fn reset_sum(&mut self, initial_sum: S::Ok) {\n\n self.sum = initial_sum;\n\n }\n\n\n", "file_path": "src/stream.rs", "rank": 91, "score": 2.5432942476253775 }, { "content": " Xor,\n\n\n\n Modulus,\n\n\n\n // Unary operators\n\n Cos,\n\n Sin,\n\n Tan,\n\n ACos,\n\n ASin,\n\n ATan, // Atan is kind of binary\n\n\n\n Abs,\n\n Exp,\n\n Fix,\n\n Fup,\n\n Ln,\n\n Round,\n\n Sqrt,\n\n\n", "file_path": "src/types.rs", "rank": 92, "score": 2.4416567442669046 }, { "content": " use super::{PushBack, PushBackable};\n\n use futures::stream::{self, StreamExt};\n\n\n\n #[test]\n\n fn the_stream_works() {\n\n let data = [1, 2, 4, 8, 16, 32, 64, 128]\n\n .iter()\n\n .copied()\n\n .map(Result::<_, core::convert::Infallible>::Ok)\n\n .collect::<Vec<_>>();\n\n let mut strm = PushBack::new(stream::iter(data.iter().copied()));\n\n assert_eq!(\n\n futures_executor::block_on((&mut strm).collect::<Vec<_>>()),\n\n data\n\n );\n\n }\n\n\n\n #[test]\n\n fn pushbacked_value_come_out_first() {\n\n let data = [1, 2, 4, 8, 16, 32, 64, 128]\n", "file_path": "src/stream.rs", "rank": 93, "score": 2.3827567026576317 }, { "content": " * (precedence(op) == precedence(stack.top) AND !op.is_right_associative) do\n\n * pop and add into postfix expression\n\n * done\n\n */\n\n while stack\n\n .last()\n\n .map(|tok| match tok {\n\n Stacked::Operator(stacked_op) => {\n\n op.precedence() < stacked_op.precedence()\n\n || (op.precedence() == stacked_op.precedence()\n\n && op.associativity() == Associativity::Left)\n\n }\n\n Stacked::OpenBracket => false,\n\n _ => unreachable!(),\n\n })\n\n .unwrap_or(false)\n\n {\n\n postfix.push(\n\n match stack.pop().unwrap() {\n\n Stacked::Operator(op) => op,\n", "file_path": "src/parser/expressions.rs", "rank": 94, "score": 2.353329781241546 }, { "content": " };\n\n match b {\n\n b'\\r' | b'\\n' => {\n\n input.push_back(b);\n\n break Some(Ok(()));\n\n }\n\n _ => {}\n\n }\n\n }\n\n}\n\n\n\n#[cfg(all(feature = \"parse-trailing-comment\", feature = \"parse-comments\"))]\n\nasync fn parse_eol_comment<S, E>(input: &mut S) -> Option<ParseResult<Comment, E>>\n\nwhere\n\n S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>,\n\n{\n\n let mut v = Vec::new();\n\n loop {\n\n let b = try_result!(input.next());\n\n match b {\n", "file_path": "src/parser.rs", "rank": 95, "score": 2.3159220110663 }, { "content": " mod test {\n\n use super::{PushBackable, XorSumPushBack};\n\n use futures::stream::{self, StreamExt};\n\n\n\n #[test]\n\n fn the_stream_works_and_the_xorsum_is_computed() {\n\n let data = [1, 2, 4, 8, 16, 32, 64, 128]\n\n .iter()\n\n .copied()\n\n .map(Result::<_, core::convert::Infallible>::Ok)\n\n .collect::<Vec<_>>();\n\n let mut strm = XorSumPushBack::new(stream::iter(data.iter().copied()), 0);\n\n assert_eq!(\n\n futures_executor::block_on((&mut strm).collect::<Vec<_>>()),\n\n data\n\n );\n\n assert_eq!(strm.sum(), 0xFF);\n\n }\n\n\n\n #[test]\n", "file_path": "src/stream.rs", "rank": 96, "score": 2.237581702429221 }, { "content": " }\n\n }\n\n\n\n impl<S> Stream for PushBack<S>\n\n where\n\n S: TryStream,\n\n {\n\n type Item = Result<S::Ok, S::Error>;\n\n fn poll_next(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Option<Self::Item>> {\n\n let this = self.project();\n\n if let Some(v) = this.val.take() {\n\n Poll::Ready(Some(Ok(v)))\n\n } else {\n\n this.stream.try_poll_next(ctx)\n\n }\n\n }\n\n }\n\n\n\n #[cfg(test)]\n\n mod test {\n", "file_path": "src/stream.rs", "rank": 97, "score": 1.7645381525973751 }, { "content": " b' ' => {}\n\n b => break Error::UnexpectedByte(b).into(),\n\n }\n\n })\n\n}\n\n\n\nmacro_rules! try_await {\n\n ($input:expr) => {\n\n match $input.await? {\n\n ParseResult::Ok(ok) => ok,\n\n ParseResult::Parsing(err) => break Err(err.into()),\n\n ParseResult::Input(err) => break Err(err.into()),\n\n }\n\n };\n\n}\n\n\n\nmacro_rules! try_await_result {\n\n ($input:expr) => {\n\n match $input.await? {\n\n Ok(ok) => ok,\n", "file_path": "src/parser.rs", "rank": 98, "score": 1.7224589446204521 }, { "content": " S::Ok: core::ops::BitXorAssign + Copy,\n\n {\n\n type Item = Result<S::Ok, S::Error>;\n\n\n\n fn poll_next(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Option<Self::Item>> {\n\n let this = self.project();\n\n let item = if let Some(item) = this.head.take() {\n\n item\n\n } else {\n\n match this.stream.try_poll_next(ctx) {\n\n Poll::Ready(Some(Ok(item))) => item,\n\n other => return other,\n\n }\n\n };\n\n *this.sum ^= item;\n\n Poll::Ready(Some(Ok(item)))\n\n }\n\n }\n\n\n\n #[cfg(test)]\n", "file_path": "src/stream.rs", "rank": 99, "score": 1.5897688422425569 } ]
Rust
core/src/snapshot_packager_service.rs
glottologist/solana
770bdec924481038ed93962bd79da6ccc0e799bf
use solana_gossip::cluster_info::{ClusterInfo, MAX_SNAPSHOT_HASHES}; use solana_runtime::{ snapshot_archive_info::SnapshotArchiveInfoGetter, snapshot_package::PendingSnapshotPackage, snapshot_utils, }; use solana_sdk::{clock::Slot, hash::Hash}; use std::{ sync::{ atomic::{AtomicBool, Ordering}, Arc, }, thread::{self, Builder, JoinHandle}, time::Duration, }; pub struct SnapshotPackagerService { t_snapshot_packager: JoinHandle<()>, } impl SnapshotPackagerService { pub fn new( pending_snapshot_package: PendingSnapshotPackage, starting_snapshot_hash: Option<(Slot, Hash)>, exit: &Arc<AtomicBool>, cluster_info: &Arc<ClusterInfo>, maximum_snapshots_to_retain: usize, ) -> Self { let exit = exit.clone(); let cluster_info = cluster_info.clone(); let t_snapshot_packager = Builder::new() .name("snapshot-packager".to_string()) .spawn(move || { let mut hashes = vec![]; if let Some(starting_snapshot_hash) = starting_snapshot_hash { hashes.push(starting_snapshot_hash); } cluster_info.push_snapshot_hashes(hashes.clone()); loop { if exit.load(Ordering::Relaxed) { break; } let snapshot_package = pending_snapshot_package.lock().unwrap().take(); if snapshot_package.is_none() { std::thread::sleep(Duration::from_millis(100)); continue; } let snapshot_package = snapshot_package.unwrap(); snapshot_utils::archive_snapshot_package( &snapshot_package, maximum_snapshots_to_retain, ) .expect("failed to archive snapshot package"); hashes.push((snapshot_package.slot(), *snapshot_package.hash())); while hashes.len() > MAX_SNAPSHOT_HASHES { hashes.remove(0); } cluster_info.push_snapshot_hashes(hashes.clone()); } }) .unwrap(); Self { t_snapshot_packager, } } pub fn join(self) -> thread::Result<()> { self.t_snapshot_packager.join() } } #[cfg(test)] mod tests { use super::*; use bincode::serialize_into; use solana_runtime::{ accounts_db::AccountStorageEntry, bank::BankSlotDelta, snapshot_archive_info::SnapshotArchiveInfo, snapshot_package::{SnapshotPackage, SnapshotType}, snapshot_utils::{self, ArchiveFormat, SnapshotVersion, SNAPSHOT_STATUS_CACHE_FILE_NAME}, }; use solana_sdk::hash::Hash; use std::{ fs::{self, remove_dir_all, OpenOptions}, io::Write, path::{Path, PathBuf}, }; use tempfile::TempDir; fn make_tmp_dir_path() -> PathBuf { let out_dir = std::env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_string()); let path = PathBuf::from(format!("{}/tmp/test_package_snapshots", out_dir)); let _ignored = std::fs::remove_dir_all(&path); let _ignored = std::fs::remove_file(&path); path } #[test] fn test_package_snapshots_relative_ledger_path() { let temp_dir = make_tmp_dir_path(); create_and_verify_snapshot(&temp_dir); remove_dir_all(temp_dir).expect("should remove tmp dir"); } #[test] fn test_package_snapshots() { create_and_verify_snapshot(TempDir::new().unwrap().path()) } fn create_and_verify_snapshot(temp_dir: &Path) { let accounts_dir = temp_dir.join("accounts"); let snapshots_dir = temp_dir.join("snapshots"); let snapshot_archives_dir = temp_dir.join("snapshots_output"); fs::create_dir_all(&snapshot_archives_dir).unwrap(); fs::create_dir_all(&accounts_dir).unwrap(); let storage_entries: Vec<_> = (0..5) .map(|i| Arc::new(AccountStorageEntry::new(&accounts_dir, 0, i, 10))) .collect(); let snapshots_paths: Vec<_> = (0..5) .map(|i| { let snapshot_file_name = format!("{}", i); let snapshots_dir = snapshots_dir.join(&snapshot_file_name); fs::create_dir_all(&snapshots_dir).unwrap(); let fake_snapshot_path = snapshots_dir.join(&snapshot_file_name); let mut fake_snapshot_file = OpenOptions::new() .read(true) .write(true) .create(true) .open(&fake_snapshot_path) .unwrap(); fake_snapshot_file.write_all(b"Hello, world!").unwrap(); fake_snapshot_path }) .collect(); let link_snapshots_dir = tempfile::tempdir_in(&temp_dir).unwrap(); for snapshots_path in snapshots_paths { let snapshot_file_name = snapshots_path.file_name().unwrap(); let link_snapshots_dir = link_snapshots_dir.path().join(snapshot_file_name); fs::create_dir_all(&link_snapshots_dir).unwrap(); let link_path = link_snapshots_dir.join(snapshot_file_name); fs::hard_link(&snapshots_path, &link_path).unwrap(); } let slot = 42; let hash = Hash::default(); let archive_format = ArchiveFormat::TarBzip2; let output_tar_path = snapshot_utils::build_full_snapshot_archive_path( snapshot_archives_dir, slot, &hash, archive_format, ); let snapshot_package = SnapshotPackage { snapshot_archive_info: SnapshotArchiveInfo { path: output_tar_path.clone(), slot, hash, archive_format, }, block_height: slot, slot_deltas: vec![], snapshot_links: link_snapshots_dir, snapshot_storages: vec![storage_entries], snapshot_version: SnapshotVersion::default(), snapshot_type: SnapshotType::FullSnapshot, }; snapshot_utils::archive_snapshot_package( &snapshot_package, snapshot_utils::DEFAULT_MAX_FULL_SNAPSHOT_ARCHIVES_TO_RETAIN, ) .unwrap(); let dummy_slot_deltas: Vec<BankSlotDelta> = vec![]; snapshot_utils::serialize_snapshot_data_file( &snapshots_dir.join(SNAPSHOT_STATUS_CACHE_FILE_NAME), |stream| { serialize_into(stream, &dummy_slot_deltas)?; Ok(()) }, ) .unwrap(); snapshot_utils::verify_snapshot_archive( output_tar_path, snapshots_dir, accounts_dir, archive_format, ); } }
use solana_gossip::cluster_info::{ClusterInfo, MAX_SNAPSHOT_HASHES}; use solana_runtime::{ snapshot_archive_info::SnapshotArchiveInfoGetter, snapshot_package::PendingSnapshotPackage, snapshot_utils, }; use solana_sdk::{clock::Slot, hash::Hash}; use std::{ sync::{ atomic::{AtomicBool, Ordering}, Arc, }, thread::{self, Builder, JoinHandle}, time::Duration, }; pub struct SnapshotPackagerService { t_snapshot_packager: JoinHandle<()>, } impl SnapshotPackagerService { pub fn new( pending_snapshot_package: PendingSnapshotPackage, starting_snapshot_hash: Option<(Slot, Hash)>, exit: &Arc<AtomicBool>, cluster_info: &Arc<ClusterInfo>, maximum_snapshots_to_retain: usize, ) -> Self { let exit = exit.clone(); let cluster_info = cluster_info.clone(); let t_snapshot_packager = Builder::new() .name("snapshot-packager".to_string()) .spawn(move || { let mut hashes = vec![];
cluster_info.push_snapshot_hashes(hashes.clone()); loop { if exit.load(Ordering::Relaxed) { break; } let snapshot_package = pending_snapshot_package.lock().unwrap().take(); if snapshot_package.is_none() { std::thread::sleep(Duration::from_millis(100)); continue; } let snapshot_package = snapshot_package.unwrap(); snapshot_utils::archive_snapshot_package( &snapshot_package, maximum_snapshots_to_retain, ) .expect("failed to archive snapshot package"); hashes.push((snapshot_package.slot(), *snapshot_package.hash())); while hashes.len() > MAX_SNAPSHOT_HASHES { hashes.remove(0); } cluster_info.push_snapshot_hashes(hashes.clone()); } }) .unwrap(); Self { t_snapshot_packager, } } pub fn join(self) -> thread::Result<()> { self.t_snapshot_packager.join() } } #[cfg(test)] mod tests { use super::*; use bincode::serialize_into; use solana_runtime::{ accounts_db::AccountStorageEntry, bank::BankSlotDelta, snapshot_archive_info::SnapshotArchiveInfo, snapshot_package::{SnapshotPackage, SnapshotType}, snapshot_utils::{self, ArchiveFormat, SnapshotVersion, SNAPSHOT_STATUS_CACHE_FILE_NAME}, }; use solana_sdk::hash::Hash; use std::{ fs::{self, remove_dir_all, OpenOptions}, io::Write, path::{Path, PathBuf}, }; use tempfile::TempDir; fn make_tmp_dir_path() -> PathBuf { let out_dir = std::env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_string()); let path = PathBuf::from(format!("{}/tmp/test_package_snapshots", out_dir)); let _ignored = std::fs::remove_dir_all(&path); let _ignored = std::fs::remove_file(&path); path } #[test] fn test_package_snapshots_relative_ledger_path() { let temp_dir = make_tmp_dir_path(); create_and_verify_snapshot(&temp_dir); remove_dir_all(temp_dir).expect("should remove tmp dir"); } #[test] fn test_package_snapshots() { create_and_verify_snapshot(TempDir::new().unwrap().path()) } fn create_and_verify_snapshot(temp_dir: &Path) { let accounts_dir = temp_dir.join("accounts"); let snapshots_dir = temp_dir.join("snapshots"); let snapshot_archives_dir = temp_dir.join("snapshots_output"); fs::create_dir_all(&snapshot_archives_dir).unwrap(); fs::create_dir_all(&accounts_dir).unwrap(); let storage_entries: Vec<_> = (0..5) .map(|i| Arc::new(AccountStorageEntry::new(&accounts_dir, 0, i, 10))) .collect(); let snapshots_paths: Vec<_> = (0..5) .map(|i| { let snapshot_file_name = format!("{}", i); let snapshots_dir = snapshots_dir.join(&snapshot_file_name); fs::create_dir_all(&snapshots_dir).unwrap(); let fake_snapshot_path = snapshots_dir.join(&snapshot_file_name); let mut fake_snapshot_file = OpenOptions::new() .read(true) .write(true) .create(true) .open(&fake_snapshot_path) .unwrap(); fake_snapshot_file.write_all(b"Hello, world!").unwrap(); fake_snapshot_path }) .collect(); let link_snapshots_dir = tempfile::tempdir_in(&temp_dir).unwrap(); for snapshots_path in snapshots_paths { let snapshot_file_name = snapshots_path.file_name().unwrap(); let link_snapshots_dir = link_snapshots_dir.path().join(snapshot_file_name); fs::create_dir_all(&link_snapshots_dir).unwrap(); let link_path = link_snapshots_dir.join(snapshot_file_name); fs::hard_link(&snapshots_path, &link_path).unwrap(); } let slot = 42; let hash = Hash::default(); let archive_format = ArchiveFormat::TarBzip2; let output_tar_path = snapshot_utils::build_full_snapshot_archive_path( snapshot_archives_dir, slot, &hash, archive_format, ); let snapshot_package = SnapshotPackage { snapshot_archive_info: SnapshotArchiveInfo { path: output_tar_path.clone(), slot, hash, archive_format, }, block_height: slot, slot_deltas: vec![], snapshot_links: link_snapshots_dir, snapshot_storages: vec![storage_entries], snapshot_version: SnapshotVersion::default(), snapshot_type: SnapshotType::FullSnapshot, }; snapshot_utils::archive_snapshot_package( &snapshot_package, snapshot_utils::DEFAULT_MAX_FULL_SNAPSHOT_ARCHIVES_TO_RETAIN, ) .unwrap(); let dummy_slot_deltas: Vec<BankSlotDelta> = vec![]; snapshot_utils::serialize_snapshot_data_file( &snapshots_dir.join(SNAPSHOT_STATUS_CACHE_FILE_NAME), |stream| { serialize_into(stream, &dummy_slot_deltas)?; Ok(()) }, ) .unwrap(); snapshot_utils::verify_snapshot_archive( output_tar_path, snapshots_dir, accounts_dir, archive_format, ); } }
if let Some(starting_snapshot_hash) = starting_snapshot_hash { hashes.push(starting_snapshot_hash); }
if_condition
[ { "content": "#[cfg(feature = \"full\")]\n\npub fn new_rand<R: ?Sized>(rng: &mut R) -> Hash\n\nwhere\n\n R: rand::Rng,\n\n{\n\n let mut buf = [0u8; HASH_BYTES];\n\n rng.fill(&mut buf);\n\n Hash::new(&buf)\n\n}\n", "file_path": "sdk/src/hash.rs", "rank": 0, "score": 337905.97106482985 }, { "content": "#[allow(clippy::same_item_push)]\n\npub fn create_ticks(num_ticks: u64, hashes_per_tick: u64, mut hash: Hash) -> Vec<Entry> {\n\n let mut ticks = Vec::with_capacity(num_ticks as usize);\n\n for _ in 0..num_ticks {\n\n let new_tick = next_entry_mut(&mut hash, hashes_per_tick, vec![]);\n\n ticks.push(new_tick);\n\n }\n\n\n\n ticks\n\n}\n\n\n", "file_path": "entry/src/entry.rs", "rank": 1, "score": 333111.5411683656 }, { "content": "pub fn next_entry_mut(start: &mut Hash, num_hashes: u64, transactions: Vec<Transaction>) -> Entry {\n\n let entry = Entry::new(start, num_hashes, transactions);\n\n *start = entry.hash;\n\n entry\n\n}\n\n\n", "file_path": "entry/src/entry.rs", "rank": 2, "score": 332319.1064290006 }, { "content": "/// Spend and verify from every node in the network\n\npub fn spend_and_verify_all_nodes<S: ::std::hash::BuildHasher + Sync + Send>(\n\n entry_point_info: &ContactInfo,\n\n funding_keypair: &Keypair,\n\n nodes: usize,\n\n ignore_nodes: HashSet<Pubkey, S>,\n\n socket_addr_space: SocketAddrSpace,\n\n) {\n\n let cluster_nodes =\n\n discover_cluster(&entry_point_info.gossip, nodes, socket_addr_space).unwrap();\n\n assert!(cluster_nodes.len() >= nodes);\n\n let ignore_nodes = Arc::new(ignore_nodes);\n\n cluster_nodes.par_iter().for_each(|ingress_node| {\n\n if ignore_nodes.contains(&ingress_node.id) {\n\n return;\n\n }\n\n let random_keypair = Keypair::new();\n\n let client = create_client(ingress_node.client_facing_addr(), VALIDATOR_PORT_RANGE);\n\n let bal = client\n\n .poll_get_balance_with_commitment(\n\n &funding_keypair.pubkey(),\n", "file_path": "local-cluster/src/cluster_tests.rs", "rank": 3, "score": 325339.6603179736 }, { "content": "#[allow(clippy::same_item_push)]\n\npub fn create_random_ticks(num_ticks: u64, max_hashes_per_tick: u64, mut hash: Hash) -> Vec<Entry> {\n\n let mut ticks = Vec::with_capacity(num_ticks as usize);\n\n for _ in 0..num_ticks {\n\n let hashes_per_tick = thread_rng().gen_range(1, max_hashes_per_tick);\n\n let new_tick = next_entry_mut(&mut hash, hashes_per_tick, vec![]);\n\n ticks.push(new_tick);\n\n }\n\n\n\n ticks\n\n}\n\n\n", "file_path": "entry/src/entry.rs", "rank": 4, "score": 324240.56020049425 }, { "content": "pub fn verify_balances<S: ::std::hash::BuildHasher>(\n\n expected_balances: HashMap<Pubkey, u64, S>,\n\n node: &ContactInfo,\n\n) {\n\n let client = create_client(node.client_facing_addr(), VALIDATOR_PORT_RANGE);\n\n for (pk, b) in expected_balances {\n\n let bal = client\n\n .poll_get_balance_with_commitment(&pk, CommitmentConfig::processed())\n\n .expect(\"balance in source\");\n\n assert_eq!(bal, b);\n\n }\n\n}\n\n\n", "file_path": "local-cluster/src/cluster_tests.rs", "rank": 5, "score": 288111.77764382644 }, { "content": "/// Withdraw funds from the vote account\n\npub fn withdraw<S: std::hash::BuildHasher>(\n\n vote_account: &KeyedAccount,\n\n lamports: u64,\n\n to_account: &KeyedAccount,\n\n signers: &HashSet<Pubkey, S>,\n\n) -> Result<(), InstructionError> {\n\n let vote_state: VoteState =\n\n State::<VoteStateVersions>::state(vote_account)?.convert_to_current();\n\n\n\n verify_authorized_signer(&vote_state.authorized_withdrawer, signers)?;\n\n\n\n match vote_account.lamports()?.cmp(&lamports) {\n\n Ordering::Less => return Err(InstructionError::InsufficientFunds),\n\n Ordering::Equal => {\n\n // Deinitialize upon zero-balance\n\n vote_account.set_state(&VoteStateVersions::new_current(VoteState::default()))?;\n\n }\n\n _ => (),\n\n }\n\n vote_account\n\n .try_account_ref_mut()?\n\n .checked_sub_lamports(lamports)?;\n\n to_account\n\n .try_account_ref_mut()?\n\n .checked_add_lamports(lamports)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "programs/vote/src/vote_state/mod.rs", "rank": 6, "score": 288111.77764382644 }, { "content": "/// Authorize the given pubkey to withdraw or sign votes. This may be called multiple times,\n\n/// but will implicitly withdraw authorization from the previously authorized\n\n/// key\n\npub fn authorize<S: std::hash::BuildHasher>(\n\n vote_account: &KeyedAccount,\n\n authorized: &Pubkey,\n\n vote_authorize: VoteAuthorize,\n\n signers: &HashSet<Pubkey, S>,\n\n clock: &Clock,\n\n) -> Result<(), InstructionError> {\n\n let mut vote_state: VoteState =\n\n State::<VoteStateVersions>::state(vote_account)?.convert_to_current();\n\n\n\n // current authorized signer must say \"yay\"\n\n match vote_authorize {\n\n VoteAuthorize::Voter => {\n\n vote_state.set_new_authorized_voter(\n\n authorized,\n\n clock.epoch,\n\n clock.leader_schedule_epoch + 1,\n\n |epoch_authorized_voter| verify_authorized_signer(&epoch_authorized_voter, signers),\n\n )?;\n\n }\n\n VoteAuthorize::Withdrawer => {\n\n verify_authorized_signer(&vote_state.authorized_withdrawer, signers)?;\n\n vote_state.authorized_withdrawer = *authorized;\n\n }\n\n }\n\n\n\n vote_account.set_state(&VoteStateVersions::new_current(vote_state))\n\n}\n\n\n", "file_path": "programs/vote/src/vote_state/mod.rs", "rank": 7, "score": 288111.77764382644 }, { "content": "/// Initialize the vote_state for a vote account\n\n/// Assumes that the account is being init as part of a account creation or balance transfer and\n\n/// that the transaction must be signed by the staker's keys\n\npub fn initialize_account<S: std::hash::BuildHasher>(\n\n vote_account: &KeyedAccount,\n\n vote_init: &VoteInit,\n\n signers: &HashSet<Pubkey, S>,\n\n clock: &Clock,\n\n check_data_size: bool,\n\n) -> Result<(), InstructionError> {\n\n if check_data_size && vote_account.data_len()? != VoteState::size_of() {\n\n return Err(InstructionError::InvalidAccountData);\n\n }\n\n let versioned = State::<VoteStateVersions>::state(vote_account)?;\n\n\n\n if !versioned.is_uninitialized() {\n\n return Err(InstructionError::AccountAlreadyInitialized);\n\n }\n\n\n\n // node must agree to accept this vote account\n\n verify_authorized_signer(&vote_init.node_pubkey, signers)?;\n\n\n\n vote_account.set_state(&VoteStateVersions::new_current(VoteState::new(\n\n vote_init, clock,\n\n )))\n\n}\n\n\n", "file_path": "programs/vote/src/vote_state/mod.rs", "rank": 8, "score": 283352.23361154663 }, { "content": "/// Update the vote account's commission\n\npub fn update_commission<S: std::hash::BuildHasher>(\n\n vote_account: &KeyedAccount,\n\n commission: u8,\n\n signers: &HashSet<Pubkey, S>,\n\n) -> Result<(), InstructionError> {\n\n let mut vote_state: VoteState =\n\n State::<VoteStateVersions>::state(vote_account)?.convert_to_current();\n\n\n\n // current authorized withdrawer must say \"yay\"\n\n verify_authorized_signer(&vote_state.authorized_withdrawer, signers)?;\n\n\n\n vote_state.commission = commission;\n\n\n\n vote_account.set_state(&VoteStateVersions::new_current(vote_state))\n\n}\n\n\n", "file_path": "programs/vote/src/vote_state/mod.rs", "rank": 9, "score": 283352.2336115467 }, { "content": "pub fn process_vote<S: std::hash::BuildHasher>(\n\n vote_account: &KeyedAccount,\n\n slot_hashes: &[SlotHash],\n\n clock: &Clock,\n\n vote: &Vote,\n\n signers: &HashSet<Pubkey, S>,\n\n) -> Result<(), InstructionError> {\n\n let versioned = State::<VoteStateVersions>::state(vote_account)?;\n\n\n\n if versioned.is_uninitialized() {\n\n return Err(InstructionError::UninitializedAccount);\n\n }\n\n\n\n let mut vote_state = versioned.convert_to_current();\n\n let authorized_voter = vote_state.get_and_update_authorized_voter(clock.epoch)?;\n\n verify_authorized_signer(&authorized_voter, signers)?;\n\n\n\n vote_state.process_vote(vote, slot_hashes, clock.epoch)?;\n\n if let Some(timestamp) = vote.timestamp {\n\n vote.slots\n\n .iter()\n\n .max()\n\n .ok_or(VoteError::EmptySlots)\n\n .and_then(|slot| vote_state.process_timestamp(*slot, timestamp))?;\n\n }\n\n vote_account.set_state(&VoteStateVersions::new_current(vote_state))\n\n}\n\n\n", "file_path": "programs/vote/src/vote_state/mod.rs", "rank": 10, "score": 283352.23361154663 }, { "content": "pub fn mark_disabled(batches: &mut [Packets], r: &[Vec<u8>]) {\n\n batches.iter_mut().zip(r).for_each(|(b, v)| {\n\n b.packets.iter_mut().zip(v).for_each(|(p, f)| {\n\n p.meta.discard = *f == 0;\n\n })\n\n });\n\n}\n\n\n", "file_path": "perf/src/sigverify.rs", "rank": 11, "score": 283159.2051775879 }, { "content": "#[allow(clippy::same_item_push)]\n\nfn make_programs_txs(txes: usize, hash: Hash) -> Vec<Transaction> {\n\n let progs = 4;\n\n (0..txes)\n\n .map(|_| {\n\n let mut instructions = vec![];\n\n let from_key = Keypair::new();\n\n for _ in 1..progs {\n\n let to_key = pubkey::new_rand();\n\n instructions.push(system_instruction::transfer(&from_key.pubkey(), &to_key, 1));\n\n }\n\n let message = Message::new(&instructions, Some(&from_key.pubkey()));\n\n Transaction::new(&[&from_key], message, hash)\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "core/benches/banking_stage.rs", "rank": 12, "score": 282687.9147967766 }, { "content": "/// Update the node_pubkey, requires signature of the authorized voter\n\npub fn update_validator_identity<S: std::hash::BuildHasher>(\n\n vote_account: &KeyedAccount,\n\n node_pubkey: &Pubkey,\n\n signers: &HashSet<Pubkey, S>,\n\n) -> Result<(), InstructionError> {\n\n let mut vote_state: VoteState =\n\n State::<VoteStateVersions>::state(vote_account)?.convert_to_current();\n\n\n\n // current authorized withdrawer must say \"yay\"\n\n verify_authorized_signer(&vote_state.authorized_withdrawer, signers)?;\n\n\n\n // new node must say \"yay\"\n\n verify_authorized_signer(node_pubkey, signers)?;\n\n\n\n vote_state.node_pubkey = *node_pubkey;\n\n\n\n vote_account.set_state(&VoteStateVersions::new_current(vote_state))\n\n}\n\n\n", "file_path": "programs/vote/src/vote_state/mod.rs", "rank": 13, "score": 278854.9319541919 }, { "content": "/// Return a Sha256 hash for the given data.\n\npub fn hash(val: &[u8]) -> Hash {\n\n hashv(&[val])\n\n}\n\n\n", "file_path": "sdk/program/src/hash.rs", "rank": 14, "score": 277038.31919248245 }, { "content": "pub fn copy_return_values(sig_lens: &[Vec<u32>], out: &PinnedVec<u8>, rvs: &mut Vec<Vec<u8>>) {\n\n let mut num = 0;\n\n for (vs, sig_vs) in rvs.iter_mut().zip(sig_lens.iter()) {\n\n for (v, sig_v) in vs.iter_mut().zip(sig_vs.iter()) {\n\n if *sig_v == 0 {\n\n *v = 0;\n\n } else {\n\n let mut vout = 1;\n\n for _ in 0..*sig_v {\n\n if 0 == out[num] {\n\n vout = 0;\n\n }\n\n num = num.saturating_add(1);\n\n }\n\n *v = vout;\n\n }\n\n if *v != 0 {\n\n trace!(\"VERIFIED PACKET!!!!!\");\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "perf/src/sigverify.rs", "rank": 15, "score": 275312.9352997327 }, { "content": "/// Creates the next Tick or Transaction Entry `num_hashes` after `start_hash`.\n\npub fn next_entry(prev_hash: &Hash, num_hashes: u64, transactions: Vec<Transaction>) -> Entry {\n\n assert!(num_hashes > 0 || transactions.is_empty());\n\n let transactions = transactions.into_iter().map(Into::into).collect::<Vec<_>>();\n\n Entry {\n\n num_hashes,\n\n hash: next_hash(prev_hash, num_hashes, &transactions),\n\n transactions,\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use solana_sdk::{\n\n hash::{hash, Hash},\n\n pubkey::Pubkey,\n\n signature::{Keypair, Signer},\n\n system_transaction,\n\n };\n\n\n", "file_path": "entry/src/entry.rs", "rank": 16, "score": 273544.863567483 }, { "content": "pub fn version_from_hash(hash: &Hash) -> u16 {\n\n let hash = hash.as_ref();\n\n let mut accum = [0u8; 2];\n\n hash.chunks(2).for_each(|seed| {\n\n accum\n\n .iter_mut()\n\n .zip(seed)\n\n .for_each(|(accum, seed)| *accum ^= *seed)\n\n });\n\n // convert accum into a u16\n\n // Because accum[0] is a u8, 8bit left shift of the u16 can never overflow\n\n #[allow(clippy::integer_arithmetic)]\n\n let version = ((accum[0] as u16) << 8) | accum[1] as u16;\n\n\n\n // ensure version is never zero, to avoid looking like an uninitialized version\n\n version.saturating_add(1)\n\n}\n\n\n", "file_path": "sdk/src/shred_version.rs", "rank": 17, "score": 272820.0897076205 }, { "content": "/// Return a Keccak256 hash for the given data.\n\npub fn hash(val: &[u8]) -> Hash {\n\n hashv(&[val])\n\n}\n\n\n", "file_path": "sdk/program/src/keccak.rs", "rank": 18, "score": 268793.4136029873 }, { "content": "/// Return a Blake3 hash for the given data.\n\npub fn hash(val: &[u8]) -> Hash {\n\n hashv(&[val])\n\n}\n\n\n", "file_path": "sdk/program/src/blake3.rs", "rank": 19, "score": 268793.4136029873 }, { "content": "pub fn append_u8(buf: &mut Vec<u8>, data: u8) {\n\n let start = buf.len();\n\n buf.resize(buf.len() + 1, 0);\n\n buf[start] = data;\n\n}\n\n\n", "file_path": "sdk/program/src/serialize_utils.rs", "rank": 20, "score": 267996.68737142446 }, { "content": "pub fn append_slice(buf: &mut Vec<u8>, data: &[u8]) {\n\n let start = buf.len();\n\n buf.resize(buf.len() + data.len(), 0);\n\n let end = buf.len();\n\n buf[start..end].copy_from_slice(data);\n\n}\n\n\n", "file_path": "sdk/program/src/serialize_utils.rs", "rank": 21, "score": 267996.68737142446 }, { "content": "pub fn append_u16(buf: &mut Vec<u8>, data: u16) {\n\n let start = buf.len();\n\n buf.resize(buf.len() + 2, 0);\n\n let end = buf.len();\n\n buf[start..end].copy_from_slice(&data.to_le_bytes());\n\n}\n\n\n", "file_path": "sdk/program/src/serialize_utils.rs", "rank": 22, "score": 267996.68737142446 }, { "content": "fn make_accounts_txs(txes: usize, mint_keypair: &Keypair, hash: Hash) -> Vec<Transaction> {\n\n let to_pubkey = pubkey::new_rand();\n\n let dummy = system_transaction::transfer(mint_keypair, &to_pubkey, 1, hash);\n\n (0..txes)\n\n .into_par_iter()\n\n .map(|_| {\n\n let mut new = dummy.clone();\n\n let sig: Vec<u8> = (0..64).map(|_| thread_rng().gen()).collect();\n\n new.message.account_keys[0] = pubkey::new_rand();\n\n new.message.account_keys[1] = pubkey::new_rand();\n\n new.signatures = vec![Signature::new(&sig[0..64])];\n\n new\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "core/benches/banking_stage.rs", "rank": 23, "score": 258747.20373738208 }, { "content": "/// Return the hash of the given hash extended with the given value.\n\npub fn extend_and_hash(id: &Hash, val: &[u8]) -> Hash {\n\n let mut hash_data = id.as_ref().to_vec();\n\n hash_data.extend_from_slice(val);\n\n hash(&hash_data)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_new_unique() {\n\n assert!(Hash::new_unique() != Hash::new_unique());\n\n }\n\n\n\n #[test]\n\n fn test_hash_fromstr() {\n\n let hash = hash(&[1u8]);\n\n\n\n let mut hash_base58_str = bs58::encode(hash).into_string();\n", "file_path": "sdk/program/src/hash.rs", "rank": 24, "score": 257333.4904894104 }, { "content": "/// Return a Sha256 hash for the given data.\n\npub fn hashv(vals: &[&[u8]]) -> Hash {\n\n // Perform the calculation inline, calling this from within a program is\n\n // not supported\n\n #[cfg(not(target_arch = \"bpf\"))]\n\n {\n\n let mut hasher = Hasher::default();\n\n hasher.hashv(vals);\n\n hasher.result()\n\n }\n\n // Call via a system call to perform the calculation\n\n #[cfg(target_arch = \"bpf\")]\n\n {\n\n extern \"C\" {\n\n fn sol_sha256(vals: *const u8, val_len: u64, hash_result: *mut u8) -> u64;\n\n }\n\n let mut hash_result = [0; HASH_BYTES];\n\n unsafe {\n\n sol_sha256(\n\n vals as *const _ as *const u8,\n\n vals.len() as u64,\n\n &mut hash_result as *mut _ as *mut u8,\n\n );\n\n }\n\n Hash::new_from_array(hash_result)\n\n }\n\n}\n\n\n", "file_path": "sdk/program/src/hash.rs", "rank": 25, "score": 254799.837795909 }, { "content": "/// Return the hash of the given hash extended with the given value.\n\npub fn extend_and_hash(id: &Hash, val: &[u8]) -> Hash {\n\n let mut hash_data = id.as_ref().to_vec();\n\n hash_data.extend_from_slice(val);\n\n hash(&hash_data)\n\n}\n", "file_path": "sdk/program/src/keccak.rs", "rank": 26, "score": 251895.0739169952 }, { "content": "/// Return the hash of the given hash extended with the given value.\n\npub fn extend_and_hash(id: &Hash, val: &[u8]) -> Hash {\n\n let mut hash_data = id.as_ref().to_vec();\n\n hash_data.extend_from_slice(val);\n\n hash(&hash_data)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_new_unique() {\n\n assert!(Hash::new_unique() != Hash::new_unique());\n\n }\n\n\n\n #[test]\n\n fn test_hash_fromstr() {\n\n let hash = hash(&[1u8]);\n\n\n\n let mut hash_base58_str = bs58::encode(hash).into_string();\n", "file_path": "sdk/program/src/blake3.rs", "rank": 27, "score": 251895.0739169952 }, { "content": "fn sink(exit: Arc<AtomicBool>, rvs: Arc<AtomicUsize>, r: PacketReceiver) -> JoinHandle<()> {\n\n spawn(move || loop {\n\n if exit.load(Ordering::Relaxed) {\n\n return;\n\n }\n\n let timer = Duration::new(1, 0);\n\n if let Ok(msgs) = r.recv_timeout(timer) {\n\n rvs.fetch_add(msgs.packets.len(), Ordering::Relaxed);\n\n }\n\n })\n\n}\n\n\n", "file_path": "bench-streamer/src/main.rs", "rank": 28, "score": 250492.67257389953 }, { "content": "pub fn hash_transactions(transactions: &[VersionedTransaction]) -> Hash {\n\n // a hash of a slice of transactions only needs to hash the signatures\n\n let signatures: Vec<_> = transactions\n\n .iter()\n\n .flat_map(|tx| tx.signatures.iter())\n\n .collect();\n\n let merkle_tree = MerkleTree::new(&signatures);\n\n if let Some(root_hash) = merkle_tree.get_root() {\n\n *root_hash\n\n } else {\n\n Hash::default()\n\n }\n\n}\n\n\n", "file_path": "entry/src/entry.rs", "rank": 29, "score": 250379.13531245815 }, { "content": "fn resize_vec(keyvec: &mut PinnedVec<u8>) -> usize {\n\n //HACK: Pubkeys vector is passed along as a `Packets` buffer to the GPU\n\n //TODO: GPU needs a more opaque interface, which can handle variable sized structures for data\n\n //Pad the Pubkeys buffer such that it is bigger than a buffer of Packet sized elems\n\n let num_in_packets = (keyvec.len() + (size_of::<Packet>() - 1)) / size_of::<Packet>();\n\n keyvec.resize(num_in_packets * size_of::<Packet>(), 0u8);\n\n num_in_packets\n\n}\n\n\n", "file_path": "ledger/src/sigverify_shreds.rs", "rank": 30, "score": 248971.99792559573 }, { "content": "// Lock on each iteration. Slowest.\n\nfn bench_arc_mutex_poh_hash(bencher: &mut Bencher) {\n\n let poh = Arc::new(Mutex::new(Poh::new(Hash::default(), None)));\n\n bencher.iter(|| {\n\n for _ in 0..NUM_HASHES {\n\n poh.lock().unwrap().hash(1);\n\n }\n\n })\n\n}\n\n\n\n#[bench]\n", "file_path": "poh/benches/poh.rs", "rank": 31, "score": 247650.11068600006 }, { "content": "#[inline]\n\npub fn sol_memset(s: &mut [u8], c: u8, n: usize) {\n\n #[cfg(target_arch = \"bpf\")]\n\n {\n\n extern \"C\" {\n\n fn sol_memset_(s: *mut u8, c: u8, n: u64);\n\n }\n\n unsafe {\n\n sol_memset_(s.as_mut_ptr(), c, n as u64);\n\n }\n\n }\n\n\n\n #[cfg(not(target_arch = \"bpf\"))]\n\n crate::program_stubs::sol_memset(s.as_mut_ptr(), c, n);\n\n}\n", "file_path": "sdk/program/src/program_memory.rs", "rank": 32, "score": 246185.89039535215 }, { "content": "// Acquire lock every NUM_HASHES_PER_BATCH iterations.\n\n// Speed should be close to bench_poh_hash() if NUM_HASHES_PER_BATCH is set well.\n\nfn bench_arc_mutex_poh_batched_hash(bencher: &mut Bencher) {\n\n let poh = Arc::new(Mutex::new(Poh::new(Hash::default(), Some(NUM_HASHES))));\n\n //let exit = Arc::new(AtomicBool::new(false));\n\n let exit = Arc::new(AtomicBool::new(true));\n\n\n\n bencher.iter(|| {\n\n // NOTE: This block attempts to look as close as possible to `PohService::tick_producer()`\n\n loop {\n\n if poh.lock().unwrap().hash(DEFAULT_HASHES_PER_BATCH) {\n\n poh.lock().unwrap().tick().unwrap();\n\n if exit.load(Ordering::Relaxed) {\n\n break;\n\n }\n\n }\n\n }\n\n })\n\n}\n\n\n\n#[bench]\n", "file_path": "poh/benches/poh.rs", "rank": 33, "score": 242294.1513841028 }, { "content": "fn add_test_accounts(vec: &AppendVec, size: usize) -> Vec<(usize, usize)> {\n\n (0..size)\n\n .filter_map(|sample| {\n\n let (meta, account) = create_test_account(sample);\n\n vec.append_account(meta, &account, Hash::default())\n\n .map(|pos| (sample, pos))\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "runtime/benches/append_vec.rs", "rank": 34, "score": 241973.5434378183 }, { "content": "/// Creates the hash `num_hashes` after `start_hash`. If the transaction contains\n\n/// a signature, the final hash will be a hash of both the previous ID and\n\n/// the signature. If num_hashes is zero and there's no transaction data,\n\n/// start_hash is returned.\n\npub fn next_hash(\n\n start_hash: &Hash,\n\n num_hashes: u64,\n\n transactions: &[VersionedTransaction],\n\n) -> Hash {\n\n if num_hashes == 0 && transactions.is_empty() {\n\n return *start_hash;\n\n }\n\n\n\n let mut poh = Poh::new(*start_hash, None);\n\n poh.hash(num_hashes.saturating_sub(1));\n\n if transactions.is_empty() {\n\n poh.tick().unwrap().hash\n\n } else {\n\n poh.record(hash_transactions(transactions)).unwrap().hash\n\n }\n\n}\n\n\n", "file_path": "entry/src/entry.rs", "rank": 35, "score": 239844.1984397908 }, { "content": "/// Return a Keccak256 hash for the given data.\n\npub fn hashv(vals: &[&[u8]]) -> Hash {\n\n // Perform the calculation inline, calling this from within a program is\n\n // not supported\n\n #[cfg(not(target_arch = \"bpf\"))]\n\n {\n\n let mut hasher = Hasher::default();\n\n hasher.hashv(vals);\n\n hasher.result()\n\n }\n\n // Call via a system call to perform the calculation\n\n #[cfg(target_arch = \"bpf\")]\n\n {\n\n extern \"C\" {\n\n fn sol_keccak256(vals: *const u8, val_len: u64, hash_result: *mut u8) -> u64;\n\n }\n\n let mut hash_result = [0; HASH_BYTES];\n\n unsafe {\n\n sol_keccak256(\n\n vals as *const _ as *const u8,\n\n vals.len() as u64,\n\n &mut hash_result as *mut _ as *mut u8,\n\n );\n\n }\n\n Hash::new_from_array(hash_result)\n\n }\n\n}\n\n\n", "file_path": "sdk/program/src/keccak.rs", "rank": 36, "score": 238475.56496689928 }, { "content": "/// Return a Blake3 hash for the given data.\n\npub fn hashv(vals: &[&[u8]]) -> Hash {\n\n // Perform the calculation inline, calling this from within a program is\n\n // not supported\n\n #[cfg(not(target_arch = \"bpf\"))]\n\n {\n\n let mut hasher = Hasher::default();\n\n hasher.hashv(vals);\n\n hasher.result()\n\n }\n\n // Call via a system call to perform the calculation\n\n #[cfg(target_arch = \"bpf\")]\n\n {\n\n extern \"C\" {\n\n fn sol_blake3(vals: *const u8, val_len: u64, hash_result: *mut u8) -> u64;\n\n }\n\n let mut hash_result = [0; HASH_BYTES];\n\n unsafe {\n\n sol_blake3(\n\n vals as *const _ as *const u8,\n\n vals.len() as u64,\n\n &mut hash_result as *mut _ as *mut u8,\n\n );\n\n }\n\n Hash::new_from_array(hash_result)\n\n }\n\n}\n\n\n", "file_path": "sdk/program/src/blake3.rs", "rank": 37, "score": 238475.56496689928 }, { "content": "#[cfg(not(target_os = \"linux\"))]\n\npub fn recv_mmsg(socket: &UdpSocket, packets: &mut [Packet]) -> io::Result<(usize, usize)> {\n\n let mut i = 0;\n\n let count = cmp::min(NUM_RCVMMSGS, packets.len());\n\n let mut total_size = 0;\n\n for p in packets.iter_mut().take(count) {\n\n p.meta.size = 0;\n\n match socket.recv_from(&mut p.data) {\n\n Err(_) if i > 0 => {\n\n break;\n\n }\n\n Err(e) => {\n\n return Err(e);\n\n }\n\n Ok((nrecv, from)) => {\n\n total_size += nrecv;\n\n p.meta.size = nrecv;\n\n p.meta.set_addr(&from);\n\n if i == 0 {\n\n socket.set_nonblocking(true)?;\n\n }\n\n }\n\n }\n\n i += 1;\n\n }\n\n Ok((total_size, i))\n\n}\n\n\n", "file_path": "streamer/src/recvmmsg.rs", "rank": 38, "score": 236564.59838587575 }, { "content": "#[cfg(target_os = \"linux\")]\n\n#[allow(clippy::uninit_assumed_init)]\n\npub fn recv_mmsg(sock: &UdpSocket, packets: &mut [Packet]) -> io::Result<(usize, usize)> {\n\n const SOCKADDR_STORAGE_SIZE: usize = mem::size_of::<sockaddr_storage>();\n\n\n\n let mut hdrs: [mmsghdr; NUM_RCVMMSGS] = unsafe { mem::zeroed() };\n\n let mut iovs: [iovec; NUM_RCVMMSGS] = unsafe { mem::MaybeUninit::uninit().assume_init() };\n\n let mut addrs: [sockaddr_storage; NUM_RCVMMSGS] = unsafe { mem::zeroed() };\n\n\n\n let sock_fd = sock.as_raw_fd();\n\n let count = cmp::min(iovs.len(), packets.len());\n\n\n\n for (packet, hdr, iov, addr) in\n\n izip!(packets.iter_mut(), &mut hdrs, &mut iovs, &mut addrs).take(count)\n\n {\n\n *iov = iovec {\n\n iov_base: packet.data.as_mut_ptr() as *mut libc::c_void,\n\n iov_len: packet.data.len(),\n\n };\n\n hdr.msg_hdr.msg_name = addr as *mut _ as *mut _;\n\n hdr.msg_hdr.msg_namelen = SOCKADDR_STORAGE_SIZE as socklen_t;\n\n hdr.msg_hdr.msg_iov = iov;\n", "file_path": "streamer/src/recvmmsg.rs", "rank": 39, "score": 236564.59838587578 }, { "content": "#[inline]\n\npub fn sol_memcpy(dst: &mut [u8], src: &[u8], n: usize) {\n\n #[cfg(target_arch = \"bpf\")]\n\n {\n\n extern \"C\" {\n\n fn sol_memcpy_(dst: *mut u8, src: *const u8, n: u64);\n\n }\n\n unsafe {\n\n sol_memcpy_(dst.as_mut_ptr(), src.as_ptr(), n as u64);\n\n }\n\n }\n\n\n\n #[cfg(not(target_arch = \"bpf\"))]\n\n crate::program_stubs::sol_memcpy(dst.as_mut_ptr(), src.as_ptr(), n);\n\n}\n\n\n\n/// Memmove\n\n///\n\n/// @param dst - Destination\n\n/// @param src - Source\n\n/// @param n - Number of bytes to copy\n", "file_path": "sdk/program/src/program_memory.rs", "rank": 40, "score": 236379.55418977857 }, { "content": "// Creates a new ledger with slot 0 full of ticks (and only ticks).\n\n//\n\n// Returns the blockhash that can be used to append entries with.\n\npub fn create_new_ledger(\n\n ledger_path: &Path,\n\n genesis_config: &GenesisConfig,\n\n max_genesis_archive_unpacked_size: u64,\n\n access_type: AccessType,\n\n) -> Result<Hash> {\n\n Blockstore::destroy(ledger_path)?;\n\n genesis_config.write(ledger_path)?;\n\n\n\n // Fill slot 0 with ticks that link back to the genesis_config to bootstrap the ledger.\n\n let blockstore = Blockstore::open_with_access_type(ledger_path, access_type, None, false)?;\n\n let ticks_per_slot = genesis_config.ticks_per_slot;\n\n let hashes_per_tick = genesis_config.poh_config.hashes_per_tick.unwrap_or(0);\n\n let entries = create_ticks(ticks_per_slot, hashes_per_tick, genesis_config.hash());\n\n let last_hash = entries.last().unwrap().hash;\n\n let version = solana_sdk::shred_version::version_from_hash(&last_hash);\n\n\n\n let shredder = Shredder::new(0, 0, 0, version).unwrap();\n\n let shreds = shredder\n\n .entries_to_shreds(&Keypair::new(), &entries, true, 0)\n", "file_path": "ledger/src/blockstore.rs", "rank": 41, "score": 234342.98771524947 }, { "content": "pub fn parse_new_nonce(\n\n matches: &ArgMatches<'_>,\n\n default_signer: &DefaultSigner,\n\n wallet_manager: &mut Option<Arc<RemoteWalletManager>>,\n\n) -> Result<CliCommandInfo, CliError> {\n\n let nonce_account = pubkey_of_signer(matches, \"nonce_account_pubkey\", wallet_manager)?.unwrap();\n\n let memo = matches.value_of(MEMO_ARG.name).map(String::from);\n\n let (nonce_authority, nonce_authority_pubkey) =\n\n signer_of(matches, NONCE_AUTHORITY_ARG.name, wallet_manager)?;\n\n\n\n let payer_provided = None;\n\n let signer_info = default_signer.generate_unique_signers(\n\n vec![payer_provided, nonce_authority],\n\n matches,\n\n wallet_manager,\n\n )?;\n\n\n\n Ok(CliCommandInfo {\n\n command: CliCommand::NewNonce {\n\n nonce_account,\n\n nonce_authority: signer_info.index_of(nonce_authority_pubkey).unwrap(),\n\n memo,\n\n },\n\n signers: signer_info.signers,\n\n })\n\n}\n\n\n", "file_path": "cli/src/nonce.rs", "rank": 42, "score": 234330.46594879212 }, { "content": "pub fn process_new_nonce(\n\n rpc_client: &RpcClient,\n\n config: &CliConfig,\n\n nonce_account: &Pubkey,\n\n nonce_authority: SignerIndex,\n\n memo: Option<&String>,\n\n) -> ProcessResult {\n\n check_unique_pubkeys(\n\n (&config.signers[0].pubkey(), \"cli keypair\".to_string()),\n\n (nonce_account, \"nonce_account_pubkey\".to_string()),\n\n )?;\n\n\n\n if let Err(err) = rpc_client.get_account(nonce_account) {\n\n return Err(CliError::BadParameter(format!(\n\n \"Unable to advance nonce account {}. error: {}\",\n\n nonce_account, err\n\n ))\n\n .into());\n\n }\n\n\n", "file_path": "cli/src/nonce.rs", "rank": 43, "score": 234330.46594879212 }, { "content": "#[allow(clippy::result_unit_err)]\n\npub fn decode_shortu16_len(bytes: &[u8]) -> Result<(usize, usize), ()> {\n\n let mut val = 0;\n\n for (nth_byte, byte) in bytes.iter().take(MAX_ENCODING_LENGTH).enumerate() {\n\n match visit_byte(*byte, val, nth_byte).map_err(|_| ())? {\n\n VisitStatus::More(new_val) => val = new_val,\n\n VisitStatus::Done(new_val) => {\n\n return Ok((usize::from(new_val), nth_byte.saturating_add(1)));\n\n }\n\n }\n\n }\n\n Err(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use assert_matches::assert_matches;\n\n use bincode::{deserialize, serialize};\n\n\n\n /// Return the serialized length.\n", "file_path": "sdk/program/src/short_vec.rs", "rank": 44, "score": 234189.2710935035 }, { "content": "pub fn ed25519_verify_cpu(batches: &mut [Packets]) {\n\n use rayon::prelude::*;\n\n let count = batch_size(batches);\n\n debug!(\"CPU ECDSA for {}\", batch_size(batches));\n\n PAR_THREAD_POOL.install(|| {\n\n batches\n\n .into_par_iter()\n\n .for_each(|p| p.packets.par_iter_mut().for_each(|p| verify_packet(p)))\n\n });\n\n inc_new_counter_debug!(\"ed25519_verify_cpu\", count);\n\n}\n\n\n", "file_path": "perf/src/sigverify.rs", "rank": 45, "score": 233807.71045446763 }, { "content": "pub fn goto_end_of_slot(bank: &mut Bank) {\n\n let mut tick_hash = bank.last_blockhash();\n\n loop {\n\n tick_hash = hashv(&[tick_hash.as_ref(), &[42]]);\n\n bank.register_tick(&tick_hash);\n\n if tick_hash == bank.last_blockhash() {\n\n bank.freeze();\n\n return;\n\n }\n\n }\n\n}\n\n\n", "file_path": "runtime/src/bank.rs", "rank": 46, "score": 233807.71045446763 }, { "content": "pub fn ed25519_verify_disabled(batches: &mut [Packets]) {\n\n use rayon::prelude::*;\n\n let count = batch_size(batches);\n\n debug!(\"disabled ECDSA for {}\", batch_size(batches));\n\n batches.into_par_iter().for_each(|p| {\n\n p.packets\n\n .par_iter_mut()\n\n .for_each(|p| p.meta.discard = false)\n\n });\n\n inc_new_counter_debug!(\"ed25519_verify_disabled\", count);\n\n}\n\n\n", "file_path": "perf/src/sigverify.rs", "rank": 47, "score": 233807.71045446763 }, { "content": "#[bench]\n\nfn bench_vec(b: &mut Bencher) {\n\n b.iter(|| {\n\n let bytes = test::black_box(create_encoded_vec());\n\n deserialize::<Vec<u8>>(&bytes).unwrap();\n\n });\n\n}\n", "file_path": "sdk/benches/short_vec.rs", "rank": 48, "score": 232739.68471335256 }, { "content": "pub fn recv_batch(recvr: &PacketReceiver, max_batch: usize) -> Result<(Vec<Packets>, usize, u64)> {\n\n let timer = Duration::new(1, 0);\n\n let msgs = recvr.recv_timeout(timer)?;\n\n let recv_start = Instant::now();\n\n trace!(\"got msgs\");\n\n let mut len = msgs.packets.len();\n\n let mut batch = vec![msgs];\n\n while let Ok(more) = recvr.try_recv() {\n\n trace!(\"got more msgs\");\n\n len += more.packets.len();\n\n batch.push(more);\n\n if len > max_batch {\n\n break;\n\n }\n\n }\n\n trace!(\"batch len {}\", batch.len());\n\n Ok((batch, len, duration_as_ms(&recv_start.elapsed())))\n\n}\n\n\n", "file_path": "streamer/src/streamer.rs", "rank": 49, "score": 232559.2627921963 }, { "content": "pub fn verify_nonce_account(acc: &AccountSharedData, hash: &Hash) -> bool {\n\n if acc.owner() != &crate::system_program::id() {\n\n return false;\n\n }\n\n match StateMut::<Versions>::state(acc).map(|v| v.convert_to_current()) {\n\n Ok(State::Initialized(ref data)) => *hash == data.blockhash,\n\n _ => false,\n\n }\n\n}\n\n\n", "file_path": "sdk/src/nonce_account.rs", "rank": 50, "score": 232450.28832567227 }, { "content": "pub fn to_packets_chunked<T: Serialize>(xs: &[T], chunks: usize) -> Vec<Packets> {\n\n let mut out = vec![];\n\n for x in xs.chunks(chunks) {\n\n let mut p = Packets::with_capacity(x.len());\n\n p.packets.resize(x.len(), Packet::default());\n\n for (i, o) in x.iter().zip(p.packets.iter_mut()) {\n\n Packet::populate_packet(o, None, i).expect(\"serialize request\");\n\n }\n\n out.push(p);\n\n }\n\n out\n\n}\n\n\n", "file_path": "perf/src/packet.rs", "rank": 51, "score": 232343.15475401247 }, { "content": "pub fn do_bench_tps<T>(client: Arc<T>, config: Config, gen_keypairs: Vec<Keypair>) -> u64\n\nwhere\n\n T: 'static + Client + Send + Sync,\n\n{\n\n let Config {\n\n id,\n\n threads,\n\n thread_batch_sleep_ms,\n\n duration,\n\n tx_count,\n\n sustained,\n\n target_slots_per_epoch,\n\n ..\n\n } = config;\n\n\n\n let mut source_keypair_chunks: Vec<Vec<&Keypair>> = Vec::new();\n\n let mut dest_keypair_chunks: Vec<VecDeque<&Keypair>> = Vec::new();\n\n assert!(gen_keypairs.len() >= 2 * tx_count);\n\n for chunk in gen_keypairs.chunks_exact(2 * tx_count) {\n\n source_keypair_chunks.push(chunk[..tx_count].iter().collect());\n", "file_path": "bench-tps/src/bench.rs", "rank": 52, "score": 230388.42699901212 }, { "content": "// Same as `create_new_ledger()` but use a temporary ledger name based on the provided `name`\n\n//\n\n// Note: like `create_new_ledger` the returned ledger will have slot 0 full of ticks (and only\n\n// ticks)\n\npub fn create_new_ledger_from_name(\n\n name: &str,\n\n genesis_config: &GenesisConfig,\n\n access_type: AccessType,\n\n) -> (PathBuf, Hash) {\n\n let ledger_path = get_ledger_path_from_name(name);\n\n let blockhash = create_new_ledger(\n\n &ledger_path,\n\n genesis_config,\n\n MAX_GENESIS_ARCHIVE_UNPACKED_SIZE,\n\n access_type,\n\n )\n\n .unwrap();\n\n (ledger_path, blockhash)\n\n}\n\n\n", "file_path": "ledger/src/blockstore.rs", "rank": 53, "score": 229136.15366324765 }, { "content": "pub fn new_secp256k1_instruction(\n\n priv_key: &libsecp256k1::SecretKey,\n\n message_arr: &[u8],\n\n) -> Instruction {\n\n let secp_pubkey = libsecp256k1::PublicKey::from_secret_key(priv_key);\n\n let eth_pubkey = construct_eth_pubkey(&secp_pubkey);\n\n let mut hasher = sha3::Keccak256::new();\n\n hasher.update(&message_arr);\n\n let message_hash = hasher.finalize();\n\n let mut message_hash_arr = [0u8; 32];\n\n message_hash_arr.copy_from_slice(message_hash.as_slice());\n\n let message = libsecp256k1::Message::parse(&message_hash_arr);\n\n let (signature, recovery_id) = libsecp256k1::sign(&message, priv_key);\n\n let signature_arr = signature.serialize();\n\n assert_eq!(signature_arr.len(), SIGNATURE_SERIALIZED_SIZE);\n\n\n\n let mut instruction_data = vec![];\n\n instruction_data.resize(\n\n DATA_START\n\n .saturating_add(eth_pubkey.len())\n", "file_path": "sdk/src/secp256k1_instruction.rs", "rank": 54, "score": 229123.3018392427 }, { "content": "/// Computes a normalized (log of actual stake) stake.\n\npub fn get_stake<S: std::hash::BuildHasher>(id: &Pubkey, stakes: &HashMap<Pubkey, u64, S>) -> f32 {\n\n // cap the max balance to u32 max (it should be plenty)\n\n let bal = f64::from(u32::max_value()).min(*stakes.get(id).unwrap_or(&0) as f64);\n\n 1_f32.max((bal as f32).ln())\n\n}\n\n\n", "file_path": "gossip/src/crds_gossip.rs", "rank": 55, "score": 228733.46429426485 }, { "content": "// Retains only CRDS values associated with nodes with enough stake.\n\n// (some crds types are exempted)\n\nfn retain_staked(values: &mut Vec<CrdsValue>, stakes: &HashMap<Pubkey, u64>) {\n\n values.retain(|value| {\n\n match value.data {\n\n CrdsData::ContactInfo(_) => true,\n\n // May Impact new validators starting up without any stake yet.\n\n CrdsData::Vote(_, _) => true,\n\n // Unstaked nodes can still help repair.\n\n CrdsData::EpochSlots(_, _) => true,\n\n // Unstaked nodes can still serve snapshots.\n\n CrdsData::SnapshotHashes(_) => true,\n\n // Otherwise unstaked voting nodes will show up with no version in\n\n // the various dashboards.\n\n CrdsData::Version(_) => true,\n\n CrdsData::NodeInstance(_) => true,\n\n CrdsData::LowestSlot(_, _)\n\n | CrdsData::AccountsHashes(_)\n\n | CrdsData::LegacyVersion(_)\n\n | CrdsData::DuplicateShred(_, _) => {\n\n let stake = stakes.get(&value.pubkey()).copied();\n\n stake.unwrap_or_default() >= MIN_STAKE_FOR_GOSSIP\n", "file_path": "gossip/src/cluster_info.rs", "rank": 56, "score": 228581.3568328877 }, { "content": "fn pin<T>(_mem: &mut Vec<T>) {\n\n if let Some(api) = perf_libs::api() {\n\n use std::ffi::c_void;\n\n use std::mem::size_of;\n\n\n\n let ptr = _mem.as_mut_ptr();\n\n let size = _mem.capacity().saturating_mul(size_of::<T>());\n\n let err = unsafe {\n\n (api.cuda_host_register)(ptr as *mut c_void, size, /*flags=*/ 0)\n\n };\n\n if err != CUDA_SUCCESS {\n\n panic!(\n\n \"cudaHostRegister error: {} ptr: {:?} bytes: {}\",\n\n err, ptr, size,\n\n );\n\n }\n\n }\n\n}\n\n\n", "file_path": "perf/src/cuda_runtime.rs", "rank": 57, "score": 228101.0010142238 }, { "content": "#[bench]\n\nfn bench_short_vec(b: &mut Bencher) {\n\n b.iter(|| {\n\n let bytes = test::black_box(create_encoded_short_vec());\n\n deserialize::<ShortVec<u8>>(&bytes).unwrap();\n\n });\n\n}\n\n\n", "file_path": "sdk/benches/short_vec.rs", "rank": 58, "score": 228047.91134317592 }, { "content": "fn set_invoke_context(new: &mut dyn InvokeContext) {\n\n INVOKE_CONTEXT.with(|invoke_context| unsafe {\n\n invoke_context.replace(Some(transmute::<_, (usize, usize)>(new)))\n\n });\n\n}\n", "file_path": "program-test/src/lib.rs", "rank": 59, "score": 226960.31636343637 }, { "content": "#[cfg(windows)]\n\npub fn string_to_winreg_bytes(s: &str) -> Vec<u8> {\n\n use std::ffi::OsString;\n\n use std::os::windows::ffi::OsStrExt;\n\n let v: Vec<_> = OsString::from(format!(\"{}\\x00\", s)).encode_wide().collect();\n\n unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 2).to_vec() }\n\n}\n\n\n\n// This is used to decode the value of HKCU\\Environment\\PATH. If that\n\n// key is not Unicode (or not REG_SZ | REG_EXPAND_SZ) then this\n\n// returns null. The winreg library itself does a lossy unicode\n\n// conversion.\n", "file_path": "install/src/command.rs", "rank": 60, "score": 226955.93891631806 }, { "content": "#[cfg(RUSTC_WITH_SPECIALIZATION)]\n\nfn filter_allow_attrs(attrs: &mut Vec<Attribute>) {\n\n attrs.retain(|attr| {\n\n let ss = &attr.path.segments.first().unwrap().ident.to_string();\n\n ss.starts_with(\"allow\")\n\n });\n\n}\n\n\n", "file_path": "frozen-abi/macro/src/lib.rs", "rank": 61, "score": 226819.47309608277 }, { "content": "#[cfg(feature = \"full\")]\n\npub fn new_rand() -> Pubkey {\n\n Pubkey::new(&rand::random::<[u8; PUBKEY_BYTES]>())\n\n}\n\n\n", "file_path": "sdk/src/pubkey.rs", "rank": 62, "score": 226780.72791707946 }, { "content": "#[inline(never)]\n\npub fn recurse(data: &mut [u8]) {\n\n if data.len() <= 1 {\n\n return;\n\n }\n\n recurse(&mut data[1..]);\n\n msg!(line!(), 0, 0, 0, data[0]);\n\n}\n\n\n\n/// # Safety\n\n#[inline(never)]\n\n#[no_mangle]\n\npub unsafe extern \"C\" fn entrypoint(input: *mut u8) -> u64 {\n\n msg!(\"Call depth\");\n\n let depth = *(input.add(16) as *mut u8);\n\n msg!(line!(), 0, 0, 0, depth);\n\n let mut data = Vec::with_capacity(depth as usize);\n\n for i in 0_u8..depth {\n\n data.push(i);\n\n }\n\n recurse(&mut data);\n\n SUCCESS\n\n}\n\n\n\ncustom_panic_default!();\n", "file_path": "programs/bpf/rust/call_depth/src/lib.rs", "rank": 63, "score": 225524.82373245526 }, { "content": "pub fn activate_all_features(genesis_config: &mut GenesisConfig) {\n\n // Activate all features at genesis in development mode\n\n for feature_id in FeatureSet::default().inactive {\n\n genesis_config.accounts.insert(\n\n feature_id,\n\n Account::from(feature::create_account(\n\n &Feature {\n\n activated_at: Some(0),\n\n },\n\n std::cmp::max(genesis_config.rent.minimum_balance(Feature::size_of()), 1),\n\n )),\n\n );\n\n }\n\n}\n\n\n", "file_path": "runtime/src/genesis_utils.rs", "rank": 64, "score": 225524.82373245526 }, { "content": "/// Removes duplicate signers while preserving order. O(n²)\n\npub fn unique_signers(signers: Vec<&dyn Signer>) -> Vec<&dyn Signer> {\n\n signers.into_iter().unique_by(|s| s.pubkey()).collect()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::signer::keypair::Keypair;\n\n\n\n fn pubkeys(signers: &[&dyn Signer]) -> Vec<Pubkey> {\n\n signers.iter().map(|x| x.pubkey()).collect()\n\n }\n\n\n\n #[test]\n\n fn test_unique_signers() {\n\n let alice = Keypair::new();\n\n let bob = Keypair::new();\n\n assert_eq!(\n\n pubkeys(&unique_signers(vec![&alice, &bob, &alice])),\n\n pubkeys(&[&alice, &bob])\n\n );\n\n }\n\n}\n", "file_path": "sdk/src/signer/mod.rs", "rank": 65, "score": 225496.2881466401 }, { "content": "fn test_node(exit: &Arc<AtomicBool>) -> (Arc<ClusterInfo>, GossipService, UdpSocket) {\n\n let keypair = Arc::new(Keypair::new());\n\n let mut test_node = Node::new_localhost_with_pubkey(&keypair.pubkey());\n\n let cluster_info = Arc::new(ClusterInfo::new(\n\n test_node.info.clone(),\n\n keypair,\n\n SocketAddrSpace::Unspecified,\n\n ));\n\n let gossip_service = GossipService::new(\n\n &cluster_info,\n\n None,\n\n test_node.sockets.gossip,\n\n None,\n\n true, // should_check_duplicate_instance\n\n exit,\n\n );\n\n let _ = cluster_info.my_contact_info();\n\n (\n\n cluster_info,\n\n gossip_service,\n\n test_node.sockets.tvu.pop().unwrap(),\n\n )\n\n}\n\n\n", "file_path": "gossip/tests/gossip.rs", "rank": 66, "score": 225099.82405097657 }, { "content": "pub fn check_no_new_roots(\n\n num_slots_to_wait: usize,\n\n contact_infos: &[ContactInfo],\n\n test_name: &str,\n\n) {\n\n assert!(!contact_infos.is_empty());\n\n let mut roots = vec![0; contact_infos.len()];\n\n let max_slot = contact_infos\n\n .iter()\n\n .enumerate()\n\n .map(|(i, ingress_node)| {\n\n let client = create_client(ingress_node.client_facing_addr(), VALIDATOR_PORT_RANGE);\n\n let initial_root = client\n\n .get_slot()\n\n .unwrap_or_else(|_| panic!(\"get_slot for {} failed\", ingress_node.id));\n\n roots[i] = initial_root;\n\n client\n\n .get_slot_with_commitment(CommitmentConfig::processed())\n\n .unwrap_or_else(|_| panic!(\"get_slot for {} failed\", ingress_node.id))\n\n })\n", "file_path": "local-cluster/src/cluster_tests.rs", "rank": 67, "score": 224259.85834770958 }, { "content": "pub fn new_vote_transaction(\n\n slots: Vec<Slot>,\n\n bank_hash: Hash,\n\n blockhash: Hash,\n\n node_keypair: &Keypair,\n\n vote_keypair: &Keypair,\n\n authorized_voter_keypair: &Keypair,\n\n switch_proof_hash: Option<Hash>,\n\n) -> Transaction {\n\n let votes = Vote::new(slots, bank_hash);\n\n let vote_ix = if let Some(switch_proof_hash) = switch_proof_hash {\n\n vote_instruction::vote_switch(\n\n &vote_keypair.pubkey(),\n\n &authorized_voter_keypair.pubkey(),\n\n votes,\n\n switch_proof_hash,\n\n )\n\n } else {\n\n vote_instruction::vote(\n\n &vote_keypair.pubkey(),\n", "file_path": "programs/vote/src/vote_transaction.rs", "rank": 68, "score": 224259.85834770958 }, { "content": "pub fn make_accounts_hashes_message(\n\n keypair: &Keypair,\n\n accounts_hashes: Vec<(Slot, Hash)>,\n\n) -> Option<CrdsValue> {\n\n let message = CrdsData::AccountsHashes(SnapshotHash::new(keypair.pubkey(), accounts_hashes));\n\n Some(CrdsValue::new_signed(message, keypair))\n\n}\n\n\n\npub(crate) type Ping = ping_pong::Ping<[u8; GOSSIP_PING_TOKEN_SIZE]>;\n\n\n\n// TODO These messages should go through the gpu pipeline for spam filtering\n\n#[frozen_abi(digest = \"AqKhoLDkFr85WPiZnXG4bcRwHU4qSSyDZ3MQZLk3cnJf\")]\n\n#[derive(Serialize, Deserialize, Debug, AbiEnumVisitor, AbiExample)]\n\n#[allow(clippy::large_enum_variant)]\n\npub(crate) enum Protocol {\n\n /// Gossip protocol messages\n\n PullRequest(CrdsFilter, CrdsValue),\n\n PullResponse(Pubkey, Vec<CrdsValue>),\n\n PushMessage(Pubkey, Vec<CrdsValue>),\n\n // TODO: Remove the redundant outer pubkey here,\n", "file_path": "gossip/src/cluster_info.rs", "rank": 69, "score": 224184.60670655803 }, { "content": "pub fn download_then_check_genesis_hash(\n\n rpc_addr: &SocketAddr,\n\n ledger_path: &std::path::Path,\n\n expected_genesis_hash: Option<Hash>,\n\n max_genesis_archive_unpacked_size: u64,\n\n no_genesis_fetch: bool,\n\n use_progress_bar: bool,\n\n) -> Result<GenesisConfig, String> {\n\n if no_genesis_fetch {\n\n let genesis_config = load_local_genesis(ledger_path, expected_genesis_hash)?;\n\n return Ok(genesis_config);\n\n }\n\n\n\n let genesis_package = ledger_path.join(DEFAULT_GENESIS_ARCHIVE);\n\n let genesis_config = if let Ok(tmp_genesis_package) =\n\n download_genesis_if_missing(rpc_addr, &genesis_package, use_progress_bar)\n\n {\n\n unpack_genesis_archive(\n\n &tmp_genesis_package,\n\n ledger_path,\n", "file_path": "genesis-utils/src/lib.rs", "rank": 70, "score": 224184.60670655803 }, { "content": "#[bench]\n\nfn append_vec_append(bencher: &mut Bencher) {\n\n let path = get_append_vec_path(\"bench_append\");\n\n let vec = AppendVec::new(&path.path, true, 64 * 1024);\n\n bencher.iter(|| {\n\n let (meta, account) = create_test_account(0);\n\n if vec\n\n .append_account(meta, &account, Hash::default())\n\n .is_none()\n\n {\n\n vec.reset();\n\n }\n\n });\n\n}\n\n\n", "file_path": "runtime/benches/append_vec.rs", "rank": 71, "score": 223626.10907066637 }, { "content": "fn deposit_many(bank: &Bank, pubkeys: &mut Vec<Pubkey>, num: usize) -> Result<(), LamportsError> {\n\n for t in 0..num {\n\n let pubkey = solana_sdk::pubkey::new_rand();\n\n let account =\n\n AccountSharedData::new((t + 1) as u64, 0, AccountSharedData::default().owner());\n\n pubkeys.push(pubkey);\n\n assert!(bank.get_account(&pubkey).is_none());\n\n bank.deposit(&pubkey, (t + 1) as u64)?;\n\n assert_eq!(bank.get_account(&pubkey).unwrap(), account);\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "runtime/benches/accounts.rs", "rank": 72, "score": 220782.9370754321 }, { "content": "pub fn add_genesis_accounts(genesis_config: &mut GenesisConfig, mut issued_lamports: u64) {\n\n // add_stakes() and add_validators() award tokens for rent exemption and\n\n // to cover an initial transfer-free period of the network\n\n\n\n issued_lamports += add_stakes(\n\n genesis_config,\n\n CREATOR_STAKER_INFOS,\n\n &UNLOCKS_HALF_AT_9_MONTHS,\n\n ) + add_stakes(\n\n genesis_config,\n\n SERVICE_STAKER_INFOS,\n\n &UNLOCKS_ALL_AT_9_MONTHS,\n\n ) + add_stakes(\n\n genesis_config,\n\n FOUNDATION_STAKER_INFOS,\n\n &UNLOCKS_ALL_DAY_ZERO,\n\n ) + add_stakes(genesis_config, GRANTS_STAKER_INFOS, &UNLOCKS_ALL_DAY_ZERO)\n\n + add_stakes(\n\n genesis_config,\n\n COMMUNITY_STAKER_INFOS,\n", "file_path": "genesis/src/genesis_accounts.rs", "rank": 73, "score": 220610.61674693628 }, { "content": "fn sort_stakes(stakes: &mut Vec<(Pubkey, u64)>) {\n\n // Sort first by stake. If stakes are the same, sort by pubkey to ensure a\n\n // deterministic result.\n\n // Note: Use unstable sort, because we dedup right after to remove the equal elements.\n\n stakes.sort_unstable_by(|(l_pubkey, l_stake), (r_pubkey, r_stake)| {\n\n if r_stake == l_stake {\n\n r_pubkey.cmp(l_pubkey)\n\n } else {\n\n r_stake.cmp(l_stake)\n\n }\n\n });\n\n\n\n // Now that it's sorted, we can do an O(n) dedup.\n\n stakes.dedup();\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use solana_runtime::genesis_utils::{\n", "file_path": "ledger/src/leader_schedule_utils.rs", "rank": 74, "score": 219805.7135912089 }, { "content": "fn verify_authorized_signer<S: std::hash::BuildHasher>(\n\n authorized: &Pubkey,\n\n signers: &HashSet<Pubkey, S>,\n\n) -> Result<(), InstructionError> {\n\n if signers.contains(authorized) {\n\n Ok(())\n\n } else {\n\n Err(InstructionError::MissingRequiredSignature)\n\n }\n\n}\n\n\n", "file_path": "programs/vote/src/vote_state/mod.rs", "rank": 75, "score": 219687.46748145786 }, { "content": "pub fn read_pubkey(current: &mut usize, data: &[u8]) -> Result<Pubkey, SanitizeError> {\n\n let len = std::mem::size_of::<Pubkey>();\n\n if data.len() < *current + len {\n\n return Err(SanitizeError::IndexOutOfBounds);\n\n }\n\n let e = Pubkey::new(&data[*current..*current + len]);\n\n *current += len;\n\n Ok(e)\n\n}\n\n\n", "file_path": "sdk/program/src/serialize_utils.rs", "rank": 76, "score": 219490.11852390063 }, { "content": "pub fn read_u16(current: &mut usize, data: &[u8]) -> Result<u16, SanitizeError> {\n\n if data.len() < *current + 2 {\n\n return Err(SanitizeError::IndexOutOfBounds);\n\n }\n\n let mut fixed_data = [0u8; 2];\n\n fixed_data.copy_from_slice(&data[*current..*current + 2]);\n\n let e = u16::from_le_bytes(fixed_data);\n\n *current += 2;\n\n Ok(e)\n\n}\n\n\n", "file_path": "sdk/program/src/serialize_utils.rs", "rank": 77, "score": 219490.11852390063 }, { "content": "pub fn read_u8(current: &mut usize, data: &[u8]) -> Result<u8, SanitizeError> {\n\n if data.len() < *current + 1 {\n\n return Err(SanitizeError::IndexOutOfBounds);\n\n }\n\n let e = data[*current];\n\n *current += 1;\n\n Ok(e)\n\n}\n\n\n", "file_path": "sdk/program/src/serialize_utils.rs", "rank": 78, "score": 219490.11852390063 }, { "content": "#[bench]\n\nfn append_vec_sequential_read(bencher: &mut Bencher) {\n\n let path = get_append_vec_path(\"seq_read\");\n\n let vec = AppendVec::new(&path.path, true, 64 * 1024);\n\n let size = 1_000;\n\n let mut indexes = add_test_accounts(&vec, size);\n\n bencher.iter(|| {\n\n let (sample, pos) = indexes.pop().unwrap();\n\n println!(\"reading pos {} {}\", sample, pos);\n\n let (account, _next) = vec.get_account(pos).unwrap();\n\n let (_meta, test) = create_test_account(sample);\n\n assert_eq!(account.data, test.data());\n\n indexes.push((sample, pos));\n\n });\n\n}\n", "file_path": "runtime/benches/append_vec.rs", "rank": 79, "score": 219451.04196636783 }, { "content": "#[bench]\n\nfn append_vec_random_read(bencher: &mut Bencher) {\n\n let path = get_append_vec_path(\"random_read\");\n\n let vec = AppendVec::new(&path.path, true, 64 * 1024);\n\n let size = 1_000;\n\n let indexes = add_test_accounts(&vec, size);\n\n bencher.iter(|| {\n\n let random_index: usize = thread_rng().gen_range(0, indexes.len());\n\n let (sample, pos) = &indexes[random_index];\n\n let (account, _next) = vec.get_account(*pos).unwrap();\n\n let (_meta, test) = create_test_account(*sample);\n\n assert_eq!(account.data, test.data());\n\n });\n\n}\n\n\n", "file_path": "runtime/benches/append_vec.rs", "rank": 80, "score": 219451.04196636783 }, { "content": "#[bench]\n\nfn test_accounts_hash_bank_hash(bencher: &mut Bencher) {\n\n let accounts = Accounts::new_with_config_for_benches(\n\n vec![PathBuf::from(\"bench_accounts_hash_internal\")],\n\n &ClusterType::Development,\n\n AccountSecondaryIndexes::default(),\n\n false,\n\n AccountShrinkThreshold::default(),\n\n );\n\n let mut pubkeys: Vec<Pubkey> = vec![];\n\n let num_accounts = 60_000;\n\n let slot = 0;\n\n create_test_accounts(&accounts, &mut pubkeys, num_accounts, slot);\n\n let ancestors = Ancestors::from(vec![0]);\n\n let (_, total_lamports) = accounts.accounts_db.update_accounts_hash(0, &ancestors);\n\n let test_hash_calculation = false;\n\n bencher.iter(|| {\n\n assert!(accounts.verify_bank_hash_and_lamports(\n\n 0,\n\n &ancestors,\n\n total_lamports,\n\n test_hash_calculation\n\n ))\n\n });\n\n}\n\n\n", "file_path": "runtime/benches/accounts.rs", "rank": 81, "score": 219401.56782292423 }, { "content": "pub fn get_thread_count() -> usize {\n\n *MAX_RAYON_THREADS\n\n}\n", "file_path": "rayon-threadlimit/src/lib.rs", "rank": 82, "score": 216703.53450875505 }, { "content": "/// Returns a list of indexes shuffled based on the input weights\n\n/// Note - The sum of all weights must not exceed `u64::MAX`\n\npub fn weighted_shuffle<T, B, F>(weights: F, seed: [u8; 32]) -> Vec<usize>\n\nwhere\n\n T: Copy + PartialOrd + iter::Sum + Div<T, Output = T> + FromPrimitive + ToPrimitive,\n\n B: Borrow<T>,\n\n F: Iterator<Item = B> + Clone,\n\n{\n\n let total_weight: T = weights.clone().map(|x| *x.borrow()).sum();\n\n let mut rng = ChaChaRng::from_seed(seed);\n\n weights\n\n .enumerate()\n\n .map(|(i, weight)| {\n\n let weight = weight.borrow();\n\n // This generates an \"inverse\" weight but it avoids floating point math\n\n let x = (total_weight / *weight)\n\n .to_u64()\n\n .expect(\"values > u64::max are not supported\");\n\n (\n\n i,\n\n // capture the u64 into u128s to prevent overflow\n\n rng.gen_range(1, u128::from(std::u16::MAX)) * u128::from(x),\n\n )\n\n })\n\n // sort in ascending order\n\n .sorted_by(|(_, l_val), (_, r_val)| l_val.cmp(r_val))\n\n .map(|x| x.0)\n\n .collect()\n\n}\n\n\n", "file_path": "gossip/src/weighted_shuffle.rs", "rank": 83, "score": 216622.03874681034 }, { "content": "#[bench]\n\nfn bench_to_from_account(b: &mut Bencher) {\n\n let mut slot_hashes = SlotHashes::new(&[]);\n\n for i in 0..MAX_ENTRIES {\n\n slot_hashes.add(i as Slot, Hash::default());\n\n }\n\n b.iter(|| {\n\n let account = create_account_for_test(&slot_hashes);\n\n slot_hashes = from_account::<SlotHashes, _>(&account).unwrap();\n\n });\n\n}\n", "file_path": "sdk/benches/slot_hashes.rs", "rank": 84, "score": 216540.13687507802 }, { "content": "pub fn recv_from(obj: &mut Packets, socket: &UdpSocket, max_wait_ms: u64) -> Result<usize> {\n\n let mut i = 0;\n\n //DOCUMENTED SIDE-EFFECT\n\n //Performance out of the IO without poll\n\n // * block on the socket until it's readable\n\n // * set the socket to non blocking\n\n // * read until it fails\n\n // * set it back to blocking before returning\n\n socket.set_nonblocking(false)?;\n\n trace!(\"receiving on {}\", socket.local_addr().unwrap());\n\n let start = Instant::now();\n\n loop {\n\n obj.packets.resize(\n\n std::cmp::min(i + NUM_RCVMMSGS, PACKETS_PER_BATCH),\n\n Packet::default(),\n\n );\n\n match recv_mmsg(socket, &mut obj.packets[i..]) {\n\n Err(_) if i > 0 => {\n\n if start.elapsed().as_millis() as u64 > max_wait_ms {\n\n break;\n", "file_path": "streamer/src/packet.rs", "rank": 85, "score": 215825.32395594596 }, { "content": "#[bench]\n\nfn append_vec_concurrent_append_read(bencher: &mut Bencher) {\n\n let path = get_append_vec_path(\"concurrent_read\");\n\n let vec = Arc::new(AppendVec::new(&path.path, true, 1024 * 1024));\n\n let vec1 = vec.clone();\n\n let indexes: Arc<Mutex<Vec<(usize, usize)>>> = Arc::new(Mutex::new(vec![]));\n\n let indexes1 = indexes.clone();\n\n spawn(move || loop {\n\n let sample = indexes1.lock().unwrap().len();\n\n let (meta, account) = create_test_account(sample);\n\n if let Some(pos) = vec1.append_account(meta, &account, Hash::default()) {\n\n indexes1.lock().unwrap().push((sample, pos))\n\n } else {\n\n break;\n\n }\n\n });\n\n while indexes.lock().unwrap().is_empty() {\n\n sleep(Duration::from_millis(100));\n\n }\n\n bencher.iter(|| {\n\n let len = indexes.lock().unwrap().len();\n\n let random_index: usize = thread_rng().gen_range(0, len);\n\n let (sample, pos) = *indexes.lock().unwrap().get(random_index).unwrap();\n\n let (account, _next) = vec.get_account(pos).unwrap();\n\n let (_meta, test) = create_test_account(sample);\n\n assert_eq!(account.data, test.data());\n\n });\n\n}\n\n\n", "file_path": "runtime/benches/append_vec.rs", "rank": 86, "score": 215502.117042951 }, { "content": "#[bench]\n\nfn append_vec_concurrent_read_append(bencher: &mut Bencher) {\n\n let path = get_append_vec_path(\"concurrent_read\");\n\n let vec = Arc::new(AppendVec::new(&path.path, true, 1024 * 1024));\n\n let vec1 = vec.clone();\n\n let indexes: Arc<Mutex<Vec<(usize, usize)>>> = Arc::new(Mutex::new(vec![]));\n\n let indexes1 = indexes.clone();\n\n spawn(move || loop {\n\n let len = indexes1.lock().unwrap().len();\n\n if len == 0 {\n\n continue;\n\n }\n\n let random_index: usize = thread_rng().gen_range(0, len + 1);\n\n let (sample, pos) = *indexes1.lock().unwrap().get(random_index % len).unwrap();\n\n let (account, _next) = vec1.get_account(pos).unwrap();\n\n let (_meta, test) = create_test_account(sample);\n\n assert_eq!(account.data, test.data());\n\n });\n\n bencher.iter(|| {\n\n let sample: usize = thread_rng().gen_range(0, 256);\n\n let (meta, account) = create_test_account(sample);\n\n if let Some(pos) = vec.append_account(meta, &account, Hash::default()) {\n\n indexes.lock().unwrap().push((sample, pos))\n\n }\n\n });\n\n}\n", "file_path": "runtime/benches/append_vec.rs", "rank": 87, "score": 215502.117042951 }, { "content": "pub fn read_transaction_infos(db: &PickleDb) -> Vec<TransactionInfo> {\n\n db.iter()\n\n .map(|kv| kv.get_value::<TransactionInfo>().unwrap())\n\n .collect()\n\n}\n\n\n", "file_path": "tokens/src/db.rs", "rank": 88, "score": 214893.87109763463 }, { "content": "pub fn parse_accounts(message: &Message) -> Vec<ParsedAccount> {\n\n let mut accounts: Vec<ParsedAccount> = vec![];\n\n for (i, account_key) in message.account_keys.iter().enumerate() {\n\n accounts.push(ParsedAccount {\n\n pubkey: account_key.to_string(),\n\n writable: message.is_writable(i),\n\n signer: message.is_signer(i),\n\n });\n\n }\n\n accounts\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use solana_sdk::message::MessageHeader;\n\n\n\n #[test]\n\n fn test_parse_accounts() {\n\n let pubkey0 = solana_sdk::pubkey::new_rand();\n", "file_path": "transaction-status/src/parse_accounts.rs", "rank": 89, "score": 214893.87109763463 }, { "content": "#[allow(dead_code)]\n\npub fn serialize_iter_as_tuple<I>(iter: I) -> impl Serialize\n\nwhere\n\n I: IntoIterator,\n\n <I as IntoIterator>::Item: Serialize,\n\n <I as IntoIterator>::IntoIter: ExactSizeIterator,\n\n{\n\n struct SerializableSequencedIterator<I> {\n\n iter: std::cell::RefCell<Option<I>>,\n\n }\n\n\n\n #[cfg(all(test, RUSTC_WITH_SPECIALIZATION))]\n\n impl<I> IgnoreAsHelper for SerializableSequencedIterator<I> {}\n\n\n\n impl<I> Serialize for SerializableSequencedIterator<I>\n\n where\n\n I: IntoIterator,\n\n <I as IntoIterator>::Item: Serialize,\n\n <I as IntoIterator>::IntoIter: ExactSizeIterator,\n\n {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n", "file_path": "runtime/src/serde_snapshot/utils.rs", "rank": 90, "score": 212800.97732840927 }, { "content": "#[allow(dead_code)]\n\npub fn serialize_iter_as_seq<I>(iter: I) -> impl Serialize\n\nwhere\n\n I: IntoIterator,\n\n <I as IntoIterator>::Item: Serialize,\n\n <I as IntoIterator>::IntoIter: ExactSizeIterator,\n\n{\n\n struct SerializableSequencedIterator<I> {\n\n iter: std::cell::RefCell<Option<I>>,\n\n }\n\n\n\n #[cfg(all(test, RUSTC_WITH_SPECIALIZATION))]\n\n impl<I> IgnoreAsHelper for SerializableSequencedIterator<I> {}\n\n\n\n impl<I> Serialize for SerializableSequencedIterator<I>\n\n where\n\n I: IntoIterator,\n\n <I as IntoIterator>::Item: Serialize,\n\n <I as IntoIterator>::IntoIter: ExactSizeIterator,\n\n {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n", "file_path": "runtime/src/serde_snapshot/utils.rs", "rank": 91, "score": 212800.97732840927 }, { "content": "/// fund the dests keys by spending all of the source keys into MAX_SPENDS_PER_TX\n\n/// on every iteration. This allows us to replay the transfers because the source is either empty,\n\n/// or full\n\npub fn fund_keys<T: 'static + Client + Send + Sync>(\n\n client: Arc<T>,\n\n source: &Keypair,\n\n dests: &[Keypair],\n\n total: u64,\n\n max_fee: u64,\n\n lamports_per_account: u64,\n\n) {\n\n let mut funded: Vec<&Keypair> = vec![source];\n\n let mut funded_funds = total;\n\n let mut not_funded: Vec<&Keypair> = dests.iter().collect();\n\n while !not_funded.is_empty() {\n\n // Build to fund list and prepare funding sources for next iteration\n\n let mut new_funded: Vec<&Keypair> = vec![];\n\n let mut to_fund: Vec<(&Keypair, Vec<(Pubkey, u64)>)> = vec![];\n\n let to_lamports = (funded_funds - lamports_per_account - max_fee) / MAX_SPENDS_PER_TX;\n\n for f in funded {\n\n let start = not_funded.len() - MAX_SPENDS_PER_TX as usize;\n\n let dests: Vec<_> = not_funded.drain(start..).collect();\n\n let spends: Vec<_> = dests.iter().map(|k| (k.pubkey(), to_lamports)).collect();\n", "file_path": "bench-tps/src/bench.rs", "rank": 92, "score": 212799.67013283752 }, { "content": "/// Creates a new process bar for processing that will take an unknown amount of time\n\npub fn new_spinner_progress_bar() -> ProgressBar {\n\n let progress_bar = indicatif::ProgressBar::new(42);\n\n progress_bar.set_draw_target(ProgressDrawTarget::stdout());\n\n progress_bar\n\n .set_style(ProgressStyle::default_spinner().template(\"{spinner:.green} {wide_msg}\"));\n\n progress_bar.enable_steady_tick(100);\n\n\n\n ProgressBar {\n\n progress_bar,\n\n is_term: console::Term::stdout().is_term(),\n\n }\n\n}\n\n\n\npub struct ProgressBar {\n\n progress_bar: indicatif::ProgressBar,\n\n is_term: bool,\n\n}\n\n\n\nimpl ProgressBar {\n\n pub fn set_message<T: Into<Cow<'static, str>> + Display>(&self, msg: T) {\n", "file_path": "validator/src/lib.rs", "rank": 93, "score": 212163.7804559509 }, { "content": "#[bench]\n\nfn bench_add_hash(bencher: &mut Bencher) {\n\n let mut rng = rand::thread_rng();\n\n let hash_values: Vec<_> = std::iter::repeat_with(|| solana_sdk::hash::new_rand(&mut rng))\n\n .take(1200)\n\n .collect();\n\n let mut fail = 0;\n\n bencher.iter(|| {\n\n let mut bloom = Bloom::random(1287, 0.1, 7424);\n\n for hash_value in &hash_values {\n\n bloom.add(hash_value);\n\n }\n\n let index = rng.gen_range(0, hash_values.len());\n\n if !bloom.contains(&hash_values[index]) {\n\n fail += 1;\n\n }\n\n });\n\n assert_eq!(fail, 0);\n\n}\n\n\n", "file_path": "runtime/benches/bloom.rs", "rank": 94, "score": 211671.97253676396 }, { "content": "// No locking. Fastest.\n\nfn bench_poh_hash(bencher: &mut Bencher) {\n\n let mut poh = Poh::new(Hash::default(), None);\n\n bencher.iter(|| {\n\n poh.hash(NUM_HASHES);\n\n })\n\n}\n\n\n\n#[bench]\n", "file_path": "poh/benches/poh.rs", "rank": 95, "score": 211671.97253676396 }, { "content": "#[cfg(test)]\n\npub fn to_packets<T: Serialize>(xs: &[T]) -> Vec<Packets> {\n\n to_packets_chunked(xs, NUM_PACKETS)\n\n}\n\n\n", "file_path": "perf/src/packet.rs", "rank": 96, "score": 211435.64629069527 }, { "content": "pub fn add_genesis_account(genesis_config: &mut GenesisConfig) -> u64 {\n\n let mut account = create_config_account(vec![], &Config::default(), 0);\n\n let lamports = genesis_config.rent.minimum_balance(account.data().len());\n\n\n\n account.set_lamports(lamports.max(1));\n\n\n\n genesis_config.add_account(config::id(), account);\n\n\n\n lamports\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use solana_sdk::pubkey::Pubkey;\n\n use std::cell::RefCell;\n\n\n\n #[test]\n\n fn test() {\n\n let account = RefCell::new(create_account(0, &Config::default()));\n\n assert_eq!(from(&account.borrow()), Some(Config::default()));\n\n assert_eq!(\n\n from_keyed_account(&KeyedAccount::new(&Pubkey::default(), false, &account)),\n\n Err(InstructionError::InvalidArgument)\n\n );\n\n }\n\n}\n", "file_path": "programs/stake/src/config.rs", "rank": 97, "score": 211246.35694812192 }, { "content": "pub fn add_genesis_accounts(genesis_config: &mut GenesisConfig) -> u64 {\n\n config::add_genesis_account(genesis_config)\n\n}\n", "file_path": "programs/stake/src/lib.rs", "rank": 98, "score": 211246.35694812192 }, { "content": "fn null_tracer() -> Option<impl FnMut(&RewardCalculationEvent)> {\n\n None::<fn(&RewardCalculationEvent)>\n\n}\n\n\n\nimpl fmt::Display for RewardType {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(\n\n f,\n\n \"{}\",\n\n match self {\n\n RewardType::Fee => \"fee\",\n\n RewardType::Rent => \"rent\",\n\n RewardType::Staking => \"staking\",\n\n RewardType::Voting => \"voting\",\n\n }\n\n )\n\n }\n\n}\n\n\n", "file_path": "runtime/src/bank.rs", "rank": 99, "score": 210179.0414674453 } ]
Rust
src/client.rs
thallada/BazaarRealmClient
dffe435c5908045b4e20de01b01125b1f6d9fddf
use std::{ffi::CStr, ffi::CString, os::raw::c_char, path::Path}; use anyhow::Result; use log::LevelFilter; use reqwest::{blocking::Response, Url}; use uuid::Uuid; #[cfg(not(test))] use log::{error, info}; #[cfg(test)] use std::{println as info, println as error}; use crate::{ error::extract_error_from_response, log_server_error, result::{FFIError, FFIResult}, }; #[no_mangle] pub extern "C" fn init() -> bool { match dirs::document_dir() { Some(mut log_dir) => { log_dir.push(Path::new( r#"My Games\Skyrim Special Edition\SKSE\BazaarRealmClient.log"#, )); match simple_logging::log_to_file(log_dir, LevelFilter::Info) { Ok(_) => true, Err(_) => false, } } None => false, } } #[no_mangle] pub extern "C" fn status_check(api_url: *const c_char) -> FFIResult<bool> { let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy(); info!("status_check api_url: {:?}", api_url); fn inner(api_url: &str) -> Result<()> { #[cfg(not(test))] let api_url = Url::parse(api_url)?.join("v1/status")?; #[cfg(test)] let api_url = Url::parse(&mockito::server_url())?.join("v1/status")?; let resp = reqwest::blocking::get(api_url)?; let status = resp.status(); let bytes = resp.bytes()?; if status.is_success() { Ok(()) } else { Err(extract_error_from_response(status, &bytes)) } } match inner(&api_url) { Ok(()) => { info!("status_check ok"); FFIResult::Ok(true) } Err(err) => { error!("status_check failed. {}", err); FFIResult::Err(FFIError::from(err)) } } } #[no_mangle] pub unsafe extern "C" fn generate_api_key() -> *mut c_char { let uuid = CString::new(format!("{}", Uuid::new_v4())) .expect("could not create CString") .into_raw(); info!("generate_api_key successful"); uuid } #[cfg(test)] mod tests { use super::*; use mockito::mock; #[test] fn test_status_check() { let mock = mock("GET", "/v1/status").with_status(200).create(); let api_url = CString::new("url").unwrap().into_raw(); let result = status_check(api_url); mock.assert(); match result { FFIResult::Ok(success) => { assert_eq!(success, true); } FFIResult::Err(error) => panic!( "status_check returned error: {:?}", match error { FFIError::Server(server_error) => format!("{} {}", server_error.status, unsafe { CStr::from_ptr(server_error.title).to_string_lossy() }), FFIError::Network(network_error) => unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(), } ), } } #[test] fn test_status_check_server_error() { let mock = mock("GET", "/v1/status") .with_status(500) .with_body("Internal Server Error") .create(); let api_url = CString::new("url").unwrap().into_raw(); let result = status_check(api_url); mock.assert(); match result { FFIResult::Ok(success) => panic!("status_check returned Ok result: {:?}", success), FFIResult::Err(error) => match error { FFIError::Server(server_error) => { assert_eq!(server_error.status, 500); assert_eq!( unsafe { CStr::from_ptr(server_error.title).to_string_lossy() }, "Internal Server Error" ); } _ => panic!("status_check did not return a server error"), }, } } }
use std::{ffi::CStr, ffi::CString, os::raw::c_char, path::Path}; use anyhow::Result; use log::LevelFilter; use reqwest::{blocking::Response, Url}; use uuid::Uuid; #[cfg(not(test))] use log::{error, info}; #[cfg(test)] use std::{println as info, println as error}; use crate::{ error::extract_error_from_response, log_server_error, result::{FFIError, FFIResult}, }; #[no_mangle] pub extern "C" fn init() -> bool { match dirs::document_di
#[no_mangle] pub extern "C" fn status_check(api_url: *const c_char) -> FFIResult<bool> { let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy(); info!("status_check api_url: {:?}", api_url); fn inner(api_url: &str) -> Result<()> { #[cfg(not(test))] let api_url = Url::parse(api_url)?.join("v1/status")?; #[cfg(test)] let api_url = Url::parse(&mockito::server_url())?.join("v1/status")?; let resp = reqwest::blocking::get(api_url)?; let status = resp.status(); let bytes = resp.bytes()?; if status.is_success() { Ok(()) } else { Err(extract_error_from_response(status, &bytes)) } } match inner(&api_url) { Ok(()) => { info!("status_check ok"); FFIResult::Ok(true) } Err(err) => { error!("status_check failed. {}", err); FFIResult::Err(FFIError::from(err)) } } } #[no_mangle] pub unsafe extern "C" fn generate_api_key() -> *mut c_char { let uuid = CString::new(format!("{}", Uuid::new_v4())) .expect("could not create CString") .into_raw(); info!("generate_api_key successful"); uuid } #[cfg(test)] mod tests { use super::*; use mockito::mock; #[test] fn test_status_check() { let mock = mock("GET", "/v1/status").with_status(200).create(); let api_url = CString::new("url").unwrap().into_raw(); let result = status_check(api_url); mock.assert(); match result { FFIResult::Ok(success) => { assert_eq!(success, true); } FFIResult::Err(error) => panic!( "status_check returned error: {:?}", match error { FFIError::Server(server_error) => format!("{} {}", server_error.status, unsafe { CStr::from_ptr(server_error.title).to_string_lossy() }), FFIError::Network(network_error) => unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(), } ), } } #[test] fn test_status_check_server_error() { let mock = mock("GET", "/v1/status") .with_status(500) .with_body("Internal Server Error") .create(); let api_url = CString::new("url").unwrap().into_raw(); let result = status_check(api_url); mock.assert(); match result { FFIResult::Ok(success) => panic!("status_check returned Ok result: {:?}", success), FFIResult::Err(error) => match error { FFIError::Server(server_error) => { assert_eq!(server_error.status, 500); assert_eq!( unsafe { CStr::from_ptr(server_error.title).to_string_lossy() }, "Internal Server Error" ); } _ => panic!("status_check did not return a server error"), }, } } }
r() { Some(mut log_dir) => { log_dir.push(Path::new( r#"My Games\Skyrim Special Edition\SKSE\BazaarRealmClient.log"#, )); match simple_logging::log_to_file(log_dir, LevelFilter::Info) { Ok(_) => true, Err(_) => false, } } None => false, } }
function_block-function_prefixed
[ { "content": "pub fn log_server_error(resp: Response) {\n\n let status = resp.status();\n\n if let Ok(text) = resp.text() {\n\n error!(\"Server error: {} {}\", status, text);\n\n }\n\n error!(\"Server error: {}\", status);\n\n}\n\n\n\n#[no_mangle]\n\npub extern \"C\" fn free_string(ptr: *mut c_char) {\n\n unsafe { drop(CString::from_raw(ptr)) }\n\n}\n", "file_path": "src/lib.rs", "rank": 0, "score": 85408.69136191512 }, { "content": "pub fn extract_error_from_response(status: StatusCode, bytes: &Bytes) -> Error {\n\n match serde_json::from_slice::<HttpApiProblem>(bytes) {\n\n Ok(api_problem) => {\n\n let server_error = ServerError {\n\n status,\n\n title: api_problem.title,\n\n detail: api_problem.detail,\n\n };\n\n error!(\"{}\", server_error);\n\n anyhow!(server_error)\n\n }\n\n Err(_) => {\n\n let title = str::from_utf8(bytes)\n\n .unwrap_or_else(|_| &status.canonical_reason().unwrap_or(\"unknown\"))\n\n .to_string();\n\n let server_error = ServerError {\n\n status,\n\n title,\n\n detail: None,\n\n };\n\n error!(\"{}\", server_error);\n\n anyhow!(server_error)\n\n }\n\n }\n\n}\n", "file_path": "src/error.rs", "rank": 1, "score": 83384.8825284099 }, { "content": "pub fn update_file_caches(\n\n body_cache_path: PathBuf,\n\n metadata_cache_path: PathBuf,\n\n bytes: Bytes,\n\n headers: HeaderMap,\n\n) {\n\n thread::spawn(move || {\n\n update_file_cache(&body_cache_path, &bytes)\n\n .map_err(|err| {\n\n error!(\"Failed to update body file cache: {}\", err);\n\n })\n\n .ok();\n\n update_metadata_file_cache(&metadata_cache_path, &headers)\n\n .map_err(|err| {\n\n error!(\"Failed to update metadata file cache: {}\", err);\n\n })\n\n .ok();\n\n });\n\n}\n\n\n", "file_path": "src/cache.rs", "rank": 2, "score": 68178.17204981839 }, { "content": "pub fn file_cache_dir(api_url: &str) -> Result<PathBuf> {\n\n let encoded_url = encode_config(api_url, URL_SAFE_NO_PAD);\n\n let path = Path::new(\"Data/SKSE/Plugins/BazaarRealmCache\")\n\n .join(encoded_url)\n\n .join(API_VERSION);\n\n #[cfg(not(test))]\n\n create_dir_all(&path)?;\n\n Ok(path)\n\n}\n\n\n", "file_path": "src/cache.rs", "rank": 3, "score": 65099.22031221013 }, { "content": "pub fn load_metadata_from_file_cache(cache_path: &Path) -> Result<Metadata> {\n\n #[cfg(not(test))]\n\n let file = File::open(cache_path).with_context(|| {\n\n format!(\n\n \"Object not found in API or in cache: {}\",\n\n cache_path.file_name().unwrap_or_default().to_string_lossy()\n\n )\n\n })?;\n\n #[cfg(test)]\n\n let file = tempfile()?; // cache always reads from an empty temp file in cfg(test)\n\n\n\n let reader = BufReader::new(file);\n\n info!(\"returning value from cache: {:?}\", cache_path);\n\n let metadata: Metadata = serde_json::from_reader(reader).with_context(|| {\n\n format!(\n\n \"Object not found in API or in cache: {}\",\n\n cache_path.file_name().unwrap_or_default().to_string_lossy(),\n\n )\n\n })?;\n\n Ok(metadata)\n\n}\n", "file_path": "src/cache.rs", "rank": 4, "score": 46387.69408473248 }, { "content": "pub fn update_file_cache(cache_path: &Path, bytes: &Bytes) -> Result<()> {\n\n #[cfg(not(test))]\n\n let mut file = File::create(cache_path)?;\n\n #[cfg(test)]\n\n let mut file = tempfile()?;\n\n\n\n file.write_all(&bytes.as_ref())?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/cache.rs", "rank": 5, "score": 45354.95419411401 }, { "content": "fn main() {\n\n let crate_dir = env::var(\"CARGO_MANIFEST_DIR\").unwrap();\n\n \n\n cbindgen::generate(crate_dir)\n\n .expect(\"Unable to generate bindings\")\n\n .write_to_file(\"bindings.h\");\n\n}", "file_path": "build.rs", "rank": 6, "score": 44332.5430886468 }, { "content": "pub fn update_metadata_file_cache(cache_path: &Path, headers: &HeaderMap) -> Result<()> {\n\n #[cfg(not(test))]\n\n let mut file = File::create(cache_path)?;\n\n #[cfg(test)]\n\n let mut file = tempfile()?;\n\n\n\n let etag = headers\n\n .get(\"etag\")\n\n .map(|val| val.to_str().unwrap_or(\"\").to_string());\n\n let date = headers\n\n .get(\"date\")\n\n .map(|val| val.to_str().unwrap_or(\"\").parse().unwrap_or(Utc::now()));\n\n let metadata = Metadata { etag, date };\n\n serde_json::to_writer(file, &metadata)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/cache.rs", "rank": 7, "score": 42512.10440198272 }, { "content": "pub fn from_file_cache<T: for<'de> Deserialize<'de>>(cache_path: &Path) -> Result<T> {\n\n #[cfg(not(test))]\n\n let file = File::open(cache_path).with_context(|| {\n\n format!(\n\n \"Object not found in API or in cache: {}\",\n\n cache_path.file_name().unwrap_or_default().to_string_lossy()\n\n )\n\n })?;\n\n #[cfg(test)]\n\n let file = tempfile()?; // cache always reads from an empty temp file in cfg(test)\n\n\n\n let reader = BufReader::new(file);\n\n info!(\"returning value from cache: {:?}\", cache_path);\n\n Ok(bincode::deserialize_from(reader).with_context(|| {\n\n format!(\n\n \"Object not found in API or in cache: {}\",\n\n cache_path.file_name().unwrap_or_default().to_string_lossy(),\n\n )\n\n })?)\n\n}\n\n\n", "file_path": "src/cache.rs", "rank": 8, "score": 39990.34966923309 }, { "content": "use std::fmt;\n\nuse std::str;\n\n\n\nuse anyhow::{anyhow, Error};\n\nuse bytes::Bytes;\n\nuse http_api_problem::HttpApiProblem;\n\nuse reqwest::StatusCode;\n\n\n\n#[cfg(not(test))]\n\nuse log::error;\n\n#[cfg(test)]\n\nuse std::println as error;\n\n\n\n#[derive(Debug)]\n\npub struct ServerError {\n\n pub status: StatusCode,\n\n pub title: String,\n\n pub detail: Option<String>,\n\n}\n\n\n", "file_path": "src/error.rs", "rank": 9, "score": 31816.22378499151 }, { "content": "impl fmt::Display for ServerError {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n if let Some(detail) = &self.detail {\n\n write!(\n\n f,\n\n \"Server {} {}: {}\",\n\n self.status.as_u16(),\n\n self.title,\n\n detail\n\n )\n\n } else {\n\n write!(f, \"Server {} {}\", self.status.as_u16(), self.title)\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/error.rs", "rank": 10, "score": 31803.627895107395 }, { "content": " FFIResult<bool> _bool_result;\n", "file_path": "bindings.h", "rank": 11, "score": 23580.45074748855 }, { "content": "struct FFIServerError {\n\n uint16_t status;\n\n const char *title;\n\n const char *detail;\n", "file_path": "bindings.h", "rank": 12, "score": 22361.995350474725 }, { "content": "use std::{ffi::CStr, ffi::CString, os::raw::c_char, slice};\n\n\n\nuse anyhow::Result;\n\nuse chrono::NaiveDateTime;\n\nuse reqwest::{StatusCode, Url};\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[cfg(not(test))]\n\nuse log::{error, info};\n\n#[cfg(test)]\n\nuse std::{println as info, println as error};\n\n\n\nuse crate::{\n\n cache::file_cache_dir, cache::from_file_cache, cache::load_metadata_from_file_cache,\n\n cache::update_file_caches, error::extract_error_from_response, log_server_error,\n\n result::{FFIError, FFIResult},\n\n};\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\npub struct MerchandiseList {\n", "file_path": "src/merchandise_list.rs", "rank": 14, "score": 22.88545243301729 }, { "content": "use std::{ffi::CStr, ffi::CString, os::raw::c_char};\n\n\n\nuse anyhow::Result;\n\nuse chrono::NaiveDateTime;\n\nuse reqwest::Url;\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[cfg(not(test))]\n\nuse log::{error, info};\n\n#[cfg(test)]\n\nuse std::{println as info, println as error};\n\n\n\nuse crate::{\n\n cache::file_cache_dir,\n\n cache::update_file_caches,\n\n error::extract_error_from_response,\n\n result::{FFIError, FFIResult},\n\n};\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n", "file_path": "src/owner.rs", "rank": 15, "score": 22.52253540682079 }, { "content": "use std::{ffi::CStr, ffi::CString, os::raw::c_char, slice};\n\n\n\nuse anyhow::Result;\n\nuse chrono::NaiveDateTime;\n\nuse reqwest::Url;\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[cfg(not(test))]\n\nuse log::{error, info};\n\n#[cfg(test)]\n\nuse std::{println as info, println as error};\n\n\n\nuse crate::{\n\n cache::file_cache_dir,\n\n cache::update_file_caches,\n\n error::extract_error_from_response,\n\n result::{FFIError, FFIResult},\n\n};\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n", "file_path": "src/transaction.rs", "rank": 16, "score": 22.415936882237553 }, { "content": "use std::{ffi::CStr, ffi::CString, os::raw::c_char, slice};\n\n\n\nuse anyhow::Result;\n\nuse chrono::NaiveDateTime;\n\nuse reqwest::{StatusCode, Url};\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[cfg(not(test))]\n\nuse log::{error, info};\n\n#[cfg(test)]\n\nuse std::{println as info, println as error};\n\n\n\nuse crate::{\n\n cache::file_cache_dir,\n\n cache::from_file_cache,\n\n cache::load_metadata_from_file_cache,\n\n cache::update_file_caches,\n\n error::extract_error_from_response,\n\n log_server_error,\n\n result::{FFIError, FFIResult},\n", "file_path": "src/interior_ref_list.rs", "rank": 17, "score": 21.686239826804602 }, { "content": "use std::{ffi::CStr, ffi::CString, os::raw::c_char, slice};\n\n\n\nuse anyhow::Result;\n\nuse chrono::NaiveDateTime;\n\nuse reqwest::{StatusCode, Url};\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[cfg(not(test))]\n\nuse log::{error, info};\n\n#[cfg(test)]\n\nuse std::{println as info, println as error};\n\n\n\nuse crate::{\n\n cache::file_cache_dir,\n\n cache::from_file_cache,\n\n cache::load_metadata_from_file_cache,\n\n cache::update_file_caches,\n\n error::extract_error_from_response,\n\n log_server_error,\n\n result::{FFIError, FFIResult},\n", "file_path": "src/shop.rs", "rank": 18, "score": 21.686239826804602 }, { "content": "use anyhow::Error;\n\n\n\nuse std::convert::From;\n\nuse std::ffi::CString;\n\nuse std::os::raw::c_char;\n\nuse std::ptr::null;\n\n\n\nuse crate::error::ServerError;\n\n\n\n#[derive(Debug, PartialEq)]\n\n#[repr(C)]\n\npub struct FFIServerError {\n\n pub status: u16,\n\n pub title: *const c_char,\n\n pub detail: *const c_char,\n\n}\n\n\n\nimpl From<&ServerError> for FFIServerError {\n\n fn from(server_error: &ServerError) -> Self {\n\n FFIServerError {\n", "file_path": "src/result.rs", "rank": 20, "score": 18.658529542183746 }, { "content": "use std::{\n\n fs::create_dir_all, fs::File, io::BufReader, io::Write, path::Path, path::PathBuf, thread,\n\n};\n\n\n\nuse anyhow::{Context, Result};\n\nuse base64::{encode_config, URL_SAFE_NO_PAD};\n\nuse bytes::Bytes;\n\nuse chrono::{DateTime, Utc};\n\nuse reqwest::header::HeaderMap;\n\nuse serde::{Deserialize, Serialize};\n\n#[cfg(test)]\n\nuse tempfile::tempfile;\n\n\n\n#[cfg(not(test))]\n\nuse log::{error, info};\n\n#[cfg(test)]\n\nuse std::{println as error, println as info};\n\n\n\nuse super::API_VERSION;\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Metadata {\n\n pub etag: Option<String>,\n\n pub date: Option<DateTime<Utc>>,\n\n}\n\n\n", "file_path": "src/cache.rs", "rank": 21, "score": 18.377519610783068 }, { "content": " error!(\"create_shop failed. {}\", err);\n\n FFIResult::Err(FFIError::from(err))\n\n }\n\n }\n\n}\n\n\n\n#[no_mangle]\n\npub extern \"C\" fn update_shop(\n\n api_url: *const c_char,\n\n api_key: *const c_char,\n\n id: u32,\n\n name: *const c_char,\n\n description: *const c_char,\n\n gold: i32,\n\n shop_type: *const c_char,\n\n vendor_keywords: *mut *const c_char,\n\n vendor_keywords_len: usize,\n\n vendor_keywords_exclude: bool,\n\n) -> FFIResult<RawShop> {\n\n info!(\"update_shop begin\");\n", "file_path": "src/shop.rs", "rank": 22, "score": 17.184692885710565 }, { "content": " },\n\n })\n\n }\n\n Err(err) => {\n\n error!(\"get_interior_ref_list failed. {}\", err);\n\n FFIResult::Err(FFIError::from(err))\n\n }\n\n }\n\n}\n\n\n\n#[no_mangle]\n\npub extern \"C\" fn get_interior_ref_list_by_shop_id(\n\n api_url: *const c_char,\n\n api_key: *const c_char,\n\n shop_id: i32,\n\n) -> FFIResult<RawInteriorRefData> {\n\n let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy();\n\n let api_key = unsafe { CStr::from_ptr(api_key) }.to_string_lossy();\n\n info!(\n\n \"get_interior_ref_list_by_shop_id api_url: {:?}, api_key: {:?}, shop_id: {:?}\",\n", "file_path": "src/interior_ref_list.rs", "rank": 24, "score": 16.018052190625593 }, { "content": " // TODO: need to pass this back into Rust once C++ is done with it so it can be manually dropped and the CStrings dropped from raw pointers.\n\n FFIResult::Ok(RawShop::from(shop))\n\n }\n\n Err(err) => {\n\n error!(\"get_shop failed. {}\", err);\n\n FFIResult::Err(FFIError::from(err))\n\n }\n\n }\n\n}\n\n\n\n#[no_mangle]\n\npub extern \"C\" fn list_shops(\n\n api_url: *const c_char,\n\n api_key: *const c_char,\n\n) -> FFIResult<RawShopVec> {\n\n let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy();\n\n let api_key = unsafe { CStr::from_ptr(api_key) }.to_string_lossy();\n\n info!(\"list_shops api_url: {:?}, api_key: {:?}\", api_url, api_key);\n\n\n\n fn inner(api_url: &str, api_key: &str) -> Result<Vec<SavedShop>> {\n", "file_path": "src/shop.rs", "rank": 26, "score": 15.536280925876206 }, { "content": " error!(\"update_interior_ref_list failed. {}\", err);\n\n FFIResult::Err(FFIError::from(err))\n\n }\n\n }\n\n}\n\n\n\n// TODO: delete me if unused\n\n#[no_mangle]\n\npub extern \"C\" fn get_interior_ref_list(\n\n api_url: *const c_char,\n\n api_key: *const c_char,\n\n interior_ref_list_id: i32,\n\n) -> FFIResult<RawInteriorRefData> {\n\n let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy();\n\n let api_key = unsafe { CStr::from_ptr(api_key) }.to_string_lossy();\n\n info!(\n\n \"get_interior_ref_list api_url: {:?}, api_key: {:?}, interior_ref_list_id: {:?}\",\n\n api_url, api_key, interior_ref_list_id\n\n );\n\n\n", "file_path": "src/interior_ref_list.rs", "rank": 27, "score": 15.535377291016196 }, { "content": " error!(\"get_merchandise_list failed. {}\", err);\n\n FFIResult::Err(FFIError::from(err))\n\n }\n\n }\n\n}\n\n\n\n#[no_mangle]\n\npub extern \"C\" fn get_merchandise_list_by_shop_id(\n\n api_url: *const c_char,\n\n api_key: *const c_char,\n\n shop_id: i32,\n\n) -> FFIResult<RawMerchandiseVec> {\n\n let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy();\n\n let api_key = unsafe { CStr::from_ptr(api_key) }.to_string_lossy();\n\n info!(\n\n \"get_merchandise_list_by_shop_id api_url: {:?}, api_key: {:?}, shop_id: {:?}\",\n\n api_url, api_key, shop_id\n\n );\n\n\n\n fn inner(api_url: &str, api_key: &str, shop_id: i32) -> Result<SavedMerchandiseList> {\n", "file_path": "src/merchandise_list.rs", "rank": 28, "score": 15.354455206081509 }, { "content": " pub ptr: *mut RawShop,\n\n pub len: usize,\n\n pub cap: usize,\n\n}\n\n\n\n#[no_mangle]\n\npub extern \"C\" fn create_shop(\n\n api_url: *const c_char,\n\n api_key: *const c_char,\n\n name: *const c_char,\n\n description: *const c_char,\n\n) -> FFIResult<RawShop> {\n\n let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy();\n\n let api_key = unsafe { CStr::from_ptr(api_key) }.to_string_lossy();\n\n let name = unsafe { CStr::from_ptr(name) }.to_string_lossy();\n\n let description = unsafe { CStr::from_ptr(description) }.to_string_lossy();\n\n info!(\n\n \"create_shop api_url: {:?}, api_key: {:?}, name: {:?}, description: {:?}\",\n\n api_url, api_key, name, description\n\n );\n", "file_path": "src/shop.rs", "rank": 29, "score": 15.210343848766648 }, { "content": " pub ptr: *mut RawTransaction,\n\n pub len: usize,\n\n pub cap: usize,\n\n}\n\n\n\n#[no_mangle]\n\npub extern \"C\" fn create_transaction(\n\n api_url: *const c_char,\n\n api_key: *const c_char,\n\n raw_transaction: RawTransaction,\n\n) -> FFIResult<RawTransaction> {\n\n let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy();\n\n let api_key = unsafe { CStr::from_ptr(api_key) }.to_string_lossy();\n\n let transaction = Transaction::from(raw_transaction);\n\n info!(\n\n \"create_transaction api_url: {:?}, api_key: {:?}, transaction: {:?}\",\n\n api_url, api_key, transaction\n\n );\n\n\n\n fn inner(api_url: &str, api_key: &str, transaction: Transaction) -> Result<SavedTransaction> {\n", "file_path": "src/transaction.rs", "rank": 30, "score": 14.941724111646678 }, { "content": "#![allow(non_snake_case)]\n\n#![feature(vec_into_raw_parts)]\n\n\n\nuse std::ffi::CString;\n\nuse std::os::raw::c_char;\n\n\n\nuse reqwest::blocking::Response;\n\n\n\n#[cfg(not(test))]\n\nuse log::error;\n\n\n\n#[cfg(test)]\n\nuse std::println as error;\n\n\n\nmod cache;\n\nmod client;\n\nmod error;\n\nmod interior_ref_list;\n\nmod merchandise_list;\n\nmod owner;\n\nmod result;\n\nmod shop;\n\nmod transaction;\n\n\n\npub const API_VERSION: &'static str = \"v1\";\n\n\n", "file_path": "src/lib.rs", "rank": 31, "score": 14.628793981817891 }, { "content": " FFIResult::Err(FFIError::from(err))\n\n }\n\n }\n\n}\n\n\n\n#[no_mangle]\n\npub extern \"C\" fn update_interior_ref_list(\n\n api_url: *const c_char,\n\n api_key: *const c_char,\n\n shop_id: i32,\n\n raw_interior_ref_ptr: *const RawInteriorRef,\n\n raw_interior_ref_len: usize,\n\n raw_shelf_ptr: *const RawShelf,\n\n raw_shelf_len: usize,\n\n) -> FFIResult<i32> {\n\n let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy();\n\n let api_key = unsafe { CStr::from_ptr(api_key) }.to_string_lossy();\n\n info!(\"update_interior_ref_list api_url: {:?}, api_key: {:?}, shop_id: {:?}, raw_interior_ref_len: {:?}, raw_shelf_len: {:?}\", api_url, api_key, shop_id, raw_interior_ref_len, raw_shelf_len);\n\n let raw_interior_ref_slice = match raw_interior_ref_ptr.is_null() {\n\n true => &[],\n", "file_path": "src/interior_ref_list.rs", "rank": 32, "score": 14.450129626917757 }, { "content": "pub extern \"C\" fn get_shop(\n\n api_url: *const c_char,\n\n api_key: *const c_char,\n\n shop_id: i32,\n\n) -> FFIResult<RawShop> {\n\n info!(\"get_shop begin\");\n\n let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy();\n\n let api_key = unsafe { CStr::from_ptr(api_key) }.to_string_lossy();\n\n info!(\n\n \"get_shop api_url: {:?}, api_key: {:?}, shop_id: {:?}\",\n\n api_url, api_key, shop_id\n\n );\n\n\n\n fn inner(api_url: &str, api_key: &str, shop_id: i32) -> Result<SavedShop> {\n\n #[cfg(not(test))]\n\n let url = Url::parse(api_url)?.join(&format!(\"v1/shops/{}\", shop_id))?;\n\n #[cfg(test)]\n\n let url = Url::parse(&mockito::server_url())?.join(&format!(\"v1/shops/{}\", shop_id))?;\n\n info!(\"api_url: {:?}\", url);\n\n\n", "file_path": "src/shop.rs", "rank": 33, "score": 14.085275279372889 }, { "content": "\n\n#[no_mangle]\n\npub extern \"C\" fn update_owner(\n\n api_url: *const c_char,\n\n api_key: *const c_char,\n\n id: i32,\n\n name: *const c_char,\n\n mod_version: i32,\n\n) -> FFIResult<RawOwner> {\n\n let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy();\n\n let api_key = unsafe { CStr::from_ptr(api_key) }.to_string_lossy();\n\n let name = unsafe { CStr::from_ptr(name) }.to_string_lossy();\n\n info!(\n\n \"update_owner api_url: {:?}, api_key: {:?}, name: {:?}, mod_version: {:?}\",\n\n api_url, api_key, name, mod_version\n\n );\n\n\n\n fn inner(\n\n api_url: &str,\n\n api_key: &str,\n", "file_path": "src/owner.rs", "rank": 35, "score": 13.741078615803605 }, { "content": "\n\n let api_url = CString::new(\"url\").unwrap().into_raw();\n\n let api_key = CString::new(\"api-key\").unwrap().into_raw();\n\n let result = get_shop(api_url, api_key, 1);\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(raw_shop) => panic!(\"get_shop returned Ok result: {:#x?}\", raw_shop),\n\n FFIResult::Err(error) => match error {\n\n FFIError::Network(network_error) => {\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() },\n\n \"Object not found in API or in cache: shop_1.bin\",\n\n );\n\n }\n\n _ => panic!(\"get_shop did not return a network error\"),\n\n },\n\n }\n\n }\n\n\n\n #[test]\n", "file_path": "src/shop.rs", "rank": 36, "score": 13.660461557174692 }, { "content": "\n\n let api_url = CString::new(\"url\").unwrap().into_raw();\n\n let api_key = CString::new(\"api-key\").unwrap().into_raw();\n\n let name = CString::new(\"name\").unwrap().into_raw();\n\n let description = CString::new(\"description\").unwrap().into_raw();\n\n let result = create_shop(api_url, api_key, name, description);\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(raw_shop) => panic!(\"create_shop returned Ok result: {:#x?}\", raw_shop),\n\n FFIResult::Err(error) => match error {\n\n FFIError::Server(server_error) => {\n\n assert_eq!(server_error.status, 500);\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(server_error.title).to_string_lossy() },\n\n \"Internal Server Error\"\n\n );\n\n }\n\n _ => panic!(\"create_shop did not return a server error\"),\n\n },\n\n }\n", "file_path": "src/shop.rs", "rank": 37, "score": 13.647295412771596 }, { "content": " let api_url = CString::new(\"url\").unwrap().into_raw();\n\n let api_key = CString::new(\"api-key\").unwrap().into_raw();\n\n let name = CString::new(\"name\").unwrap().into_raw();\n\n let mod_version = 1;\n\n let result = update_owner(api_url, api_key, 1, name, mod_version);\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(raw_owner) => {\n\n panic!(\"update_owner returned Ok result: {:#x?}\", raw_owner)\n\n }\n\n FFIResult::Err(error) => match error {\n\n FFIError::Server(server_error) => {\n\n assert_eq!(server_error.status, 500);\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(server_error.title).to_string_lossy() },\n\n \"Internal Server Error\"\n\n );\n\n }\n\n _ => panic!(\"update_owner did not return a server error\"),\n\n },\n\n }\n\n }\n\n}\n", "file_path": "src/owner.rs", "rank": 38, "score": 13.575424123110771 }, { "content": " let api_url = CString::new(\"url\").unwrap().into_raw();\n\n let api_key = CString::new(\"api-key\").unwrap().into_raw();\n\n let result = get_merchandise_list(api_url, api_key, 1);\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(raw_merchandise_vec) => panic!(\n\n \"get_merchandise_list returned Ok result: {:#x?}\",\n\n raw_merchandise_vec\n\n ),\n\n FFIResult::Err(error) => match error {\n\n FFIError::Network(network_error) => {\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() },\n\n \"Object not found in API or in cache: merchandise_list_1.bin\",\n\n );\n\n }\n\n _ => panic!(\"get_merchandise_list did not return a network error\"),\n\n },\n\n }\n\n }\n", "file_path": "src/merchandise_list.rs", "rank": 39, "score": 13.4016827977895 }, { "content": "\n\n#[derive(Debug)]\n\n#[repr(C)]\n\npub struct RawMerchandiseVec {\n\n pub ptr: *mut RawMerchandise,\n\n pub len: usize,\n\n pub cap: usize,\n\n}\n\n\n\n// TODO: delete me if unused\n\n#[no_mangle]\n\npub extern \"C\" fn create_merchandise_list(\n\n api_url: *const c_char,\n\n api_key: *const c_char,\n\n shop_id: i32,\n\n raw_merchandise_ptr: *const RawMerchandise,\n\n raw_merchandise_len: usize,\n\n) -> FFIResult<RawMerchandiseVec> {\n\n let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy();\n\n let api_key = unsafe { CStr::from_ptr(api_key) }.to_string_lossy();\n", "file_path": "src/merchandise_list.rs", "rank": 40, "score": 13.234823429691856 }, { "content": " fn test_create_owner_server_error() {\n\n let mock = mock(\"POST\", \"/v1/owners\")\n\n .with_status(500)\n\n .with_body(\"Internal Server Error\")\n\n .create();\n\n\n\n let api_url = CString::new(\"url\").unwrap().into_raw();\n\n let api_key = CString::new(\"api-key\").unwrap().into_raw();\n\n let name = CString::new(\"name\").unwrap().into_raw();\n\n let mod_version = 1;\n\n let result = create_owner(api_url, api_key, name, mod_version);\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(raw_owner) => {\n\n panic!(\"create_owner returned Ok result: {:#x?}\", raw_owner)\n\n }\n\n FFIResult::Err(error) => match error {\n\n FFIError::Server(server_error) => {\n\n assert_eq!(server_error.status, 500);\n\n assert_eq!(\n", "file_path": "src/owner.rs", "rank": 41, "score": 13.158273220136444 }, { "content": "\n\n#[no_mangle]\n\npub extern \"C\" fn create_owner(\n\n api_url: *const c_char,\n\n api_key: *const c_char,\n\n name: *const c_char,\n\n mod_version: i32,\n\n) -> FFIResult<RawOwner> {\n\n let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy();\n\n let api_key = unsafe { CStr::from_ptr(api_key) }.to_string_lossy();\n\n let name = unsafe { CStr::from_ptr(name) }.to_string_lossy();\n\n info!(\n\n \"create_owner api_url: {:?}, api_key: {:?}, name: {:?}, mod_version: {:?}\",\n\n api_url, api_key, name, mod_version\n\n );\n\n\n\n fn inner(api_url: &str, api_key: &str, name: &str, mod_version: i32) -> Result<SavedOwner> {\n\n #[cfg(not(test))]\n\n let url = Url::parse(api_url)?.join(\"v1/owners\")?;\n\n #[cfg(test)]\n", "file_path": "src/owner.rs", "rank": 42, "score": 13.047553198704552 }, { "content": " }\n\n })\n\n .collect::<Vec<RawMerchandise>>()\n\n .into_raw_parts();\n\n // TODO: need to pass this back into Rust once C++ is done with it so it can be manually dropped and the CStrings dropped from raw pointers.\n\n FFIResult::Ok(RawMerchandiseVec { ptr, len, cap })\n\n }\n\n Err(err) => {\n\n error!(\"update_merchandise_list failed. {}\", err);\n\n FFIResult::Err(FFIError::from(err))\n\n }\n\n }\n\n}\n\n\n\n// TODO: delete me if unused\n\n#[no_mangle]\n\npub extern \"C\" fn get_merchandise_list(\n\n api_url: *const c_char,\n\n api_key: *const c_char,\n\n merchandise_list_id: i32,\n", "file_path": "src/merchandise_list.rs", "rank": 43, "score": 12.906679898315486 }, { "content": " }\n\n })\n\n .collect::<Vec<RawMerchandise>>()\n\n .into_raw_parts();\n\n // TODO: need to pass this back into Rust once C++ is done with it so it can be manually dropped and the CStrings dropped from raw pointers.\n\n FFIResult::Ok(RawMerchandiseVec { ptr, len, cap })\n\n }\n\n Err(err) => {\n\n error!(\"create_merchandise_list failed. {}\", err);\n\n FFIResult::Err(FFIError::from(err))\n\n }\n\n }\n\n}\n\n\n\n#[no_mangle]\n\npub extern \"C\" fn update_merchandise_list(\n\n api_url: *const c_char,\n\n api_key: *const c_char,\n\n shop_id: i32,\n\n raw_merchandise_ptr: *const RawMerchandise,\n", "file_path": "src/merchandise_list.rs", "rank": 44, "score": 12.826196429192308 }, { "content": " }\n\n\n\n #[test]\n\n fn test_get_interior_ref_list_server_error() {\n\n let mock = mock(\"GET\", \"/v1/interior_ref_lists/1\")\n\n .with_status(500)\n\n .with_body(\"Internal Server Error\")\n\n .create();\n\n\n\n let api_url = CString::new(\"url\").unwrap().into_raw();\n\n let api_key = CString::new(\"api-key\").unwrap().into_raw();\n\n let result = get_interior_ref_list(api_url, api_key, 1);\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(raw_interior_ref_vec) => panic!(\n\n \"get_interior_ref_list returned Ok result: {:#x?}\",\n\n raw_interior_ref_vec\n\n ),\n\n FFIResult::Err(error) => match error {\n\n FFIError::Network(network_error) => {\n", "file_path": "src/interior_ref_list.rs", "rank": 45, "score": 12.790943996415319 }, { "content": " status: server_error.status.as_u16(),\n\n // TODO: may need to drop these CStrings once C++ is done reading them\n\n title: CString::new(server_error.title.clone())\n\n .expect(\"could not create CString\")\n\n .into_raw(),\n\n detail: match &server_error.detail {\n\n Some(detail) => CString::new(detail.clone())\n\n .expect(\"could not create CString\")\n\n .into_raw(),\n\n None => null(),\n\n },\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, PartialEq)]\n\n#[repr(C, u8)]\n\npub enum FFIError {\n\n Server(FFIServerError),\n\n Network(*const c_char),\n", "file_path": "src/result.rs", "rank": 46, "score": 12.777784696728352 }, { "content": " #[test]\n\n fn test_get_merchandise_list_server_error_by_shop_id() {\n\n let mock = mock(\"GET\", \"/v1/shops/1/merchandise_list\")\n\n .with_status(500)\n\n .with_body(\"Internal Server Error\")\n\n .create();\n\n\n\n let api_url = CString::new(\"url\").unwrap().into_raw();\n\n let api_key = CString::new(\"api-key\").unwrap().into_raw();\n\n let result = get_merchandise_list_by_shop_id(api_url, api_key, 1);\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(raw_merchandise_vec) => panic!(\n\n \"get_merchandise_list_by_shop_id returned Ok result: {:#x?}\",\n\n raw_merchandise_vec\n\n ),\n\n FFIResult::Err(error) => match error {\n\n FFIError::Network(network_error) => {\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() },\n\n \"Object not found in API or in cache: shop_1_merchandise_list.bin\",\n\n );\n\n }\n\n _ => panic!(\"get_merchandise_list_by_shop_id did not return a network error\"),\n\n },\n\n }\n\n }\n\n}\n", "file_path": "src/merchandise_list.rs", "rank": 47, "score": 12.380538364092342 }, { "content": " FFIError::Network(network_error) =>\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(),\n\n }\n\n ),\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_get_interior_ref_list_by_shop_id_server_error() {\n\n let mock = mock(\"GET\", \"/v1/shops/1/interior_ref_list\")\n\n .with_status(500)\n\n .with_body(\"Internal Server Error\")\n\n .create();\n\n\n\n let api_url = CString::new(\"url\").unwrap().into_raw();\n\n let api_key = CString::new(\"api-key\").unwrap().into_raw();\n\n let result = get_interior_ref_list_by_shop_id(api_url, api_key, 1);\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(raw_interior_ref_vec) => panic!(\n", "file_path": "src/interior_ref_list.rs", "rank": 48, "score": 12.356135186847554 }, { "content": "#[no_mangle]\n\npub extern \"C\" fn create_interior_ref_list(\n\n api_url: *const c_char,\n\n api_key: *const c_char,\n\n shop_id: i32,\n\n raw_interior_ref_ptr: *const RawInteriorRef,\n\n raw_interior_ref_len: usize,\n\n raw_shelf_ptr: *const RawShelf,\n\n raw_shelf_len: usize,\n\n) -> FFIResult<i32> {\n\n let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy();\n\n let api_key = unsafe { CStr::from_ptr(api_key) }.to_string_lossy();\n\n info!(\"create_interior_ref_list api_url: {:?}, api_key: {:?}, shop_id: {:?}, raw_interior_ref_len: {:?}, raw_shelf_len: {:?}\", api_url, api_key, shop_id, raw_interior_ref_len, raw_shelf_len);\n\n let raw_interior_ref_slice = match raw_interior_ref_ptr.is_null() {\n\n true => &[],\n\n false => unsafe { slice::from_raw_parts(raw_interior_ref_ptr, raw_interior_ref_len) },\n\n };\n\n let raw_shelf_slice = match raw_shelf_ptr.is_null() {\n\n true => &[],\n\n false => unsafe { slice::from_raw_parts(raw_shelf_ptr, raw_shelf_len) },\n", "file_path": "src/interior_ref_list.rs", "rank": 49, "score": 12.344441366535913 }, { "content": "extern crate cbindgen;\n\n\n\nuse std::env;\n\n\n", "file_path": "build.rs", "rank": 50, "score": 12.038939358089447 }, { "content": " let result = update_shop(\n\n api_url,\n\n api_key,\n\n 1,\n\n name,\n\n description,\n\n 100,\n\n shop_type,\n\n keywords_ptr,\n\n keywords_len,\n\n true,\n\n );\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(raw_shop) => panic!(\"update_shop returned Ok result: {:#x?}\", raw_shop),\n\n FFIResult::Err(error) => match error {\n\n FFIError::Server(server_error) => {\n\n assert_eq!(server_error.status, 500);\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(server_error.title).to_string_lossy() },\n", "file_path": "src/shop.rs", "rank": 51, "score": 11.659700320012858 }, { "content": " amount: 100,\n\n quantity: 1,\n\n keywords,\n\n keywords_len,\n\n };\n\n let result = create_transaction(api_url, api_key, raw_transaction);\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(raw_transaction) => panic!(\n\n \"create_transaction returned Ok result: {:#?}\",\n\n raw_transaction\n\n ),\n\n FFIResult::Err(error) => match error {\n\n FFIError::Server(server_error) => {\n\n assert_eq!(server_error.status, 500);\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(server_error.title).to_string_lossy() },\n\n \"Internal Server Error\"\n\n );\n\n }\n\n _ => panic!(\"create_transaction did not return a server error\"),\n\n },\n\n }\n\n }\n\n}\n", "file_path": "src/transaction.rs", "rank": 52, "score": 11.535033494821036 }, { "content": " format!(\"{} {}\", server_error.status, unsafe {\n\n CStr::from_ptr(server_error.title).to_string_lossy()\n\n }),\n\n FFIError::Network(network_error) =>\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(),\n\n }\n\n ),\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_list_shops_server_error() {\n\n let mock = mock(\"GET\", \"/v1/shops?limit=128\")\n\n .with_status(500)\n\n .with_body(\"Internal Server Error\")\n\n .create();\n\n\n\n let api_url = CString::new(\"url\").unwrap().into_raw();\n\n let api_key = CString::new(\"api-key\").unwrap().into_raw();\n\n let result = list_shops(api_url, api_key);\n", "file_path": "src/shop.rs", "rank": 53, "score": 11.426893391745084 }, { "content": " form_type: 1,\n\n is_food: false,\n\n price: 100,\n\n keywords,\n\n keywords_len,\n\n }]\n\n .into_raw_parts();\n\n let result = create_merchandise_list(api_url, api_key, 1, ptr, len);\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(raw_merchandise_vec) => panic!(\n\n \"create_merchandise_list returned Ok result: {:#x?}\",\n\n raw_merchandise_vec\n\n ),\n\n FFIResult::Err(error) => match error {\n\n FFIError::Server(server_error) => {\n\n assert_eq!(server_error.status, 500);\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(server_error.title).to_string_lossy() },\n\n \"Internal Server Error\"\n", "file_path": "src/merchandise_list.rs", "rank": 55, "score": 11.263474243130599 }, { "content": "}\n\n\n\nimpl From<Error> for FFIError {\n\n fn from(error: Error) -> Self {\n\n if let Some(server_error) = error.downcast_ref::<ServerError>() {\n\n FFIError::Server(FFIServerError::from(server_error))\n\n } else {\n\n // TODO: also need to drop this CString once C++ is done reading it\n\n let err_string = CString::new(error.to_string())\n\n .expect(\"could not create CString\")\n\n .into_raw();\n\n FFIError::Network(err_string)\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, PartialEq)]\n\n#[repr(C, u8)]\n\npub enum FFIResult<T> {\n\n Ok(T),\n\n Err(FFIError),\n\n}\n", "file_path": "src/result.rs", "rank": 56, "score": 10.910557229719817 }, { "content": " .into_raw_parts();\n\n // TODO: need to pass this back into Rust once C++ is done with it so it can be manually dropped and the CStrings dropped from raw pointers.\n\n FFIResult::Ok(RawMerchandiseVec { ptr, len, cap })\n\n }\n\n Err(err) => {\n\n error!(\"get_merchandise_list_by_shop_id failed. {}\", err);\n\n FFIResult::Err(FFIError::from(err))\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::ffi::CString;\n\n\n\n use super::*;\n\n use chrono::Utc;\n\n use mockito::mock;\n\n\n\n #[test]\n", "file_path": "src/merchandise_list.rs", "rank": 57, "score": 10.691308257167353 }, { "content": " cap: shelf_cap,\n\n },\n\n })\n\n }\n\n Err(err) => {\n\n error!(\"get_interior_ref_list_by_shop_id failed. {}\", err);\n\n FFIResult::Err(FFIError::from(err))\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::ffi::CString;\n\n\n\n use super::*;\n\n use chrono::Utc;\n\n use mockito::mock;\n\n\n\n #[test]\n", "file_path": "src/interior_ref_list.rs", "rank": 58, "score": 10.553309210695907 }, { "content": " Err(err) => {\n\n error!(\"update_owner failed. {}\", err);\n\n FFIResult::Err(FFIError::from(err))\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::ffi::CString;\n\n\n\n use super::*;\n\n use chrono::Utc;\n\n use mockito::mock;\n\n\n\n #[test]\n\n fn test_create_owner() {\n\n let example = SavedOwner {\n\n id: 1,\n\n name: \"name\".to_string(),\n", "file_path": "src/owner.rs", "rank": 59, "score": 10.364366322620036 }, { "content": " unsafe { CStr::from_ptr(keywords_slice[0]) }\n\n .to_string_lossy()\n\n .to_string(),\n\n \"VendorItemWeapon\".to_string(),\n\n );\n\n }\n\n FFIResult::Err(error) => panic!(\n\n \"get_merchandise_list_by_shop_id returned error: {:?}\",\n\n match error {\n\n FFIError::Server(server_error) =>\n\n format!(\"{} {}\", server_error.status, unsafe {\n\n CStr::from_ptr(server_error.title).to_string_lossy()\n\n }),\n\n FFIError::Network(network_error) =>\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(),\n\n }\n\n ),\n\n }\n\n }\n\n\n", "file_path": "src/merchandise_list.rs", "rank": 60, "score": 10.36042606637963 }, { "content": " .with_header(\"content-type\", \"application/octet-stream\")\n\n .with_body(bincode::serialize(&example).unwrap())\n\n .create();\n\n\n\n let api_url = CString::new(\"url\").unwrap().into_raw();\n\n let api_key = CString::new(\"api-key\").unwrap().into_raw();\n\n let name = CString::new(\"name\").unwrap().into_raw();\n\n let mod_version = 1;\n\n let result = update_owner(api_url, api_key, 1, name, mod_version);\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(raw_owner) => {\n\n assert_eq!(raw_owner.id, 1);\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(raw_owner.name).to_string_lossy() },\n\n \"name\"\n\n );\n\n assert_eq!(raw_owner.mod_version, 1);\n\n }\n\n FFIResult::Err(error) => panic!(\n", "file_path": "src/owner.rs", "rank": 61, "score": 10.350420660616873 }, { "content": " unsafe { CStr::from_ptr(raw_owner.name).to_string_lossy() },\n\n \"name\"\n\n );\n\n assert_eq!(raw_owner.mod_version, 1);\n\n }\n\n FFIResult::Err(error) => panic!(\n\n \"create_owner returned error: {:?}\",\n\n match error {\n\n FFIError::Server(server_error) =>\n\n format!(\"{} {}\", server_error.status, unsafe {\n\n CStr::from_ptr(server_error.title).to_string_lossy()\n\n }),\n\n FFIError::Network(network_error) =>\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(),\n\n }\n\n ),\n\n }\n\n }\n\n\n\n #[test]\n", "file_path": "src/owner.rs", "rank": 62, "score": 10.31987037425653 }, { "content": " interior_ref_ptr,\n\n interior_ref_len,\n\n shelf_ptr,\n\n shelf_len,\n\n );\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(interior_ref_list_id) => {\n\n assert_eq!(interior_ref_list_id, 1);\n\n }\n\n FFIResult::Err(error) => panic!(\n\n \"create_interior_ref_list returned error: {:?}\",\n\n match error {\n\n FFIError::Server(server_error) =>\n\n format!(\"{} {}\", server_error.status, unsafe {\n\n CStr::from_ptr(server_error.title).to_string_lossy()\n\n }),\n\n FFIError::Network(network_error) =>\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(),\n\n }\n", "file_path": "src/interior_ref_list.rs", "rank": 63, "score": 10.281116645467792 }, { "content": " .to_string_lossy()\n\n .to_string()\n\n })\n\n .collect(),\n\n },\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\n#[repr(C)]\n\npub struct RawTransaction {\n\n pub id: i32,\n\n pub shop_id: i32,\n\n pub mod_name: *const c_char,\n\n pub local_form_id: i32,\n\n pub name: *const c_char,\n\n pub form_type: i32,\n\n pub is_food: bool,\n\n pub price: i32,\n", "file_path": "src/transaction.rs", "rank": 64, "score": 10.225580830657247 }, { "content": " \"update_owner returned error: {:?}\",\n\n match error {\n\n FFIError::Server(server_error) =>\n\n format!(\"{} {}\", server_error.status, unsafe {\n\n CStr::from_ptr(server_error.title).to_string_lossy()\n\n }),\n\n FFIError::Network(network_error) =>\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(),\n\n }\n\n ),\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_update_owner_server_error() {\n\n let mock = mock(\"PATCH\", \"/v1/owners/1\")\n\n .with_status(500)\n\n .with_body(\"Internal Server Error\")\n\n .create();\n\n\n", "file_path": "src/owner.rs", "rank": 65, "score": 10.101391614515535 }, { "content": " mock.assert();\n\n match result {\n\n FFIResult::Ok(raw_shop) => panic!(\"list_shops returned Ok result: {:#x?}\", raw_shop),\n\n FFIResult::Err(error) => match error {\n\n FFIError::Network(network_error) => {\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() },\n\n \"Object not found in API or in cache: shops.bin\",\n\n );\n\n }\n\n _ => panic!(\"list_shops did not return a network error\"),\n\n },\n\n }\n\n }\n\n}\n", "file_path": "src/shop.rs", "rank": 66, "score": 10.039773284760422 }, { "content": " \"get_merchandise_list returned error: {:?}\",\n\n match error {\n\n FFIError::Server(server_error) =>\n\n format!(\"{} {}\", server_error.status, unsafe {\n\n CStr::from_ptr(server_error.title).to_string_lossy()\n\n }),\n\n FFIError::Network(network_error) =>\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(),\n\n }\n\n ),\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_get_merchandise_list_server_error() {\n\n let mock = mock(\"GET\", \"/v1/merchandise_lists/1\")\n\n .with_status(500)\n\n .with_body(\"Internal Server Error\")\n\n .create();\n\n\n", "file_path": "src/merchandise_list.rs", "rank": 67, "score": 9.971983710890784 }, { "content": " }\n\n }\n\n Err(err) => {\n\n error!(\"get_merchandise_list_by_shop_id api request error: {}\", err);\n\n from_file_cache(&body_cache_path)\n\n }\n\n }\n\n }\n\n\n\n match inner(&api_url, &api_key, shop_id) {\n\n Ok(merchandise_list) => {\n\n let (ptr, len, cap) = merchandise_list\n\n .form_list\n\n .into_iter()\n\n .map(|merchandise| {\n\n let (keywords_ptr, keywords_len, _) = merchandise\n\n .keywords\n\n .into_iter()\n\n .map(|keyword| {\n\n CString::new(keyword).unwrap_or_default().into_raw() as *const c_char\n", "file_path": "src/merchandise_list.rs", "rank": 68, "score": 9.938180572127568 }, { "content": " FFIResult::Err(error) => panic!(\n\n \"get_shop returned error: {:?}\",\n\n match error {\n\n FFIError::Server(server_error) =>\n\n format!(\"{} {}\", server_error.status, unsafe {\n\n CStr::from_ptr(server_error.title).to_string_lossy()\n\n }),\n\n FFIError::Network(network_error) =>\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(),\n\n }\n\n ),\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_get_shop_server_error() {\n\n let mock = mock(\"GET\", \"/v1/shops/1\")\n\n .with_status(500)\n\n .with_body(\"Internal Server Error\")\n\n .create();\n", "file_path": "src/shop.rs", "rank": 69, "score": 9.935479303524327 }, { "content": " FFIResult::Err(error) => panic!(\n\n \"create_shop returned error: {:?}\",\n\n match error {\n\n FFIError::Server(server_error) =>\n\n format!(\"{} {}\", server_error.status, unsafe {\n\n CStr::from_ptr(server_error.title).to_string_lossy()\n\n }),\n\n FFIError::Network(network_error) =>\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(),\n\n }\n\n ),\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_create_shop_server_error() {\n\n let mock = mock(\"POST\", \"/v1/shops\")\n\n .with_status(500)\n\n .with_body(\"Internal Server Error\")\n\n .create();\n", "file_path": "src/shop.rs", "rank": 70, "score": 9.935479303524327 }, { "content": " }\n\n }\n\n }\n\n\n\n match inner(&api_url, &api_key) {\n\n Ok(shops) => {\n\n // TODO: need to pass this back into Rust once C++ is done with it so it can be manually dropped and the CStrings dropped from raw pointers.\n\n let raw_shops: Vec<RawShop> = shops.into_iter().map(RawShop::from).collect();\n\n let (ptr, len, cap) = raw_shops.into_raw_parts();\n\n FFIResult::Ok(RawShopVec { ptr, len, cap })\n\n }\n\n Err(err) => {\n\n error!(\"list_shops failed. {}\", err);\n\n FFIResult::Err(FFIError::from(err))\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "src/shop.rs", "rank": 71, "score": 9.933975306190735 }, { "content": "\n\n#[derive(Debug)]\n\n#[repr(C)]\n\npub struct RawShop {\n\n pub id: i32,\n\n pub name: *const c_char,\n\n pub description: *const c_char,\n\n pub gold: i32,\n\n pub shop_type: *const c_char,\n\n pub vendor_keywords: *mut *const c_char,\n\n pub vendor_keywords_len: usize,\n\n pub vendor_keywords_exclude: bool,\n\n}\n\n\n\nimpl From<SavedShop> for RawShop {\n\n fn from(shop: SavedShop) -> Self {\n\n let (keywords_ptr, keywords_len, _) = shop\n\n .vendor_keywords\n\n .into_iter()\n\n .map(|keyword| CString::new(keyword).unwrap_or_default().into_raw() as *const c_char)\n", "file_path": "src/shop.rs", "rank": 72, "score": 9.826940207869436 }, { "content": " Some(form_type) => form_type,\n\n },\n\n filter_is_food: shelf.filter_is_food,\n\n search: match shelf.search {\n\n None => std::ptr::null(),\n\n Some(search) => CString::new(search).unwrap_or_default().into_raw(),\n\n },\n\n sort_on: match shelf.sort_on {\n\n None => std::ptr::null(),\n\n Some(sort_on) => CString::new(sort_on).unwrap_or_default().into_raw(),\n\n },\n\n sort_asc: shelf.sort_asc,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\n#[repr(C)]\n\npub struct RawInteriorRefVec {\n\n pub ptr: *mut RawInteriorRef,\n", "file_path": "src/interior_ref_list.rs", "rank": 73, "score": 9.810167986072113 }, { "content": " pub mod_name: String,\n\n pub local_form_id: i32,\n\n pub name: String,\n\n pub form_type: i32,\n\n pub is_food: bool,\n\n pub price: i32,\n\n pub is_sell: bool,\n\n pub quantity: i32,\n\n pub amount: i32,\n\n pub keywords: Vec<String>,\n\n pub created_at: NaiveDateTime,\n\n pub updated_at: NaiveDateTime,\n\n}\n\n\n\nimpl From<RawTransaction> for Transaction {\n\n fn from(raw_transaction: RawTransaction) -> Self {\n\n Self {\n\n shop_id: raw_transaction.shop_id,\n\n owner_id: None,\n\n mod_name: unsafe { CStr::from_ptr(raw_transaction.mod_name) }\n", "file_path": "src/transaction.rs", "rank": 74, "score": 9.799874509125473 }, { "content": " }\n\n ),\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_update_shop_server_error() {\n\n let mock = mock(\"PATCH\", \"/v1/shops/1\")\n\n .with_status(500)\n\n .with_body(\"Internal Server Error\")\n\n .create();\n\n\n\n let api_url = CString::new(\"url\").unwrap().into_raw();\n\n let api_key = CString::new(\"api-key\").unwrap().into_raw();\n\n let name = CString::new(\"name\").unwrap().into_raw();\n\n let description = CString::new(\"description\").unwrap().into_raw();\n\n let shop_type = CString::new(\"general_store\").unwrap().into_raw();\n\n let (keywords_ptr, keywords_len, _) =\n\n vec![CString::new(\"VendorNoSale\").unwrap().into_raw() as *const c_char]\n\n .into_raw_parts();\n", "file_path": "src/shop.rs", "rank": 75, "score": 9.770898046305472 }, { "content": " let metadata_cache_path =\n\n cache_dir.join(format!(\"owner_{}_metadata.json\", saved_owner.id));\n\n update_file_caches(body_cache_path, metadata_cache_path, bytes, headers);\n\n Ok(saved_owner)\n\n } else {\n\n Err(extract_error_from_response(status, &bytes))\n\n }\n\n }\n\n\n\n match inner(&api_url, &api_key, &name, mod_version) {\n\n Ok(owner) => {\n\n info!(\"create_owner successful\");\n\n FFIResult::Ok(RawOwner::from(owner))\n\n }\n\n Err(err) => {\n\n error!(\"create_owner failed. {}\", err);\n\n FFIResult::Err(FFIError::from(err))\n\n }\n\n }\n\n}\n", "file_path": "src/owner.rs", "rank": 76, "score": 9.735704323156687 }, { "content": " unsafe {\n\n slice::from_raw_parts(\n\n raw_transaction.keywords,\n\n raw_transaction.keywords_len,\n\n )\n\n }\n\n .iter()\n\n .map(|&keyword| {\n\n unsafe { CStr::from_ptr(keyword).to_string_lossy().to_string() }\n\n })\n\n .collect::<Vec<String>>(),\n\n vec![\"VendorItemMisc\".to_string()]\n\n );\n\n }\n\n FFIResult::Err(error) => panic!(\n\n \"create_transaction returned error: {:?}\",\n\n match error {\n\n FFIError::Server(server_error) =>\n\n format!(\"{} {}\", server_error.status, unsafe {\n\n CStr::from_ptr(server_error.title).to_string_lossy()\n", "file_path": "src/transaction.rs", "rank": 77, "score": 9.632332221880947 }, { "content": ") -> FFIResult<RawMerchandiseVec> {\n\n info!(\"get_merchandise_list begin\");\n\n let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy();\n\n let api_key = unsafe { CStr::from_ptr(api_key) }.to_string_lossy();\n\n info!(\n\n \"get_merchandise_list api_url: {:?}, api_key: {:?}, merchandise_list_id: {:?}\",\n\n api_url, api_key, merchandise_list_id\n\n );\n\n\n\n fn inner(\n\n api_url: &str,\n\n api_key: &str,\n\n merchandise_list_id: i32,\n\n ) -> Result<SavedMerchandiseList> {\n\n #[cfg(not(test))]\n\n let url =\n\n Url::parse(api_url)?.join(&format!(\"v1/merchandise_lists/{}\", merchandise_list_id))?;\n\n #[cfg(test)]\n\n let url = Url::parse(&mockito::server_url())?\n\n .join(&format!(\"v1/merchandise_lists/{}\", merchandise_list_id))?;\n", "file_path": "src/merchandise_list.rs", "rank": 78, "score": 9.61847894932905 }, { "content": " let keywords_slice = unsafe {\n\n slice::from_raw_parts(raw_shop.vendor_keywords, raw_shop.vendor_keywords_len)\n\n };\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(keywords_slice[0]) }\n\n .to_string_lossy()\n\n .to_string(),\n\n \"VendorNoSale\".to_string(),\n\n );\n\n assert_eq!(raw_shop.vendor_keywords_exclude, true);\n\n }\n\n FFIResult::Err(error) => panic!(\n\n \"update_shop returned error: {:?}\",\n\n match error {\n\n FFIError::Server(server_error) =>\n\n format!(\"{} {}\", server_error.status, unsafe {\n\n CStr::from_ptr(server_error.title).to_string_lossy()\n\n }),\n\n FFIError::Network(network_error) =>\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(),\n", "file_path": "src/shop.rs", "rank": 79, "score": 9.589803972858693 }, { "content": " raw_merchandise_len: usize,\n\n) -> FFIResult<RawMerchandiseVec> {\n\n let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy();\n\n let api_key = unsafe { CStr::from_ptr(api_key) }.to_string_lossy();\n\n info!(\"update_merchandise_list api_url: {:?}, api_key: {:?}, shop_id: {:?}, raw_merchandise_len: {:?}, raw_merchandise_ptr: {:?}\", api_url, api_key, shop_id, raw_merchandise_len, raw_merchandise_ptr);\n\n let raw_merchandise_slice = match raw_merchandise_ptr.is_null() {\n\n true => &[],\n\n false => unsafe { slice::from_raw_parts(raw_merchandise_ptr, raw_merchandise_len) },\n\n };\n\n\n\n fn inner(\n\n api_url: &str,\n\n api_key: &str,\n\n shop_id: i32,\n\n raw_merchandise_slice: &[RawMerchandise],\n\n ) -> Result<SavedMerchandiseList> {\n\n #[cfg(not(test))]\n\n let url = Url::parse(api_url)?.join(&format!(\"v1/shops/{}/merchandise_list\", shop_id))?;\n\n #[cfg(test)]\n\n let url = Url::parse(&mockito::server_url())?\n", "file_path": "src/merchandise_list.rs", "rank": 80, "score": 9.53320857274722 }, { "content": " pub filter_is_food: bool,\n\n pub search: *const c_char,\n\n pub sort_on: *const c_char,\n\n pub sort_asc: bool,\n\n}\n\n\n\nimpl From<Shelf> for RawShelf {\n\n fn from(shelf: Shelf) -> Self {\n\n Self {\n\n shelf_type: shelf.shelf_type,\n\n position_x: shelf.position_x,\n\n position_y: shelf.position_y,\n\n position_z: shelf.position_z,\n\n angle_x: shelf.angle_x,\n\n angle_y: shelf.angle_y,\n\n angle_z: shelf.angle_z,\n\n scale: shelf.scale,\n\n page: shelf.page,\n\n filter_form_type: match shelf.filter_form_type {\n\n None => 0,\n", "file_path": "src/interior_ref_list.rs", "rank": 81, "score": 9.526218739698349 }, { "content": " 1,\n\n interior_ref_ptr,\n\n interior_ref_len,\n\n shelf_ptr,\n\n shelf_len,\n\n );\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(interior_ref_list_id) => panic!(\n\n \"update_interior_ref_list returned Ok result: {:?}\",\n\n interior_ref_list_id\n\n ),\n\n FFIResult::Err(error) => match error {\n\n FFIError::Server(server_error) => {\n\n assert_eq!(server_error.status, 500);\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(server_error.title).to_string_lossy() },\n\n \"Internal Server Error\"\n\n );\n\n }\n", "file_path": "src/interior_ref_list.rs", "rank": 82, "score": 9.503246431626048 }, { "content": " pub shop_id: i32,\n\n pub owner_id: i32,\n\n pub form_list: Vec<Merchandise>,\n\n pub created_at: NaiveDateTime,\n\n pub updated_at: NaiveDateTime,\n\n}\n\n\n\n#[derive(Debug)]\n\n#[repr(C)]\n\npub struct RawMerchandise {\n\n pub mod_name: *const c_char,\n\n pub local_form_id: u32,\n\n pub name: *const c_char,\n\n pub quantity: u32,\n\n pub form_type: u32,\n\n pub is_food: bool,\n\n pub price: u32,\n\n pub keywords: *mut *const c_char,\n\n pub keywords_len: usize,\n\n}\n", "file_path": "src/merchandise_list.rs", "rank": 83, "score": 9.403964318265578 }, { "content": " .to_string_lossy()\n\n .to_string(),\n\n \"Iron Sword\".to_string(),\n\n );\n\n assert_eq!(raw_merchandise.quantity, 1);\n\n assert_eq!(raw_merchandise.form_type, 1);\n\n assert_eq!(raw_merchandise.is_food, false);\n\n assert_eq!(raw_merchandise.price, 100);\n\n }\n\n FFIResult::Err(error) => panic!(\n\n \"create_merchandise_list returned error: {:?}\",\n\n match error {\n\n FFIError::Server(server_error) =>\n\n format!(\"{} {}\", server_error.status, unsafe {\n\n CStr::from_ptr(server_error.title).to_string_lossy()\n\n }),\n\n FFIError::Network(network_error) =>\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(),\n\n }\n\n ),\n", "file_path": "src/merchandise_list.rs", "rank": 84, "score": 9.399081139145084 }, { "content": " }\n\n }\n\n\n\n #[test]\n\n fn test_create_merchandise_list_server_error() {\n\n let mock = mock(\"POST\", \"/v1/merchandise_lists\")\n\n .with_status(500)\n\n .with_body(\"Internal Server Error\")\n\n .create();\n\n\n\n let (keywords, keywords_len, _) =\n\n vec![CString::new(\"VendorItemWeapon\").unwrap().into_raw() as *const c_char]\n\n .into_raw_parts();\n\n let api_url = CString::new(\"url\").unwrap().into_raw();\n\n let api_key = CString::new(\"api-key\").unwrap().into_raw();\n\n let (ptr, len, _cap) = vec![RawMerchandise {\n\n mod_name: CString::new(\"Skyrim.esm\").unwrap().into_raw(),\n\n local_form_id: 1,\n\n name: CString::new(\"Iron Sword\").unwrap().into_raw(),\n\n quantity: 1,\n", "file_path": "src/merchandise_list.rs", "rank": 85, "score": 9.358173204880604 }, { "content": " FFIResult::Ok(interior_ref_list_id) => {\n\n assert_eq!(interior_ref_list_id, 1);\n\n }\n\n FFIResult::Err(error) => panic!(\n\n \"update_interior_ref_list returned error: {:?}\",\n\n match error {\n\n FFIError::Server(server_error) =>\n\n format!(\"{} {}\", server_error.status, unsafe {\n\n CStr::from_ptr(server_error.title).to_string_lossy()\n\n }),\n\n FFIError::Network(network_error) =>\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(),\n\n }\n\n ),\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_update_interior_ref_list_server_error() {\n\n let mock = mock(\"PATCH\", \"/v1/shops/1/interior_ref_list\")\n", "file_path": "src/interior_ref_list.rs", "rank": 86, "score": 9.352390141821079 }, { "content": " pub is_sell: bool,\n\n pub quantity: i32,\n\n pub amount: i32,\n\n pub keywords: *mut *const c_char,\n\n pub keywords_len: usize,\n\n}\n\n\n\nimpl From<SavedTransaction> for RawTransaction {\n\n fn from(transaction: SavedTransaction) -> Self {\n\n let (keywords_ptr, keywords_len, _) = transaction\n\n .keywords\n\n .into_iter()\n\n .map(|keyword| CString::new(keyword).unwrap_or_default().into_raw() as *const c_char)\n\n .collect::<Vec<*const c_char>>()\n\n .into_raw_parts();\n\n Self {\n\n id: transaction.id,\n\n shop_id: transaction.shop_id,\n\n mod_name: CString::new(transaction.mod_name)\n\n .unwrap_or_default()\n", "file_path": "src/transaction.rs", "rank": 87, "score": 9.233580568990547 }, { "content": " pub shop_id: i32,\n\n pub owner_id: Option<i32>,\n\n pub form_list: Vec<Merchandise>,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\npub struct Merchandise {\n\n pub mod_name: String,\n\n pub local_form_id: u32,\n\n pub name: String,\n\n pub quantity: u32,\n\n pub form_type: u32,\n\n pub is_food: bool,\n\n pub price: u32,\n\n pub keywords: Vec<String>,\n\n}\n\n\n\nimpl MerchandiseList {\n\n pub fn from_game(shop_id: i32, merch_records: &[RawMerchandise]) -> Self {\n\n info!(\"MerchandiseList::from_game shop_id: {:?}\", shop_id);\n", "file_path": "src/merchandise_list.rs", "rank": 88, "score": 9.180565188637491 }, { "content": " raw_merchandise_vec\n\n ),\n\n FFIResult::Err(error) => match error {\n\n FFIError::Server(server_error) => {\n\n assert_eq!(server_error.status, 500);\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(server_error.title).to_string_lossy() },\n\n \"Internal Server Error\"\n\n );\n\n }\n\n _ => panic!(\"update_merchandise_list did not return a server error\"),\n\n },\n\n }\n\n }\n\n #[test]\n\n fn test_get_merchandise_list() {\n\n let example = SavedMerchandiseList {\n\n id: 1,\n\n owner_id: 1,\n\n shop_id: 1,\n", "file_path": "src/merchandise_list.rs", "rank": 89, "score": 9.122313411476915 }, { "content": " ),\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_create_interior_ref_list_server_error() {\n\n let mock = mock(\"POST\", \"/v1/interior_ref_lists\")\n\n .with_status(500)\n\n .with_body(\"Internal Server Error\")\n\n .create();\n\n\n\n let api_url = CString::new(\"url\").unwrap().into_raw();\n\n let api_key = CString::new(\"api-key\").unwrap().into_raw();\n\n let (interior_ref_ptr, interior_ref_len, _cap) = vec![RawInteriorRef {\n\n base_mod_name: CString::new(\"Skyrim.esm\").unwrap().into_raw(),\n\n base_local_form_id: 1,\n\n ref_mod_name: CString::new(\"BazaarRealm.esp\").unwrap().into_raw(),\n\n ref_local_form_id: 1,\n\n position_x: 100.,\n\n position_y: 0.,\n", "file_path": "src/interior_ref_list.rs", "rank": 90, "score": 9.042134335677401 }, { "content": " ),\n\n },\n\n sort_on: match rec.sort_on.is_null() {\n\n true => None,\n\n false => Some(\n\n unsafe { CStr::from_ptr(rec.sort_on) }\n\n .to_string_lossy()\n\n .to_string(),\n\n ),\n\n },\n\n sort_asc: rec.sort_asc,\n\n })\n\n .collect(),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub struct SavedInteriorRefList {\n\n pub id: i32,\n", "file_path": "src/interior_ref_list.rs", "rank": 91, "score": 9.040088001666874 }, { "content": " \"get_interior_ref_list_by_shop_id returned Ok result: {:#x?}\",\n\n raw_interior_ref_vec\n\n ),\n\n FFIResult::Err(error) => match error {\n\n FFIError::Network(network_error) => {\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() },\n\n \"Object not found in API or in cache: shop_1_interior_ref_list.bin\",\n\n );\n\n }\n\n _ => panic!(\"get_interior_ref_list_by_shop_id did not return a network error\"),\n\n },\n\n }\n\n }\n\n}\n", "file_path": "src/interior_ref_list.rs", "rank": 92, "score": 8.961961504943526 }, { "content": " pub sort_asc: bool,\n\n}\n\n\n\nimpl InteriorRefList {\n\n pub fn from_game(\n\n shop_id: i32,\n\n raw_interior_ref_slice: &[RawInteriorRef],\n\n raw_shelves_slice: &[RawShelf],\n\n ) -> Self {\n\n Self {\n\n shop_id,\n\n owner_id: None,\n\n ref_list: raw_interior_ref_slice\n\n .iter()\n\n .map(|rec| InteriorRef {\n\n base_mod_name: unsafe { CStr::from_ptr(rec.base_mod_name) }\n\n .to_string_lossy()\n\n .to_string(),\n\n base_local_form_id: rec.base_local_form_id,\n\n ref_mod_name: match rec.ref_mod_name.is_null() {\n", "file_path": "src/interior_ref_list.rs", "rank": 93, "score": 8.818038654949714 }, { "content": " assert_eq!(\n\n unsafe { CStr::from_ptr(raw_shop.shop_type).to_string_lossy() },\n\n \"general_store\"\n\n );\n\n assert!(!raw_shop.vendor_keywords.is_null());\n\n let keywords_slice = unsafe {\n\n slice::from_raw_parts(raw_shop.vendor_keywords, raw_shop.vendor_keywords_len)\n\n };\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(keywords_slice[0]) }\n\n .to_string_lossy()\n\n .to_string(),\n\n \"VendorNoSale\".to_string(),\n\n );\n\n assert_eq!(raw_shop.vendor_keywords_exclude, true);\n\n }\n\n FFIResult::Err(error) => panic!(\n\n \"list_shops returned error: {:?}\",\n\n match error {\n\n FFIError::Server(server_error) =>\n", "file_path": "src/shop.rs", "rank": 94, "score": 8.735943271524167 }, { "content": " let mock = mock(\"POST\", \"/v1/shops\")\n\n .with_status(201)\n\n .with_header(\"content-type\", \"application/octet-stream\")\n\n .with_body(bincode::serialize(&example).unwrap())\n\n .create();\n\n\n\n let api_url = CString::new(\"url\").unwrap().into_raw();\n\n let api_key = CString::new(\"api-key\").unwrap().into_raw();\n\n let name = CString::new(\"name\").unwrap().into_raw();\n\n let description = CString::new(\"description\").unwrap().into_raw();\n\n let result = create_shop(api_url, api_key, name, description);\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(raw_shop) => {\n\n assert_eq!(raw_shop.id, 1);\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(raw_shop.name).to_string_lossy() },\n\n \"name\"\n\n );\n\n assert_eq!(\n", "file_path": "src/shop.rs", "rank": 95, "score": 8.728040499275878 }, { "content": " assert_eq!(raw_shelf.angle_z, 0.);\n\n assert_eq!(raw_shelf.scale, 1);\n\n assert_eq!(raw_shelf.filter_form_type, 0);\n\n assert_eq!(raw_shelf.filter_is_food, false);\n\n assert_eq!(raw_shelf.search, std::ptr::null());\n\n assert_eq!(raw_shelf.sort_on, std::ptr::null());\n\n assert_eq!(raw_shelf.sort_asc, true);\n\n }\n\n FFIResult::Err(error) => panic!(\n\n \"get_interior_ref_list returned error: {:?}\",\n\n match error {\n\n FFIError::Server(server_error) =>\n\n format!(\"{} {}\", server_error.status, unsafe {\n\n CStr::from_ptr(server_error.title).to_string_lossy()\n\n }),\n\n FFIError::Network(network_error) =>\n\n unsafe { CStr::from_ptr(network_error).to_string_lossy() }.to_string(),\n\n }\n\n ),\n\n }\n", "file_path": "src/interior_ref_list.rs", "rank": 96, "score": 8.69732293945731 }, { "content": " let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy();\n\n let api_key = unsafe { CStr::from_ptr(api_key) }.to_string_lossy();\n\n let name = unsafe { CStr::from_ptr(name) }\n\n .to_string_lossy()\n\n .to_string();\n\n let description = unsafe { CStr::from_ptr(description) }\n\n .to_string_lossy()\n\n .to_string();\n\n let shop_type = unsafe { CStr::from_ptr(shop_type) }\n\n .to_string_lossy()\n\n .to_string();\n\n let keywords = match vendor_keywords.is_null() {\n\n true => vec![],\n\n false => unsafe { slice::from_raw_parts(vendor_keywords, vendor_keywords_len) }\n\n .iter()\n\n .map(|&keyword| {\n\n unsafe { CStr::from_ptr(keyword) }\n\n .to_string_lossy()\n\n .to_string()\n\n })\n", "file_path": "src/shop.rs", "rank": 97, "score": 8.668364623274723 }, { "content": " .into_raw_parts();\n\n let api_url = CString::new(\"url\").unwrap().into_raw();\n\n let api_key = CString::new(\"api-key\").unwrap().into_raw();\n\n let (ptr, len, _cap) = vec![RawMerchandise {\n\n mod_name: CString::new(\"Skyrim.esm\").unwrap().into_raw(),\n\n local_form_id: 1,\n\n name: CString::new(\"Iron Sword\").unwrap().into_raw(),\n\n quantity: 1,\n\n form_type: 1,\n\n is_food: false,\n\n price: 100,\n\n keywords,\n\n keywords_len,\n\n }]\n\n .into_raw_parts();\n\n let result = update_merchandise_list(api_url, api_key, 1, ptr, len);\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(raw_merchandise_vec) => panic!(\n\n \"update_merchandise_list returned Ok result: {:#x?}\",\n", "file_path": "src/merchandise_list.rs", "rank": 98, "score": 8.59481746679619 }, { "content": " updated_at: Utc::now().naive_utc(),\n\n };\n\n let mock = mock(\"GET\", \"/v1/shops/1\")\n\n .with_status(201)\n\n .with_header(\"content-type\", \"application/octet-stream\")\n\n .with_body(bincode::serialize(&example).unwrap())\n\n .create();\n\n\n\n let api_url = CString::new(\"url\").unwrap().into_raw();\n\n let api_key = CString::new(\"api-key\").unwrap().into_raw();\n\n let result = get_shop(api_url, api_key, 1);\n\n mock.assert();\n\n match result {\n\n FFIResult::Ok(raw_shop) => {\n\n assert_eq!(raw_shop.id, 1);\n\n assert_eq!(\n\n unsafe { CStr::from_ptr(raw_shop.name).to_string_lossy() },\n\n \"name\"\n\n );\n\n assert_eq!(\n", "file_path": "src/shop.rs", "rank": 99, "score": 8.573932698606345 } ]
Rust
capsules/src/nrf51822_serialization.rs
jettr/tock
419f293f649989bf208af731f343886ff0fe3748
use core::cmp; use kernel::common::cells::{OptionalCell, TakeCell}; use kernel::hil; use kernel::hil::uart; use kernel::{ CommandReturn, Driver, ErrorCode, Grant, ProcessId, ReadOnlyProcessBuffer, ReadWriteProcessBuffer, ReadableProcessBuffer, WriteableProcessBuffer, }; use crate::driver; pub const DRIVER_NUM: usize = driver::NUM::Nrf51822Serialization as usize; #[derive(Default)] pub struct App { tx_buffer: ReadOnlyProcessBuffer, rx_buffer: ReadWriteProcessBuffer, } pub static mut WRITE_BUF: [u8; 600] = [0; 600]; pub static mut READ_BUF: [u8; 600] = [0; 600]; pub struct Nrf51822Serialization<'a> { uart: &'a dyn uart::UartAdvanced<'a>, reset_pin: &'a dyn hil::gpio::Pin, apps: Grant<App, 1>, active_app: OptionalCell<ProcessId>, tx_buffer: TakeCell<'static, [u8]>, rx_buffer: TakeCell<'static, [u8]>, } impl<'a> Nrf51822Serialization<'a> { pub fn new( uart: &'a dyn uart::UartAdvanced<'a>, grant: Grant<App, 1>, reset_pin: &'a dyn hil::gpio::Pin, tx_buffer: &'static mut [u8], rx_buffer: &'static mut [u8], ) -> Nrf51822Serialization<'a> { Nrf51822Serialization { uart: uart, reset_pin: reset_pin, apps: grant, active_app: OptionalCell::empty(), tx_buffer: TakeCell::new(tx_buffer), rx_buffer: TakeCell::new(rx_buffer), } } pub fn initialize(&self) { let _ = self.uart.configure(uart::Parameters { baud_rate: 250000, width: uart::Width::Eight, stop_bits: uart::StopBits::One, parity: uart::Parity::Even, hw_flow_control: true, }); } pub fn reset(&self) { self.reset_pin.make_output(); self.reset_pin.clear(); for _ in 0..10 { self.reset_pin.clear(); } self.reset_pin.set(); } } impl Driver for Nrf51822Serialization<'_> { fn allow_readwrite( &self, appid: ProcessId, allow_type: usize, mut slice: ReadWriteProcessBuffer, ) -> Result<ReadWriteProcessBuffer, (ReadWriteProcessBuffer, ErrorCode)> { let res = match allow_type { 0 => { self.active_app.set(appid); self.apps .enter(appid, |app, _| { core::mem::swap(&mut app.rx_buffer, &mut slice); }) .map_err(ErrorCode::from) } _ => Err(ErrorCode::NOSUPPORT), }; if let Err(e) = res { Err((slice, e)) } else { Ok(slice) } } fn allow_readonly( &self, appid: ProcessId, allow_type: usize, mut slice: ReadOnlyProcessBuffer, ) -> Result<ReadOnlyProcessBuffer, (ReadOnlyProcessBuffer, ErrorCode)> { let res = match allow_type { 0 => { self.active_app.set(appid); self.apps .enter(appid, |app, _| { core::mem::swap(&mut app.tx_buffer, &mut slice) }) .map_err(ErrorCode::from) } _ => Err(ErrorCode::NOSUPPORT), }; if let Err(e) = res { Err((slice, e)) } else { Ok(slice) } } fn command( &self, command_type: usize, arg1: usize, _: usize, appid: ProcessId, ) -> CommandReturn { match command_type { 0 /* check if present */ => CommandReturn::success(), 1 => { self.apps.enter(appid, |app, _| { app.tx_buffer.enter(|slice| { let write_len = slice.len(); self.tx_buffer.take().map_or(CommandReturn::failure(ErrorCode::FAIL), |buffer| { for (i, c) in slice.iter().enumerate() { buffer[i] = c.get(); } let _ = self.uart.transmit_buffer(buffer, write_len); CommandReturn::success() }) }).unwrap_or(CommandReturn::failure(ErrorCode::FAIL)) }).unwrap_or(CommandReturn::failure(ErrorCode::FAIL)) } 2 => { self.rx_buffer.take().map_or(CommandReturn::failure(ErrorCode::RESERVE), |buffer| { let len = arg1; if len > buffer.len() { CommandReturn::failure(ErrorCode::SIZE) } else { let _ = self.uart.receive_automatic(buffer, len, 250); CommandReturn::success_u32(len as u32) } }) } 3 => { self.reset(); CommandReturn::success() } _ => CommandReturn::failure(ErrorCode::NOSUPPORT), } } fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::procs::Error> { self.apps.enter(processid, |_, _| {}) } } impl uart::TransmitClient for Nrf51822Serialization<'_> { fn transmitted_buffer( &self, buffer: &'static mut [u8], _tx_len: usize, _rcode: Result<(), ErrorCode>, ) { self.tx_buffer.replace(buffer); self.active_app.map(|appid| { let _ = self.apps.enter(*appid, |_app, upcalls| { upcalls.schedule_upcall(0, 1, 0, 0).ok(); }); }); } fn transmitted_word(&self, _rcode: Result<(), ErrorCode>) {} } impl uart::ReceiveClient for Nrf51822Serialization<'_> { fn received_buffer( &self, buffer: &'static mut [u8], rx_len: usize, _rcode: Result<(), ErrorCode>, _error: uart::Error, ) { self.rx_buffer.replace(buffer); self.active_app.map(|appid| { let _ = self.apps.enter(*appid, |app, upcalls| { let len = app .rx_buffer .mut_enter(|rb| { let max_len = cmp::min(rx_len, rb.len()); self.rx_buffer.map_or(0, |buffer| { for idx in 0..max_len { rb[idx].set(buffer[idx]); } max_len }) }) .unwrap_or(0); upcalls.schedule_upcall(0, 4, rx_len, len).ok(); }); }); self.rx_buffer.take().map(|buffer| { let len = buffer.len(); let _ = self.uart.receive_automatic(buffer, len, 250); }); } fn received_word(&self, _word: u32, _rcode: Result<(), ErrorCode>, _err: uart::Error) {} }
use core::cmp; use kernel::common::cells::{OptionalCell, TakeCell}; use kernel::hil; use kernel::hil::uart; use kernel::{ CommandReturn, Driver, ErrorCode, Grant, ProcessId, ReadOnlyProcessBuffer, ReadWriteProcessBuffer, ReadableProcessBuffer, WriteableProcessBuffer, }; use crate::driver; pub const DRIVER_NUM: usize = driver::NUM::Nrf51822Serialization as usize; #[derive(Default)] pub struct App { tx_buffer: ReadOnlyProcessBuffer, rx_buffer: ReadWriteProcessBuffer, } pub static mut WRITE_BUF: [u8; 600] = [0; 600]; pub static mut READ_BUF: [u8; 600] = [0; 600]; pub struct Nrf51822Serialization<'a> { uart: &'a dyn uart::UartAdvanced<'a>, reset_pin: &'a dyn hil::gpio::Pin, apps: Grant<App, 1>, active_app: OptionalCell<ProcessId>, tx_buffer: TakeCell<'static, [u8]>, rx_buffer: TakeCell<'static, [u8]>, } impl<'a> Nrf51822Serialization<'a> { pub fn new( uart: &'a dyn uart::UartAdvanced<'a>, grant: Grant<App, 1>, reset_pin: &'a dyn hil::gpio::Pin, tx_buffer: &'static mut [u8], rx_buffer: &'static mut [u8], ) -> Nrf51822Serialization<'a> { Nrf51822Serialization { uart: uart, reset_pin: reset_pin, apps: grant, active_app: OptionalCell::empty(), tx_buffer: TakeCell::new(tx_buffer), rx_buffer: TakeCell::new(rx_buffer), } } pub fn initialize(&self) { let _ = self.uart.configure(uart::Parameters { baud_rate: 250000, width: uart::Width::Eight, stop_bits: uart::StopBits::One, parity: uart::Parity::Even, hw_flow_control: true, }); } pub fn reset(&self) { self.reset_pin.make_output(); self.reset_pin.clear(); for _ in 0..10 { self.reset_pin.clear(); } self.reset_pin.set(); } } impl Driver for Nrf51822Serialization<'_> { fn allow_readwrite( &self, appid: ProcessId, allow_type: usize, mut slice: ReadWriteProcessBuffer, ) -> Result<ReadWriteProcessBuffer, (ReadWriteProcessBuffer, ErrorCode)> { let res = match allow_type { 0 => { self.active_app.set(appid); self.apps .enter(appid, |app, _| { core::mem::swap(&mut app.rx_buffer, &mut slice); }) .map_err(ErrorCode::from) } _ => Err(ErrorCode::NOSUPPORT), }; if let Err(e) = res { Err((slice, e)) } else { Ok(slice) } } fn allow_readonly( &self, appid: ProcessId, allow_type: usize, mut slice: ReadOnlyProcessBuffer, ) -> Result<ReadOnlyProcessBuffer, (ReadOnlyProcessBuffer, ErrorCode)> { let res = match allow_type { 0 => { self.active_app.set(appid); self.apps .enter(appid, |app, _| { core::mem::swap(&mut app.tx_buffer, &mut slic
fn command( &self, command_type: usize, arg1: usize, _: usize, appid: ProcessId, ) -> CommandReturn { match command_type { 0 /* check if present */ => CommandReturn::success(), 1 => { self.apps.enter(appid, |app, _| { app.tx_buffer.enter(|slice| { let write_len = slice.len(); self.tx_buffer.take().map_or(CommandReturn::failure(ErrorCode::FAIL), |buffer| { for (i, c) in slice.iter().enumerate() { buffer[i] = c.get(); } let _ = self.uart.transmit_buffer(buffer, write_len); CommandReturn::success() }) }).unwrap_or(CommandReturn::failure(ErrorCode::FAIL)) }).unwrap_or(CommandReturn::failure(ErrorCode::FAIL)) } 2 => { self.rx_buffer.take().map_or(CommandReturn::failure(ErrorCode::RESERVE), |buffer| { let len = arg1; if len > buffer.len() { CommandReturn::failure(ErrorCode::SIZE) } else { let _ = self.uart.receive_automatic(buffer, len, 250); CommandReturn::success_u32(len as u32) } }) } 3 => { self.reset(); CommandReturn::success() } _ => CommandReturn::failure(ErrorCode::NOSUPPORT), } } fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::procs::Error> { self.apps.enter(processid, |_, _| {}) } } impl uart::TransmitClient for Nrf51822Serialization<'_> { fn transmitted_buffer( &self, buffer: &'static mut [u8], _tx_len: usize, _rcode: Result<(), ErrorCode>, ) { self.tx_buffer.replace(buffer); self.active_app.map(|appid| { let _ = self.apps.enter(*appid, |_app, upcalls| { upcalls.schedule_upcall(0, 1, 0, 0).ok(); }); }); } fn transmitted_word(&self, _rcode: Result<(), ErrorCode>) {} } impl uart::ReceiveClient for Nrf51822Serialization<'_> { fn received_buffer( &self, buffer: &'static mut [u8], rx_len: usize, _rcode: Result<(), ErrorCode>, _error: uart::Error, ) { self.rx_buffer.replace(buffer); self.active_app.map(|appid| { let _ = self.apps.enter(*appid, |app, upcalls| { let len = app .rx_buffer .mut_enter(|rb| { let max_len = cmp::min(rx_len, rb.len()); self.rx_buffer.map_or(0, |buffer| { for idx in 0..max_len { rb[idx].set(buffer[idx]); } max_len }) }) .unwrap_or(0); upcalls.schedule_upcall(0, 4, rx_len, len).ok(); }); }); self.rx_buffer.take().map(|buffer| { let len = buffer.len(); let _ = self.uart.receive_automatic(buffer, len, 250); }); } fn received_word(&self, _word: u32, _rcode: Result<(), ErrorCode>, _err: uart::Error) {} }
e) }) .map_err(ErrorCode::from) } _ => Err(ErrorCode::NOSUPPORT), }; if let Err(e) = res { Err((slice, e)) } else { Ok(slice) } }
function_block-function_prefixed
[ { "content": "pub fn u16_to_network_slice(short: u16, slice: &mut [u8]) {\n\n slice[0] = (short >> 8) as u8;\n\n slice[1] = (short & 0xff) as u8;\n\n}\n", "file_path": "capsules/src/net/util.rs", "rank": 0, "score": 343884.3090572432 }, { "content": "/// This test should be called with I2C2, specifically\n\npub fn i2c_scan_slaves(i2c_master: &'static mut dyn I2CMaster) {\n\n static mut DATA: [u8; 255] = [0; 255];\n\n\n\n let dev = i2c_master;\n\n\n\n let i2c_client = unsafe { kernel::static_init!(ScanClient, ScanClient::new(dev)) };\n\n dev.set_master_client(i2c_client);\n\n\n\n dev.enable();\n\n\n\n debug!(\"Scanning for I2C devices...\");\n\n dev.write(i2c_client.dev_id.get(), unsafe { &mut DATA }, 2)\n\n .unwrap();\n\n}\n\n\n\n// ===========================================\n\n// Test FXOS8700CQ\n\n// ===========================================\n\n\n", "file_path": "boards/imix/src/test/i2c_dummy.rs", "rank": 1, "score": 302937.86258150055 }, { "content": "pub fn encode_u8(buf: &mut [u8], b: u8) -> SResult {\n\n stream_len_cond!(buf, 1);\n\n buf[0] = b;\n\n stream_done!(1);\n\n}\n\n\n", "file_path": "capsules/src/net/stream.rs", "rank": 2, "score": 291335.71069039294 }, { "content": "/// Convert a `Result<(), ErrorCode>` to a StatusCode (usize) for userspace.\n\n///\n\n/// StatusCode is a useful \"pseudotype\" (there is no actual Rust type called\n\n/// StatusCode in Tock) for three reasons:\n\n///\n\n/// 1. It can be represented in a single `usize`. This allows StatusCode to be\n\n/// easily passed across the syscall interface between the kernel and\n\n/// userspace.\n\n///\n\n/// 2. It extends ErrorCode, but keeps the same error-to-number mappings as\n\n/// ErrorCode. For example, in both StatusCode and ErrorCode, the `SIZE`\n\n/// error is always represented as 7.\n\n///\n\n/// 3. It can encode success values, whereas ErrorCode can only encode errors.\n\n/// Number 0 in ErrorCode is reserved, and is used for `SUCCESS` in\n\n/// StatusCode.\n\n///\n\n/// This helper function converts the Tock and Rust convention for a\n\n/// success/error type to a StatusCode. StatusCode is represented as a usize\n\n/// which is sufficient to send to userspace via an upcall.\n\n///\n\n/// The key to this conversion and portability between the kernel and userspace\n\n/// is that `ErrorCode`, which only expresses errors, is assigned fixed values,\n\n/// but does not use value 0 by convention. This allows us to use 0 as success\n\n/// in ReturnCode.\n\npub fn into_statuscode(r: Result<(), ErrorCode>) -> usize {\n\n match r {\n\n Ok(()) => 0,\n\n Err(e) => e as usize,\n\n }\n\n}\n", "file_path": "kernel/src/errorcode.rs", "rank": 3, "score": 286073.0322022679 }, { "content": "pub fn decode_bytes(buf: &[u8], out: &mut [u8]) -> SResult {\n\n stream_len_cond!(buf, out.len());\n\n let len = out.len();\n\n out.copy_from_slice(&buf[..len]);\n\n stream_done!(out.len());\n\n}\n\n\n", "file_path": "capsules/src/net/stream.rs", "rank": 4, "score": 283084.047729549 }, { "content": "// This function assumes that the host is little-endian\n\npub fn decode_bytes_be(buf: &[u8], out: &mut [u8]) -> SResult {\n\n stream_len_cond!(buf, out.len());\n\n for (i, b) in buf[..out.len()].iter().rev().enumerate() {\n\n out[i] = *b;\n\n }\n\n stream_done!(out.len());\n\n}\n", "file_path": "capsules/src/net/stream.rs", "rank": 5, "score": 283084.047729549 }, { "content": "// This function assumes that the host is little-endian\n\npub fn encode_bytes_be(buf: &mut [u8], bs: &[u8]) -> SResult {\n\n stream_len_cond!(buf, bs.len());\n\n for (i, b) in bs.iter().rev().enumerate() {\n\n buf[i] = *b;\n\n }\n\n stream_done!(bs.len());\n\n}\n\n\n", "file_path": "capsules/src/net/stream.rs", "rank": 6, "score": 278678.0202871602 }, { "content": "pub fn encode_bytes(buf: &mut [u8], bs: &[u8]) -> SResult {\n\n stream_len_cond!(buf, bs.len());\n\n buf[..bs.len()].copy_from_slice(bs);\n\n stream_done!(bs.len());\n\n}\n\n\n", "file_path": "capsules/src/net/stream.rs", "rank": 7, "score": 278678.0202871602 }, { "content": "/// Verifies that the prefixes of the two buffers match, where the length of the\n\n/// prefix is given in bits\n\npub fn matches_prefix(buf1: &[u8], buf2: &[u8], prefix_len: u8) -> bool {\n\n let full_bytes = (prefix_len / 8) as usize;\n\n let remaining_bits = prefix_len % 8;\n\n let bytes = full_bytes + if remaining_bits != 0 { 1 } else { 0 };\n\n\n\n if bytes > buf1.len() || bytes > buf2.len() {\n\n return false;\n\n }\n\n\n\n // Ensure that the prefix bits in the last byte match\n\n if remaining_bits != 0 {\n\n let last_byte_mask = 0xff << (8 - remaining_bits);\n\n if (buf1[full_bytes] ^ buf2[full_bytes]) & last_byte_mask != 0 {\n\n return false;\n\n }\n\n }\n\n\n\n // Ensure that the prefix bytes before that match\n\n buf1[..full_bytes].iter().eq(buf2[..full_bytes].iter())\n\n}\n\n\n", "file_path": "capsules/src/net/util.rs", "rank": 8, "score": 263785.9749544005 }, { "content": "// When reading from a buffer in host order\n\npub fn host_slice_to_u16(buf: &[u8]) -> u16 {\n\n ((buf[1] as u16) << 8) | (buf[0] as u16)\n\n}\n\n\n", "file_path": "capsules/src/net/util.rs", "rank": 9, "score": 259203.5141942898 }, { "content": "// When reading from a buffer in network order\n\npub fn network_slice_to_u16(buf: &[u8]) -> u16 {\n\n ((buf[0] as u16) << 8) | (buf[1] as u16)\n\n}\n\n\n", "file_path": "capsules/src/net/util.rs", "rank": 10, "score": 259203.5141942898 }, { "content": "pub fn encode_u16(buf: &mut [u8], b: u16) -> SResult {\n\n stream_len_cond!(buf, 2);\n\n buf[0] = (b >> 8) as u8;\n\n buf[1] = b as u8;\n\n stream_done!(2);\n\n}\n\n\n", "file_path": "capsules/src/net/stream.rs", "rank": 11, "score": 255942.9628519053 }, { "content": "pub fn encode_u32(buf: &mut [u8], b: u32) -> SResult {\n\n stream_len_cond!(buf, 4);\n\n buf[0] = (b >> 24) as u8;\n\n buf[1] = (b >> 16) as u8;\n\n buf[2] = (b >> 8) as u8;\n\n buf[3] = b as u8;\n\n stream_done!(4);\n\n}\n\n\n", "file_path": "capsules/src/net/stream.rs", "rank": 12, "score": 255942.9628519053 }, { "content": "// NOTE: We currently only support (or intend to support) carrying the UDP\n\n// checksum inline.\n\nfn compress_udp_checksum(udp_header: &UDPHeader, buf: &mut [u8], written: &mut usize) -> u8 {\n\n // get_cksum returns cksum in host byte order\n\n let cksum = udp_header.get_cksum().to_be();\n\n buf[*written] = cksum as u8;\n\n buf[*written + 1] = (cksum >> 8) as u8;\n\n *written += 2;\n\n // Inline checksum corresponds to the 0 flag\n\n 0\n\n}\n\n\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_compression.rs", "rank": 13, "score": 254060.76687467686 }, { "content": "fn compress_udp_ports(udp_header: &UDPHeader, buf: &mut [u8], written: &mut usize) -> u8 {\n\n // Need to deal with fields in network byte order when writing directly to buf\n\n let src_port = udp_header.get_src_port().to_be();\n\n let dst_port = udp_header.get_dst_port().to_be();\n\n\n\n let mut udp_port_nhc = 0;\n\n if (src_port & nhc::UDP_4BIT_PORT_MASK) == nhc::UDP_4BIT_PORT\n\n && (dst_port & nhc::UDP_4BIT_PORT_MASK) == nhc::UDP_4BIT_PORT\n\n {\n\n // Both can be compressed to 4 bits\n\n udp_port_nhc |= nhc::UDP_SRC_PORT_FLAG | nhc::UDP_DST_PORT_FLAG;\n\n // This should compress the ports to a single 8-bit value,\n\n // with the source port before the destination port\n\n buf[*written] = (((src_port & !nhc::UDP_4BIT_PORT_MASK) << 4)\n\n | (dst_port & !nhc::UDP_4BIT_PORT_MASK)) as u8;\n\n *written += 1;\n\n } else if (src_port & nhc::UDP_8BIT_PORT_MASK) == nhc::UDP_8BIT_PORT {\n\n // Source port compressed to 8 bits, destination port uncompressed\n\n udp_port_nhc |= nhc::UDP_SRC_PORT_FLAG;\n\n buf[*written] = (src_port & !nhc::UDP_8BIT_PORT_MASK) as u8;\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_compression.rs", "rank": 14, "score": 254060.76687467686 }, { "content": "/// This test should be called with I2C2, specifically\n\npub fn i2c_li_test(i2c_master: &'static dyn I2CMaster) {\n\n static mut DATA: [u8; 255] = [0; 255];\n\n\n\n let pin = sam4l::gpio::GPIOPin::new(sam4l::gpio::Pin::PA16);\n\n pin.enable_output();\n\n pin.set();\n\n\n\n let dev = i2c_master;\n\n\n\n let i2c_client = unsafe { kernel::static_init!(LiClient, LiClient::new(dev)) };\n\n dev.set_master_client(i2c_client);\n\n dev.enable();\n\n\n\n let buf = unsafe { &mut DATA };\n\n debug!(\"Enabling LI...\");\n\n buf[0] = 0;\n\n buf[1] = 0b10100000;\n\n buf[2] = 0b00000000;\n\n dev.write(0x44, buf, 3).unwrap();\n\n i2c_client.state.set(LiClientState::Enabling);\n\n}\n", "file_path": "boards/imix/src/test/i2c_dummy.rs", "rank": 15, "score": 252516.2505629557 }, { "content": "/// This test should be called with I2C2, specifically\n\npub fn i2c_accel_test(i2c_master: &'static dyn I2CMaster) {\n\n static mut DATA: [u8; 255] = [0; 255];\n\n\n\n let dev = i2c_master;\n\n\n\n let i2c_client = unsafe { kernel::static_init!(AccelClient, AccelClient::new(dev)) };\n\n dev.set_master_client(i2c_client);\n\n dev.enable();\n\n\n\n let buf = unsafe { &mut DATA };\n\n debug!(\"Reading Accel's WHOAMI...\");\n\n buf[0] = 0x0D as u8; // 0x0D == WHOAMI register\n\n dev.write_read(0x1e, buf, 1, 1).unwrap();\n\n i2c_client.state.set(AccelClientState::ReadingWhoami);\n\n}\n\n\n\n// ===========================================\n\n// Test LI\n\n// ===========================================\n\n\n", "file_path": "boards/imix/src/test/i2c_dummy.rs", "rank": 16, "score": 252516.2505629557 }, { "content": "fn decompress_nh(iphc_header: u8, buf: &[u8], consumed: &mut usize) -> (bool, u8) {\n\n let is_nhc = (iphc_header & iphc::NH) != 0;\n\n let mut next_header: u8 = 0;\n\n if !is_nhc {\n\n next_header = buf[*consumed];\n\n *consumed += 1;\n\n }\n\n (is_nhc, next_header)\n\n}\n\n\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_compression.rs", "rank": 17, "score": 249885.02174848178 }, { "content": "/// State that is stored in each process's grant region to support IPC.\n\nstruct IPCData<const NUM_PROCS: usize> {\n\n /// An array of process buffers that this application has shared\n\n /// with other applications.\n\n shared_memory: [ReadWriteProcessBuffer; NUM_PROCS],\n\n search_buf: ReadOnlyProcessBuffer,\n\n}\n\n\n\nimpl<const NUM_PROCS: usize> Default for IPCData<NUM_PROCS> {\n\n fn default() -> IPCData<NUM_PROCS> {\n\n const DEFAULT_RW_PROC_BUF: ReadWriteProcessBuffer = ReadWriteProcessBuffer::const_default();\n\n IPCData {\n\n shared_memory: [DEFAULT_RW_PROC_BUF; NUM_PROCS],\n\n search_buf: ReadOnlyProcessBuffer::default(),\n\n }\n\n }\n\n}\n\n\n\n/// The upcall setup by a service. Each process can only be one service.\n\n/// Subscribe with subscribe_num == 0 is how a process registers\n\n/// itself as an IPC service. Each process can only register as a\n", "file_path": "kernel/src/ipc.rs", "rank": 18, "score": 248867.02711987798 }, { "content": "/// Get closest power of two greater than the given number.\n\npub fn closest_power_of_two(mut num: u32) -> u32 {\n\n num -= 1;\n\n num |= num >> 1;\n\n num |= num >> 2;\n\n num |= num >> 4;\n\n num |= num >> 8;\n\n num |= num >> 16;\n\n num += 1;\n\n num\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, Ord)]\n\npub struct PowerOfTwo(u32);\n\n\n\n/// Represents an integral power-of-two as an exponent\n\nimpl PowerOfTwo {\n\n /// Returns the base-2 exponent as a numeric type\n\n pub fn exp<R>(self) -> R\n\n where\n\n R: From<u32>,\n", "file_path": "kernel/src/common/math.rs", "rank": 19, "score": 247943.45085018384 }, { "content": "fn decompress_tf(ip6_header: &mut IP6Header, iphc_header: u8, buf: &[u8], consumed: &mut usize) {\n\n let fl_compressed = (iphc_header & iphc::TF_FLOW_LABEL) != 0;\n\n let tc_compressed = (iphc_header & iphc::TF_TRAFFIC_CLASS) != 0;\n\n\n\n // Determine ECN and DSCP separately because the order is different\n\n // from the IPv6 traffic class field.\n\n if !fl_compressed || !tc_compressed {\n\n let ecn = buf[*consumed] >> 6;\n\n ip6_header.set_ecn(ecn);\n\n }\n\n if !tc_compressed {\n\n let dscp = buf[*consumed] & 0b111111;\n\n ip6_header.set_dscp(dscp);\n\n *consumed += 1;\n\n }\n\n\n\n // Flow label is always in the same bit position relative to the last\n\n // three bytes in the inline fields\n\n if fl_compressed {\n\n ip6_header.set_flow_label(0);\n\n } else {\n\n let flow = (((buf[*consumed] & 0x0f) as u32) << 16)\n\n | ((buf[*consumed + 1] as u32) << 8)\n\n | (buf[*consumed + 2] as u32);\n\n *consumed += 3;\n\n ip6_header.set_flow_label(flow);\n\n }\n\n}\n\n\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_compression.rs", "rank": 20, "score": 247175.783212438 }, { "content": "#[allow(unused_variables)]\n\npub trait Driver {\n\n /// System call for a process to perform a short synchronous operation\n\n /// or start a long-running split-phase operation (whose completion\n\n /// is signaled with an upcall). Command 0 is a reserved command to\n\n /// detect if a peripheral system call driver is installed and must\n\n /// always return a CommandReturn::Success.\n\n fn command(\n\n &self,\n\n command_num: usize,\n\n r2: usize,\n\n r3: usize,\n\n process_id: ProcessId,\n\n ) -> CommandReturn {\n\n CommandReturn::failure(ErrorCode::NOSUPPORT)\n\n }\n\n\n\n /// System call for a process to pass a buffer (a ReadWriteProcessBuffer) to\n\n /// the kernel that the kernel can either read or write. The kernel calls\n\n /// this method only after it checks that the entire buffer is\n\n /// within memory the process can both read and write.\n", "file_path": "kernel/src/driver.rs", "rank": 21, "score": 246729.55920083274 }, { "content": "pub fn decode_u8(buf: &[u8]) -> SResult<u8> {\n\n stream_len_cond!(buf, 1);\n\n stream_done!(1, buf[0]);\n\n}\n\n\n", "file_path": "capsules/src/net/stream.rs", "rank": 22, "score": 240110.03961221513 }, { "content": "/// Implement this trait and use `set_client()` in order to receive callbacks.\n\n///\n\n/// 'L' is the length of the 'u8' array to store the digest output.\n\npub trait Client<'a, const L: usize> {\n\n /// This callback is called when the data has been added to the digest\n\n /// engine.\n\n /// On error or success `data` will contain a reference to the original\n\n /// data supplied to `add_data()`.\n\n fn add_data_done(&'a self, result: Result<(), ErrorCode>, data: &'static mut [u8]);\n\n\n\n /// This callback is called when a digest is computed.\n\n /// On error or success `digest` will contain a reference to the original\n\n /// data supplied to `run()`.\n\n fn hash_done(&'a self, result: Result<(), ErrorCode>, digest: &'static mut [u8; L]);\n\n}\n\n\n", "file_path": "kernel/src/hil/digest.rs", "rank": 23, "score": 239473.3507664011 }, { "content": "/// Computes a digest (cryptographic hash) over data\n\n///\n\n/// 'L' is the length of the 'u8' array to store the digest output.\n\npub trait Digest<'a, const L: usize> {\n\n /// Set the client instance which will receive `hash_done()` and\n\n /// `add_data_done()` callbacks.\n\n /// This callback is called when the data has been added to the digest\n\n /// engine.\n\n /// The callback should follow the `Client` `add_data_done` callback.\n\n fn set_client(&'a self, client: &'a dyn Client<'a, L>);\n\n\n\n /// Add data to the digest block. This is the data that will be used\n\n /// for the hash function.\n\n /// Returns the number of bytes parsed on success\n\n /// There is no guarantee the data has been written until the `add_data_done()`\n\n /// callback is fired.\n\n /// On error the return value will contain a return code and the original data\n\n fn add_data(\n\n &self,\n\n data: LeasableBuffer<'static, u8>,\n\n ) -> Result<usize, (ErrorCode, &'static mut [u8])>;\n\n\n\n /// Request the hardware block to generate a Digest and stores the returned\n", "file_path": "kernel/src/hil/digest.rs", "rank": 24, "score": 239467.60654427073 }, { "content": "// Table 2.5\n\n// http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0553a/CHDBIBGJ.html\n\npub fn ipsr_isr_number_to_str(isr_number: usize) -> &'static str {\n\n match isr_number {\n\n 0 => \"Thread Mode\",\n\n 1 => \"Reserved\",\n\n 2 => \"NMI\",\n\n 3 => \"HardFault\",\n\n 4 => \"MemManage\",\n\n 5 => \"BusFault\",\n\n 6 => \"UsageFault\",\n\n 7..=10 => \"Reserved\",\n\n 11 => \"SVCall\",\n\n 12 => \"Reserved for Debug\",\n\n 13 => \"Reserved\",\n\n 14 => \"PendSV\",\n\n 15 => \"SysTick\",\n\n 16..=255 => \"IRQn\",\n\n _ => \"(Unknown! Illegal value?)\",\n\n }\n\n}\n\n\n", "file_path": "arch/cortex-m/src/lib.rs", "rank": 25, "score": 239197.52406371065 }, { "content": "fn compress_hl(ip6_header: &IP6Header, buf: &mut [u8], written: &mut usize) {\n\n let hop_limit_flag = match ip6_header.hop_limit {\n\n 1 => iphc::HLIM_1,\n\n 64 => iphc::HLIM_64,\n\n 255 => iphc::HLIM_255,\n\n _ => {\n\n buf[*written] = ip6_header.hop_limit;\n\n *written += 1;\n\n iphc::HLIM_INLINE\n\n }\n\n };\n\n buf[0] |= hop_limit_flag;\n\n}\n\n\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_compression.rs", "rank": 26, "score": 237934.3316737523 }, { "content": "fn compress_tf(ip6_header: &IP6Header, buf: &mut [u8], written: &mut usize) {\n\n let ecn = ip6_header.get_ecn();\n\n let dscp = ip6_header.get_dscp();\n\n let flow = ip6_header.get_flow_label();\n\n\n\n let mut tf_encoding = 0;\n\n let old_offset = *written;\n\n\n\n // If ECN != 0 we are forced to at least have one byte,\n\n // otherwise we can elide dscp\n\n if dscp == 0 && (ecn == 0 || flow != 0) {\n\n tf_encoding |= iphc::TF_TRAFFIC_CLASS;\n\n } else {\n\n buf[*written] = dscp;\n\n *written += 1;\n\n }\n\n\n\n // We can elide flow if it is 0\n\n if flow == 0 {\n\n tf_encoding |= iphc::TF_FLOW_LABEL;\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_compression.rs", "rank": 27, "score": 237934.3316737523 }, { "content": "fn exceeded_check(size: usize, allocated: usize) -> &'static str {\n\n if size > allocated {\n\n \" EXCEEDED!\"\n\n } else {\n\n \" \"\n\n }\n\n}\n\n\n\nimpl<C: 'static + Chip> ProcessStandard<'_, C> {\n\n // Memory offset for upcall ring buffer (10 element length).\n\n const CALLBACK_LEN: usize = 10;\n\n const CALLBACKS_OFFSET: usize = mem::size_of::<Task>() * Self::CALLBACK_LEN;\n\n\n\n // Memory offset to make room for this process's metadata.\n\n const PROCESS_STRUCT_OFFSET: usize = mem::size_of::<ProcessStandard<C>>();\n\n\n\n pub(crate) unsafe fn create<'a>(\n\n kernel: &'static Kernel,\n\n chip: &'static C,\n\n app_flash: &'static [u8],\n", "file_path": "kernel/src/process_standard.rs", "rank": 28, "score": 236191.29134292353 }, { "content": "// Returns the UDP ports in host byte-order\n\nfn decompress_udp_ports(udp_nhc: u8, buf: &[u8], consumed: &mut usize) -> (u16, u16) {\n\n let src_compressed = (udp_nhc & nhc::UDP_SRC_PORT_FLAG) != 0;\n\n let dst_compressed = (udp_nhc & nhc::UDP_DST_PORT_FLAG) != 0;\n\n\n\n let src_port;\n\n let dst_port;\n\n if src_compressed && dst_compressed {\n\n // Both src and dst are compressed to 4 bits\n\n let src_short = ((buf[*consumed] >> 4) & 0xf) as u16;\n\n let dst_short = (buf[*consumed] & 0xf) as u16;\n\n src_port = nhc::UDP_4BIT_PORT | src_short;\n\n dst_port = nhc::UDP_4BIT_PORT | dst_short;\n\n *consumed += 1;\n\n } else if src_compressed {\n\n // Source port is compressed to 8 bits\n\n src_port = nhc::UDP_8BIT_PORT | (buf[*consumed] as u16);\n\n // Destination port is uncompressed\n\n dst_port = u16::from_be(network_slice_to_u16(&buf[*consumed + 1..*consumed + 3]));\n\n *consumed += 3;\n\n } else if dst_compressed {\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_compression.rs", "rank": 29, "score": 230623.0233301064 }, { "content": "/// Encodes a key ID into a buffer in the format expected by the userland driver.\n\nfn encode_key_id(key_id: &KeyId, buf: &mut [u8]) -> SResult {\n\n let off = enc_consume!(buf; encode_u8, KeyIdModeUserland::from(key_id) as u8);\n\n let off = match *key_id {\n\n KeyId::Implicit => 0,\n\n KeyId::Index(index) => enc_consume!(buf, off; encode_u8, index),\n\n KeyId::Source4Index(ref src, index) => {\n\n let off = enc_consume!(buf, off; encode_bytes, src);\n\n enc_consume!(buf, off; encode_u8, index)\n\n }\n\n KeyId::Source8Index(ref src, index) => {\n\n let off = enc_consume!(buf, off; encode_bytes, src);\n\n enc_consume!(buf, off; encode_u8, index)\n\n }\n\n };\n\n stream_done!(off);\n\n}\n\n\n", "file_path": "capsules/src/ieee802154/driver.rs", "rank": 30, "score": 226788.66635499522 }, { "content": "/// Blinks a recognizable pattern forever.\n\n///\n\n/// If a multi-color LED is used for the panic pattern, it is\n\n/// advised to turn off other LEDs before calling this method.\n\n///\n\n/// Generally, boards should blink red during panic if possible,\n\n/// otherwise choose the 'first' or most prominent LED. Some\n\n/// boards may find it appropriate to blink multiple LEDs (e.g.\n\n/// one on the top and one on the bottom), thus this method\n\n/// accepts an array, however most will only need one.\n\npub fn panic_blink_forever<L: hil::led::Led>(leds: &mut [&L]) -> ! {\n\n leds.iter_mut().for_each(|led| led.init());\n\n loop {\n\n for _ in 0..1000000 {\n\n leds.iter_mut().for_each(|led| led.on());\n\n }\n\n for _ in 0..100000 {\n\n leds.iter_mut().for_each(|led| led.off());\n\n }\n\n for _ in 0..1000000 {\n\n leds.iter_mut().for_each(|led| led.on());\n\n }\n\n for _ in 0..500000 {\n\n leds.iter_mut().for_each(|led| led.off());\n\n }\n\n }\n\n}\n\n\n\n// panic! support routines\n\n///////////////////////////////////////////////////////////////////\n", "file_path": "kernel/src/debug.rs", "rank": 31, "score": 225239.89495018445 }, { "content": "pub fn begin_debug_verbose_fmt(args: Arguments, file_line: &(&'static str, u32)) {\n\n let writer = unsafe { get_debug_writer() };\n\n\n\n writer.increment_count();\n\n let count = writer.get_count();\n\n\n\n let (file, line) = *file_line;\n\n let _ = writer.write_fmt(format_args!(\"TOCK_DEBUG({}): {}:{}: \", count, file, line));\n\n let _ = write(writer, args);\n\n let _ = writer.write_str(\"\\r\\n\");\n\n writer.publish_bytes();\n\n}\n\n\n\n/// In-kernel `println()` debugging.\n\n#[macro_export]\n\nmacro_rules! debug {\n\n () => ({\n\n // Allow an empty debug!() to print the location when hit\n\n debug!(\"\")\n\n });\n", "file_path": "kernel/src/debug.rs", "rank": 32, "score": 224962.22318615674 }, { "content": "fn compress_nh(ip6_header: &IP6Header, is_nhc: bool, buf: &mut [u8], written: &mut usize) {\n\n if is_nhc {\n\n buf[0] |= iphc::NH;\n\n } else {\n\n buf[*written] = ip6_header.next_header;\n\n *written += 1;\n\n }\n\n}\n\n\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_compression.rs", "rank": 33, "score": 223931.1425786934 }, { "content": "/// The type of keys, this should define the output size of the digest\n\n/// operations.\n\npub trait KeyType: Eq + Copy + Clone + Sized + AsRef<[u8]> + AsMut<[u8]> {}\n\n\n\nimpl KeyType for [u8; 8] {}\n\n\n", "file_path": "kernel/src/hil/kv_system.rs", "rank": 34, "score": 221485.1477398435 }, { "content": "// Debugging functions.\n\nfn packet_to_hex(packet: &[VolatileCell<u8>], packet_hex: &mut [u8]) {\n\n let hex_char = |x: u8| {\n\n if x < 10 {\n\n b'0' + x\n\n } else {\n\n b'a' + x - 10\n\n }\n\n };\n\n\n\n for (i, x) in packet.iter().enumerate() {\n\n let x = x.get();\n\n packet_hex[2 * i] = hex_char(x >> 4);\n\n packet_hex[2 * i + 1] = hex_char(x & 0x0f);\n\n }\n\n}\n\n\n", "file_path": "chips/nrf52/src/usbd.rs", "rank": 35, "score": 221166.35994421624 }, { "content": "pub fn debug_flush_queue_() {\n\n let writer = unsafe { get_debug_writer() };\n\n\n\n unsafe { DEBUG_QUEUE.as_deref_mut() }.map(|buffer| {\n\n buffer.dw.map(|dw| {\n\n dw.ring_buffer.map(|ring_buffer| {\n\n writer.write_ring_buffer(ring_buffer);\n\n ring_buffer.empty();\n\n });\n\n });\n\n });\n\n}\n\n\n\n/// This macro prints a new line to an internal ring buffer, the contents of\n\n/// which are only flushed with `debug_flush_queue!` and in the panic handler.\n\n#[macro_export]\n\nmacro_rules! debug_enqueue {\n\n () => ({\n\n debug_enqueue!(\"\")\n\n });\n", "file_path": "kernel/src/debug.rs", "rank": 36, "score": 220740.86913585776 }, { "content": "/// Verifies that a prefix given in the form of a byte array slice is valid with\n\n/// respect to its length in bits (prefix_len):\n\n///\n\n/// - The byte array slice must contain enough bytes to cover the prefix length\n\n/// (no implicit zero-padding)\n\n/// - The rest of the prefix array slice is zero-padded\n\npub fn verify_prefix_len(prefix: &[u8], prefix_len: u8) -> bool {\n\n let full_bytes = (prefix_len / 8) as usize;\n\n let remaining_bits = prefix_len % 8;\n\n let bytes = full_bytes + if remaining_bits != 0 { 1 } else { 0 };\n\n\n\n if bytes > prefix.len() {\n\n return false;\n\n }\n\n\n\n // The bits between the prefix's end and the next byte boundary must be 0\n\n if remaining_bits != 0 {\n\n let last_byte_mask = 0xff >> remaining_bits;\n\n if prefix[full_bytes] & last_byte_mask != 0 {\n\n return false;\n\n }\n\n }\n\n\n\n // Ensure that the remaining bytes are also 0\n\n prefix[bytes..].iter().all(|&b| b == 0)\n\n}\n\n\n", "file_path": "capsules/src/net/util.rs", "rank": 37, "score": 219970.5854627157 }, { "content": "pub fn is_lowpan(packet: &[u8]) -> bool {\n\n (packet[0] & iphc::DISPATCH[0]) == iphc::DISPATCH[0]\n\n}\n\n\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_compression.rs", "rank": 38, "score": 214288.36197319458 }, { "content": "/// Are there any pending `DeferredCall`s?\n\npub fn has_tasks() -> bool {\n\n DEFERRED_CALL.load_relaxed() != 0\n\n}\n\n\n\n/// Represents a way to generate an asynchronous call without a hardware\n\n/// interrupt. Supports up to 32 possible deferrable tasks.\n\npub struct DeferredCall<T>(T);\n\n\n\nimpl<T: Into<usize> + TryFrom<usize> + Copy> DeferredCall<T> {\n\n /// Creates a new DeferredCall\n\n ///\n\n /// Only create one per task, preferably in the module that it will be used\n\n /// in.\n\n pub const unsafe fn new(task: T) -> Self {\n\n DeferredCall(task)\n\n }\n\n\n\n /// Set the `DeferredCall` as pending\n\n pub fn set(&self) {\n\n DEFERRED_CALL.fetch_or_relaxed(1 << self.0.into() as usize);\n", "file_path": "kernel/src/common/deferred_call.rs", "rank": 39, "score": 209318.78745720474 }, { "content": "pub fn decode_u32(buf: &[u8]) -> SResult<u32> {\n\n stream_len_cond!(buf, 4);\n\n let b = (buf[0] as u32) << 24 | (buf[1] as u32) << 16 | (buf[2] as u32) << 8 | (buf[3] as u32);\n\n stream_done!(4, b);\n\n}\n\n\n", "file_path": "capsules/src/net/stream.rs", "rank": 40, "score": 204582.71995888415 }, { "content": "pub fn decode_u16(buf: &[u8]) -> SResult<u16> {\n\n stream_len_cond!(buf, 2);\n\n stream_done!(2, (buf[0] as u16) << 8 | (buf[1] as u16));\n\n}\n\n\n", "file_path": "capsules/src/net/stream.rs", "rank": 41, "score": 204582.71995888415 }, { "content": "pub trait Uart<'a>: Configure + Transmit<'a> + Receive<'a> {}\n", "file_path": "kernel/src/hil/uart.rs", "rank": 42, "score": 200596.70302250743 }, { "content": "struct Entropy32ToRandomIter<'a>(&'a mut dyn Iterator<Item = u32>);\n\n\n\nimpl Iterator for Entropy32ToRandomIter<'_> {\n\n type Item = u32;\n\n\n\n fn next(&mut self) -> Option<u32> {\n\n self.0.next()\n\n }\n\n}\n\n\n\npub struct Entropy8To32<'a> {\n\n egen: &'a dyn Entropy8<'a>,\n\n client: OptionalCell<&'a dyn entropy::Client32>,\n\n count: Cell<usize>,\n\n bytes: Cell<u32>,\n\n}\n\n\n\nimpl<'a> Entropy8To32<'a> {\n\n pub fn new(egen: &'a dyn Entropy8<'a>) -> Entropy8To32<'a> {\n\n Entropy8To32 {\n", "file_path": "capsules/src/rng.rs", "rank": 43, "score": 200228.46832762446 }, { "content": "/// Helper function to load processes from flash into an array of active\n\n/// processes. This is the default template for loading processes, but a board\n\n/// is able to create its own `load_processes()` function and use that instead.\n\n///\n\n/// Processes are found in flash starting from the given address and iterating\n\n/// through Tock Binary Format (TBF) headers. Processes are given memory out of\n\n/// the `app_memory` buffer until either the memory is exhausted or the\n\n/// allocated number of processes are created. This buffer is a non-static slice,\n\n/// ensuring that this code cannot hold onto the slice past the end of this function\n\n/// (instead, processes store a pointer and length), which necessary for later\n\n/// creation of `ProcessBuffer`s in this memory region to be sound.\n\n/// A reference to each process is stored in the provided `procs` array.\n\n/// How process faults are handled by the\n\n/// kernel must be provided and is assigned to every created process.\n\n///\n\n/// This function is made `pub` so that board files can use it, but loading\n\n/// processes from slices of flash an memory is fundamentally unsafe. Therefore,\n\n/// we require the `ProcessManagementCapability` to call this function.\n\n///\n\n/// Returns `Ok(())` if process discovery went as expected. Returns a\n\n/// `ProcessLoadError` if something goes wrong during TBF parsing or process\n\n/// creation.\n\npub fn load_processes<C: Chip>(\n\n kernel: &'static Kernel,\n\n chip: &'static C,\n\n app_flash: &'static [u8],\n\n app_memory: &mut [u8], // not static, so that process.rs cannot hold on to slice w/o unsafe\n\n procs: &'static mut [Option<&'static dyn Process>],\n\n fault_policy: &'static dyn ProcessFaultPolicy,\n\n _capability: &dyn ProcessManagementCapability,\n\n) -> Result<(), ProcessLoadError> {\n\n if config::CONFIG.debug_load_processes {\n\n debug!(\n\n \"Loading processes from flash={:#010X}-{:#010X} into sram={:#010X}-{:#010X}\",\n\n app_flash.as_ptr() as usize,\n\n app_flash.as_ptr() as usize + app_flash.len() - 1,\n\n app_memory.as_ptr() as usize,\n\n app_memory.as_ptr() as usize + app_memory.len() - 1\n\n );\n\n }\n\n\n\n let mut remaining_flash = app_flash;\n", "file_path": "kernel/src/process_utilities.rs", "rank": 44, "score": 199383.0898494982 }, { "content": "pub fn debug_enqueue_fmt(args: Arguments) {\n\n unsafe { DEBUG_QUEUE.as_deref_mut() }.map(|buffer| {\n\n let _ = write(buffer, args);\n\n let _ = buffer.write_str(\"\\r\\n\");\n\n });\n\n}\n\n\n", "file_path": "kernel/src/debug.rs", "rank": 45, "score": 199361.58824224598 }, { "content": "pub fn begin_debug_fmt(args: Arguments) {\n\n let writer = unsafe { get_debug_writer() };\n\n\n\n let _ = write(writer, args);\n\n let _ = writer.write_str(\"\\r\\n\");\n\n writer.publish_bytes();\n\n}\n\n\n", "file_path": "kernel/src/debug.rs", "rank": 46, "score": 199361.58824224598 }, { "content": "pub fn abs(n: f32) -> f32 {\n\n f32::from_bits(n.to_bits() & 0x7FFF_FFFF)\n\n}\n\n\n", "file_path": "kernel/src/common/math.rs", "rank": 47, "score": 199177.06800474357 }, { "content": "pub fn log10(x: f32) -> f32 {\n\n //using change of base log10(x) = ln(x)/ln(10)\n\n let ln10_recip = f32::consts::LOG10_E;\n\n let fract_base_ln = ln10_recip;\n\n let value_ln = ln_1to2_series_approximation(x);\n\n value_ln * fract_base_ln\n\n}\n\n\n\n//-----------------------------------------------------------\n", "file_path": "kernel/src/common/math.rs", "rank": 48, "score": 199177.06800474357 }, { "content": "/// Computes the LoWPAN Interface Identifier from either the 16-bit short MAC or\n\n/// the IEEE EUI-64 that is derived from the 48-bit MAC.\n\npub fn compute_iid(mac_addr: &MacAddress) -> [u8; 8] {\n\n match mac_addr {\n\n &MacAddress::Short(short_addr) => {\n\n // IID is 0000:00ff:fe00:XXXX, where XXXX is 16-bit MAC\n\n let mut iid: [u8; 8] = iphc::MAC_BASE;\n\n iid[6] = (short_addr >> 1) as u8;\n\n iid[7] = (short_addr & 0xff) as u8;\n\n iid\n\n }\n\n &MacAddress::Long(long_addr) => {\n\n // IID is IEEE EUI-64 with universal/local bit inverted\n\n let mut iid: [u8; 8] = long_addr;\n\n iid[0] ^= iphc::MAC_UL;\n\n iid\n\n }\n\n }\n\n}\n\n\n\nimpl ContextStore for Context {\n\n fn get_context_from_addr(&self, ip_addr: IPAddr) -> Option<Context> {\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_compression.rs", "rank": 49, "score": 197705.71900613458 }, { "content": "fn exceeded_check(size: usize, allocated: usize) -> &'static str {\n\n if size > allocated {\n\n \" EXCEEDED!\"\n\n } else {\n\n \" \"\n\n }\n\n}\n\n\n\nimpl<'a, C: ProcessManagementCapability> ProcessConsole<'a, C> {\n\n pub fn new(\n\n uart: &'a dyn uart::UartData<'a>,\n\n tx_buffer: &'static mut [u8],\n\n rx_buffer: &'static mut [u8],\n\n queue_buffer: &'static mut [u8],\n\n cmd_buffer: &'static mut [u8],\n\n kernel: &'static Kernel,\n\n kernel_addresses: KernelAddresses,\n\n capability: C,\n\n ) -> ProcessConsole<'a, C> {\n\n ProcessConsole {\n", "file_path": "capsules/src/process_console.rs", "rank": 50, "score": 192941.62377887036 }, { "content": "pub fn compute_sum(buf: &[u8], len: u16) -> u32 {\n\n let mut sum: u32 = 0;\n\n\n\n let mut i: usize = 0;\n\n while i < (len as usize) {\n\n let msb = (buf[i] as u32) << 8;\n\n let lsb = buf[i + 1] as u32;\n\n sum += msb + lsb;\n\n i += 2;\n\n }\n\n\n\n sum\n\n}\n", "file_path": "capsules/src/net/ipv6/ip_utils.rs", "rank": 51, "score": 192564.83345850196 }, { "content": "/// Implement this trait and use `set_client()` in order to receive callbacks.\n\npub trait Client<'a, const T: usize> {\n\n /// This callback is called when the binary data has been loaded\n\n /// On error or success `input` will contain a reference to the original\n\n /// data supplied to `load_binary()`.\n\n fn binary_load_done(&'a self, result: Result<(), ErrorCode>, input: &'static mut [u8]);\n\n\n\n /// This callback is called when a operation is computed.\n\n /// On error or success `output` will contain a reference to the original\n\n /// data supplied to `run()`.\n\n fn op_done(&'a self, result: Result<(), ErrorCode>, output: &'static mut [u8; T]);\n\n}\n\n\n\nregister_structs! {\n\n pub OtbnRegisters {\n\n (0x00 => intr_state: ReadWrite<u32, INTR::Register>),\n\n (0x04 => intr_enable: ReadWrite<u32, INTR::Register>),\n\n (0x08 => intr_test: WriteOnly<u32, INTR::Register>),\n\n (0x0C => alert_test: WriteOnly<u32, ALERT_TEST::Register>),\n\n (0x10 => cmd: ReadWrite<u32, CMD::Register>),\n\n (0x14 => status: ReadOnly<u32, STATUS::Register>),\n", "file_path": "chips/lowrisc/src/otbn.rs", "rank": 52, "score": 192289.37924825013 }, { "content": "/// AtomicUsize with no CAS operations that works on targets that have \"no atomic\n\n/// support\" according to their specification. This makes it work on thumbv6\n\n/// platforms.\n\n///\n\n/// Borrowed from https://github.com/japaric/heapless/blob/master/src/ring_buffer/mod.rs\n\n/// See: https://github.com/japaric/heapless/commit/37c8b5b63780ed8811173dc1ec8859cd99efa9ad\n\nstruct AtomicUsize {\n\n v: UnsafeCell<usize>,\n\n}\n\n\n\nimpl AtomicUsize {\n\n pub(crate) const fn new(v: usize) -> AtomicUsize {\n\n AtomicUsize {\n\n v: UnsafeCell::new(v),\n\n }\n\n }\n\n\n\n pub(crate) fn load_relaxed(&self) -> usize {\n\n unsafe { intrinsics::atomic_load_relaxed(self.v.get()) }\n\n }\n\n\n\n pub(crate) fn store_relaxed(&self, val: usize) {\n\n unsafe { intrinsics::atomic_store_relaxed(self.v.get(), val) }\n\n }\n\n\n\n pub(crate) fn fetch_or_relaxed(&self, val: usize) {\n\n unsafe { intrinsics::atomic_store_relaxed(self.v.get(), self.load_relaxed() | val) }\n\n }\n\n}\n\n\n\nunsafe impl Sync for AtomicUsize {}\n\n\n\nstatic DEFERRED_CALL: AtomicUsize = AtomicUsize::new(0);\n\n\n", "file_path": "kernel/src/common/deferred_call.rs", "rank": 53, "score": 190966.0180987856 }, { "content": "#[repr(C)]\n\nstruct GrantPointerEntry {\n\n /// The syscall driver number associated with the allocated grant.\n\n ///\n\n /// This defaults to 0 if the grant has not been allocated. Note, however,\n\n /// that 0 is a valid driver_num, and therefore cannot be used to check if a\n\n /// grant is allocated or not.\n\n driver_num: usize,\n\n\n\n /// The start of the memory location where the grant has been allocated, or\n\n /// null if the grant has not been allocated.\n\n grant_ptr: *mut u8,\n\n}\n\n\n\n/// A type for userspace processes in Tock.\n\npub struct ProcessStandard<'a, C: 'static + Chip> {\n\n /// Identifier of this process and the index of the process in the process\n\n /// table.\n\n process_id: Cell<ProcessId>,\n\n\n\n /// Pointer to the main Kernel struct.\n", "file_path": "kernel/src/process_standard.rs", "rank": 54, "score": 190938.59303561947 }, { "content": "/// Trait for configuring a UART.\n\npub trait Configure {\n\n /// Returns Ok(()), or\n\n /// - OFF: The underlying hardware is currently not available, perhaps\n\n /// because it has not been initialized or in the case of a shared\n\n /// hardware USART controller because it is set up for SPI.\n\n /// - INVAL: Impossible parameters (e.g. a `baud_rate` of 0)\n\n /// - ENOSUPPORT: The underlying UART cannot satisfy this configuration.\n\n fn configure(&self, params: Parameters) -> Result<(), ErrorCode>;\n\n}\n\n\n", "file_path": "kernel/src/hil/uart.rs", "rank": 55, "score": 190880.79356028308 }, { "content": "/// Implementation required for the flash controller hardware. This\n\n/// should read, write and erase flash from the hardware using the\n\n/// flash controller.\n\n///\n\n/// This is the public trait for the Flash controller implementation.\n\n///\n\n/// The size of the regions (pages) must be the smallest size that can be\n\n/// erased in a single operation. This is specified as the constant `S`\n\n/// when implementing `FlashController` and `TicKV` and it must match\n\n/// the length of the `read_buffer`.\n\n///\n\n/// The start and end address of the FlashController must be aligned\n\n/// to the size of regions.\n\n/// All `region_number`s and `address`es are offset from zero. If you\n\n/// want to use flash that doesn't start at zero, or is a partition\n\n/// offset from the start of flash you will need to add that offset\n\n/// to the values in your implementation.\n\n///\n\n/// The boiler plate for an implementation will look something like this\n\n///\n\n/// ```rust\n\n/// use tickv::error_codes::ErrorCode;\n\n/// use tickv::flash_controller::FlashController;\n\n///\n\n/// #[derive(Default)]\n\n/// struct FlashCtrl {}\n\n///\n\n/// impl FlashCtrl {\n\n/// fn new() -> Self {\n\n/// Self { /* fields */ }\n\n/// }\n\n/// }\n\n///\n\n/// impl FlashController<1024> for FlashCtrl {\n\n/// fn read_region(&self, region_number: usize, offset: usize, buf: &mut [u8; 1024]) -> Result<(), ErrorCode> {\n\n/// unimplemented!()\n\n/// }\n\n///\n\n/// fn write(&self, address: usize, buf: &[u8]) -> Result<(), ErrorCode> {\n\n/// unimplemented!()\n\n/// }\n\n///\n\n/// fn erase_region(&self, region_number: usize) -> Result<(), ErrorCode> {\n\n/// unimplemented!()\n\n/// }\n\n/// }\n\n/// ```\n\npub trait FlashController<const S: usize> {\n\n /// This function must read the data from the flash region specified by\n\n /// `region_number` into `buf`. The length of the data read should be the\n\n /// same length as buf. `offset` indicates an offset into the region that\n\n /// should be read.\n\n ///\n\n /// On success it should return nothing, on failure it\n\n /// should return ErrorCode::ReadFail.\n\n ///\n\n /// If the read operation is to be complete asynchronously then\n\n /// `read_region()` can return `ErrorCode::ReadNotReady(region_number)`.\n\n /// By returning `ErrorCode::ReadNotReady(region_number)`\n\n /// `read_region()` can indicate that the operation should be retried in\n\n /// the future.\n\n /// After running the `continue_()` functions after a async\n\n /// `read_region()` has returned `ErrorCode::ReadNotReady(region_number)`\n\n /// the `read_region()` function will be called again and this time should\n\n /// return the data.\n\n fn read_region(\n\n &self,\n", "file_path": "libraries/tickv/src/flash_controller.rs", "rank": 56, "score": 188181.836094531 }, { "content": "pub trait Transmit<'a> {\n\n /// Set the transmit client, which will be called when transmissions\n\n /// complete.\n\n fn set_transmit_client(&self, client: &'a dyn TransmitClient);\n\n\n\n /// Transmit a buffer of data. On completion, `transmitted_buffer`\n\n /// in the `TransmitClient` will be called. If the `Result<(), ErrorCode>`\n\n /// returned by `transmit` is an `Ok(())`, the struct will issue a `transmitted_buffer`\n\n /// callback in the future. If the value of the `Result<(), ErrorCode>` is\n\n /// `Err(), then the `tx_buffer` argument is returned in the\n\n /// `Err()`, along with the `ErrorCode`.\n\n /// Valid `ErrorCode` values are:\n\n /// - OFF: The underlying hardware is not available, perhaps because\n\n /// it has not been initialized or in the case of a shared\n\n /// hardware USART controller because it is set up for SPI.\n\n /// - BUSY: the UART is already transmitting and has not made a\n\n /// transmission callback yet.\n\n /// - SIZE : `tx_len` is larger than the passed slice.\n\n /// - FAIL: some other error.\n\n ///\n", "file_path": "kernel/src/hil/uart.rs", "rank": 57, "score": 187547.20760683867 }, { "content": "pub trait Receive<'a> {\n\n /// Set the receive client, which will he called when reads complete.\n\n fn set_receive_client(&self, client: &'a dyn ReceiveClient);\n\n\n\n /// Receive `rx_len` bytes into `rx_buffer`, making a callback to\n\n /// the `ReceiveClient` when complete. If the `Result<(), ErrorCode>` of\n\n /// `receive_buffer`'s return is `Ok(())`, the struct will issue a `received_buffer`\n\n /// callback in the future. If the value of the `Result<(), ErrorCode>` is\n\n /// `Err()`, then the `rx_buffer` argument is returned in the\n\n /// `Err()`. Valid `ErrorCode` values are:\n\n /// - OFF: The underlying hardware is not available, perhaps because\n\n /// it has not been initialized or in the case of a shared\n\n /// hardware USART controller because it is set up for SPI.\n\n /// - BUSY: the UART is already receiving and has not made a\n\n /// reception `complete` callback yet.\n\n /// - SIZE : `rx_len` is larger than the passed slice.\n\n /// Each byte in `rx_buffer` is a UART transfer word of 8 or fewer\n\n /// bits. The width is determined by the UART\n\n /// configuration. Clients that need to transfer 9-bit words\n\n /// should use `receive_word`. Calling `receive_buffer` while\n", "file_path": "kernel/src/hil/uart.rs", "rank": 58, "score": 187547.20760683867 }, { "content": "/// Get log base 2 of a number.\n\n/// Note: this is the floor of the result. Also, an input of 0 results in an\n\n/// output of 0\n\npub fn log_base_two(num: u32) -> u32 {\n\n if num == 0 {\n\n 0\n\n } else {\n\n 31 - num.leading_zeros()\n\n }\n\n}\n\n\n", "file_path": "kernel/src/common/math.rs", "rank": 59, "score": 186617.57458092974 }, { "content": "fn crc8(data: &[u8]) -> u8 {\n\n let polynomial = 0x31;\n\n let mut crc = 0xff;\n\n\n\n for x in 0..data.len() {\n\n crc ^= data[x as usize] as u8;\n\n for _i in 0..8 {\n\n if (crc & 0x80) != 0 {\n\n crc = crc << 1 ^ polynomial;\n\n } else {\n\n crc = crc << 1;\n\n }\n\n }\n\n }\n\n crc\n\n}\n\n\n\npub struct SHT3x<'a, A: Alarm<'a>> {\n\n i2c: &'a dyn i2c::I2CDevice,\n\n humidity_client: OptionalCell<&'a dyn kernel::hil::sensors::HumidityClient>,\n", "file_path": "capsules/src/sht3x.rs", "rank": 60, "score": 186375.81965987908 }, { "content": "/// Trait implemented by a UART transmitter to receive callbacks when\n\n/// operations complete.\n\npub trait TransmitClient {\n\n /// A call to `Transmit::transmit_word` completed. The `Result<(), ErrorCode>`\n\n /// indicates whether the word was successfully transmitted. A call\n\n /// to `transmit_word` or `transmit_buffer` made within this callback\n\n /// SHOULD NOT return BUSY: when this callback is made the UART should\n\n /// be ready to receive another call.\n\n ///\n\n /// `rval` is Ok(()) if the word was successfully transmitted, or\n\n /// - CANCEL if the call to `transmit_word` was cancelled and\n\n /// the word was not transmitted.\n\n /// - FAIL if the transmission failed in some way.\n\n fn transmitted_word(&self, _rval: Result<(), ErrorCode>) {}\n\n\n\n /// A call to `Transmit::transmit_buffer` completed. The `Result<(), ErrorCode>`\n\n /// indicates whether the buffer was successfully transmitted. A call\n\n /// to `transmit_word` or `transmit_buffer` made within this callback\n\n /// SHOULD NOT return BUSY: when this callback is made the UART should\n\n /// be ready to receive another call.\n\n ///\n\n /// The `tx_len` argument specifies how many words were transmitted.\n", "file_path": "kernel/src/hil/uart.rs", "rank": 61, "score": 185839.33054575475 }, { "content": "pub trait ReceiveClient {\n\n /// A call to `Receive::receive_word` completed. The `Result<(), ErrorCode>`\n\n /// indicates whether the word was successfully received. A call\n\n /// to `receive_word` or `receive_buffer` made within this callback\n\n /// SHOULD NOT return BUSY: when this callback is made the UART should\n\n /// be ready to receive another call.\n\n ///\n\n /// `rval` Ok(()) if the word was successfully received, or\n\n /// - CANCEL if the call to `receive_word` was cancelled and\n\n /// the word was not received: `word` should be ignored.\n\n /// - FAIL if the reception failed in some way and `word`\n\n /// should be ignored. `error` may contain further information\n\n /// on the sort of error.\n\n fn received_word(&self, _word: u32, _rval: Result<(), ErrorCode>, _error: Error) {}\n\n\n\n /// A call to `Receive::receive_buffer` completed. The `Result<(), ErrorCode>`\n\n /// indicates whether the buffer was successfully received. A call\n\n /// to `receive_word` or `receive_buffer` made within this callback\n\n /// SHOULD NOT return BUSY: when this callback is made the UART should\n\n /// be ready to receive another call.\n", "file_path": "kernel/src/hil/uart.rs", "rank": 62, "score": 185832.84029905376 }, { "content": "/// Log base 2 of 64 bit unsigned integers.\n\npub fn log_base_two_u64(num: u64) -> u32 {\n\n if num == 0 {\n\n 0\n\n } else {\n\n 63 - num.leading_zeros()\n\n }\n\n}\n\n\n\n// f32 log10 function adapted from [micromath](https://github.com/NeoBirth/micromath)\n\nconst EXPONENT_MASK: u32 = 0b01111111_10000000_00000000_00000000;\n\nconst EXPONENT_BIAS: u32 = 127;\n\n\n", "file_path": "kernel/src/common/math.rs", "rank": 63, "score": 182895.91393776855 }, { "content": "/// A basic interface for a temperature sensor\n\npub trait TemperatureDriver<'a> {\n\n fn set_client(&self, client: &'a dyn TemperatureClient);\n\n fn read_temperature(&self) -> Result<(), ErrorCode>;\n\n}\n\n\n", "file_path": "kernel/src/hil/sensors.rs", "rank": 64, "score": 182501.4321889193 }, { "content": "/// A basic interface for a humidity sensor\n\npub trait HumidityDriver<'a> {\n\n fn set_client(&self, client: &'a dyn HumidityClient);\n\n fn read_humidity(&self) -> Result<(), ErrorCode>;\n\n}\n\n\n", "file_path": "kernel/src/hil/sensors.rs", "rank": 65, "score": 182501.4321889193 }, { "content": "/// A basic interface for a proximity sensor\n\npub trait ProximityDriver<'a> {\n\n fn set_client(&self, client: &'a dyn ProximityClient);\n\n /// Callback issued after sensor reads proximity value\n\n fn read_proximity(&self) -> Result<(), ErrorCode>;\n\n /// Callback issued after sensor reads proximity value greater than 'high_threshold' or less than 'low_threshold'\n\n ///\n\n /// To elaborate, the callback is not issued by the driver until (prox_reading >= high_threshold || prox_reading <= low_threshold).\n\n /// When (prox_reading >= high_threshold || prox_reading <= low_threshold) is read by the sensor, an I2C interrupt is generated and sent to the kernel\n\n /// which prompts the driver to collect the proximity reading from the sensor and perform the callback.\n\n /// Any apps issuing this command will have to wait for the proximity reading to fall within the aforementioned ranges in order to received a callback.\n\n /// Threshold: A value of range [0 , 255] which represents at what proximity reading ranges an interrupt will occur.\n\n fn read_proximity_on_interrupt(\n\n &self,\n\n low_threshold: u8,\n\n high_threshold: u8,\n\n ) -> Result<(), ErrorCode>;\n\n}\n\n\n", "file_path": "kernel/src/hil/sensors.rs", "rank": 66, "score": 182501.4321889193 }, { "content": "/// Decodes a key ID that is in the format produced by the userland driver.\n\nfn decode_key_id(buf: &[u8]) -> SResult<KeyId> {\n\n stream_len_cond!(buf, 1);\n\n let mode = stream_from_option!(KeyIdModeUserland::from_u8(buf[0]));\n\n match mode {\n\n KeyIdModeUserland::Implicit => stream_done!(0, KeyId::Implicit),\n\n KeyIdModeUserland::Index => {\n\n let (off, index) = dec_try!(buf; decode_u8);\n\n stream_done!(off, KeyId::Index(index));\n\n }\n\n KeyIdModeUserland::Source4Index => {\n\n let mut src = [0u8; 4];\n\n let off = dec_consume!(buf; decode_bytes, &mut src);\n\n let (off, index) = dec_try!(buf, off; decode_u8);\n\n stream_done!(off, KeyId::Source4Index(src, index));\n\n }\n\n KeyIdModeUserland::Source8Index => {\n\n let mut src = [0u8; 8];\n\n let off = dec_consume!(buf; decode_bytes, &mut src);\n\n let (off, index) = dec_try!(buf, off; decode_u8);\n\n stream_done!(off, KeyId::Source8Index(src, index));\n", "file_path": "capsules/src/ieee802154/driver.rs", "rank": 67, "score": 180950.42134634356 }, { "content": "pub trait UartData<'a>: Transmit<'a> + Receive<'a> {}\n", "file_path": "kernel/src/hil/uart.rs", "rank": 68, "score": 179961.9482626796 }, { "content": "#[cfg(test)]\n\nfn test_runner(tests: &[&dyn Fn()]) {\n\n unsafe {\n\n let (board_kernel, earlgrey_nexysvideo, chip, peripherals) = setup();\n\n\n\n BOARD = Some(board_kernel);\n\n PLATFORM = Some(&earlgrey_nexysvideo);\n\n PERIPHERALS = Some(peripherals);\n\n SCHEDULER =\n\n Some(components::sched::priority::PriorityComponent::new(board_kernel).finalize(()));\n\n MAIN_CAP = Some(&create_capability!(capabilities::MainLoopCapability));\n\n\n\n chip.watchdog().setup();\n\n\n\n for test in tests {\n\n test();\n\n }\n\n }\n\n\n\n // Exit QEMU with a return code of 0\n\n crate::tests::semihost_command_exit_success()\n\n}\n", "file_path": "boards/earlgrey-nexysvideo/src/main.rs", "rank": 69, "score": 177890.44404155086 }, { "content": "pub fn new_dma1_stream<'a>(dma: &'a Dma1) -> [Stream<'a>; 8] {\n\n [\n\n Stream::new(StreamId::Stream0, dma),\n\n Stream::new(StreamId::Stream1, dma),\n\n Stream::new(StreamId::Stream2, dma),\n\n Stream::new(StreamId::Stream3, dma),\n\n Stream::new(StreamId::Stream4, dma),\n\n Stream::new(StreamId::Stream5, dma),\n\n Stream::new(StreamId::Stream6, dma),\n\n Stream::new(StreamId::Stream7, dma),\n\n ]\n\n}\n\n\n", "file_path": "chips/stm32f4xx/src/dma1.rs", "rank": 70, "score": 174203.41617648056 }, { "content": "/// NOP instruction (mock)\n\npub fn nop() {\n\n unimplemented!()\n\n}\n\n\n\n#[cfg(not(any(target_arch = \"riscv32\", target_os = \"none\")))]\n\n/// WFI instruction (mock)\n\npub unsafe fn wfi() {\n\n unimplemented!()\n\n}\n", "file_path": "arch/rv32i/src/support.rs", "rank": 71, "score": 173889.6768635683 }, { "content": "/// NOP instruction (mock)\n\npub fn nop() {\n\n unimplemented!()\n\n}\n\n\n\n#[cfg(not(any(target_arch = \"arm\", target_os = \"none\")))]\n\n/// WFI instruction (mock)\n\npub unsafe fn wfi() {\n\n unimplemented!()\n\n}\n\n\n\n#[cfg(not(any(target_arch = \"arm\", target_os = \"none\")))]\n\npub unsafe fn atomic<F, R>(_f: F) -> R\n\nwhere\n\n F: FnOnce() -> R,\n\n{\n\n unimplemented!()\n\n}\n", "file_path": "arch/cortex-m/src/support.rs", "rank": 72, "score": 173889.6768635683 }, { "content": "pub trait BleAdvertisementDriver<'a> {\n\n fn transmit_advertisement(&self, buf: &'static mut [u8], len: usize, channel: RadioChannel);\n\n fn receive_advertisement(&self, channel: RadioChannel);\n\n fn set_receive_client(&self, client: &'a dyn RxClient);\n\n fn set_transmit_client(&self, client: &'a dyn TxClient);\n\n}\n\n\n", "file_path": "kernel/src/hil/ble_advertising.rs", "rank": 73, "score": 173335.34426952127 }, { "content": "/// Trait that isn't required for basic UART operation, but provides useful\n\n/// abstractions that capsules may want to be able to leverage.\n\n///\n\n/// The interfaces are included here because some hardware platforms may be able\n\n/// to directly implement them, while others platforms may need to emulate them\n\n/// in software. The ones that can implement them in hardware should be able to\n\n/// leverage that efficiency, and by placing the interfaces here in the HIL they\n\n/// can do that.\n\n///\n\n/// Other interface ideas that have been discussed, but are not included due to\n\n/// the lack of a clear use case, but are noted here in case they might help\n\n/// someone in the future:\n\n/// - `receive_until_terminator`: This would read in bytes until a specified\n\n/// byte is received (or the buffer is full) and then return to the client.\n\n/// - `receive_len_then_message`: This would do a one byte read to get a length\n\n/// byte and then read that many more bytes from UART before returning to the\n\n/// client.\n\npub trait ReceiveAdvanced<'a>: Receive<'a> {\n\n /// Receive data until `interbyte_timeout` bit periods have passed since the\n\n /// last byte or buffer is full. Does not timeout until at least one byte\n\n /// has been received.\n\n ///\n\n /// * `interbyte_timeout`: number of bit periods since last data received.\n\n fn receive_automatic(\n\n &self,\n\n rx_buffer: &'static mut [u8],\n\n rx_len: usize,\n\n interbyte_timeout: u8,\n\n ) -> Result<(), (ErrorCode, &'static mut [u8])>;\n\n}\n", "file_path": "kernel/src/hil/uart.rs", "rank": 74, "score": 172751.5189277599 }, { "content": "/// Parse a `u32` from four bytes as received on the bus\n\nfn get_u32(b0: u8, b1: u8, b2: u8, b3: u8) -> u32 {\n\n (b0 as u32) | ((b1 as u32) << 8) | ((b2 as u32) << 16) | ((b3 as u32) << 24)\n\n}\n\n\n", "file_path": "capsules/src/usb/descriptors.rs", "rank": 75, "score": 171109.11822593713 }, { "content": "pub trait UartAdvanced<'a>: Configure + Transmit<'a> + ReceiveAdvanced<'a> {}\n", "file_path": "kernel/src/hil/uart.rs", "rank": 76, "score": 170675.72875367483 }, { "content": "pub fn oscillator_disable() {\n\n unlock(Register::OSCCTRL0);\n\n SCIF.oscctrl0.write(Oscillator::OSCEN::CLEAR);\n\n}\n\n\n", "file_path": "chips/sam4l/src/scif.rs", "rank": 77, "score": 170521.1821188167 }, { "content": "/// Setup the internal 32kHz RC oscillator.\n\npub fn enable_rc32k() {\n\n let rc32kcr = BSCIF.rc32kcr.extract();\n\n // Unlock the BSCIF::RC32KCR register\n\n BSCIF\n\n .unlock\n\n .write(Unlock::KEY.val(0xAA) + Unlock::ADDR.val(0x24));\n\n // Write the BSCIF::RC32KCR register.\n\n // Enable the generic clock source, the temperature compensation, and the\n\n // 32k output.\n\n BSCIF.rc32kcr.modify_no_read(\n\n rc32kcr,\n\n RC32Control::EN32K::OutputEnable\n\n + RC32Control::TCEN::TempCompensated\n\n + RC32Control::EN::GclkSourceEnable,\n\n );\n\n // Wait for it to be ready, although it feels like this won't do anything\n\n while !BSCIF.rc32kcr.is_set(RC32Control::EN) {}\n\n\n\n // Load magic calibration value for the 32KHz RC oscillator\n\n //\n\n // Unlock the BSCIF::RC32KTUNE register\n\n BSCIF\n\n .unlock\n\n .write(Unlock::KEY.val(0xAA) + Unlock::ADDR.val(0x28));\n\n // Write the BSCIF::RC32KTUNE register\n\n BSCIF\n\n .rc32ktune\n\n .write(RC32kTuning::COARSE.val(0x1d) + RC32kTuning::FINE.val(0x15));\n\n}\n\n\n", "file_path": "chips/sam4l/src/bscif.rs", "rank": 78, "score": 170521.1821188167 }, { "content": "/// Transform descriptor structs into descriptor buffers that can be\n\n/// passed into the control endpoint handler. Each endpoint descriptor list\n\n/// corresponds to the matching index in the interface descriptor list. For\n\n/// example, if the interface descriptor list contains `[ID1, ID2, ID3]`,\n\n/// and the endpoint descriptors list is `[[ED1, ED2], [ED3, ED4, ED5],\n\n/// [ED6]]`, then the third interface descriptor (`ID3`) has one\n\n/// corresponding endpoint descriptor (`ED6`).\n\npub fn create_descriptor_buffers(\n\n device_descriptor: DeviceDescriptor,\n\n mut configuration_descriptor: ConfigurationDescriptor,\n\n interface_descriptor: &mut [InterfaceDescriptor],\n\n endpoint_descriptors: &[&[EndpointDescriptor]],\n\n hid_descriptor: Option<&HIDDescriptor>,\n\n cdc_descriptor: Option<&[CdcInterfaceDescriptor]>,\n\n) -> (DeviceBuffer, DescriptorBuffer) {\n\n // Create device descriptor buffer and fill.\n\n // Cell doesn't implement Copy, so here we are.\n\n let mut dev_buf = DeviceBuffer {\n\n buf: [\n\n Cell::default(),\n\n Cell::default(),\n\n Cell::default(),\n\n Cell::default(),\n\n Cell::default(),\n\n Cell::default(),\n\n Cell::default(),\n\n Cell::default(),\n", "file_path": "capsules/src/usb/descriptors.rs", "rank": 79, "score": 167372.44978585196 }, { "content": "/// Decompresses a 6loWPAN header into a full IPv6 header\n\n///\n\n/// This function decompresses the header found in `buf` and writes it\n\n/// `out_buf`. It does not, though, copy payload bytes or a non-compressed next\n\n/// header. As a result, the caller should copy the `buf.len - consumed`\n\n/// remaining bytes from `buf` to `out_buf`.\n\n///\n\n///\n\n/// Note that in the case of fragmentation, the total length of the IPv6\n\n/// packet cannot be inferred from a single frame, and is instead provided\n\n/// by the dgram_size field in the fragmentation header. Thus, if we are\n\n/// decompressing a fragment, we rely on the dgram_size field; otherwise,\n\n/// we infer the length from the size of buf.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `ctx_store` - ???\n\n///\n\n/// * `buf` - A slice containing the 6LowPAN packet along with its payload.\n\n///\n\n/// * `src_mac_addr` - the 16-bit MAC address of the frame sender.\n\n///\n\n/// * `dst_mac_addr` - the 16-bit MAC address of the frame receiver.\n\n///\n\n/// * `out_buf` - A buffer to write the output to. Must be at least large enough\n\n/// to store an IPv6 header (XX bytes).\n\n///\n\n/// * `dgram_size` - If `is_fragment` is `true`, this is used as the IPv6\n\n/// packets total payload size. Otherwise, this is ignored.\n\n///\n\n/// * `is_fragment` - ???\n\n///\n\n/// # Returns\n\n///\n\n/// `Ok((consumed, written))` if decompression is successful.\n\n///\n\n/// * `consumed` is the number of header bytes consumed from the 6LoWPAN header\n\n///\n\n/// * `written` is the number of uncompressed header bytes written into\n\n/// `out_buf`.\n\npub fn decompress(\n\n ctx_store: &dyn ContextStore,\n\n buf: &[u8],\n\n src_mac_addr: MacAddress,\n\n dst_mac_addr: MacAddress,\n\n out_buf: &mut [u8],\n\n dgram_size: u16,\n\n is_fragment: bool,\n\n) -> Result<(usize, usize), ()> {\n\n // Get the LOWPAN_IPHC header (the first two bytes are the header)\n\n let iphc_header_1: u8 = buf[0];\n\n let iphc_header_2: u8 = buf[1];\n\n let mut consumed: usize = 2;\n\n\n\n let mut ip6_header = IP6Header::new();\n\n let mut written: usize = mem::size_of::<IP6Header>();\n\n\n\n // Decompress CID and CIE fields if they exist\n\n let (src_ctx, dst_ctx) = decompress_cie(ctx_store, iphc_header_1, &buf, &mut consumed)?;\n\n\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_compression.rs", "rank": 80, "score": 167371.4742791725 }, { "content": "pub fn setup_rc_1mhz() {\n\n let rc1mcr = BSCIF.rc1mcr.extract();\n\n // Unlock the BSCIF::RC32KCR register\n\n BSCIF\n\n .unlock\n\n .write(Unlock::KEY.val(0xAA) + Unlock::ADDR.val(0x58));\n\n // Enable the RC1M\n\n BSCIF\n\n .rc1mcr\n\n .modify_no_read(rc1mcr, RC1MClockConfig::CLKOEN::Output);\n\n\n\n // Wait for the RC1M to be enabled\n\n while !BSCIF.rc1mcr.is_set(RC1MClockConfig::CLKOEN) {}\n\n}\n\n\n\npub unsafe fn disable_rc_1mhz() {\n\n let rc1mcr = BSCIF.rc1mcr.extract();\n\n // Unlock the BSCIF::RC32KCR register\n\n BSCIF\n\n .unlock\n\n .write(Unlock::KEY.val(0xAA) + Unlock::ADDR.val(0x58));\n\n // Disable the RC1M\n\n BSCIF\n\n .rc1mcr\n\n .modify_no_read(rc1mcr, RC1MClockConfig::CLKOEN::NotOutput);\n\n\n\n // Wait for the RC1M to be disabled\n\n while BSCIF.rc1mcr.is_set(RC1MClockConfig::CLKOEN) {}\n\n}\n", "file_path": "chips/sam4l/src/bscif.rs", "rank": 81, "score": 167363.0506630438 }, { "content": "pub fn debug_regs() {\n\n debug!(\n\n \" registers:\\\n\n \\n USBFSM={:08x}\\\n\n \\n USBCON={:08x}\\\n\n \\n USBSTA={:08x}\\\n\n \\n UDESC={:08x}\\\n\n \\n UDCON={:08x}\\\n\n \\n UDINTE={:08x}\\\n\n \\n UDINT={:08x}\\\n\n \\n UERST={:08x}\\\n\n \\n UECFG0={:08x}\\\n\n \\n UECON0={:08x}\",\n\n USBFSM.read(),\n\n USBCON.read(),\n\n USBSTA.read(),\n\n UDESC.read(),\n\n UDCON.read(),\n\n UDINTE.read(),\n\n UDINT.read(),\n\n UERST.read(),\n\n UECFG0.read(),\n\n UECON0.read()\n\n );\n\n}\n\n*/\n", "file_path": "chips/sam4l/src/usbc/debug.rs", "rank": 82, "score": 167363.0506630438 }, { "content": "fn get_frag_hdr(hdr: &[u8]) -> (bool, u16, u16, usize) {\n\n let is_frag1 = match hdr[0] & lowpan_frag::FRAGN_HDR {\n\n lowpan_frag::FRAG1_HDR => true,\n\n _ => false,\n\n };\n\n // Zero out upper bits\n\n let dgram_size = network_slice_to_u16(&hdr[0..2]) & !(0xf << 12);\n\n let dgram_tag = network_slice_to_u16(&hdr[2..4]);\n\n let dgram_offset = if is_frag1 { 0 } else { hdr[4] };\n\n (is_frag1, dgram_size, dgram_tag, (dgram_offset as usize) * 8)\n\n}\n\n\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_state.rs", "rank": 83, "score": 167027.92639967223 }, { "content": "/// Parse a `u16` from two bytes as received on the bus\n\nfn get_u16(b0: u8, b1: u8) -> u16 {\n\n (b0 as u16) | ((b1 as u16) << 8)\n\n}\n\n\n", "file_path": "capsules/src/usb/descriptors.rs", "rank": 84, "score": 166704.31969921343 }, { "content": "pub trait Client: ReceiveClient + TransmitClient {}\n\n\n\n// Provide blanket implementations for all trait groups\n\nimpl<'a, T: Configure + Transmit<'a> + Receive<'a>> Uart<'a> for T {}\n\nimpl<'a, T: Transmit<'a> + Receive<'a>> UartData<'a> for T {}\n\nimpl<'a, T: Configure + Transmit<'a> + ReceiveAdvanced<'a>> UartAdvanced<'a> for T {}\n\nimpl<T: ReceiveClient + TransmitClient> Client for T {}\n\n\n", "file_path": "kernel/src/hil/uart.rs", "rank": 85, "score": 166419.49213405635 }, { "content": "/// Maps a LoWPAN_NHC header the corresponding IPv6 next header type,\n\n/// or an error if the NHC header is invalid\n\nfn nhc_to_ip6_nh(nhc: u8) -> Result<u8, ()> {\n\n match nhc & nhc::DISPATCH_MASK {\n\n nhc::DISPATCH_NHC => match nhc & nhc::EID_MASK {\n\n nhc::HOP_OPTS => Ok(ip6_nh::HOP_OPTS),\n\n nhc::ROUTING => Ok(ip6_nh::ROUTING),\n\n nhc::FRAGMENT => Ok(ip6_nh::FRAGMENT),\n\n nhc::DST_OPTS => Ok(ip6_nh::DST_OPTS),\n\n nhc::MOBILITY => Ok(ip6_nh::MOBILITY),\n\n nhc::IP6 => Ok(ip6_nh::IP6),\n\n _ => Err(()),\n\n },\n\n nhc::DISPATCH_UDP => Ok(ip6_nh::UDP),\n\n _ => Err(()),\n\n }\n\n}\n\n\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_compression.rs", "rank": 86, "score": 166159.5125553159 }, { "content": "fn run_kernel_op(loops: usize) {\n\n unsafe {\n\n for _i in 0..loops {\n\n BOARD.unwrap().kernel_loop_operation(\n\n PLATFORM.unwrap(),\n\n CHIP.unwrap(),\n\n None::<&kernel::ipc::IPC<NUM_PROCS>>,\n\n SCHEDULER.unwrap(),\n\n true,\n\n MAIN_CAP.unwrap(),\n\n );\n\n }\n\n }\n\n}\n\n\n", "file_path": "boards/earlgrey-nexysvideo/src/tests/mod.rs", "rank": 87, "score": 165734.6065998207 }, { "content": "/// Parse a TBF header stored in flash.\n\n///\n\n/// The `header` must be a slice that only contains the TBF header. The caller\n\n/// should use the `parse_tbf_header_lengths()` function to determine this\n\n/// length to create the correct sized slice.\n\npub fn parse_tbf_header(\n\n header: &'static [u8],\n\n version: u16,\n\n) -> Result<types::TbfHeader, types::TbfParseError> {\n\n match version {\n\n 2 => {\n\n // Get the required base. This will succeed because we parsed the\n\n // first bit of the header already in `parse_tbf_header_lengths()`.\n\n let tbf_header_base: types::TbfHeaderV2Base = header.try_into()?;\n\n\n\n // Calculate checksum. The checksum is the XOR of each 4 byte word\n\n // in the header.\n\n let mut checksum: u32 = 0;\n\n\n\n // Get an iterator across 4 byte fields in the header.\n\n let header_iter = header.chunks_exact(4);\n\n\n\n // Iterate all chunks and XOR the chunks to compute the checksum.\n\n for (i, chunk) in header_iter.enumerate() {\n\n let word = u32::from_le_bytes(chunk.try_into()?);\n", "file_path": "libraries/tock-tbf/src/parse.rs", "rank": 88, "score": 164408.57954117813 }, { "content": "pub fn setup_dfll_rc32k_48mhz() {\n\n fn wait_dfll0_ready() {\n\n while !SCIF.pclksr.is_set(Interrupt::DFLL0RDY) {}\n\n }\n\n\n\n // Check to see if the DFLL is already setup or is not locked\n\n if !SCIF.dfll0conf.is_set(Dfll::EN) || !SCIF.pclksr.is_set(Interrupt::DFLL0LOCKF) {\n\n // Enable the GENCLK_SRC_RC32K\n\n if !bscif::rc32k_enabled() {\n\n bscif::enable_rc32k();\n\n }\n\n\n\n // Next, initialize closed-loop mode ...\n\n\n\n // Must do a SCIF sync before reading the SCIF registers?\n\n // 13.7.16: \"To be able to read the current value of DFLLxVAL or DFLLxRATIO, this bit must\n\n // be written to one. The updated value are available in DFLLxVAL or DFLLxRATIO when\n\n // PCLKSR.DFLL0RDY is set.\"\n\n SCIF.dfll0sync.set(0x01);\n\n wait_dfll0_ready();\n", "file_path": "chips/sam4l/src/scif.rs", "rank": 89, "score": 164396.17332700436 }, { "content": "/// Parse the TBF header length and the entire length of the TBF binary.\n\n///\n\n/// ## Return\n\n///\n\n/// If all parsing is successful:\n\n/// - Ok((Version, TBF header length, entire TBF length))\n\n///\n\n/// If we cannot parse the header because we have run out of flash, or the\n\n/// values are entirely wrong we return `UnableToParse`. This means we have hit\n\n/// the end of apps in flash.\n\n/// - Err(InitialTbfParseError::UnableToParse)\n\n///\n\n/// Any other error we return an error and the length of the entire app so that\n\n/// we can skip over it and check for the next app.\n\n/// - Err(InitialTbfParseError::InvalidHeader(app_length))\n\npub fn parse_tbf_header_lengths(\n\n app: &'static [u8; 8],\n\n) -> Result<(u16, u16, u32), types::InitialTbfParseError> {\n\n // Version is the first 16 bits of the app TBF contents. We need this to\n\n // correctly parse the other lengths.\n\n //\n\n // ## Safety\n\n // We trust that the version number has been checked prior to running this\n\n // parsing code. That is, whatever loaded this application has verified that\n\n // the version is valid and therefore we can trust it.\n\n let version = u16::from_le_bytes([app[0], app[1]]);\n\n\n\n match version {\n\n 2 => {\n\n // In version 2, the next 16 bits after the version represent\n\n // the size of the TBF header in bytes.\n\n let tbf_header_size = u16::from_le_bytes([app[2], app[3]]);\n\n\n\n // The next 4 bytes are the size of the entire app's TBF space\n\n // including the header. This also must be checked before parsing\n", "file_path": "libraries/tock-tbf/src/parse.rs", "rank": 90, "score": 161616.47734513023 }, { "content": "pub fn all_artemis_nano_tests() {\n\n println!(\"Tock board-runner starting...\");\n\n println!();\n\n println!(\"Running artemis_nano tests...\");\n\n artemis_nano_c_hello().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n artemis_nano_blink().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n // Doesn't work\n\n // artemis_nano_sensors().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n // Doesn't work\n\n // artemis_nano_c_hello_and_printf_long().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n artemis_nano_blink_and_c_hello_and_buttons()\n\n .unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n\n\n artemis_nano_malloc_test1().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n // Doesn't work\n\n // artemis_nano_stack_size_test1().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n // Doesn't work\n\n // artemis_nano_stack_size_test2().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n // Doesn't work\n\n // artemis_nano_mpu_stack_growth().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n artemis_nano_mpu_walk_region().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n artemis_nano_multi_alarm_test()\n\n .unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n // Doesn't work\n\n // artemis_nano_lua().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n artemis_nano_whileone().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n\n\n println!(\"artemis_nano SUCCESS.\");\n\n}\n", "file_path": "tools/board-runner/src/artemis_nano.rs", "rank": 91, "score": 161603.68739417882 }, { "content": "pub fn compute_udp_checksum(\n\n ip6_header: &IP6Header,\n\n udp_header: &UDPHeader,\n\n udp_length: u16,\n\n payload: &[u8],\n\n) -> u16 {\n\n //This checksum is calculated according to some of the recommendations found in RFC 1071.\n\n\n\n let src_port = udp_header.get_src_port();\n\n let dst_port = udp_header.get_dst_port();\n\n let mut sum: u32 = 0;\n\n {\n\n //First, iterate through src/dst address and add them to the sum\n\n let mut i = 0;\n\n while i <= 14 {\n\n let msb_src: u16 = ((ip6_header.src_addr.0[i]) as u16) << 8;\n\n let lsb_src: u16 = ip6_header.src_addr.0[i + 1] as u16;\n\n let temp_src: u16 = msb_src + lsb_src;\n\n sum += temp_src as u32;\n\n\n", "file_path": "capsules/src/net/ipv6/ip_utils.rs", "rank": 92, "score": 161603.68739417882 }, { "content": "pub fn compute_icmp_checksum(\n\n ipv6_header: &IP6Header,\n\n icmp_header: &ICMP6Header,\n\n payload: &[u8],\n\n) -> u16 {\n\n let mut sum: u32 = 0;\n\n\n\n // add ipv6 pseudo-header\n\n sum += compute_ipv6_ph_sum(ipv6_header);\n\n\n\n // add type and code\n\n let msb = (icmp_header.get_type_as_int() as u32) << 8;\n\n let lsb = icmp_header.get_code() as u32;\n\n sum += msb + lsb;\n\n\n\n // add options\n\n match icmp_header.get_options() {\n\n ICMP6HeaderOptions::Type1 { unused } | ICMP6HeaderOptions::Type3 { unused } => {\n\n sum += unused >> 16; // upper 16 bits\n\n sum += unused & 0xffff; // lower 16 bits\n", "file_path": "capsules/src/net/ipv6/ip_utils.rs", "rank": 93, "score": 161603.68739417882 }, { "content": "pub fn all_earlgrey_nexysvideo_tests() {\n\n println!(\"Tock board-runner starting...\");\n\n println!();\n\n println!(\"Running earlgrey_nexysvideo tests...\");\n\n earlgrey_nexysvideo_c_hello()\n\n .unwrap_or_else(|e| panic!(\"earlgrey_nexysvideo_c_hello job failed with {}\", e));\n\n earlgrey_nexysvideo_blink()\n\n .unwrap_or_else(|e| panic!(\"earlgrey_nexysvideo_blink job failed with {}\", e));\n\n earlgrey_nexysvideo_c_hello_and_printf_long().unwrap_or_else(|e| {\n\n panic!(\n\n \"earlgrey_nexysvideo_c_hello_and_printf_long job failed with {}\",\n\n e\n\n )\n\n });\n\n earlgrey_nexysvideo_recv_short_and_recv_long().unwrap_or_else(|e| {\n\n panic!(\n\n \"earlgrey_nexysvideo_recv_short_and_recv_long job failed with {}\",\n\n e\n\n )\n\n });\n", "file_path": "tools/board-runner/src/earlgrey_nexysvideo.rs", "rank": 94, "score": 161603.68739417882 }, { "content": "#[inline]\n\nfn encode_address(addr: &Option<MacAddress>) -> usize {\n\n let short_addr_only = match *addr {\n\n Some(MacAddress::Short(addr)) => addr as usize,\n\n _ => 0,\n\n };\n\n ((AddressMode::from(addr) as usize) << 16) | short_addr_only\n\n}\n\n\n\nimpl device::RxClient for RadioDriver<'_> {\n\n fn receive<'b>(&self, buf: &'b [u8], header: Header<'b>, data_offset: usize, data_len: usize) {\n\n self.apps.each(|_, app, upcalls| {\n\n let read_present = app\n\n .app_read\n\n .mut_enter(|rbuf| {\n\n let len = min(rbuf.len(), data_offset + data_len);\n\n // Copy the entire frame over to userland, preceded by two\n\n // bytes: the data offset and the data length.\n\n rbuf[..len].copy_from_slice(&buf[..len]);\n\n rbuf[0].set(data_offset as u8);\n\n rbuf[1].set(data_len as u8);\n", "file_path": "capsules/src/ieee802154/driver.rs", "rank": 95, "score": 160954.28497138436 }, { "content": "pub fn rc32k_enabled() -> bool {\n\n BSCIF.rc32kcr.is_set(RC32Control::EN)\n\n}\n\n\n", "file_path": "chips/sam4l/src/bscif.rs", "rank": 96, "score": 160667.21607235272 }, { "content": "/// Compresses an IPv6 header into a 6loWPAN header\n\n///\n\n/// Constructs a 6LoWPAN header in `buf` from the given IPv6 datagram and\n\n/// 16-bit MAC addresses. If the compression was successful, returns\n\n/// `Ok((consumed, written))`, where `consumed` is the number of header\n\n/// bytes consumed from the IPv6 datagram `written` is the number of\n\n/// compressed header bytes written into `buf`. Payload bytes and\n\n/// non-compressed next headers are not written, so the remaining `buf.len()\n\n/// - consumed` bytes must still be copied over to `buf`.\n\npub fn compress<'a>(\n\n ctx_store: &dyn ContextStore,\n\n ip6_packet: &'a IP6Packet<'a>,\n\n src_mac_addr: MacAddress,\n\n dst_mac_addr: MacAddress,\n\n mut buf: &mut [u8],\n\n) -> Result<(usize, usize), ()> {\n\n // Note that consumed should be constant, and equal sizeof(IP6Header)\n\n //let (mut consumed, ip6_header) = IP6Header::decode(ip6_datagram).done().ok_or(())?;\n\n let mut consumed = 40; // TODO\n\n let ip6_header = ip6_packet.header;\n\n\n\n //let mut next_headers: &[u8] = &ip6_datagram[consumed..];\n\n\n\n // The first two bytes are the LOWPAN_IPHC header\n\n let mut written: usize = 2;\n\n\n\n // Initialize the LOWPAN_IPHC header\n\n buf[0..2].copy_from_slice(&iphc::DISPATCH);\n\n\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_compression.rs", "rank": 97, "score": 160667.21607235272 }, { "content": " kernel_readwrite_length: Cell<usize>,\n\n // Where to read/write from the kernel request.\n\n kernel_readwrite_address: Cell<usize>,\n\n}\n\n\n\nimpl<'a> NonvolatileStorage<'a> {\n\n pub fn new(\n\n driver: &'a dyn hil::nonvolatile_storage::NonvolatileStorage<'static>,\n\n grant: Grant<App, 2>,\n\n userspace_start_address: usize,\n\n userspace_length: usize,\n\n kernel_start_address: usize,\n\n kernel_length: usize,\n\n buffer: &'static mut [u8],\n\n ) -> NonvolatileStorage<'a> {\n\n NonvolatileStorage {\n\n driver: driver,\n\n apps: grant,\n\n buffer: TakeCell::new(buffer),\n\n current_user: OptionalCell::empty(),\n", "file_path": "capsules/src/nonvolatile_storage_driver.rs", "rank": 98, "score": 64.41370511805468 }, { "content": " pending_command: bool,\n\n flash_address: usize,\n\n}\n\n\n\npub struct AppFlash<'a> {\n\n driver: &'a dyn hil::nonvolatile_storage::NonvolatileStorage<'static>,\n\n apps: Grant<App, 1>,\n\n current_app: OptionalCell<ProcessId>,\n\n buffer: TakeCell<'static, [u8]>,\n\n}\n\n\n\nimpl<'a> AppFlash<'a> {\n\n pub fn new(\n\n driver: &'a dyn hil::nonvolatile_storage::NonvolatileStorage<'static>,\n\n grant: Grant<App, 1>,\n\n buffer: &'static mut [u8],\n\n ) -> AppFlash<'a> {\n\n AppFlash {\n\n driver: driver,\n\n apps: grant,\n", "file_path": "capsules/src/app_flash_driver.rs", "rank": 99, "score": 63.392890564799295 } ]
Rust
engine/src/graphics/mod.rs
arcana-engine/arcana
e641ecfdf48c2844cf886834ad3aa981d3be7168
#[macro_export] macro_rules! vertex_location { ($offset:ident, $elem:ty as $semantics:literal) => { VertexLocation { format: <$elem as $crate::graphics::FormatElement>::FORMAT, semantics: $crate::graphics::Semantics::new($semantics), offset: { let offset = $offset; #[allow(unused_assignments)] { $offset += ::core::mem::size_of::<$elem>() as u32; } offset }, } }; ($offset:ident, $va:ty) => { VertexLocation { format: <$va as $crate::graphics::VertexAttribute>::FORMAT, semantics: <$va as $crate::graphics::VertexAttribute>::SEMANTICS, offset: { let offset = $offset; #[allow(unused_assignments)] { $offset += ::core::mem::size_of::<$va>() as u32; } offset }, } }; } #[macro_export] macro_rules! define_vertex_attribute { ($( $(#[$meta:meta])* $vis:vis struct $va:ident as $semantics:tt ($fvis:vis $ft:ty); )*) => {$( $(#[$meta])* #[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)] #[repr(transparent)] $vis struct $va($fvis $ft); unsafe impl bytemuck::Zeroable for $va {} unsafe impl bytemuck::Pod for $va {} impl $crate::graphics::VertexAttribute for $va { const FORMAT: $crate::sierra::Format = <$ft as $crate::graphics::FormatElement>::FORMAT; const SEMANTICS: $crate::graphics::Semantics = $semantics; } impl<T> From<T> for $va where T: Into<$ft> { fn from(t: T) -> $va { $va(t.into()) } } )*}; } #[macro_export] macro_rules! define_vertex_type { ($( $(#[$meta:meta])* $vis:vis struct $vt:ident as $rate:ident { $( $van:ident: $vat:ty $(as $semantics:literal)? ),* $(,)? } )*) => {$( $(#[$meta])* #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] $vis struct $vt { $( $van: $vat, )* } unsafe impl bytemuck::Zeroable for $vt {} unsafe impl bytemuck::Pod for $vt {} impl $crate::graphics::VertexType for $vt { const LOCATIONS: &'static [$crate::graphics::VertexLocation] = { let mut offset = 0; $( let $van = $crate::vertex_location!(offset, $vat as $semantics ); )* &[$($van,)*] }; const RATE: $crate::graphics::VertexInputRate = $crate::graphics::VertexInputRate::$rate; } )*}; } pub mod node; pub mod renderer; mod format; mod material; mod scale; mod texture; mod upload; mod vertex; #[cfg(feature = "3d")] mod mesh; use std::{ collections::hash_map::{Entry, HashMap}, hash::Hash, ops::Deref, }; use bitsetium::{BitEmpty, BitSearch, BitUnset, Bits1024}; use bytemuck::Pod; use raw_window_handle::HasRawWindowHandle; use scoped_arena::Scope; use sierra::{ AccessFlags, Buffer, BufferInfo, CommandBuffer, CreateSurfaceError, Device, Encoder, Extent3d, Fence, Format, Image, ImageInfo, ImageUsage, Layout, Offset3d, OutOfMemory, PipelineStageFlags, PresentOk, Queue, Semaphore, SingleQueueQuery, SubresourceLayers, Surface, SwapchainImage, }; use self::upload::Uploader; pub use self::{format::*, material::*, scale::*, texture::*, vertex::*}; #[cfg(feature = "3d")] pub use self::mesh::*; pub struct Graphics { uploader: Uploader, queue: Queue, device: Device, } impl Graphics { pub fn new() -> eyre::Result<Self> { let graphics = sierra::Graphics::get_or_init()?; let physical = graphics .devices()? .into_iter() .max_by_key(|d| d.info().kind) .ok_or_else(|| eyre::eyre!("Failed to find physical device"))?; let (device, queue) = physical.create_device( &[ sierra::Feature::SurfacePresentation, sierra::Feature::ShaderSampledImageDynamicIndexing, sierra::Feature::ShaderSampledImageNonUniformIndexing, sierra::Feature::RuntimeDescriptorArray, sierra::Feature::ScalarBlockLayout, ], SingleQueueQuery::GRAPHICS, )?; Ok(Graphics { uploader: Uploader::new(&device)?, device, queue, }) } } impl Graphics { #[tracing::instrument(skip(self, window))] pub fn create_surface( &self, window: &impl HasRawWindowHandle, ) -> Result<Surface, CreateSurfaceError> { self.device.graphics().create_surface(window) } #[inline] #[tracing::instrument(skip(self, data))] pub fn upload_buffer<T>( &mut self, buffer: &Buffer, offset: u64, data: &[T], ) -> Result<(), OutOfMemory> where T: Pod, { self.uploader .upload_buffer(&self.device, buffer, offset, data) } #[inline] #[tracing::instrument(skip(self, data))] pub fn upload_buffer_with<'a, T>( &self, buffer: &'a Buffer, offset: u64, data: &'a [T], encoder: &mut Encoder<'a>, ) -> Result<(), OutOfMemory> where T: Pod, { self.uploader .upload_buffer_with(&self.device, buffer, offset, data, encoder) } #[inline] #[tracing::instrument(skip(self, data))] pub fn upload_image<T>(&mut self, upload: UploadImage, data: &[T]) -> Result<(), OutOfMemory> where T: Pod, { self.uploader.upload_image(&self.device, upload, data) } #[tracing::instrument(skip(self, data))] pub fn upload_image_with<'a, T>( &self, upload: UploadImage, data: &[T], encoder: &mut Encoder<'a>, ) -> Result<(), OutOfMemory> where T: Pod, { self.uploader .upload_image_with(&self.device, upload, data, encoder) } #[tracing::instrument(skip(self, data))] pub fn create_fast_buffer_static<T>( &mut self, info: BufferInfo, data: &[T], ) -> Result<Buffer, OutOfMemory> where T: Pod, { let buffer = self.device.create_buffer(info)?; self.upload_buffer(&buffer, 0, data)?; Ok(buffer) } #[tracing::instrument(skip(self, data))] pub fn create_image_static<T>( &mut self, mut info: ImageInfo, layout: Layout, data: &[T], format: Format, row_length: u32, image_height: u32, ) -> Result<Image, OutOfMemory> where T: Pod, { info.usage |= ImageUsage::TRANSFER_DST; let layers = SubresourceLayers::all_layers(&info, 0); let image = self.device.create_image(info)?; self.upload_image( UploadImage { image: &image, offset: Offset3d::ZERO, extent: info.extent.into_3d(), layers, old_layout: None, new_layout: layout, old_access: AccessFlags::empty(), new_access: AccessFlags::all(), format, row_length, image_height, }, data, )?; Ok(image) } pub fn create_encoder<'a>(&mut self, scope: &'a Scope<'a>) -> Result<Encoder<'a>, OutOfMemory> { self.queue.create_encoder(scope) } pub fn submit( &mut self, wait: &mut [(PipelineStageFlags, &mut Semaphore)], cbufs: impl IntoIterator<Item = CommandBuffer>, signal: &mut [&mut Semaphore], fence: Option<&mut Fence>, scope: &Scope<'_>, ) -> Result<(), OutOfMemory> { self.flush_uploads(scope)?; self.queue.submit(wait, cbufs, signal, fence, scope); Ok(()) } pub fn present(&mut self, image: SwapchainImage) -> Result<PresentOk, OutOfMemory> { self.queue.present(image) } fn flush_uploads(&mut self, scope: &Scope<'_>) -> Result<(), OutOfMemory> { self.uploader .flush_uploads(&self.device, &mut self.queue, scope) } } impl Drop for Graphics { fn drop(&mut self) { if !std::thread::panicking() { self.wait_idle(); } } } impl Deref for Graphics { type Target = Device; #[inline(always)] fn deref(&self) -> &Device { &self.device } } pub struct SparseDescriptors<T> { resources: HashMap<T, u32>, bitset: Bits1024, next: u32, } impl<T> Default for SparseDescriptors<T> { #[inline] fn default() -> Self { SparseDescriptors::new() } } impl<T> SparseDescriptors<T> { #[inline] pub fn new() -> Self { SparseDescriptors { resources: HashMap::new(), bitset: BitEmpty::empty(), next: 0, } } pub fn index(&mut self, resource: T) -> (u32, bool) where T: Hash + Eq, { match self.resources.entry(resource) { Entry::Occupied(entry) => (*entry.get(), false), Entry::Vacant(entry) => { if let Some(index) = self.bitset.find_first_set(0) { self.bitset.unset(index); (*entry.insert(index as u32), true) } else { self.next += 1; (*entry.insert(self.next - 1), true) } } } } } #[derive(Debug)] pub struct UploadImage<'a> { pub image: &'a Image, pub offset: Offset3d, pub extent: Extent3d, pub layers: SubresourceLayers, pub old_layout: Option<Layout>, pub new_layout: Layout, pub old_access: AccessFlags, pub new_access: AccessFlags, pub format: Format, pub row_length: u32, pub image_height: u32, }
#[macro_export] macro_rules! vertex_location { ($offset:ident, $elem:ty as $semantics:literal) => { VertexLocation { format: <$elem as $crate::graphics::FormatElement>::FORMAT, semantics: $crate::graphics::Semantics::new($semantics), offset: { let offset = $offset; #[allow(unused_assignments)] { $offset += ::core::mem::size_of::<$elem>() as u32; } offset }, } }; ($offset:ident, $va:ty) => { VertexLocation { format: <$va as $crate::graphics::VertexAttribute>::FORMAT, semantics: <$va as $crate::graphics::VertexAttribute>::SEMANTICS, offset: { let offset = $offset; #[allow(unused_assignments)] { $offset += ::core::mem::size_of::<$va>() as u32; } offset }, } }; } #[macro_export] macro_rules! define_vertex_attribute { ($( $(#[$meta:meta])* $vis:vis struct $va:ident as $semantics:tt ($fvis:vis $ft:ty); )*) => {$( $(#[$meta])* #[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)] #[repr(transparent)] $vis struct $va($fvis $ft); unsafe impl bytemuck::Zeroable for $va {} unsafe impl bytemuck::Pod for $va {} impl $crate::graphics::VertexAttribute for $va { const FORMAT: $crate::sierra::Format = <$ft as $crate::graphics::FormatElement>::FORMAT; const SEMANTICS: $crate::graphics::Semantics = $semantics; } impl<T> From<T> for $va where T: Into<$ft> { fn from(t: T) -> $va { $va(t.into()) } } )*}; } #[macro_export] macro_rules! define_vertex_type { ($( $(#[$meta:meta])* $vis:vis struct $vt:ident as $rate:ident { $( $van:ident: $vat:ty $(as $semantics:literal)? ),* $(,)? } )*) => {$( $(#[$meta])* #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] $vis struct $vt { $( $van: $vat, )* } unsafe impl bytemuck::Zeroable for $vt {} unsafe impl bytemuck::Pod for $vt {} impl $crate::graphics::VertexType for $vt { const LOCATIONS: &'static [$crate::graphics::VertexLocation] = { let mut offset = 0; $( let $van = $crate::vertex_location!(offset, $vat as $semantics ); )* &[$($van,)*] }; const RATE: $crate::graphics::VertexInputRate = $crate::graphics::VertexInputRate::$rate; } )*}; } pub mod node; pub mod renderer; mod format; mod material; mod scale; mod texture; mod upload; mod vertex; #[cfg(feature = "3d")] mod mesh; use std::{ collections::hash_map::{Entry, HashMap}, hash::Hash, ops::Deref, }; use bitsetium::{BitEmpty, BitSearch, BitUnset, Bits1024}; use bytemuck::Pod; use raw_window_handle::HasRawWindowHandle; use scoped_arena::Scope; use sierra::{ AccessFlags, Buffer, BufferInfo, CommandBuffer, CreateSurfaceError, Device, Encoder, Extent3d, Fence, Format, Image, ImageInfo, ImageUsage, Layout, Offset3d, OutOfMemory, PipelineStageFlags, PresentOk, Queue, Semaphore, SingleQueueQuery, SubresourceLayers, Surface, SwapchainImage, }; use self::upload::Uploader; pub use self::{format::*, material::*, scale::*, texture::*, vertex::*}; #[cfg(feature = "3d")] pub use self::mesh::*; pub struct Graphics { uploader: Uploader, queue: Queue, device: Device, } impl Graphics { pub fn new() -> eyre::Result<Self> { let graphics = sierra::Graphics::get_or_init()?; let physical = graphics .devices()? .into_iter() .max_by_key(|d| d.info().kind) .ok_or_else(|| eyre::eyre!("Failed to find physical device"))?; let (device, queue) = physical.create_device( &[ sierra::Feature::SurfacePresentation, sierra::Feature::ShaderSampledImageDynamicIndexing, sierra::Feature::ShaderSampledImageNonUniformIndexing, sierra::Feature::RuntimeDescriptorArray, sierra::Feature::ScalarBlockLayout, ], SingleQueueQuery::GRAPHICS, )?; Ok(Graphics { uploader: Uploader::new(&device)?, device, queue, }) } } impl Graphics { #[tracing::instrument(skip(self, window))]
#[inline] #[tracing::instrument(skip(self, data))] pub fn upload_buffer<T>( &mut self, buffer: &Buffer, offset: u64, data: &[T], ) -> Result<(), OutOfMemory> where T: Pod, { self.uploader .upload_buffer(&self.device, buffer, offset, data) } #[inline] #[tracing::instrument(skip(self, data))] pub fn upload_buffer_with<'a, T>( &self, buffer: &'a Buffer, offset: u64, data: &'a [T], encoder: &mut Encoder<'a>, ) -> Result<(), OutOfMemory> where T: Pod, { self.uploader .upload_buffer_with(&self.device, buffer, offset, data, encoder) } #[inline] #[tracing::instrument(skip(self, data))] pub fn upload_image<T>(&mut self, upload: UploadImage, data: &[T]) -> Result<(), OutOfMemory> where T: Pod, { self.uploader.upload_image(&self.device, upload, data) } #[tracing::instrument(skip(self, data))] pub fn upload_image_with<'a, T>( &self, upload: UploadImage, data: &[T], encoder: &mut Encoder<'a>, ) -> Result<(), OutOfMemory> where T: Pod, { self.uploader .upload_image_with(&self.device, upload, data, encoder) } #[tracing::instrument(skip(self, data))] pub fn create_fast_buffer_static<T>( &mut self, info: BufferInfo, data: &[T], ) -> Result<Buffer, OutOfMemory> where T: Pod, { let buffer = self.device.create_buffer(info)?; self.upload_buffer(&buffer, 0, data)?; Ok(buffer) } #[tracing::instrument(skip(self, data))] pub fn create_image_static<T>( &mut self, mut info: ImageInfo, layout: Layout, data: &[T], format: Format, row_length: u32, image_height: u32, ) -> Result<Image, OutOfMemory> where T: Pod, { info.usage |= ImageUsage::TRANSFER_DST; let layers = SubresourceLayers::all_layers(&info, 0); let image = self.device.create_image(info)?; self.upload_image( UploadImage { image: &image, offset: Offset3d::ZERO, extent: info.extent.into_3d(), layers, old_layout: None, new_layout: layout, old_access: AccessFlags::empty(), new_access: AccessFlags::all(), format, row_length, image_height, }, data, )?; Ok(image) } pub fn create_encoder<'a>(&mut self, scope: &'a Scope<'a>) -> Result<Encoder<'a>, OutOfMemory> { self.queue.create_encoder(scope) } pub fn submit( &mut self, wait: &mut [(PipelineStageFlags, &mut Semaphore)], cbufs: impl IntoIterator<Item = CommandBuffer>, signal: &mut [&mut Semaphore], fence: Option<&mut Fence>, scope: &Scope<'_>, ) -> Result<(), OutOfMemory> { self.flush_uploads(scope)?; self.queue.submit(wait, cbufs, signal, fence, scope); Ok(()) } pub fn present(&mut self, image: SwapchainImage) -> Result<PresentOk, OutOfMemory> { self.queue.present(image) } fn flush_uploads(&mut self, scope: &Scope<'_>) -> Result<(), OutOfMemory> { self.uploader .flush_uploads(&self.device, &mut self.queue, scope) } } impl Drop for Graphics { fn drop(&mut self) { if !std::thread::panicking() { self.wait_idle(); } } } impl Deref for Graphics { type Target = Device; #[inline(always)] fn deref(&self) -> &Device { &self.device } } pub struct SparseDescriptors<T> { resources: HashMap<T, u32>, bitset: Bits1024, next: u32, } impl<T> Default for SparseDescriptors<T> { #[inline] fn default() -> Self { SparseDescriptors::new() } } impl<T> SparseDescriptors<T> { #[inline] pub fn new() -> Self { SparseDescriptors { resources: HashMap::new(), bitset: BitEmpty::empty(), next: 0, } } pub fn index(&mut self, resource: T) -> (u32, bool) where T: Hash + Eq, { match self.resources.entry(resource) { Entry::Occupied(entry) => (*entry.get(), false), Entry::Vacant(entry) => { if let Some(index) = self.bitset.find_first_set(0) { self.bitset.unset(index); (*entry.insert(index as u32), true) } else { self.next += 1; (*entry.insert(self.next - 1), true) } } } } } #[derive(Debug)] pub struct UploadImage<'a> { pub image: &'a Image, pub offset: Offset3d, pub extent: Extent3d, pub layers: SubresourceLayers, pub old_layout: Option<Layout>, pub new_layout: Layout, pub old_access: AccessFlags, pub new_access: AccessFlags, pub format: Format, pub row_length: u32, pub image_height: u32, }
pub fn create_surface( &self, window: &impl HasRawWindowHandle, ) -> Result<Surface, CreateSurfaceError> { self.device.graphics().create_surface(window) }
function_block-full_function
[ { "content": "pub trait FormatElement: Clone + Copy + Debug + Default + PartialEq + PartialOrd + Pod {\n\n const FORMAT: Format;\n\n}\n\n\n\n#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\n#[cfg_attr(feature = \"serde-1\", derive(serde::Serialize, serde::Deserialize))]\n\n#[cfg_attr(feature = \"serde-1\", serde(transparent))]\n\n#[repr(transparent)]\n\npub struct Srgb(pub u8);\n\n\n\nunsafe impl Zeroable for Srgb {}\n\nunsafe impl Pod for Srgb {}\n\n\n\n#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\n#[cfg_attr(feature = \"serde-1\", derive(serde::Serialize, serde::Deserialize))]\n\n#[cfg_attr(feature = \"serde-1\", serde(transparent))]\n\n#[repr(transparent)]\n\npub struct Norm<T>(pub T);\n\n\n\nunsafe impl<T: Zeroable> Zeroable for Norm<T> {}\n", "file_path": "engine/src/graphics/format.rs", "rank": 0, "score": 315695.8574164294 }, { "content": "/// Single render node.\n\n/// Renderer may consist of few of them.\n\n/// Rarely used in generic way.\n\n/// This trait's main purpose is to define API for render nodes to implement.\n\npub trait RenderNode: for<'a> RenderNodeInputs<'a> + 'static {\n\n /// Outputs produced by render pass.\n\n /// This includes any resources render pass creates.\n\n /// This does not include existing resources to which render pass will write.\n\n type Outputs;\n\n\n\n /// Render using inputs and producing outputs.\n\n fn render<'a>(\n\n &'a mut self,\n\n cx: RendererContext<'a, 'a>,\n\n inputs: <Self as RenderNodeInputs<'a>>::Inputs,\n\n ) -> eyre::Result<Self::Outputs>;\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/mod.rs", "rank": 1, "score": 296836.5327309633 }, { "content": "pub trait DrawNode: 'static {\n\n /// Draw.\n\n fn draw<'a, 'b: 'a>(\n\n &'b mut self,\n\n cx: RendererContext<'a, 'b>,\n\n encoder: &mut Encoder<'a>,\n\n render_pass: &mut RenderPassEncoder<'_, 'b>,\n\n camera: EntityId,\n\n viewport: Extent2d,\n\n ) -> eyre::Result<()>;\n\n}\n\n\n\nimpl<N> DrawNode for Box<N>\n\nwhere\n\n N: DrawNode + ?Sized,\n\n{\n\n fn draw<'a, 'b: 'a>(\n\n &'b mut self,\n\n cx: RendererContext<'a, 'b>,\n\n\n", "file_path": "engine/src/graphics/renderer/mod.rs", "rank": 2, "score": 296579.4080237998 }, { "content": "/// Trait for vertex layouts.\n\npub trait VertexType: Debug + Default + PartialEq + Pod {\n\n const LOCATIONS: &'static [VertexLocation];\n\n const RATE: VertexInputRate;\n\n\n\n /// Get layout of this vertex type.\n\n fn layout() -> VertexLayout\n\n where\n\n Self: Sized,\n\n {\n\n VertexLayout {\n\n locations: Cow::Borrowed(Self::LOCATIONS),\n\n stride: size_of::<Self>() as u32,\n\n rate: Self::RATE,\n\n }\n\n }\n\n}\n\n\n\nimpl<T> VertexType for T\n\nwhere\n\n T: VertexAttribute,\n", "file_path": "engine/src/graphics/vertex.rs", "rank": 3, "score": 288798.06688185397 }, { "content": "/// Trait for single vertex attribute.\n\npub trait VertexAttribute: Debug + Default + PartialEq + Pod {\n\n const FORMAT: Format;\n\n const SEMANTICS: Semantics;\n\n}\n\n\n", "file_path": "engine/src/graphics/vertex.rs", "rank": 4, "score": 288792.9303305709 }, { "content": "pub fn vertex_layouts_for_pipeline(\n\n layouts: &[VertexLayout],\n\n) -> (Vec<VertexInputBinding>, Vec<VertexInputAttribute>) {\n\n let mut next_location = 0;\n\n\n\n let mut locations = Vec::new();\n\n\n\n let bindings = layouts\n\n .iter()\n\n .enumerate()\n\n .map(|(binding, layout)| {\n\n locations.extend(layout.locations.iter().map(|layout| {\n\n next_location += 1;\n\n\n\n VertexInputAttribute {\n\n location: next_location - 1,\n\n format: layout.format,\n\n offset: layout.offset,\n\n binding: binding as u32,\n\n }\n", "file_path": "engine/src/graphics/vertex.rs", "rank": 5, "score": 271953.2060769985 }, { "content": "/// Abstract rendering system.\n\npub trait Renderer: 'static {\n\n /// Render into specified viewports.\n\n fn render(\n\n &mut self,\n\n cx: RendererContext<'_, '_>,\n\n viewports: &mut [&mut Viewport],\n\n ) -> eyre::Result<()>;\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/mod.rs", "rank": 6, "score": 270015.1994789364 }, { "content": "pub fn texture_view_from_qoi_image(\n\n qoi: &rapid_qoi::Qoi,\n\n pixels: &[u8],\n\n graphics: &mut Graphics,\n\n) -> Result<ImageView, OutOfMemory> {\n\n use rapid_qoi::Colors::*;\n\n use sierra::Format::*;\n\n\n\n let (data_format, image_format) = match qoi.colors {\n\n Rgb => (RGB8Unorm, RGBA8Unorm),\n\n Rgba => (RGBA8Unorm, RGBA8Unorm),\n\n Srgb => (RGB8Srgb, RGBA8Srgb),\n\n SrgbLinA => (RGBA8Srgb, RGBA8Srgb),\n\n };\n\n\n\n let image = graphics.create_image_static(\n\n ImageInfo {\n\n extent: ImageExtent::D2 {\n\n width: qoi.width,\n\n height: qoi.height,\n", "file_path": "engine/src/graphics/texture.rs", "rank": 7, "score": 267758.03119590523 }, { "content": "struct BufferUpload {\n\n staging: Buffer,\n\n buffer: Buffer,\n\n offset: u64,\n\n old_access: AccessFlags,\n\n new_access: AccessFlags,\n\n}\n\n\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 8, "score": 252002.33813919275 }, { "content": "struct ImageUpload {\n\n image: Image,\n\n offset: Offset3d,\n\n extent: Extent3d,\n\n layers: SubresourceLayers,\n\n old_layout: Option<Layout>,\n\n new_layout: Layout,\n\n old_access: AccessFlags,\n\n new_access: AccessFlags,\n\n staging: Buffer,\n\n format: Format,\n\n row_length: u32,\n\n image_height: u32,\n\n}\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 9, "score": 251937.32916510807 }, { "content": "pub fn v2<A, B>(a: impl Into<A>, b: impl Into<B>) -> V2<A, B> {\n\n V2(a.into(), b.into())\n\n}\n\n\n\nunsafe impl<A: Zeroable, B: Zeroable> Zeroable for V2<A, B> {}\n\nunsafe impl<A: Pod, B: Pod> Pod for V2<A, B> {}\n\n\n\nimpl<A, B> VertexType for V2<A, B>\n\nwhere\n\n A: VertexAttribute,\n\n B: VertexAttribute,\n\n{\n\n const LOCATIONS: &'static [VertexLocation] = &[\n\n VertexLocation {\n\n format: A::FORMAT,\n\n offset: 0,\n\n semantics: A::SEMANTICS,\n\n },\n\n VertexLocation {\n\n format: B::FORMAT,\n", "file_path": "engine/src/graphics/vertex.rs", "rank": 10, "score": 249871.78698715207 }, { "content": "pub trait RenderNodeInputs<'a> {\n\n /// Inputs required by render pass.\n\n /// This includes resources to which render pass will write.\n\n type Inputs;\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/mod.rs", "rank": 11, "score": 239143.90718907522 }, { "content": "pub fn v3<A, B, C>(a: impl Into<A>, b: impl Into<B>, c: impl Into<C>) -> V3<A, B, C> {\n\n V3(a.into(), b.into(), c.into())\n\n}\n\n\n\nunsafe impl<A: Zeroable, B: Zeroable, C: Zeroable> Zeroable for V3<A, B, C> {}\n\nunsafe impl<A: Pod, B: Pod, C: Pod> Pod for V3<A, B, C> {}\n\n\n\nimpl<A, B, C> VertexType for V3<A, B, C>\n\nwhere\n\n A: VertexAttribute,\n\n B: VertexAttribute,\n\n C: VertexAttribute,\n\n{\n\n const LOCATIONS: &'static [VertexLocation] = &[\n\n VertexLocation {\n\n format: A::FORMAT,\n\n offset: 0,\n\n semantics: A::SEMANTICS,\n\n },\n\n VertexLocation {\n", "file_path": "engine/src/graphics/vertex.rs", "rank": 12, "score": 238424.044290127 }, { "content": "#[repr(C)]\n\n#[derive(Clone, Copy, Debug, Default, PartialEq)]\n\nstruct Vertex {\n\n pos: Position2,\n\n uv: UV,\n\n albedo: u32,\n\n albedo_factor: LinSrgba<f32>,\n\n}\n\n\n\nunsafe impl bytemuck::Zeroable for Vertex {}\n\nunsafe impl bytemuck::Pod for Vertex {}\n\n\n\nimpl VertexType for Vertex {\n\n const LOCATIONS: &'static [VertexLocation] = {\n\n let mut offset = 0;\n\n\n\n let pos = vertex_location!(offset, Position2);\n\n let uv = vertex_location!(offset, UV);\n\n let albedo = vertex_location!(offset, u32 as \"Albedo\");\n\n let albedo_factor = vertex_location!(offset, LinSrgba<f32>);\n\n &[pos, uv, albedo, albedo_factor]\n\n };\n\n const RATE: VertexInputRate = VertexInputRate::Vertex;\n\n}\n", "file_path": "engine/src/graphics/renderer/sigils.rs", "rank": 13, "score": 234616.00154002546 }, { "content": "#[allow(unused)]\n\n#[inline(always)]\n\nfn mat4_na_to_sierra(m: na::Matrix4<f32>) -> sierra::mat4<f32> {\n\n let array: [[f32; 4]; 4] = m.into();\n\n sierra::mat4::from(array)\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/mod.rs", "rank": 14, "score": 231422.82732744166 }, { "content": "#[allow(unused)]\n\n#[inline(always)]\n\nfn mat3_na_to_sierra(m: na::Matrix3<f32>) -> sierra::mat3<f32> {\n\n let array: [[f32; 3]; 3] = m.into();\n\n sierra::mat3::from(array)\n\n}\n", "file_path": "engine/src/graphics/renderer/mod.rs", "rank": 15, "score": 231422.8273274416 }, { "content": "fn triplets(mut iter: impl ExactSizeIterator<Item = u32>) -> Vec<[u32; 3]> {\n\n let mut result = Vec::with_capacity(iter.len() / 3);\n\n loop {\n\n match (iter.next(), iter.next(), iter.next()) {\n\n (Some(a), Some(b), Some(c)) => result.push([a, b, c]),\n\n _ => return result,\n\n }\n\n }\n\n}\n", "file_path": "engine/src/assets/import/gltf/collider.rs", "rank": 16, "score": 228348.47828901123 }, { "content": "pub fn load_material(material: gltf::Material, textures: &[TextureInfo]) -> MaterialInfo {\n\n let pbr = material.pbr_metallic_roughness();\n\n\n\n MaterialInfo {\n\n albedo: pbr\n\n .base_color_texture()\n\n .map(|info| textures[info.texture().index()]),\n\n albedo_factor: {\n\n let [r, g, b, a] = pbr.base_color_factor();\n\n [r, g, b, a]\n\n },\n\n metalness_roughness: pbr\n\n .metallic_roughness_texture()\n\n .map(|info| textures[info.texture().index()]),\n\n metalness_factor: pbr.metallic_factor(),\n\n roughness_factor: pbr.roughness_factor(),\n\n\n\n emissive: material\n\n .emissive_texture()\n\n .map(|info| textures[info.texture().index()]),\n", "file_path": "engine/src/assets/import/gltf/material.rs", "rank": 17, "score": 210553.47123569477 }, { "content": "pub fn v4<A, B, C, D>(\n\n a: impl Into<A>,\n\n b: impl Into<B>,\n\n c: impl Into<C>,\n\n d: impl Into<D>,\n\n) -> V4<A, B, C, D> {\n\n V4(a.into(), b.into(), c.into(), d.into())\n\n}\n\n\n\nunsafe impl<A: Zeroable, B: Zeroable, C: Zeroable, D: Zeroable> Zeroable for V4<A, B, C, D> {}\n\nunsafe impl<A: Pod, B: Pod, C: Pod, D: Pod> Pod for V4<A, B, C, D> {}\n\n\n\nimpl<A, B, C, D> VertexType for V4<A, B, C, D>\n\nwhere\n\n A: VertexAttribute,\n\n B: VertexAttribute,\n\n C: VertexAttribute,\n\n D: VertexAttribute,\n\n{\n\n const LOCATIONS: &'static [VertexLocation] = &[\n", "file_path": "engine/src/graphics/vertex.rs", "rank": 18, "score": 202396.14914419313 }, { "content": "#[derive(ShaderRepr)]\n\n#[sierra(std140)]\n\nstruct OffsetStride {\n\n offset: ivec2,\n\n stride: u32,\n\n}\n\n\n", "file_path": "engine/src/graphics/upload/rgb2rgba.rs", "rank": 19, "score": 199396.19108220979 }, { "content": "#[derive(Descriptors)]\n\nstruct TextureDescriptor {\n\n #[sierra(image(sampled), fragment)]\n\n texture: ImageView,\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/egui.rs", "rank": 20, "score": 198951.524956208 }, { "content": "/// All rendering nodes implement this trait for ease of use.\n\n/// Nodes need not be designed to be used generically.\n\npub trait Node {\n\n /// Resources consumed by the `Node`.\n\n /// This type contains all resources, images and buffers required\n\n /// for this Node to run.\n\n ///\n\n /// It is also useful to place \"output\" resources here,\n\n //// such as render attachments,\n\n /// so node would use them instead of creating own resources.\n\n type Input;\n\n\n\n /// Resources produced by the node. That can be put into following nodes.\n\n type Output;\n\n\n\n /// Run this node.\n\n fn run(&mut self, cx: NodeContext<'_>, input: Self::Input) -> eyre::Result<Self::Output>;\n\n}\n", "file_path": "engine/src/graphics/node.rs", "rank": 21, "score": 196795.0003579675 }, { "content": "struct VcolorRenderable {\n\n descriptors: <VcolorDescriptors as DescriptorsInput>::Instance,\n\n}\n\n\n\nimpl VcolorRenderer {\n\n fn render(&mut self, cx: RendererContext<'_>, viewport: &mut Viewport) -> eyre::Result<()> {\n\n if let Some(fence) = &mut self.fences[self.fence_index] {\n\n cx.graphics.wait_fences(&mut [fence], true);\n\n cx.graphics.reset_fences(&mut [fence]);\n\n }\n\n\n\n let view = cx\n\n .world\n\n .get_mut::<Global3>(viewport.camera())?\n\n .iso\n\n .inverse()\n\n .to_homogeneous();\n\n\n\n let proj = cx\n\n .world\n", "file_path": "engine/src/graphics/renderer/vcolor.rs", "rank": 22, "score": 166064.34021049904 }, { "content": "struct BasicRenderable {\n\n descriptors: <BasicDescriptors as Descriptors>::Instance,\n\n}\n\n\n\nimpl DrawNode for BasicDraw {\n\n fn draw<'a, 'b: 'a>(\n\n &'b mut self,\n\n cx: RendererContext<'a, 'b>,\n\n encoder: &mut Encoder<'a>,\n\n render_pass: &mut RenderPassEncoder<'_, 'b>,\n\n camera: EntityId,\n\n _viewport: Extent2d,\n\n ) -> eyre::Result<()> {\n\n let (global, camera) = cx.world.query_one::<(&Global3, &Camera3)>(&camera)?;\n\n\n\n let view = global.iso.inverse().to_homogeneous();\n\n let proj = camera.proj().to_homogeneous();\n\n\n\n let mut uniforms = Uniforms {\n\n camera_view: mat4_na_to_sierra(view),\n", "file_path": "engine/src/graphics/renderer/basic.rs", "rank": 23, "score": 166064.34021049904 }, { "content": "#[derive(Pass)]\n\n#[sierra(subpass(color = color, depth = depth))]\n\nstruct SimpleRenderPass {\n\n #[sierra(attachment(store = const Layout::Present, clear = const ClearColor(0.02, 0.03, 0.03, 1.0)))]\n\n color: Image,\n\n\n\n #[sierra(attachment(clear = const ClearDepth(1.0)))]\n\n depth: Format,\n\n}\n\n\n\npub struct SimpleRenderer<N> {\n\n nodes: Vec<N>,\n\n render_pass: SimpleRenderPassInstance,\n\n fences: [Option<Fence>; 3],\n\n fence_index: usize,\n\n}\n\n\n\nimpl<N> SimpleRenderer<N> {\n\n pub fn new(node: N) -> Self {\n\n SimpleRenderer::with_multiple(vec![node])\n\n }\n\n\n", "file_path": "engine/src/graphics/renderer/simple.rs", "rank": 24, "score": 163553.24395149367 }, { "content": "#[pass]\n\n#[subpass(color = color, depth = depth)]\n\nstruct VcolorRenderPass {\n\n #[attachment(store(const Layout::Present), clear(const ClearColor(0.2, 0.1, 0.1, 1.0)))]\n\n color: Image,\n\n\n\n #[attachment(clear(const ClearDepth(1.0)))]\n\n depth: Format,\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/vcolor.rs", "rank": 25, "score": 163548.371921824 }, { "content": "fn random_spawn_location(world: &mut World) -> Global2 {\n\n let maps_count = world\n\n .query_mut::<()>()\n\n .with::<TileMap>()\n\n .with::<TileSet>()\n\n .with::<Global2>()\n\n .into_iter()\n\n .count();\n\n\n\n let map_index = rand::random::<usize>() % maps_count;\n\n\n\n let (_, (map, set, global)) = world\n\n .query_mut::<(&TileMap, &TileSet, &Global2)>()\n\n .into_iter()\n\n .nth(map_index)\n\n .unwrap();\n\n\n\n let dim = map.dimensions();\n\n\n\n loop {\n", "file_path": "examples/tanks/server/src/main.rs", "rank": 26, "score": 159778.9016389935 }, { "content": "fn dimensions(attribute: VertexAttribute) -> &'static [Dimensions] {\n\n match attribute {\n\n VertexAttribute::Position3 => &[Dimensions::Vec3],\n\n VertexAttribute::Normal3 => &[Dimensions::Vec3],\n\n VertexAttribute::Tangent3 => &[Dimensions::Vec4],\n\n VertexAttribute::UV => &[Dimensions::Vec2],\n\n VertexAttribute::Color => &[Dimensions::Vec4],\n\n VertexAttribute::Joints => &[Dimensions::Vec4],\n\n VertexAttribute::Weights => &[Dimensions::Vec4],\n\n }\n\n}\n\n\n", "file_path": "engine/src/assets/import/gltf/primitive.rs", "rank": 27, "score": 159497.2298601923 }, { "content": "#[derive(Clone, Copy, Default, ShaderRepr)]\n\n#[sierra(std140)]\n\nstruct Uniforms {\n\n inv_dimensions: vec2,\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/egui.rs", "rank": 28, "score": 158846.39633274585 }, { "content": "#[derive(Clone, Copy, Default, ShaderRepr)]\n\n#[sierra(std140)]\n\nstruct Uniforms {\n\n camera: mat3,\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/sprite.rs", "rank": 29, "score": 158846.39633274585 }, { "content": "#[derive(Clone, Copy, ShaderRepr)]\n\n#[sierra(std140)]\n\nstruct Uniforms {\n\n albedo_factor: vec4,\n\n camera_view: mat4,\n\n camera_proj: mat4,\n\n transform: mat4,\n\n joints: [mat4; 128],\n\n}\n\n\n\nimpl Default for Uniforms {\n\n #[inline]\n\n fn default() -> Self {\n\n Uniforms {\n\n camera_view: mat4::default(),\n\n camera_proj: mat4::default(),\n\n transform: mat4::default(),\n\n joints: [mat4::default(); 128],\n\n albedo_factor: vec4::default(),\n\n }\n\n }\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/basic.rs", "rank": 30, "score": 158841.63805723927 }, { "content": "#[shader_repr]\n\n#[derive(Clone, Copy)]\n\nstruct Uniforms {\n\n albedo: u32,\n\n}\n\n\n\nimpl Default for Uniforms {\n\n #[inline]\n\n fn default() -> Self {\n\n Uniforms { albedo: u32::MAX }\n\n }\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/sigils.rs", "rank": 31, "score": 158836.8139751123 }, { "content": "#[shader_repr]\n\n#[derive(Clone, Copy)]\n\nstruct Uniforms {\n\n camera_view: mat4,\n\n camera_proj: mat4,\n\n transform: mat4,\n\n}\n\n\n\nimpl Default for Uniforms {\n\n #[inline]\n\n fn default() -> Self {\n\n Uniforms {\n\n camera_view: mat4::default(),\n\n camera_proj: mat4::default(),\n\n transform: mat4::default(),\n\n }\n\n }\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/vcolor.rs", "rank": 32, "score": 158836.8139751123 }, { "content": "#[repr(C)]\n\n#[derive(Clone, Copy, Debug, Default, PartialEq)]\n\nstruct SpriteInstance {\n\n pos: Rect,\n\n uv: Rect,\n\n layer: f32,\n\n albedo: u32,\n\n albedo_factor: LinSrgba<f32>,\n\n transform: Transformation2,\n\n}\n\n\n\nunsafe impl bytemuck::Zeroable for SpriteInstance {}\n\nunsafe impl bytemuck::Pod for SpriteInstance {}\n\n\n\nimpl VertexType for SpriteInstance {\n\n const LOCATIONS: &'static [VertexLocation] = {\n\n let mut offset = 0;\n\n\n\n let pos = vertex_location!(offset, Rect);\n\n let uv = vertex_location!(offset, Rect);\n\n let layer = vertex_location!(offset, f32 as \"Layer\");\n\n let albedo = vertex_location!(offset, u32 as \"Albedo\");\n", "file_path": "engine/src/graphics/renderer/sprite.rs", "rank": 33, "score": 155998.1407444709 }, { "content": "#[allow(unused)]\n\n#[derive(PipelineInput)]\n\nstruct BasicPipeline {\n\n #[sierra(set)]\n\n set: BasicDescriptors,\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/basic.rs", "rank": 34, "score": 155983.77478023758 }, { "content": "#[descriptors]\n\nstruct SigilsDescriptors {\n\n #[sampler]\n\n #[stages(Fragment)]\n\n sampler: Sampler,\n\n\n\n #[sampled_image]\n\n #[stages(Fragment)]\n\n textures: [ImageView; 128],\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/sigils.rs", "rank": 35, "score": 155983.77478023758 }, { "content": "#[derive(Descriptors)]\n\nstruct SpriteDescriptors {\n\n #[sierra(sampler, fragment)]\n\n sampler: Sampler,\n\n\n\n #[sierra(image(sampled), fragment)]\n\n textures: [ImageView; 128],\n\n\n\n #[sierra(uniform, vertex)]\n\n uniforms: Uniforms,\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/sprite.rs", "rank": 36, "score": 155983.77478023758 }, { "content": "#[pipeline]\n\nstruct SigilsPipeline {\n\n #[set]\n\n set: SigilsDescriptors,\n\n}\n\n\n\npub struct SigilsDraw {\n\n pipeline: DynamicGraphicsPipeline,\n\n pipeline_layout: <SigilsPipeline as PipelineInput>::Layout,\n\n descriptors: SigilsDescriptors,\n\n set: SigilsDescriptorsInstance,\n\n textures: SparseDescriptors<ImageView>,\n\n meshes: Buffer,\n\n font_upload_buffer: Option<Buffer>,\n\n font_atlas_view: Option<ImageView>,\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/sigils.rs", "rank": 37, "score": 155983.77478023758 }, { "content": "#[derive(Descriptors)]\n\nstruct SamplerUniforms {\n\n #[sierra(sampler, fragment)]\n\n sampler: Sampler,\n\n\n\n #[sierra(uniform, vertex)]\n\n uniforms: Uniforms,\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/egui.rs", "rank": 38, "score": 155983.77478023758 }, { "content": "#[descriptors]\n\nstruct VcolorDescriptors {\n\n #[uniform]\n\n #[stages(Vertex, Fragment)]\n\n uniforms: Uniforms,\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/vcolor.rs", "rank": 39, "score": 155983.77478023758 }, { "content": "#[derive(PipelineInput)]\n\nstruct SpritePipeline {\n\n #[sierra(set)]\n\n set: SpriteDescriptors,\n\n}\n\n\n\nimpl SpriteDraw {\n\n pub fn new(layer_range: Range<f32>, graphics: &mut Graphics) -> eyre::Result<Self> {\n\n assert!(\n\n layer_range.start >= 0.0 && layer_range.end > layer_range.start,\n\n \"Layers range {}..{} is invalid\",\n\n layer_range.start,\n\n layer_range.end,\n\n );\n\n\n\n let layer_start_bits = layer_range.start.to_bits();\n\n let layer_end_bits = layer_range.end.to_bits();\n\n\n\n const MAX_LAYERS_COUNT: u32 = u16::MAX as u32;\n\n\n\n assert!(\n", "file_path": "engine/src/graphics/renderer/sprite.rs", "rank": 40, "score": 155983.77478023758 }, { "content": "#[derive(Descriptors)]\n\nstruct BasicDescriptors {\n\n #[sierra(sampler, fragment)]\n\n sampler: Sampler,\n\n\n\n #[sierra(image(sampled), fragment)]\n\n albedo: ImageView,\n\n\n\n #[sierra(uniform, stages(vertex, fragment))]\n\n uniforms: Uniforms,\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/basic.rs", "rank": 41, "score": 155983.77478023758 }, { "content": "#[pipeline]\n\nstruct VcolorPipeline {\n\n #[set]\n\n set: VcolorDescriptors,\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/vcolor.rs", "rank": 42, "score": 155983.77478023758 }, { "content": "#[derive(PipelineInput)]\n\nstruct EguiPipeline {\n\n #[sierra(set)]\n\n sampler_uniforms: SamplerUniforms,\n\n\n\n #[sierra(set)]\n\n texture: TextureDescriptor,\n\n}\n\n\n\npub struct EguiDraw {\n\n pipeline: DynamicGraphicsPipeline,\n\n pipeline_layout: EguiPipelineLayout,\n\n sampler_uniforms: SamplerUniforms,\n\n sampler_uniforms_set: SamplerUniformsInstance,\n\n meshes: Buffer,\n\n textures: HashMap<TextureId, TextureDescriptorInstance>,\n\n}\n\n\n\nimpl EguiDraw {\n\n pub fn new(graphics: &mut Graphics) -> eyre::Result<Self> {\n\n let vert_module = graphics.create_shader_module(ShaderModuleInfo::glsl(\n", "file_path": "engine/src/graphics/renderer/egui.rs", "rank": 43, "score": 155983.77478023758 }, { "content": "#[derive(Descriptors)]\n\n#[sierra(capacity = 32)]\n\nstruct Rgb2RgbaDescriptors {\n\n #[sierra(buffer(texel = rgba8unorm, uniform), compute)]\n\n pixels: BufferView,\n\n\n\n #[sierra(image(storage, layout = General), compute)]\n\n image: Image,\n\n}\n\n\n", "file_path": "engine/src/graphics/upload/rgb2rgba.rs", "rank": 44, "score": 153590.14683663094 }, { "content": "#[allow(unused)]\n\n#[derive(PipelineInput)]\n\nstruct Rgb2RgbaPipeline {\n\n #[sierra(set)]\n\n set: Rgb2RgbaDescriptors,\n\n\n\n #[sierra(push, compute)]\n\n offset_stride: OffsetStride,\n\n}\n\n\n\npub(super) struct Rgb2RgbaUploader {\n\n layout: Rgb2RgbaPipelineLayout,\n\n descriptors: Mutex<Rgb2RgbaDescriptorsInstance>,\n\n pipeline: ComputePipeline,\n\n}\n\n\n\nimpl Drop for Rgb2RgbaUploader {\n\n fn drop(&mut self) {\n\n self.descriptors.get_mut().clear();\n\n }\n\n}\n\n\n", "file_path": "engine/src/graphics/upload/rgb2rgba.rs", "rank": 45, "score": 153585.0862015906 }, { "content": "fn load_texture(\n\n texture: gltf::Texture,\n\n samplers: &[Option<SamplerInfo>],\n\n dependencies: &mut (impl Dependencies + ?Sized),\n\n missing: &mut Vec<Dependency>,\n\n) -> Result<Option<TextureInfo>, String> {\n\n match texture.source().source() {\n\n gltf::image::Source::View { .. } => unimplemented!(),\n\n gltf::image::Source::Uri { uri, .. } => {\n\n let image = dependencies.get_or_append(uri, \"qoi\", missing)?;\n\n\n\n match image {\n\n None => Ok(None),\n\n Some(image) => {\n\n let image = goods::AssetId(image.value());\n\n let sampler = texture.sampler().index().and_then(|idx| samplers[idx]);\n\n let texture = match sampler {\n\n None => TextureInfo::image(image),\n\n Some(sampler) => TextureInfo { image, sampler },\n\n };\n\n Ok(Some(texture))\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "engine/src/assets/import/gltf/mod.rs", "rank": 46, "score": 153500.8884870331 }, { "content": "struct SigilsDrawAssets {\n\n images: HashMap<AssetId, ImageView>,\n\n // fonts: HashMap<AssetId, FontFaces>,\n\n}\n\n\n\nimpl SigilsDraw {\n\n pub fn new(graphics: &mut Graphics) -> eyre::Result<Self> {\n\n let vert_module = graphics.create_shader_module(ShaderModuleInfo::spirv(\n\n std::include_bytes!(\"sigils.vert.spv\")\n\n .to_vec()\n\n .into_boxed_slice(),\n\n ))?;\n\n\n\n let frag_module = graphics.create_shader_module(ShaderModuleInfo::spirv(\n\n std::include_bytes!(\"sigils.frag.spv\")\n\n .to_vec()\n\n .into_boxed_slice(),\n\n ))?;\n\n\n\n let pipeline_layout = SigilsPipeline::layout(graphics)?;\n", "file_path": "engine/src/graphics/renderer/sigils.rs", "rank": 47, "score": 153258.35543231634 }, { "content": "fn build_triangles_blas<'a>(\n\n indices: Option<&Indices>,\n\n binding: &Binding,\n\n location: &VertexLocation,\n\n count: u32,\n\n vertex_count: u32,\n\n encoder: &mut Encoder<'a>,\n\n device: &Device,\n\n) -> Result<AccelerationStructure, OutOfMemory> {\n\n assert_eq!(count % 3, 0);\n\n let triangle_count = count / 3;\n\n\n\n assert_eq!(binding.layout, Position3::layout());\n\n\n\n let pos_range = BufferRange {\n\n buffer: binding.buffer.clone(),\n\n offset: binding.offset,\n\n size: u64::from(Position3::layout().stride) * u64::from(vertex_count),\n\n };\n\n\n", "file_path": "engine/src/graphics/mesh.rs", "rank": 48, "score": 152417.05894332094 }, { "content": "fn topology_triangles() -> PrimitiveTopology {\n\n PrimitiveTopology::TriangleList\n\n}\n\n\n\n#[cfg(feature = \"genmesh\")]\n\nimpl Mesh {\n\n pub fn cuboid<V>(\n\n usage: BufferUsage,\n\n cx: &mut Graphics,\n\n index_type: IndexType,\n\n vertex: impl Fn(genmesh::Vertex) -> V,\n\n ) -> Result<Self, OutOfMemory>\n\n where\n\n V: VertexType,\n\n {\n\n Self::from_generator(\n\n &genmesh::generators::Cube::new(),\n\n usage,\n\n cx,\n\n index_type,\n", "file_path": "engine/src/graphics/mesh.rs", "rank": 49, "score": 149691.0737829039 }, { "content": "fn default_distances() -> Arc<[f32]> {\n\n Arc::new([])\n\n}\n\n\n", "file_path": "engine/src/sprite/mod.rs", "rank": 50, "score": 149135.09146062974 }, { "content": "fn purpose(mesh: &gltf::Mesh) -> MeshPurpose {\n\n if let Some(name) = mesh.name() {\n\n match name.rfind('.') {\n\n Some(pos) => {\n\n let ext = name[pos + 1..].trim();\n\n\n\n match ext {\n\n \"draw\" => MeshPurpose {\n\n render: true,\n\n collider: None,\n\n },\n\n \"aabb\" => MeshPurpose {\n\n render: false,\n\n collider: Some(ColliderKind::Aabb),\n\n },\n\n \"convex\" => MeshPurpose {\n\n render: false,\n\n collider: Some(ColliderKind::Convex),\n\n },\n\n \"trimesh\" => MeshPurpose {\n", "file_path": "engine/src/assets/import/gltf/mesh.rs", "rank": 51, "score": 148584.00745885458 }, { "content": "fn get_missing_texture_dependencies(\n\n texture: gltf::Texture,\n\n dependencies: &mut (impl Dependencies + ?Sized),\n\n missing: &mut Vec<Dependency>,\n\n) -> Result<(), String> {\n\n match texture.source().source() {\n\n gltf::image::Source::View { .. } => unimplemented!(),\n\n gltf::image::Source::Uri { uri, .. } => {\n\n dependencies.get_or_append(uri, \"qoi\", missing)?;\n\n Ok(())\n\n }\n\n }\n\n}\n", "file_path": "engine/src/assets/import/gltf/mod.rs", "rank": 52, "score": 148328.02299867483 }, { "content": "fn align_vec(bytes: &mut Vec<u8>, align_mask: usize) {\n\n let new_size = (bytes.len() + align_mask) & !align_mask;\n\n bytes.resize(new_size, 0xfe);\n\n}\n\n\n", "file_path": "engine/src/assets/import/gltf/mod.rs", "rank": 53, "score": 147522.76013166015 }, { "content": "fn default_animations() -> Arc<[SpriteAnimation]> {\n\n Arc::new([])\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Animation {\n\n pub frames: Vec<SpriteFrame>,\n\n pub animations: Vec<SpriteAnimation>,\n\n}\n\n\n\n#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]\n\npub struct SpriteAnimation {\n\n pub name: Box<str>,\n\n pub from: usize,\n\n pub to: usize,\n\n\n\n #[serde(default, skip_serializing_if = \"serde_json::Value::is_null\")]\n\n pub features: serde_json::Value,\n\n}\n", "file_path": "engine/src/sprite/mod.rs", "rank": 54, "score": 146493.18800266756 }, { "content": "pub fn load_sampler(sampler: gltf::texture::Sampler) -> Option<SamplerInfo> {\n\n let sampler = SamplerInfo {\n\n mag_filter: match sampler.mag_filter() {\n\n None | Some(MagFilter::Nearest) => Filter::Nearest,\n\n Some(MagFilter::Linear) => Filter::Linear,\n\n },\n\n min_filter: match sampler.min_filter() {\n\n None\n\n | Some(MinFilter::Nearest)\n\n | Some(MinFilter::NearestMipmapNearest)\n\n | Some(MinFilter::NearestMipmapLinear) => Filter::Nearest,\n\n _ => Filter::Linear,\n\n },\n\n mipmap_mode: match sampler.min_filter() {\n\n None\n\n | Some(MinFilter::Nearest)\n\n | Some(MinFilter::Linear)\n\n | Some(MinFilter::NearestMipmapNearest)\n\n | Some(MinFilter::LinearMipmapNearest) => MipmapMode::Nearest,\n\n _ => MipmapMode::Linear,\n", "file_path": "engine/src/assets/import/gltf/sampler.rs", "rank": 55, "score": 142601.3837235495 }, { "content": "fn topology_is_triangles(topology: &PrimitiveTopology) -> bool {\n\n *topology == PrimitiveTopology::TriangleList\n\n}\n\n\n", "file_path": "engine/src/graphics/mesh.rs", "rank": 56, "score": 140832.67264858395 }, { "content": "/// System trait for the ECS.\n\npub trait System: 'static {\n\n /// Name of the system.\n\n /// Used for debug purposes.\n\n fn name(&self) -> &str;\n\n\n\n /// Run system with provided context.\n\n fn run(&mut self, cx: SystemContext<'_>);\n\n}\n\n\n\n/// Functions are systems.\n\nimpl<F> System for F\n\nwhere\n\n F: for<'a> FnMut(SystemContext<'a>) + 'static,\n\n{\n\n fn name(&self) -> &str {\n\n std::any::type_name::<F>()\n\n }\n\n\n\n fn run(&mut self, cx: SystemContext<'_>) {\n\n (*self)(cx);\n\n }\n\n}\n\n\n", "file_path": "engine/src/system.rs", "rank": 57, "score": 139939.3017687705 }, { "content": "/// Installs default eyre handler.\n\npub fn install_eyre_handler() {\n\n if let Err(err) = color_eyre::install() {\n\n panic!(\"Failed to install eyre report handler: {}\", err);\n\n }\n\n}\n\n\n", "file_path": "engine/src/lib.rs", "rank": 58, "score": 138887.5282494474 }, { "content": "/// Installs default tracing subscriber.\n\npub fn install_tracing_subscriber() {\n\n use tracing_subscriber::layer::SubscriberExt as _;\n\n if let Err(err) = tracing::subscriber::set_global_default(\n\n tracing_subscriber::fmt()\n\n .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())\n\n .finish()\n\n .with(tracing_error::ErrorLayer::default()),\n\n ) {\n\n panic!(\"Failed to install tracing subscriber: {}\", err);\n\n }\n\n}\n\n\n", "file_path": "engine/src/lib.rs", "rank": 59, "score": 138887.5282494474 }, { "content": "fn u32_norm(v: u32) -> f32 {\n\n const U32_NORM: f32 = 1.0 / u32::MAX as f32;\n\n v as f32 * U32_NORM\n\n}\n", "file_path": "engine/src/assets/import/gltf/primitive.rs", "rank": 60, "score": 138156.52901565464 }, { "content": "use std::{convert::TryFrom, mem::size_of_val};\n\n\n\nuse bytemuck::Pod;\n\nuse scoped_arena::Scope;\n\nuse sierra::{\n\n AccessFlags, Buffer, BufferCopy, BufferImageCopy, BufferInfo, BufferUsage, Device, Encoder,\n\n Extent3d, Format, Image, ImageMemoryBarrier, Layout, Offset3d, OutOfMemory, PipelineStageFlags,\n\n Queue, SubresourceLayers,\n\n};\n\n\n\nuse super::UploadImage;\n\n\n\nmod rgb2rgba;\n\n\n\npub struct Uploader {\n\n buffer_uploads: Vec<BufferUpload>,\n\n image_uploads: Vec<ImageUpload>,\n\n\n\n rgb2rgba: rgb2rgba::Rgb2RgbaUploader,\n\n}\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 61, "score": 132504.29786820617 }, { "content": " encoder.copy_buffer(\n\n &staging,\n\n buffer,\n\n &[BufferCopy {\n\n src_offset: 0,\n\n dst_offset: offset,\n\n size: size_of_val(data) as u64,\n\n }],\n\n );\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn upload_image<T>(\n\n &mut self,\n\n device: &Device,\n\n upload: UploadImage,\n\n data: &[T],\n\n ) -> Result<(), OutOfMemory>\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 62, "score": 132485.99815274266 }, { "content": "\n\nimpl Uploader {\n\n pub fn new(device: &Device) -> Result<Self, OutOfMemory> {\n\n Ok(Uploader {\n\n buffer_uploads: Vec::new(),\n\n image_uploads: Vec::new(),\n\n\n\n rgb2rgba: rgb2rgba::Rgb2RgbaUploader::new(device)?,\n\n })\n\n }\n\n\n\n pub fn upload_buffer<T>(\n\n &mut self,\n\n device: &Device,\n\n buffer: &Buffer,\n\n offset: u64,\n\n data: &[T],\n\n ) -> Result<(), OutOfMemory>\n\n where\n\n T: Pod,\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 63, "score": 132484.64942793216 }, { "content": " PipelineStageFlags::ALL_COMMANDS,\n\n &[ImageMemoryBarrier {\n\n image: upload.image,\n\n old_layout: Some(Layout::TransferDstOptimal),\n\n new_layout: upload.new_layout,\n\n old_access: AccessFlags::TRANSFER_WRITE,\n\n new_access: upload.new_access,\n\n family_transfer: None,\n\n range: upload.layers.into(),\n\n }],\n\n );\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn flush_uploads(\n\n &mut self,\n\n device: &Device,\n\n queue: &mut Queue,\n\n scope: &Scope<'_>,\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 64, "score": 132481.64620832074 }, { "content": " &[BufferImageCopy {\n\n buffer_offset: 0,\n\n buffer_row_length: upload.row_length,\n\n buffer_image_height: upload.image_height,\n\n image_subresource: upload.layers,\n\n image_offset: upload.offset,\n\n image_extent: upload.extent,\n\n }],\n\n ),\n\n (Format::RGB8Unorm, Format::RGBA8Unorm) => {\n\n self.rgb2rgba.upload_synchronized(\n\n device,\n\n upload.image,\n\n upload.offset,\n\n upload.extent,\n\n staging.clone(),\n\n upload.row_length,\n\n upload.image_height,\n\n encoder,\n\n )?;\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 65, "score": 132480.96571908277 }, { "content": " image_subresource: upload.layers,\n\n image_offset: upload.offset,\n\n image_extent: upload.extent,\n\n }],\n\n ),\n\n (Format::RGB8Unorm, Format::RGBA8Unorm) => {\n\n self.rgb2rgba.upload_synchronized(\n\n device,\n\n &upload.image,\n\n Offset3d::ZERO,\n\n upload.image.info().extent.into_3d(),\n\n upload.staging.clone(),\n\n upload.row_length,\n\n upload.image_height,\n\n &mut encoder,\n\n )?;\n\n }\n\n (Format::RGB8Srgb, Format::RGBA8Srgb) => {\n\n self.rgb2rgba.upload_synchronized(\n\n device,\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 66, "score": 132480.00954419796 }, { "content": " old_layout: Some(Layout::TransferDstOptimal),\n\n new_layout: upload.new_layout,\n\n old_access: AccessFlags::TRANSFER_WRITE,\n\n new_access: upload.new_access,\n\n family_transfer: None,\n\n range: upload.layers.into(),\n\n });\n\n }\n\n\n\n encoder.image_barriers(\n\n PipelineStageFlags::TRANSFER,\n\n PipelineStageFlags::ALL_COMMANDS,\n\n images.leak(),\n\n );\n\n }\n\n\n\n queue.submit(&mut [], Some(encoder.finish()), &mut [], None, scope);\n\n\n\n self.buffer_uploads.clear();\n\n self.image_uploads.clear();\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 67, "score": 132479.8385758587 }, { "content": " ) -> Result<(), OutOfMemory> {\n\n if self.buffer_uploads.is_empty() && self.image_uploads.is_empty() {\n\n return Ok(());\n\n }\n\n\n\n let mut encoder = queue.create_encoder(scope)?;\n\n\n\n if !self.buffer_uploads.is_empty() {\n\n tracing::debug!(\"Uploading buffers\");\n\n\n\n let mut old_access = AccessFlags::empty();\n\n let mut new_access = AccessFlags::empty();\n\n\n\n for upload in &self.buffer_uploads {\n\n old_access |= upload.old_access;\n\n new_access |= upload.new_access;\n\n }\n\n\n\n encoder.memory_barrier(\n\n PipelineStageFlags::ALL_COMMANDS,\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 68, "score": 132479.533234107 }, { "content": " offset: upload.offset,\n\n extent: upload.extent,\n\n layers: upload.layers,\n\n old_layout: upload.old_layout,\n\n new_layout: upload.new_layout,\n\n old_access: upload.old_access,\n\n new_access: upload.new_access,\n\n staging,\n\n format: upload.format,\n\n row_length: upload.row_length,\n\n image_height: upload.image_height,\n\n });\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn upload_image_with<'a, T>(\n\n &self,\n\n device: &Device,\n\n upload: UploadImage,\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 69, "score": 132477.96077056622 }, { "content": " }\n\n\n\n let images_len = images.len();\n\n\n\n encoder.image_barriers(\n\n PipelineStageFlags::TOP_OF_PIPE,\n\n PipelineStageFlags::TRANSFER,\n\n images.leak(),\n\n );\n\n\n\n for upload in &self.image_uploads {\n\n match (upload.format, upload.image.info().format) {\n\n (from, to) if from == to => encoder.copy_buffer_to_image(\n\n &upload.staging,\n\n &upload.image,\n\n Layout::TransferDstOptimal,\n\n &[BufferImageCopy {\n\n buffer_offset: 0,\n\n buffer_row_length: upload.row_length,\n\n buffer_image_height: upload.image_height,\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 70, "score": 132476.53306757263 }, { "content": "\n\n encoder.image_barriers(\n\n PipelineStageFlags::TOP_OF_PIPE,\n\n PipelineStageFlags::TRANSFER,\n\n &[ImageMemoryBarrier {\n\n image: upload.image,\n\n old_layout: upload.old_layout,\n\n new_layout: Layout::TransferDstOptimal,\n\n old_access: upload.old_access,\n\n new_access: AccessFlags::TRANSFER_WRITE,\n\n family_transfer: None,\n\n range: upload.layers.into(),\n\n }],\n\n );\n\n\n\n match (upload.format, upload.image.info().format) {\n\n (from, to) if from == to => encoder.copy_buffer_to_image(\n\n &staging,\n\n upload.image,\n\n Layout::TransferDstOptimal,\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 71, "score": 132475.25774110266 }, { "content": " });\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn upload_buffer_with<'a, T>(\n\n &self,\n\n device: &Device,\n\n buffer: &'a Buffer,\n\n offset: u64,\n\n data: &'a [T],\n\n encoder: &mut Encoder<'a>,\n\n ) -> Result<(), OutOfMemory>\n\n where\n\n T: Pod,\n\n {\n\n const UPDATE_LIMIT: usize = 16384;\n\n\n\n assert_eq!(\n\n size_of_val(data) & 3,\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 72, "score": 132474.73224768136 }, { "content": " }\n\n (Format::RGB8Srgb, Format::RGBA8Srgb) => {\n\n self.rgb2rgba.upload_synchronized(\n\n device,\n\n upload.image,\n\n upload.offset,\n\n upload.extent,\n\n staging.clone(),\n\n upload.row_length,\n\n upload.image_height,\n\n encoder,\n\n )?;\n\n }\n\n (from, to) => {\n\n panic!(\"Uploading from '{:?}' to '{:?}' is unimplemented\", from, to)\n\n }\n\n }\n\n\n\n encoder.image_barriers(\n\n PipelineStageFlags::TRANSFER,\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 73, "score": 132472.29746054066 }, { "content": " data: &[T],\n\n encoder: &mut Encoder<'a>,\n\n ) -> Result<(), OutOfMemory>\n\n where\n\n T: Pod,\n\n {\n\n let staging_usage = if upload.format == upload.image.info().format {\n\n BufferUsage::TRANSFER_SRC\n\n } else {\n\n BufferUsage::UNIFORM_TEXEL\n\n };\n\n\n\n let staging = device.create_buffer_static(\n\n BufferInfo {\n\n align: 15,\n\n size: u64::try_from(size_of_val(data)).map_err(|_| OutOfMemory)?,\n\n usage: staging_usage,\n\n },\n\n data,\n\n )?;\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 74, "score": 132472.26168848062 }, { "content": " PipelineStageFlags::ALL_COMMANDS,\n\n new_access,\n\n );\n\n }\n\n\n\n if !self.image_uploads.is_empty() {\n\n tracing::debug!(\"Uploading images\");\n\n\n\n let mut images = Vec::with_capacity_in(self.image_uploads.len(), scope);\n\n\n\n for upload in &self.image_uploads {\n\n images.push(ImageMemoryBarrier {\n\n image: &upload.image,\n\n old_layout: upload.old_layout,\n\n new_layout: Layout::TransferDstOptimal,\n\n old_access: upload.old_access,\n\n new_access: AccessFlags::TRANSFER_WRITE,\n\n family_transfer: None,\n\n range: upload.layers.into(),\n\n });\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 75, "score": 132471.69760925745 }, { "content": " old_access,\n\n PipelineStageFlags::TRANSFER,\n\n AccessFlags::TRANSFER_WRITE,\n\n );\n\n\n\n for upload in &self.buffer_uploads {\n\n encoder.copy_buffer(\n\n &upload.staging,\n\n &upload.buffer,\n\n &[BufferCopy {\n\n src_offset: 0,\n\n dst_offset: upload.offset,\n\n size: upload.staging.info().size,\n\n }],\n\n );\n\n }\n\n\n\n encoder.memory_barrier(\n\n PipelineStageFlags::TRANSFER,\n\n AccessFlags::TRANSFER_WRITE,\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 76, "score": 132469.3530871726 }, { "content": " {\n\n if data.is_empty() {\n\n return Ok(());\n\n }\n\n\n\n let staging = device.create_buffer_static(\n\n BufferInfo {\n\n align: 15,\n\n size: size_of_val(data) as u64,\n\n usage: BufferUsage::TRANSFER_SRC,\n\n },\n\n data,\n\n )?;\n\n\n\n self.buffer_uploads.push(BufferUpload {\n\n staging,\n\n buffer: buffer.clone(),\n\n offset,\n\n old_access: AccessFlags::all(),\n\n new_access: AccessFlags::all(),\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 77, "score": 132468.85192511702 }, { "content": " 0,\n\n \"Buffer uploading data size must be a multiple of 4\"\n\n );\n\n\n\n if data.is_empty() {\n\n return Ok(());\n\n }\n\n\n\n if size_of_val(data) <= UPDATE_LIMIT {\n\n encoder.update_buffer(buffer, offset, data);\n\n } else {\n\n let staging = device.create_buffer_static(\n\n BufferInfo {\n\n align: 15,\n\n size: size_of_val(data) as u64,\n\n usage: BufferUsage::TRANSFER_SRC,\n\n },\n\n data,\n\n )?;\n\n\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 78, "score": 132467.90783040685 }, { "content": " &upload.image,\n\n Offset3d::ZERO,\n\n upload.image.info().extent.into_3d(),\n\n upload.staging.clone(),\n\n upload.row_length,\n\n upload.image_height,\n\n &mut encoder,\n\n )?;\n\n }\n\n (from, to) => {\n\n panic!(\"Uploading from '{:?}' to '{:?}' is unimplemented\", from, to)\n\n }\n\n }\n\n }\n\n\n\n let mut images = Vec::with_capacity_in(images_len, scope);\n\n\n\n for upload in &self.image_uploads {\n\n images.push(ImageMemoryBarrier {\n\n image: &upload.image,\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 79, "score": 132467.58179003414 }, { "content": " where\n\n T: Pod,\n\n {\n\n let staging_usage = if upload.format == upload.image.info().format {\n\n BufferUsage::TRANSFER_SRC\n\n } else {\n\n BufferUsage::UNIFORM_TEXEL\n\n };\n\n\n\n let staging = device.create_buffer_static(\n\n BufferInfo {\n\n align: 15,\n\n size: u64::try_from(size_of_val(data)).map_err(|_| OutOfMemory)?,\n\n usage: staging_usage,\n\n },\n\n data,\n\n )?;\n\n\n\n self.image_uploads.push(ImageUpload {\n\n image: upload.image.clone(),\n", "file_path": "engine/src/graphics/upload/mod.rs", "rank": 80, "score": 132467.2461860475 }, { "content": "/// An input controller.\n\n/// Receives device events from `Control` hub.\n\npub trait InputController: Send + 'static {\n\n /// Translates device event into controls.\n\n fn control(&mut self, event: InputEvent, res: &mut Res, world: &mut World) -> ControlResult;\n\n}\n\n\n\n/// Collection of controllers.\n\n#[derive(Default)]\n\npub struct Control {\n\n /// Controllers bound to specific devices.\n\n devices: HashMap<DeviceId, Box<dyn InputController>>,\n\n\n\n /// Global controller that receives all events unhandled by device specific controllers.\n\n global: slab::Slab<Box<dyn InputController>>,\n\n}\n\n\n\n/// Identifier of the controller set in global slot.\n\n/// See [`Control::add_global_controller`].\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]\n\n#[repr(transparent)]\n\npub struct GlobalControllerId {\n", "file_path": "engine/src/control.rs", "rank": 81, "score": 132381.04751875479 }, { "content": "use edict::{entity::EntityId, world::World};\n\nuse scoped_arena::Scope;\n\nuse sierra::{Encoder, Extent2d, RenderPassEncoder};\n\n\n\n#[cfg(feature = \"3d\")]\n\npub mod basic;\n\n\n\n#[cfg(feature = \"2d\")]\n\npub mod sprite;\n\n\n\n#[cfg(feature = \"with-egui\")]\n\npub mod egui;\n\n\n\npub mod simple;\n\n\n\nuse crate::{assets::Assets, clocks::ClockIndex, resources::Res, viewport::Viewport};\n\n\n\nuse super::Graphics;\n\n\n\npub struct RendererContext<'a, 'b> {\n", "file_path": "engine/src/graphics/renderer/mod.rs", "rank": 82, "score": 132126.07836855255 }, { "content": " encoder: &mut Encoder<'a>,\n\n render_pass: &mut RenderPassEncoder<'_, 'b>,\n\n camera: EntityId,\n\n viewport: Extent2d,\n\n ) -> eyre::Result<()> {\n\n (&mut **self).draw(cx, encoder, render_pass, camera, viewport)\n\n }\n\n}\n\n\n\n/// Inputs for render node that simply draws objects.\n\npub struct DrawNodeInputs<'a> {\n\n pub encoder: &'a mut Encoder<'a>,\n\n pub render_pass: RenderPassEncoder<'a, 'a>,\n\n pub camera: EntityId,\n\n pub viewport: Extent2d,\n\n}\n\n\n\nimpl<'a, N> RenderNodeInputs<'a> for N\n\nwhere\n\n N: DrawNode,\n", "file_path": "engine/src/graphics/renderer/mod.rs", "rank": 83, "score": 132124.47292096552 }, { "content": "}\n\n\n\nimpl<'a> RendererContext<'_, 'a> {\n\n pub fn reborrow(&mut self) -> RendererContext<'_, 'a> {\n\n RendererContext {\n\n world: &mut *self.world,\n\n res: &mut *self.res,\n\n assets: &mut *self.assets,\n\n scope: self.scope,\n\n clock: self.clock,\n\n graphics: &mut *self.graphics,\n\n }\n\n }\n\n}\n\n\n\n/// Abstract rendering system.\n", "file_path": "engine/src/graphics/renderer/mod.rs", "rank": 84, "score": 132117.93103578867 }, { "content": "{\n\n type Inputs = DrawNodeInputs<'a>;\n\n}\n\n\n\nimpl<N> RenderNode for N\n\nwhere\n\n N: DrawNode,\n\n{\n\n type Outputs = ();\n\n\n\n fn render<'a>(\n\n &'a mut self,\n\n cx: RendererContext<'a, 'a>,\n\n\n\n mut inputs: DrawNodeInputs<'a>,\n\n ) -> eyre::Result<()> {\n\n self.draw(\n\n cx,\n\n inputs.encoder,\n\n &mut inputs.render_pass,\n\n inputs.camera,\n\n inputs.viewport,\n\n )\n\n }\n\n}\n\n\n", "file_path": "engine/src/graphics/renderer/mod.rs", "rank": 85, "score": 132117.7102375893 }, { "content": " /// World on which systems are run.\n\n pub world: &'a mut World,\n\n\n\n /// Resources map.\n\n /// All singleton values are stored here and accessible by type.\n\n pub res: &'a mut Res,\n\n\n\n /// Asset loader.\n\n /// Assets are loaded asynchronously,\n\n /// result can be awaited in task. See `spawner` field.\n\n pub assets: &'a mut Assets,\n\n\n\n /// Arena allocator for allocations in hot-path.\n\n pub scope: &'b Scope<'b>,\n\n\n\n /// Clock index.\n\n pub clock: ClockIndex,\n\n\n\n /// Graphics context.\n\n pub graphics: &'a mut Graphics,\n", "file_path": "engine/src/graphics/renderer/mod.rs", "rank": 86, "score": 132109.4063069001 }, { "content": "#[cfg(all(feature = \"visible\", feature = \"graphics\", feature = \"2d\"))]\n\npub fn game2<F, Fut>(f: F) -> !\n\nwhere\n\n F: FnOnce(Game) -> Fut + 'static,\n\n Fut: Future<Output = eyre::Result<Game>>,\n\n{\n\n tracing::debug!(\"Starting 2D game\");\n\n game::<_, _, _, (Camera2, Global2)>(f, |g| {\n\n Ok(Box::new(SimpleRenderer::new(SpriteDraw::new(0.0..1.0, g)?)))\n\n })\n\n}\n\n\n", "file_path": "engine/src/game.rs", "rank": 87, "score": 123514.54982780761 }, { "content": "#[cfg(all(feature = \"visible\", feature = \"graphics\", feature = \"3d\"))]\n\npub fn game3<F, Fut>(f: F) -> !\n\nwhere\n\n F: FnOnce(Game) -> Fut + 'static,\n\n Fut: Future<Output = eyre::Result<Game>>,\n\n{\n\n tracing::debug!(\"Starting 3D game\");\n\n game::<_, _, _, (Camera3, Global3)>(f, |g| {\n\n Ok(Box::new(SimpleRenderer::new(BasicDraw::new(g)?)))\n\n })\n\n}\n\n\n", "file_path": "engine/src/game.rs", "rank": 88, "score": 123514.54982780761 }, { "content": "#[cfg(not(feature = \"visible\"))]\n\npub fn headless<F, Fut>(f: F)\n\nwhere\n\n F: FnOnce(Game) -> Fut + 'static,\n\n Fut: Future<Output = eyre::Result<Game>>,\n\n{\n\n crate::install_eyre_handler();\n\n crate::install_tracing_subscriber();\n\n\n\n let runtime = tokio::runtime::Builder::new_current_thread()\n\n .enable_all()\n\n .build()\n\n .expect(\"Failed to build tokio runtime\");\n\n\n\n // Load config.\n\n let cfg = Config::load_default();\n\n\n\n let teardown_timeout = cfg.teardown_timeout;\n\n let main_step = cfg.main_step;\n\n\n\n // Create new world with camera.\n", "file_path": "engine/src/game.rs", "rank": 89, "score": 123509.66275227911 }, { "content": "#[cfg(feature = \"visible\")]\n\npub fn headless<F, Fut>(_f: F)\n\nwhere\n\n F: FnOnce(Game) -> Fut + 'static,\n\n Fut: Future<Output = eyre::Result<Game>>,\n\n{\n\n panic!(\"This function must be used only with \\\"visible\\\" feature disabled\")\n\n}\n\n\n", "file_path": "engine/src/game.rs", "rank": 90, "score": 123509.66275227911 }, { "content": "#[derive(Clone, Copy)]\n\nstruct MeshPurpose {\n\n render: bool,\n\n collider: Option<ColliderKind>,\n\n}\n\n\n", "file_path": "engine/src/assets/import/gltf/mesh.rs", "rank": 91, "score": 123331.85565116035 }, { "content": "#[proc_macro_derive(Unfold, attributes(unfold))]\n\npub fn unfold(item: TokenStream) -> TokenStream {\n\n match unfold::derive_unfold(item) {\n\n Ok(tokens) => tokens,\n\n Err(err) => err.into_compile_error().into(),\n\n }\n\n}\n", "file_path": "proc/src/lib.rs", "rank": 92, "score": 122753.0321882207 }, { "content": "pub fn timespan(item: TokenStream) -> TokenStream {\n\n match item.to_string().parse::<TimeSpan>() {\n\n Ok(span) => format!(\"arcana::TimeSpan::from_nanos({})\", span.as_nanos()),\n\n Err(err) => format!(\"compile_error!(\\\"{}\\\")\", err),\n\n }\n\n .parse()\n\n .unwrap()\n\n}\n", "file_path": "proc/src/time.rs", "rank": 93, "score": 122753.0321882207 }, { "content": "#[proc_macro]\n\npub fn timespan(item: TokenStream) -> TokenStream {\n\n time::timespan(item)\n\n}\n\n\n", "file_path": "proc/src/lib.rs", "rank": 94, "score": 122753.0321882207 }, { "content": "#[cfg(feature = \"visible\")]\n\nstruct MainWindowFunnel;\n\n\n\n#[cfg(feature = \"visible\")]\n\nimpl Funnel<Event> for MainWindowFunnel {\n\n fn filter(&mut self, res: &mut Res, _world: &mut World, event: Event) -> Option<Event> {\n\n match event {\n\n Event::WindowEvent {\n\n event: WindowEvent::CloseRequested,\n\n window_id,\n\n } => {\n\n if let Some(window) = res.get::<MainWindow>() {\n\n if window_id == window.id() {\n\n res.insert(Exit);\n\n res.remove::<MainWindow>();\n\n }\n\n }\n\n Some(event)\n\n }\n\n Event::Loop => {\n\n if let Some(window) = res.get::<MainWindow>() {\n", "file_path": "engine/src/game.rs", "rank": 95, "score": 117159.11613487062 }, { "content": "struct RaysRenderer {\n\n blases: HashMap<graphics::Mesh, graphics::AccelerationStructure>,\n\n}\n\n\n\nimpl graphics::Renderer for RaysRenderer {\n\n fn new(graphics: &mut graphics::Graphics) -> eyre::Result<Self>\n\n where\n\n Self: Sized,\n\n {\n\n Ok(RaysRenderer {\n\n blases: HashMap::new(),\n\n })\n\n }\n\n\n\n fn render(\n\n &mut self,\n\n cx: graphics::RendererContext<'_>,\n\n viewports: &mut [&mut Viewport],\n\n ) -> eyre::Result<()> {\n\n let mut encoder = cx.graphics.create_encoder(&*cx.scope)?;\n", "file_path": "examples/rays/src/main.rs", "rank": 96, "score": 116619.52115637869 }, { "content": "/// Returns borrowed `TaskContext`.\n\n/// Only usable when called in futures spawned with [`Spawner`].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if called outside future spawner with [`Spawner`].\n\n///\n\n/// # Safety\n\n///\n\n/// ???\n\n///\n\n/// ```compile_fail\n\n/// # fn func<'a>(cx: TaskContext<'a>) {\n\n/// let cx: TaskContext<'_> = cx;\n\n/// std::thread::new(move || { cx; })\n\n/// # }\n\n/// ```\n\n///\n\n/// ```compile_fail\n\n/// # fn func<'a>(cx: TaskContext<'a>) {\n\n/// let cx: &TaskContext<'_> = &cx;\n\n/// std::thread::new(move || { cx; })\n\n/// # }\n\n/// ```\n\npub fn with_async_task_context<F, R>(f: F) -> R\n\nwhere\n\n F: for<'a> FnOnce(TaskContext<'a>) -> R,\n\n{\n\n TASK_CONTEXT.with(|cell| unsafe {\n\n let tcx = (&mut *cell.get())\n\n .as_mut()\n\n .expect(\"Called outside task executor\");\n\n\n\n f(TaskContext::from_raw(tcx))\n\n })\n\n}\n\n\n\n/// Task spawner.\n\npub struct Spawner {\n\n local_set: Option<LocalSet>,\n\n}\n\n\n\nimpl Spawner {\n\n pub(crate) fn new() -> Self {\n", "file_path": "engine/src/task.rs", "rank": 97, "score": 116077.87069256544 }, { "content": "pub trait EntityDisplay {\n\n fn display<'a>(&self, info: &'a DebugInfo) -> EntityDebugInfo<'a>;\n\n}\n\n\n\nimpl EntityDisplay for EntityId {\n\n fn display<'a>(&self, info: &'a DebugInfo) -> EntityDebugInfo<'a> {\n\n info.for_entity(*self)\n\n }\n\n}\n", "file_path": "engine/src/debug.rs", "rank": 98, "score": 115394.34120010896 }, { "content": "pub trait WorldExt {\n\n fn entity_display(&self, entity: EntityId) -> Option<EntityRefDebugInfo<'_>>;\n\n}\n\n\n\nimpl WorldExt for World {\n\n fn entity_display(&self, entity: EntityId) -> Option<EntityRefDebugInfo<'_>> {\n\n EntityRefDebugInfo::fetch(entity, self)\n\n }\n\n}\n\n\n", "file_path": "engine/src/debug.rs", "rank": 99, "score": 115394.34120010896 } ]
Rust
15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu.rs
TomaszWaszczyk/rust-raspberrypi-OS-tutorials
b1c438dc6693431885e597890daeb5536a991e0b
use crate::{ bsp, memory, memory::{mmu::TranslationGranule, Address, Physical, Virtual}, }; use core::intrinsics::unlikely; use cortex_a::{asm::barrier, registers::*}; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; struct MemoryManagementUnit; pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; #[allow(dead_code)] pub mod mair { pub const DEVICE: u64 = 0; pub const NORMAL: u64 = 1; } static MMU: MemoryManagementUnit = MemoryManagementUnit; impl<const AS_SIZE: usize> memory::mmu::AddressSpace<AS_SIZE> { pub const fn arch_address_space_size_sanity_checks() { assert!((AS_SIZE % Granule512MiB::SIZE) == 0); assert!(AS_SIZE <= (1 << 48)); } } impl MemoryManagementUnit { fn set_up_mair(&self) { MAIR_EL1.write( MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, ); } fn configure_translation_control(&self) { let t0sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; TCR_EL1.write( TCR_EL1::TBI0::Used + TCR_EL1::IPS::Bits_40 + TCR_EL1::TG0::KiB_64 + TCR_EL1::SH0::Inner + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::EPD0::EnableTTBR0Walks + TCR_EL1::A1::TTBR0 + TCR_EL1::T0SZ.val(t0sz) + TCR_EL1::EPD1::DisableTTBR1Walks, ); } } pub fn mmu() -> &'static impl memory::mmu::interface::MMU { &MMU } use memory::mmu::{MMUEnableError, TranslationError}; impl memory::mmu::interface::MMU for MemoryManagementUnit { unsafe fn enable_mmu_and_caching( &self, phys_tables_base_addr: Address<Physical>, ) -> Result<(), MMUEnableError> { if unlikely(self.is_enabled()) { return Err(MMUEnableError::AlreadyEnabled); } if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { return Err(MMUEnableError::Other( "Translation granule not supported in HW", )); } self.set_up_mair(); TTBR0_EL1.set_baddr(phys_tables_base_addr.into_usize() as u64); self.configure_translation_control(); barrier::isb(barrier::SY); SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); barrier::isb(barrier::SY); Ok(()) } #[inline(always)] fn is_enabled(&self) -> bool { SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) } fn try_virt_to_phys( &self, virt: Address<Virtual>, ) -> Result<Address<Physical>, TranslationError> { if !self.is_enabled() { return Err(TranslationError::MMUDisabled); } let addr = virt.into_usize() as u64; unsafe { asm!( "AT S1E1R, {0}", in(reg) addr, options(readonly, nostack, preserves_flags) ); } let par_el1 = PAR_EL1.extract(); if par_el1.matches_all(PAR_EL1::F::TranslationAborted) { return Err(TranslationError::Aborted); } let phys_addr = (par_el1.read(PAR_EL1::PA) << 12) | (addr & 0xFFF); Ok(Address::new(phys_addr as usize)) } }
use crate::{ bsp, memory, memory::{mmu::TranslationGranule, Address, Physical, Virtual}, }; use core::intrinsics::unlikely; use cortex_a::{asm::barrier, registers::*}; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; struct MemoryManagementUnit; pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; #[allow(dead_code)] pub mod mair { pub const DEVICE: u64 = 0; pub const NORMAL: u64 = 1; } static MMU: MemoryManagementUnit = MemoryManagementUnit; impl<const AS_SIZE: usize> memory::mmu::AddressSpace<AS_SIZE> { pub const fn arch_address_space_size_sanity_checks() { assert!((AS_SIZE % Granule512MiB::SIZE) == 0); assert!(AS_SIZE <= (1 << 48)); } } impl MemoryManagementUnit {
fn configure_translation_control(&self) { let t0sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; TCR_EL1.write( TCR_EL1::TBI0::Used + TCR_EL1::IPS::Bits_40 + TCR_EL1::TG0::KiB_64 + TCR_EL1::SH0::Inner + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::EPD0::EnableTTBR0Walks + TCR_EL1::A1::TTBR0 + TCR_EL1::T0SZ.val(t0sz) + TCR_EL1::EPD1::DisableTTBR1Walks, ); } } pub fn mmu() -> &'static impl memory::mmu::interface::MMU { &MMU } use memory::mmu::{MMUEnableError, TranslationError}; impl memory::mmu::interface::MMU for MemoryManagementUnit { unsafe fn enable_mmu_and_caching( &self, phys_tables_base_addr: Address<Physical>, ) -> Result<(), MMUEnableError> { if unlikely(self.is_enabled()) { return Err(MMUEnableError::AlreadyEnabled); } if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { return Err(MMUEnableError::Other( "Translation granule not supported in HW", )); } self.set_up_mair(); TTBR0_EL1.set_baddr(phys_tables_base_addr.into_usize() as u64); self.configure_translation_control(); barrier::isb(barrier::SY); SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); barrier::isb(barrier::SY); Ok(()) } #[inline(always)] fn is_enabled(&self) -> bool { SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) } fn try_virt_to_phys( &self, virt: Address<Virtual>, ) -> Result<Address<Physical>, TranslationError> { if !self.is_enabled() { return Err(TranslationError::MMUDisabled); } let addr = virt.into_usize() as u64; unsafe { asm!( "AT S1E1R, {0}", in(reg) addr, options(readonly, nostack, preserves_flags) ); } let par_el1 = PAR_EL1.extract(); if par_el1.matches_all(PAR_EL1::F::TranslationAborted) { return Err(TranslationError::Aborted); } let phys_addr = (par_el1.read(PAR_EL1::PA) << 12) | (addr & 0xFFF); Ok(Address::new(phys_addr as usize)) } }
fn set_up_mair(&self) { MAIR_EL1.write( MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, ); }
function_block-full_function
[ { "content": "/// Return a reference to the MMU instance.\n\npub fn mmu() -> &'static impl memory::mmu::interface::MMU {\n\n &MMU\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse memory::mmu::MMUEnableError;\n\n\n\nimpl memory::mmu::interface::MMU for MemoryManagementUnit {\n\n unsafe fn enable_mmu_and_caching(\n\n &self,\n\n phys_tables_base_addr: Address<Physical>,\n\n ) -> Result<(), MMUEnableError> {\n\n if unlikely(self.is_enabled()) {\n\n return Err(MMUEnableError::AlreadyEnabled);\n\n }\n\n\n\n // Fail early if translation granule is not supported.\n\n if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) {\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu.rs", "rank": 1, "score": 478839.1362249274 }, { "content": "/// Return a reference to the MMU instance.\n\npub fn mmu() -> &'static impl memory::mmu::interface::MMU {\n\n &MMU\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse memory::mmu::MMUEnableError;\n\n\n\nimpl memory::mmu::interface::MMU for MemoryManagementUnit {\n\n unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError> {\n\n if unlikely(self.is_enabled()) {\n\n return Err(MMUEnableError::AlreadyEnabled);\n\n }\n\n\n\n // Fail early if translation granule is not supported.\n\n if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) {\n\n return Err(MMUEnableError::Other(\n\n \"Translation granule not supported in HW\",\n\n ));\n", "file_path": "10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu.rs", "rank": 2, "score": 478839.1362249274 }, { "content": "/// Return a reference to the MMU instance.\n\npub fn mmu() -> &'static impl memory::mmu::interface::MMU {\n\n &MMU\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse memory::mmu::{MMUEnableError, TranslationError};\n\n\n\nimpl memory::mmu::interface::MMU for MemoryManagementUnit {\n\n unsafe fn enable_mmu_and_caching(\n\n &self,\n\n phys_tables_base_addr: Address<Physical>,\n\n ) -> Result<(), MMUEnableError> {\n\n if unlikely(self.is_enabled()) {\n\n return Err(MMUEnableError::AlreadyEnabled);\n\n }\n\n\n\n // Fail early if translation granule is not supported.\n\n if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) {\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/memory/mmu.rs", "rank": 3, "score": 474764.55193805957 }, { "content": "/// Return a reference to the MMU instance.\n\npub fn mmu() -> &'static impl memory::mmu::interface::MMU {\n\n &MMU\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse memory::mmu::MMUEnableError;\n\n\n\nimpl memory::mmu::interface::MMU for MemoryManagementUnit {\n\n unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError> {\n\n if unlikely(self.is_enabled()) {\n\n return Err(MMUEnableError::AlreadyEnabled);\n\n }\n\n\n\n // Fail early if translation granule is not supported.\n\n if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) {\n\n return Err(MMUEnableError::Other(\n\n \"Translation granule not supported in HW\",\n\n ));\n", "file_path": "12_integrated_testing/src/_arch/aarch64/memory/mmu.rs", "rank": 4, "score": 450046.1335731865 }, { "content": "/// Return a reference to the MMU instance.\n\npub fn mmu() -> &'static impl memory::mmu::interface::MMU {\n\n &MMU\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse memory::mmu::MMUEnableError;\n\n\n\nimpl memory::mmu::interface::MMU for MemoryManagementUnit {\n\n unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError> {\n\n if unlikely(self.is_enabled()) {\n\n return Err(MMUEnableError::AlreadyEnabled);\n\n }\n\n\n\n // Fail early if translation granule is not supported.\n\n if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) {\n\n return Err(MMUEnableError::Other(\n\n \"Translation granule not supported in HW\",\n\n ));\n", "file_path": "11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu.rs", "rank": 5, "score": 446271.118162787 }, { "content": "/// Return a reference to the MMU instance.\n\npub fn mmu() -> &'static impl memory::mmu::interface::MMU {\n\n &MMU\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse memory::mmu::MMUEnableError;\n\n\n\nimpl memory::mmu::interface::MMU for MemoryManagementUnit {\n\n unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError> {\n\n if unlikely(self.is_enabled()) {\n\n return Err(MMUEnableError::AlreadyEnabled);\n\n }\n\n\n\n // Fail early if translation granule is not supported.\n\n if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) {\n\n return Err(MMUEnableError::Other(\n\n \"Translation granule not supported in HW\",\n\n ));\n", "file_path": "13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu.rs", "rank": 6, "score": 439024.37647160457 }, { "content": "/// Pointer to the last page of the physical address space.\n\npub fn phys_addr_space_end_page() -> *const Page<Physical> {\n\n common::align_down(\n\n super::phys_addr_space_end().into_usize(),\n\n KernelGranule::SIZE,\n\n ) as *const Page<_>\n\n}\n\n\n\n/// Map the kernel binary.\n\n///\n\n/// # Safety\n\n///\n\n/// - Any miscalculation or attribute error will likely be fatal. Needs careful manual checking.\n\npub unsafe fn kernel_map_binary() -> Result<(), &'static str> {\n\n generic_mmu::kernel_map_pages_at(\n\n \"Kernel code and RO data\",\n\n &virt_rx_page_desc(),\n\n &phys_rx_page_desc(),\n\n &AttributeFields {\n\n mem_attributes: MemAttributes::CacheableDRAM,\n\n acc_perms: AccessPermissions::ReadOnly,\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory/mmu.rs", "rank": 7, "score": 424217.60164399 }, { "content": "/// Pointer to the last page of the physical address space.\n\npub fn phys_addr_space_end_page() -> *const Page<Physical> {\n\n common::align_down(\n\n super::phys_addr_space_end().into_usize(),\n\n KernelGranule::SIZE,\n\n ) as *const Page<_>\n\n}\n\n\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory/mmu.rs", "rank": 8, "score": 424217.60164399 }, { "content": "/// Try to translate a virtual address to a physical address.\n\n///\n\n/// Will only succeed if there exists a valid mapping for the input VA.\n\npub fn try_virt_to_phys(virt: Address<Virtual>) -> Result<Address<Physical>, TranslationError> {\n\n arch_mmu::mmu().try_virt_to_phys(virt)\n\n}\n\n\n\n/// Enable the MMU and data + instruction caching.\n\n///\n\n/// # Safety\n\n///\n\n/// - Crucial function during kernel init. Changes the the complete memory view of the processor.\n\n#[inline(always)]\n\npub unsafe fn enable_mmu_and_caching(\n\n phys_tables_base_addr: Address<Physical>,\n\n) -> Result<(), MMUEnableError> {\n\n arch_mmu::mmu().enable_mmu_and_caching(phys_tables_base_addr)\n\n}\n\n\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/memory/mmu.rs", "rank": 9, "score": 422188.0880304982 }, { "content": "/// Pointer to the last page of the physical address space.\n\npub fn phys_addr_space_end_page() -> *const Page<Physical> {\n\n common::align_down(\n\n super::phys_addr_space_end().into_usize(),\n\n KernelGranule::SIZE,\n\n ) as *const Page<_>\n\n}\n\n\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory/mmu.rs", "rank": 10, "score": 419322.73549062305 }, { "content": "/// Try to translate a virtual address to a physical address.\n\n///\n\n/// Will only succeed if there exists a valid mapping for the input VA.\n\npub fn try_virt_to_phys(virt: Address<Virtual>) -> Result<Address<Physical>, TranslationError> {\n\n arch_mmu::mmu().try_virt_to_phys(virt)\n\n}\n\n\n\n/// Enable the MMU and data + instruction caching.\n\n///\n\n/// # Safety\n\n///\n\n/// - Crucial function during kernel init. Changes the the complete memory view of the processor.\n\n#[inline(always)]\n\npub unsafe fn enable_mmu_and_caching(\n\n phys_tables_base_addr: Address<Physical>,\n\n) -> Result<(), MMUEnableError> {\n\n arch_mmu::mmu().enable_mmu_and_caching(phys_tables_base_addr)\n\n}\n\n\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/memory/mmu.rs", "rank": 11, "score": 418166.9204972542 }, { "content": "#[inline(always)]\n\npub fn board_default_load_addr() -> *const u64 {\n\n map::BOARD_DEFAULT_LOAD_ADDRESS as _\n\n}\n", "file_path": "06_uart_chainloader/src/bsp/raspberrypi/memory.rs", "rank": 12, "score": 408413.6003100879 }, { "content": "/// Return a reference to the virtual memory layout.\n\npub fn virt_mem_layout() -> &'static KernelVirtualLayout<NUM_MEM_RANGES> {\n\n &LAYOUT\n\n}\n\n\n\n//--------------------------------------------------------------------------------------------------\n\n// Testing\n\n//--------------------------------------------------------------------------------------------------\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use test_macros::kernel_test;\n\n\n\n /// Check alignment of the kernel's virtual memory layout sections.\n\n #[kernel_test]\n\n fn virt_mem_layout_sections_are_64KiB_aligned() {\n\n const SIXTYFOUR_KIB: usize = 65536;\n\n\n\n for i in LAYOUT.inner().iter() {\n\n let start: usize = *(i.virtual_range)().start();\n", "file_path": "12_integrated_testing/src/bsp/raspberrypi/memory/mmu.rs", "rank": 13, "score": 385432.7320691212 }, { "content": "/// Return a reference to the virtual memory layout.\n\npub fn virt_mem_layout() -> &'static KernelVirtualLayout<NUM_MEM_RANGES> {\n\n &LAYOUT\n\n}\n", "file_path": "10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs", "rank": 14, "score": 384896.5463167133 }, { "content": "/// Return a reference to the virtual memory layout.\n\npub fn virt_mem_layout() -> &'static KernelVirtualLayout<NUM_MEM_RANGES> {\n\n &LAYOUT\n\n}\n", "file_path": "11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs", "rank": 15, "score": 381037.854990663 }, { "content": "/// Return a reference to the console.\n\npub fn console() -> &'static impl console::interface::All {\n\n &super::PL011_UART\n\n}\n\n\n\n//--------------------------------------------------------------------------------------------------\n\n// Testing\n\n//--------------------------------------------------------------------------------------------------\n\n\n\n/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps\n\n/// than on real hardware due to QEMU's abstractions.\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/console.rs", "rank": 16, "score": 373006.4628603361 }, { "content": "/// Return a reference to the console.\n\npub fn console() -> &'static impl console::interface::All {\n\n &super::PL011_UART\n\n}\n\n\n\n//--------------------------------------------------------------------------------------------------\n\n// Testing\n\n//--------------------------------------------------------------------------------------------------\n\n\n\n/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps\n\n/// than on real hardware due to QEMU's abstractions.\n\n///\n\n/// For the RPi, nothing needs to be done.\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/console.rs", "rank": 17, "score": 373006.4628603361 }, { "content": "/// Return a reference to the console.\n\npub fn console() -> &'static impl console::interface::All {\n\n &super::PL011_UART\n\n}\n", "file_path": "10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/console.rs", "rank": 18, "score": 373006.4628603362 }, { "content": "/// Return a reference to the virtual memory layout.\n\npub fn virt_mem_layout() -> &'static KernelVirtualLayout<NUM_MEM_RANGES> {\n\n &LAYOUT\n\n}\n\n\n\n//--------------------------------------------------------------------------------------------------\n\n// Testing\n\n//--------------------------------------------------------------------------------------------------\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use test_macros::kernel_test;\n\n\n\n /// Check alignment of the kernel's virtual memory layout sections.\n\n #[kernel_test]\n\n fn virt_mem_layout_sections_are_64KiB_aligned() {\n\n const SIXTYFOUR_KIB: usize = 65536;\n\n\n\n for i in LAYOUT.inner().iter() {\n\n let start: usize = *(i.virtual_range)().start();\n", "file_path": "13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory/mmu.rs", "rank": 19, "score": 372630.3575713262 }, { "content": "/// Return a reference to the kernel's translation tables.\n\npub fn kernel_translation_tables() -> &'static InitStateLock<KernelTranslationTable> {\n\n &KERNEL_TABLES\n\n}\n\n\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory/mmu.rs", "rank": 20, "score": 372618.83400811884 }, { "content": "/// Return a reference to the kernel's translation tables.\n\npub fn kernel_translation_tables() -> &'static InitStateLock<KernelTranslationTable> {\n\n &KERNEL_TABLES\n\n}\n\n\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory/mmu.rs", "rank": 21, "score": 372618.83400811884 }, { "content": "/// Return a reference to the console.\n\npub fn console() -> &'static impl console::interface::All {\n\n &super::PL011_UART\n\n}\n\n\n\n//--------------------------------------------------------------------------------------------------\n\n// Testing\n\n//--------------------------------------------------------------------------------------------------\n\n\n\n/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps\n\n/// than on real hardware due to QEMU's abstractions.\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/console.rs", "rank": 22, "score": 368866.56934529287 }, { "content": "/// Return a reference to the kernel's translation tables.\n\npub fn kernel_translation_tables() -> &'static InitStateLock<KernelTranslationTable> {\n\n &KERNEL_TABLES\n\n}\n\n\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory/mmu.rs", "rank": 23, "score": 368595.2894118896 }, { "content": "/// Return a reference to the driver manager.\n\npub fn driver_manager() -> &'static impl driver::interface::DriverManager {\n\n &BSP_DRIVER_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse driver::interface::DeviceDriver;\n\n\n\nimpl driver::interface::DriverManager for BSPDriverManager {\n\n fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[..]\n\n }\n\n\n\n fn post_device_driver_init(&self) {\n\n // Configure PL011Uart's output pins.\n\n super::GPIO.map_pl011_uart();\n\n }\n\n}\n", "file_path": "10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/driver.rs", "rank": 24, "score": 360963.232550052 }, { "content": "/// Return a reference to the driver manager.\n\npub fn driver_manager() -> &'static impl driver::interface::DriverManager {\n\n &BSP_DRIVER_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse driver::interface::DeviceDriver;\n\n\n\nimpl driver::interface::DriverManager for BSPDriverManager {\n\n fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[..]\n\n }\n\n\n\n fn early_print_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[0..=1]\n\n }\n\n\n\n fn non_early_print_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[2..]\n\n }\n\n\n\n fn post_early_print_device_driver_init(&self) {\n\n // Configure PL011Uart's output pins.\n\n super::GPIO.map_pl011_uart();\n\n }\n\n}\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/driver.rs", "rank": 25, "score": 360963.232550052 }, { "content": "/// Return a reference to the driver manager.\n\npub fn driver_manager() -> &'static impl driver::interface::DriverManager {\n\n &BSP_DRIVER_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse driver::interface::DeviceDriver;\n\n\n\nimpl driver::interface::DriverManager for BSPDriverManager {\n\n fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[..]\n\n }\n\n\n\n fn early_print_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[0..=1]\n\n }\n\n\n\n fn non_early_print_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[2..]\n\n }\n\n\n\n fn post_early_print_device_driver_init(&self) {\n\n // Configure PL011Uart's output pins.\n\n super::GPIO.map_pl011_uart();\n\n }\n\n}\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/driver.rs", "rank": 26, "score": 360963.232550052 }, { "content": "/// Return a reference to the driver manager.\n\npub fn driver_manager() -> &'static impl driver::interface::DriverManager {\n\n &BSP_DRIVER_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse driver::interface::DeviceDriver;\n\n\n\nimpl driver::interface::DriverManager for BSPDriverManager {\n\n fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[..]\n\n }\n\n\n\n fn early_print_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[0..=1]\n\n }\n\n\n\n fn non_early_print_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[2..]\n\n }\n\n\n\n fn post_early_print_device_driver_init(&self) {\n\n // Configure PL011Uart's output pins.\n\n super::GPIO.map_pl011_uart();\n\n }\n\n}\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/driver.rs", "rank": 27, "score": 357188.5491175953 }, { "content": "/// Return a reference to the IRQ manager.\n\npub fn irq_manager() -> &'static impl exception::asynchronous::interface::IRQManager<\n\n IRQNumberType = bsp::device_driver::IRQNumber,\n\n> {\n\n &super::super::INTERRUPT_CONTROLLER\n\n}\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/exception/asynchronous.rs", "rank": 28, "score": 347512.9642209854 }, { "content": "/// Return a reference to the IRQ manager.\n\npub fn irq_manager() -> &'static impl exception::asynchronous::interface::IRQManager<\n\n IRQNumberType = bsp::device_driver::IRQNumber,\n\n> {\n\n &super::super::INTERRUPT_CONTROLLER\n\n}\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/exception/asynchronous.rs", "rank": 29, "score": 347512.9642209854 }, { "content": "/// Return a reference to the console.\n\npub fn console() -> &'static impl console::interface::All {\n\n &super::PL011_UART\n\n}\n", "file_path": "07_timestamps/src/bsp/raspberrypi/console.rs", "rank": 30, "score": 346429.89560325386 }, { "content": "/// Return a reference to the IRQ manager.\n\npub fn irq_manager() -> &'static impl exception::asynchronous::interface::IRQManager<\n\n IRQNumberType = bsp::device_driver::IRQNumber,\n\n> {\n\n &super::super::INTERRUPT_CONTROLLER\n\n}\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/exception/asynchronous.rs", "rank": 31, "score": 343955.54678088444 }, { "content": "/// Return a reference to the console.\n\npub fn console() -> &'static impl console::interface::All {\n\n &QEMU_OUTPUT\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse synchronization::interface::Mutex;\n\n\n\n/// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to\n\n/// serialize access.\n\nimpl console::interface::Write for QEMUOutput {\n\n fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result {\n\n // Fully qualified syntax for the call to `core::fmt::Write::write:fmt()` to increase\n\n // readability.\n\n self.inner.lock(|inner| fmt::Write::write_fmt(inner, args))\n\n }\n\n}\n\n\n\nimpl console::interface::Statistics for QEMUOutput {\n\n fn chars_written(&self) -> usize {\n\n self.inner.lock(|inner| inner.chars_written)\n\n }\n\n}\n", "file_path": "04_safe_globals/src/bsp/raspberrypi/console.rs", "rank": 32, "score": 342456.99895609065 }, { "content": "/// Return a reference to the console.\n\npub fn console() -> &'static impl console::interface::All {\n\n &super::PL011_UART\n\n}\n", "file_path": "06_uart_chainloader/src/bsp/raspberrypi/console.rs", "rank": 33, "score": 342456.99895609065 }, { "content": "/// Return a reference to the console.\n\npub fn console() -> &'static impl console::interface::All {\n\n &super::PL011_UART\n\n}\n\n\n\n//--------------------------------------------------------------------------------------------------\n\n// Testing\n\n//--------------------------------------------------------------------------------------------------\n\n\n\n/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps\n\n/// than on real hardware due to QEMU's abstractions.\n\n///\n\n/// For the RPi, nothing needs to be done.\n", "file_path": "12_integrated_testing/src/bsp/raspberrypi/console.rs", "rank": 34, "score": 342456.99895609065 }, { "content": "/// Return a reference to the console.\n\npub fn console() -> &'static impl console::interface::All {\n\n &super::PL011_UART\n\n}\n", "file_path": "09_privilege_level/src/bsp/raspberrypi/console.rs", "rank": 35, "score": 342456.99895609065 }, { "content": "#[inline(always)]\n\nfn virt_rx_start() -> Address<Virtual> {\n\n Address::new(unsafe { __rx_start.get() as usize })\n\n}\n\n\n\n/// Size of the Read+Execute (RX) range.\n\n///\n\n/// # Safety\n\n///\n\n/// - Value is provided by the linker script and must be trusted as-is.\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory.rs", "rank": 36, "score": 341781.61986652215 }, { "content": "#[inline(always)]\n\nfn virt_rw_start() -> Address<Virtual> {\n\n Address::new(unsafe { __rw_start.get() as usize })\n\n}\n\n\n\n/// Size of the Read+Write (RW) range.\n\n///\n\n/// # Safety\n\n///\n\n/// - Value is provided by the linker script and must be trusted as-is.\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory.rs", "rank": 37, "score": 341781.61986652215 }, { "content": "#[inline(always)]\n\nfn virt_rx_start() -> Address<Virtual> {\n\n Address::new(unsafe { __rx_start.get() as usize })\n\n}\n\n\n\n/// Size of the Read+Execute (RX) range.\n\n///\n\n/// # Safety\n\n///\n\n/// - Value is provided by the linker script and must be trusted as-is.\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory.rs", "rank": 38, "score": 341781.61986652215 }, { "content": "#[inline(always)]\n\nfn virt_rw_start() -> Address<Virtual> {\n\n Address::new(unsafe { __rw_start.get() as usize })\n\n}\n\n\n\n/// Size of the Read+Write (RW) range.\n\n///\n\n/// # Safety\n\n///\n\n/// - Value is provided by the linker script and must be trusted as-is.\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory.rs", "rank": 39, "score": 341781.61986652215 }, { "content": "/// Return a reference to the console.\n\npub fn console() -> &'static impl console::interface::All {\n\n &super::PL011_UART\n\n}\n", "file_path": "08_hw_debug_JTAG/src/bsp/raspberrypi/console.rs", "rank": 40, "score": 338614.39727038494 }, { "content": "/// Return a reference to the console.\n\npub fn console() -> &'static impl console::interface::All {\n\n &super::PL011_UART\n\n}\n", "file_path": "05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs", "rank": 41, "score": 338614.39727038494 }, { "content": "/// Return a reference to the console.\n\npub fn console() -> &'static impl console::interface::All {\n\n &super::PL011_UART\n\n}\n", "file_path": "11_exceptions_part1_groundwork/src/bsp/raspberrypi/console.rs", "rank": 42, "score": 338614.39727038494 }, { "content": "/// Return a reference to the console.\n\npub fn console() -> &'static impl console::interface::All {\n\n &super::PL011_UART\n\n}\n", "file_path": "X1_JTAG_boot/src/bsp/raspberrypi/console.rs", "rank": 43, "score": 338614.39727038494 }, { "content": "#[inline(always)]\n\nfn virt_rw_start() -> Address<Virtual> {\n\n Address::new(unsafe { __rw_start.get() as usize })\n\n}\n\n\n\n/// Size of the Read+Write (RW) range.\n\n///\n\n/// # Safety\n\n///\n\n/// - Value is provided by the linker script and must be trusted as-is.\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory.rs", "rank": 44, "score": 338369.3374140271 }, { "content": "#[inline(always)]\n\nfn virt_rx_start() -> Address<Virtual> {\n\n Address::new(unsafe { __rx_start.get() as usize })\n\n}\n\n\n\n/// Size of the Read+Execute (RX) range.\n\n///\n\n/// # Safety\n\n///\n\n/// - Value is provided by the linker script and must be trusted as-is.\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory.rs", "rank": 45, "score": 338369.3374140271 }, { "content": "#[inline(always)]\n\nfn phys_addr_space_end() -> Address<Physical> {\n\n map::END\n\n}\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory.rs", "rank": 46, "score": 335452.7237227391 }, { "content": "#[inline(always)]\n\nfn phys_addr_space_end() -> Address<Physical> {\n\n map::END\n\n}\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory.rs", "rank": 47, "score": 335452.723722739 }, { "content": "#[inline(always)]\n\nfn virt_boot_core_stack_start() -> Address<Virtual> {\n\n Address::new(unsafe { __boot_core_stack_start.get() as usize })\n\n}\n\n\n\n/// Size of the boot core's stack.\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory.rs", "rank": 48, "score": 335057.6105167824 }, { "content": "#[inline(always)]\n\nfn virt_boot_core_stack_start() -> Address<Virtual> {\n\n Address::new(unsafe { __boot_core_stack_start.get() as usize })\n\n}\n\n\n\n/// Size of the boot core's stack.\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory.rs", "rank": 49, "score": 335057.6105167824 }, { "content": "/// Return a reference to the driver manager.\n\npub fn driver_manager() -> &'static impl driver::interface::DriverManager {\n\n &BSP_DRIVER_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse driver::interface::DeviceDriver;\n\n\n\nimpl driver::interface::DriverManager for BSPDriverManager {\n\n fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[..]\n\n }\n\n\n\n fn post_device_driver_init(&self) {\n\n // Configure PL011Uart's output pins.\n\n super::GPIO.map_pl011_uart();\n\n }\n\n}\n", "file_path": "07_timestamps/src/bsp/raspberrypi/driver.rs", "rank": 50, "score": 334895.78423430235 }, { "content": "/// Add mapping records for the kernel binary.\n\n///\n\n/// The actual translation table entries for the kernel binary are generated using the offline\n\n/// `translation table tool` and patched into the kernel binary. This function just adds the mapping\n\n/// record entries.\n\n///\n\n/// It must be ensured that these entries are in sync with the offline tool.\n\npub fn kernel_add_mapping_records_for_precomputed() {\n\n generic_mmu::kernel_add_mapping_record(\n\n \"Kernel code and RO data\",\n\n &virt_rx_page_desc(),\n\n &phys_rx_page_desc(),\n\n &AttributeFields {\n\n mem_attributes: MemAttributes::CacheableDRAM,\n\n acc_perms: AccessPermissions::ReadOnly,\n\n execute_never: false,\n\n },\n\n );\n\n\n\n generic_mmu::kernel_add_mapping_record(\n\n \"Kernel data and bss\",\n\n &virt_rw_page_desc(),\n\n &phys_rw_page_desc(),\n\n &AttributeFields {\n\n mem_attributes: MemAttributes::CacheableDRAM,\n\n acc_perms: AccessPermissions::ReadWrite,\n\n execute_never: true,\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory/mmu.rs", "rank": 51, "score": 333679.9831068655 }, { "content": "#[inline(always)]\n\nfn virt_boot_core_stack_start() -> Address<Virtual> {\n\n Address::new(unsafe { __boot_core_stack_start.get() as usize })\n\n}\n\n\n\n/// Size of the boot core's stack.\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory.rs", "rank": 52, "score": 331841.9766790324 }, { "content": "#[inline(always)]\n\nfn phys_addr_space_end() -> Address<Physical> {\n\n map::END\n\n}\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory.rs", "rank": 53, "score": 331317.91247992637 }, { "content": "/// Return a reference to the driver manager.\n\npub fn driver_manager() -> &'static impl driver::interface::DriverManager {\n\n &BSP_DRIVER_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse driver::interface::DeviceDriver;\n\n\n\nimpl driver::interface::DriverManager for BSPDriverManager {\n\n fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[..]\n\n }\n\n\n\n fn post_device_driver_init(&self) {\n\n // Configure PL011Uart's output pins.\n\n super::GPIO.map_pl011_uart();\n\n }\n\n}\n", "file_path": "09_privilege_level/src/bsp/raspberrypi/driver.rs", "rank": 54, "score": 331295.2540440692 }, { "content": "/// Return a reference to the driver manager.\n\npub fn driver_manager() -> &'static impl driver::interface::DriverManager {\n\n &BSP_DRIVER_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse driver::interface::DeviceDriver;\n\n\n\nimpl driver::interface::DriverManager for BSPDriverManager {\n\n fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[..]\n\n }\n\n\n\n fn post_device_driver_init(&self) {\n\n // Configure PL011Uart's output pins.\n\n super::GPIO.map_pl011_uart();\n\n }\n\n}\n", "file_path": "12_integrated_testing/src/bsp/raspberrypi/driver.rs", "rank": 55, "score": 331295.2540440692 }, { "content": "/// Return a reference to the driver manager.\n\npub fn driver_manager() -> &'static impl driver::interface::DriverManager {\n\n &BSP_DRIVER_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse driver::interface::DeviceDriver;\n\n\n\nimpl driver::interface::DriverManager for BSPDriverManager {\n\n fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[..]\n\n }\n\n\n\n fn post_device_driver_init(&self) {\n\n // Configure PL011Uart's output pins.\n\n super::GPIO.map_pl011_uart();\n\n }\n\n}\n", "file_path": "06_uart_chainloader/src/bsp/raspberrypi/driver.rs", "rank": 56, "score": 331295.2540440692 }, { "content": "/// Return a reference to the console.\n\npub fn console() -> &'static impl console::interface::All {\n\n &super::PL011_UART\n\n}\n\n\n\n//--------------------------------------------------------------------------------------------------\n\n// Testing\n\n//--------------------------------------------------------------------------------------------------\n\n\n\n/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps\n\n/// than on real hardware due to QEMU's abstractions.\n\n///\n\n/// For the RPi, nothing needs to be done.\n", "file_path": "13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/console.rs", "rank": 57, "score": 331295.2540440692 }, { "content": "/// Add mapping records for the kernel binary.\n\n///\n\n/// The actual translation table entries for the kernel binary are generated using the offline\n\n/// `translation table tool` and patched into the kernel binary. This function just adds the mapping\n\n/// record entries.\n\n///\n\n/// It must be ensured that these entries are in sync with the offline tool.\n\npub fn kernel_add_mapping_records_for_precomputed() {\n\n generic_mmu::kernel_add_mapping_record(\n\n \"Kernel code and RO data\",\n\n &virt_rx_page_desc(),\n\n &phys_rx_page_desc(),\n\n &AttributeFields {\n\n mem_attributes: MemAttributes::CacheableDRAM,\n\n acc_perms: AccessPermissions::ReadOnly,\n\n execute_never: false,\n\n },\n\n );\n\n\n\n generic_mmu::kernel_add_mapping_record(\n\n \"Kernel data and bss\",\n\n &virt_rw_page_desc(),\n\n &phys_rw_page_desc(),\n\n &AttributeFields {\n\n mem_attributes: MemAttributes::CacheableDRAM,\n\n acc_perms: AccessPermissions::ReadWrite,\n\n execute_never: true,\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory/mmu.rs", "rank": 58, "score": 329693.45811476174 }, { "content": "/// Return a reference to the driver manager.\n\npub fn driver_manager() -> &'static impl driver::interface::DriverManager {\n\n &BSP_DRIVER_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse driver::interface::DeviceDriver;\n\n\n\nimpl driver::interface::DriverManager for BSPDriverManager {\n\n fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[..]\n\n }\n\n\n\n fn post_device_driver_init(&self) {\n\n // Configure PL011Uart's output pins.\n\n super::GPIO.map_pl011_uart();\n\n }\n\n}\n", "file_path": "X1_JTAG_boot/src/bsp/raspberrypi/driver.rs", "rank": 59, "score": 327807.270106026 }, { "content": "/// Return a reference to the driver manager.\n\npub fn driver_manager() -> &'static impl driver::interface::DriverManager {\n\n &BSP_DRIVER_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse driver::interface::DeviceDriver;\n\n\n\nimpl driver::interface::DriverManager for BSPDriverManager {\n\n fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[..]\n\n }\n\n\n\n fn post_device_driver_init(&self) {\n\n // Configure PL011Uart's output pins.\n\n super::GPIO.map_pl011_uart();\n\n }\n\n}\n", "file_path": "08_hw_debug_JTAG/src/bsp/raspberrypi/driver.rs", "rank": 60, "score": 327807.270106026 }, { "content": "/// Return a reference to the driver manager.\n\npub fn driver_manager() -> &'static impl driver::interface::DriverManager {\n\n &BSP_DRIVER_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse driver::interface::DeviceDriver;\n\n\n\nimpl driver::interface::DriverManager for BSPDriverManager {\n\n fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[..]\n\n }\n\n\n\n fn post_device_driver_init(&self) {\n\n // Configure PL011Uart's output pins.\n\n super::GPIO.map_pl011_uart();\n\n }\n\n}\n", "file_path": "11_exceptions_part1_groundwork/src/bsp/raspberrypi/driver.rs", "rank": 61, "score": 327807.270106026 }, { "content": "/// Return a reference to the driver manager.\n\npub fn driver_manager() -> &'static impl driver::interface::DriverManager {\n\n &BSP_DRIVER_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse driver::interface::DeviceDriver;\n\n\n\nimpl driver::interface::DriverManager for BSPDriverManager {\n\n fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[..]\n\n }\n\n\n\n fn post_device_driver_init(&self) {\n\n // Configure PL011Uart's output pins.\n\n super::GPIO.map_pl011_uart();\n\n }\n\n}\n", "file_path": "05_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs", "rank": 62, "score": 327807.270106026 }, { "content": "/// Board identification.\n\npub fn board_name() -> &'static str {\n\n #[cfg(feature = \"bsp_rpi3\")]\n\n {\n\n \"Raspberry Pi 3\"\n\n }\n\n\n\n #[cfg(feature = \"bsp_rpi4\")]\n\n {\n\n \"Raspberry Pi 4\"\n\n }\n\n}\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi.rs", "rank": 63, "score": 324343.9413358775 }, { "content": "/// Board identification.\n\npub fn board_name() -> &'static str {\n\n #[cfg(feature = \"bsp_rpi3\")]\n\n {\n\n \"Raspberry Pi 3\"\n\n }\n\n\n\n #[cfg(feature = \"bsp_rpi4\")]\n\n {\n\n \"Raspberry Pi 4\"\n\n }\n\n}\n", "file_path": "10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi.rs", "rank": 64, "score": 324343.9413358775 }, { "content": "/// Board identification.\n\npub fn board_name() -> &'static str {\n\n #[cfg(feature = \"bsp_rpi3\")]\n\n {\n\n \"Raspberry Pi 3\"\n\n }\n\n\n\n #[cfg(feature = \"bsp_rpi4\")]\n\n {\n\n \"Raspberry Pi 4\"\n\n }\n\n}\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi.rs", "rank": 65, "score": 324343.9413358775 }, { "content": "/// Return a reference to the driver manager.\n\npub fn driver_manager() -> &'static impl driver::interface::DriverManager {\n\n &BSP_DRIVER_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\nuse driver::interface::DeviceDriver;\n\n\n\nimpl driver::interface::DriverManager for BSPDriverManager {\n\n fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] {\n\n &self.device_drivers[..]\n\n }\n\n\n\n fn post_device_driver_init(&self) {\n\n // Configure PL011Uart's output pins.\n\n super::GPIO.map_pl011_uart();\n\n }\n\n}\n", "file_path": "13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/driver.rs", "rank": 66, "score": 321148.4727967292 }, { "content": "/// Board identification.\n\npub fn board_name() -> &'static str {\n\n #[cfg(feature = \"bsp_rpi3\")]\n\n {\n\n \"Raspberry Pi 3\"\n\n }\n\n\n\n #[cfg(feature = \"bsp_rpi4\")]\n\n {\n\n \"Raspberry Pi 4\"\n\n }\n\n}\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi.rs", "rank": 67, "score": 320684.95413840376 }, { "content": "/// Return a reference to the time manager.\n\npub fn time_manager() -> &'static impl time::interface::TimeManager {\n\n &TIME_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\n\n\nimpl time::interface::TimeManager for GenericTimer {\n\n fn resolution(&self) -> Duration {\n\n Duration::from_nanos(NS_PER_S / (CNTFRQ_EL0.get() as u64))\n\n }\n\n\n\n fn uptime(&self) -> Duration {\n\n let current_count: u64 = self.read_cntpct() * NS_PER_S;\n\n let frq: u64 = CNTFRQ_EL0.get() as u64;\n\n\n\n Duration::from_nanos(current_count / frq)\n\n }\n\n\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/time.rs", "rank": 68, "score": 319809.40500819456 }, { "content": "/// Return a reference to the time manager.\n\npub fn time_manager() -> &'static impl time::interface::TimeManager {\n\n &TIME_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\n\n\nimpl time::interface::TimeManager for GenericTimer {\n\n fn resolution(&self) -> Duration {\n\n Duration::from_nanos(NS_PER_S / (CNTFRQ_EL0.get() as u64))\n\n }\n\n\n\n fn uptime(&self) -> Duration {\n\n let current_count: u64 = self.read_cntpct() * NS_PER_S;\n\n let frq: u64 = CNTFRQ_EL0.get() as u64;\n\n\n\n Duration::from_nanos(current_count / frq)\n\n }\n\n\n", "file_path": "10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/time.rs", "rank": 69, "score": 319809.40500819456 }, { "content": "/// Return a reference to the time manager.\n\npub fn time_manager() -> &'static impl time::interface::TimeManager {\n\n &TIME_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\n\n\nimpl time::interface::TimeManager for GenericTimer {\n\n fn resolution(&self) -> Duration {\n\n Duration::from_nanos(NS_PER_S / (CNTFRQ_EL0.get() as u64))\n\n }\n\n\n\n fn uptime(&self) -> Duration {\n\n let current_count: u64 = self.read_cntpct() * NS_PER_S;\n\n let frq: u64 = CNTFRQ_EL0.get() as u64;\n\n\n\n Duration::from_nanos(current_count / frq)\n\n }\n\n\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/time.rs", "rank": 70, "score": 319809.40500819456 }, { "content": "/// Return a reference to the time manager.\n\npub fn time_manager() -> &'static impl time::interface::TimeManager {\n\n &TIME_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\n\n\nimpl time::interface::TimeManager for GenericTimer {\n\n fn resolution(&self) -> Duration {\n\n Duration::from_nanos(NS_PER_S / (CNTFRQ_EL0.get() as u64))\n\n }\n\n\n\n fn uptime(&self) -> Duration {\n\n let current_count: u64 = self.read_cntpct() * NS_PER_S;\n\n let frq: u64 = CNTFRQ_EL0.get() as u64;\n\n\n\n Duration::from_nanos(current_count / frq)\n\n }\n\n\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/time.rs", "rank": 71, "score": 316649.1125958479 }, { "content": "/// Return a reference to the IRQ manager.\n\npub fn irq_manager() -> &'static impl exception::asynchronous::interface::IRQManager<\n\n IRQNumberType = bsp::device_driver::IRQNumber,\n\n> {\n\n &super::super::INTERRUPT_CONTROLLER\n\n}\n", "file_path": "13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception/asynchronous.rs", "rank": 72, "score": 308869.51757138 }, { "content": "/// Human-readable print of all recorded kernel mappings.\n\npub fn kernel_print_mappings() {\n\n mapping_record::kernel_print()\n\n}\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/memory/mmu.rs", "rank": 73, "score": 305686.2167304197 }, { "content": "/// Human-readable print of all recorded kernel mappings.\n\npub fn kernel_print_mappings() {\n\n mapping_record::kernel_print()\n\n}\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs", "rank": 74, "score": 305686.2167304198 }, { "content": "/// Human-readable print of all recorded kernel mappings.\n\npub fn kernel_print() {\n\n KERNEL_MAPPING_RECORD.read(|mr| mr.print());\n\n}\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/memory/mmu/mapping_record.rs", "rank": 75, "score": 301897.2702291679 }, { "content": "/// Human-readable print of all recorded kernel mappings.\n\npub fn kernel_print_mappings() {\n\n mapping_record::kernel_print()\n\n}\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/memory/mmu.rs", "rank": 76, "score": 301897.2702291679 }, { "content": "/// Human-readable print of all recorded kernel mappings.\n\npub fn kernel_print() {\n\n KERNEL_MAPPING_RECORD.read(|mr| mr.print());\n\n}\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/memory/mmu/mapping_record.rs", "rank": 77, "score": 301897.2702291679 }, { "content": "/// Add an entry to the mapping info record.\n\npub fn kernel_add(\n\n name: &'static str,\n\n virt_pages: &PageSliceDescriptor<Virtual>,\n\n phys_pages: &PageSliceDescriptor<Physical>,\n\n attr: &AttributeFields,\n\n) -> Result<(), &'static str> {\n\n KERNEL_MAPPING_RECORD.write(|mr| mr.add(name, virt_pages, phys_pages, attr))\n\n}\n\n\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/memory/mmu/mapping_record.rs", "rank": 78, "score": 301891.4789510657 }, { "content": "/// Add an entry to the mapping info record.\n\npub fn kernel_add_mapping_record(\n\n name: &'static str,\n\n virt_pages: &PageSliceDescriptor<Virtual>,\n\n phys_pages: &PageSliceDescriptor<Physical>,\n\n attr: &AttributeFields,\n\n) {\n\n if let Err(x) = mapping_record::kernel_add(name, virt_pages, phys_pages, attr) {\n\n warn!(\"{}\", x);\n\n }\n\n}\n\n\n\n/// Raw mapping of virtual to physical pages in the kernel translation tables.\n\n///\n\n/// Prevents mapping into the MMIO range of the tables.\n\n///\n\n/// # Safety\n\n///\n\n/// - See `kernel_map_pages_at_unchecked()`.\n\n/// - Does not prevent aliasing. Currently, the callers must be trusted.\n\npub unsafe fn kernel_map_pages_at(\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/memory/mmu.rs", "rank": 79, "score": 301891.47895106574 }, { "content": "/// Add an entry to the mapping info record.\n\npub fn kernel_add(\n\n name: &'static str,\n\n virt_pages: &PageSliceDescriptor<Virtual>,\n\n phys_pages: &PageSliceDescriptor<Physical>,\n\n attr: &AttributeFields,\n\n) -> Result<(), &'static str> {\n\n KERNEL_MAPPING_RECORD.write(|mr| mr.add(name, virt_pages, phys_pages, attr))\n\n}\n\n\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/memory/mmu/mapping_record.rs", "rank": 80, "score": 301891.4789510657 }, { "content": "/// Human-readable print of all recorded kernel mappings.\n\npub fn kernel_print() {\n\n KERNEL_MAPPING_RECORD.read(|mr| mr.print());\n\n}\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/mapping_record.rs", "rank": 81, "score": 298230.58109378675 }, { "content": "/// Add an entry to the mapping info record.\n\npub fn kernel_add(\n\n name: &'static str,\n\n virt_pages: &PageSliceDescriptor<Virtual>,\n\n phys_pages: &PageSliceDescriptor<Physical>,\n\n attr: &AttributeFields,\n\n) -> Result<(), &'static str> {\n\n KERNEL_MAPPING_RECORD.write(|mr| mr.add(name, virt_pages, phys_pages, attr))\n\n}\n\n\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/mapping_record.rs", "rank": 82, "score": 298224.78981568443 }, { "content": "/// Add an entry to the mapping info record.\n\npub fn kernel_add_mapping_record(\n\n name: &'static str,\n\n virt_pages: &PageSliceDescriptor<Virtual>,\n\n phys_pages: &PageSliceDescriptor<Physical>,\n\n attr: &AttributeFields,\n\n) {\n\n if let Err(x) = mapping_record::kernel_add(name, virt_pages, phys_pages, attr) {\n\n warn!(\"{}\", x);\n\n }\n\n}\n\n\n\n/// Raw mapping of virtual to physical pages in the kernel translation tables.\n\n///\n\n/// Prevents mapping into the MMIO range of the tables.\n\n///\n\n/// # Safety\n\n///\n\n/// - See `kernel_map_pages_at_unchecked()`.\n\n/// - Does not prevent aliasing. Currently, the callers must be trusted.\n\npub unsafe fn kernel_map_pages_at(\n", "file_path": "16_virtual_mem_part4_higher_half_kernel/src/memory/mmu.rs", "rank": 83, "score": 298224.78981568443 }, { "content": "/// Board identification.\n\npub fn board_name() -> &'static str {\n\n #[cfg(feature = \"bsp_rpi3\")]\n\n {\n\n \"Raspberry Pi 3\"\n\n }\n\n\n\n #[cfg(feature = \"bsp_rpi4\")]\n\n {\n\n \"Raspberry Pi 4\"\n\n }\n\n}\n", "file_path": "07_timestamps/src/bsp/raspberrypi.rs", "rank": 84, "score": 294160.96259619313 }, { "content": "fn rx_range_inclusive() -> RangeInclusive<usize> {\n\n // Notice the subtraction to turn the exclusive end into an inclusive end.\n\n #[allow(clippy::range_minus_one)]\n\n RangeInclusive::new(super::rx_start(), super::rx_end_exclusive() - 1)\n\n}\n\n\n", "file_path": "10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs", "rank": 85, "score": 293884.87831819354 }, { "content": "fn mmio_range_inclusive() -> RangeInclusive<usize> {\n\n RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE)\n\n}\n\n\n\n//--------------------------------------------------------------------------------------------------\n\n// Public Code\n\n//--------------------------------------------------------------------------------------------------\n\n\n", "file_path": "10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs", "rank": 86, "score": 293884.87831819354 }, { "content": "/// The Read+Execute (RX) pages of the kernel binary.\n\nfn virt_rx_page_desc() -> PageSliceDescriptor<Virtual> {\n\n let num_pages = size_to_num_pages(super::rx_size());\n\n\n\n PageSliceDescriptor::from_addr(super::virt_rx_start(), num_pages)\n\n}\n\n\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory/mmu.rs", "rank": 87, "score": 291328.99914272863 }, { "content": "/// The Read+Write (RW) pages of the kernel binary.\n\nfn virt_rw_page_desc() -> PageSliceDescriptor<Virtual> {\n\n let num_pages = size_to_num_pages(super::rw_size());\n\n\n\n PageSliceDescriptor::from_addr(super::virt_rw_start(), num_pages)\n\n}\n\n\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory/mmu.rs", "rank": 88, "score": 291328.99914272863 }, { "content": "/// The Read+Execute (RX) pages of the kernel binary.\n\nfn virt_rx_page_desc() -> PageSliceDescriptor<Virtual> {\n\n let num_pages = size_to_num_pages(super::rx_size());\n\n\n\n PageSliceDescriptor::from_addr(super::virt_rx_start(), num_pages)\n\n}\n\n\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory/mmu.rs", "rank": 89, "score": 291328.99914272863 }, { "content": "/// The Read+Write (RW) pages of the kernel binary.\n\nfn virt_rw_page_desc() -> PageSliceDescriptor<Virtual> {\n\n let num_pages = size_to_num_pages(super::rw_size());\n\n\n\n PageSliceDescriptor::from_addr(super::virt_rw_start(), num_pages)\n\n}\n\n\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory/mmu.rs", "rank": 90, "score": 291328.99914272863 }, { "content": "pub fn kernel_find_and_insert_mmio_duplicate(\n\n mmio_descriptor: &MMIODescriptor,\n\n new_user: &'static str,\n\n) -> Option<Address<Virtual>> {\n\n let phys_pages: PageSliceDescriptor<Physical> = (*mmio_descriptor).into();\n\n\n\n KERNEL_MAPPING_RECORD.write(|mr| {\n\n let dup = mr.find_duplicate(&phys_pages)?;\n\n\n\n if let Err(x) = dup.add_user(new_user) {\n\n warn!(\"{}\", x);\n\n }\n\n\n\n Some(dup.virt_start_addr)\n\n })\n\n}\n\n\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/memory/mmu/mapping_record.rs", "rank": 91, "score": 291235.2543388961 }, { "content": "pub fn kernel_find_and_insert_mmio_duplicate(\n\n mmio_descriptor: &MMIODescriptor,\n\n new_user: &'static str,\n\n) -> Option<Address<Virtual>> {\n\n let phys_pages: PageSliceDescriptor<Physical> = (*mmio_descriptor).into();\n\n\n\n KERNEL_MAPPING_RECORD.write(|mr| {\n\n let dup = mr.find_duplicate(&phys_pages)?;\n\n\n\n if let Err(x) = dup.add_user(new_user) {\n\n warn!(\"{}\", x);\n\n }\n\n\n\n Some(dup.virt_start_addr)\n\n })\n\n}\n\n\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/memory/mmu/mapping_record.rs", "rank": 92, "score": 291235.2543388961 }, { "content": "/// Return a reference to the time manager.\n\npub fn time_manager() -> &'static impl time::interface::TimeManager {\n\n &TIME_MANAGER\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//------------------------------------------------------------------------------\n\n\n\nimpl time::interface::TimeManager for GenericTimer {\n\n fn resolution(&self) -> Duration {\n\n Duration::from_nanos(NS_PER_S / (CNTFRQ_EL0.get() as u64))\n\n }\n\n\n\n fn uptime(&self) -> Duration {\n\n let current_count: u64 = self.read_cntpct() * NS_PER_S;\n\n let frq: u64 = CNTFRQ_EL0.get() as u64;\n\n\n\n Duration::from_nanos(current_count / frq)\n\n }\n\n\n", "file_path": "07_timestamps/src/_arch/aarch64/time.rs", "rank": 93, "score": 291086.1479872564 }, { "content": "struct EsrEL1(InMemoryRegister<u64, ESR_EL1::Register>);\n\n\n\n/// The exception context as it is stored on the stack on exception entry.\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception.rs", "rank": 94, "score": 290914.5339151006 }, { "content": "#[repr(transparent)]\n\nstruct SpsrEL1(InMemoryRegister<u64, SPSR_EL1::Register>);\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/exception.rs", "rank": 95, "score": 290914.53391510056 }, { "content": "#[repr(transparent)]\n\nstruct SpsrEL1(InMemoryRegister<u64, SPSR_EL1::Register>);\n", "file_path": "14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception.rs", "rank": 96, "score": 290914.5339151006 }, { "content": "struct EsrEL1(InMemoryRegister<u64, ESR_EL1::Register>);\n\n\n\n/// The exception context as it is stored on the stack on exception entry.\n", "file_path": "15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/exception.rs", "rank": 97, "score": 290914.5339151006 }, { "content": "/// Board identification.\n\npub fn board_name() -> &'static str {\n\n #[cfg(feature = \"bsp_rpi3\")]\n\n {\n\n \"Raspberry Pi 3\"\n\n }\n\n\n\n #[cfg(feature = \"bsp_rpi4\")]\n\n {\n\n \"Raspberry Pi 4\"\n\n }\n\n}\n", "file_path": "12_integrated_testing/src/bsp/raspberrypi.rs", "rank": 98, "score": 290770.10567352426 }, { "content": "/// Board identification.\n\npub fn board_name() -> &'static str {\n\n #[cfg(feature = \"bsp_rpi3\")]\n\n {\n\n \"Raspberry Pi 3\"\n\n }\n\n\n\n #[cfg(feature = \"bsp_rpi4\")]\n\n {\n\n \"Raspberry Pi 4\"\n\n }\n\n}\n", "file_path": "06_uart_chainloader/src/bsp/raspberrypi.rs", "rank": 99, "score": 290770.1056735242 } ]
Rust
src/gens/csharp/mod.rs
fizruk/trans-gen
9a5b4635b39a18e9844a4bf40e8ca582fc3ffca2
use super::*; fn conv(name: &str) -> String { name.replace("Int32", "Int") .replace("Int64", "Long") .replace("Float32", "Float") .replace("Float64", "Double") .replace("Params", "Parameters") } pub struct Generator { main_namespace: String, files: HashMap<String, String>, } fn new_var(var: &str, suffix: &str) -> String { let var = match var.find('.') { Some(index) => &var[index + 1..], None => var, }; let indexing_count = var.chars().filter(|&c| c == '[').count(); let var = match var.find('[') { Some(index) => &var[..index], None => var, }; let mut var = var.to_owned(); for _ in 0..indexing_count { var.push_str("Element"); } var.push_str(suffix); Name::new(var).mixed_case(conv) } fn is_null(var: &str, schema: &Schema) -> String { if nullable(schema) { format!("{} == null", var) } else { format!("!{}.HasValue", var) } } fn option_unwrap(var: &str, schema: &Schema) -> String { if nullable(schema) { var.to_owned() } else { format!("{}.Value", var) } } fn nullable(schema: &Schema) -> bool { match schema { Schema::Bool | Schema::Int32 | Schema::Int64 | Schema::Float32 | Schema::Float64 | Schema::Enum { .. } | Schema::Struct { .. } => false, Schema::String | Schema::Option(_) | Schema::Vec(_) | Schema::Map(_, _) | Schema::OneOf { .. } => true, } } fn type_name(schema: &Schema) -> String { format!( "{}{}", type_name_prearray(schema), type_name_postarray(schema), ) } fn type_name_prearray(schema: &Schema) -> String { match schema { Schema::Bool => "bool".to_owned(), Schema::Int32 => "int".to_owned(), Schema::Int64 => "long".to_owned(), Schema::Float32 => "float".to_owned(), Schema::Float64 => "double".to_owned(), Schema::String => "string".to_owned(), Schema::Struct { .. } | Schema::OneOf { .. } | Schema::Enum { .. } => name_path(schema), Schema::Option(inner) => { if nullable(inner) { type_name(inner) } else { format!("{}?", type_name(inner)) } } Schema::Vec(inner) => type_name_prearray(inner), Schema::Map(key, value) => format!( "System.Collections.Generic.IDictionary<{}, {}>", type_name(key), type_name(value) ), } } fn type_name_postarray(schema: &Schema) -> String { match schema { Schema::Vec(inner) => format!("[]{}", type_name_postarray(inner)), _ => String::new(), } } fn doc_comment(documentation: &Documentation) -> String { let mut result = String::new(); result.push_str("/// <summary>\n"); for line in documentation.get("en").unwrap().lines() { result.push_str("/// "); result.push_str(line); result.push('\n'); } result.push_str("/// </summary>\n"); result.trim().to_owned() } fn doc_read_from(name: &str) -> String { format!("/// <summary> Read {} from reader </summary>", name) } fn doc_write_to(name: &str) -> String { format!("/// <summary> Write {} to writer </summary>", name) } fn doc_to_string(name: &str) -> String { format!( "/// <summary> Get string representation of {} </summary>", name, ) } fn read_var(var: &str, schema: &Schema) -> String { include_templing!("src/gens/csharp/read_var.templing") } fn write_var(var: &str, schema: &Schema) -> String { include_templing!("src/gens/csharp/write_var.templing") } fn var_to_string(var: &str, schema: &Schema) -> String { include_templing!("src/gens/csharp/var_to_string.templing") } fn struct_impl(definition: &Struct, base: Option<(&Name, usize)>) -> String { include_templing!("src/gens/csharp/struct_impl.templing") } fn namespace_path(namespace: &Namespace) -> String { namespace .parts .iter() .map(|name| name.camel_case(conv)) .collect::<Vec<_>>() .join(".") } fn namespace_path_suffix(namespace: &Namespace) -> String { let namespace_path = namespace_path(namespace); if namespace_path.is_empty() { namespace_path } else { format!(".{}", namespace_path) } } fn name_path(schema: &Schema) -> String { match schema { Schema::Enum { namespace, base_name: name, .. } | Schema::Struct { namespace, definition: Struct { name, .. }, .. } | Schema::OneOf { namespace, base_name: name, .. } => { let namespace_path = namespace_path(namespace); if namespace_path.is_empty() { name.camel_case(conv) } else { format!("{}.{}", namespace_path, name.camel_case(conv)) } } _ => unreachable!(), } } impl crate::Generator for Generator { const NAME: &'static str = "C#"; type Options = (); fn new(name: &str, _version: &str, _: ()) -> Self { let name = Name::new(name.to_owned()); let mut files = HashMap::new(); files.insert( format!("{}.csproj", name.camel_case(conv)), include_str!("project.csproj").to_owned(), ); Self { main_namespace: name.camel_case(conv), files, } } fn generate(mut self, extra_files: Vec<File>) -> GenResult { for file in extra_files { self.files.insert(file.path, file.content); } self.files.into() } fn add_only(&mut self, schema: &Schema) { match schema { Schema::Enum { namespace, documentation, base_name, variants, } => { self.files.insert( format!("{}.cs", name_path(schema).replace('.', "/")), include_templing!("src/gens/csharp/enum.templing"), ); } Schema::Struct { namespace, definition, } => { self.files.insert( format!("{}.cs", name_path(schema).replace('.', "/")), include_templing!("src/gens/csharp/struct.templing"), ); } Schema::OneOf { namespace, documentation, base_name, variants, } => { self.files.insert( format!("{}.cs", name_path(schema).replace('.', "/")), include_templing!("src/gens/csharp/oneof.templing"), ); } Schema::Bool | Schema::Int32 | Schema::Int64 | Schema::Float32 | Schema::Float64 | Schema::String | Schema::Option(_) | Schema::Vec(_) | Schema::Map(_, _) => {} } } } impl RunnableGenerator for Generator { fn build_local(path: &Path, verbose: bool) -> anyhow::Result<()> { command("dotnet") .current_dir(path) .arg("publish") .arg("-c") .arg("Release") .arg("-o") .arg(".") .show_output(verbose) .run() } fn run_local(path: &Path) -> anyhow::Result<Command> { fn project_name(path: &Path) -> anyhow::Result<String> { for file in std::fs::read_dir(path)? { let file = file?; if file.path().extension() == Some("csproj".as_ref()) { return Ok(file .path() .file_stem() .unwrap() .to_str() .unwrap() .to_owned()); } } anyhow::bail!("Failed to determine project name") } let mut command = command("dotnet"); command .arg(format!("{}.dll", project_name(path)?)) .current_dir(path); Ok(command) } } impl<D: Trans + PartialEq + Debug> TestableGenerator<testing::FileReadWrite<D>> for Generator { fn extra_files(&self, test: &testing::FileReadWrite<D>) -> Vec<File> { let schema = Schema::of::<D>(&test.version); let schema: &Schema = &schema; vec![File { path: "Runner.cs".to_owned(), content: include_templing!("src/gens/csharp/FileReadWrite.cs.templing"), }] } } impl<D: Trans + PartialEq + Debug> TestableGenerator<testing::TcpReadWrite<D>> for Generator { fn extra_files(&self, test: &testing::TcpReadWrite<D>) -> Vec<File> { let schema = Schema::of::<D>(&test.version); let schema: &Schema = &schema; vec![File { path: "Runner.cs".to_owned(), content: include_templing!("src/gens/csharp/TcpReadWrite.cs.templing"), }] } }
use super::*; fn conv(name: &str) -> String { name.replace("Int32", "Int") .replace("Int64", "Long") .replace("Float32", "Float") .replace("Float64", "Double") .replace("Params", "Parameters") } pub struct Generator { main_namespace: String, files: HashMap<String, String>, } fn new_var(var: &str, suffix: &str) -> String { let var = match var.find('.') { Some(index) => &var[index + 1..], None => var, }; let indexing_count = var.chars().filter(|&c| c == '[').count(); let var = match var.find('[') { Some(index) => &var[..index], None => var, }; let mut var = var.to_owned(); for _ in 0..indexing_count { var.push_str("Element"); } var.push_str(suffix); Name::new(var).mixed_case(conv) } fn is_null(var: &str, schema: &Schema) -> String { if nullable(schema) { format!("{} == null", var) } else { format!("!{}.HasValue", var) } } fn option_unwrap(var: &str, schema: &Schema) -> String { if nullable(schema) { var.to_owned() } else { format!("{}.Value", var) } } fn nullable(schema: &Schema) -> bool { match schema { Schema::Bool | Schema::Int32 | Schema::Int64 | Schema::Float32 | Schema::Float64 | Schema::Enum { .. } | Schema::Struct { .. } => false, Schema::String | Schema::Option(_) | Schema::Vec(_) | Schema::Map(_, _) | Schema::OneOf { .. } => true, } } fn type_name(schema: &Schema) -> String { format!( "{}{}", type_name_prearray(schema), type_name_postarray(schema), ) } fn type_name_prearray(schema: &Schema) -> String { match schema { Schema::Bool => "bool".to_owned(), Schema::Int32 => "int".to_owned(), Schema::Int64 => "long".to_owned(), Schema::Float32 => "float".to_owned(), Schema::Float64 => "double".to_owned(), Schema::String => "string".to_owned(), Schema::Struct { .. } | Schema::OneOf { .. } | Schema::Enum { .. } => name_path(schema), Schema::Option(inner) => { if nullable(inner) { type_name(inner) } else { format!("{}?", type_name(inner)) } } Schema::Vec(inner) => type_name_prearray(inner), Schema::Map(key, value) => format!( "System.Collections.Generic.IDictionary<{}, {}>", type_name(key), type_name(value) ), } } fn type_name_postarray(schema: &Schema) -> String { match schema { Schema::Vec(inner) => format!("[]{}", type_name_postarray(inner)), _ => String::new(), } } fn doc_comment(documentation: &Documentation) -> String { let mut result = String::new(); result.push_str("/// <summary>\n"); for line in documentation.get("en").unwrap().lines() { result.push_str("/// "); result.push_str(line); result.push('\n'); } result.push_str("/// </summary>\n"); result.trim().to_owned() } fn doc_read_from(name: &str) -> String { format!("/// <summary> Read {} from reader </summary>", name) } fn doc_write_to(name: &str) -> String { format!("/// <summary> Write {} to writer </summary>", name) } fn doc_to_string(name: &str) -> String { format!( "/// <summary> Get string representation of {} </summary>", name, ) } fn read_var(var: &str, schema: &Schema) -> String { include_templing!("src/gens/csharp/read_var.templing") } fn write_var(var: &str, schema: &Schema) -> String { include_templing!("src/gens/csharp/write_var.templing") } fn var_to_string(var: &str, schema: &Schema) -> String { include_templing!("src/gens/csharp/var_to_string.templing") } fn struct_impl(definition: &Struct, base: Option<(&Name, usize)>) -> String { include_templing!("src/gens/csharp/struct_impl.templing") } fn namespace_path(namespace: &Namespace) -> String { namespace .parts .iter() .map(|name| name.camel_case(conv)) .collect::<Vec<_>>() .join(".") } fn namespace_path_suffix(namespace: &Namespace) -> String { let namespace_path = namespace_path(namespace); if namespace_path.is_empty() { namespace_path } else { format!(".{}", namespace_path) } } fn name_path(schema: &Schema) -> String { match schema { Schema::Enum { namespace, base_name: name, .. } | Schema::Struct { namespace, definition: Struct { name, .. }, .. } | Schema::OneOf { namespace, base_name: name, .. } => { let namespace_path = namespace_path(namespace); if namespace_path.is_empty() { name.camel_case(conv) } else { format!("{}.{}", namespace_path, name.camel_case(conv)) } } _ => unreachable!(), } } impl crate::Generator for Generator { const NAME: &'static str = "C#"; type Options = (); fn new(name: &str, _version: &str, _: ()) -> Self { let name = Name::new(name.to_owned()); let mut files = HashMap::new(); files.insert( format!("{}.csproj", name.camel_case(conv)), include_str!("project.csproj").to_owned(), ); Self { main_namespace: name.camel_case(conv), files, } } fn generate(mut self, extra_files: Vec<File>) -> GenResult { for file in extra_files { self.files.insert(file.path, file.content); } self.files.into() } fn add_only(&mut self, schema: &Schema) { match schema { Schema::Enum { namespace, documentation, base_name, variants, } => { self.files.insert( format!("{}.cs", name_path(schema).replace('.', "/")), include_templing!("src/gens/csharp/enum.templing"), ); } Schema::Struct { namespace, definition, } => { self.files.insert( format!("{}.cs", name_path(schema).replace('.', "/")), include_templing!("src/gens/csharp/struct.templing"), ); } Schema::OneOf { namespace, documentation, base_name, variants, } => { self.files.insert( format!("{}.cs", name_path(schema).replace('.', "/")), include_templing!("src/gens/csharp/oneof.templing"), ); } Schema::Bool | Schema::Int32 | Schema::Int64 | Schema::Float32 | Schema::Float64 | Schema::String | Schema::Option(_) | Schema::Vec(_) | Schema::Map(_, _) => {} } } } impl RunnableGenerator for Generator { fn build_local(path: &Path, verbose: bool) -> anyhow::Result<()> { command("dotnet") .current_dir(path) .arg("publish") .arg("-c") .arg("Release") .arg("-o") .arg(".") .show_output(verbose) .run() } fn run_local(path: &Path) -> anyhow::Result<Command> { fn project_name(path: &Path) -> anyhow::Result<String> { for file in std::fs::read_dir(path)? { let file = file?; if file.path().extension() == Some("csproj".as_ref()) { return Ok(file .path() .file_stem() .unwrap() .to_str() .unwrap() .to_owned()); } } anyhow::bail!("Failed to determine project name") } let mut command = command("dotnet"); command .arg(format!("{}.dll", project_name(path)?)) .current_dir(path); Ok(command) } } impl<D: Trans + PartialEq + Debug> TestableGenerator<testing::FileReadWrite<D>> for Generator { fn extra_files(&self, test: &testing::FileReadWrite<D>) -> Vec<File> { let schema = Schema::of::<D>(&test.version); let schema: &Schema = &schema; vec![File { path: "Runner.cs".to_owned(), content: include_templing!("src/gens/csharp/FileReadWrite.cs.templing"), }] } } impl<D: Trans + PartialEq + Debug> TestableGenerator<testing::TcpReadWrite<D>> for Generator { fn extra_files(&self, test: &testing::TcpReadWrite<D>) -> Vec<File> { let schema = Schema::of::<D>(&test.version);
}
let schema: &Schema = &schema; vec![File { path: "Runner.cs".to_owned(), content: include_templing!("src/gens/csharp/TcpReadWrite.cs.templing"), }] }
function_block-function_prefix_line
[ { "content": "fn struct_impl(definition: &Struct, base: Option<(&Name, usize)>) -> String {\n\n include_templing!(\"src/gens/python/struct_impl.templing\")\n\n}\n\n\n", "file_path": "src/gens/python/mod.rs", "rank": 0, "score": 497748.56248176645 }, { "content": "fn struct_impl(definition: &Struct, base: Option<(&Name, usize)>) -> String {\n\n include_templing!(\"src/gens/fsharp/struct_impl.templing\")\n\n}\n\n\n", "file_path": "src/gens/fsharp/mod.rs", "rank": 1, "score": 497748.56248176645 }, { "content": "fn struct_impl(definition: &Struct, base: Option<(&Name, usize)>) -> String {\n\n include_templing!(\"src/gens/dlang/struct_impl.templing\")\n\n}\n\n\n", "file_path": "src/gens/dlang/mod.rs", "rank": 3, "score": 497748.56248176645 }, { "content": "fn struct_impl(definition: &Struct, base: Option<(&Name, usize)>) -> String {\n\n include_templing!(\"src/gens/go/struct_impl.templing\")\n\n}\n\n\n", "file_path": "src/gens/go/mod.rs", "rank": 4, "score": 497748.56248176645 }, { "content": "fn struct_impl(definition: &Struct, base: Option<(&Name, usize)>) -> String {\n\n include_templing!(\"src/gens/javascript/struct_impl.templing\")\n\n}\n\n\n", "file_path": "src/gens/javascript/mod.rs", "rank": 5, "score": 497748.56248176645 }, { "content": "fn struct_impl(definition: &Struct, base: Option<(&Name, usize)>) -> String {\n\n include_templing!(\"src/gens/haskell/struct_impl.templing\")\n\n}\n\n\n\nimpl crate::Generator for Generator {\n\n const NAME: &'static str = \"Haskell\";\n\n type Options = ();\n\n fn new(name: &str, version: &str, _: ()) -> Self {\n\n let version = match version.find('-') {\n\n Some(index) => &version[..index],\n\n None => version,\n\n };\n\n let package_name = Name::new(name.to_owned())\n\n .snake_case(conv)\n\n .replace('_', \"-\");\n\n let package_name = &package_name;\n\n let mut files = HashMap::new();\n\n files.insert(\n\n \"stack.yaml\".to_owned(),\n\n include_templing!(\"src/gens/haskell/stack.yaml.templing\"),\n", "file_path": "src/gens/haskell/mod.rs", "rank": 6, "score": 497748.56248176645 }, { "content": "fn struct_impl(definition: &Struct, base: Option<(&Name, usize)>) -> String {\n\n include_templing!(\"src/gens/ruby/struct_impl.templing\")\n\n}\n\n\n", "file_path": "src/gens/ruby/mod.rs", "rank": 7, "score": 497748.56248176645 }, { "content": "fn struct_impl(definition: &Struct, base: Option<(&Name, usize)>) -> String {\n\n include_templing!(\"src/gens/typescript/struct_impl.templing\")\n\n}\n\n\n", "file_path": "src/gens/typescript/mod.rs", "rank": 8, "score": 497748.56248176645 }, { "content": "pub fn write_variant_field<T>(variant_name: &str, field_name: &str) -> String {\n\n format!(\n\n \"Failed to write {}::{}::{}\",\n\n tynm::type_name::<T>(),\n\n variant_name,\n\n field_name,\n\n )\n\n}\n\n\n", "file_path": "trans/src/error_format.rs", "rank": 9, "score": 451164.96581675863 }, { "content": "pub fn read_variant_field<T>(variant_name: &str, field_name: &str) -> String {\n\n format!(\n\n \"Failed to read {}::{}::{}\",\n\n tynm::type_name::<T>(),\n\n variant_name,\n\n field_name,\n\n )\n\n}\n\n\n", "file_path": "trans/src/error_format.rs", "rank": 10, "score": 451148.0442676451 }, { "content": "pub fn write_tag<T>(variant_name: &str) -> String {\n\n format!(\n\n \"Failed to write tag of {}::{}\",\n\n tynm::type_name::<T>(),\n\n variant_name,\n\n )\n\n}\n", "file_path": "trans/src/error_format.rs", "rank": 11, "score": 442293.64454407303 }, { "content": "pub fn write_field<T>(field_name: &str) -> String {\n\n format!(\"Failed to write {}::{}\", tynm::type_name::<T>(), field_name)\n\n}\n\n\n", "file_path": "trans/src/error_format.rs", "rank": 13, "score": 405175.00015428633 }, { "content": "pub fn read_field<T>(field_name: &str) -> String {\n\n format!(\"Failed to read {}::{}\", tynm::type_name::<T>(), field_name)\n\n}\n\n\n", "file_path": "trans/src/error_format.rs", "rank": 14, "score": 405156.80578788935 }, { "content": "fn write_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/fsharp/write_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/fsharp/mod.rs", "rank": 16, "score": 397201.3184027168 }, { "content": "fn write_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/swift/write_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/swift/mod.rs", "rank": 17, "score": 397201.3184027168 }, { "content": "fn write_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/php/write_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/php/mod.rs", "rank": 18, "score": 397201.3184027168 }, { "content": "fn write_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/dlang/write_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/dlang/mod.rs", "rank": 19, "score": 397201.3184027168 }, { "content": "fn write_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/python/write_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/python/mod.rs", "rank": 20, "score": 397201.3184027168 }, { "content": "fn write_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/typescript/write_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/typescript/mod.rs", "rank": 21, "score": 397201.3184027168 }, { "content": "fn write_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/javascript/write_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/javascript/mod.rs", "rank": 22, "score": 397201.3184027168 }, { "content": "fn write_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/go/write_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/go/mod.rs", "rank": 23, "score": 397201.3184027168 }, { "content": "fn write_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/ruby/write_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/ruby/mod.rs", "rank": 24, "score": 397201.3184027168 }, { "content": "fn read_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/javascript/read_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/javascript/mod.rs", "rank": 25, "score": 397182.7753399532 }, { "content": "fn read_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/dlang/read_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/dlang/mod.rs", "rank": 26, "score": 397182.7753399532 }, { "content": "fn read_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/typescript/read_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/typescript/mod.rs", "rank": 28, "score": 397182.7753399532 }, { "content": "fn read_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/go/read_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/go/mod.rs", "rank": 29, "score": 397182.7753399532 }, { "content": "fn read_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/swift/read_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/swift/mod.rs", "rank": 30, "score": 397182.7753399532 }, { "content": "fn read_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/python/read_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/python/mod.rs", "rank": 31, "score": 397182.7753399532 }, { "content": "fn read_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/php/read_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/php/mod.rs", "rank": 32, "score": 397182.7753399532 }, { "content": "fn read_var(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/ruby/read_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/ruby/mod.rs", "rank": 33, "score": 397182.7753399532 }, { "content": "pub fn invalid_value_of_type<T, V: std::fmt::Debug>(value: V) -> String {\n\n format!(\n\n \"{:?} is invalid value of type {}\",\n\n value,\n\n tynm::type_name::<T>(),\n\n )\n\n}\n\n\n", "file_path": "trans/src/error_format.rs", "rank": 35, "score": 380456.93750921777 }, { "content": "fn var_to_string(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/ruby/var_to_string.templing\")\n\n}\n\n\n", "file_path": "src/gens/ruby/mod.rs", "rank": 37, "score": 369684.2944839819 }, { "content": "fn var_to_string(var: &str, schema: &Schema) -> String {\n\n include_templing!(\"src/gens/go/var_to_string.templing\")\n\n}\n\n\n", "file_path": "src/gens/go/mod.rs", "rank": 38, "score": 369684.2944839819 }, { "content": "fn new_var(var: &str, suffix: &str) -> String {\n\n let var = match var.rfind('.') {\n\n Some(index) => &var[index + 1..],\n\n None => var,\n\n };\n\n Name::new(format!(\"{}{}\", var, suffix)).mixed_case(conv)\n\n}\n\n\n", "file_path": "src/gens/fsharp/mod.rs", "rank": 39, "score": 361910.5199474992 }, { "content": "fn project_name(path: &Path) -> anyhow::Result<String> {\n\n Ok(std::fs::read_to_string(path.join(\"go.mod\"))\n\n .context(\"Failed to read go.mod\")?\n\n .lines()\n\n .next()\n\n .ok_or(anyhow!(\"go.mod is empty\"))?\n\n .strip_prefix(\"module \")\n\n .ok_or(anyhow!(\"Expected to see module name in go.mod\"))?\n\n .trim()\n\n .to_owned())\n\n}\n\n\n\nimpl RunnableGenerator for Generator {\n\n fn build_local(path: &Path, verbose: bool) -> anyhow::Result<()> {\n\n command(\"go\")\n\n .arg(\"build\")\n\n .arg(\"-o\")\n\n .arg(format!(\n\n \"{}{}\",\n\n project_name(path)?,\n", "file_path": "src/gens/go/mod.rs", "rank": 41, "score": 360201.2077287624 }, { "content": "pub fn invalid_bool(value: u8) -> String {\n\n format!(\n\n \"Bool values should be encoded as 0 or 1, got 0x{:X?}\",\n\n value,\n\n )\n\n}\n\n\n", "file_path": "trans/src/error_format.rs", "rank": 42, "score": 353740.8912307323 }, { "content": "fn namespace_path(schema: &Schema) -> String {\n\n schema\n\n .namespace()\n\n .unwrap()\n\n .parts\n\n .iter()\n\n .map(|name| name.camel_case(conv))\n\n .collect::<Vec<String>>()\n\n .join(\"\\\\\")\n\n}\n\n\n", "file_path": "src/gens/php/mod.rs", "rank": 43, "score": 338792.9863421107 }, { "content": "fn namespace_path(namespace: &Namespace) -> Option<String> {\n\n if namespace.parts.is_empty() {\n\n None\n\n } else {\n\n Some(\n\n namespace\n\n .parts\n\n .iter()\n\n .map(|name| name.camel_case(conv))\n\n .collect::<Vec<_>>()\n\n .join(\".\"),\n\n )\n\n }\n\n}\n\n\n", "file_path": "src/gens/haskell/mod.rs", "rank": 44, "score": 326448.43165360397 }, { "content": "fn namespace_path(namespace: &Namespace) -> Option<String> {\n\n if namespace.parts.is_empty() {\n\n None\n\n } else {\n\n Some(\n\n namespace\n\n .parts\n\n .iter()\n\n .map(|name| name.snake_case(conv))\n\n .collect::<Vec<_>>()\n\n .join(\"/\"),\n\n )\n\n }\n\n}\n\n\n", "file_path": "src/gens/go/mod.rs", "rank": 45, "score": 326448.43165360397 }, { "content": "fn namespace_path(namespace: &Namespace) -> Option<String> {\n\n if namespace.parts.is_empty() {\n\n None\n\n } else {\n\n Some(\n\n namespace\n\n .parts\n\n .iter()\n\n .map(|name| name.snake_case(conv))\n\n .collect::<Vec<_>>()\n\n .join(\".\"),\n\n )\n\n }\n\n}\n\n\n", "file_path": "src/gens/kotlin/mod.rs", "rank": 46, "score": 326448.43165360397 }, { "content": "fn namespace_path(namespace: &Namespace) -> Option<String> {\n\n if namespace.parts.is_empty() {\n\n None\n\n } else {\n\n Some(\n\n namespace\n\n .parts\n\n .iter()\n\n .map(|name| name.snake_case(conv))\n\n .collect::<Vec<_>>()\n\n .join(\".\"),\n\n )\n\n }\n\n}\n\n\n", "file_path": "src/gens/scala/mod.rs", "rank": 47, "score": 326448.43165360397 }, { "content": "fn namespace_path(namespace: &Namespace) -> Option<String> {\n\n if namespace.parts.is_empty() {\n\n None\n\n } else {\n\n Some(\n\n namespace\n\n .parts\n\n .iter()\n\n .map(|name| name.snake_case(conv))\n\n .collect::<Vec<_>>()\n\n .join(\"::\"),\n\n )\n\n }\n\n}\n\n\n", "file_path": "src/gens/cpp/mod.rs", "rank": 48, "score": 326448.43165360397 }, { "content": "fn namespace_path(namespace: &Namespace) -> Option<String> {\n\n if namespace.parts.is_empty() {\n\n None\n\n } else {\n\n Some(\n\n namespace\n\n .parts\n\n .iter()\n\n .map(|name| name.snake_case(conv))\n\n .collect::<Vec<_>>()\n\n .join(\".\"),\n\n )\n\n }\n\n}\n\n\n", "file_path": "src/gens/dlang/mod.rs", "rank": 49, "score": 326448.43165360397 }, { "content": "fn namespace_path(namespace: &Namespace) -> Option<String> {\n\n if namespace.parts.is_empty() {\n\n None\n\n } else {\n\n Some(\n\n namespace\n\n .parts\n\n .iter()\n\n .map(|name| name.snake_case(conv))\n\n .collect::<Vec<_>>()\n\n .join(\".\"),\n\n )\n\n }\n\n}\n\n\n", "file_path": "src/gens/java/mod.rs", "rank": 50, "score": 326448.43165360397 }, { "content": "pub fn read_tag<T>() -> String {\n\n format!(\"Failed to read tag of {}\", tynm::type_name::<T>())\n\n}\n\n\n", "file_path": "trans/src/error_format.rs", "rank": 51, "score": 323675.33385288087 }, { "content": "fn doc_write_to(name: &str) -> String {\n\n format!(\"# Write {} to output stream\", name)\n\n}\n\n\n", "file_path": "src/gens/ruby/mod.rs", "rank": 52, "score": 318238.272453012 }, { "content": "fn doc_write_to(name: &str) -> String {\n\n format!(\"// Write {} to writer\", name)\n\n}\n\n\n", "file_path": "src/gens/go/mod.rs", "rank": 53, "score": 318238.27245301194 }, { "content": "fn doc_write_to(name: &str) -> String {\n\n format!(\"/**\\n * Write {} to output stream\\n */\", name)\n\n}\n\n\n", "file_path": "src/gens/java/mod.rs", "rank": 55, "score": 318238.272453012 }, { "content": "fn doc_write_to(name: &str) -> String {\n\n format!(\"/**\\n * Write {} to output stream\\n */\", name)\n\n}\n\n\n", "file_path": "src/gens/scala/mod.rs", "rank": 56, "score": 318238.27245301194 }, { "content": "fn doc_write_to(name: &str) -> String {\n\n format!(\"/// Write {} to writer\", name)\n\n}\n\n\n", "file_path": "src/gens/dlang/mod.rs", "rank": 57, "score": 318238.27245301194 }, { "content": "fn doc_write_to(name: &str) -> String {\n\n format!(\"/// Write {} to writer\", name)\n\n}\n\n\n", "file_path": "src/gens/fsharp/mod.rs", "rank": 58, "score": 318238.272453012 }, { "content": "fn doc_write_to(name: &str) -> String {\n\n format!(\"/**\\n * Write {} to output stream\\n */\", name)\n\n}\n\n\n", "file_path": "src/gens/kotlin/mod.rs", "rank": 59, "score": 318238.272453012 }, { "content": "fn doc_write_to(name: &str) -> String {\n\n format!(\"/**\\n * Write {} to output stream\\n */\", name)\n\n}\n\n\n", "file_path": "src/gens/javascript/mod.rs", "rank": 60, "score": 318238.27245301194 }, { "content": "fn doc_write_to(name: &str) -> String {\n\n format!(\"\\\"\\\"\\\"Write {} to output stream\\n\\\"\\\"\\\"\", name)\n\n}\n\n\n", "file_path": "src/gens/python/mod.rs", "rank": 61, "score": 318238.272453012 }, { "content": "fn doc_write_to(name: &str) -> String {\n\n format!(\"/// Write {} to output stream\", name)\n\n}\n\n\n", "file_path": "src/gens/swift/mod.rs", "rank": 62, "score": 318238.272453012 }, { "content": "fn doc_write_to(name: &str) -> String {\n\n format!(\"/**\\n * Write {} to output stream\\n */\", name)\n\n}\n\n\n", "file_path": "src/gens/typescript/mod.rs", "rank": 63, "score": 318238.27245301194 }, { "content": "fn doc_write_to(name: &str) -> String {\n\n format!(\"/**\\n * Write {} to output stream\\n */\", name)\n\n}\n\n\n", "file_path": "src/gens/php/mod.rs", "rank": 64, "score": 318238.27245301194 }, { "content": "fn doc_read_from(name: &str) -> String {\n\n format!(\"# Read {} from input stream\", name)\n\n}\n\n\n", "file_path": "src/gens/ruby/mod.rs", "rank": 65, "score": 318218.9903025941 }, { "content": "fn doc_read_from(name: &str) -> String {\n\n format!(\"/// Read {} from reader\", name)\n\n}\n\n\n", "file_path": "src/gens/dlang/mod.rs", "rank": 66, "score": 318218.9903025941 }, { "content": "fn doc_read_from(name: &str) -> String {\n\n format!(\"/**\\n * Read {} from input stream\\n */\", name)\n\n}\n\n\n", "file_path": "src/gens/javascript/mod.rs", "rank": 67, "score": 318218.9903025941 }, { "content": "fn doc_read_from(name: &str) -> String {\n\n format!(\"/**\\n * Read {} from input stream\\n */\", name)\n\n}\n\n\n", "file_path": "src/gens/java/mod.rs", "rank": 68, "score": 318218.9903025941 }, { "content": "fn doc_read_from(name: &str) -> String {\n\n format!(\"/// Read {} from reader\", name)\n\n}\n\n\n", "file_path": "src/gens/fsharp/mod.rs", "rank": 69, "score": 318218.9903025941 }, { "content": "fn doc_read_from(name: &str) -> String {\n\n format!(\"/**\\n * Read {} from input stream\\n */\", name)\n\n}\n\n\n", "file_path": "src/gens/scala/mod.rs", "rank": 70, "score": 318218.9903025941 }, { "content": "fn doc_read_from(name: &str) -> String {\n\n format!(\"\\\"\\\"\\\"Read {} from input stream\\n\\\"\\\"\\\"\", name)\n\n}\n\n\n", "file_path": "src/gens/python/mod.rs", "rank": 71, "score": 318218.9903025941 }, { "content": "fn doc_read_from(name: &str) -> String {\n\n format!(\"// Read {} from reader\", name)\n\n}\n\n\n", "file_path": "src/gens/go/mod.rs", "rank": 73, "score": 318218.9903025941 }, { "content": "fn doc_read_from(name: &str) -> String {\n\n format!(\"/**\\n * Read {} from input stream\\n */\", name)\n\n}\n\n\n", "file_path": "src/gens/php/mod.rs", "rank": 74, "score": 318218.9903025941 }, { "content": "fn doc_read_from(name: &str) -> String {\n\n format!(\"/// Read {} from input stream\", name)\n\n}\n\n\n", "file_path": "src/gens/swift/mod.rs", "rank": 75, "score": 318218.9903025941 }, { "content": "fn doc_read_from(name: &str) -> String {\n\n format!(\"/**\\n * Read {} from input stream\\n */\", name)\n\n}\n\n\n", "file_path": "src/gens/typescript/mod.rs", "rank": 76, "score": 318218.9903025941 }, { "content": "fn doc_read_from(name: &str) -> String {\n\n format!(\"/**\\n * Read {} from input stream\\n */\", name)\n\n}\n\n\n", "file_path": "src/gens/kotlin/mod.rs", "rank": 77, "score": 318218.9903025941 }, { "content": "pub fn test_serde_eq<T: Trans + std::fmt::Debug + PartialEq>(version: &Version, value: &T) {\n\n let serded: T = deserialize(\n\n version,\n\n &serialize(version, value).expect(\"Failed to serialize\"),\n\n )\n\n .expect(\"Failed to deserialize\");\n\n assert_eq!(*value, serded);\n\n}\n\n\n", "file_path": "trans/src/test_utils.rs", "rank": 78, "score": 307756.73546822526 }, { "content": "fn namespace_path_for(schema: &Schema) -> String {\n\n match schema {\n\n Schema::Struct { namespace, .. }\n\n | Schema::OneOf { namespace, .. }\n\n | Schema::Enum { namespace, .. } => {\n\n namespace_path(namespace).unwrap_or(\"common\".to_owned())\n\n }\n\n _ => unreachable!(),\n\n }\n\n}\n\n\n", "file_path": "src/gens/go/mod.rs", "rank": 79, "score": 304372.2061007936 }, { "content": "fn file_path(schema: &Schema) -> String {\n\n module_name(schema).replace('.', \"/\")\n\n}\n\n\n", "file_path": "src/gens/haskell/mod.rs", "rank": 80, "score": 304372.2061007936 }, { "content": "fn read_var(schema: &Schema) -> String {\n\n include_templing!(\"src/gens/fsharp/read_var.templing\")\n\n}\n\n\n", "file_path": "src/gens/fsharp/mod.rs", "rank": 81, "score": 303713.4929666894 }, { "content": "fn file_name(schema: &Schema) -> String {\n\n match schema {\n\n Schema::Enum {\n\n namespace,\n\n base_name: name,\n\n ..\n\n }\n\n | Schema::Struct {\n\n namespace,\n\n definition: Struct { name, .. },\n\n ..\n\n }\n\n | Schema::OneOf {\n\n namespace,\n\n base_name: name,\n\n ..\n\n } => format!(\n\n \"{}/{}\",\n\n namespace_path(namespace).unwrap_or(\"common\".to_owned()),\n\n name.snake_case(conv),\n", "file_path": "src/gens/go/mod.rs", "rank": 82, "score": 303664.65483424504 }, { "content": "fn file_name(schema: &Schema) -> String {\n\n name_path(schema).replace(\"::\", \"/\")\n\n}\n\n\n\nimpl Generator {\n\n fn type_name(&self, schema: &Schema) -> String {\n\n match schema {\n\n Schema::Bool => \"bool\".to_owned(),\n\n Schema::Int32 => \"int\".to_owned(),\n\n Schema::Int64 => \"long long\".to_owned(),\n\n Schema::Float32 => \"float\".to_owned(),\n\n Schema::Float64 => \"double\".to_owned(),\n\n Schema::String => \"std::string\".to_owned(),\n\n Schema::OneOf { .. } => format!(\"std::shared_ptr<{}>\", name_path(schema)),\n\n Schema::Struct { .. } | Schema::Enum { .. } => name_path(schema),\n\n Schema::Option(inner) => {\n\n if self.options.cxx_standard >= 17 {\n\n format!(\"std::optional<{}>\", self.type_name(inner))\n\n } else {\n\n format!(\"std::shared_ptr<{}>\", self.type_name(inner))\n", "file_path": "src/gens/cpp/mod.rs", "rank": 83, "score": 303664.65483424504 }, { "content": "fn file_name(schema: &Schema) -> String {\n\n schema\n\n .namespace()\n\n .unwrap()\n\n .parts\n\n .iter()\n\n .chain(std::iter::once(schema.name().unwrap()))\n\n .map(|name| name.camel_case(conv))\n\n .collect::<Vec<String>>()\n\n .join(\"/\")\n\n}\n\n\n", "file_path": "src/gens/php/mod.rs", "rank": 84, "score": 303664.65483424504 }, { "content": "fn file_name(schema: &Schema) -> String {\n\n match schema {\n\n Schema::Enum {\n\n namespace,\n\n base_name: name,\n\n ..\n\n }\n\n | Schema::Struct {\n\n namespace,\n\n definition: Struct { name, .. },\n\n ..\n\n }\n\n | Schema::OneOf {\n\n namespace,\n\n base_name: name,\n\n ..\n\n } => match namespace_path(namespace) {\n\n None => name.camel_case(conv),\n\n Some(path) => format!(\"{}/{}\", path.replace('.', \"/\"), name.camel_case(conv)),\n\n },\n\n _ => unreachable!(),\n\n }\n\n}\n\n\n", "file_path": "src/gens/kotlin/mod.rs", "rank": 85, "score": 303664.65483424504 }, { "content": "fn type_name(schema: &Schema) -> String {\n\n match schema {\n\n Schema::Bool => \"bool\".to_owned(),\n\n Schema::Int32 | Schema::Int64 | Schema::Enum { .. } => \"int\".to_owned(),\n\n Schema::Float32 | Schema::Float64 => \"float\".to_owned(),\n\n Schema::String => \"string\".to_owned(),\n\n Schema::Struct { .. } | Schema::OneOf { .. } => class_name(schema),\n\n Schema::Vec(_) | Schema::Map(_, _) => \"array\".to_owned(),\n\n Schema::Option(inner) => format!(\"?{}\", type_name(inner)),\n\n }\n\n}\n\n\n", "file_path": "src/gens/php/mod.rs", "rank": 86, "score": 303664.65483424504 }, { "content": "fn type_name(schema: &Schema) -> String {\n\n match schema {\n\n Schema::Bool => \"boolean\".to_owned(),\n\n Schema::Int32 => \"number\".to_owned(),\n\n Schema::Int64 => \"bigint\".to_owned(),\n\n Schema::Float32 => \"number\".to_owned(),\n\n Schema::Float64 => \"number\".to_owned(),\n\n Schema::String => \"string\".to_owned(),\n\n Schema::Option(inner) => format!(\"{} | null\", type_name(inner)),\n\n Schema::Struct {\n\n definition: Struct { name, .. },\n\n ..\n\n } => name.camel_case(conv),\n\n Schema::OneOf { base_name, .. } => base_name.camel_case(conv),\n\n Schema::Vec(inner) => format!(\"Array<{}>\", type_name(inner)),\n\n Schema::Map(key_type, value_type) => {\n\n format!(\"Map<{}, {}>\", type_name(key_type), type_name(value_type))\n\n }\n\n Schema::Enum { base_name, .. } => base_name.camel_case(conv),\n\n }\n\n}\n\n\n", "file_path": "src/gens/typescript/mod.rs", "rank": 87, "score": 303664.65483424504 }, { "content": "fn type_name(schema: &Schema) -> String {\n\n match schema {\n\n Schema::Bool => \"Bool\".to_owned(),\n\n Schema::Int32 => \"Int32\".to_owned(),\n\n Schema::Int64 => \"Int64\".to_owned(),\n\n Schema::Float32 => \"Float\".to_owned(),\n\n Schema::Float64 => \"Double\".to_owned(),\n\n Schema::String => \"String\".to_owned(),\n\n Schema::Struct {\n\n definition: Struct { name, .. },\n\n ..\n\n }\n\n | Schema::OneOf {\n\n base_name: name, ..\n\n }\n\n | Schema::Enum {\n\n base_name: name, ..\n\n } => format!(\"{}\", name.camel_case(conv)),\n\n Schema::Option(inner) => format!(\"Maybe {}\", type_name(inner)),\n\n Schema::Vec(inner) => format!(\"[{}]\", type_name(inner)),\n\n Schema::Map(key, value) => format!(\"Map {} {}\", type_name(key), type_name(value)),\n\n }\n\n}\n\n\n", "file_path": "src/gens/haskell/mod.rs", "rank": 88, "score": 303664.65483424504 }, { "content": "fn type_name(schema: &Schema) -> String {\n\n format!(\"{}{}\", type_name_prearray(schema), type_post_array(schema))\n\n}\n\n\n", "file_path": "src/gens/fsharp/mod.rs", "rank": 89, "score": 303664.65483424504 }, { "content": "fn file_name(schema: &Schema) -> String {\n\n match schema {\n\n Schema::Enum {\n\n namespace,\n\n base_name: name,\n\n ..\n\n }\n\n | Schema::Struct {\n\n namespace,\n\n definition: Struct { name, .. },\n\n ..\n\n }\n\n | Schema::OneOf {\n\n namespace,\n\n base_name: name,\n\n ..\n\n } => match namespace_path(namespace) {\n\n None => name.camel_case(conv),\n\n Some(path) => format!(\"{}/{}\", path.replace('.', \"/\"), name.camel_case(conv)),\n\n },\n", "file_path": "src/gens/java/mod.rs", "rank": 90, "score": 303664.65483424504 }, { "content": "fn file_name(schema: &Schema) -> String {\n\n let mut result = String::new();\n\n for part in schema\n\n .namespace()\n\n .unwrap()\n\n .parts\n\n .iter()\n\n .chain(std::iter::once(schema.name().unwrap()))\n\n {\n\n if !result.is_empty() {\n\n result.push('/');\n\n }\n\n result.push_str(&part.snake_case(conv).replace('_', \"-\"));\n\n }\n\n result\n\n}\n\n\n\nimpl Generator {\n\n fn add_only(&mut self, schema: &Schema) -> anyhow::Result<()> {\n\n match schema {\n", "file_path": "src/gens/javascript/mod.rs", "rank": 91, "score": 303664.65483424504 }, { "content": "fn type_name(schema: &Schema) -> String {\n\n match schema {\n\n Schema::Bool => \"Bool\".to_owned(),\n\n Schema::Int32 => \"Int32\".to_owned(),\n\n Schema::Int64 => \"Int64\".to_owned(),\n\n Schema::Float32 => \"Float\".to_owned(),\n\n Schema::Float64 => \"Double\".to_owned(),\n\n Schema::String => \"String\".to_owned(),\n\n Schema::Struct {\n\n definition: Struct { name, .. },\n\n ..\n\n }\n\n | Schema::OneOf {\n\n base_name: name, ..\n\n }\n\n | Schema::Enum {\n\n base_name: name, ..\n\n } => name.camel_case(conv),\n\n Schema::Option(inner) => format!(\"{}?\", type_name(inner)),\n\n Schema::Vec(inner) => format!(\"[{}]\", type_name(inner)),\n\n Schema::Map(key, value) => format!(\"[{}: {}]\", type_name(key), type_name(value)),\n\n }\n\n}\n\n\n", "file_path": "src/gens/swift/mod.rs", "rank": 92, "score": 303664.65483424504 }, { "content": "fn type_name(schema: &Schema) -> String {\n\n match schema {\n\n Schema::Bool => \"bool\".to_owned(),\n\n Schema::Int32 => \"int\".to_owned(),\n\n Schema::Int64 => \"long\".to_owned(),\n\n Schema::Float32 => \"float\".to_owned(),\n\n Schema::Float64 => \"double\".to_owned(),\n\n Schema::String => \"string\".to_owned(),\n\n Schema::Struct {\n\n namespace,\n\n definition: Struct { name, .. },\n\n ..\n\n }\n\n | Schema::OneOf {\n\n namespace,\n\n base_name: name,\n\n ..\n\n }\n\n | Schema::Enum {\n\n namespace,\n", "file_path": "src/gens/dlang/mod.rs", "rank": 93, "score": 303664.65483424504 }, { "content": "fn type_name(schema: &Schema) -> String {\n\n match schema {\n\n Schema::Bool => \"bool\".to_owned(),\n\n Schema::Int32 => \"int32\".to_owned(),\n\n Schema::Int64 => \"int64\".to_owned(),\n\n Schema::Float32 => \"float32\".to_owned(),\n\n Schema::Float64 => \"float64\".to_owned(),\n\n Schema::String => \"string\".to_owned(),\n\n Schema::Struct {\n\n definition: Struct { name, .. },\n\n ..\n\n }\n\n | Schema::OneOf {\n\n base_name: name, ..\n\n }\n\n | Schema::Enum {\n\n base_name: name, ..\n\n } => name.camel_case(conv),\n\n Schema::Option(inner) => format!(\"*{}\", type_name(inner)),\n\n Schema::Vec(inner) => format!(\"[]{}\", type_name(inner)),\n\n Schema::Map(key, value) => format!(\"map[{}]{}\", type_name(key), type_name(value),),\n\n }\n\n}\n\n\n", "file_path": "src/gens/go/mod.rs", "rank": 94, "score": 303664.65483424504 }, { "content": "fn file_name(schema: &Schema) -> String {\n\n schema\n\n .namespace()\n\n .unwrap()\n\n .parts\n\n .iter()\n\n .chain(std::iter::once(schema.name().unwrap()))\n\n .map(|name| name.camel_case(conv))\n\n .collect::<Vec<String>>()\n\n .join(\"/\")\n\n}\n\n\n\nimpl crate::Generator for Generator {\n\n const NAME: &'static str = \"Swift\";\n\n type Options = ();\n\n fn new(name: &str, _version: &str, _: ()) -> Self {\n\n let name = Name::new(name.to_owned());\n\n let mut files = HashMap::new();\n\n let package_name = name.camel_case(conv);\n\n let package_name = &package_name;\n", "file_path": "src/gens/swift/mod.rs", "rank": 95, "score": 303664.65483424504 }, { "content": "fn file_name(schema: &Schema) -> String {\n\n let mut result = String::new();\n\n for part in schema\n\n .namespace()\n\n .unwrap()\n\n .parts\n\n .iter()\n\n .chain(std::iter::once(schema.name().unwrap()))\n\n {\n\n if !result.is_empty() {\n\n result.push('/');\n\n }\n\n result.push_str(&part.snake_case(conv).replace('_', \"-\"));\n\n }\n\n result\n\n}\n\n\n\nimpl Generator {\n\n fn add_only(&mut self, schema: &Schema) -> anyhow::Result<()> {\n\n match schema {\n", "file_path": "src/gens/typescript/mod.rs", "rank": 96, "score": 303664.65483424504 }, { "content": "fn file_name(schema: &Schema) -> String {\n\n schema\n\n .namespace()\n\n .unwrap()\n\n .parts\n\n .iter()\n\n .chain(std::iter::once(schema.name().unwrap()))\n\n .map(|name| name.snake_case(conv))\n\n .collect::<Vec<String>>()\n\n .join(\"/\")\n\n}\n\n\n", "file_path": "src/gens/ruby/mod.rs", "rank": 97, "score": 303664.65483424504 }, { "content": "fn file_name(schema: &Schema) -> String {\n\n match schema {\n\n Schema::Enum {\n\n namespace,\n\n base_name: name,\n\n ..\n\n }\n\n | Schema::Struct {\n\n namespace,\n\n definition: Struct { name, .. },\n\n ..\n\n }\n\n | Schema::OneOf {\n\n namespace,\n\n base_name: name,\n\n ..\n\n } => match namespace_path(namespace) {\n\n Some(path) => format!(\"{}/{}\", path.replace('.', \"/\"), name.snake_case(conv)),\n\n None => name.snake_case(conv),\n\n },\n\n _ => unreachable!(),\n\n }\n\n}\n\n\n", "file_path": "src/gens/dlang/mod.rs", "rank": 99, "score": 303664.65483424504 } ]
Rust
src/rust/grapl-observe/src/statsd_formatter.rs
alexjmacdonald/grapl
44d5fcabef02d11548018742c3dc00785ca7b571
use crate::metric_error::MetricError; use crate::metric_error::MetricError::{MetricInvalidCharacterError, MetricInvalidSampleRateError}; use crate::metric_reporter::TagPair; use lazy_static::lazy_static; use regex::Regex; use std::fmt::Write; lazy_static! { static ref INVALID_CHARS: Regex = Regex::new("[|#,=:]").unwrap(); } pub fn reject_invalid_chars(s: &str) -> Result<(), MetricError> { let matched = INVALID_CHARS.is_match(s); if matched { Err(MetricInvalidCharacterError()) } else { Ok(()) } } pub enum MetricType { Gauge, Counter, Histogram, } const GAUGE_STR: &'static str = "g"; const COUNTER_STR: &'static str = "c"; const HISTOGRAM_STR: &'static str = "h"; impl MetricType { fn statsd_type(&self) -> &'static str { match self { MetricType::Gauge => GAUGE_STR, MetricType::Counter => COUNTER_STR, MetricType::Histogram => HISTOGRAM_STR, } } } /** Don't call statsd_format directly; instead, prefer the public functions of MetricClient. To go from a formatted string to usable data again, use the 'statsd-parser' crate. */ #[allow(dead_code)] pub fn statsd_format( buf: &mut String, metric_name: &str, value: f64, metric_type: MetricType, sample_rate: impl Into<Option<f64>>, tags: &[TagPair], ) -> Result<(), MetricError> { buf.clear(); reject_invalid_chars(metric_name)?; write!( buf, "{metric_name}:{value}|{metric_type}", metric_name = metric_name, value = value, metric_type = metric_type.statsd_type() )?; match (metric_type, sample_rate.into()) { (MetricType::Counter, Some(rate)) => { if rate >= 0.0 && rate < 1.0 { write!(buf, "|@{sample_rate}", sample_rate = rate)?; } else { return Err(MetricInvalidSampleRateError()); } } _ => {} } let mut first_tag: bool = true; if !tags.is_empty() { write!(buf, "|#")?; for pair in tags { if !first_tag { write!(buf, ",")?; } else { first_tag = false; } pair.write_to_buf(buf)?; } } Ok(()) } #[cfg(test)] mod tests { use crate::metric_error::MetricError; use crate::statsd_formatter::{reject_invalid_chars, statsd_format, MetricType, TagPair}; const INVALID_STRS: [&str; 5] = [ "some|metric", "some#metric", "some,metric", "some:metric", "some=metric", ]; const VALID_STR: &str = "some_str"; const VALID_VALUE: f64 = 12345.6; fn make_tags() -> Vec<TagPair<'static>> { vec![ TagPair("some_key", "some_value"), TagPair("some_key_2", "some_value_2"), ] } fn make_empty_tags() -> [TagPair<'static>; 0] { let empty_slice: [TagPair<'static>; 0] = []; return empty_slice; } #[test] fn test_reject_invalid_chars() -> Result<(), String> { for invalid_str in INVALID_STRS.iter() { let result = reject_invalid_chars(invalid_str); match result.expect_err("else panic") { MetricError::MetricInvalidCharacterError() => Ok(()), _ => Err(String::from("expected invalid character error")), }? } assert!(reject_invalid_chars(VALID_STR).is_ok()); Ok(()) } #[test] fn test_statsd_format_basic_counter() -> Result<(), MetricError> { let mut buf: String = String::with_capacity(256); statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, None, &make_empty_tags(), )?; assert_eq!(buf, "some_str:12345.6|c"); Ok(()) } #[test] fn test_statsd_format_specify_rate() -> Result<(), MetricError> { let mut buf: String = String::with_capacity(256); statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, 0.5, &make_empty_tags(), )?; assert_eq!(buf, "some_str:12345.6|c|@0.5"); Ok(()) } #[test] fn test_statsd_format_specify_bad_rate() -> Result<(), String> { let mut buf: String = String::with_capacity(256); let result = statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, 1.5, &make_empty_tags(), ); match result.expect_err("") { MetricError::MetricInvalidSampleRateError() => Ok(()), _ => Err(String::from("unexpected err")), } } #[test] fn test_statsd_format_tags() -> Result<(), MetricError> { let mut buf: String = String::with_capacity(256); statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, None, &make_tags(), )?; assert_eq!( buf, "some_str:12345.6|c|#some_key:some_value,some_key_2:some_value_2" ); Ok(()) } #[test] fn test_statsd_format_bad_tags() -> Result<(), String> { let mut buf: String = String::with_capacity(256); let result = statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, None, &[TagPair("some|key", "val")], ); match result.expect_err("") { MetricError::MetricInvalidCharacterError() => Ok(()), _ => Err(String::from("unexpected err")), } } }
use crate::metric_error::MetricError; use crate::metric_error::MetricError::{MetricInvalidCharacterError, MetricInvalidSampleRateError}; use crate::metric_reporter::TagPair; use lazy_static::lazy_static; use regex::Regex; use std::fmt::Write; lazy_static! { static ref INVALID_CHARS: Regex = Regex::new("[|#,=:]").unwrap(); } pub fn reject_invalid_chars(s: &str) -> Result<(), MetricError> { let matched = INVALID_CHARS.is_match(s); if matched { Err(MetricInvalidCharacterError()) } else { Ok(()) } } pub enum MetricType { Gauge, Counter, Histogram, } const GAUGE_STR: &'static str = "g"; const COUNTER_STR: &'static str = "c"; const HISTOGRAM_STR: &'static str = "h"; impl MetricType { fn statsd_type(&self) -> &'static str { match self { MetricType::Gauge => GAUGE_STR, MetricType::Counter => COUNTER_STR, MetricType::Histogram => HISTOGRAM_STR, } } } /** Don't call statsd_format directly; instead, prefer the public functions of MetricClient. To go from a formatted string to usable data again, use the 'statsd-parser' crate. */ #[allow(dead_code)] pub fn statsd_format( buf: &mut String, metric_name: &str, value: f64, metric_type: MetricType, sample_rate: impl Into<Option<f64>>, tags: &[TagPair], ) -> Result<(), MetricError> { buf.clear(); reject_invalid_chars(metric_name)?; write!( buf, "{metric_name}:{value}|{metric_type}", metric_name = metric_name, value = value, metric_type = metric_type.statsd_type() )?; match (metric_type, sample_rate.into()) { (MetricType::Counter, Some(rate)) => { if rate >= 0.0 && rate < 1.0 { write!(buf, "|@{sample_rate}", sample_rate = rate)?; } else { return Err(MetricInvalidSampleRateError()); } } _ => {} } let mut first_tag: bool = true; if !tags.is_empty() { write!(buf, "|#")?; for pair in tags { if !first_tag { write!(buf, ",")?; } else { first_tag = false; } pair.write_to_buf(buf)?; } } Ok(()) } #[cfg(test)] mod tests { use crate::metric_error::MetricError; use crate::statsd_formatter::{reject_invalid_chars, statsd_format, MetricType, TagPair}; const INVALID_STRS: [&str; 5] = [ "some|metric", "some#metric", "some,metric", "some:metric", "some=metric", ]; const VALID_STR: &str = "some_str"; const VALID_VALUE: f64 = 12345.6; fn make_tags() -> Vec<TagPair<'static>> { vec![ TagPair("some_key", "some_value"), TagPair("some_key_2", "some_value_2"), ] } fn make_empty_tags() -> [TagPair<'static>; 0] { let empty_slice: [TagPair<'static>; 0] = []; return empty_slice; } #[test] fn test_reject_invalid_chars() -> Result<(), String> { for invalid_str in INVALID_STRS.iter() { let result = reject_invalid_chars(invalid_str); match result.expect_err("else panic") { MetricError::MetricInvalidCharacterError() => Ok(()), _ => Err(String::from("expected invalid character error")), }? } assert!(reject_invalid_chars(VALID_STR).is_ok()); Ok(()) } #[test] fn test_statsd_format_basic_counter() -> Result<(), MetricError> { let mut buf: String = String::with_capacity(256); statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, None, &make_empty_tags(), )?; assert_eq!(buf, "some_str:12345.6|c"); Ok(()) } #[test] fn test_statsd_format_specify_rate() -> Result<(), MetricError> { let mut buf: String = String::with_capacity(256); statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, 0.5, &make_empty_tags(), )?; assert_eq!(buf, "some_str:12345.6|c|@0.5"); Ok(()) } #[test]
#[test] fn test_statsd_format_tags() -> Result<(), MetricError> { let mut buf: String = String::with_capacity(256); statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, None, &make_tags(), )?; assert_eq!( buf, "some_str:12345.6|c|#some_key:some_value,some_key_2:some_value_2" ); Ok(()) } #[test] fn test_statsd_format_bad_tags() -> Result<(), String> { let mut buf: String = String::with_capacity(256); let result = statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, None, &[TagPair("some|key", "val")], ); match result.expect_err("") { MetricError::MetricInvalidCharacterError() => Ok(()), _ => Err(String::from("unexpected err")), } } }
fn test_statsd_format_specify_bad_rate() -> Result<(), String> { let mut buf: String = String::with_capacity(256); let result = statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, 1.5, &make_empty_tags(), ); match result.expect_err("") { MetricError::MetricInvalidSampleRateError() => Ok(()), _ => Err(String::from("unexpected err")), } }
function_block-full_function
[ { "content": "/// Converts a Sysmon UTC string to UNIX Epoch time\n\n///\n\n/// If the provided string is not parseable as a UTC timestamp, an error is returned.\n\npub fn utc_to_epoch(utc: &str) -> Result<u64, Error> {\n\n let dt = NaiveDateTime::parse_from_str(utc, \"%Y-%m-%d %H:%M:%S%.3f\")?;\n\n\n\n let dt: DateTime<Utc> = DateTime::from_utc(dt, Utc);\n\n let ts = dt.timestamp_millis();\n\n\n\n if ts < 0 {\n\n bail!(\"Timestamp is negative\")\n\n }\n\n\n\n if ts < 1_000_000_000_000 {\n\n Ok(ts as u64 * 1000)\n\n } else {\n\n Ok(ts as u64)\n\n }\n\n}\n", "file_path": "src/rust/sysmon-subgraph-generator/src/models/mod.rs", "rank": 1, "score": 306591.35412332066 }, { "content": "fn base64_decode_raw_log_to_gzip(data: &str) -> Result<Vec<u8>, MetricForwarderError> {\n\n use base64::decode;\n\n\n\n decode(data).map_err(|err| DecodeBase64Error(err.to_string()))\n\n}\n\n\n", "file_path": "src/rust/metric-forwarder/src/deser_logs_data.rs", "rank": 2, "score": 299506.2671077266 }, { "content": "fn gunzip_to_string(gzipped: Vec<u8>) -> Result<String, MetricForwarderError> {\n\n use flate2::read::GzDecoder;\n\n use std::io::Read;\n\n\n\n let mut raw_data = String::new();\n\n match GzDecoder::new(gzipped.as_slice()).read_to_string(&mut raw_data) {\n\n Ok(_) => Ok(raw_data),\n\n Err(err) => Err(GunzipToStringError(err.to_string())),\n\n }\n\n}\n\n\n", "file_path": "src/rust/metric-forwarder/src/deser_logs_data.rs", "rank": 3, "score": 294228.3187102517 }, { "content": "pub fn filter_invalid_stats(parsed_stats: Vec<Result<Stat, MetricForwarderError>>) -> Vec<Stat> {\n\n parsed_stats\n\n .into_par_iter()\n\n .filter_map(|stat_res| match stat_res {\n\n Ok(stat) => Some(stat),\n\n Err(e) => {\n\n warn!(\"Dropped metric: {}\", e);\n\n None\n\n }\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "src/rust/metric-forwarder/src/cloudwatch_send.rs", "rank": 4, "score": 282407.44550769555 }, { "content": "pub fn parse_logs(logs_data: CloudwatchLogsData) -> Vec<Result<Stat, MetricForwarderError>> {\n\n /*\n\n Parse the incoming, raw logs into a platform-agnostic Stat type.\n\n */\n\n logs_data\n\n .log_events\n\n .par_iter()\n\n .filter_map(|logs_log_event: &CloudwatchLogsLogEvent| logs_log_event.message.as_ref())\n\n .map(|s| parse_log(s))\n\n .collect()\n\n}\n\n\n", "file_path": "src/rust/metric-forwarder/src/cloudwatch_logs_parse.rs", "rank": 5, "score": 273857.5426411537 }, { "content": "pub fn mg_alphas() -> Vec<String> {\n\n return std::env::var(\"MG_ALPHAS\")\n\n .expect(\"MG_ALPHAS\")\n\n .split(',')\n\n .map(str::to_string)\n\n .collect();\n\n}\n\n\n", "file_path": "src/rust/grapl-config/src/lib.rs", "rank": 6, "score": 255066.75897182385 }, { "content": "pub fn parse_log(log_str: &str) -> Result<Stat, MetricForwarderError> {\n\n /*\n\n The input will look like\n\n MONITORING|timestamp|statsd|stuff|goes|here\\n\n\n */\n\n let split: Vec<&str> = log_str.trim_end().splitn(4, MONITORING_DELIM).collect();\n\n match &split[..] {\n\n [_monitoring, service_name, timestamp, statsd_component] => {\n\n let statsd_msg = statsd_parser::parse(statsd_component.to_string());\n\n statsd_msg\n\n .map(|msg| Stat {\n\n msg: msg,\n\n timestamp: timestamp.to_string(),\n\n service_name: service_name.to_string(),\n\n })\n\n .map_err(|parse_err| {\n\n MetricForwarderError::ParseStringToStatsdError(\n\n parse_err.to_string(),\n\n log_str.to_string(),\n\n )\n", "file_path": "src/rust/metric-forwarder/src/cloudwatch_logs_parse.rs", "rank": 7, "score": 254953.08226416228 }, { "content": "fn parse_string_to_logsdata(gunzipped: String) -> Result<CloudwatchLogsData, MetricForwarderError> {\n\n use serde_json::from_str;\n\n\n\n from_str(&gunzipped).map_err(|err| ParseStringToLogsdataError(err.to_string()))\n\n}\n\n\n", "file_path": "src/rust/metric-forwarder/src/deser_logs_data.rs", "rank": 8, "score": 252748.51524200893 }, { "content": "/// A nice simplification of our Metric Forwarder is that:\n\n/// since we process things per-log-group,\n\n/// and one log group only has things from one service\n\n/// ---> each execution of this lambda will only be dealing with 1 namespace.\n\n/// We simply assert this invariant in this function.\n\n/// A more robust way would be to group by namespace, but, eh, not needed for us\n\npub fn get_namespace(stats: &[Stat]) -> Result<String, MetricForwarderError> {\n\n if let Some(first) = stats.get(0) {\n\n let expected_namespace = first.service_name.clone();\n\n let find_different_namespace = stats\n\n .par_iter()\n\n .find_any(|s| s.service_name != expected_namespace);\n\n match find_different_namespace {\n\n Some(different) => Err(MetricForwarderError::MoreThanOneNamespaceError(\n\n expected_namespace.to_string(),\n\n different.service_name.to_string(),\n\n )),\n\n None => Ok(expected_namespace),\n\n }\n\n } else {\n\n // I don't expect this to ever happen.\n\n Err(MetricForwarderError::NoLogsError())\n\n }\n\n}\n\n\n", "file_path": "src/rust/metric-forwarder/src/cloudwatch_send.rs", "rank": 9, "score": 248973.27696823922 }, { "content": "pub fn static_mapping_table_name() -> String {\n\n return std::env::var(\"STATIC_MAPPING_TABLE\").expect(\"STATIC_MAPPING_TABLE\");\n\n}\n\n\n", "file_path": "src/rust/grapl-config/src/lib.rs", "rank": 10, "score": 237969.94398592808 }, { "content": "// can't impl From for HandlerError, sadly\n\npub fn to_handler_error(err: &impl Display) -> HandlerError {\n\n HandlerError::from(err.to_string().as_str())\n\n}\n", "file_path": "src/rust/metric-forwarder/src/error.rs", "rank": 11, "score": 228037.34646412588 }, { "content": "fn encode_subgraph(subgraph: &Graph) -> Result<Vec<u8>, Error> {\n\n let mut buf = Vec::with_capacity(5000);\n\n subgraph.encode(&mut buf)?;\n\n Ok(buf)\n\n}\n\n\n\n#[async_trait]\n\nimpl<S> EventHandler for AnalyzerDispatcher<S>\n\nwhere\n\n S: S3 + Send + Sync + 'static,\n\n{\n\n type InputEvent = GeneratedSubgraphs;\n\n type OutputEvent = Vec<AnalyzerDispatchEvent>;\n\n type Error = sqs_lambda::error::Error;\n\n\n\n async fn handle_event(\n\n &mut self,\n\n subgraphs: GeneratedSubgraphs,\n\n ) -> OutputEvent<Self::OutputEvent, Self::Error> {\n\n let bucket = std::env::var(\"BUCKET_PREFIX\")\n", "file_path": "src/rust/analyzer-dispatcher/src/main.rs", "rank": 12, "score": 221578.5925653574 }, { "content": "fn create_or_empty_table(dynamo: &impl DynamoDb, table_name: impl Into<String>) {\n\n let mut runtime = Runtime::new().unwrap();\n\n let table_name = table_name.into();\n\n\n\n let _ = runtime.block_on(dynamo.delete_table(DeleteTableInput {\n\n table_name: table_name.clone(),\n\n }));\n\n\n\n std::thread::sleep(Duration::from_millis(250));\n\n\n\n while let Err(_e) = runtime.block_on(try_create_table(dynamo, table_name.clone())) {\n\n std::thread::sleep(Duration::from_millis(250));\n\n }\n\n}\n\n\n\n// Given an empty timeline\n\n// When a canonical creation event comes in\n\n// Then the newly created session should be in the timeline\n", "file_path": "src/rust/node-identifier/tests/sessiondb_integration_tests.rs", "rank": 13, "score": 221360.6945959684 }, { "content": "fn report_sqs_service_result(result: Result<String, String>, tx: &SyncSender<String>) {\n\n match result {\n\n Ok(success_message) => {\n\n info!(\n\n \"Handled an event, which was successfully deleted: {}\",\n\n &success_message\n\n );\n\n tx.send(success_message).unwrap();\n\n }\n\n Err(error_message) => {\n\n info!(\n\n \"Handled an event, though we failed to delete it: {}\",\n\n &error_message\n\n );\n\n tx.send(error_message).unwrap();\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/rust/graph-generator-lib/src/aws.rs", "rank": 14, "score": 216537.49866752303 }, { "content": "pub fn accumulate_metric_data(input: Vec<MetricDatum>) -> Vec<MetricDatum> {\n\n let mut datum_to_count: DatumToCountMap = HashMap::new();\n\n /*\n\n * This section of the code will convert input of (boiled down for simplicity)\n\n * [MetricDatum('metric', 1.0), MetricDatum('metric', 5.0), MetricDatum('metric', 1.0)]\n\n * into\n\n * {\n\n * MetricDatum('metric', _): {\n\n * // value -> num_occurences\n\n * 1.0: 2,\n\n * 5.0: 1\n\n * }\n\n * }\n\n */\n\n input.into_iter().for_each(|datum| {\n\n let value = &datum.value.unwrap();\n\n let count_map = datum_to_count\n\n .entry(WrappedMetricDatum(datum))\n\n .or_insert(HashMap::new());\n\n let count = count_map.entry(OrderedFloat(*value)).or_insert(0f64);\n", "file_path": "src/rust/metric-forwarder/src/accumulate_metrics.rs", "rank": 15, "score": 216126.97227157303 }, { "content": "/// Gets the name of the process given a path to the executable.\n\nfn get_image_name(image_path: &str) -> Option<String> {\n\n image_path\n\n .split('\\\\')\n\n .last()\n\n .map(|name| name.replace(\"- \", \"\").replace('\\\\', \"\"))\n\n}\n\n\n", "file_path": "src/rust/sysmon-subgraph-generator/src/models/mod.rs", "rank": 17, "score": 209272.34030663577 }, { "content": "pub fn is_local() -> bool {\n\n std::env::var(\"IS_LOCAL\")\n\n .map(|is_local| is_local.to_lowercase().parse().unwrap_or(false))\n\n .unwrap_or(false)\n\n}\n\n\n\npub async fn event_cache() -> RedisCache {\n\n let cache_address = {\n\n let generic_event_cache_addr =\n\n std::env::var(\"EVENT_CACHE_ADDR\").expect(\"GENERIC_EVENT_CACHE_ADDR\");\n\n let generic_event_cache_port =\n\n std::env::var(\"EVENT_CACHE_PORT\").expect(\"GENERIC_EVENT_CACHE_PORT\");\n\n\n\n format!(\"{}:{}\", generic_event_cache_addr, generic_event_cache_port,)\n\n };\n\n\n\n RedisCache::new(cache_address.to_owned())\n\n .await\n\n .expect(\"Could not create redis client\")\n\n}\n\n\n", "file_path": "src/rust/grapl-config/src/lib.rs", "rank": 18, "score": 205925.85115935496 }, { "content": "pub fn process_history_table_name() -> String {\n\n return std::env::var(\"PROCESS_HISTORY_TABLE\").expect(\"PROCESS_HISTORY_TABLE\");\n\n}\n\n\n", "file_path": "src/rust/grapl-config/src/lib.rs", "rank": 19, "score": 197486.689041622 }, { "content": "pub fn dynamic_session_table_name() -> String {\n\n return std::env::var(\"DYNAMIC_SESSION_TABLE\").expect(\"DYNAMIC_SESSION_TABLE\");\n\n}\n\n\n", "file_path": "src/rust/grapl-config/src/lib.rs", "rank": 20, "score": 197486.689041622 }, { "content": "pub fn file_history_table_name() -> String {\n\n return std::env::var(\"FILE_HISTORY_TABLE\").expect(\"FILE_HISTORY_TABLE\");\n\n}\n\n\n", "file_path": "src/rust/grapl-config/src/lib.rs", "rank": 21, "score": 197486.689041622 }, { "content": "pub fn outbound_connection_history_table_name() -> String {\n\n return std::env::var(\"OUTBOUND_CONNECTION_HISTORY_TABLE\")\n\n .expect(\"OUTBOUND_CONNECTION_HISTORY_TABLE\");\n\n}\n\n\n", "file_path": "src/rust/grapl-config/src/lib.rs", "rank": 22, "score": 194952.74207496486 }, { "content": "pub fn asset_id_mappings_table_name() -> String {\n\n return std::env::var(\"ASSET_ID_MAPPINGS\").expect(\"ASSET_ID_MAPPINGS\");\n\n}\n", "file_path": "src/rust/grapl-config/src/lib.rs", "rank": 23, "score": 194952.74207496486 }, { "content": "pub fn ip_connection_history_table_name() -> String {\n\n return std::env::var(\"IP_CONNECTION_HISTORY_TABLE\").expect(\"IP_CONNECTION_HISTORY_TABLE\");\n\n}\n\n\n", "file_path": "src/rust/grapl-config/src/lib.rs", "rank": 24, "score": 194952.74207496486 }, { "content": "pub fn network_connection_history_table_name() -> String {\n\n return std::env::var(\"NETWORK_CONNECTION_HISTORY_TABLE\")\n\n .expect(\"NETWORK_CONNECTION_HISTORY_TABLE\");\n\n}\n\n\n", "file_path": "src/rust/grapl-config/src/lib.rs", "rank": 25, "score": 194952.74207496486 }, { "content": "pub fn inbound_connection_history_table_name() -> String {\n\n return std::env::var(\"INBOUND_CONNECTION_HISTORY_TABLE\")\n\n .expect(\"INBOUND_CONNECTION_HISTORY_TABLE\");\n\n}\n\n\n", "file_path": "src/rust/grapl-config/src/lib.rs", "rank": 26, "score": 194952.74207496486 }, { "content": "pub fn handler(event: SqsEvent, ctx: Context) -> Result<(), HandlerError> {\n\n _handler(event, ctx, false)\n\n}\n\n\n", "file_path": "src/rust/node-identifier/src/lib.rs", "rank": 27, "score": 194677.3540577346 }, { "content": "pub fn retry_handler(event: SqsEvent, ctx: Context) -> Result<(), HandlerError> {\n\n _handler(event, ctx, true)\n\n}\n\n\n\n#[derive(Clone, Debug, Default)]\n\npub struct SubgraphSerializer {\n\n proto: Vec<u8>,\n\n}\n\n\n\nimpl CompletionEventSerializer for SubgraphSerializer {\n\n type CompletedEvent = GeneratedSubgraphs;\n\n type Output = Vec<u8>;\n\n type Error = sqs_lambda::error::Error;\n\n\n\n fn serialize_completed_events(\n\n &mut self,\n\n completed_events: &[Self::CompletedEvent],\n\n ) -> Result<Vec<Self::Output>, Self::Error> {\n\n if completed_events.is_empty() {\n\n warn!(\"No events to serialize\");\n", "file_path": "src/rust/node-identifier/src/lib.rs", "rank": 28, "score": 191802.8993647492 }, { "content": "pub fn parse_host_port(mg_alpha: String) -> (String, u16) {\n\n let mut splat = mg_alpha.split(\":\");\n\n let host = splat.next().expect(\"missing host\").to_owned();\n\n let port_str = splat.next();\n\n let port = port_str\n\n .expect(\"missing port\")\n\n .parse()\n\n .expect(&format!(\"invalid port: \\\"{:?}\\\"\", port_str));\n\n\n\n (host, port)\n\n}\n\n\n\npub async fn wait_for_s3(s3_client: impl S3) -> color_eyre::Result<()> {\n\n wait_loop(150, || async {\n\n match s3_client.list_buckets().await {\n\n Err(RusotoError::HttpDispatch(e)) => {\n\n debug!(\"Waiting for S3 to become available: {:?}\", e);\n\n Err(e)\n\n }\n\n _ => Ok(()),\n", "file_path": "src/rust/grapl-config/src/lib.rs", "rank": 29, "score": 191578.61658023298 }, { "content": "fn remove_dead_nodes(graph: &mut Graph, dead_nodes: &HashSet<impl Deref<Target = str>>) {\n\n for dead_node in dead_nodes {\n\n graph.nodes.remove(dead_node.deref());\n\n graph.edges.remove(dead_node.deref());\n\n }\n\n}\n\n\n", "file_path": "src/rust/node-identifier/src/lib.rs", "rank": 30, "score": 190902.23264134303 }, { "content": "fn _handler(event: SqsEvent, ctx: Context, should_default: bool) -> Result<(), HandlerError> {\n\n info!(\"Handling event\");\n\n\n\n let mut initial_events: HashSet<String> = event\n\n .records\n\n .iter()\n\n .map(|event| event.message_id.clone().unwrap())\n\n .collect();\n\n\n\n info!(\"Initial Events {:?}\", initial_events);\n\n\n\n let (tx, rx) = std::sync::mpsc::sync_channel(10);\n\n\n\n let completed_tx = tx.clone();\n\n\n\n std::thread::spawn(move || {\n\n tokio_compat::run_std(async move {\n\n let source_queue_url = std::env::var(\"SOURCE_QUEUE_URL\").expect(\"SOURCE_QUEUE_URL\");\n\n debug!(\"Queue Url: {}\", source_queue_url);\n\n let bucket_prefix = std::env::var(\"BUCKET_PREFIX\").expect(\"BUCKET_PREFIX\");\n", "file_path": "src/rust/node-identifier/src/lib.rs", "rank": 31, "score": 188577.9784680521 }, { "content": "pub fn aws_event_to_cloudwatch_logs_data(\n\n event: CloudwatchLogsEvent,\n\n) -> Result<CloudwatchLogsData, MetricForwarderError> {\n\n if let Some(data) = event.aws_logs.data {\n\n let result = base64_decode_raw_log_to_gzip(&data)\n\n .and_then(gunzip_to_string)\n\n .and_then(parse_string_to_logsdata);\n\n result\n\n } else {\n\n Err(PoorlyFormattedEventError())\n\n }\n\n}\n", "file_path": "src/rust/metric-forwarder/src/deser_logs_data.rs", "rank": 32, "score": 187251.36725737667 }, { "content": "/// Returns the provided file path with the Windows Zone Identifier removed if present.\n\n///\n\n/// When files are downloaded via a browser (e.g. Internet Explorer), an alternative data stream (ADS) may be created\n\n/// to store additional meta-data about the file. These ADS files are suffixed with `:Zone.Identifier`.\n\n///\n\n/// The purpose of these ADS files is to provide context to users and Windows Policy controls to keep users safe.\n\n///\n\n/// For example, Microsoft Word may open potentially unsafe `.docx` files marked with `:Zone.Identifier`\n\n/// in Protected View if the URL security zone is not well trusted.\n\n///\n\n/// [\"What are Zone Identifier Files?\"](https://stackoverflow.com/questions/4496697/what-are-zone-identifier-files)\n\nfn strip_file_zone_identifier(path: &str) -> &str {\n\n if path.ends_with(\":Zone.Identifier\") {\n\n &path[0..path.len() - \":Zone.Identifier\".len()]\n\n } else {\n\n path\n\n }\n\n}\n\n\n", "file_path": "src/rust/sysmon-subgraph-generator/src/models/mod.rs", "rank": 33, "score": 183050.6427900895 }, { "content": "pub fn statsd_as_cloudwatch_metric_bulk(parsed_stats: Vec<Stat>) -> Vec<MetricDatum> {\n\n /*\n\n Convert the platform-agnostic Stat type to Cloudwatch-specific type.\n\n */\n\n parsed_stats\n\n .into_par_iter()\n\n .map(statsd_as_cloudwatch_metric)\n\n .collect()\n\n}\n\n\n\nimpl From<Stat> for MetricDatum {\n\n fn from(s: Stat) -> MetricDatum {\n\n statsd_as_cloudwatch_metric(s)\n\n }\n\n}\n\n\n", "file_path": "src/rust/metric-forwarder/src/cloudwatch_send.rs", "rank": 34, "score": 178285.23045226093 }, { "content": "fn remap_edges(graph: &mut Graph, unid_id_map: &HashMap<String, String>) {\n\n for (_node_key, edge_list) in graph.edges.iter_mut() {\n\n for edge in edge_list.edges.iter_mut() {\n\n let from = match unid_id_map.get(&edge.from) {\n\n Some(from) => from,\n\n None => {\n\n warn!(\n\n \"Failed to lookup from node in unid_id_map {}\",\n\n &edge.edge_name\n\n );\n\n continue;\n\n }\n\n };\n\n\n\n let to = match unid_id_map.get(&edge.to) {\n\n Some(to) => to,\n\n None => {\n\n warn!(\n\n \"Failed to lookup to node in unid_id_map {}\",\n\n &edge.edge_name\n", "file_path": "src/rust/node-identifier/src/lib.rs", "rank": 35, "score": 175852.52390226978 }, { "content": "fn remap_nodes(graph: &mut Graph, unid_id_map: &HashMap<String, String>) {\n\n let mut nodes = HashMap::with_capacity(graph.nodes.len());\n\n\n\n for (_node_key, node) in graph.nodes.iter_mut() {\n\n // DynamicNodes are identified in-place\n\n if let Some(_n) = node.as_dynamic_node() {\n\n let old_node = nodes.insert(node.clone_node_key(), node.clone());\n\n if let Some(ref old_node) = old_node {\n\n NodeT::merge(\n\n nodes\n\n .get_mut(node.get_node_key())\n\n .expect(\"node key not in map\"),\n\n old_node,\n\n );\n\n }\n\n } else if let Some(new_key) = unid_id_map.get(node.get_node_key()) {\n\n node.set_node_key(new_key.to_owned());\n\n\n\n // We may have actually had nodes with different unid node_keys that map to the\n\n // same node_key. Therefor we must merge any nodes when there is a collision.\n", "file_path": "src/rust/node-identifier/src/lib.rs", "rank": 36, "score": 175852.52390226978 }, { "content": "pub fn _init_grapl_env(service_name: &str) -> ServiceEnv {\n\n let env = ServiceEnv {\n\n service_name: service_name.to_string(),\n\n is_local: is_local(),\n\n };\n\n _init_grapl_log(&env);\n\n env\n\n}\n\n\n", "file_path": "src/rust/grapl-config/src/lib.rs", "rank": 37, "score": 174120.26648179154 }, { "content": "pub fn skewed_cmp(ts_1: u64, ts_2: u64) -> bool {\n\n ts_1 - 10 < ts_2 && ts_1 + 10 > ts_2\n\n}\n", "file_path": "src/rust/node-identifier/src/sessiondb.rs", "rank": 38, "score": 166016.36097319366 }, { "content": " def test_invalid_tag_keys_and_values(self) -> None:\n\n for invalid_str in TestData.INVALID_STRS:\n\n # mutate key, then value\n\n with pytest.raises(ValueError):\n\n TagPair(invalid_str, TestData.VALID_STR)\n\n with pytest.raises(ValueError):\n", "file_path": "src/python/grapl-common/tests/metrics/test_statsd_formatter.py", "rank": 39, "score": 164832.54738026232 }, { "content": "#[quickcheck]\n\n#[cfg(feature = \"integration\")]\n\nfn update_end_time(asset_id: String, pid: u64) {\n\n let mut runtime = Runtime::new().unwrap();\n\n let table_name = \"process_history_update_end_time\";\n\n let dynamo = init_dynamodb_client();\n\n\n\n create_or_empty_table(&dynamo, table_name);\n\n\n\n let session_db = SessionDb::new(dynamo, table_name);\n\n\n\n // Given a timeline with a single session, where that session has a non canon\n\n // end time 'X'\n\n let session = Session {\n\n pseudo_key: format!(\"{}{}\", asset_id, pid),\n\n create_time: 1_544_301_484_600,\n\n is_create_canon: false,\n\n session_id: \"SessionId\".into(),\n\n is_end_canon: false,\n\n end_time: 1_544_301_484_700,\n\n version: 0,\n\n };\n", "file_path": "src/rust/node-identifier/tests/sessiondb_integration_tests.rs", "rank": 40, "score": 163768.85443342075 }, { "content": "fn into_unid_session(node: &Node) -> Result<Option<UnidSession>, Error> {\n\n match &node.which_node {\n\n Some(WhichNode::ProcessNode(node)) => {\n\n let (is_creation, timestamp) = match (\n\n node.created_timestamp != 0,\n\n node.last_seen_timestamp != 0,\n\n node.terminated_timestamp != 0,\n\n ) {\n\n (true, _, _) => (true, node.created_timestamp),\n\n (_, _, true) => (false, node.terminated_timestamp),\n\n (_, true, _) => (false, node.last_seen_timestamp),\n\n _ => bail!(\"At least one timestamp must be set\"),\n\n };\n\n\n\n Ok(Some(UnidSession {\n\n pseudo_key: format!(\n\n \"{}{}\",\n\n node.get_asset_id().expect(\"ProcessNode must have asset_id\"),\n\n node.process_id\n\n ),\n", "file_path": "src/rust/node-identifier/src/lib.rs", "rank": 41, "score": 163738.13238386202 }, { "content": "#[quickcheck]\n\n#[cfg(feature = \"integration\")]\n\nfn canon_create_on_empty_timeline(asset_id: String, pid: u64) {\n\n let mut runtime = Runtime::new().unwrap();\n\n let table_name = \"process_history_canon_create_on_empty_timeline\";\n\n let dynamo = init_dynamodb_client();\n\n\n\n create_or_empty_table(&dynamo, table_name);\n\n\n\n let session_db = SessionDb::new(dynamo, table_name);\n\n\n\n let unid = UnidSession {\n\n pseudo_key: format!(\"{}{}\", asset_id, pid),\n\n timestamp: 1544301484600,\n\n is_creation: true,\n\n };\n\n\n\n let session_id = runtime\n\n .block_on(session_db.handle_unid_session(unid, false))\n\n .expect(\"Failed to create session\");\n\n\n\n assert!(!session_id.is_empty());\n\n}\n\n\n\n// Given a timeline with a single session, where that session has a non canon\n\n// creation time 'X'\n\n// When a canonical creation event comes in with a creation time of 'Y'\n\n// where 'Y' < 'X'\n\n// Then the session should be updated to have 'Y' as its canonical create time\n", "file_path": "src/rust/node-identifier/tests/sessiondb_integration_tests.rs", "rank": 42, "score": 161693.90961967094 }, { "content": "#[quickcheck]\n\n#[cfg(feature = \"integration\")]\n\nfn noncanon_create_on_empty_timeline_with_default(asset_id: String, pid: u64) {\n\n let mut runtime = Runtime::new().unwrap();\n\n let table_name = \"process_history_noncanon_create_on_empty_timeline_with_default\";\n\n let dynamo = init_dynamodb_client();\n\n\n\n create_or_empty_table(&dynamo, table_name);\n\n\n\n let session_db = SessionDb::new(dynamo, table_name);\n\n\n\n let unid = UnidSession {\n\n pseudo_key: format!(\"{}{}\", asset_id, pid),\n\n timestamp: 1_544_301_484_500,\n\n is_creation: false,\n\n };\n\n\n\n let session_id = runtime\n\n .block_on(session_db.handle_unid_session(unid, true))\n\n .expect(\"Failed to create session\");\n\n\n\n assert!(!session_id.is_empty());\n\n}\n\n\n\n// Given an empty timeline\n\n// When a noncanon create event comes in and 'should_default' is false\n\n// Then return an error\n", "file_path": "src/rust/node-identifier/tests/sessiondb_integration_tests.rs", "rank": 43, "score": 159689.7014841385 }, { "content": "type PutResult = Result<(), RusotoError<PutMetricDataError>>;\n\n\n", "file_path": "src/rust/metric-forwarder/src/cloudwatch_send.rs", "rank": 44, "score": 159517.0033069485 }, { "content": "/// Creates an S3 client used when running Grapl on AWS\n\nfn init_production_s3_client(region_str: String) -> S3Client {\n\n let region = Region::from_str(&region_str).expect(\"region_str\");\n\n\n\n match std::env::var(\"ASSUME_ROLE\") {\n\n Ok(role) => {\n\n let provider = StsAssumeRoleSessionCredentialsProvider::new(\n\n StsClient::new(region.clone()),\n\n role,\n\n \"default\".to_owned(),\n\n None,\n\n None,\n\n None,\n\n None,\n\n );\n\n S3Client::new_with(\n\n rusoto_core::request::HttpClient::new().expect(\"Failed to create HTTP client\"),\n\n provider,\n\n region,\n\n )\n\n }\n\n _ => S3Client::new(region),\n\n }\n\n}\n", "file_path": "src/rust/graph-generator-lib/src/aws.rs", "rank": 45, "score": 156536.5527335921 }, { "content": "fn chunk<T, U>(data: U, count: usize) -> Vec<U>\n\nwhere\n\n U: IntoIterator<Item = T>,\n\n U: FromIterator<T>,\n\n <U as IntoIterator>::IntoIter: ExactSizeIterator,\n\n{\n\n let mut iter = data.into_iter();\n\n let iter = iter.by_ref();\n\n\n\n let chunk_len = (iter.len() / count) as usize + 1;\n\n\n\n let mut chunks = Vec::new();\n\n for _ in 0..count {\n\n chunks.push(iter.take(chunk_len).collect())\n\n }\n\n chunks\n\n}\n\n\n", "file_path": "src/rust/graph-merger/src/main.rs", "rank": 46, "score": 156399.8743014887 }, { "content": "#[quickcheck]\n\n#[cfg(feature = \"integration\")]\n\nfn noncanon_create_update_existing_non_canon_create(asset_id: String, pid: u64) {\n\n let mut runtime = Runtime::new().unwrap();\n\n let table_name = \"process_history_noncanon_create_update_existing_non_canon_create\";\n\n let dynamo = init_dynamodb_client();\n\n\n\n create_or_empty_table(&dynamo, table_name);\n\n\n\n let session_db = SessionDb::new(dynamo, table_name);\n\n\n\n // Given a timeline with a single session, where that session has a non canon\n\n // creation time 'X'\n\n let session = Session {\n\n pseudo_key: format!(\"{}{}\", asset_id, pid),\n\n create_time: 1_544_301_484_600,\n\n is_create_canon: false,\n\n session_id: \"SessionId\".into(),\n\n is_end_canon: false,\n\n end_time: 1_544_301_484_700,\n\n version: 0,\n\n };\n", "file_path": "src/rust/node-identifier/tests/sessiondb_integration_tests.rs", "rank": 47, "score": 155879.14187513 }, { "content": "#[quickcheck]\n\n#[cfg(feature = \"integration\")]\n\nfn canon_create_update_existing_non_canon_create(asset_id: String, pid: u64) {\n\n let mut runtime = Runtime::new().unwrap();\n\n let table_name = \"process_history_canon_create_update_existing_non_canon_create\";\n\n let dynamo = init_dynamodb_client();\n\n\n\n create_or_empty_table(&dynamo, table_name);\n\n\n\n let session_db = SessionDb::new(dynamo, table_name);\n\n\n\n // Given a timeline with a single session, where that session has a non canon\n\n // creation time 'X'\n\n let session = Session {\n\n pseudo_key: format!(\"{}{}\", asset_id, pid),\n\n create_time: 1_544_301_484_600,\n\n is_create_canon: false,\n\n session_id: \"SessionId\".into(),\n\n is_end_canon: false,\n\n end_time: 1_544_301_484_700,\n\n version: 0,\n\n };\n", "file_path": "src/rust/node-identifier/tests/sessiondb_integration_tests.rs", "rank": 48, "score": 155879.14187513 }, { "content": "fn handler(event: SqsEvent, ctx: Context) -> Result<(), HandlerError> {\n\n info!(\"Handling event\");\n\n\n\n let mut initial_events: HashSet<String> = event\n\n .records\n\n .iter()\n\n .map(|event| event.message_id.clone().unwrap())\n\n .collect();\n\n\n\n info!(\"Initial Events {:?}\", initial_events);\n\n\n\n let (tx, rx) = std::sync::mpsc::sync_channel(10);\n\n let completed_tx = tx.clone();\n\n\n\n std::thread::spawn(move || {\n\n tokio_compat::run_std(async move {\n\n let source_queue_url = std::env::var(\"SOURCE_QUEUE_URL\").expect(\"SOURCE_QUEUE_URL\");\n\n debug!(\"Queue Url: {}\", source_queue_url);\n\n let cache_address = {\n\n let retry_identity_cache_addr =\n", "file_path": "src/rust/graph-merger/src/main.rs", "rank": 49, "score": 147080.68972541284 }, { "content": "fn handler(event: SqsEvent, ctx: Context) -> Result<(), HandlerError> {\n\n info!(\"Handling event\");\n\n\n\n let mut initial_events: HashSet<String> = event\n\n .records\n\n .iter()\n\n .map(|event| event.message_id.clone().unwrap())\n\n .collect();\n\n\n\n info!(\"Initial Events {:?}\", initial_events);\n\n\n\n let (tx, rx) = std::sync::mpsc::sync_channel(10);\n\n let completed_tx = tx.clone();\n\n\n\n std::thread::spawn(move || {\n\n tokio_compat::run_std(async move {\n\n let source_queue_url = std::env::var(\"SOURCE_QUEUE_URL\").expect(\"SOURCE_QUEUE_URL\");\n\n debug!(\"Queue Url: {}\", source_queue_url);\n\n let bucket_prefix = std::env::var(\"BUCKET_PREFIX\").expect(\"BUCKET_PREFIX\");\n\n\n", "file_path": "src/rust/analyzer-dispatcher/src/main.rs", "rank": 50, "score": 147080.6897254128 }, { "content": "fn handler_sync(event: CloudwatchLogsEvent, _ctx: Context) -> Result<(), HandlerError> {\n\n /**\n\n * Do some threading magic to block on `handler_async` until it completes\n\n */\n\n type R = Result<(), MetricForwarderError>;\n\n let result_arc: Arc<Mutex<R>> = Arc::new(Mutex::new(Ok(())));\n\n let result_arc_for_thread = Arc::clone(&result_arc);\n\n\n\n let thread = std::thread::spawn(move || {\n\n tokio_compat::run_std(async move {\n\n let result: R = handler_async(event).await.clone();\n\n *result_arc_for_thread.lock().unwrap() = result;\n\n ()\n\n })\n\n });\n\n\n\n thread.join().unwrap();\n\n let result = result_arc.lock().unwrap();\n\n result\n\n .as_ref()\n", "file_path": "src/rust/metric-forwarder/src/main.rs", "rank": 51, "score": 142682.56960258458 }, { "content": "pub fn region() -> Region {\n\n let region_override = std::env::var(\"AWS_REGION_OVERRIDE\");\n\n\n\n match region_override {\n\n Ok(region) => Region::Custom {\n\n name: \"override\".to_string(),\n\n endpoint: region,\n\n },\n\n Err(_) => {\n\n let region_str = std::env::var(\"AWS_REGION\").expect(\"AWS_REGION\");\n\n Region::from_str(&region_str).expect(\"Region error\")\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/rust/grapl-config/src/lib.rs", "rank": 52, "score": 137027.56179895694 }, { "content": "fn generate_edge_insert(from: &str, to: &str, edge_name: &str) -> dgraph_tonic::Mutation {\n\n let mu = json!({\n\n \"uid\": from,\n\n edge_name: {\n\n \"uid\": to\n\n }\n\n });\n\n\n\n let mut mutation = dgraph_tonic::Mutation::new();\n\n mutation.commit_now = true;\n\n mutation.set_set_json(&mu);\n\n\n\n mutation\n\n}\n\n\n\nasync fn node_key_to_uid(dg: &DgraphClient, node_key: &str) -> Result<Option<String>, Error> {\n\n let mut txn = dg.new_read_only_txn();\n\n\n\n const QUERY: &str = r\"\n\n query q0($a: string)\n", "file_path": "src/rust/graph-merger/src/main.rs", "rank": 53, "score": 136475.5840320412 }, { "content": "fn time_based_key_fn(_event: &[u8]) -> String {\n\n info!(\"event length {}\", _event.len());\n\n let cur_ms = match SystemTime::now().duration_since(UNIX_EPOCH) {\n\n Ok(n) => n.as_millis(),\n\n Err(_) => panic!(\"SystemTime before UNIX EPOCH!\"),\n\n };\n\n\n\n let cur_day = cur_ms - (cur_ms % 86400);\n\n\n\n format!(\"{}/{}-{}\", cur_day, cur_ms, uuid::Uuid::new_v4())\n\n}\n\n\n", "file_path": "src/rust/node-identifier/src/lib.rs", "rank": 54, "score": 136086.88542405423 }, { "content": "fn time_based_key_fn(_event: &[u8]) -> String {\n\n info!(\"event length {}\", _event.len());\n\n let cur_ms = match SystemTime::now().duration_since(UNIX_EPOCH) {\n\n Ok(n) => n.as_millis(),\n\n Err(_) => panic!(\"SystemTime before UNIX EPOCH!\"),\n\n };\n\n\n\n let cur_day = cur_ms - (cur_ms % 86400);\n\n\n\n format!(\"{}/{}-{}\", cur_day, cur_ms, uuid::Uuid::new_v4())\n\n}\n\n\n", "file_path": "src/rust/graph-merger/src/main.rs", "rank": 55, "score": 136086.88542405423 }, { "content": "/// Creates a subgraph describing an outbound `NetworkEvent`\n\n///\n\n/// Subgraph generation for an outbound `NetworkEvent` includes the following:\n\n/// * An `Asset` node - indicating the asset in which the outbound `NetworkEvent` occurred\n\n/// * A `Process` node - indicating the process which triggered the outbound `NetworkEvent`\n\n/// * A subject `OutboundConnection` node - indicating the network connection triggered by the process\n\n/// * Source and Destination IP Address and Port nodes\n\n/// * IP connection and Network connection nodes\n\npub fn generate_outbound_connection_subgraph(\n\n conn_log: &NetworkEvent,\n\n) -> Result<Graph, failure::Error> {\n\n let timestamp = utc_to_epoch(&conn_log.event_data.utc_time)?;\n\n\n\n let mut graph = Graph::new(timestamp);\n\n\n\n let asset = AssetBuilder::default()\n\n .asset_id(conn_log.system.computer.computer.clone())\n\n .hostname(conn_log.system.computer.computer.clone())\n\n .build()\n\n .map_err(|err| failure::err_msg(err))?;\n\n\n\n // A process creates an outbound connection to dst_port\n\n let process = ProcessBuilder::default()\n\n .asset_id(conn_log.system.computer.computer.clone())\n\n .hostname(conn_log.system.computer.computer.clone())\n\n .state(ProcessState::Existing)\n\n .process_id(conn_log.event_data.process_id)\n\n .last_seen_timestamp(timestamp)\n", "file_path": "src/rust/sysmon-subgraph-generator/src/models/network/outbound.rs", "rank": 56, "score": 136050.83942719465 }, { "content": "// Inbound is the 'src' in sysmon\n\n/// Creates a subgraph describing an inbound `NetworkEvent`\n\n///\n\n/// The subgraph generated is similar to the graph generated by [super::generate_outbound_connection_subgraph]\n\npub fn generate_inbound_connection_subgraph(\n\n conn_log: &NetworkEvent,\n\n) -> Result<Graph, failure::Error> {\n\n let timestamp = utc_to_epoch(&conn_log.event_data.utc_time)?;\n\n\n\n let mut graph = Graph::new(timestamp);\n\n\n\n let asset = AssetBuilder::default()\n\n .asset_id(conn_log.system.computer.computer.clone())\n\n .hostname(conn_log.system.computer.computer.clone())\n\n .build()\n\n .map_err(|err| failure::err_msg(err))?;\n\n\n\n // A process creates an outbound connection to dst_port\n\n let process = ProcessBuilder::default()\n\n .asset_id(conn_log.system.computer.computer.clone())\n\n .hostname(conn_log.system.computer.computer.clone())\n\n .state(ProcessState::Existing)\n\n .process_id(conn_log.event_data.process_id)\n\n .last_seen_timestamp(timestamp)\n", "file_path": "src/rust/sysmon-subgraph-generator/src/models/network/inbound.rs", "rank": 57, "score": 136050.83942719465 }, { "content": "/// Creates a subgrqph describing a `FileCreateEvent`\n\n///\n\n/// The subgraph generation for a `FileCreateEvent` includes the following:\n\n/// * A creator `Process` node - denotes the process that created the file\n\n/// * A subject `File` node - the file that is created as part of this event\n\npub fn generate_file_create_subgraph(\n\n file_create: &FileCreateEvent,\n\n) -> Result<Graph, failure::Error> {\n\n let timestamp = utc_to_epoch(&file_create.event_data.creation_utc_time)?;\n\n let mut graph = Graph::new(timestamp);\n\n\n\n let asset = AssetBuilder::default()\n\n .asset_id(file_create.system.computer.computer.clone())\n\n .hostname(file_create.system.computer.computer.clone())\n\n .build()\n\n .map_err(|err| failure::err_msg(err))?;\n\n\n\n let creator = ProcessBuilder::default()\n\n .asset_id(file_create.system.computer.computer.clone())\n\n .state(ProcessState::Existing)\n\n .process_id(file_create.event_data.process_id)\n\n .process_name(get_image_name(&file_create.event_data.image.clone()).unwrap())\n\n .last_seen_timestamp(timestamp)\n\n // .created_timestamp(file_create.event_data.process_guid.get_creation_timestamp())\n\n .build()\n", "file_path": "src/rust/sysmon-subgraph-generator/src/models/file/create.rs", "rank": 58, "score": 136050.83942719465 }, { "content": "/// Creates a subgraph describing a `ProcessCreateEvent`.\n\n///\n\n/// Subgraph generation for a `ProcessCreateEvent` includes the following:\n\n/// * An `Asset` node - indicating the asset in which the process was created\n\n/// * A parent `Process` node - indicating the process that created the subject process\n\n/// * A subject `Process` node - indicating the process created per the `ProcessCreateEvent`\n\n/// * A process `File` node - indicating the file executed in creating the new process\n\npub fn generate_process_create_subgraph(\n\n process_start: &ProcessCreateEvent,\n\n) -> Result<Graph, failure::Error> {\n\n let timestamp = utc_to_epoch(&process_start.event_data.utc_time)?;\n\n let mut graph = Graph::new(timestamp);\n\n\n\n let asset = AssetBuilder::default()\n\n .asset_id(process_start.system.computer.computer.clone())\n\n .hostname(process_start.system.computer.computer.clone())\n\n .build()\n\n .map_err(|err| failure::err_msg(err))?;\n\n\n\n let parent = ProcessBuilder::default()\n\n .asset_id(process_start.system.computer.computer.clone())\n\n .state(ProcessState::Existing)\n\n .process_id(process_start.event_data.parent_process_id)\n\n .process_name(get_image_name(&process_start.event_data.parent_image.clone()).unwrap())\n\n .process_command_line(&process_start.event_data.parent_command_line.command_line)\n\n .last_seen_timestamp(timestamp)\n\n // .created_timestamp(process_start.event_data.parent_process_guid.get_creation_timestamp())\n", "file_path": "src/rust/sysmon-subgraph-generator/src/models/process/create.rs", "rank": 59, "score": 136050.83942719465 }, { "content": " def write(self, some_str: str) -> int:\n\n self.writes.append(some_str)\n", "file_path": "src/python/grapl-common/tests/metrics/test_metric_reporter.py", "rank": 60, "score": 133727.4212265167 }, { "content": "pub fn init_sqs_client() -> SqsClient {\n\n info!(\"Connecting to local us-east-1 http://sqs.us-east-1.amazonaws.com:9324\");\n\n\n\n SqsClient::new_with(\n\n HttpClient::new().expect(\"failed to create request dispatcher\"),\n\n rusoto_credential::StaticProvider::new_minimal(\n\n \"dummy_sqs\".to_owned(),\n\n \"dummy_sqs\".to_owned(),\n\n ),\n\n Region::Custom {\n\n name: \"us-east-1\".to_string(),\n\n endpoint: \"http://sqs.us-east-1.amazonaws.com:9324\".to_string(),\n\n },\n\n )\n\n}\n\n\n", "file_path": "src/rust/node-identifier/src/lib.rs", "rank": 61, "score": 131502.4988151352 }, { "content": "pub fn init_s3_client() -> S3Client {\n\n info!(\"Connecting to local http://s3:9000\");\n\n S3Client::new_with(\n\n HttpClient::new().expect(\"failed to create request dispatcher\"),\n\n rusoto_credential::StaticProvider::new_minimal(\n\n \"minioadmin\".to_owned(),\n\n \"minioadmin\".to_owned(),\n\n ),\n\n Region::Custom {\n\n name: \"locals3\".to_string(),\n\n endpoint: \"http://s3:9000\".to_string(),\n\n },\n\n )\n\n}\n\n\n", "file_path": "src/rust/node-identifier/src/lib.rs", "rank": 62, "score": 131502.4988151352 }, { "content": " def test_counter_with_sample_rate(self) -> None:\n\n result = statsd_format(\n\n metric_name=TestData.METRIC_NAME,\n\n value=TestData.VALUE,\n\n sample_rate=TestData.SAMPLE_RATE,\n\n typ=\"c\",\n\n )\n", "file_path": "src/python/grapl-common/tests/metrics/test_statsd_formatter.py", "rank": 63, "score": 130147.55032915866 }, { "content": "pub fn init_dynamodb_client() -> DynamoDbClient {\n\n info!(\"Connecting to local http://dynamodb:8000\");\n\n DynamoDbClient::new_with(\n\n HttpClient::new().expect(\"failed to create request dispatcher\"),\n\n rusoto_credential::StaticProvider::new_minimal(\n\n \"dummy_cred_aws_access_key_id\".to_owned(),\n\n \"dummy_cred_aws_secret_access_key\".to_owned(),\n\n ),\n\n Region::Custom {\n\n name: \"us-west-2\".to_string(),\n\n endpoint: \"http://dynamodb:8000\".to_string(),\n\n },\n\n )\n\n}\n\n\n", "file_path": "src/rust/node-identifier/src/lib.rs", "rank": 64, "score": 129814.8590769826 }, { "content": "pub fn init_dynamodb_client() -> DynamoDbClient {\n\n if grapl_config::is_local() {\n\n info!(\"Connecting to local DynamoDB http://dynamodb:8000\");\n\n DynamoDbClient::new_with(\n\n HttpClient::new().expect(\"failed to create request dispatcher\"),\n\n rusoto_credential::StaticProvider::new_minimal(\n\n \"dummy_cred_aws_access_key_id\".to_owned(),\n\n \"dummy_cred_aws_secret_access_key\".to_owned(),\n\n ),\n\n Region::Custom {\n\n name: \"us-west-2\".to_string(),\n\n endpoint: \"http://dynamodb:8000\".to_string(),\n\n },\n\n )\n\n } else {\n\n info!(\"Connecting to DynamoDB\");\n\n let region = grapl_config::region();\n\n DynamoDbClient::new(region.clone())\n\n }\n\n}\n\n\n", "file_path": "src/rust/graph-merger/src/main.rs", "rank": 65, "score": 129814.8590769826 }, { "content": "#[test]\n\n#[cfg(feature = \"integration\")]\n\nfn map_hostname_to_asset_id() {\n\n let mut runtime = Runtime::new().unwrap();\n\n let region = Region::Custom {\n\n endpoint: \"http://localhost:8000\".to_owned(),\n\n name: \"us-east-9\".to_owned(),\n\n };\n\n\n\n let asset_id_db = AssetIdDb::new(init_dynamodb_client());\n\n\n\n runtime\n\n .block_on(asset_id_db.create_mapping(\n\n &HostId::Hostname(\"fakehostname\".to_owned()),\n\n \"asset_id_a\".into(),\n\n 1500,\n\n ))\n\n .expect(\"Mapping creation failed\");\n\n\n\n let mapping = runtime\n\n .block_on(asset_id_db.resolve_asset_id(&HostId::Hostname(\"fakehostname\".to_owned()), 1510))\n\n .expect(\"Failed to resolve asset id mapping\")\n\n .expect(\"Failed to resolve asset id mapping\");\n\n\n\n assert_eq!(mapping, \"asset_id_a\");\n\n}\n", "file_path": "src/rust/node-identifier/tests/assetdb_integration_tests.rs", "rank": 66, "score": 126886.54535136452 }, { "content": "fn remove_dead_edges(graph: &mut Graph) {\n\n let edges = &mut graph.edges;\n\n let nodes = &graph.nodes;\n\n for (_node_key, edge_list) in edges.iter_mut() {\n\n let live_edges: Vec<_> = edge_list\n\n .edges\n\n .clone()\n\n .into_iter()\n\n .filter(|edge| nodes.contains_key(&edge.to) && nodes.contains_key(&edge.from))\n\n .collect();\n\n\n\n *edge_list = EdgeList { edges: live_edges };\n\n }\n\n}\n\n\n", "file_path": "src/rust/node-identifier/src/lib.rs", "rank": 67, "score": 125716.10133429262 }, { "content": "pub fn grapl_log_level() -> log::Level {\n\n match std::env::var(\"GRAPL_LOG_LEVEL\") {\n\n Ok(level) => {\n\n log::Level::from_str(&level).expect(&format!(\"Invalid logging level {}\", level))\n\n }\n\n Err(_) => log::Level::Error,\n\n }\n\n}\n\n\n", "file_path": "src/rust/grapl-config/src/lib.rs", "rank": 68, "score": 125503.25724986181 }, { "content": " def test_non_counter_with_sample_rate_doesnt_include_it(self) -> None:\n\n result = statsd_format(\n\n metric_name=TestData.METRIC_NAME,\n\n value=TestData.VALUE,\n\n sample_rate=TestData.SAMPLE_RATE,\n\n typ=\"g\",\n\n )\n", "file_path": "src/python/grapl-common/tests/metrics/test_statsd_formatter.py", "rank": 69, "score": 124390.24012470088 }, { "content": "#[test]\n\n#[cfg(feature = \"integration\")]\n\nfn canon_create_on_timeline_with_surrounding_canon_sessions() {\n\n let table_name = \"process_history_canon_create_on_timeline_with_surrounding_canon_sessions\";\n\n let dynamo = init_dynamodb_client();\n\n\n\n create_or_empty_table(&dynamo, table_name);\n\n\n\n let session_db = SessionDb::new(dynamo, table_name);\n\n}\n\n\n\n// Given an empty timeline\n\n// When a noncanon create event comes in and 'should_default' is true\n\n// Then Create the new noncanon session\n", "file_path": "src/rust/node-identifier/tests/sessiondb_integration_tests.rs", "rank": 70, "score": 123832.16375391743 }, { "content": "#[test]\n\n#[cfg(feature = \"integration\")]\n\nfn noncanon_create_on_empty_timeline_without_default() {\n\n let mut runtime = Runtime::new().unwrap();\n\n let table_name = \"process_history_noncanon_create_on_empty_timeline_without_default\";\n\n let dynamo = init_dynamodb_client();\n\n\n\n create_or_empty_table(&dynamo, table_name);\n\n\n\n let session_db = SessionDb::new(dynamo, table_name);\n\n\n\n let unid = UnidSession {\n\n pseudo_key: \"asset_id_a1234\".into(),\n\n timestamp: 1_544_301_484_500,\n\n is_creation: false,\n\n };\n\n\n\n let session_id = runtime.block_on(session_db.handle_unid_session(unid, false));\n\n assert!(session_id.is_err());\n\n}\n\n\n\n// Given a timeline with one session, where the session has a create_time\n\n// of X\n\n// When a canon create event comes in with a create time within ~100ms of X\n\n// Then we should make the session create time canonical\n", "file_path": "src/rust/node-identifier/tests/sessiondb_integration_tests.rs", "rank": 71, "score": 123832.16375391743 }, { "content": "pub fn _init_grapl_log(env: &ServiceEnv) {\n\n let filter = EnvFilter::from_default_env()\n\n .add_directive(\"warn\".parse().expect(\"Invalid directive\"))\n\n .add_directive(\n\n format!(\"{}={}\", env.service_name, grapl_log_level())\n\n .parse()\n\n .expect(\"Invalid directive\"),\n\n );\n\n if env.is_local {\n\n tracing_subscriber::fmt().with_env_filter(filter).init();\n\n } else {\n\n tracing_subscriber::fmt()\n\n .json()\n\n .with_env_filter(filter)\n\n .init();\n\n }\n\n}\n\n\n", "file_path": "src/rust/grapl-config/src/lib.rs", "rank": 72, "score": 123815.61751170925 }, { "content": "#[test]\n\n#[cfg(feature = \"integration\")]\n\nfn canon_create_on_timeline_with_existing_session_within_skew() {\n\n let table_name = \"process_history_canon_create_on_timeline_with_existing_session_within_skew\";\n\n let dynamo = init_dynamodb_client();\n\n\n\n create_or_empty_table(&dynamo, table_name);\n\n\n\n let session_db = SessionDb::new(dynamo, table_name);\n\n}\n\n\n", "file_path": "src/rust/node-identifier/tests/sessiondb_integration_tests.rs", "rank": 73, "score": 122382.71429672782 }, { "content": "class TagPair:\n\n tag_key: str\n\n tag_value: str\n\n\n\n def __init__(self, tag_key: str, tag_value: str) -> None:\n\n _reject_invalid_chars(tag_key)\n\n _reject_invalid_chars(tag_value)\n\n self.tag_key = tag_key\n\n self.tag_value = tag_value\n\n\n\n def statsd_serialized(self) -> str:\n", "file_path": "src/python/grapl-common/grapl_common/metrics/statsd_formatter.py", "rank": 74, "score": 120535.09405897059 }, { "content": "#[proc_macro_derive(GraplStaticId, attributes(grapl))]\n\npub fn derive_grapl_session(input: TokenStream) -> TokenStream {\n\n let input: syn::DeriveInput = syn::parse_macro_input!(input as syn::DeriveInput);\n\n\n\n let input_struct = match input.data {\n\n Data::Struct(input_struct) => input_struct,\n\n _ => panic!(\"Only available for struct\"),\n\n };\n\n\n\n let fields = match input_struct.fields {\n\n Fields::Named(fields) => fields.named,\n\n _ => panic!(\"Requires named fields\"),\n\n };\n\n\n\n let id_fields = fields\n\n .iter()\n\n .filter_map(|field| {\n\n for attr in &field.attrs {\n\n if attr.path.segments.is_empty() {\n\n return None;\n\n }\n", "file_path": "src/rust/derive-dynamic-node/src/lib.rs", "rank": 75, "score": 114423.74917362203 }, { "content": "#[proc_macro_derive(DynamicNode)]\n\npub fn derive_dynamic_node(input: TokenStream) -> TokenStream {\n\n let input: syn::DeriveInput = syn::parse_macro_input!(input as syn::DeriveInput);\n\n\n\n let input_struct = match input.data {\n\n Data::Struct(input_struct) => input_struct,\n\n _ => panic!(\"Only available for struct\"),\n\n };\n\n\n\n let fields = match input_struct.fields {\n\n Fields::Named(fields) => fields.named,\n\n _ => panic!(\"Requires named fields\"),\n\n };\n\n\n\n let methods = fields\n\n .iter()\n\n .map(name_and_ty)\n\n .map(|(name, ty)| get_method(name, ty))\n\n .fold(quote!(), |mut acc, method| {\n\n acc.extend(method);\n\n acc\n", "file_path": "src/rust/derive-dynamic-node/src/lib.rs", "rank": 76, "score": 114419.30131841524 }, { "content": "pub fn shave_int(input: u64, digits: u8) -> u64 {\n\n let digits = 10u64.pow((digits as u32) + 1u32);\n\n input - (input % digits)\n\n}\n", "file_path": "src/rust/node-identifier/src/sessions.rs", "rank": 77, "score": 110477.29717818675 }, { "content": "class UploadTestData(Protocol):\n\n def upload(self, s3_client: S3ServiceResource) -> None:\n", "file_path": "src/python/grapl-tests-common/grapl_tests_common/upload_test_data.py", "rank": 78, "score": 107968.7344758273 }, { "content": "class UploadSysmonLogsTestData(UploadTestData):\n\n def __init__(self, path: str) -> None:\n\n self.path = path\n\n\n\n def upload(self, s3_client: S3ServiceResource) -> None:\n\n logging.info(f\"S3 uploading test data from {self.path}\")\n\n upload_sysmon_logs(\n\n prefix=BUCKET_PREFIX,\n\n logfile=self.path,\n\n use_links=True,\n", "file_path": "src/python/grapl-tests-common/grapl_tests_common/upload_test_data.py", "rank": 79, "score": 105816.97696420309 }, { "content": " def test_expected_data_in_dgraph(self) -> None:\n\n lens_resource = wait_for_lens()\n\n wait_result = wait_for([lens_resource], timeout_secs=240)\n\n\n\n lens: LensView = wait_result[lens_resource]\n\n assert lens.get_lens_name() == LENS_NAME\n\n\n\n def condition() -> bool:\n\n # lens scope is not atomic\n\n length = len(lens.get_scope())\n\n print(f\"Expected 4 nodes in scope, currently is {length}\")\n\n return length == 4\n\n\n", "file_path": "src/python/grapl_e2e_tests/tests.py", "rank": 80, "score": 96832.46167588262 }, { "content": " def __str__(self) -> str:\n", "file_path": "src/python/grapl_e2e_tests/tests.py", "rank": 81, "score": 95778.44517117196 }, { "content": " def test_tags(self) -> None:\n\n result = statsd_format(\n\n metric_name=TestData.METRIC_NAME,\n\n value=TestData.VALUE,\n\n sample_rate=TestData.SAMPLE_RATE,\n\n typ=\"ms\",\n\n tags=TestData.TAGS,\n\n )\n", "file_path": "src/python/grapl-common/tests/metrics/test_statsd_formatter.py", "rank": 82, "score": 95484.24599330225 }, { "content": "class TestData:\n\n METRIC_NAME = \"some_metric\"\n\n VALUE = 2.0\n\n SAMPLE_RATE = 0.5\n\n TAGS = (\n\n TagPair(\"key\", \"value\"),\n\n TagPair(\"key2\", \"value2\"),\n\n )\n\n\n\n VALID_STR = \"some_str\"\n\n INVALID_STRS: Sequence[str] = (\n\n \"some|metric\",\n\n \"some#metric\",\n\n \"some,metric\",\n\n \"some:metric\",\n\n \"some=metric\",\n", "file_path": "src/python/grapl-common/tests/metrics/test_statsd_formatter.py", "rank": 83, "score": 95444.53437879392 }, { "content": "from typing_extensions import Protocol\n\nfrom grapl_tests_common.types import S3ServiceResource\n\nfrom grapl_tests_common.upload_sysmon_logs import upload_sysmon_logs\n\nimport logging\n\nimport subprocess\n\n\n\nBUCKET_PREFIX = \"local-grapl\"\n\n\n\n\n\nclass UploadTestData(Protocol):\n\n def upload(self, s3_client: S3ServiceResource) -> None:\n\n pass\n\n\n\n\n\nclass UploadSysmonLogsTestData(UploadTestData):\n\n def __init__(self, path: str) -> None:\n\n self.path = path\n\n\n\n def upload(self, s3_client: S3ServiceResource) -> None:\n\n logging.info(f\"S3 uploading test data from {self.path}\")\n\n upload_sysmon_logs(\n\n prefix=BUCKET_PREFIX,\n\n logfile=self.path,\n\n use_links=True,\n\n )\n", "file_path": "src/python/grapl-tests-common/grapl_tests_common/upload_test_data.py", "rank": 84, "score": 95444.53437879392 }, { "content": " def test__histogram_ctx(self) -> None:\n\n f = Fixture()\n\n\n\n dts = [\n\n # start\n\n datetime(\n\n year=2020, month=9, day=20, hour=1, minute=2, second=3, microsecond=1000\n\n ),\n\n # end, which is +3 milliseconds\n\n datetime(\n\n year=2020, month=9, day=20, hour=1, minute=2, second=3, microsecond=4000\n\n ),\n\n # this last one doesn't matter for measuring delta, just the timestamp\n\n datetime(\n\n year=2020, month=9, day=20, hour=1, minute=2, second=3, microsecond=8000\n\n ),\n\n ]\n\n\n\n def return_dts() -> datetime:\n\n return dts.pop(0)\n\n\n\n f.metric_reporter.utc_now = return_dts\n\n\n\n # histogram_ctx should get the two values\n\n with f.metric_reporter.histogram_ctx(\"some_metric\"):\n\n pass\n\n\n\n assert f.out.writes == [\n\n \"MONITORING|py_test_service|2020-09-20T01:02:03.008|some_metric:3|h\\n\",\n", "file_path": "src/python/grapl-common/tests/metrics/test_metric_reporter.py", "rank": 85, "score": 94142.44304384917 }, { "content": "def _upload_test_data(\n\n s3_client: S3ServiceResource, test_data: Sequence[UploadTestData]\n\n) -> None:\n\n logging.info(f\"Uploading test data...\")\n\n\n\n for datum in test_data:\n", "file_path": "src/python/grapl-tests-common/grapl_tests_common/setup.py", "rank": 86, "score": 94100.68949624927 }, { "content": " def __init__(self, path: str) -> None:\n", "file_path": "src/python/grapl-tests-common/grapl_tests_common/upload_test_data.py", "rank": 87, "score": 94100.68949624927 }, { "content": " def upload(self, s3_client: S3ServiceResource) -> None:\n\n logging.info(f\"S3 uploading test data from {self.path}\")\n\n upload_sysmon_logs(\n\n prefix=BUCKET_PREFIX,\n\n logfile=self.path,\n\n use_links=True,\n", "file_path": "src/python/grapl-tests-common/grapl_tests_common/upload_test_data.py", "rank": 88, "score": 94100.68949624927 }, { "content": " def test_basic_counter(self) -> None:\n\n result = statsd_format(\n\n metric_name=TestData.METRIC_NAME,\n\n value=TestData.VALUE,\n\n typ=\"c\",\n\n )\n", "file_path": "src/python/grapl-common/tests/metrics/test_statsd_formatter.py", "rank": 89, "score": 94095.13183475529 }, { "content": " def test_invalid_metric_names(self) -> None:\n\n for invalid_metric_name in TestData.INVALID_STRS:\n\n with pytest.raises(ValueError):\n\n statsd_format(\n\n metric_name=invalid_metric_name,\n\n value=TestData.VALUE,\n\n typ=\"c\",\n", "file_path": "src/python/grapl-common/tests/metrics/test_statsd_formatter.py", "rank": 90, "score": 92834.0577983903 }, { "content": " def __str__(self) -> str:\n", "file_path": "src/python/grapl-tests-common/grapl_tests_common/wait.py", "rank": 91, "score": 90929.33901644396 }, { "content": " def return_dts() -> datetime:\n", "file_path": "src/python/grapl-common/tests/metrics/test_metric_reporter.py", "rank": 92, "score": 89487.90052053261 }, { "content": "def rand_str(l: int) -> str:\n\n return \"\".join(\n\n random.choice(string.ascii_uppercase + string.digits) for _ in range(l)\n", "file_path": "src/python/grapl-tests-common/grapl_tests_common/upload_sysmon_logs.py", "rank": 93, "score": 86566.66979232519 }, { "content": "class test(_test):\n\n def run(self):\n\n compile_all_protobufs()\n", "file_path": "src/rust/graph-descriptions/setup.py", "rank": 94, "score": 85531.74743814397 }, { "content": " def histogram(\n\n self,\n\n metric_name: str,\n\n value: MillisDuration,\n\n tags: Sequence[TagPair] = (),\n\n ) -> None:\n\n \"\"\"\n\n A histogram is a measure of the distribution of timer values over time, calculated at the\n\n server. As the data exported for timers and histograms is the same,\n\n this is currently an alias for a timer.\n\n\n\n example: the time to complete rendering of a web page for a user.\n\n \"\"\"\n\n self.write_metric(\n\n metric_name=metric_name,\n\n value=value,\n\n typ=\"h\",\n\n tags=tags,\n", "file_path": "src/python/grapl-common/grapl_common/metrics/metric_reporter.py", "rank": 95, "score": 82475.57210393556 }, { "content": " def write(self, some_str: str) -> int:\n", "file_path": "src/python/grapl-common/grapl_common/metrics/metric_reporter.py", "rank": 96, "score": 82434.78191641736 }, { "content": " }\n\n }\n\n}\n\n\n\npub struct TagPair<'a>(pub &'a str, pub &'a str);\n\n\n\nimpl TagPair<'_> {\n\n pub fn write_to_buf(&self, buf: &mut String) -> Result<(), MetricError> {\n\n let TagPair(tag_key, tag_value) = self;\n\n statsd_formatter::reject_invalid_chars(tag_key)?;\n\n statsd_formatter::reject_invalid_chars(tag_value)?;\n\n Ok(write!(buf, \"{}:{}\", tag_key, tag_value)?)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n fn test_utc() -> DateTime<Utc> {\n", "file_path": "src/rust/grapl-observe/src/metric_reporter.rs", "rank": 98, "score": 60.89660078448028 } ]
Rust
src/distribution/internal.rs
Twister915/statrs
c5536a8c916852259832b2064a9b845b68751c8f
pub fn is_valid_multinomial(arr: &[f64], incl_zero: bool) -> bool { let mut sum = 0.0; for &elt in arr { if incl_zero && elt < 0.0 || !incl_zero && elt <= 0.0 || elt.is_nan() { return false; } sum += elt; } sum != 0.0 } #[cfg(test)] pub mod tests { use super::is_valid_multinomial; use crate::consts::ACC; use crate::distribution::{Continuous, ContinuousCDF, Discrete, DiscreteCDF}; fn check_integrate_pdf_is_cdf<D: ContinuousCDF<f64, f64> + Continuous<f64, f64>>( dist: &D, x_min: f64, x_max: f64, step: f64, ) { let mut prev_x = x_min; let mut prev_density = dist.pdf(x_min); let mut sum = 0.0; loop { let x = prev_x + step; let density = dist.pdf(x); assert!(density >= 0.0); let ln_density = dist.ln_pdf(x); assert_almost_eq!(density.ln(), ln_density, 1e-10); sum += (prev_density + density) * step / 2.0; let cdf = dist.cdf(x); if (sum - cdf).abs() > 1e-3 { println!("Integral of pdf doesn't equal cdf!"); println!("Integration from {} by {} to {} = {}", x_min, step, x, sum); println!("cdf = {}", cdf); panic!(); } if x >= x_max { break; } else { prev_x = x; prev_density = density; } } assert!(sum > 0.99); assert!(sum <= 1.001); } fn check_sum_pmf_is_cdf<D: DiscreteCDF<u64, f64> + Discrete<u64, f64>>(dist: &D, x_max: u64) { let mut sum = 0.0; for i in 0..x_max + 3 { let prob = dist.pmf(i); assert!(prob >= 0.0); assert!(prob <= 1.0); sum += prob; if i == x_max { assert!(sum > 0.99); } assert_almost_eq!(sum, dist.cdf(i), 1e-10); } assert!(sum > 0.99); assert!(sum <= 1.0 + 1e-10); } pub fn check_continuous_distribution<D: ContinuousCDF<f64, f64> + Continuous<f64, f64>>( dist: &D, x_min: f64, x_max: f64, ) { assert_eq!(dist.pdf(f64::NEG_INFINITY), 0.0); assert_eq!(dist.pdf(f64::INFINITY), 0.0); assert_eq!(dist.ln_pdf(f64::NEG_INFINITY), f64::NEG_INFINITY); assert_eq!(dist.ln_pdf(f64::INFINITY), f64::NEG_INFINITY); assert_eq!(dist.cdf(f64::NEG_INFINITY), 0.0); assert_eq!(dist.cdf(f64::INFINITY), 1.0); check_integrate_pdf_is_cdf(dist, x_min, x_max, (x_max - x_min) / 100000.0); } pub fn check_discrete_distribution<D: DiscreteCDF<u64, f64> + Discrete<u64, f64>>( dist: &D, x_max: u64, ) { check_sum_pmf_is_cdf(dist, x_max); } #[test] fn test_is_valid_multinomial() { use std::f64; let invalid = [1.0, f64::NAN, 3.0]; assert!(!is_valid_multinomial(&invalid, true)); let invalid2 = [-2.0, 5.0, 1.0, 6.2]; assert!(!is_valid_multinomial(&invalid2, true)); let invalid3 = [0.0, 0.0, 0.0]; assert!(!is_valid_multinomial(&invalid3, true)); let valid = [5.2, 0.0, 1e-15, 1000000.12]; assert!(is_valid_multinomial(&valid, true)); } #[test] fn test_is_valid_multinomial_no_zero() { let invalid = [5.2, 0.0, 1e-15, 1000000.12]; assert!(!is_valid_multinomial(&invalid, false)); } }
pub fn is_valid_multinomial(arr: &[f64], incl_zero: bool) -> bool { let mut sum = 0.0; for &elt in arr { if incl_zero && elt < 0.0 || !incl_zero && elt <= 0.0 || elt.is_nan() { return false; } sum += elt; } sum != 0.0 } #[cfg(test)] pub mod tests { use super::is_valid_multinomial; use crate::consts::ACC; use crate::distribution::{Continuous, ContinuousCDF, Discrete, DiscreteCDF};
fn check_sum_pmf_is_cdf<D: DiscreteCDF<u64, f64> + Discrete<u64, f64>>(dist: &D, x_max: u64) { let mut sum = 0.0; for i in 0..x_max + 3 { let prob = dist.pmf(i); assert!(prob >= 0.0); assert!(prob <= 1.0); sum += prob; if i == x_max { assert!(sum > 0.99); } assert_almost_eq!(sum, dist.cdf(i), 1e-10); } assert!(sum > 0.99); assert!(sum <= 1.0 + 1e-10); } pub fn check_continuous_distribution<D: ContinuousCDF<f64, f64> + Continuous<f64, f64>>( dist: &D, x_min: f64, x_max: f64, ) { assert_eq!(dist.pdf(f64::NEG_INFINITY), 0.0); assert_eq!(dist.pdf(f64::INFINITY), 0.0); assert_eq!(dist.ln_pdf(f64::NEG_INFINITY), f64::NEG_INFINITY); assert_eq!(dist.ln_pdf(f64::INFINITY), f64::NEG_INFINITY); assert_eq!(dist.cdf(f64::NEG_INFINITY), 0.0); assert_eq!(dist.cdf(f64::INFINITY), 1.0); check_integrate_pdf_is_cdf(dist, x_min, x_max, (x_max - x_min) / 100000.0); } pub fn check_discrete_distribution<D: DiscreteCDF<u64, f64> + Discrete<u64, f64>>( dist: &D, x_max: u64, ) { check_sum_pmf_is_cdf(dist, x_max); } #[test] fn test_is_valid_multinomial() { use std::f64; let invalid = [1.0, f64::NAN, 3.0]; assert!(!is_valid_multinomial(&invalid, true)); let invalid2 = [-2.0, 5.0, 1.0, 6.2]; assert!(!is_valid_multinomial(&invalid2, true)); let invalid3 = [0.0, 0.0, 0.0]; assert!(!is_valid_multinomial(&invalid3, true)); let valid = [5.2, 0.0, 1e-15, 1000000.12]; assert!(is_valid_multinomial(&valid, true)); } #[test] fn test_is_valid_multinomial_no_zero() { let invalid = [5.2, 0.0, 1e-15, 1000000.12]; assert!(!is_valid_multinomial(&invalid, false)); } }
fn check_integrate_pdf_is_cdf<D: ContinuousCDF<f64, f64> + Continuous<f64, f64>>( dist: &D, x_min: f64, x_max: f64, step: f64, ) { let mut prev_x = x_min; let mut prev_density = dist.pdf(x_min); let mut sum = 0.0; loop { let x = prev_x + step; let density = dist.pdf(x); assert!(density >= 0.0); let ln_density = dist.ln_pdf(x); assert_almost_eq!(density.ln(), ln_density, 1e-10); sum += (prev_density + density) * step / 2.0; let cdf = dist.cdf(x); if (sum - cdf).abs() > 1e-3 { println!("Integral of pdf doesn't equal cdf!"); println!("Integration from {} by {} to {} = {}", x_min, step, x, sum); println!("cdf = {}", cdf); panic!(); } if x >= x_max { break; } else { prev_x = x; prev_density = density; } } assert!(sum > 0.99); assert!(sum <= 1.001); }
function_block-full_function
[ { "content": "/// Computes the inverse of the regularized incomplete beta function\n\n//\n\n// This code is based on the implementation in the [\"special\"][1] crate,\n\n// which in turn is based on a [C implementation][2] by John Burkardt. The\n\n// original algorithm was published in Applied Statistics and is known as\n\n// [Algorithm AS 64][3] and [Algorithm AS 109][4].\n\n//\n\n// [1]: https://docs.rs/special/0.8.1/\n\n// [2]: http://people.sc.fsu.edu/~jburkardt/c_src/asa109/asa109.html\n\n// [3]: http://www.jstor.org/stable/2346798\n\n// [4]: http://www.jstor.org/stable/2346887\n\n//\n\n// > Copyright 2014–2019 The special Developers\n\n// >\n\n// > Permission is hereby granted, free of charge, to any person obtaining a copy of\n\n// > this software and associated documentation files (the “Software”), to deal in\n\n// > the Software without restriction, including without limitation the rights to\n\n// > use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n\n// > the Software, and to permit persons to whom the Software is furnished to do so,\n\n// > subject to the following conditions:\n\n// >\n\n// > The above copyright notice and this permission notice shall be included in all\n\n// > copies or substantial portions of the Software.\n\n// >\n\n// > THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n// > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n\n// > FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n\n// > COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n\n// > IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\n// > CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\npub fn inv_beta_reg(mut a: f64, mut b: f64, mut x: f64) -> f64 {\n\n // Algorithm AS 64\n\n // http://www.jstor.org/stable/2346798\n\n //\n\n // An approximation x₀ to x if found from (cf. Scheffé and Tukey, 1944)\n\n //\n\n // 1 + x₀ 4p + 2q - 2\n\n // ------ = -----------\n\n // 1 - x₀ χ²(α)\n\n //\n\n // where χ²(α) is the upper α point of the χ² distribution with 2q\n\n // degrees of freedom and is obtained from Wilson and Hilferty’s\n\n // approximation (cf. Wilson and Hilferty, 1931)\n\n //\n\n // χ²(α) = 2q (1 - 1 / (9q) + y(α) sqrt(1 / (9q)))^3,\n\n //\n\n // y(α) being Hastings’ approximation (cf. Hastings, 1955) for the upper\n\n // α point of the standard normal distribution. If χ²(α) < 0, then\n\n //\n\n // x₀ = 1 - ((1 - α)q B(p, q))^(1 / q).\n", "file_path": "src/function/beta.rs", "rank": 1, "score": 245535.86809645398 }, { "content": "/// Returns true if `a` and `b `are within `acc` of each other.\n\n/// If `a` or `b` are infinite, returns `true` only if both are\n\n/// infinite and similarly signed. Always returns `false` if\n\n/// either number is a `NAN`.\n\npub fn almost_eq(a: f64, b: f64, acc: f64) -> bool {\n\n // only true if a and b are infinite with same\n\n // sign\n\n if a.is_infinite() || b.is_infinite() {\n\n return a == b;\n\n }\n\n\n\n // NANs are never equal\n\n if a.is_nan() && b.is_nan() {\n\n return false;\n\n }\n\n\n\n (a - b).abs() < acc\n\n}\n", "file_path": "src/prec.rs", "rank": 2, "score": 230513.04934820894 }, { "content": "/// Loads a test data file into a vector of `f64`'s.\n\n/// Path is relative to /data.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the file does not exist or could not be opened, or\n\n/// there was an error reading the file.\n\npub fn load_data(path: &str) -> Vec<f64> {\n\n // note: the copious use of unwrap is because this is a test helper and\n\n // if reading the data file fails, we want to panic immediately\n\n\n\n let path_prefix = \"./data/\".to_string();\n\n let true_path = path_prefix + path.trim().trim_start_matches('/');\n\n\n\n let f = File::open(true_path).unwrap();\n\n let mut reader = BufReader::new(f);\n\n\n\n let mut buf = String::new();\n\n let mut data: Vec<f64> = vec![];\n\n while reader.read_line(&mut buf).unwrap() > 0 {\n\n data.push(buf.trim().parse::<f64>().unwrap());\n\n buf.clear();\n\n }\n\n data\n\n}\n", "file_path": "src/testing/mod.rs", "rank": 3, "score": 229198.2605868106 }, { "content": "// Selection algorithm from Numerical Recipes\n\n// See: https://en.wikipedia.org/wiki/Selection_algorithm\n\nfn select_inplace(arr: &mut [f64], rank: usize) -> f64 {\n\n if rank == 0 {\n\n return arr.min();\n\n }\n\n if rank > arr.len() - 1 {\n\n return arr.max();\n\n }\n\n\n\n let mut low = 0;\n\n let mut high = arr.len() - 1;\n\n loop {\n\n if high <= low + 1 {\n\n if high == low + 1 && arr[high] < arr[low] {\n\n arr.swap(low, high)\n\n }\n\n return arr[rank];\n\n }\n\n\n\n let middle = (low + high) / 2;\n\n arr.swap(middle, low + 1);\n", "file_path": "src/statistics/slice_statistics.rs", "rank": 4, "score": 228629.1228352983 }, { "content": "/// Generates one sample from the Poisson distribution either by\n\n/// Knuth's method if lambda < 30.0 or Rejection method PA by\n\n/// A. C. Atkinson from the Journal of the Royal Statistical Society\n\n/// Series C (Applied Statistics) Vol. 28 No. 1. (1979) pp. 29 - 35\n\n/// otherwise\n\npub fn sample_unchecked<R: Rng + ?Sized>(rng: &mut R, lambda: f64) -> f64 {\n\n if lambda < 30.0 {\n\n let limit = (-lambda).exp();\n\n let mut count = 0.0;\n\n let mut product: f64 = rng.gen();\n\n while product >= limit {\n\n count += 1.0;\n\n product *= rng.gen::<f64>();\n\n }\n\n count\n\n } else {\n\n let c = 0.767 - 3.36 / lambda;\n\n let beta = f64::consts::PI / (3.0 * lambda).sqrt();\n\n let alpha = beta * lambda;\n\n let k = c.ln() - lambda - beta.ln();\n\n\n\n loop {\n\n let u: f64 = rng.gen();\n\n let x = (alpha - ((1.0 - u) / u).ln()) / beta;\n\n let n = (x + 0.5).floor();\n", "file_path": "src/distribution/poisson.rs", "rank": 5, "score": 201454.6042727222 }, { "content": "/// Draws a sample from the categorical distribution described by `cdf`\n\n/// without doing any bounds checking\n\npub fn sample_unchecked<R: Rng + ?Sized>(rng: &mut R, cdf: &[f64]) -> f64 {\n\n let draw = rng.gen::<f64>() * cdf.last().unwrap();\n\n cdf.iter()\n\n .enumerate()\n\n .find(|(_, val)| **val >= draw)\n\n .map(|(i, _)| i)\n\n .unwrap() as f64\n\n}\n\n\n", "file_path": "src/distribution/categorical.rs", "rank": 6, "score": 201454.6042727222 }, { "content": "/// Samples from a gamma distribution with a shape of `shape` and a\n\n/// rate of `rate` using `rng` as the source of randomness. Implementation from:\n\n/// <br />\n\n/// <div>\n\n/// <i>\"A Simple Method for Generating Gamma Variables\"</i> - Marsaglia & Tsang\n\n/// </div>\n\n/// <div>\n\n/// ACM Transactions on Mathematical Software, Vol. 26, No. 3, September 2000,\n\n/// Pages 363-372\n\n/// </div>\n\n/// <br />\n\npub fn sample_unchecked<R: Rng + ?Sized>(rng: &mut R, shape: f64, rate: f64) -> f64 {\n\n let mut a = shape;\n\n let mut afix = 1.0;\n\n if shape < 1.0 {\n\n a = shape + 1.0;\n\n afix = rng.gen::<f64>().powf(1.0 / shape);\n\n }\n\n\n\n let d = a - 1.0 / 3.0;\n\n let c = 1.0 / (9.0 * d).sqrt();\n\n loop {\n\n let mut x;\n\n let mut v;\n\n loop {\n\n x = super::normal::sample_unchecked(rng, 0.0, 1.0);\n\n v = 1.0 + c * x;\n\n if v > 0.0 {\n\n break;\n\n };\n\n }\n", "file_path": "src/distribution/gamma.rs", "rank": 7, "score": 201195.9613590636 }, { "content": "/// draws a sample from a normal distribution using the Box-Muller algorithm\n\npub fn sample_unchecked<R: Rng + ?Sized>(rng: &mut R, mean: f64, std_dev: f64) -> f64 {\n\n mean + std_dev * ziggurat::sample_std_normal(rng)\n\n}\n\n\n\n#[rustfmt::skip]\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::statistics::*;\n\n use crate::distribution::{ContinuousCDF, Continuous, Normal};\n\n use crate::distribution::internal::*;\n\n use crate::consts::ACC;\n\n\n\n fn try_create(mean: f64, std_dev: f64) -> Normal {\n\n let n = Normal::new(mean, std_dev);\n\n assert!(n.is_ok());\n\n n.unwrap()\n\n }\n\n\n\n fn create_case(mean: f64, std_dev: f64) {\n\n let n = try_create(mean, std_dev);\n", "file_path": "src/distribution/normal.rs", "rank": 8, "score": 198686.12724719252 }, { "content": "pub fn sample_exp_1<R: Rng + ?Sized>(rng: &mut R) -> f64 {\n\n #[inline]\n\n fn pdf(x: f64) -> f64 {\n\n (-x).exp()\n\n }\n\n\n\n #[inline]\n\n fn zero_case<R: Rng + ?Sized>(rng: &mut R, _u: f64) -> f64 {\n\n ziggurat_tables::ZIG_EXP_R - rng.gen::<f64>().ln()\n\n }\n\n\n\n ziggurat(\n\n rng,\n\n false,\n\n &ziggurat_tables::ZIG_EXP_X,\n\n &ziggurat_tables::ZIG_EXP_F,\n\n pdf,\n\n zero_case,\n\n )\n\n}\n\n\n\n// Ziggurat method for sampling a random number based on the ZIGNOR\n\n// variant from Doornik 2005. Code borrowed from\n\n// https://github.com/rust-lang-nursery/rand/blob/master/src/distributions/mod.\n\n// rs#L223\n", "file_path": "src/distribution/ziggurat.rs", "rank": 9, "score": 195159.5885631999 }, { "content": "pub fn sample_std_normal<R: Rng + ?Sized>(rng: &mut R) -> f64 {\n\n #[inline]\n\n fn pdf(x: f64) -> f64 {\n\n (-x * x / 2.0).exp()\n\n }\n\n\n\n #[inline]\n\n fn zero_case<R: Rng + ?Sized>(rng: &mut R, u: f64) -> f64 {\n\n let mut x = 1.0f64;\n\n let mut y = 0.0f64;\n\n while -2.0 * y < x * x {\n\n let x_: f64 = rng.sample(Open01);\n\n let y_: f64 = rng.sample(Open01);\n\n\n\n x = x_.ln() / ziggurat_tables::ZIG_NORM_R;\n\n y = y_.ln();\n\n }\n\n if u < 0.0 {\n\n x - ziggurat_tables::ZIG_NORM_R\n\n } else {\n", "file_path": "src/distribution/ziggurat.rs", "rank": 10, "score": 192028.3378596331 }, { "content": "/// Computes the beta function\n\n/// where `a` is the first beta parameter\n\n/// and `b` is the second beta parameter.\n\n///\n\n///\n\n/// # Panics\n\n///\n\n/// if `a <= 0.0` or `b <= 0.0`\n\npub fn beta(a: f64, b: f64) -> f64 {\n\n checked_beta(a, b).unwrap()\n\n}\n\n\n", "file_path": "src/function/beta.rs", "rank": 11, "score": 182575.32176618732 }, { "content": "/// `erf_impl` computes the error function at `z`.\n\n/// If `inv` is true, `1 - erf` is calculated as opposed to `erf`\n\nfn erf_impl(z: f64, inv: bool) -> f64 {\n\n if z < 0.0 {\n\n if !inv {\n\n return -erf_impl(-z, false);\n\n }\n\n if z < -0.5 {\n\n return 2.0 - erf_impl(-z, true);\n\n }\n\n return 1.0 + erf_impl(-z, false);\n\n }\n\n\n\n let result = if z < 0.5 {\n\n if z < 1e-10 {\n\n z * 1.125 + z * 0.003379167095512573896158903121545171688\n\n } else {\n\n z * 1.125\n\n + z * evaluate::polynomial(z, ERF_IMPL_AN) / evaluate::polynomial(z, ERF_IMPL_AD)\n\n }\n\n } else if z < 110.0 {\n\n let (r, b) = if z < 0.75 {\n", "file_path": "src/function/erf.rs", "rank": 12, "score": 182504.55072660287 }, { "content": "/// `erfc` calculates the complementary error function\n\n/// at `x`.\n\npub fn erfc(x: f64) -> f64 {\n\n if x.is_nan() {\n\n f64::NAN\n\n } else if x == f64::INFINITY {\n\n 0.0\n\n } else if x == f64::NEG_INFINITY {\n\n 2.0\n\n } else {\n\n erf_impl(x, true)\n\n }\n\n}\n\n\n", "file_path": "src/function/erf.rs", "rank": 13, "score": 181964.49895934653 }, { "content": "/// Computes the Digamma function which is defined as the derivative of\n\n/// the log of the gamma function. The implementation is based on\n\n/// \"Algorithm AS 103\", Jose Bernardo, Applied Statistics, Volume 25, Number 3\n\n/// 1976, pages 315 - 317\n\npub fn digamma(x: f64) -> f64 {\n\n let c = 12.0;\n\n let d1 = -0.57721566490153286;\n\n let d2 = 1.6449340668482264365;\n\n let s = 1e-6;\n\n let s3 = 1.0 / 12.0;\n\n let s4 = 1.0 / 120.0;\n\n let s5 = 1.0 / 252.0;\n\n let s6 = 1.0 / 240.0;\n\n let s7 = 1.0 / 132.0;\n\n\n\n if x == f64::NEG_INFINITY || x.is_nan() {\n\n return f64::NAN;\n\n }\n\n if x <= 0.0 && ulps_eq!(x.floor(), x) {\n\n return f64::NEG_INFINITY;\n\n }\n\n if x < 0.0 {\n\n return digamma(1.0 - x) + f64::consts::PI / (-f64::consts::PI * x).tan();\n\n }\n", "file_path": "src/function/gamma.rs", "rank": 14, "score": 181964.49895934653 }, { "content": "/// Computes the gamma function with an accuracy\n\n/// of 16 floating point digits. The implementation\n\n/// is derived from \"An Analysis of the Lanczos Gamma Approximation\",\n\n/// Glendon Ralph Pugh, 2004 p. 116\n\npub fn gamma(x: f64) -> f64 {\n\n if x < 0.5 {\n\n let s = GAMMA_DK\n\n .iter()\n\n .enumerate()\n\n .skip(1)\n\n .fold(GAMMA_DK[0], |s, t| s + t.1 / (t.0 as f64 - x));\n\n\n\n f64::consts::PI\n\n / ((f64::consts::PI * x).sin()\n\n * s\n\n * consts::TWO_SQRT_E_OVER_PI\n\n * ((0.5 - x + GAMMA_R) / f64::consts::E).powf(0.5 - x))\n\n } else {\n\n let s = GAMMA_DK\n\n .iter()\n\n .enumerate()\n\n .skip(1)\n\n .fold(GAMMA_DK[0], |s, t| s + t.1 / (x + t.0 as f64 - 1.0));\n\n\n\n s * consts::TWO_SQRT_E_OVER_PI * ((x - 0.5 + GAMMA_R) / f64::consts::E).powf(x - 0.5)\n\n }\n\n}\n\n\n", "file_path": "src/function/gamma.rs", "rank": 15, "score": 181964.49895934653 }, { "content": "/// Computes the logistic function\n\npub fn logistic(p: f64) -> f64 {\n\n 1.0 / ((-p).exp() + 1.0)\n\n}\n\n\n", "file_path": "src/function/logistic.rs", "rank": 16, "score": 181964.49895934653 }, { "content": "/// Computes the logit function\n\n///\n\n/// # Panics\n\n///\n\n/// If `p < 0.0` or `p > 1.0`\n\npub fn logit(p: f64) -> f64 {\n\n checked_logit(p).unwrap()\n\n}\n\n\n", "file_path": "src/function/logistic.rs", "rank": 17, "score": 181964.49895934653 }, { "content": "/// `erf` calculates the error function at `x`.\n\npub fn erf(x: f64) -> f64 {\n\n if x.is_nan() {\n\n f64::NAN\n\n } else if x >= 0.0 && x.is_infinite() {\n\n 1.0\n\n } else if x <= 0.0 && x.is_infinite() {\n\n -1.0\n\n } else if is_zero(x) {\n\n 0.0\n\n } else {\n\n erf_impl(x, false)\n\n }\n\n}\n\n\n", "file_path": "src/function/erf.rs", "rank": 18, "score": 181964.49895934653 }, { "content": "/// Computes the upper incomplete regularized gamma function\n\n/// `Q(a,x) = 1 / Gamma(a) * int(exp(-t)t^(a-1), t=0..x) for a > 0, x > 0`\n\n/// where `a` is the argument for the gamma function and\n\n/// `x` is the lower integral limit.\n\n///\n\n/// # Remarks\n\n///\n\n/// Returns `f64::NAN` if either argument is `f64::NAN`\n\n///\n\n/// # Panics\n\n///\n\n/// if `a` or `x` are not in `(0, +inf)`\n\npub fn gamma_ur(a: f64, x: f64) -> f64 {\n\n checked_gamma_ur(a, x).unwrap()\n\n}\n\n\n", "file_path": "src/function/gamma.rs", "rank": 19, "score": 179917.17684289336 }, { "content": "/// Computes the lower incomplete regularized gamma function\n\n/// `P(a,x) = 1 / Gamma(a) * int(exp(-t)t^(a-1), t=0..x) for real a > 0, x > 0`\n\n/// where `a` is the argument for the gamma function and `x` is the upper\n\n/// integral limit.\n\n///\n\n/// # Remarks\n\n///\n\n/// Returns `f64::NAN` if either argument is `f64::NAN`\n\n///\n\n/// # Panics\n\n///\n\n/// if `a` or `x` are not in `(0, +inf)`\n\npub fn gamma_lr(a: f64, x: f64) -> f64 {\n\n checked_gamma_lr(a, x).unwrap()\n\n}\n\n\n", "file_path": "src/function/gamma.rs", "rank": 20, "score": 179917.12019421248 }, { "content": "/// evaluates a polynomial at `z` where `coeff` are the coeffecients\n\n/// to a polynomial of order `k` where `k` is the length of `coeff` and the\n\n/// coeffecient\n\n/// to the `k`th power is the `k`th element in coeff. E.g. [3,-1,2] equates to\n\n/// `2z^2 - z + 3`\n\n///\n\n/// # Remarks\n\n///\n\n/// Returns 0 for a 0 length coefficient slice\n\npub fn polynomial(z: f64, coeff: &[f64]) -> f64 {\n\n let n = coeff.len();\n\n if n == 0 {\n\n return 0.0;\n\n }\n\n\n\n let mut sum = *coeff.last().unwrap();\n\n for c in coeff[0..n - 1].iter().rev() {\n\n sum = *c + z * sum;\n\n }\n\n sum\n\n}\n\n\n\n#[rustfmt::skip]\n\n#[cfg(test)]\n\nmod tests {\n\n use std::f64;\n\n\n\n // these tests probably could be more robust\n\n #[test]\n", "file_path": "src/function/evaluate.rs", "rank": 21, "score": 179913.170540715 }, { "content": "/// Computes the lower incomplete gamma function\n\n/// `gamma(a,x) = int(exp(-t)t^(a-1), t=0..x) for a > 0, x > 0`\n\n/// where `a` is the argument for the gamma function and `x`\n\n/// is the upper integral limit.\n\n///\n\n///\n\n/// # Panics\n\n///\n\n/// if `a` or `x` are not in `(0, +inf)`\n\npub fn gamma_li(a: f64, x: f64) -> f64 {\n\n checked_gamma_li(a, x).unwrap()\n\n}\n\n\n", "file_path": "src/function/gamma.rs", "rank": 22, "score": 179909.09315158307 }, { "content": "/// Computes the upper incomplete gamma function\n\n/// `Gamma(a,x) = int(exp(-t)t^(a-1), t=0..x) for a > 0, x > 0`\n\n/// where `a` is the argument for the gamma function and\n\n/// `x` is the lower intergral limit.\n\n///\n\n/// # Panics\n\n///\n\n/// if `a` or `x` are not in `(0, +inf)`\n\npub fn gamma_ui(a: f64, x: f64) -> f64 {\n\n checked_gamma_ui(a, x).unwrap()\n\n}\n\n\n", "file_path": "src/function/gamma.rs", "rank": 23, "score": 179909.09315158307 }, { "content": "/// Computes the natural logarithm\n\n/// of the beta function\n\n/// where `a` is the first beta parameter\n\n/// and `b` is the second beta parameter\n\n/// and `a > 0`, `b > 0`.\n\n///\n\n/// # Panics\n\n///\n\n/// if `a <= 0.0` or `b <= 0.0`\n\npub fn ln_beta(a: f64, b: f64) -> f64 {\n\n checked_ln_beta(a, b).unwrap()\n\n}\n\n\n", "file_path": "src/function/beta.rs", "rank": 24, "score": 179909.09315158307 }, { "content": "pub fn inv_digamma(x: f64) -> f64 {\n\n if x.is_nan() {\n\n return f64::NAN;\n\n }\n\n if x == f64::NEG_INFINITY {\n\n return 0.0;\n\n }\n\n if x == f64::INFINITY {\n\n return f64::INFINITY;\n\n }\n\n let mut y = x.exp();\n\n let mut i = 1.0;\n\n while i > 1e-15 {\n\n y += i * signum(x - digamma(y));\n\n i /= 2.0;\n\n }\n\n y\n\n}\n\n\n", "file_path": "src/function/gamma.rs", "rank": 25, "score": 179007.4538914215 }, { "content": "/// Computes the logarithm of the gamma function\n\n/// with an accuracy of 16 floating point digits.\n\n/// The implementation is derived from\n\n/// \"An Analysis of the Lanczos Gamma Approximation\",\n\n/// Glendon Ralph Pugh, 2004 p. 116\n\npub fn ln_gamma(x: f64) -> f64 {\n\n if x < 0.5 {\n\n let s = GAMMA_DK\n\n .iter()\n\n .enumerate()\n\n .skip(1)\n\n .fold(GAMMA_DK[0], |s, t| s + t.1 / (t.0 as f64 - x));\n\n\n\n consts::LN_PI\n\n - (f64::consts::PI * x).sin().ln()\n\n - s.ln()\n\n - consts::LN_2_SQRT_E_OVER_PI\n\n - (0.5 - x) * ((0.5 - x + GAMMA_R) / f64::consts::E).ln()\n\n } else {\n\n let s = GAMMA_DK\n\n .iter()\n\n .enumerate()\n\n .skip(1)\n\n .fold(GAMMA_DK[0], |s, t| s + t.1 / (x + t.0 as f64 - 1.0));\n\n\n\n s.ln()\n\n + consts::LN_2_SQRT_E_OVER_PI\n\n + (x - 0.5) * ((x - 0.5 + GAMMA_R) / f64::consts::E).ln()\n\n }\n\n}\n\n\n", "file_path": "src/function/gamma.rs", "rank": 26, "score": 179007.4538914215 }, { "content": "/// `erf_inv` calculates the inverse error function\n\n/// at `x`.\n\npub fn erf_inv(x: f64) -> f64 {\n\n if x == 0.0 {\n\n 0.0\n\n } else if x >= 1.0 {\n\n f64::INFINITY\n\n } else if x <= -1.0 {\n\n f64::NEG_INFINITY\n\n } else if x < 0.0 {\n\n erf_inv_impl(-x, 1.0 + x, -1.0)\n\n } else {\n\n erf_inv_impl(x, 1.0 - x, 1.0)\n\n }\n\n}\n\n\n", "file_path": "src/function/erf.rs", "rank": 27, "score": 179007.4538914215 }, { "content": "/// `erfc_inv` calculates the complementary inverse\n\n/// error function at `x`.\n\npub fn erfc_inv(x: f64) -> f64 {\n\n if x <= 0.0 {\n\n f64::INFINITY\n\n } else if x >= 2.0 {\n\n f64::NEG_INFINITY\n\n } else if x > 1.0 {\n\n erf_inv_impl(-1.0 + x, 2.0 - x, -1.0)\n\n } else {\n\n erf_inv_impl(1.0 - x, x, 1.0)\n\n }\n\n}\n\n\n\n// **********************************************************\n\n// ********** Coefficients for erf_impl polynomial **********\n\n// **********************************************************\n\n\n\n/// Polynomial coefficients for a numerator of `erf_impl`\n\n/// in the interval [1e-10, 0.5].\n\nconst ERF_IMPL_AN: &[f64] = &[\n\n 0.00337916709551257388990745,\n", "file_path": "src/function/erf.rs", "rank": 28, "score": 179007.4538914215 }, { "content": "/// Computes the lower incomplete (unregularized) beta function\n\n/// `B(a,b,x) = int(t^(a-1)*(1-t)^(b-1),t=0..x)` for `a > 0, b > 0, 1 >= x >= 0`\n\n/// where `a` is the first beta parameter, `b` is the second beta parameter, and\n\n/// `x` is the upper limit of the integral\n\n///\n\n/// # Panics\n\n///\n\n/// If `a <= 0.0`, `b <= 0.0`, `x < 0.0`, or `x > 1.0`\n\npub fn beta_inc(a: f64, b: f64, x: f64) -> f64 {\n\n checked_beta_inc(a, b, x).unwrap()\n\n}\n\n\n", "file_path": "src/function/beta.rs", "rank": 29, "score": 178901.980886418 }, { "content": "/// Computes the regularized lower incomplete beta function\n\n/// `I_x(a,b) = 1/Beta(a,b) * int(t^(a-1)*(1-t)^(b-1), t=0..x)`\n\n/// `a > 0`, `b > 0`, `1 >= x >= 0` where `a` is the first beta parameter,\n\n/// `b` is the second beta parameter, and `x` is the upper limit of the\n\n/// integral.\n\n///\n\n/// # Panics\n\n///\n\n/// if `a <= 0.0`, `b <= 0.0`, `x < 0.0`, or `x > 1.0`\n\npub fn beta_reg(a: f64, b: f64, x: f64) -> f64 {\n\n checked_beta_reg(a, b, x).unwrap()\n\n}\n\n\n", "file_path": "src/function/beta.rs", "rank": 30, "score": 178901.980886418 }, { "content": "// determines if `a` is a valid alpha array\n\n// for the Dirichlet distribution\n\nfn is_valid_alpha(a: &[f64]) -> bool {\n\n a.len() >= 2 && super::internal::is_valid_multinomial(a, false)\n\n}\n\n\n\n#[rustfmt::skip]\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use nalgebra::{DVector};\n\n use crate::function::gamma;\n\n use crate::statistics::*;\n\n use crate::distribution::{Continuous, Dirichlet};\n\n use crate::consts::ACC;\n\n\n\n #[test]\n\n fn test_is_valid_alpha() {\n\n let invalid = [1.0];\n\n assert!(!is_valid_alpha(&invalid));\n\n }\n\n\n", "file_path": "src/distribution/dirichlet.rs", "rank": 31, "score": 178226.22319270796 }, { "content": "/// Computes the beta function\n\n/// where `a` is the first beta parameter\n\n/// and `b` is the second beta parameter.\n\n///\n\n///\n\n/// # Errors\n\n///\n\n/// if `a <= 0.0` or `b <= 0.0`\n\npub fn checked_beta(a: f64, b: f64) -> Result<f64> {\n\n checked_ln_beta(a, b).map(|x| x.exp())\n\n}\n\n\n", "file_path": "src/function/beta.rs", "rank": 32, "score": 175616.25560186658 }, { "content": "/// Computes the logit function\n\n///\n\n/// # Errors\n\n///\n\n/// If `p < 0.0` or `p > 1.0`\n\npub fn checked_logit(p: f64) -> Result<f64> {\n\n if p < 0.0 || p > 1.0 {\n\n Err(StatsError::ArgIntervalIncl(\"p\", 0.0, 1.0))\n\n } else {\n\n Ok((p / (1.0 - p)).ln())\n\n }\n\n}\n\n\n\n#[rustfmt::skip]\n\n#[cfg(test)]\n\nmod tests {\n\n use std::f64;\n\n\n\n #[test]\n\n fn test_logistic() {\n\n assert_eq!(super::logistic(f64::NEG_INFINITY), 0.0);\n\n assert_eq!(super::logistic(-11.512915464920228103874353849992239636376994324587), 0.00001);\n\n assert_almost_eq!(super::logistic(-6.9067547786485535272274487616830597875179908939086), 0.001, 1e-18);\n\n assert_almost_eq!(super::logistic(-2.1972245773362193134015514347727700402304323440139), 0.1, 1e-16);\n\n assert_eq!(super::logistic(0.0), 0.5);\n", "file_path": "src/function/logistic.rs", "rank": 33, "score": 174020.69806814773 }, { "content": "/// Computes the upper incomplete regularized gamma function\n\n/// `Q(a,x) = 1 / Gamma(a) * int(exp(-t)t^(a-1), t=0..x) for a > 0, x > 0`\n\n/// where `a` is the argument for the gamma function and\n\n/// `x` is the lower integral limit.\n\n///\n\n/// # Remarks\n\n///\n\n/// Returns `f64::NAN` if either argument is `f64::NAN`\n\n///\n\n/// # Errors\n\n///\n\n/// if `a` or `x` are not in `(0, +inf)`\n\npub fn checked_gamma_ur(a: f64, x: f64) -> Result<f64> {\n\n if a.is_nan() || x.is_nan() {\n\n return Ok(f64::NAN);\n\n }\n\n if a <= 0.0 || a == f64::INFINITY {\n\n return Err(StatsError::ArgIntervalExcl(\"a\", 0.0, f64::INFINITY));\n\n }\n\n if x <= 0.0 || x == f64::INFINITY {\n\n return Err(StatsError::ArgIntervalExcl(\"x\", 0.0, f64::INFINITY));\n\n }\n\n\n\n let eps = 0.000000000000001;\n\n let big = 4503599627370496.0;\n\n let big_inv = 2.22044604925031308085e-16;\n\n\n\n if x < 1.0 || x <= a {\n\n return Ok(1.0 - gamma_lr(a, x));\n\n }\n\n\n\n let mut ax = a * x.ln() - x - ln_gamma(a);\n", "file_path": "src/function/gamma.rs", "rank": 34, "score": 173183.4709180224 }, { "content": "/// Computes the lower incomplete regularized gamma function\n\n/// `P(a,x) = 1 / Gamma(a) * int(exp(-t)t^(a-1), t=0..x) for real a > 0, x > 0`\n\n/// where `a` is the argument for the gamma function and `x` is the upper\n\n/// integral limit.\n\n///\n\n/// # Remarks\n\n///\n\n/// Returns `f64::NAN` if either argument is `f64::NAN`\n\n///\n\n/// # Errors\n\n///\n\n/// if `a` or `x` are not in `(0, +inf)`\n\npub fn checked_gamma_lr(a: f64, x: f64) -> Result<f64> {\n\n if a.is_nan() || x.is_nan() {\n\n return Ok(f64::NAN);\n\n }\n\n if a <= 0.0 || a == f64::INFINITY {\n\n return Err(StatsError::ArgIntervalExcl(\"a\", 0.0, f64::INFINITY));\n\n }\n\n if x <= 0.0 || x == f64::INFINITY {\n\n return Err(StatsError::ArgIntervalExcl(\"x\", 0.0, f64::INFINITY));\n\n }\n\n\n\n let eps = 0.000000000000001;\n\n let big = 4503599627370496.0;\n\n let big_inv = 2.22044604925031308085e-16;\n\n\n\n if prec::almost_eq(a, 0.0, prec::DEFAULT_F64_ACC) {\n\n return Ok(1.0);\n\n }\n\n if prec::almost_eq(x, 0.0, prec::DEFAULT_F64_ACC) {\n\n return Ok(0.0);\n", "file_path": "src/function/gamma.rs", "rank": 35, "score": 173183.4142693415 }, { "content": "/// Computes the natural logarithm\n\n/// of the beta function\n\n/// where `a` is the first beta parameter\n\n/// and `b` is the second beta parameter\n\n/// and `a > 0`, `b > 0`.\n\n///\n\n/// # Errors\n\n///\n\n/// if `a <= 0.0` or `b <= 0.0`\n\npub fn checked_ln_beta(a: f64, b: f64) -> Result<f64> {\n\n if a <= 0.0 {\n\n Err(StatsError::ArgMustBePositive(\"a\"))\n\n } else if b <= 0.0 {\n\n Err(StatsError::ArgMustBePositive(\"b\"))\n\n } else {\n\n Ok(gamma::ln_gamma(a) + gamma::ln_gamma(b) - gamma::ln_gamma(a + b))\n\n }\n\n}\n\n\n", "file_path": "src/function/beta.rs", "rank": 36, "score": 173175.38722671208 }, { "content": "/// Computes the upper incomplete gamma function\n\n/// `Gamma(a,x) = int(exp(-t)t^(a-1), t=0..x) for a > 0, x > 0`\n\n/// where `a` is the argument for the gamma function and\n\n/// `x` is the lower intergral limit.\n\n///\n\n/// # Errors\n\n///\n\n/// if `a` or `x` are not in `(0, +inf)`\n\npub fn checked_gamma_ui(a: f64, x: f64) -> Result<f64> {\n\n checked_gamma_ur(a, x).map(|x| x * gamma(a))\n\n}\n\n\n", "file_path": "src/function/gamma.rs", "rank": 37, "score": 173175.38722671208 }, { "content": "/// Computes the lower incomplete gamma function\n\n/// `gamma(a,x) = int(exp(-t)t^(a-1), t=0..x) for a > 0, x > 0`\n\n/// where `a` is the argument for the gamma function and `x`\n\n/// is the upper integral limit.\n\n///\n\n///\n\n/// # Errors\n\n///\n\n/// if `a` or `x` are not in `(0, +inf)`\n\npub fn checked_gamma_li(a: f64, x: f64) -> Result<f64> {\n\n checked_gamma_lr(a, x).map(|x| x * gamma(a))\n\n}\n\n\n", "file_path": "src/function/gamma.rs", "rank": 38, "score": 173175.38722671208 }, { "content": "/// Computes the lower incomplete (unregularized) beta function\n\n/// `B(a,b,x) = int(t^(a-1)*(1-t)^(b-1),t=0..x)` for `a > 0, b > 0, 1 >= x >= 0`\n\n/// where `a` is the first beta parameter, `b` is the second beta parameter, and\n\n/// `x` is the upper limit of the integral\n\n///\n\n/// # Errors\n\n///\n\n/// If `a <= 0.0`, `b <= 0.0`, `x < 0.0`, or `x > 1.0`\n\npub fn checked_beta_inc(a: f64, b: f64, x: f64) -> Result<f64> {\n\n checked_beta_reg(a, b, x).and_then(|x| checked_beta(a, b).map(|y| x * y))\n\n}\n\n\n", "file_path": "src/function/beta.rs", "rank": 39, "score": 172871.11494149466 }, { "content": "/// Computes the regularized lower incomplete beta function\n\n/// `I_x(a,b) = 1/Beta(a,b) * int(t^(a-1)*(1-t)^(b-1), t=0..x)`\n\n/// `a > 0`, `b > 0`, `1 >= x >= 0` where `a` is the first beta parameter,\n\n/// `b` is the second beta parameter, and `x` is the upper limit of the\n\n/// integral.\n\n///\n\n/// # Errors\n\n///\n\n/// if `a <= 0.0`, `b <= 0.0`, `x < 0.0`, or `x > 1.0`\n\npub fn checked_beta_reg(a: f64, b: f64, x: f64) -> Result<f64> {\n\n if a <= 0.0 {\n\n Err(StatsError::ArgMustBePositive(\"a\"))\n\n } else if b <= 0.0 {\n\n Err(StatsError::ArgMustBePositive(\"b\"))\n\n } else if x < 0.0 || x > 1.0 {\n\n Err(StatsError::ArgIntervalIncl(\"x\", 0.0, 1.0))\n\n } else {\n\n let bt = if is_zero(x) || ulps_eq!(x, 1.0) {\n\n 0.0\n\n } else {\n\n (gamma::ln_gamma(a + b) - gamma::ln_gamma(a) - gamma::ln_gamma(b)\n\n + a * x.ln()\n\n + b * (1.0 - x).ln())\n\n .exp()\n\n };\n\n let symm_transform = x >= (a + 1.0) / (a + b + 2.0);\n\n let eps = prec::F64_PREC;\n\n let fpmin = f64::MIN_POSITIVE / eps;\n\n\n", "file_path": "src/function/beta.rs", "rank": 40, "score": 172871.11494149466 }, { "content": "/// performs an unchecked pdf calculation for a normal distribution\n\n/// with the given mean and standard deviation at x\n\npub fn pdf_unchecked(x: f64, mean: f64, std_dev: f64) -> f64 {\n\n let d = (x - mean) / std_dev;\n\n (-0.5 * d * d).exp() / (consts::SQRT_2PI * std_dev)\n\n}\n\n\n", "file_path": "src/distribution/normal.rs", "rank": 41, "score": 172162.1986770452 }, { "content": "/// performs an unchecked cdf calculation for a normal distribution\n\n/// with the given mean and standard deviation at x\n\npub fn cdf_unchecked(x: f64, mean: f64, std_dev: f64) -> f64 {\n\n 0.5 * erf::erfc((mean - x) / (std_dev * f64::consts::SQRT_2))\n\n}\n\n\n", "file_path": "src/distribution/normal.rs", "rank": 42, "score": 172162.1986770452 }, { "content": "/// Computes the generalized harmonic number of order `n` of `m`\n\n/// e.g. `(1 + 1/2^m + 1/3^m + ... + 1/n^m)`\n\n///\n\n/// # Remarks\n\n///\n\n/// Returns `1` as a special case when `n == 0`\n\npub fn gen_harmonic(n: u64, m: f64) -> f64 {\n\n match n {\n\n 0 => 1.0,\n\n _ => (0..n).fold(0.0, |acc, x| acc + (x as f64 + 1.0).powf(-m)),\n\n }\n\n}\n\n\n\n#[rustfmt::skip]\n\n#[cfg(test)]\n\nmod tests {\n\n use std::f64;\n\n\n\n #[test]\n\n fn test_harmonic() {\n\n assert_eq!(super::harmonic(0), 1.0);\n\n assert_almost_eq!(super::harmonic(1), 1.0, 1e-14);\n\n assert_almost_eq!(super::harmonic(2), 1.5, 1e-14);\n\n assert_almost_eq!(super::harmonic(4), 2.083333333333333333333, 1e-14);\n\n assert_almost_eq!(super::harmonic(8), 2.717857142857142857143, 1e-14);\n\n assert_almost_eq!(super::harmonic(16), 3.380728993228993228993, 1e-14);\n", "file_path": "src/function/harmonic.rs", "rank": 43, "score": 172037.5938055804 }, { "content": "/// Computes the generalized Exponential Integral function\n\n/// where `x` is the argument and `n` is the integer power of the\n\n/// denominator term.\n\n///\n\n/// # Errors\n\n///\n\n/// Returns an error if `x < 0.0` or the computation could not\n\n/// converge after 100 iterations\n\n///\n\n/// # Remarks\n\n///\n\n/// This implementation follows the derivation in\n\n/// <br />\n\n/// <div>\n\n/// <i>\"Handbook of Mathematical Functions, Applied Mathematics Series, Volume\n\n/// 55\"</i> - Abramowitz, M., and Stegun, I.A 1964\n\n/// </div>\n\n/// AND\n\n/// <br />\n\n/// <div>\n\n/// <i>\"Advanced mathematical methods for scientists and engineers\" - Bender,\n\n/// Carl M.; Steven A. Orszag (1978). page 253\n\n/// </div>\n\n/// <br />\n\n/// The continued fraction approac is used for `x > 1.0` while the taylor\n\n/// series expansions\n\n/// is used for `0.0 < x <= 1`\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// ```\n\npub fn integral(x: f64, n: u64) -> Result<f64> {\n\n let eps = 0.00000000000000001;\n\n let max_iter = 100;\n\n let nf64 = n as f64;\n\n let near_f64min = 1e-100; // needs very small value that is not quite as small as f64 min\n\n\n\n // special cases\n\n if n == 0 {\n\n return Ok((-1.0 * x).exp() / x);\n\n }\n\n if x == 0.0 {\n\n return Ok(1.0 / (nf64 - 1.0));\n\n }\n\n\n\n if x > 1.0 {\n\n let mut b = x + nf64;\n\n let mut c = 1.0 / near_f64min;\n\n let mut d = 1.0 / b;\n\n let mut h = d;\n\n for i in 1..max_iter + 1 {\n", "file_path": "src/function/exponential.rs", "rank": 44, "score": 170209.74973339878 }, { "content": "/// performs an unchecked log(pdf) calculation for a normal distribution\n\n/// with the given mean and standard deviation at x\n\npub fn ln_pdf_unchecked(x: f64, mean: f64, std_dev: f64) -> f64 {\n\n let d = (x - mean) / std_dev;\n\n (-0.5 * d * d) - consts::LN_SQRT_2PI - std_dev.ln()\n\n}\n\n\n", "file_path": "src/distribution/normal.rs", "rank": 45, "score": 170092.29378131084 }, { "content": "/// Computes the factorial function `x -> x!` for\n\n/// `170 >= x >= 0`. All factorials larger than `170!`\n\n/// will overflow an `f64`.\n\n///\n\n/// # Remarks\n\n///\n\n/// Returns `f64::INFINITY` if `x > 170`\n\npub fn factorial(x: u64) -> f64 {\n\n if x > MAX_ARG {\n\n f64::INFINITY\n\n } else {\n\n get_fcache()[x as usize]\n\n }\n\n}\n\n\n", "file_path": "src/function/factorial.rs", "rank": 46, "score": 166339.49476945592 }, { "content": "/// Computes the `t`-th harmonic number\n\n///\n\n/// # Remarks\n\n///\n\n/// Returns `1` as a special case when `t == 0`\n\npub fn harmonic(t: u64) -> f64 {\n\n match t {\n\n 0 => 1.0,\n\n _ => consts::EULER_MASCHERONI + gamma::digamma(t as f64 + 1.0),\n\n }\n\n}\n\n\n", "file_path": "src/function/harmonic.rs", "rank": 47, "score": 166335.1464473126 }, { "content": "/// Computes the cdf from the given probability masses. Performs\n\n/// no parameter or bounds checking.\n\npub fn prob_mass_to_cdf(prob_mass: &[f64]) -> Vec<f64> {\n\n let mut cdf = Vec::with_capacity(prob_mass.len());\n\n prob_mass.iter().fold(0.0, |s, p| {\n\n let sum = s + p;\n\n cdf.push(sum);\n\n sum\n\n });\n\n cdf\n\n}\n\n\n", "file_path": "src/distribution/categorical.rs", "rank": 48, "score": 166290.70193248783 }, { "content": "/// Computes the logarithmic factorial function `x -> ln(x!)`\n\n/// for `x >= 0`.\n\n///\n\n/// # Remarks\n\n///\n\n/// Returns `0.0` if `x <= 1`\n\npub fn ln_factorial(x: u64) -> f64 {\n\n if x <= 1 {\n\n 0.0\n\n } else if x > MAX_ARG {\n\n gamma::ln_gamma(x as f64 + 1.0)\n\n } else {\n\n get_fcache()[x as usize].ln()\n\n }\n\n}\n\n\n", "file_path": "src/function/factorial.rs", "rank": 49, "score": 163175.91939840952 }, { "content": "fn sample_unchecked<R: Rng + ?Sized>(rng: &mut R, min: f64, max: f64, mode: f64) -> f64 {\n\n let f: f64 = rng.gen();\n\n if f < (mode - min) / (max - min) {\n\n min + (f * (max - min) * (mode - min)).sqrt()\n\n } else {\n\n max - ((1.0 - f) * (max - min) * (max - mode)).sqrt()\n\n }\n\n}\n\n\n\n#[rustfmt::skip]\n\n#[cfg(test)]\n\nmod tests {\n\n use std::fmt::Debug;\n\n use crate::statistics::*;\n\n use crate::distribution::{ContinuousCDF, Continuous, Triangular};\n\n use crate::distribution::internal::*;\n\n use crate::consts::ACC;\n\n\n\n fn try_create(min: f64, max: f64, mode: f64) -> Triangular {\n\n let n = Triangular::new(min, max, mode);\n", "file_path": "src/distribution/triangular.rs", "rank": 50, "score": 162012.25046211758 }, { "content": "/// Generates a base 10 log spaced vector of the given length between the\n\n/// specified decade exponents (inclusive). Equivalent to MATLAB logspace\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use statrs::generate;\n\n///\n\n/// let x = generate::log_spaced(5, 0.0, 4.0);\n\n/// assert_eq!(x, [1.0, 10.0, 100.0, 1000.0, 10000.0]);\n\n/// ```\n\npub fn log_spaced(length: usize, start_exp: f64, stop_exp: f64) -> Vec<f64> {\n\n match length {\n\n 0 => Vec::new(),\n\n 1 => vec![10f64.powf(stop_exp)],\n\n _ => {\n\n let step = (stop_exp - start_exp) / (length - 1) as f64;\n\n let mut vec = (0..length)\n\n .map(|x| 10f64.powf(start_exp + (x as f64) * step))\n\n .collect::<Vec<f64>>();\n\n vec[length - 1] = 10f64.powf(stop_exp);\n\n vec\n\n }\n\n }\n\n}\n\n\n\n/// Infinite iterator returning floats that form a periodic wave\n\npub struct InfinitePeriodic {\n\n amplitude: f64,\n\n step: f64,\n\n phase: f64,\n", "file_path": "src/generate.rs", "rank": 51, "score": 161249.92847856035 }, { "content": "/// Computes the binomial coefficient `n choose k`\n\n/// where `k` and `n` are non-negative values.\n\n///\n\n/// # Remarks\n\n///\n\n/// Returns `0.0` if `k > n`\n\npub fn binomial(n: u64, k: u64) -> f64 {\n\n if k > n {\n\n 0.0\n\n } else {\n\n (0.5 + (ln_factorial(n) - ln_factorial(k) - ln_factorial(n - k)).exp()).floor()\n\n }\n\n}\n\n\n", "file_path": "src/function/factorial.rs", "rank": 52, "score": 158832.23631055403 }, { "content": "/// Computes the natural logarithm of the binomial coefficient\n\n/// `ln(n choose k)` where `k` and `n` are non-negative values\n\n///\n\n/// # Remarks\n\n///\n\n/// Returns `f64::NEG_INFINITY` if `k > n`\n\npub fn ln_binomial(n: u64, k: u64) -> f64 {\n\n if k > n {\n\n f64::NEG_INFINITY\n\n } else {\n\n ln_factorial(n) - ln_factorial(k) - ln_factorial(n - k)\n\n }\n\n}\n\n\n", "file_path": "src/function/factorial.rs", "rank": 53, "score": 155839.38546387598 }, { "content": "/// Computes the multinomial coefficient: `n choose n1, n2, n3, ...`\n\n///\n\n/// # Panics\n\n///\n\n/// If the elements in `ni` do not sum to `n`\n\npub fn multinomial(n: u64, ni: &[u64]) -> f64 {\n\n checked_multinomial(n, ni).unwrap()\n\n}\n\n\n", "file_path": "src/function/factorial.rs", "rank": 54, "score": 155836.06099284103 }, { "content": "/// Computes the multinomial coefficient: `n choose n1, n2, n3, ...`\n\n///\n\n/// # Errors\n\n///\n\n/// If the elements in `ni` do not sum to `n`\n\npub fn checked_multinomial(n: u64, ni: &[u64]) -> Result<f64> {\n\n let (sum, ret) = ni.iter().fold((0, ln_factorial(n)), |acc, &x| {\n\n (acc.0 + x, acc.1 - ln_factorial(x))\n\n });\n\n if sum != n {\n\n Err(StatsError::ContainerExpectedSumVar(\"ni\", \"n\"))\n\n } else {\n\n Ok((0.5 + ret.exp()).floor())\n\n }\n\n}\n\n\n\n// Initialization for pre-computed cache of 171 factorial\n\n// values 0!...170!\n\nconst CACHE_SIZE: usize = 171;\n\n\n\nstatic mut FCACHE: [f64; CACHE_SIZE] = [1.0; CACHE_SIZE];\n\nstatic START: Once = Once::new();\n\n\n", "file_path": "src/function/factorial.rs", "rank": 55, "score": 148400.36468453877 }, { "content": "/// The `Discrete` trait provides an interface for interacting with discrete\n\n/// statistical distributions\n\n///\n\n/// # Remarks\n\n///\n\n/// All methods provided by the `Discrete` trait are unchecked, meaning\n\n/// they can panic if in an invalid state or encountering invalid input\n\n/// depending on the implementing distribution.\n\npub trait Discrete<K, T> {\n\n /// Returns the probability mass function calculated at `x` for a given\n\n /// distribution.\n\n /// May panic depending on the implementor.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use statrs::distribution::{Discrete, Binomial};\n\n /// use statrs::prec;\n\n ///\n\n /// let n = Binomial::new(0.5, 10).unwrap();\n\n /// assert!(prec::almost_eq(n.pmf(5), 0.24609375, 1e-15));\n\n /// ```\n\n fn pmf(&self, x: K) -> T;\n\n\n\n /// Returns the log of the probability mass function calculated at `x` for\n\n /// a given distribution.\n\n /// May panic depending on the implementor.\n\n ///\n", "file_path": "src/distribution/mod.rs", "rank": 56, "score": 135450.81088230177 }, { "content": "// modified signum that returns 0.0 if x == 0.0. Used\n\n// by inv_digamma, may consider extracting into a public\n\n// method\n\nfn signum(x: f64) -> f64 {\n\n if x == 0.0 {\n\n 0.0\n\n } else {\n\n x.signum()\n\n }\n\n}\n\n\n\n#[rustfmt::skip]\n\n#[cfg(test)]\n\nmod tests {\n\n use std::f64::{self, consts};\n\n\n\n #[test]\n\n fn test_gamma() {\n\n assert!(super::gamma(f64::NAN).is_nan());\n\n assert_almost_eq!(super::gamma(1.000001e-35), 9.9999900000099999900000099999899999522784235098567139293e+34, 1e20);\n\n assert_almost_eq!(super::gamma(1.000001e-10), 9.99998999943278432519738283781280989934496494539074049002e+9, 1e-5);\n\n assert_almost_eq!(super::gamma(1.000001e-5), 99999.32279432557746387178953902739303931424932435387031653234, 1e-10);\n\n assert_almost_eq!(super::gamma(1.000001e-2), 99.43248512896257405886134437203369035261893114349805309870831, 1e-13);\n", "file_path": "src/function/gamma.rs", "rank": 57, "score": 130975.12731577722 }, { "content": "// `erf_inv_impl` computes the inverse error function where\n\n// `p`,`q`, and `s` are the first, second, and third intermediate\n\n// parameters respectively\n\nfn erf_inv_impl(p: f64, q: f64, s: f64) -> f64 {\n\n let result = if p <= 0.5 {\n\n let y = 0.0891314744949340820313;\n\n let g = p * (p + 10.0);\n\n let r = evaluate::polynomial(p, ERF_INV_IMPL_AN) / evaluate::polynomial(p, ERF_INV_IMPL_AD);\n\n g * y + g * r\n\n } else if q >= 0.25 {\n\n let y = 2.249481201171875;\n\n let g = (-2.0 * q.ln()).sqrt();\n\n let xs = q - 0.25;\n\n let r =\n\n evaluate::polynomial(xs, ERF_INV_IMPL_BN) / evaluate::polynomial(xs, ERF_INV_IMPL_BD);\n\n g / (y + r)\n\n } else {\n\n let x = (-q.ln()).sqrt();\n\n if x < 3.0 {\n\n let y = 0.807220458984375;\n\n let xs = x - 1.125;\n\n let r = evaluate::polynomial(xs, ERF_INV_IMPL_CN)\n\n / evaluate::polynomial(xs, ERF_INV_IMPL_CD);\n", "file_path": "src/function/erf.rs", "rank": 58, "score": 130845.67422817726 }, { "content": "/// The `DiscreteCDF` trait is used to specify an interface for univariate\n\n/// discrete distributions.\n\npub trait DiscreteCDF<K: Bounded + Clone + Num, T: Float>: Min<K> + Max<K> {\n\n /// Returns the cumulative distribution function calculated\n\n /// at `x` for a given distribution. May panic depending\n\n /// on the implementor.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use statrs::distribution::{ContinuousCDF, Uniform};\n\n ///\n\n /// let n = Uniform::new(0.0, 1.0).unwrap();\n\n /// assert_eq!(0.5, n.cdf(0.5));\n\n /// ```\n\n fn cdf(&self, x: K) -> T;\n\n /// Due to issues with rounding and floating-point accuracy the default implementation may be ill-behaved\n\n /// Specialized inverse cdfs should be used whenever possible.\n\n fn inverse_cdf(&self, p: T) -> K {\n\n // TODO: fix integer implementation\n\n if p == T::zero() {\n\n return self.min();\n", "file_path": "src/distribution/mod.rs", "rank": 59, "score": 124582.1030863993 }, { "content": "// Returns the index of val if placed into the sorted search array.\n\n// If val is greater than all elements, it therefore would return\n\n// the length of the array (N). If val is less than all elements, it would\n\n// return 0. Otherwise val returns the index of the first element larger than\n\n// it within the search array.\n\nfn binary_index(search: &[f64], val: f64) -> usize {\n\n use std::cmp;\n\n\n\n let mut low = 0 as isize;\n\n let mut high = search.len() as isize - 1;\n\n while low <= high {\n\n let mid = low + ((high - low) / 2);\n\n let el = *search.get(mid as usize).unwrap();\n\n if el > val {\n\n high = mid - 1;\n\n } else if el < val {\n\n low = mid.saturating_add(1);\n\n } else {\n\n return mid as usize;\n\n }\n\n }\n\n cmp::min(search.len(), cmp::max(low, 0) as usize)\n\n}\n\n\n", "file_path": "src/distribution/categorical.rs", "rank": 60, "score": 120481.05669807033 }, { "content": "fn bench_order_statistic(c: &mut Criterion) {\n\n let mut rng = thread_rng();\n\n let to_random_owned = |data: &[f64]| -> Vec<f64> {\n\n let mut rng = thread_rng();\n\n let mut owned = data.to_vec();\n\n owned.shuffle(&mut rng);\n\n owned\n\n };\n\n let k = black_box(rng.gen());\n\n let tau = black_box(rng.gen_range(0.0, 1.0));\n\n let mut group = c.benchmark_group(\"order statistic\");\n\n let data: Vec<_> = (0..100).map(|x| x as f64).collect();\n\n group.bench_function(\"order_statistic\", |b| {\n\n b.iter_batched(\n\n || to_random_owned(&data),\n\n |mut data| data.order_statistic(k),\n\n BatchSize::SmallInput,\n\n )\n\n });\n\n group.bench_function(\"median\", |b| {\n", "file_path": "benches/order_statistics.rs", "rank": 61, "score": 118177.94176087924 }, { "content": "fn get_fcache() -> [f64; CACHE_SIZE] {\n\n START.call_once(|| {\n\n (1..CACHE_SIZE).fold(1.0, |acc, i| {\n\n let fac = acc * i as f64;\n\n unsafe {\n\n FCACHE[i] = fac;\n\n }\n\n fac\n\n });\n\n });\n\n unsafe { FCACHE }\n\n}\n\n\n\n#[rustfmt::skip]\n\n#[cfg(test)]\n\nmod tests {\n\n use std::{f64, u64};\n\n\n\n #[test]\n\n fn test_factorial_and_ln_factorial() {\n", "file_path": "src/function/factorial.rs", "rank": 62, "score": 113303.74712165116 }, { "content": "#[test]\n\nfn test_binary_index() {\n\n let arr = [0.0, 3.0, 5.0, 9.0, 10.0];\n\n assert_eq!(0, binary_index(&arr, -1.0));\n\n assert_eq!(2, binary_index(&arr, 5.0));\n\n assert_eq!(3, binary_index(&arr, 5.2));\n\n assert_eq!(5, binary_index(&arr, 10.1));\n\n}\n\n\n\n#[rustfmt::skip]\n\n#[cfg(test)]\n\nmod tests {\n\n use std::fmt::Debug;\n\n use crate::statistics::*;\n\n use crate::distribution::{Categorical, Discrete, DiscreteCDF};\n\n use crate::distribution::internal::*;\n\n use crate::consts::ACC;\n\n\n\n fn try_create(prob_mass: &[f64]) -> Categorical {\n\n let n = Categorical::new(prob_mass);\n\n assert!(n.is_ok());\n", "file_path": "src/distribution/categorical.rs", "rank": 63, "score": 101526.37095493538 }, { "content": "#[test]\n\nfn test_prob_mass_to_cdf() {\n\n let arr = [0.0, 0.5, 0.5, 3.0, 1.1];\n\n let res = prob_mass_to_cdf(&arr);\n\n assert_eq!(res, [0.0, 0.5, 1.0, 4.0, 5.1]);\n\n}\n\n\n", "file_path": "src/distribution/categorical.rs", "rank": 64, "score": 99292.50952528705 }, { "content": "/// The `ContinuousCDF` trait is used to specify an interface for univariate\n\n/// distributions for which cdf float arguments are sensible.\n\npub trait ContinuousCDF<K: Float, T: Float>: Min<K> + Max<K> {\n\n /// Returns the cumulative distribution function calculated\n\n /// at `x` for a given distribution. May panic depending\n\n /// on the implementor.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use statrs::distribution::{ContinuousCDF, Uniform};\n\n ///\n\n /// let n = Uniform::new(0.0, 1.0).unwrap();\n\n /// assert_eq!(0.5, n.cdf(0.5));\n\n /// ```\n\n fn cdf(&self, x: K) -> T;\n\n /// Due to issues with rounding and floating-point accuracy the default\n\n /// implementation may be ill-behaved.\n\n /// Specialized inverse cdfs should be used whenever possible.\n\n /// Performs a binary search on the domain of `cdf` to obtain an approximation\n\n /// of `F^-1(p) := inf { x | F(x) >= p }`. Needless to say, performance may\n\n /// may be lacking.\n", "file_path": "src/distribution/mod.rs", "rank": 65, "score": 97650.5889504705 }, { "content": "/// The `Continuous` trait provides an interface for interacting with\n\n/// continuous statistical distributions\n\n///\n\n/// # Remarks\n\n///\n\n/// All methods provided by the `Continuous` trait are unchecked, meaning\n\n/// they can panic if in an invalid state or encountering invalid input\n\n/// depending on the implementing distribution.\n\npub trait Continuous<K, T> {\n\n /// Returns the probability density function calculated at `x` for a given\n\n /// distribution.\n\n /// May panic depending on the implementor.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use statrs::distribution::{Continuous, Uniform};\n\n ///\n\n /// let n = Uniform::new(0.0, 1.0).unwrap();\n\n /// assert_eq!(1.0, n.pdf(0.5));\n\n /// ```\n\n fn pdf(&self, x: K) -> T;\n\n\n\n /// Returns the log of the probability density function calculated at `x`\n\n /// for a given distribution.\n\n /// May panic depending on the implementor.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use statrs::distribution::{Continuous, Uniform};\n\n ///\n\n /// let n = Uniform::new(0.0, 1.0).unwrap();\n\n /// assert_eq!(0.0, n.ln_pdf(0.5));\n\n /// ```\n\n fn ln_pdf(&self, x: K) -> T;\n\n}\n\n\n", "file_path": "src/distribution/mod.rs", "rank": 66, "score": 95422.0675262768 }, { "content": "//! Provides testing helpers and utilities\n\n\n\nuse std::fs::File;\n\nuse std::io::{BufRead, BufReader};\n\nuse std::str;\n\n\n\n/// Loads a test data file into a vector of `f64`'s.\n\n/// Path is relative to /data.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the file does not exist or could not be opened, or\n\n/// there was an error reading the file.\n", "file_path": "src/testing/mod.rs", "rank": 67, "score": 89990.3368206274 }, { "content": "pub trait DiscreteDistribution<T: Float>: ::rand::distributions::Distribution<u64> {\n\n /// Returns the mean, if it exists.\n\n fn mean(&self) -> Option<T> {\n\n None\n\n }\n\n /// Returns the variance, if it exists.\n\n fn variance(&self) -> Option<T> {\n\n None\n\n }\n\n /// Returns the standard deviation, if it exists.\n\n fn std_dev(&self) -> Option<T> {\n\n self.variance().map(|var| var.sqrt())\n\n }\n\n /// Returns the entropy, if it exists.\n\n fn entropy(&self) -> Option<T> {\n\n None\n\n }\n\n /// Returns the skewness, if it exists.\n\n fn skewness(&self) -> Option<T> {\n\n None\n\n }\n\n}\n\n\n", "file_path": "src/statistics/traits.rs", "rank": 68, "score": 83079.10102694934 }, { "content": "/// Provides a trait for the canonical modulus operation since % is technically\n\n/// the remainder operation\n\npub trait Modulus {\n\n /// Performs a canonical modulus operation between `self` and `divisor`.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use statrs::euclid::Modulus;\n\n ///\n\n /// let x = 4i64.modulus(5);\n\n /// assert_eq!(x, 4);\n\n ///\n\n /// let y = -4i64.modulus(5);\n\n /// assert_eq!(x, 4);\n\n /// ```\n\n fn modulus(self, divisor: Self) -> Self;\n\n}\n\n\n\nimpl Modulus for f64 {\n\n fn modulus(self, divisor: f64) -> f64 {\n\n ((self % divisor) + divisor) % divisor\n", "file_path": "src/euclid.rs", "rank": 69, "score": 60770.601021469796 }, { "content": "fn handle_rank_ties(\n\n ranks: &mut [f64],\n\n index: &[(usize, &f64)],\n\n a: usize,\n\n b: usize,\n\n tie_breaker: RankTieBreaker,\n\n) {\n\n let rank = match tie_breaker {\n\n // equivalent to (b + a - 1) as f64 / 2.0 + 1.0 but less overflow issues\n\n RankTieBreaker::Average => b as f64 / 2.0 + a as f64 / 2.0 + 0.5,\n\n RankTieBreaker::Min => (a + 1) as f64,\n\n RankTieBreaker::Max => b as f64,\n\n RankTieBreaker::First => unreachable!(),\n\n };\n\n for i in &index[a..b] {\n\n ranks[i.0] = rank\n\n }\n\n}\n\n\n", "file_path": "src/statistics/slice_statistics.rs", "rank": 70, "score": 59158.40084796922 }, { "content": "/// The `Median` trait returns the median of the distribution.\n\npub trait Median<T> {\n\n /// Returns the median.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use statrs::statistics::Median;\n\n /// use statrs::distribution::Uniform;\n\n ///\n\n /// let n = Uniform::new(0.0, 1.0).unwrap();\n\n /// assert_eq!(0.5, n.median());\n\n /// ```\n\n fn median(&self) -> T;\n\n}\n\n\n", "file_path": "src/statistics/traits.rs", "rank": 71, "score": 57364.20870475857 }, { "content": "/// The `Max` trait specifies that an object has a maximum value\n\npub trait Max<T> {\n\n /// Returns the maximum value in the domain of a given distribution\n\n /// if it exists, otherwise `None`.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use statrs::statistics::Max;\n\n /// use statrs::distribution::Uniform;\n\n ///\n\n /// let n = Uniform::new(0.0, 1.0).unwrap();\n\n /// assert_eq!(1.0, n.max());\n\n /// ```\n\n fn max(&self) -> T;\n\n}\n", "file_path": "src/statistics/traits.rs", "rank": 72, "score": 57359.432185917554 }, { "content": "/// The `Statistics` trait provides a host of statistical utilities for\n\n/// analyzing\n\n/// data sets\n\npub trait Statistics<T> {\n\n /// Returns the minimum value in the data\n\n ///\n\n /// # Remarks\n\n ///\n\n /// Returns `f64::NAN` if data is empty or an entry is `f64::NAN`\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use std::f64;\n\n /// use statrs::statistics::Statistics;\n\n ///\n\n /// let x: [f64; 0] = [];\n\n /// assert!(x.min().is_nan());\n\n ///\n\n /// let y = [0.0, f64::NAN, 3.0, -2.0];\n\n /// assert!(y.min().is_nan());\n\n ///\n\n /// let z = [0.0, 3.0, -2.0];\n", "file_path": "src/statistics/statistics.rs", "rank": 73, "score": 57359.432185917554 }, { "content": "/// The `Mode` trait specifies that an object has a closed form solution\n\n/// for its mode(s)\n\npub trait Mode<T> {\n\n /// Returns the mode, if one exists.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use statrs::statistics::Mode;\n\n /// use statrs::distribution::Uniform;\n\n ///\n\n /// let n = Uniform::new(0.0, 1.0).unwrap();\n\n /// assert_eq!(Some(0.5), n.mode());\n\n /// ```\n\n fn mode(&self) -> T;\n\n}\n", "file_path": "src/statistics/traits.rs", "rank": 74, "score": 57359.432185917554 }, { "content": "/// The `Min` trait specifies than an object has a minimum value\n\npub trait Min<T> {\n\n /// Returns the minimum value in the domain of a given distribution\n\n /// if it exists, otherwise `None`.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use statrs::statistics::Min;\n\n /// use statrs::distribution::Uniform;\n\n ///\n\n /// let n = Uniform::new(0.0, 1.0).unwrap();\n\n /// assert_eq!(0.0, n.min());\n\n /// ```\n\n fn min(&self) -> T;\n\n}\n\n\n", "file_path": "src/statistics/traits.rs", "rank": 75, "score": 57359.432185917554 }, { "content": "/// The `Mean` trait implements the calculation of a mean.\n\n// TODO: Clarify the traits of multidimensional distributions\n\npub trait MeanN<T> {\n\n fn mean(&self) -> Option<T>;\n\n}\n\n\n", "file_path": "src/statistics/traits.rs", "rank": 76, "score": 56247.96788858024 }, { "content": "// TODO: Clarify the traits of multidimensional distributions\n\npub trait VarianceN<T> {\n\n fn variance(&self) -> Option<T>;\n\n}\n\n\n", "file_path": "src/statistics/traits.rs", "rank": 77, "score": 56247.96788858024 }, { "content": "/// The `OrderStatistics` trait provides statistical utilities\n\n/// having to do with ordering. All the algorithms are in-place thus requiring\n\n/// a mutable borrow.\n\npub trait OrderStatistics<T> {\n\n /// Returns the order statistic `(order 1..N)` from the data\n\n ///\n\n /// # Remarks\n\n ///\n\n /// No sorting is assumed. Order must be one-based (between `1` and `N`\n\n /// inclusive)\n\n /// Returns `f64::NAN` if order is outside the viable range or data is\n\n /// empty.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use statrs::statistics::OrderStatistics;\n\n ///\n\n /// let mut x = [];\n\n /// assert!(x.order_statistic(1).is_nan());\n\n ///\n\n /// let mut y = [0.0, 3.0, -2.0];\n\n /// assert!(y.order_statistic(0).is_nan());\n", "file_path": "src/statistics/order_statistics.rs", "rank": 78, "score": 55195.367049777706 }, { "content": "#[inline(always)]\n\nfn ziggurat<R: Rng + ?Sized, P, Z>(\n\n rng: &mut R,\n\n symmetric: bool,\n\n x_tab: ziggurat_tables::ZigTable,\n\n f_tab: ziggurat_tables::ZigTable,\n\n mut pdf: P,\n\n mut zero_case: Z,\n\n) -> f64\n\nwhere\n\n P: FnMut(f64) -> f64,\n\n Z: FnMut(&mut R, f64) -> f64,\n\n{\n\n const SCALE: f64 = (1u64 << 53) as f64;\n\n loop {\n\n let bits: u64 = rng.gen();\n\n let i = (bits & 0xff) as usize;\n\n let f = (bits >> 11) as f64 / SCALE;\n\n\n\n // u is either U(-1, 1) or U(0, 1) depending on if this is a\n\n // symmetric distribution or not.\n", "file_path": "src/distribution/ziggurat.rs", "rank": 79, "score": 52411.037297914074 }, { "content": "pub trait Distribution<T: Float>: ::rand::distributions::Distribution<T> {\n\n /// Returns the mean, if it exists.\n\n /// The default implementation returns an estimation\n\n /// based on random samples. This is a crude estimate\n\n /// for when no further information is known about the\n\n /// distribution. More accurate statements about the\n\n /// mean can and should be given by overriding the\n\n /// default implementation.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use statrs::statistics::Distribution;\n\n /// use statrs::distribution::Uniform;\n\n ///\n\n /// let n = Uniform::new(0.0, 1.0).unwrap();\n\n /// assert_eq!(0.5, n.mean().unwrap());\n\n /// ```\n\n fn mean(&self) -> Option<T> {\n\n // TODO: Does not need cryptographic rng\n", "file_path": "src/statistics/traits.rs", "rank": 80, "score": 48705.90056410468 }, { "content": "pub use self::gamma::Gamma;\n\npub use self::geometric::Geometric;\n\npub use self::hypergeometric::Hypergeometric;\n\npub use self::inverse_gamma::InverseGamma;\n\npub use self::log_normal::LogNormal;\n\npub use self::multinomial::Multinomial;\n\npub use self::multivariate_normal::MultivariateNormal;\n\npub use self::negative_binomial::NegativeBinomial;\n\npub use self::normal::Normal;\n\npub use self::pareto::Pareto;\n\npub use self::poisson::Poisson;\n\npub use self::students_t::StudentsT;\n\npub use self::triangular::Triangular;\n\npub use self::uniform::Uniform;\n\npub use self::weibull::Weibull;\n\n\n\nmod bernoulli;\n\nmod beta;\n\nmod binomial;\n\nmod categorical;\n", "file_path": "src/distribution/mod.rs", "rank": 81, "score": 44966.42978322625 }, { "content": "//! Provides traits for statistical computation\n\n\n\npub use self::iter_statistics::*;\n\npub use self::order_statistics::*;\n\npub use self::statistics::*;\n\npub use self::traits::*;\n\n\n\nmod iter_statistics;\n\nmod order_statistics;\n\n// TODO: fix later\n\n// mod slice_statistics;\n\nmod statistics;\n\nmod traits;\n", "file_path": "src/statistics/mod.rs", "rank": 82, "score": 44966.274784883775 }, { "content": "//! Defines common interfaces for interacting with statistical distributions\n\n//! and provides\n\n//! concrete implementations for a variety of distributions.\n\nuse super::statistics::{Max, Min};\n\nuse ::num_traits::{float::Float, Bounded, Num};\n\n\n\npub use self::bernoulli::Bernoulli;\n\npub use self::beta::Beta;\n\npub use self::binomial::Binomial;\n\npub use self::categorical::Categorical;\n\npub use self::cauchy::Cauchy;\n\npub use self::chi::Chi;\n\npub use self::chi_squared::ChiSquared;\n\npub use self::dirac::Dirac;\n\npub use self::dirichlet::Dirichlet;\n\npub use self::discrete_uniform::DiscreteUniform;\n\npub use self::empirical::Empirical;\n\npub use self::erlang::Erlang;\n\npub use self::exponential::Exp;\n\npub use self::fisher_snedecor::FisherSnedecor;\n", "file_path": "src/distribution/mod.rs", "rank": 83, "score": 44965.16012444023 }, { "content": " /// # Examples\n\n ///\n\n /// ```\n\n /// use statrs::distribution::{Discrete, Binomial};\n\n /// use statrs::prec;\n\n ///\n\n /// let n = Binomial::new(0.5, 10).unwrap();\n\n /// assert!(prec::almost_eq(n.ln_pmf(5), (0.24609375f64).ln(), 1e-15));\n\n /// ```\n\n fn ln_pmf(&self, x: K) -> T;\n\n}\n", "file_path": "src/distribution/mod.rs", "rank": 84, "score": 44961.676669185596 }, { "content": "//! Provides a host of special statistical functions (e.g. the beta function or\n\n//! the error function)\n\n\n\npub mod beta;\n\npub mod erf;\n\npub mod evaluate;\n\npub mod exponential;\n\npub mod factorial;\n\npub mod gamma;\n\npub mod harmonic;\n\npub mod logistic;\n", "file_path": "src/function/mod.rs", "rank": 85, "score": 44961.53210160848 }, { "content": "mod pareto;\n\nmod poisson;\n\nmod students_t;\n\nmod triangular;\n\nmod uniform;\n\nmod weibull;\n\nmod ziggurat;\n\nmod ziggurat_tables;\n\n\n\nuse crate::Result;\n\n\n\n/// The `ContinuousCDF` trait is used to specify an interface for univariate\n\n/// distributions for which cdf float arguments are sensible.\n", "file_path": "src/distribution/mod.rs", "rank": 86, "score": 44960.23036267991 }, { "content": "mod cauchy;\n\nmod chi;\n\nmod chi_squared;\n\nmod dirac;\n\nmod dirichlet;\n\nmod discrete_uniform;\n\nmod empirical;\n\nmod erlang;\n\nmod exponential;\n\nmod fisher_snedecor;\n\nmod gamma;\n\nmod geometric;\n\nmod hypergeometric;\n\nmod internal;\n\nmod inverse_gamma;\n\nmod log_normal;\n\nmod multinomial;\n\nmod multivariate_normal;\n\nmod negative_binomial;\n\nmod normal;\n", "file_path": "src/distribution/mod.rs", "rank": 87, "score": 44959.092768670365 }, { "content": " fn inverse_cdf(&self, p: T) -> K {\n\n if p == T::zero() {\n\n return self.min();\n\n };\n\n if p == T::one() {\n\n return self.max();\n\n };\n\n let two = K::one() + K::one();\n\n let mut high = two;\n\n let mut low = -high;\n\n while self.cdf(low) > p {\n\n low = low + low;\n\n }\n\n while self.cdf(high) < p {\n\n high = high + high;\n\n }\n\n let mut i = 16;\n\n while i != 0 {\n\n let mid = (high + low) / two;\n\n if self.cdf(mid) >= p {\n", "file_path": "src/distribution/mod.rs", "rank": 88, "score": 44954.37829415714 }, { "content": " };\n\n if p == T::one() {\n\n return self.max();\n\n };\n\n let two = K::one() + K::one();\n\n let mut high = two.clone();\n\n let mut low = K::min_value();\n\n while self.cdf(high.clone()) < p {\n\n high = high.clone() + high.clone();\n\n }\n\n while high != low {\n\n let mid = (high.clone() + low.clone()) / two.clone();\n\n if self.cdf(mid.clone()) >= p {\n\n high = mid;\n\n } else {\n\n low = mid;\n\n }\n\n }\n\n high\n\n }\n\n}\n\n\n", "file_path": "src/distribution/mod.rs", "rank": 89, "score": 44953.75771151123 }, { "content": " high = mid;\n\n } else {\n\n low = mid;\n\n }\n\n i -= 1;\n\n }\n\n (high + low) / two\n\n }\n\n}\n\n\n", "file_path": "src/distribution/mod.rs", "rank": 90, "score": 44949.134110747254 }, { "content": " if x >= self.min && x <= self.max {\n\n -((self.max - self.min + 1) as f64).ln()\n\n } else {\n\n f64::NEG_INFINITY\n\n }\n\n }\n\n}\n\n\n\n#[rustfmt::skip]\n\n#[cfg(test)]\n\nmod tests {\n\n use std::fmt::Debug;\n\n use crate::statistics::*;\n\n use crate::distribution::{DiscreteCDF, Discrete, DiscreteUniform};\n\n use crate::consts::ACC;\n\n\n\n fn try_create(min: i64, max: i64) -> DiscreteUniform {\n\n let n = DiscreteUniform::new(min, max);\n\n assert!(n.is_ok());\n\n n.unwrap()\n", "file_path": "src/distribution/discrete_uniform.rs", "rank": 91, "score": 43601.73539076346 }, { "content": "pub struct DiscreteUniform {\n\n min: i64,\n\n max: i64,\n\n}\n\n\n\nimpl DiscreteUniform {\n\n /// Constructs a new discrete uniform distribution with a minimum value\n\n /// of `min` and a maximum value of `max`.\n\n ///\n\n /// # Errors\n\n ///\n\n /// Returns an error if `max < min`\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use statrs::distribution::DiscreteUniform;\n\n ///\n\n /// let mut result = DiscreteUniform::new(0, 5);\n\n /// assert!(result.is_ok());\n", "file_path": "src/distribution/discrete_uniform.rs", "rank": 92, "score": 43599.22905164293 }, { "content": " ///\n\n /// result = DiscreteUniform::new(5, 0);\n\n /// assert!(result.is_err());\n\n /// ```\n\n pub fn new(min: i64, max: i64) -> Result<DiscreteUniform> {\n\n if max < min {\n\n Err(StatsError::BadParams)\n\n } else {\n\n Ok(DiscreteUniform { min, max })\n\n }\n\n }\n\n}\n\n\n\nimpl ::rand::distributions::Distribution<f64> for DiscreteUniform {\n\n fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {\n\n rng.gen_range(self.min, self.max + 1) as f64\n\n }\n\n}\n\n\n\nimpl DiscreteCDF<i64, f64> for DiscreteUniform {\n", "file_path": "src/distribution/discrete_uniform.rs", "rank": 93, "score": 43595.77157685764 }, { "content": " let diff = (self.max - self.min) as f64;\n\n Some((diff + 1.0).ln())\n\n }\n\n /// Returns the skewness of the discrete uniform distribution\n\n ///\n\n /// # Formula\n\n ///\n\n /// ```ignore\n\n /// 0\n\n /// ```\n\n fn skewness(&self) -> Option<f64> {\n\n Some(0.0)\n\n }\n\n}\n\n\n\nimpl Median<f64> for DiscreteUniform {\n\n /// Returns the median of the discrete uniform distribution\n\n ///\n\n /// # Formula\n\n ///\n", "file_path": "src/distribution/discrete_uniform.rs", "rank": 94, "score": 43594.24110103203 }, { "content": " }\n\n /// Returns the variance of the discrete uniform distribution\n\n ///\n\n /// # Formula\n\n ///\n\n /// ```ignore\n\n /// ((max - min + 1)^2 - 1) / 12\n\n /// ```\n\n fn variance(&self) -> Option<f64> {\n\n let diff = (self.max - self.min) as f64;\n\n Some(((diff + 1.0) * (diff + 1.0) - 1.0) / 12.0)\n\n }\n\n /// Returns the entropy of the discrete uniform distribution\n\n ///\n\n /// # Formula\n\n ///\n\n /// ```ignore\n\n /// ln(max - min + 1)\n\n /// ```\n\n fn entropy(&self) -> Option<f64> {\n", "file_path": "src/distribution/discrete_uniform.rs", "rank": 95, "score": 43593.4804807631 }, { "content": " /// ```\n\n fn mode(&self) -> Option<i64> {\n\n Some(((self.min + self.max) as f64 / 2.0).floor() as i64)\n\n }\n\n}\n\n\n\nimpl Discrete<i64, f64> for DiscreteUniform {\n\n /// Calculates the probability mass function for the discrete uniform\n\n /// distribution at `x`\n\n ///\n\n /// # Remarks\n\n ///\n\n /// Returns `0.0` if `x` is not in `[min, max]`\n\n ///\n\n /// # Formula\n\n ///\n\n /// ```ignore\n\n /// 1 / (max - min + 1)\n\n /// ```\n\n fn pmf(&self, x: i64) -> f64 {\n", "file_path": "src/distribution/discrete_uniform.rs", "rank": 96, "score": 43592.884120973875 }, { "content": " /// distribution\n\n ///\n\n /// # Remarks\n\n ///\n\n /// This is the same value as the maximum passed into the constructor\n\n fn max(&self) -> i64 {\n\n self.max\n\n }\n\n}\n\n\n\nimpl Distribution<f64> for DiscreteUniform {\n\n /// Returns the mean of the discrete uniform distribution\n\n ///\n\n /// # Formula\n\n ///\n\n /// ```ignore\n\n /// (min + max) / 2\n\n /// ```\n\n fn mean(&self) -> Option<f64> {\n\n Some((self.min + self.max) as f64 / 2.0)\n", "file_path": "src/distribution/discrete_uniform.rs", "rank": 97, "score": 43592.60798955707 }, { "content": " test_case(-10, 10, 0.04761904761904761904762, pmf(-5));\n\n test_case(-10, 10, 0.04761904761904761904762, pmf(1));\n\n test_case(-10, 10, 0.04761904761904761904762, pmf(10));\n\n test_case(-10, -10, 0.0, pmf(0));\n\n test_case(-10, -10, 1.0, pmf(-10));\n\n }\n\n\n\n #[test]\n\n fn test_ln_pmf() {\n\n let ln_pmf = |arg: i64| move |x: DiscreteUniform| x.ln_pmf(arg);\n\n test_case(-10, 10, -3.0445224377234229965005979803657054342845752874046093, ln_pmf(-5));\n\n test_case(-10, 10, -3.0445224377234229965005979803657054342845752874046093, ln_pmf(1));\n\n test_case(-10, 10, -3.0445224377234229965005979803657054342845752874046093, ln_pmf(10));\n\n test_case(-10, -10, f64::NEG_INFINITY, ln_pmf(0));\n\n test_case(-10, -10, 0.0, ln_pmf(-10));\n\n }\n\n\n\n #[test]\n\n fn test_cdf() {\n\n let cdf = |arg: i64| move |x: DiscreteUniform| x.cdf(arg);\n", "file_path": "src/distribution/discrete_uniform.rs", "rank": 98, "score": 43591.97481956599 }, { "content": " /// ```ignore\n\n /// (max + min) / 2\n\n /// ```\n\n fn median(&self) -> f64 {\n\n (self.min + self.max) as f64 / 2.0\n\n }\n\n}\n\n\n\nimpl Mode<Option<i64>> for DiscreteUniform {\n\n /// Returns the mode for the discrete uniform distribution\n\n ///\n\n /// # Remarks\n\n ///\n\n /// Since every element has an equal probability, mode simply\n\n /// returns the middle element\n\n ///\n\n /// # Formula\n\n ///\n\n /// ```ignore\n\n /// N/A // (max + min) / 2 for the middle element\n", "file_path": "src/distribution/discrete_uniform.rs", "rank": 99, "score": 43591.66042563561 } ]
Rust
gensokyo/src/config/core/device.rs
Usami-Renko/hakurei
cccc69fe71d6efd75089d1c03c9c49fefde8e2ca
use toml; use serde_derive::Deserialize; use crate::config::engine::ConfigMirror; use crate::error::{ GsResult, GsError }; use gsvk::core::device::DeviceConfig; use gsvk::core::device::QueueRequestStrategy; use crate::utils::time::TimePeriod; use std::time::Duration; #[derive(Deserialize)] pub(crate) struct DeviceConfigMirror { queue_request_strategy: String, transfer_time_out: String, transfer_duration: u64, print_device_name : bool, print_device_api : bool, print_device_type : bool, print_device_queues: bool, } impl Default for DeviceConfigMirror { fn default() -> DeviceConfigMirror { DeviceConfigMirror { queue_request_strategy: String::from("SingleFamilySingleQueue"), transfer_time_out: String::from("Infinite"), transfer_duration: 1000_u64, print_device_name : false, print_device_api : false, print_device_type : false, print_device_queues: false, } } } impl ConfigMirror for DeviceConfigMirror { type ConfigType = DeviceConfig; fn into_config(self) -> GsResult<Self::ConfigType> { let config = DeviceConfig { queue_request_strategy: vk_raw2queue_request_strategy(&self.queue_request_strategy)?, transfer_wait_time : vk_raw2transfer_wait_time(&self.transfer_time_out, self.transfer_duration)?.vulkan_time(), print_device_name : self.print_device_name, print_device_api : self.print_device_api, print_device_type : self.print_device_type, print_device_queues: self.print_device_queues, }; Ok(config) } fn parse(&mut self, toml: &toml::Value) -> GsResult<()> { if let Some(v) = toml.get("queue_request_strategy") { self.queue_request_strategy = v.as_str() .ok_or(GsError::config("core.device.queue_request_strategy"))?.to_owned(); } if let Some(v) = toml.get("transfer_time_out") { self.transfer_time_out = v.as_str() .ok_or(GsError::config("core.device.transfer_time_out"))?.to_owned(); } if let Some(v) = toml.get("transfer_duration") { self.transfer_duration = v.as_integer() .ok_or(GsError::config("core.device.transfer_duration"))?.to_owned() as u64; } if let Some(v) = toml.get("print") { if let Some(v) = v.get("device_name") { self.print_device_name = v.as_bool() .ok_or(GsError::config("core.device.print.device_name"))?.to_owned(); } if let Some(v) = v.get("device_api_version") { self.print_device_api = v.as_bool() .ok_or(GsError::config("core.device.print.device_api_version"))?.to_owned(); } if let Some(v) = v.get("device_type") { self.print_device_type = v.as_bool() .ok_or(GsError::config("core.device.print.device_type"))?.to_owned(); } if let Some(v) = v.get("device_queues") { self.print_device_queues = v.as_bool() .ok_or(GsError::config("core.device.print.device_queues"))?.to_owned(); } } Ok(()) } } fn vk_raw2queue_request_strategy(raw: &String) -> GsResult<QueueRequestStrategy> { let strategy = match raw.as_str() { | "SingleFamilySingleQueue" => QueueRequestStrategy::SingleFamilySingleQueue, | "SingleFamilyMultiQueues" => QueueRequestStrategy::SingleFamilyMultiQueues, | _ => return Err(GsError::config(raw)), }; Ok(strategy) } fn vk_raw2transfer_wait_time(time_out: &String, duration: u64) -> GsResult<TimePeriod> { let time = match time_out.as_str() { | "Infinite" => TimePeriod::Infinite, | "Immediate" => TimePeriod::Immediate, | "Timing" => TimePeriod::Time(Duration::from_millis(duration)), | _ => return Err(GsError::config(time_out)), }; Ok(time) }
use toml; use serde_derive::Deserialize; use crate::config::engine::ConfigMirror; use crate::error::{ GsResult, GsError }; use gsvk::core::device::DeviceConfig; use gsvk::core::device::QueueRequestStrategy; use crate::utils::time::TimePeriod; use std::time::Duration; #[derive(Deserialize)] pub(crate) struct DeviceConfigMirror { queue_request_strategy: String, transfer_time_out: String, transfer_duration: u64, print_device_name : bool, print_device_api : bool, print_device_type : bool, print_device_queues: bool, } impl Default for DeviceConfigMirror { fn default() -> DeviceConfigMirror { DeviceConfigMirror { queue_request_strategy: String::from("SingleFamilySingleQueue"), transfer_time_out: String::from("Infinite"), transfer_duration: 1000_u64, print_device_name : false, print_device_api : false, print_device_type : false, print_device_queues: false, } } } impl ConfigMirror for DeviceConfigMirror { type ConfigType = DeviceConfig; fn into_config(self) -> GsResult<Self::ConfigType> { let config = DeviceConfig { queue_request_strategy: vk_raw2queue_request_strategy(&self.queue_request_strategy)?, transfer_wait_time : vk_raw2transfer_wait_time(&self.transfer_time_out, self.transfer_duration)?.vulkan_time(), print_device_name : self.print_device_name, print_device_api : self.print_device_api, print_device_type : self.print_device_type, print_device_queues: self.print_device_queues, }; Ok(config) } fn parse(&mut self, toml: &toml::Value) -> GsResult<()> { if let Some(v) = toml.get("queue_request_strategy") { self.queue_request_strategy = v.as_str() .ok_or(GsError::config("core.device.queue_request_strategy"))?.to_owned(); } if let Some(v) = toml.get("transfer_time_out") { self.transfer_time_out = v.as_str() .ok_or(GsError::config("core.device.transfer_time_out"))?.to_owned(); } if let Some(v) = toml.get("transfer_duration") { self.transfer_duration = v.as_integer() .ok_or(GsError::config("core.device.transfer_duration"))?.to_owned() as u64; } if let Some(v) = toml.get("print") { if let Some(v) = v.get("device_name") { self.print_device_name = v.as_bool() .ok_or(GsError::config("core.device.print.devic
e = match time_out.as_str() { | "Infinite" => TimePeriod::Infinite, | "Immediate" => TimePeriod::Immediate, | "Timing" => TimePeriod::Time(Duration::from_millis(duration)), | _ => return Err(GsError::config(time_out)), }; Ok(time) }
e_name"))?.to_owned(); } if let Some(v) = v.get("device_api_version") { self.print_device_api = v.as_bool() .ok_or(GsError::config("core.device.print.device_api_version"))?.to_owned(); } if let Some(v) = v.get("device_type") { self.print_device_type = v.as_bool() .ok_or(GsError::config("core.device.print.device_type"))?.to_owned(); } if let Some(v) = v.get("device_queues") { self.print_device_queues = v.as_bool() .ok_or(GsError::config("core.device.print.device_queues"))?.to_owned(); } } Ok(()) } } fn vk_raw2queue_request_strategy(raw: &String) -> GsResult<QueueRequestStrategy> { let strategy = match raw.as_str() { | "SingleFamilySingleQueue" => QueueRequestStrategy::SingleFamilySingleQueue, | "SingleFamilyMultiQueues" => QueueRequestStrategy::SingleFamilyMultiQueues, | _ => return Err(GsError::config(raw)), }; Ok(strategy) } fn vk_raw2transfer_wait_time(time_out: &String, duration: u64) -> GsResult<TimePeriod> { let tim
random
[]
Rust
src/config.rs
meltinglava/rust-osauth
aef0567d48508d98686c7c000b62311564f691f6
use std::collections::HashMap; use std::env; use std::fs::File; use std::path::{Path, PathBuf}; use dirs; use log::warn; use serde::Deserialize; use serde_yaml; use super::identity::Password; use super::{Error, ErrorKind, Session}; use osproto::identity::IdOrName; #[derive(Debug, Deserialize)] struct Auth { auth_url: String, password: String, #[serde(default)] project_name: Option<String>, #[serde(default)] project_domain_name: Option<String>, username: String, #[serde(default)] user_domain_name: Option<String>, } #[derive(Debug, Deserialize)] struct Cloud { auth: Auth, #[serde(default)] region_name: Option<String>, } #[derive(Debug, Deserialize)] struct Clouds { #[serde(flatten)] clouds: HashMap<String, Cloud>, } #[derive(Debug, Deserialize)] struct Root { clouds: Clouds, } fn find_config() -> Option<PathBuf> { let current = Path::new("./clouds.yaml"); if current.is_file() { match current.canonicalize() { Ok(val) => return Some(val), Err(e) => warn!("Cannot canonicalize {:?}: {}", current, e), } } if let Some(mut home) = dirs::home_dir() { home.push(".config/openstack/clouds.yaml"); if home.is_file() { return Some(home); } } else { warn!("Cannot find home directory"); } let abs = PathBuf::from("/etc/openstack/clouds.yaml"); if abs.is_file() { Some(abs) } else { None } } pub fn from_config<S: AsRef<str>>(cloud_name: S) -> Result<Session, Error> { let path = find_config().ok_or_else(|| { Error::new( ErrorKind::InvalidConfig, "clouds.yaml was not found in any location", ) })?; let file = File::open(path).map_err(|e| { Error::new( ErrorKind::InvalidConfig, format!("Cannot read config.yaml: {}", e), ) })?; let mut clouds_root: Root = serde_yaml::from_reader(file).map_err(|e| { Error::new( ErrorKind::InvalidConfig, format!("Cannot parse clouds.yaml: {}", e), ) })?; let name = cloud_name.as_ref(); let cloud = clouds_root.clouds.clouds.remove(name).ok_or_else(|| { Error::new(ErrorKind::InvalidConfig, format!("No such cloud: {}", name)) })?; let auth = cloud.auth; let user_domain = auth .user_domain_name .unwrap_or_else(|| String::from("Default")); let project_domain = auth .project_domain_name .unwrap_or_else(|| String::from("Default")); let mut id = Password::new(&auth.auth_url, auth.username, auth.password, user_domain)?; if let Some(project_name) = auth.project_name { id.set_project_scope(IdOrName::Name(project_name), IdOrName::Name(project_domain)); } if let Some(region) = cloud.region_name { id.set_region(region) } Ok(Session::new(id)) } const MISSING_ENV_VARS: &str = "Not all required environment variables were provided"; #[inline] fn _get_env(name: &str) -> Result<String, Error> { env::var(name).map_err(|_| Error::new(ErrorKind::InvalidInput, MISSING_ENV_VARS)) } pub fn from_env() -> Result<Session, Error> { if let Ok(cloud_name) = env::var("OS_CLOUD") { from_config(cloud_name) } else { let auth_url = _get_env("OS_AUTH_URL")?; let user_name = _get_env("OS_USERNAME")?; let password = _get_env("OS_PASSWORD")?; let user_domain = env::var("OS_USER_DOMAIN_NAME").unwrap_or_else(|_| String::from("Default")); let id = Password::new(&auth_url, user_name, password, user_domain)?; let project = _get_env("OS_PROJECT_ID") .map(IdOrName::Id) .or_else(|_| _get_env("OS_PROJECT_NAME").map(IdOrName::Name))?; let project_domain = _get_env("OS_PROJECT_DOMAIN_ID") .map(IdOrName::Id) .or_else(|_| _get_env("OS_PROJECT_DOMAIN_NAME").map(IdOrName::Name)) .ok(); let mut session = Session::new(id.with_project_scope(project, project_domain)); if let Ok(interface) = env::var("OS_INTERFACE") { session.set_endpoint_interface(interface) } Ok(session) } }
use std::collections::HashMap; use std::env; use std::fs::File; use std::path::{Path, PathBuf}; use dirs; use log::
r("OS_CLOUD") { from_config(cloud_name) } else { let auth_url = _get_env("OS_AUTH_URL")?; let user_name = _get_env("OS_USERNAME")?; let password = _get_env("OS_PASSWORD")?; let user_domain = env::var("OS_USER_DOMAIN_NAME").unwrap_or_else(|_| String::from("Default")); let id = Password::new(&auth_url, user_name, password, user_domain)?; let project = _get_env("OS_PROJECT_ID") .map(IdOrName::Id) .or_else(|_| _get_env("OS_PROJECT_NAME").map(IdOrName::Name))?; let project_domain = _get_env("OS_PROJECT_DOMAIN_ID") .map(IdOrName::Id) .or_else(|_| _get_env("OS_PROJECT_DOMAIN_NAME").map(IdOrName::Name)) .ok(); let mut session = Session::new(id.with_project_scope(project, project_domain)); if let Ok(interface) = env::var("OS_INTERFACE") { session.set_endpoint_interface(interface) } Ok(session) } }
warn; use serde::Deserialize; use serde_yaml; use super::identity::Password; use super::{Error, ErrorKind, Session}; use osproto::identity::IdOrName; #[derive(Debug, Deserialize)] struct Auth { auth_url: String, password: String, #[serde(default)] project_name: Option<String>, #[serde(default)] project_domain_name: Option<String>, username: String, #[serde(default)] user_domain_name: Option<String>, } #[derive(Debug, Deserialize)] struct Cloud { auth: Auth, #[serde(default)] region_name: Option<String>, } #[derive(Debug, Deserialize)] struct Clouds { #[serde(flatten)] clouds: HashMap<String, Cloud>, } #[derive(Debug, Deserialize)] struct Root { clouds: Clouds, } fn find_config() -> Option<PathBuf> { let current = Path::new("./clouds.yaml"); if current.is_file() { match current.canonicalize() { Ok(val) => return Some(val), Err(e) => warn!("Cannot canonicalize {:?}: {}", current, e), } } if let Some(mut home) = dirs::home_dir() { home.push(".config/openstack/clouds.yaml"); if home.is_file() { return Some(home); } } else { warn!("Cannot find home directory"); } let abs = PathBuf::from("/etc/openstack/clouds.yaml"); if abs.is_file() { Some(abs) } else { None } } pub fn from_config<S: AsRef<str>>(cloud_name: S) -> Result<Session, Error> { let path = find_config().ok_or_else(|| { Error::new( ErrorKind::InvalidConfig, "clouds.yaml was not found in any location", ) })?; let file = File::open(path).map_err(|e| { Error::new( ErrorKind::InvalidConfig, format!("Cannot read config.yaml: {}", e), ) })?; let mut clouds_root: Root = serde_yaml::from_reader(file).map_err(|e| { Error::new( ErrorKind::InvalidConfig, format!("Cannot parse clouds.yaml: {}", e), ) })?; let name = cloud_name.as_ref(); let cloud = clouds_root.clouds.clouds.remove(name).ok_or_else(|| { Error::new(ErrorKind::InvalidConfig, format!("No such cloud: {}", name)) })?; let auth = cloud.auth; let user_domain = auth .user_domain_name .unwrap_or_else(|| String::from("Default")); let project_domain = auth .project_domain_name .unwrap_or_else(|| String::from("Default")); let mut id = Password::new(&auth.auth_url, auth.username, auth.password, user_domain)?; if let Some(project_name) = auth.project_name { id.set_project_scope(IdOrName::Name(project_name), IdOrName::Name(project_domain)); } if let Some(region) = cloud.region_name { id.set_region(region) } Ok(Session::new(id)) } const MISSING_ENV_VARS: &str = "Not all required environment variables were provided"; #[inline] fn _get_env(name: &str) -> Result<String, Error> { env::var(name).map_err(|_| Error::new(ErrorKind::InvalidInput, MISSING_ENV_VARS)) } pub fn from_env() -> Result<Session, Error> { if let Ok(cloud_name) = env::va
random
[ { "content": "use log::{debug, trace};\n\nuse reqwest::header::HeaderMap;\n\nuse reqwest::r#async::{RequestBuilder, Response};\n\nuse reqwest::{Method, Url};\n\nuse serde::de::DeserializeOwned;\n\nuse serde::Serialize;\n\n\n\nuse super::cache;\n\nuse super::protocol::ServiceInfo;\n\nuse super::request;\n\nuse super::services::ServiceType;\n\nuse super::url;\n\nuse super::{Adapter, ApiVersion, AuthType, Error};\n\n\n", "file_path": "src/session.rs", "rank": 2, "score": 6.694246021525544 }, { "content": "use futures::prelude::*;\n\nuse log::{debug, trace, warn};\n\nuse osproto::common::{Root, Version};\n\nuse reqwest::{Method, Url};\n\n\n\nuse super::request;\n\nuse super::services::ServiceType;\n\nuse super::url;\n\nuse super::{ApiVersion, AuthType, Error, ErrorKind};\n\n\n\n/// Information about API endpoint.\n\n#[derive(Debug)]\n\npub struct ServiceInfo {\n\n /// Root endpoint.\n\n pub root_url: Url,\n\n /// Major API version.\n\n pub major_version: Option<ApiVersion>,\n\n /// Current API version (if supported).\n\n pub current_version: Option<ApiVersion>,\n\n /// Minimum API version (if supported).\n", "file_path": "src/protocol.rs", "rank": 3, "score": 5.951627388976937 }, { "content": "use std::fmt;\n\nuse std::hash::{Hash, Hasher};\n\nuse std::sync::Arc;\n\n\n\nuse chrono::{Duration, Local};\n\nuse futures::future;\n\nuse futures::prelude::*;\n\nuse log::{debug, error, trace};\n\nuse osproto::identity as protocol;\n\nuse reqwest::r#async::{Client, RequestBuilder, Response};\n\nuse reqwest::{IntoUrl, Method, Url};\n\n\n\nuse super::cache::ValueCache;\n\nuse super::{catalog, request, AuthType, Error, ErrorKind};\n\n\n\npub use osproto::identity::IdOrName;\n\n\n\nconst MISSING_SUBJECT_HEADER: &str = \"Missing X-Subject-Token header\";\n\nconst INVALID_SUBJECT_HEADER: &str = \"Invalid X-Subject-Token header\";\n\n// Required validity time in minutes. Here we refresh the token if it expires\n\n// in 10 minutes or less.\n\nconst TOKEN_MIN_VALIDITY: i64 = 10;\n\n\n\n/// Plain authentication token without additional details.\n\n#[derive(Clone)]\n", "file_path": "src/identity.rs", "rank": 4, "score": 5.774052632867351 }, { "content": "// Copyright 2019 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n//! Utilities to work with OpenStack requests.\n\n\n\nuse std::collections::HashMap;\n\n\n\nuse futures::future::{self, Either};\n\nuse futures::prelude::*;\n\nuse log::trace;\n\nuse reqwest::r#async::{RequestBuilder, Response};\n\nuse serde::de::DeserializeOwned;\n\nuse serde::Deserialize;\n\n\n\nuse super::Error;\n\n\n\n#[derive(Debug, Deserialize)]\n", "file_path": "src/request.rs", "rank": 5, "score": 5.6365426879694365 }, { "content": "// Copyright 2017 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n//! Low-level code to work with the service catalog.\n\n\n\nuse log::{debug, error};\n\nuse osproto::identity::{CatalogRecord, Endpoint};\n\nuse reqwest::Url;\n\n\n\nuse super::{Error, ErrorKind};\n\n\n\n/// Find an endpoint in the service catalog.\n", "file_path": "src/catalog.rs", "rank": 6, "score": 5.343072175316459 }, { "content": "\n\nuse futures::stream::{Stream, StreamFuture};\n\nuse futures::{Async, Future, Poll};\n\nuse reqwest::r#async::{Body, Decoder, RequestBuilder, Response};\n\nuse reqwest::{Method, Url};\n\nuse serde::de::DeserializeOwned;\n\nuse serde::Serialize;\n\nuse tokio::runtime::current_thread::Runtime;\n\n\n\nuse super::request;\n\nuse super::services::ServiceType;\n\nuse super::{ApiVersion, AuthType, Error, Session};\n\n\n\n/// A result of an OpenStack operation.\n\npub type Result<T> = ::std::result::Result<T, Error>;\n\n\n\n/// A reader into an asynchronous stream.\n\n#[derive(Debug)]\n\npub struct SyncStream<'s, S = Decoder>\n\nwhere\n", "file_path": "src/sync.rs", "rank": 7, "score": 4.1938352059799415 }, { "content": " info.root_url.set_scheme(\"https\").unwrap();\n\n }\n\n\n\n debug!(\"Received {:?} for {} service\", info, catalog_type);\n\n info\n\n }),\n\n )\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use std::convert::TryFrom;\n\n\n\n use osproto::common::{Link, Root, Version, XdotY};\n\n use reqwest::Url;\n\n\n\n use super::super::services::ServiceType;\n\n use super::super::{ApiVersion, ErrorKind};\n\n use super::ServiceInfo;\n", "file_path": "src/protocol.rs", "rank": 8, "score": 4.04140527160792 }, { "content": " #[cfg(test)]\n\n pub(crate) fn cache_fake_service(\n\n &mut self,\n\n service_type: &'static str,\n\n service_info: ServiceInfo,\n\n ) {\n\n let _ = self.cached_info.set(service_type, service_info);\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use futures::Future;\n\n use reqwest::Url;\n\n\n\n use super::super::protocol::ServiceInfo;\n\n use super::super::services::{GenericService, VersionSelector};\n\n use super::super::{ApiVersion, NoAuth};\n\n use super::Session;\n\n\n", "file_path": "src/session.rs", "rank": 9, "score": 3.9727905810882613 }, { "content": "mod catalog;\n\nmod config;\n\nmod error;\n\npub mod identity;\n\nmod protocol;\n\npub mod request;\n\npub mod services;\n\nmod session;\n\n#[cfg(feature = \"sync\")]\n\npub mod sync;\n\nmod url;\n\n\n\npub use crate::adapter::Adapter;\n\npub use crate::apiversion::ApiVersion;\n\npub use crate::auth::{AuthType, NoAuth};\n\npub use crate::config::{from_config, from_env};\n\npub use crate::error::{Error, ErrorKind};\n\npub use crate::session::Session;\n", "file_path": "src/lib.rs", "rank": 10, "score": 3.917366605347633 }, { "content": " /// Otherwise the base API version is used. You can use\n\n /// [pick_api_version](#method.pick_api_version) to choose an API version to use.\n\n ///\n\n /// The result is a `RequestBuilder` that can be customized further. Error checking and response\n\n /// parsing can be done using functions from the [request](request/index.html) module.\n\n ///\n\n /// ```rust,no_run\n\n /// use futures::Future;\n\n /// use reqwest::Method;\n\n ///\n\n /// let session =\n\n /// osauth::from_env().expect(\"Failed to create an identity provider from the environment\");\n\n /// let future = session\n\n /// .request(osauth::services::COMPUTE, Method::HEAD, &[\"servers\", \"1234\"], None)\n\n /// .then(osauth::request::send_checked)\n\n /// .map(|response| {\n\n /// println!(\"Response: {:?}\", response);\n\n /// });\n\n /// ```\n\n ///\n", "file_path": "src/session.rs", "rank": 11, "score": 3.8318345833968106 }, { "content": "use reqwest::{IntoUrl, Method, Url};\n\n\n\nuse super::Error;\n\n\n\n/// Trait for an authentication type.\n\n///\n\n/// An OpenStack authentication type is expected to be able to:\n\n///\n\n/// 1. get an authentication token to use when accessing services,\n\n/// 2. get an endpoint URL for the given service type.\n\n///\n\n/// An authentication type should cache the token as long as it's valid.\n", "file_path": "src/auth.rs", "rank": 12, "score": 3.779569790084148 }, { "content": "use serde::Serialize;\n\n\n\nuse super::config;\n\nuse super::request;\n\nuse super::services::ServiceType;\n\nuse super::{ApiVersion, AuthType, Error, Session};\n\n\n\n/// Adapter for a specific service.\n\n///\n\n/// An `Adapter` is very similar to a [Session](struct.Session.html), but is tied to a specific\n\n/// service, and thus does not require passing a `service` argument to all calls.\n\n#[derive(Debug, Clone)]\n\npub struct Adapter<Srv> {\n\n inner: Session,\n\n service: Srv,\n\n default_api_version: Option<ApiVersion>,\n\n}\n\n\n\nimpl<Srv> From<Adapter<Srv>> for Session {\n\n fn from(value: Adapter<Srv>) -> Session {\n", "file_path": "src/adapter.rs", "rank": 13, "score": 3.7318831284287057 }, { "content": "//! need an authentication type object first. It can be obtained by:\n\n//! * Using [Password](identity/struct.Password.html) authentication against the Identity service.\n\n//! * Using [NoAuth](struct.NoAuth.html) authentication type, allowing access to standalone\n\n//! services without authentication.\n\n//!\n\n//! A `Session` can be created directly by loading it:\n\n//! * From the `clouds.yaml` configuration file using [from_config](fn.from_config.html).\n\n//! * From environment variables using [from_env](fn.from_env.html).\n\n//!\n\n//! See [Session](struct.Session.html) documentation for the details on using a `Session` for making\n\n//! OpenStack calls.\n\n//!\n\n//! If you need to work with a small number of servics, [Adapter](struct.Adapter.html) provides a\n\n//! more convenient interface. An adapter can be created directly using\n\n//! [Adapter::new](struct.Adapter.html#method.new) or from an existing `Session` using\n\n//! [Session::adapter](struct.Session.html#method.adapter) or\n\n//! [Session::into_adapter](struct.Session.html#method.into_adapter).\n\n\n\n#![crate_name = \"osauth\"]\n\n#![crate_type = \"lib\"]\n", "file_path": "src/lib.rs", "rank": 14, "score": 3.7287115563648854 }, { "content": " I::IntoIter: Send,\n\n {\n\n self.request(service, Method::GET, path, api_version)\n\n .then(request::send_checked)\n\n }\n\n\n\n /// Fetch a JSON using the GET request.\n\n ///\n\n /// ```rust,no_run\n\n /// use futures::Future;\n\n /// use osproto::common::IdAndName;\n\n /// use serde::Deserialize;\n\n ///\n\n /// #[derive(Debug, Deserialize)]\n\n /// pub struct ServersRoot {\n\n /// pub servers: Vec<IdAndName>,\n\n /// }\n\n ///\n\n /// let session =\n\n /// osauth::from_env().expect(\"Failed to create an identity provider from the environment\");\n", "file_path": "src/session.rs", "rank": 15, "score": 3.719820342726994 }, { "content": "\n\nimpl<R> From<SyncBody<R>> for Body\n\nwhere\n\n R: io::Read + Send + 'static,\n\n{\n\n fn from(value: SyncBody<R>) -> Body {\n\n let boxed: Box<dyn Stream<Item = Vec<u8>, Error = io::Error> + Send + 'static> =\n\n Box::new(value);\n\n Body::from(boxed)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use std::io::{Cursor, Read};\n\n\n\n use futures::stream;\n\n use reqwest::r#async::Body;\n\n\n\n use super::super::session::test;\n", "file_path": "src/sync.rs", "rank": 16, "score": 3.661612252516539 }, { "content": "// Copyright 2019 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n//! Caching.\n\n\n\nuse std::collections::HashMap;\n\nuse std::hash::Hash;\n\nuse std::ops::Deref;\n\nuse std::sync::RwLock;\n", "file_path": "src/cache.rs", "rank": 17, "score": 3.6390245490649837 }, { "content": "// Copyright 2019 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n//! Adapter for a specific service.\n\n\n\nuse futures::Future;\n\nuse reqwest::r#async::{RequestBuilder, Response};\n\nuse reqwest::{Method, Url};\n\nuse serde::de::DeserializeOwned;\n", "file_path": "src/adapter.rs", "rank": 18, "score": 3.616527488382483 }, { "content": " D: Deserializer<'de>,\n\n {\n\n deserializer.deserialize_str(ApiVersionVisitor)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub mod test {\n\n use std::str::FromStr;\n\n\n\n use serde_json;\n\n\n\n use super::ApiVersion;\n\n\n\n #[test]\n\n fn test_apiversion_format() {\n\n let ver = ApiVersion(2, 27);\n\n assert_eq!(&ver.to_string(), \"2.27\");\n\n assert_eq!(ApiVersion::from_str(\"2.27\").unwrap(), ver);\n\n }\n", "file_path": "src/apiversion.rs", "rank": 20, "score": 3.550196033437099 }, { "content": " }\n\n\n\n /// Make an HTTP request to the given service.\n\n ///\n\n /// The `service` argument is an object implementing the\n\n /// [ServiceType](../services/trait.ServiceType.html) trait. Some known service types are\n\n /// available in the [services](../services/index.html) module.\n\n ///\n\n /// The `path` argument is a URL path without the service endpoint (e.g. `/servers/1234`).\n\n ///\n\n /// If `api_version` is set, it is send with the request to enable a higher API version.\n\n /// Otherwise the base API version is used. You can use\n\n /// [pick_api_version](#method.pick_api_version) to choose an API version to use.\n\n ///\n\n /// The result is a `RequestBuilder` that can be customized further. Error checking and response\n\n /// parsing can be done using e.g. [send_checked](#method.send_checked) or\n\n /// [fetch_json](#method.fetch_json).\n\n ///\n\n /// ```rust,no_run\n\n /// use reqwest::Method;\n", "file_path": "src/sync.rs", "rank": 21, "score": 3.5080894973262384 }, { "content": " where\n\n Srv: ServiceType + Send + Clone,\n\n I: IntoIterator,\n\n I::Item: AsRef<str>,\n\n I::IntoIter: Send,\n\n {\n\n self.send_checked(self.request(service, Method::GET, path, api_version)?)\n\n }\n\n\n\n /// Fetch a JSON using the GET request.\n\n ///\n\n /// ```rust,no_run\n\n /// use osproto::common::IdAndName;\n\n /// use serde::Deserialize;\n\n ///\n\n /// #[derive(Debug, Deserialize)]\n\n /// pub struct ServersRoot {\n\n /// pub servers: Vec<IdAndName>,\n\n /// }\n\n ///\n", "file_path": "src/sync.rs", "rank": 22, "score": 3.497137640376764 }, { "content": "// Copyright 2019 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n//! Session structure definition.\n\n\n\nuse std::sync::Arc;\n\n\n\nuse futures::future;\n\nuse futures::prelude::*;\n", "file_path": "src/session.rs", "rank": 23, "score": 3.4844081519438905 }, { "content": "// Copyright 2018 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n//! ApiVersion implementation.\n\n\n\nuse std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse osproto::common::XdotY;\n", "file_path": "src/apiversion.rs", "rank": 24, "score": 3.458657065256836 }, { "content": " /// The result is a `RequestBuilder` that can be customized further. Error checking and response\n\n /// parsing can be done using functions from the [request](request/index.html) module.\n\n ///\n\n /// ```rust,no_run\n\n /// use futures::Future;\n\n /// use reqwest::Method;\n\n ///\n\n /// let adapter = osauth::Adapter::from_env(osauth::services::COMPUTE)\n\n /// .expect(\"Failed to create an identity provider from the environment\");\n\n /// let future = adapter\n\n /// .request(Method::HEAD, &[\"servers\", \"1234\"], None)\n\n /// .then(osauth::request::send_checked)\n\n /// .map(|response| {\n\n /// println!(\"Response: {:?}\", response);\n\n /// });\n\n /// ```\n\n ///\n\n /// This is the most generic call to make a request. You may prefer to use more specific `get`,\n\n /// `post`, `put` or `delete` calls instead.\n\n pub fn request<I>(\n", "file_path": "src/adapter.rs", "rank": 25, "score": 3.458657065256836 }, { "content": "use serde::Deserialize;\n\nuse tokio::runtime::Runtime;\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct Server {\n\n pub id: String,\n\n pub name: String,\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct ServersRoot {\n\n pub servers: Vec<Server>,\n\n}\n\n\n", "file_path": "examples/list-servers.rs", "rank": 26, "score": 3.4450781728036763 }, { "content": "/// Generic trait for authentication using Identity API V3.\n\npub trait Identity {\n\n /// Get a reference to the auth URL.\n\n fn auth_url(&self) -> &Url;\n\n}\n\n\n\n/// Password authentication using Identity API V3.\n\n///\n\n/// For any Identity authentication you need to know `auth_url`, which is an authentication endpoint\n\n/// of the Identity service. For the Password authentication you also need:\n\n/// 1. User name and password.\n\n/// 2. Domain of the user.\n\n/// 3. Name of the project to use.\n\n/// 4. Domain of the project.\n\n///\n\n/// Note: currently only names are supported for user, user domain and project domain. ID support is\n\n/// coming later.\n\n///\n\n/// Start with creating a `Password` object using [new](#method.new), then add a project scope\n\n/// with [with_project_scope](#method.with_project_scope):\n\n///\n", "file_path": "src/identity.rs", "rank": 27, "score": 3.443388304504394 }, { "content": "// Copyright 2019 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n//! Base code for authentication.\n\n\n\nuse std::fmt::Debug;\n\n\n\nuse futures::{future, Future};\n\nuse reqwest::r#async::{Client, RequestBuilder};\n", "file_path": "src/auth.rs", "rank": 28, "score": 3.4332838067083262 }, { "content": "// Copyright 2017 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n//! JSON structures and protocol bits for the Identity V3 API.\n\n\n\nuse std::convert::TryFrom;\n\nuse std::sync::Arc;\n\n\n\nuse futures::future;\n", "file_path": "src/protocol.rs", "rank": 29, "score": 3.420736273913567 }, { "content": "// Copyright 2018 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n//! Error and Result implementations.\n\n\n\nuse std::fmt;\n\n\n\nuse reqwest::Error as HttpClientError;\n\nuse reqwest::{StatusCode, UrlError};\n", "file_path": "src/error.rs", "rank": 30, "score": 3.420736273913567 }, { "content": "use reqwest::header::HeaderValue;\n\nuse serde::de::{Error as DeserError, Visitor};\n\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\n\n\n\nuse super::{Error, ErrorKind};\n\n\n\n/// API version (major, minor).\n\n#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]\n\npub struct ApiVersion(pub u16, pub u16);\n\n\n\nimpl<T> From<XdotY<T>> for ApiVersion\n\nwhere\n\n T: Into<u16>,\n\n{\n\n fn from(value: XdotY<T>) -> ApiVersion {\n\n ApiVersion(value.0.into(), value.1.into())\n\n }\n\n}\n\n\n\nimpl fmt::Display for ApiVersion {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{}.{}\", self.0, self.1)\n\n }\n\n}\n\n\n", "file_path": "src/apiversion.rs", "rank": 31, "score": 3.3714500712957456 }, { "content": " ///\n\n /// Returns `None` if none of the requested versions are available.\n\n ///\n\n /// ```rust,no_run\n\n /// use futures::Future;\n\n ///\n\n /// let session =\n\n /// osauth::from_env().expect(\"Failed to create an identity provider from the environment\");\n\n /// let candidates = vec![osauth::ApiVersion(1, 2), osauth::ApiVersion(1, 42)];\n\n /// let future = session\n\n /// .pick_api_version(osauth::services::COMPUTE, candidates)\n\n /// .and_then(|maybe_version| {\n\n /// if let Some(version) = maybe_version {\n\n /// println!(\"Using version {}\", version);\n\n /// } else {\n\n /// println!(\"Using the base version\");\n\n /// }\n\n /// session.get(osauth::services::COMPUTE, &[\"servers\"], maybe_version)\n\n /// });\n\n /// ```\n", "file_path": "src/session.rs", "rank": 32, "score": 3.2998688295751917 }, { "content": "use serde::Deserialize;\n\nuse tokio::runtime::Runtime;\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct Node {\n\n #[serde(rename = \"uuid\")]\n\n pub id: String,\n\n pub name: Option<String>,\n\n pub provision_state: String,\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct NodesRoot {\n\n pub nodes: Vec<Node>,\n\n}\n\n\n", "file_path": "examples/list-baremetal.rs", "rank": 33, "score": 3.2534779654486132 }, { "content": " service! {\n\n $(#[$attr])*\n\n $var: $cls -> $name, discovery true\n\n }\n\n };\n\n\n\n ($(#[$attr:meta])* $var:ident: $cls:ident -> $name:expr, header $hdr:expr) => {\n\n $(#[$attr])*\n\n #[derive(Copy, Clone, Debug)]\n\n pub struct $cls {\n\n __use_new: (),\n\n }\n\n\n\n impl $cls {\n\n /// Create a new service type.\n\n pub const fn new() -> $cls {\n\n $cls { __use_new: () }\n\n }\n\n }\n\n\n", "file_path": "src/services.rs", "rank": 34, "score": 3.2534779654486132 }, { "content": "/// ```rust,no_run\n\n/// # use osproto::identity::IdOrName;\n\n/// let auth = osauth::identity::Password::new(\n\n/// \"https://cloud.local/identity\",\n\n/// \"admin\",\n\n/// \"pa$$w0rd\",\n\n/// \"Default\"\n\n/// )\n\n/// .expect(\"Invalid auth_url\")\n\n/// .with_project_scope(IdOrName::Name(\"project1\".to_string()), None);\n\n///\n\n/// let session = osauth::Session::new(auth);\n\n/// ```\n\n///\n\n/// If your cloud has several regions, pick one using [with_region](#method.with_region):\n\n///\n\n/// ```rust,no_run\n\n/// # use osproto::identity::IdOrName;\n\n/// let auth = osauth::identity::Password::new(\n\n/// \"https://cloud.local/identity\",\n", "file_path": "src/identity.rs", "rank": 35, "score": 3.2389669133111156 }, { "content": " ///\n\n /// The resulting session will use the default endpoint interface (usually,\n\n /// public).\n\n pub fn new<Auth: AuthType + 'static>(auth_type: Auth) -> Session {\n\n Session {\n\n auth: Arc::new(auth_type),\n\n cached_info: Arc::new(cache::MapCache::default()),\n\n endpoint_interface: None,\n\n }\n\n }\n\n\n\n /// Create an adapter for the specific service type.\n\n ///\n\n /// The new `Adapter` will share the same authentication and will initially use the same\n\n /// endpoint interface (although it can be changed later without affecting the `Session`).\n\n ///\n\n /// If you don't need the `Session` any more, using [into_adapter](#method.into_adapter) is a\n\n /// bit more efficient.\n\n ///\n\n /// ```rust,no_run\n", "file_path": "src/session.rs", "rank": 36, "score": 3.2093512451004074 }, { "content": "// Copyright 2019 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n//! Synchronous wrapper for a session.\n\n//!\n\n//! This module is only available when the `sync` feature is enabled.\n\n\n\nuse std::cell::RefCell;\n\nuse std::io;\n", "file_path": "src/sync.rs", "rank": 37, "score": 3.137628556369022 }, { "content": " {\n\n self.inner.pick_api_version(self.service.clone(), versions)\n\n }\n\n\n\n /// Check if the service supports the API version.\n\n pub fn supports_api_version(\n\n &self,\n\n version: ApiVersion,\n\n ) -> impl Future<Item = bool, Error = Error> + Send {\n\n self.pick_api_version(Some(version)).map(|x| x.is_some())\n\n }\n\n\n\n /// Make an HTTP request.\n\n ///\n\n /// The `path` argument is a URL path without the service endpoint (e.g. `/servers/1234`).\n\n ///\n\n /// If `api_version` is set, it is send with the request to enable a higher API version.\n\n /// Otherwise the base API version is used. You can use\n\n /// [pick_api_version](#method.pick_api_version) to choose an API version to use.\n\n ///\n", "file_path": "src/adapter.rs", "rank": 38, "score": 3.137628556369022 }, { "content": " /// This version will be used when no version is specified. No checks are done against this\n\n /// version inside of this call. If it is not valid, the subsequent `request` calls will fail.\n\n #[inline]\n\n pub fn set_default_api_version(&mut self, api_version: Option<ApiVersion>) {\n\n self.default_api_version = api_version;\n\n }\n\n\n\n /// Set endpoint interface to use.\n\n ///\n\n /// This call clears the cached service information for this `Adapter`.\n\n /// It does not, however, affect clones of this `Adapter`.\n\n pub fn set_endpoint_interface<S>(&mut self, endpoint_interface: S)\n\n where\n\n S: Into<String>,\n\n {\n\n self.inner.set_endpoint_interface(endpoint_interface);\n\n }\n\n\n\n /// Convert this adapter into one using the given authentication.\n\n #[inline]\n", "file_path": "src/adapter.rs", "rank": 39, "score": 3.1098291302936905 }, { "content": "// Copyright 2019 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n//! OpenStack service types.\n\n\n\nuse reqwest::header::HeaderMap;\n\n\n\nuse super::{ApiVersion, Error, ErrorKind};\n\n\n\n/// Trait representing a service type.\n", "file_path": "src/services.rs", "rank": 40, "score": 3.09611332995426 }, { "content": "// Copyright 2019 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nextern crate env_logger;\n\nextern crate futures;\n\nextern crate osauth;\n\nextern crate tokio;\n\n\n\nuse futures::Future;\n\nuse tokio::runtime::Runtime;\n\n\n", "file_path": "examples/compute-versions.rs", "rank": 41, "score": 3.0690415141866616 }, { "content": " /// let adapter = session.into_adapter(osauth::services::COMPUTE);\n\n /// ```\n\n #[inline]\n\n pub fn into_adapter<Srv>(self, service: Srv) -> Adapter<Srv> {\n\n Adapter::from_session(self, service)\n\n }\n\n\n\n /// Get a reference to the authentication type in use.\n\n #[inline]\n\n pub fn auth_type(&self) -> &dyn AuthType {\n\n self.auth.as_ref()\n\n }\n\n\n\n /// Endpoint interface in use (if any).\n\n #[inline]\n\n pub fn endpoint_interface(&self) -> &Option<String> {\n\n &self.endpoint_interface\n\n }\n\n\n\n /// Update the authentication and purges cached endpoint information.\n", "file_path": "src/session.rs", "rank": 42, "score": 3.0419995479342585 }, { "content": "// Copyright 2019 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n//! Authentication using Identity API v3.\n\n//!\n\n//! Currently only supports [Password](struct.Password.html) authentication.\n\n//! Identity API v2 is not and will not be supported.\n\n\n\nuse std::collections::hash_map::DefaultHasher;\n", "file_path": "src/identity.rs", "rank": 43, "score": 3.0293099640893084 }, { "content": "// Copyright 2019 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nextern crate env_logger;\n\nextern crate futures;\n\nextern crate osauth;\n\nextern crate tokio;\n\n\n\nuse futures::Future;\n\nuse tokio::runtime::Runtime;\n\n\n\nstatic DATA: u8 = 42;\n\n\n", "file_path": "examples/object-store.rs", "rank": 44, "score": 3.0293099640893084 }, { "content": " /// ```rust,no_run\n\n /// use futures::Future;\n\n /// use serde::Deserialize;\n\n ///\n\n /// #[derive(Debug, Deserialize)]\n\n /// pub struct Server {\n\n /// pub id: String,\n\n /// pub name: String,\n\n /// }\n\n ///\n\n /// #[derive(Debug, Deserialize)]\n\n /// pub struct ServersRoot {\n\n /// pub servers: Vec<Server>,\n\n /// }\n\n ///\n\n /// let adapter = osauth::from_env()\n\n /// .expect(\"Failed to create an identity provider from the environment\")\n\n /// .into_adapter(osauth::services::COMPUTE);\n\n /// let future = adapter\n\n /// .get_json(&[\"servers\"], None)\n", "file_path": "src/adapter.rs", "rank": 45, "score": 3.002960626030069 }, { "content": "pub mod test {\n\n use futures::Future;\n\n\n\n use super::{AuthType, NoAuth};\n\n\n\n #[test]\n\n fn test_noauth_new() {\n\n let a = NoAuth::new(\"http://127.0.0.1:8080/v1\").unwrap();\n\n let e = a.endpoint;\n\n assert_eq!(e.scheme(), \"http\");\n\n assert_eq!(e.host_str().unwrap(), \"127.0.0.1\");\n\n assert_eq!(e.port().unwrap(), 8080u16);\n\n assert_eq!(e.path(), \"/v1\");\n\n }\n\n\n\n #[test]\n\n fn test_noauth_new_fail() {\n\n let _ = NoAuth::new(\"foo bar\").err().unwrap();\n\n }\n\n\n", "file_path": "src/auth.rs", "rank": 46, "score": 2.964911005258183 }, { "content": " None\n\n }\n\n}\n\n\n\n/// Authentication type that provides no authentication.\n\n///\n\n/// This type always uses a pre-defined endpoint and sends no authenticaiton information:\n\n/// ```rust,no_run\n\n/// let auth = osauth::NoAuth::new(\"https://cloud.local/baremetal\")\n\n/// .expect(\"Invalid auth URL\");\n\n/// let session = osauth::Session::new(auth);\n\n/// ```\n\n#[derive(Clone, Debug)]\n\npub struct NoAuth {\n\n client: Client,\n\n endpoint: Url,\n\n}\n\n\n\nimpl NoAuth {\n\n /// Create a new fake authentication method using a fixed endpoint.\n", "file_path": "src/auth.rs", "rank": 47, "score": 2.964911005258183 }, { "content": "impl SyncSession {\n\n /// Create a new synchronous wrapper.\n\n pub fn new(session: Session) -> SyncSession {\n\n SyncSession {\n\n inner: session,\n\n runtime: RefCell::new(Runtime::new().expect(\"Cannot create a runtime\")),\n\n }\n\n }\n\n\n\n /// Get a reference to the authentication type in use.\n\n #[inline]\n\n pub fn auth_type(&self) -> &dyn AuthType {\n\n self.inner.auth_type()\n\n }\n\n\n\n /// Endpoint interface in use (if any).\n\n #[inline]\n\n pub fn endpoint_interface(&self) -> &Option<String> {\n\n &self.inner.endpoint_interface()\n\n }\n", "file_path": "src/sync.rs", "rank": 48, "score": 2.946245505085181 }, { "content": "\n\n#[cfg(test)]\n\npub mod test {\n\n use osproto::identity::{CatalogRecord, Endpoint};\n\n\n\n use super::super::{Error, ErrorKind};\n\n\n\n fn demo_service1() -> CatalogRecord {\n\n CatalogRecord {\n\n service_type: String::from(\"identity\"),\n\n endpoints: vec![\n\n Endpoint {\n\n interface: String::from(\"public\"),\n\n region: String::from(\"RegionOne\"),\n\n url: String::from(\"https://host.one/identity\"),\n\n },\n\n Endpoint {\n\n interface: String::from(\"internal\"),\n\n region: String::from(\"RegionOne\"),\n\n url: String::from(\"http://192.168.22.1/identity\"),\n", "file_path": "src/catalog.rs", "rank": 49, "score": 2.9278135507227687 }, { "content": " /// Use this call if you need some advanced features of the resulting `RequestBuilder`.\n\n /// Otherwise use:\n\n /// * [get](#method.get) to issue a generic GET without a query.\n\n /// * [get_query](#method.get_query) to issue a generic GET with a query.\n\n /// * [get_json](#method.get_json) to issue GET and parse a JSON result.\n\n /// * [get_json_query](#method.get_json_query) to issue GET with a query and parse a JSON\n\n /// result.\n\n ///\n\n /// See [request](#method.request) for an explanation of the parameters.\n\n #[inline]\n\n #[deprecated(since = \"0.2.3\", note = \"Use request\")]\n\n pub fn start_get<Srv, I>(\n\n &self,\n\n service: Srv,\n\n path: I,\n\n api_version: Option<ApiVersion>,\n\n ) -> impl Future<Item = RequestBuilder, Error = Error> + Send\n\n where\n\n Srv: ServiceType + Send + Clone,\n\n I: IntoIterator,\n", "file_path": "src/session.rs", "rank": 50, "score": 2.8920300563511225 }, { "content": " /// Default API version used when no version is specified.\n\n #[inline]\n\n pub fn default_api_version(&self) -> Option<ApiVersion> {\n\n self.default_api_version\n\n }\n\n\n\n /// Endpoint interface in use (if any).\n\n #[inline]\n\n pub fn endpoint_interface(&self) -> &Option<String> {\n\n self.inner.endpoint_interface()\n\n }\n\n\n\n /// Update the authentication and purges cached endpoint information.\n\n ///\n\n /// # Warning\n\n ///\n\n /// Authentication will also be updated for clones of this `Adapter` and its parent `Session`,\n\n /// since they share the same authentication object.\n\n #[inline]\n\n pub fn refresh(&mut self) -> impl Future<Item = (), Error = Error> + Send {\n", "file_path": "src/adapter.rs", "rank": 51, "score": 2.8563356666687745 }, { "content": " S: Stream,\n\n S::Item: AsRef<[u8]>,\n\n{\n\n session: &'s SyncSession,\n\n // NOTE(dtantsur): using Option to be able to take() it.\n\n inner: Option<StreamFuture<S>>,\n\n chunk: io::Cursor<S::Item>,\n\n}\n\n\n\n/// A synchronous body that can be used with asynchronous code.\n\n#[derive(Debug, Clone, Default)]\n\npub struct SyncBody<R> {\n\n reader: R,\n\n}\n\n\n\n/// A synchronous wrapper for an asynchronous session.\n\n#[derive(Debug)]\n\npub struct SyncSession {\n\n inner: Session,\n\n runtime: RefCell<Runtime>,\n", "file_path": "src/sync.rs", "rank": 52, "score": 2.8563356666687745 }, { "content": "/// \"admin\",\n\n/// \"pa$$w0rd\",\n\n/// \"Default\"\n\n/// )\n\n/// .expect(\"Invalid auth_url\")\n\n/// .with_project_scope(IdOrName::Name(\"project1\".to_string()), None)\n\n/// .with_region(\"US-East\");\n\n///\n\n/// let session = osauth::Session::new(auth);\n\n/// ```\n\n///\n\n/// By default, the `public` endpoint interface is used. If you would prefer to default to another\n\n/// one, you can set it with\n\n/// [with_default_endpoint_interface](#method.with_default_endpoint_interface).\n\n///\n\n/// ```rust,no_run\n\n/// # use osproto::identity::IdOrName;\n\n/// let auth = osauth::identity::Password::new(\n\n/// \"https://cloud.local/identity\",\n\n/// \"admin\",\n", "file_path": "src/identity.rs", "rank": 53, "score": 2.839008205762857 }, { "content": " /// .expect(\"Failed to create an identity provider from the environment\");\n\n /// let candidates = vec![osauth::ApiVersion(1, 2), osauth::ApiVersion(1, 42)];\n\n /// let future = adapter\n\n /// .pick_api_version(candidates)\n\n /// .and_then(|maybe_version| {\n\n /// if let Some(version) = maybe_version {\n\n /// println!(\"Using version {}\", version);\n\n /// } else {\n\n /// println!(\"Using the base version\");\n\n /// }\n\n /// adapter.get(&[\"servers\"], maybe_version)\n\n /// });\n\n /// ```\n\n pub fn pick_api_version<I>(\n\n &self,\n\n versions: I,\n\n ) -> impl Future<Item = Option<ApiVersion>, Error = Error> + Send\n\n where\n\n I: IntoIterator<Item = ApiVersion>,\n\n I::IntoIter: Send,\n", "file_path": "src/adapter.rs", "rank": 54, "score": 2.8218897052591285 }, { "content": " &self,\n\n method: Method,\n\n path: I,\n\n api_version: Option<ApiVersion>,\n\n ) -> impl Future<Item = RequestBuilder, Error = Error> + Send\n\n where\n\n I: IntoIterator,\n\n I::Item: AsRef<str>,\n\n I::IntoIter: Send,\n\n {\n\n let real_version = api_version.or(self.default_api_version);\n\n self.inner\n\n .request(self.service.clone(), method, path, real_version)\n\n }\n\n\n\n /// Start a GET request.\n\n ///\n\n /// Use this call if you need some advanced features of the resulting `RequestBuilder`.\n\n /// Otherwise use:\n\n /// * [get](#method.get) to issue a generic GET without a query.\n", "file_path": "src/adapter.rs", "rank": 55, "score": 2.8218897052591285 }, { "content": " }),\n\n )\n\n}\n\n\n\n#[cfg(test)]\n\npub mod test {\n\n #![allow(unused_results)]\n\n\n\n use super::super::AuthType;\n\n use super::{IdOrName, Identity, Password};\n\n\n\n #[test]\n\n fn test_identity_new() {\n\n let id = Password::new(\"http://127.0.0.1:8080/\", \"admin\", \"pa$$w0rd\", \"Default\").unwrap();\n\n let e = id.auth_url();\n\n assert_eq!(e.scheme(), \"http\");\n\n assert_eq!(e.host_str().unwrap(), \"127.0.0.1\");\n\n assert_eq!(e.port().unwrap(), 8080u16);\n\n assert_eq!(e.path(), \"/\");\n\n assert_eq!(id.user(), &IdOrName::Name(\"admin\".to_string()));\n", "file_path": "src/identity.rs", "rank": 56, "score": 2.7717508384244374 }, { "content": " /// It does not, however, affect clones of this `Session`.\n\n #[inline]\n\n pub fn set_auth_type<Auth: AuthType + 'static>(&mut self, auth_type: Auth) {\n\n self.reset_cache();\n\n self.auth = Arc::new(auth_type);\n\n }\n\n\n\n /// Set endpoint interface to use.\n\n ///\n\n /// This call clears the cached service information for this `Session`.\n\n /// It does not, however, affect clones of this `Session`.\n\n pub fn set_endpoint_interface<S>(&mut self, endpoint_interface: S)\n\n where\n\n S: Into<String>,\n\n {\n\n self.reset_cache();\n\n self.endpoint_interface = Some(endpoint_interface.into());\n\n }\n\n\n\n /// Convert this session into one using the given authentication.\n", "file_path": "src/session.rs", "rank": 57, "score": 2.7554314889897786 }, { "content": " self.inner.set_auth_type(auth_type);\n\n }\n\n\n\n /// Set endpoint interface to use.\n\n ///\n\n /// This call clears the cached service information for this `Session`.\n\n /// It does not, however, affect clones of this `Session`.\n\n #[inline]\n\n pub fn set_endpoint_interface<S>(&mut self, endpoint_interface: S)\n\n where\n\n S: Into<String>,\n\n {\n\n self.inner.set_endpoint_interface(endpoint_interface);\n\n }\n\n\n\n /// Convert this session into one using the given authentication.\n\n #[inline]\n\n pub fn with_auth_type<Auth: AuthType + 'static>(mut self, auth_method: Auth) -> SyncSession {\n\n self.set_auth_type(auth_method);\n\n self\n", "file_path": "src/sync.rs", "rank": 58, "score": 2.739303182927793 }, { "content": " self.inner.get_endpoint(self.service.clone(), path)\n\n }\n\n\n\n /// Get the currently used major version from the given service.\n\n ///\n\n /// Can return `None` if the service does not support API version discovery at all.\n\n pub fn get_major_version(\n\n &self,\n\n ) -> impl Future<Item = Option<ApiVersion>, Error = Error> + Send {\n\n self.inner.get_major_version(self.service.clone())\n\n }\n\n\n\n /// Pick the highest API version supported by the service.\n\n ///\n\n /// Returns `None` if none of the requested versions are available.\n\n ///\n\n /// ```rust,no_run\n\n /// use futures::Future;\n\n ///\n\n /// let adapter = osauth::Adapter::from_env(osauth::services::COMPUTE)\n", "file_path": "src/adapter.rs", "rank": 59, "score": 2.7233625850703316 }, { "content": "// Copyright 2019 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n//! Handy primitives for working with URLs.\n\n\n\nuse reqwest::Url;\n\n\n\n#[inline]\n\n#[allow(unused_results)]\n", "file_path": "src/url.rs", "rank": 60, "score": 2.6920315569920588 }, { "content": " {\n\n self.block_on(self.inner.get_major_version(service))\n\n }\n\n\n\n /// Pick the highest API version supported by the service.\n\n ///\n\n /// Returns `None` if none of the requested versions are available.\n\n ///\n\n /// ```rust,no_run\n\n /// let session = osauth::sync::SyncSession::new(\n\n /// osauth::from_env().expect(\"Failed to create an identity provider from the environment\")\n\n /// );\n\n /// let candidates = vec![osauth::ApiVersion(1, 2), osauth::ApiVersion(1, 42)];\n\n /// let maybe_version = session\n\n /// .pick_api_version(osauth::services::COMPUTE, candidates)\n\n /// .expect(\"Cannot negotiate an API version\");\n\n /// if let Some(version) = maybe_version {\n\n /// println!(\"Using version {}\", version);\n\n /// } else {\n\n /// println!(\"Using the base version\");\n", "file_path": "src/sync.rs", "rank": 61, "score": 2.676634833547137 }, { "content": "/// Trait for an authentication type.\n\n///\n\n/// An OpenStack authentication type is expected to be able to:\n\n///\n\n/// 1. get an authentication token to use when accessing services,\n\n/// 2. get an endpoint URL for the given service type.\n\n///\n\n/// An authentication type should cache the token as long as it's valid.\n\npub trait AuthType: Debug + Sync + Send {\n\n /// Get a URL for the requested service.\n\n fn get_endpoint(\n\n &self,\n\n service_type: String,\n\n endpoint_interface: Option<String>,\n\n ) -> Box<dyn Future<Item = Url, Error = Error> + Send>;\n\n\n\n /// Create an authenticated request.\n\n fn request(\n\n &self,\n\n method: Method,\n\n url: Url,\n\n ) -> Box<dyn Future<Item = RequestBuilder, Error = Error> + Send>;\n\n\n\n /// Refresh the authentication (renew the token, etc).\n\n fn refresh(&self) -> Box<dyn Future<Item = (), Error = Error> + Send>;\n\n\n\n /// Region used with this authentication (if any).\n\n fn region(&self) -> Option<String> {\n", "file_path": "src/auth.rs", "rank": 62, "score": 2.6604046071688825 }, { "content": " pub fn with_auth_type<Auth: AuthType + 'static>(mut self, auth_method: Auth) -> Adapter<Srv> {\n\n self.set_auth_type(auth_method);\n\n self\n\n }\n\n\n\n /// Convert this adapter into one using the given default API version.\n\n #[inline]\n\n pub fn with_default_api_version(mut self, api_version: Option<ApiVersion>) -> Adapter<Srv> {\n\n self.set_default_api_version(api_version);\n\n self\n\n }\n\n\n\n /// Convert this adapter into one using the given endpoint interface.\n\n #[inline]\n\n pub fn with_endpoint_interface<S>(mut self, endpoint_interface: S) -> Adapter<Srv>\n\n where\n\n S: Into<String>,\n\n {\n\n self.set_endpoint_interface(endpoint_interface);\n\n self\n", "file_path": "src/adapter.rs", "rank": 63, "score": 2.6463637685786474 }, { "content": " /// You won't need to use this call most of the time, since all request calls can fetch the\n\n /// endpoint automatically.\n\n #[inline]\n\n pub fn get_endpoint<Srv, I>(&self, service: Srv, path: I) -> Result<Url>\n\n where\n\n Srv: ServiceType + Send,\n\n I: IntoIterator,\n\n I::Item: AsRef<str>,\n\n I::IntoIter: Send,\n\n {\n\n self.block_on(self.inner.get_endpoint(service, path))\n\n }\n\n\n\n /// Get the currently used major version from the given service.\n\n ///\n\n /// Can return `None` if the service does not support API version discovery at all.\n\n #[inline]\n\n pub fn get_major_version<Srv>(&self, service: Srv) -> Result<Option<ApiVersion>>\n\n where\n\n Srv: ServiceType + Send,\n", "file_path": "src/sync.rs", "rank": 64, "score": 2.6463637685786474 }, { "content": "// Copyright 2019 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nextern crate env_logger;\n\nextern crate futures;\n\nextern crate osauth;\n\nextern crate tokio;\n\n\n\nuse futures::Future;\n", "file_path": "examples/list-baremetal.rs", "rank": 65, "score": 2.631483552461436 }, { "content": "// Copyright 2019 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nextern crate env_logger;\n\nextern crate futures;\n\nextern crate osauth;\n\nextern crate tokio;\n\n\n\nuse futures::Future;\n", "file_path": "examples/list-servers.rs", "rank": 66, "score": 2.631483552461436 }, { "content": " use super::super::{ApiVersion, Error};\n\n use super::{SyncBody, SyncSession, SyncStream};\n\n\n\n fn new_simple_sync_session(url: &str) -> SyncSession {\n\n SyncSession::new(test::new_simple_session(url))\n\n }\n\n\n\n fn new_sync_session(url: &str) -> SyncSession {\n\n SyncSession::new(test::new_session(url, test::fake_service_info()))\n\n }\n\n\n\n #[test]\n\n fn test_get_api_versions_absent() {\n\n let s = new_simple_sync_session(test::URL);\n\n let vers = s.get_api_versions(test::FAKE).unwrap();\n\n assert!(vers.is_none());\n\n }\n\n\n\n #[test]\n\n fn test_get_api_versions_present() {\n", "file_path": "src/sync.rs", "rank": 67, "score": 2.5456017007553338 }, { "content": " pub const fn new() -> $cls {\n\n $cls { __use_new: () }\n\n }\n\n }\n\n\n\n impl $crate::services::ServiceType for $cls {\n\n fn catalog_type(&self) -> &'static str {\n\n $name\n\n }\n\n\n\n fn version_discovery_supported(&self) -> bool {\n\n $disc\n\n }\n\n }\n\n\n\n $(#[$attr])*\n\n pub const $var: $cls = $cls::new();\n\n };\n\n\n\n ($(#[$attr:meta])* $var:ident: $cls:ident -> $name:expr) => {\n", "file_path": "src/services.rs", "rank": 68, "score": 2.4642830412296832 }, { "content": " },\n\n };\n\n Ok(Password {\n\n client,\n\n auth_url: url,\n\n region: None,\n\n body,\n\n token_endpoint,\n\n cached_token: Arc::new(ValueCache::default()),\n\n endpoint_interface: \"public\".to_string(),\n\n })\n\n }\n\n\n\n /// The default endpoint interface.\n\n #[inline]\n\n pub fn default_endpoint_interface(&self) -> &String {\n\n &self.endpoint_interface\n\n }\n\n\n\n /// Set the default endpoint interface to use.\n", "file_path": "src/identity.rs", "rank": 69, "score": 2.438601536631412 }, { "content": " if service.major_version_supported(ver.id.into()) {\n\n if !ver.is_stable() {\n\n warn!(\n\n \"Using version {:?} of {} API that is not marked as stable\",\n\n ver,\n\n service.catalog_type()\n\n );\n\n }\n\n\n\n ServiceInfo::try_from(ver)\n\n } else {\n\n Err(Error::new(\n\n ErrorKind::EndpointNotFound,\n\n \"Major version not supported\",\n\n ))\n\n }\n\n } else {\n\n value.sort();\n\n value\n\n .into_stable_iter()\n", "file_path": "src/protocol.rs", "rank": 70, "score": 2.4134497903218968 }, { "content": " }\n\n}\n\n\n\nimpl ComputeService {\n\n /// Create a Compute service type.\n\n pub const fn new() -> ComputeService {\n\n ComputeService { __use_new: () }\n\n }\n\n}\n\n\n\nimpl ServiceType for ComputeService {\n\n fn catalog_type(&self) -> &'static str {\n\n \"compute\"\n\n }\n\n\n\n fn major_version_supported(&self, version: ApiVersion) -> bool {\n\n version.0 == 2\n\n }\n\n\n\n fn set_api_version_headers(\n", "file_path": "src/services.rs", "rank": 71, "score": 2.4134497903218968 }, { "content": " project,\n\n domain: domain.into(),\n\n }));\n\n }\n\n\n\n /// Convert this session into one using the given endpoint interface.\n\n #[inline]\n\n pub fn with_default_endpoint_interface<S>(mut self, endpoint_interface: S) -> Self\n\n where\n\n S: Into<String>,\n\n {\n\n self.set_default_endpoint_interface(endpoint_interface);\n\n self\n\n }\n\n\n\n /// Scope authentication to the given project.\n\n #[inline]\n\n pub fn with_project_scope(\n\n mut self,\n\n project: IdOrName,\n", "file_path": "src/identity.rs", "rank": 72, "score": 2.317825541530803 }, { "content": " /// Issue a GET request.\n\n ///\n\n /// See [request](#method.request) for an explanation of the parameters.\n\n #[inline]\n\n pub fn get<I>(\n\n &self,\n\n path: I,\n\n api_version: Option<ApiVersion>,\n\n ) -> impl Future<Item = Response, Error = Error> + Send\n\n where\n\n I: IntoIterator,\n\n I::Item: AsRef<str>,\n\n I::IntoIter: Send,\n\n {\n\n self.start_get(path, api_version)\n\n .then(request::send_checked)\n\n }\n\n\n\n /// Fetch a JSON using the GET request.\n\n ///\n", "file_path": "src/adapter.rs", "rank": 73, "score": 2.229490034972356 }, { "content": " let cached_token = Arc::clone(&self.cached_token);\n\n future::Either::B(\n\n self.client\n\n .post(&self.token_endpoint)\n\n .json(&self.body)\n\n .send()\n\n .then(request::check)\n\n .and_then(token_from_response)\n\n .map(move |token| {\n\n cached_token.set(token);\n\n }),\n\n )\n\n }\n\n }\n\n\n\n /// User name.\n\n #[inline]\n\n #[deprecated(since = \"0.2.3\", note = \"Use user in preparation for user ID support.\")]\n\n pub fn user_name(&self) -> &String {\n\n match *self.user() {\n", "file_path": "src/identity.rs", "rank": 74, "score": 2.2084482875785314 }, { "content": "/// A generic service.\n\n#[derive(Copy, Clone, Debug)]\n\npub struct GenericService {\n\n catalog_type: &'static str,\n\n major_version: VersionSelector,\n\n}\n\n\n\n/// Compute service.\n\n#[derive(Copy, Clone, Debug)]\n\npub struct ComputeService {\n\n __use_new: (),\n\n}\n\n\n\nservice! {\n\n #[doc = \"Bare Metal service.\"]\n\n BAREMETAL: BareMetalService -> \"baremetal\", header \"x-openstack-ironic-api-version\"\n\n}\n\n\n\nservice! {\n\n #[doc = \"Image service.\"]\n", "file_path": "src/services.rs", "rank": 75, "score": 2.2084482875785314 }, { "content": " Exact(ApiVersion),\n\n /// A range of major versions.\n\n Range(ApiVersion, ApiVersion),\n\n /// Any major version.\n\n Any,\n\n #[doc(hidden)]\n\n __Nonexhaustive,\n\n}\n\n\n\n// TODO(dtantsur): change $name to be a literal\n\nmacro_rules! service {\n\n ($(#[$attr:meta])* $var:ident: $cls:ident -> $name:expr, discovery $disc:expr) => {\n\n $(#[$attr])*\n\n #[derive(Copy, Clone, Debug)]\n\n pub struct $cls {\n\n __use_new: (),\n\n }\n\n\n\n impl $cls {\n\n /// Create a new service type.\n", "file_path": "src/services.rs", "rank": 76, "score": 2.1675342600194396 }, { "content": " pub fn from_env(service: Srv) -> Result<Adapter<Srv>, Error> {\n\n Ok(config::from_env()?.into_adapter(service))\n\n }\n\n\n\n /// Create a new adapter from a `Session`.\n\n #[inline]\n\n pub fn from_session(session: Session, service: Srv) -> Adapter<Srv> {\n\n Adapter {\n\n inner: session,\n\n service,\n\n default_api_version: None,\n\n }\n\n }\n\n\n\n /// Get a reference to the authentication type in use.\n\n #[inline]\n\n pub fn auth_type(&self) -> &dyn AuthType {\n\n self.inner.auth_type()\n\n }\n\n\n", "file_path": "src/adapter.rs", "rank": 77, "score": 2.1476405129868317 }, { "content": " self.inner.refresh()\n\n }\n\n\n\n /// Session used for this adapter.\n\n #[inline]\n\n pub fn session(&self) -> &Session {\n\n &self.inner\n\n }\n\n\n\n /// Set a new authentication for this `Adapter`.\n\n ///\n\n /// This call clears the cached service information for this `Adapter`.\n\n /// It does not, however, affect clones of this `Adapter`.\n\n #[inline]\n\n pub fn set_auth_type<Auth: AuthType + 'static>(&mut self, auth_type: Auth) {\n\n self.inner.set_auth_type(auth_type)\n\n }\n\n\n\n /// Set the default API version.\n\n ///\n", "file_path": "src/adapter.rs", "rank": 78, "score": 2.1476405129868317 }, { "content": "\n\n /// Refresh the session.\n\n #[inline]\n\n pub fn refresh(&mut self) -> Result<()> {\n\n let fut = self.inner.refresh();\n\n self.block_on(fut)\n\n }\n\n\n\n /// Reference to the asynchronous session used.\n\n #[inline]\n\n pub fn session(&self) -> &Session {\n\n &self.inner\n\n }\n\n\n\n /// Set a new authentication for this `Session`.\n\n ///\n\n /// This call clears the cached service information for this `Session`.\n\n /// It does not, however, affect clones of this `Session`.\n\n #[inline]\n\n pub fn set_auth_type<Auth: AuthType + 'static>(&mut self, auth_type: Auth) {\n", "file_path": "src/sync.rs", "rank": 79, "score": 2.1281086166480265 }, { "content": " }\n\n\n\n /// Download a body from a response.\n\n ///\n\n /// ```rust,no_run\n\n /// use std::io::Read;\n\n ///\n\n /// let session = osauth::sync::SyncSession::new(\n\n /// osauth::from_env().expect(\"Failed to create an identity provider from the environment\")\n\n /// );\n\n ///\n\n /// session\n\n /// .get(osauth::services::OBJECT_STORAGE, &[\"test-container\", \"test-object\"], None)\n\n /// .map(|response| {\n\n /// let mut buffer = Vec::new();\n\n /// session\n\n /// .download(response)\n\n /// .read_to_end(&mut buffer)\n\n /// .map(|_| {\n\n /// println!(\"Data: {:?}\", buffer);\n", "file_path": "src/sync.rs", "rank": 80, "score": 2.1089287873371596 }, { "content": " /// See [request](#method.request) for an explanation of the parameters.\n\n #[inline]\n\n #[deprecated(since = \"0.2.3\", note = \"Use request\")]\n\n pub fn start_post<Srv, I>(\n\n &self,\n\n service: Srv,\n\n path: I,\n\n api_version: Option<ApiVersion>,\n\n ) -> impl Future<Item = RequestBuilder, Error = Error> + Send\n\n where\n\n Srv: ServiceType + Send + Clone,\n\n I: IntoIterator,\n\n I::Item: AsRef<str>,\n\n I::IntoIter: Send,\n\n {\n\n self.request(service, Method::POST, path, api_version)\n\n }\n\n\n\n /// POST a JSON object.\n\n ///\n", "file_path": "src/session.rs", "rank": 81, "score": 2.071587927439394 }, { "content": " self.extract_service_info(service, |info| {\n\n match (info.minimum_version, info.current_version) {\n\n (Some(min), Some(max)) => Some((min, max)),\n\n _ => None,\n\n }\n\n })\n\n }\n\n\n\n /// Construct and endpoint for the given service from the path.\n\n ///\n\n /// You won't need to use this call most of the time, since all request calls can fetch the\n\n /// endpoint automatically.\n\n pub fn get_endpoint<Srv, I>(\n\n &self,\n\n service: Srv,\n\n path: I,\n\n ) -> impl Future<Item = Url, Error = Error> + Send\n\n where\n\n Srv: ServiceType + Send,\n\n I: IntoIterator,\n", "file_path": "src/session.rs", "rank": 82, "score": 2.053409016219664 }, { "content": " /// Start a DELETE request.\n\n ///\n\n /// See [request](#method.request) for an explanation of the parameters.\n\n #[inline]\n\n #[deprecated(since = \"0.2.3\", note = \"Use request\")]\n\n pub fn start_delete<Srv, I>(\n\n &self,\n\n service: Srv,\n\n path: I,\n\n api_version: Option<ApiVersion>,\n\n ) -> impl Future<Item = RequestBuilder, Error = Error> + Send\n\n where\n\n Srv: ServiceType + Send + Clone,\n\n I: IntoIterator,\n\n I::Item: AsRef<str>,\n\n I::IntoIter: Send,\n\n {\n\n self.request(service, Method::DELETE, path, api_version)\n\n }\n\n\n", "file_path": "src/session.rs", "rank": 83, "score": 2.053409016219664 }, { "content": " ) -> Result<T>\n\n where\n\n Srv: ServiceType + Send + Clone,\n\n I: IntoIterator,\n\n I::Item: AsRef<str>,\n\n I::IntoIter: Send,\n\n T: DeserializeOwned + Send,\n\n {\n\n self.fetch_json(self.request(service, Method::GET, path, api_version)?)\n\n }\n\n\n\n /// Fetch a JSON using the GET request with a query.\n\n ///\n\n /// See `reqwest` crate documentation for how to define a query.\n\n /// See [request](#method.request) for an explanation of the parameters.\n\n #[inline]\n\n pub fn get_json_query<Srv, I, Q, T>(\n\n &self,\n\n service: Srv,\n\n path: I,\n", "file_path": "src/sync.rs", "rank": 84, "score": 2.0179918426934527 }, { "content": " }\n\n\n\n /// Convert this session into one using the given endpoint interface.\n\n #[inline]\n\n pub fn with_endpoint_interface<S>(mut self, endpoint_interface: S) -> SyncSession\n\n where\n\n S: Into<String>,\n\n {\n\n self.set_endpoint_interface(endpoint_interface);\n\n self\n\n }\n\n\n\n /// Get minimum/maximum API (micro)version information.\n\n ///\n\n /// Returns `None` if the range cannot be determined, which usually means\n\n /// that microversioning is not supported.\n\n ///\n\n /// ```rust,no_run\n\n /// let session = osauth::sync::SyncSession::new(\n\n /// osauth::from_env().expect(\"Failed to create an identity provider from the environment\")\n", "file_path": "src/sync.rs", "rank": 85, "score": 2.0179918426934527 }, { "content": " #[inline]\n\n pub fn with_auth_type<Auth: AuthType + 'static>(mut self, auth_method: Auth) -> Session {\n\n self.set_auth_type(auth_method);\n\n self\n\n }\n\n\n\n /// Convert this session into one using the given endpoint interface.\n\n #[inline]\n\n pub fn with_endpoint_interface<S>(mut self, endpoint_interface: S) -> Session\n\n where\n\n S: Into<String>,\n\n {\n\n self.set_endpoint_interface(endpoint_interface);\n\n self\n\n }\n\n\n\n /// Get minimum/maximum API (micro)version information.\n\n ///\n\n /// Returns `None` if the range cannot be determined, which usually means\n\n /// that microversioning is not supported.\n", "file_path": "src/session.rs", "rank": 86, "score": 2.0007374948079875 }, { "content": " I: IntoIterator,\n\n I::Item: AsRef<str>,\n\n I::IntoIter: Send,\n\n T: DeserializeOwned + Send,\n\n {\n\n self.request(service, Method::GET, path, api_version)\n\n .then(request::fetch_json)\n\n }\n\n\n\n /// Fetch a JSON using the GET request with a query.\n\n ///\n\n /// See `reqwest` crate documentation for how to define a query.\n\n /// See [request](#method.request) for an explanation of the parameters.\n\n #[inline]\n\n pub fn get_json_query<Srv, I, Q, T>(\n\n &self,\n\n service: Srv,\n\n path: I,\n\n query: Q,\n\n api_version: Option<ApiVersion>,\n", "file_path": "src/session.rs", "rank": 87, "score": 2.0007374948079875 }, { "content": " }\n\n } else {\n\n future::Either::A(future::err(e))\n\n }\n\n })\n\n .and_then(|root| ServiceInfo::from_root(root, service))\n\n .or_else(move |e| {\n\n if e.kind() == ErrorKind::EndpointNotFound {\n\n debug!(\n\n \"Service returned EndpointNotFound when attempting version discovery, using {}\",\n\n fallback.root_url\n\n );\n\n future::Either::B(future::ok(fallback))\n\n } else {\n\n future::Either::A(future::err(e))\n\n }\n\n })\n\n .map(move |mut info| {\n\n // Older Nova returns insecure URLs even for secure protocol.\n\n if secure && info.root_url.scheme() == \"http\" {\n", "file_path": "src/protocol.rs", "rank": 88, "score": 1.9837757036877237 }, { "content": " pub fn fetch<Srv: ServiceType>(\n\n service: Srv,\n\n endpoint: Url,\n\n auth: Arc<dyn AuthType>,\n\n ) -> impl Future<Item = ServiceInfo, Error = Error> {\n\n let fallback = ServiceInfo {\n\n root_url: endpoint.clone(),\n\n major_version: None,\n\n current_version: None,\n\n minimum_version: None,\n\n };\n\n\n\n if !service.version_discovery_supported() {\n\n debug!(\n\n \"Service {} does not support version discovery, using {}\",\n\n service.catalog_type(),\n\n endpoint\n\n );\n\n return future::Either::A(future::ok(fallback));\n\n }\n", "file_path": "src/protocol.rs", "rank": 89, "score": 1.9837757036877237 }, { "content": " /// println!(\"The compute service does not support microversioning\");\n\n /// }\n\n /// });\n\n /// ```\n\n pub fn get_api_versions(\n\n &self,\n\n ) -> impl Future<Item = Option<(ApiVersion, ApiVersion)>, Error = Error> + Send {\n\n self.inner.get_api_versions(self.service.clone())\n\n }\n\n\n\n /// Construct an endpoint from the path;\n\n ///\n\n /// You won't need to use this call most of the time, since all request calls can fetch the\n\n /// endpoint automatically.\n\n pub fn get_endpoint<I>(&self, path: I) -> impl Future<Item = Url, Error = Error> + Send\n\n where\n\n I: IntoIterator,\n\n I::Item: AsRef<str>,\n\n I::IntoIter: Send,\n\n {\n", "file_path": "src/adapter.rs", "rank": 90, "score": 1.9507005252268317 }, { "content": " ///\n\n /// let session = osauth::sync::SyncSession::new(\n\n /// osauth::from_env().expect(\"Failed to create an identity provider from the environment\")\n\n /// );\n\n /// session\n\n /// .request(osauth::services::COMPUTE, Method::HEAD, &[\"servers\", \"1234\"], None)\n\n /// .and_then(|builder| session.send_checked(builder))\n\n /// .map(|response| {\n\n /// println!(\"Response: {:?}\", response);\n\n /// });\n\n /// ```\n\n ///\n\n /// This is the most generic call to make a request. You may prefer to use more specific `get`,\n\n /// `post`, `put` or `delete` calls instead.\n\n pub fn request<Srv, I>(\n\n &self,\n\n service: Srv,\n\n method: Method,\n\n path: I,\n\n api_version: Option<ApiVersion>,\n", "file_path": "src/sync.rs", "rank": 91, "score": 1.9507005252268317 }, { "content": " }\n\n}\n\n\n\nimpl<Srv: ServiceType + Send + Clone> Adapter<Srv> {\n\n /// Get minimum/maximum API (micro)version information.\n\n ///\n\n /// Returns `None` if the range cannot be determined, which usually means\n\n /// that microversioning is not supported.\n\n ///\n\n /// ```rust,no_run\n\n /// use futures::Future;\n\n ///\n\n /// let adapter = osauth::Adapter::from_env(osauth::services::COMPUTE)\n\n /// .expect(\"Failed to create an identity provider from the environment\");\n\n /// let future = adapter\n\n /// .get_api_versions()\n\n /// .map(|maybe_versions| {\n\n /// if let Some((min, max)) = maybe_versions {\n\n /// println!(\"The compute service supports versions {} to {}\", min, max);\n\n /// } else {\n", "file_path": "src/adapter.rs", "rank": 92, "score": 1.9345731095304868 }, { "content": " I::IntoIter: Send,\n\n T: Serialize + Send,\n\n R: DeserializeOwned + Send,\n\n {\n\n self.request(service, Method::POST, path, api_version)\n\n .map(move |builder| builder.json(&body))\n\n .then(request::fetch_json)\n\n }\n\n\n\n /// Start a PUT request.\n\n ///\n\n /// See [request](#method.request) for an explanation of the parameters.\n\n #[inline]\n\n #[deprecated(since = \"0.2.3\", note = \"Use request\")]\n\n pub fn start_put<Srv, I>(\n\n &self,\n\n service: Srv,\n\n path: I,\n\n api_version: Option<ApiVersion>,\n\n ) -> impl Future<Item = RequestBuilder, Error = Error> + Send\n", "file_path": "src/session.rs", "rank": 93, "score": 1.9345731095304868 }, { "content": " self.start_get(path, api_version).then(request::fetch_json)\n\n }\n\n\n\n /// Fetch a JSON using the GET request with a query.\n\n ///\n\n /// See `reqwest` crate documentation for how to define a query.\n\n /// See [request](#method.request) for an explanation of the parameters.\n\n #[inline]\n\n pub fn get_json_query<I, Q, T>(\n\n &self,\n\n path: I,\n\n query: Q,\n\n api_version: Option<ApiVersion>,\n\n ) -> impl Future<Item = T, Error = Error> + Send\n\n where\n\n I: IntoIterator,\n\n I::Item: AsRef<str>,\n\n I::IntoIter: Send,\n\n Q: Serialize + Send,\n\n T: DeserializeOwned + Send,\n", "file_path": "src/adapter.rs", "rank": 94, "score": 1.91871017404782 }, { "content": "// NOTE: we do not use generic deny(warnings) to avoid breakages with new\n\n// versions of the compiler. Add more warnings here as you discover them.\n\n// Taken from https://github.com/rust-unofficial/patterns/\n\n#![deny(\n\n bare_trait_objects,\n\n const_err,\n\n dead_code,\n\n improper_ctypes,\n\n legacy_directory_ownership,\n\n missing_copy_implementations,\n\n missing_debug_implementations,\n\n missing_docs,\n\n non_shorthand_field_patterns,\n\n no_mangle_generic_items,\n\n overflowing_literals,\n\n path_statements,\n\n patterns_in_fns_without_body,\n\n plugin_as_library,\n\n private_in_public,\n\n safe_extern_statics,\n", "file_path": "src/lib.rs", "rank": 95, "score": 1.91871017404782 }, { "content": "// Copyright 2019 Dmitry Tantsur <divius.inside@gmail.com>\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nextern crate env_logger;\n\nextern crate osauth;\n\n\n", "file_path": "examples/sync-compute-versions.rs", "rank": 96, "score": 1.91871017404782 }, { "content": " /// This is the most generic call to make a request. You may prefer to use more specific `get`,\n\n /// `post`, `put` or `delete` calls instead.\n\n pub fn request<Srv, I>(\n\n &self,\n\n service: Srv,\n\n method: Method,\n\n path: I,\n\n api_version: Option<ApiVersion>,\n\n ) -> impl Future<Item = RequestBuilder, Error = Error> + Send\n\n where\n\n Srv: ServiceType + Send + Clone,\n\n I: IntoIterator,\n\n I::Item: AsRef<str>,\n\n I::IntoIter: Send,\n\n {\n\n let auth = Arc::clone(&self.auth);\n\n self.get_endpoint(service.clone(), path)\n\n .and_then(move |url| {\n\n trace!(\n\n \"Sending HTTP {} request to {} with API version {:?}\",\n", "file_path": "src/session.rs", "rank": 97, "score": 1.9031052657101823 }, { "content": " if let Some(status) = value.status() {\n\n error.with_status(status)\n\n } else {\n\n error\n\n }\n\n }\n\n}\n\n\n\nimpl From<UrlError> for Error {\n\n fn from(value: UrlError) -> Error {\n\n Error::new(ErrorKind::InvalidInput, value.to_string())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub mod test {\n\n use super::{Error, ErrorKind};\n\n\n\n #[test]\n\n fn test_error_display() {\n\n let error = Error::new(ErrorKind::InvalidInput, \"boom\");\n\n assert_eq!(error.kind(), ErrorKind::InvalidInput);\n\n let s = format!(\"{}\", error);\n\n assert_eq!(&s, \"Input value(s) are invalid or missing: boom\");\n\n }\n\n}\n", "file_path": "src/error.rs", "rank": 98, "score": 1.9031052657101823 }, { "content": " ///\n\n /// ```rust,no_run\n\n /// use futures::Future;\n\n ///\n\n /// let session =\n\n /// osauth::from_env().expect(\"Failed to create an identity provider from the environment\");\n\n /// let future = session\n\n /// .get_api_versions(osauth::services::COMPUTE)\n\n /// .map(|maybe_versions| {\n\n /// if let Some((min, max)) = maybe_versions {\n\n /// println!(\"The compute service supports versions {} to {}\", min, max);\n\n /// } else {\n\n /// println!(\"The compute service does not support microversioning\");\n\n /// }\n\n /// });\n\n /// ```\n\n pub fn get_api_versions<Srv: ServiceType + Send>(\n\n &self,\n\n service: Srv,\n\n ) -> impl Future<Item = Option<(ApiVersion, ApiVersion)>, Error = Error> + Send {\n", "file_path": "src/session.rs", "rank": 99, "score": 1.8877521396870631 } ]
Rust
src/query/iter/iter.rs
LechintanTudor/sparsey
024d4e7997172d6144f7ae59a255b20694ef3fa9
use crate::query::iter::{DenseIter, SparseIter}; use crate::query::{self, EntityIterator, Query}; use crate::storage::Entity; pub enum Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { Sparse(SparseIter<'a, G, I, E>), Dense(DenseIter<'a, G>), } impl<'a, G, I, E> Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { pub(crate) fn new(get: G, include: I, exclude: E) -> Self { let get_info = get.group_info(); let include_info = include.group_info(); let exclude_info = exclude.group_info(); match query::group_range(get_info, include_info, exclude_info) { Some(range) => { let (entities, components) = get.split_dense(); unsafe { let components = G::offset_component_ptrs(components, range.start as isize); let entities = &entities .unwrap_or_else(|| { include.into_any_entities().expect("Cannot iterate empty Query") }) .get_unchecked(range); Self::Dense(DenseIter::new(entities, components)) } } None => { let (get_entities, sparse, components) = get.split_sparse(); let (sparse_entities, include) = include.split_filter(); let (_, exclude) = exclude.split_filter(); let entities = match (get_entities, sparse_entities) { (Some(e1), Some(e2)) => { if e1.len() <= e2.len() { e1 } else { e2 } } (Some(e1), None) => e1, (None, Some(e2)) => e2, (None, None) => panic!("Cannot iterate empty Query"), }; unsafe { Self::Sparse(SparseIter::new(entities, sparse, include, exclude, components)) } } } } pub fn is_sparse(&self) -> bool { matches!(self, Self::Sparse(_)) } pub fn is_dense(&self) -> bool { matches!(self, Self::Dense(_)) } } impl<'a, G, I, E> Iterator for Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { type Item = G::Item; fn next(&mut self) -> Option<Self::Item> { match self { Self::Sparse(sparse) => sparse.next(), Self::Dense(dense) => dense.next(), } } fn fold<B, F>(self, init: B, f: F) -> B where Self: Sized, F: FnMut(B, Self::Item) -> B, { match self { Self::Sparse(sparse) => sparse.fold(init, f), Self::Dense(dense) => dense.fold(init, f), } } } impl<'a, G, I, E> EntityIterator for Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { fn next_with_entity(&mut self) -> Option<(Entity, Self::Item)> { match self { Self::Sparse(sparse) => sparse.next_with_entity(), Self::Dense(dense) => dense.next_with_entity(), } } fn fold_with_entity<B, F>(self, init: B, f: F) -> B where Self: Sized, F: FnMut(B, (Entity, Self::Item)) -> B, { match self { Self::Sparse(sparse) => sparse.fold_with_entity(init, f), Self::Dense(dense) => dense.fold_with_entity(init, f), } } }
use crate::query::iter::{DenseIter, SparseIter}; use crate::query::{self, EntityIterator, Query}; use crate::storage::Entity; pub enum Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { Sparse(SparseIter<'a, G, I, E>), Dense(DenseIter<'a, G>), } impl<'a, G, I, E> Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { pub(crate) fn new(get: G, include: I, exclude: E) -> Self { let get_info = get.group_info(); let include_info = include.group_info(); let exclude_info = exclude.group_info(); match query::group_range(get_info, include_info, exclude_info) { Some(range) => { let (entities, components) = get.split_dense(); unsafe { let components = G::offset_component_ptrs(components, range.start as isize); let entities = &entities .unwrap_or_else(|| { include.into_any_entities().expect("Cannot iterate empty Query") }) .get_unchecked(range); Self::Dense(DenseIter::new(entities, components)) } } None => { let (get_entities, sparse, components) = get.split_sparse(); let (sparse_entities, include) = include.split_filter(); let (_, exclude) = exclude.split_filter(); let entities =
; unsafe { Self::Sparse(SparseIter::new(entities, sparse, include, exclude, components)) } } } } pub fn is_sparse(&self) -> bool { matches!(self, Self::Sparse(_)) } pub fn is_dense(&self) -> bool { matches!(self, Self::Dense(_)) } } impl<'a, G, I, E> Iterator for Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { type Item = G::Item; fn next(&mut self) -> Option<Self::Item> { match self { Self::Sparse(sparse) => sparse.next(), Self::Dense(dense) => dense.next(), } } fn fold<B, F>(self, init: B, f: F) -> B where Self: Sized, F: FnMut(B, Self::Item) -> B, { match self { Self::Sparse(sparse) => sparse.fold(init, f), Self::Dense(dense) => dense.fold(init, f), } } } impl<'a, G, I, E> EntityIterator for Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { fn next_with_entity(&mut self) -> Option<(Entity, Self::Item)> { match self { Self::Sparse(sparse) => sparse.next_with_entity(), Self::Dense(dense) => dense.next_with_entity(), } } fn fold_with_entity<B, F>(self, init: B, f: F) -> B where Self: Sized, F: FnMut(B, (Entity, Self::Item)) -> B, { match self { Self::Sparse(sparse) => sparse.fold_with_entity(init, f), Self::Dense(dense) => dense.fold_with_entity(init, f), } } }
match (get_entities, sparse_entities) { (Some(e1), Some(e2)) => { if e1.len() <= e2.len() { e1 } else { e2 } } (Some(e1), None) => e1, (None, Some(e2)) => e2, (None, None) => panic!("Cannot iterate empty Query"), }
if_condition
[ { "content": "#[doc(hidden)]\n\npub trait EntityIterator: Iterator {\n\n fn next_with_entity(&mut self) -> Option<(Entity, Self::Item)>;\n\n\n\n fn fold_with_entity<B, F>(mut self, mut init: B, mut f: F) -> B\n\n where\n\n Self: Sized,\n\n F: FnMut(B, (Entity, Self::Item)) -> B,\n\n {\n\n while let Some(item) = self.next_with_entity() {\n\n init = f(init, item);\n\n }\n\n\n\n init\n\n }\n\n}\n\n\n\n/// Wrapper over a compoennt iterator that makes it also return the `Entity` to which the components\n\n/// belong.\n\npub struct EntityIter<I>(I);\n\n\n", "file_path": "src/query/iter/entities.rs", "rank": 0, "score": 153469.6580172527 }, { "content": "/// Helper trait for creating an `EntityIter`.\n\npub trait IntoEntityIter: EntityIterator + Sized {\n\n /// Makes the iterator also return the `Entity` to which the components belong.\n\n fn with_entity(self) -> EntityIter<Self>;\n\n}\n\n\n\nimpl<I> IntoEntityIter for I\n\nwhere\n\n I: EntityIterator,\n\n{\n\n fn with_entity(self) -> EntityIter<Self> {\n\n EntityIter(self)\n\n }\n\n}\n", "file_path": "src/query/iter/entities.rs", "rank": 1, "score": 149955.16463561385 }, { "content": "fn empty_page() -> EntityPage {\n\n Some(Box::new([None; PAGE_SIZE]))\n\n}\n", "file_path": "src/storage/sparse_array.rs", "rank": 2, "score": 103217.06237941103 }, { "content": "impl<I> Iterator for EntityIter<I>\n\nwhere\n\n I: EntityIterator,\n\n{\n\n type Item = (Entity, I::Item);\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n self.0.next_with_entity()\n\n }\n\n\n\n fn fold<B, F>(self, init: B, f: F) -> B\n\n where\n\n Self: Sized,\n\n F: FnMut(B, Self::Item) -> B,\n\n {\n\n self.0.fold_with_entity(init, f)\n\n }\n\n}\n\n\n", "file_path": "src/query/iter/entities.rs", "rank": 3, "score": 96471.05820423024 }, { "content": "use crate::storage::Entity;\n\n\n\n#[doc(hidden)]\n", "file_path": "src/query/iter/entities.rs", "rank": 4, "score": 96464.17511523854 }, { "content": "fn main() {\n\n let mut schedule =\n\n Schedule::builder().add_system(update_velocity).add_system(update_position).build();\n\n\n\n let mut world = World::default();\n\n schedule.set_up(&mut world);\n\n\n\n world.create((Position(0, 0), Velocity(1, 1)));\n\n world.create((Position(0, 0), Velocity(2, 2)));\n\n world.create((Position(0, 0), Velocity(3, 3), Frozen));\n\n\n\n let mut resources = Resources::default();\n\n\n\n for _ in 0..3 {\n\n schedule.run_seq(&mut world, &mut resources);\n\n }\n\n}\n", "file_path": "examples/components.rs", "rank": 5, "score": 88314.641843822 }, { "content": "#[doc(hidden)]\n\npub trait IntoCompoundQueryParts<'a> {\n\n type Get: Query<'a>;\n\n type Include: Query<'a> + Copy;\n\n type Exclude: Query<'a> + Copy;\n\n\n\n fn into_compound_query_parts(self) -> (Self::Get, Self::Include, Self::Exclude);\n\n}\n\n\n", "file_path": "src/query/compound_query.rs", "rank": 6, "score": 88097.2921662347 }, { "content": "#[test]\n\nfn test_sparse() {\n\n let mut world = World::default();\n\n world.register::<A>();\n\n world.register::<B>();\n\n world.register::<C>();\n\n world.register::<D>();\n\n\n\n let e0 = world.create((A(0), B(0)));\n\n let e1 = world.create((A(1), B(1), C(1)));\n\n let e2 = world.create((A(2), B(2), C(2), D(2)));\n\n\n\n let a = world.borrow::<A>();\n\n let b = world.borrow::<B>();\n\n let c = world.borrow::<C>();\n\n let d = world.borrow::<D>();\n\n\n\n let i = (&a, &b).iter();\n\n assert!(i.is_sparse());\n\n let e = i.with_entity().map(|(e, _)| e).collect::<HashSet<_>>();\n\n assert_eq!(e, HashSet::from_iter([e0, e1, e2]));\n", "file_path": "tests/iterators.rs", "rank": 7, "score": 86825.86151521294 }, { "content": "#[test]\n\nfn test_dense() {\n\n let layout = Layout::builder()\n\n .add_group(<(A, B)>::group())\n\n .add_group(<(A, B, C)>::group())\n\n .add_group(<(A, B, C, D)>::group())\n\n .build();\n\n\n\n let mut world = World::with_layout(&layout);\n\n let e0 = world.create((A(0), B(0)));\n\n let e1 = world.create((A(1), B(1), C(1)));\n\n let e2 = world.create((A(2), B(2), C(2), D(2)));\n\n\n\n let a = world.borrow::<A>();\n\n let b = world.borrow::<B>();\n\n let c = world.borrow::<C>();\n\n let d = world.borrow::<D>();\n\n\n\n let i = (&a, &b).iter();\n\n assert!(i.is_dense());\n\n let e = i.with_entity().map(|(e, _)| e).collect::<HashSet<_>>();\n", "file_path": "tests/iterators.rs", "rank": 8, "score": 86825.86151521294 }, { "content": "#[test]\n\nfn test_entities() {\n\n let mut world = World::default();\n\n\n\n // Create\n\n let e0 = world.create(());\n\n assert!(world.contains(e0));\n\n assert_eq!(world.entities(), &[e0]);\n\n\n\n // Destroy\n\n assert!(world.destroy(e0));\n\n assert!(!world.destroy(e0));\n\n assert!(!world.contains(e0));\n\n assert_eq!(world.entities(), &[]);\n\n\n\n // Clear\n\n let e0 = world.create(());\n\n let e1 = world.create(());\n\n world.clear();\n\n assert!(!world.contains(e0));\n\n assert!(!world.contains(e1));\n\n assert_eq!(world.entities(), &[]);\n\n}\n\n\n", "file_path": "tests/world.rs", "rank": 9, "score": 86806.68943650788 }, { "content": "#[derive(Clone, Copy, Eq, PartialEq, Debug)]\n\nenum GroupStatus {\n\n /// The storages are missing components.\n\n Incomplete,\n\n /// The storages contains all components but they are not grouped.\n\n Ungrouped,\n\n /// The storages contains all components and they are grouped.\n\n Grouped,\n\n}\n\n\n\n/// # Safety\n\n/// The group family and the storages must be valid.\n\n#[inline]\n\npub(crate) unsafe fn group_family(\n\n storages: &mut [AtomicRefCell<ComponentStorage>],\n\n groups: &mut [Group],\n\n family_range: Range<usize>,\n\n entity: Entity,\n\n) {\n\n for i in family_range {\n\n let group = groups.get_unchecked_mut(i);\n", "file_path": "src/components/group.rs", "rank": 10, "score": 86332.9840356596 }, { "content": "#[test]\n\nfn test_components() {\n\n let mut world = World::default();\n\n world.register::<A>();\n\n world.register::<B>();\n\n world.register::<C>();\n\n\n\n // Create\n\n let e0 = world.create((A(0), B(0)));\n\n\n\n {\n\n let a = world.borrow::<A>();\n\n let b = world.borrow::<B>();\n\n\n\n assert_eq!(a.get(e0).copied(), Some(A(0)));\n\n assert_eq!(b.get(e0).copied(), Some(B(0)));\n\n }\n\n\n\n // Insert\n\n assert!(world.insert(e0, (C(0),)));\n\n\n", "file_path": "tests/world.rs", "rank": 11, "score": 85447.40313479361 }, { "content": "/// Helper trait for applying \"include\" and \"exclude\" filters to queries.\n\npub trait QueryFilters<'a>: Query<'a> + Sized {\n\n /// Applies an \"include\" filter to the query.\n\n fn include<I>(self, include: I) -> Include<Self, I>\n\n where\n\n I: Query<'a> + Copy;\n\n\n\n /// Applies an \"exclude\" filter to the query.\n\n fn exclude<E>(self, exclude: E) -> IncludeExclude<Self, (), E>\n\n where\n\n E: Query<'a> + Copy;\n\n}\n\n\n\nimpl<'a, Q> QueryFilters<'a> for Q\n\nwhere\n\n Q: Query<'a>,\n\n{\n\n fn include<I>(self, include: I) -> Include<Self, I>\n\n where\n\n I: Query<'a> + Copy,\n\n {\n", "file_path": "src/query/compound_query.rs", "rank": 12, "score": 85230.27357603355 }, { "content": "fn get_as_ptr_with_masks<T>(\n\n storages: &ComponentStorages,\n\n) -> (*mut ComponentStorage, FamilyMask, GroupMask)\n\nwhere\n\n T: Component,\n\n{\n\n let (storage, family_mask, group_mask) = storages\n\n .get_as_ptr_with_masks(&TypeId::of::<T>())\n\n .unwrap_or_else(|| panic_missing_comp::<T>());\n\n\n\n (storage.as_ptr(), family_mask, group_mask)\n\n}\n\n\n\n#[rustfmt::skip]\n\nmod impls {\n\n use super::*;\n\n\n\n impl_component_set!((A, 0));\n\n impl_component_set!((A, 0), (B, 1));\n\n impl_component_set!((A, 0), (B, 1), (C, 2));\n", "file_path": "src/components/component_set.rs", "rank": 13, "score": 83104.88874902244 }, { "content": "/// Trait used for fetching and iterating entities and components from component views.\n\npub trait CompoundQuery<'a>: IntoCompoundQueryParts<'a> + Sized {\n\n /// Returns the component set associated to `entity`.\n\n fn get(self, entity: Entity) -> Option<<Self::Get as Query<'a>>::Item>;\n\n\n\n /// Returns `true` if `entity` matches the query.\n\n fn contains(self, entity: Entity) -> bool;\n\n\n\n /// Returns an iterator over all items in the query.\n\n fn iter(self) -> Iter<'a, Self::Get, Self::Include, Self::Exclude>;\n\n\n\n /// Iterates over all items in the query. Equivalent to `.iter().for_each(|item| f(item))`.\n\n fn for_each<F>(self, f: F)\n\n where\n\n F: FnMut(<Self::Get as Query<'a>>::Item),\n\n {\n\n self.iter().for_each(f)\n\n }\n\n\n\n /// Iterates over all items in the query and the entities to which they belong. Equivalent to\n\n /// `.iter().with_entity().for_each(|(entity, item)| f((entity, item)))`.\n", "file_path": "src/query/compound_query.rs", "rank": 14, "score": 82214.90775734105 }, { "content": "fn get_as_ptr_with_family_mask<T>(\n\n storages: &ComponentStorages,\n\n) -> (*mut ComponentStorage, FamilyMask)\n\nwhere\n\n T: Component,\n\n{\n\n let (storage, family_mask) = storages\n\n .get_as_ptr_with_family_mask(&TypeId::of::<T>())\n\n .unwrap_or_else(|| panic_missing_comp::<T>());\n\n\n\n (storage.as_ptr(), family_mask)\n\n}\n\n\n", "file_path": "src/components/component_set.rs", "rank": 15, "score": 81259.368015213 }, { "content": "/// Trait automatically implemented for all types that can be used as components. (Any `Send + Sync\n\n/// + 'static` type)\n\npub trait Component: Send + Sync + 'static {\n\n // Empty\n\n}\n\n\n\nimpl<T> Component for T\n\nwhere\n\n T: Send + Sync + 'static,\n\n{\n\n // Empty\n\n}\n", "file_path": "src/storage/component.rs", "rank": 16, "score": 79971.38743025275 }, { "content": "fn local_index(entity: Entity) -> usize {\n\n entity.sparse() % PAGE_SIZE\n\n}\n\n\n", "file_path": "src/storage/sparse_array.rs", "rank": 17, "score": 79537.22648591847 }, { "content": "fn page_index(entity: Entity) -> usize {\n\n entity.sparse() / PAGE_SIZE\n\n}\n\n\n", "file_path": "src/storage/sparse_array.rs", "rank": 18, "score": 79537.22648591847 }, { "content": "/// Helper trait for creating a local function from a function.\n\npub trait IntoLocalFn {\n\n /// Creates a local function.\n\n fn local_fn(self) -> LocalFn;\n\n}\n\n\n\nimpl<F> IntoLocalFn for F\n\nwhere\n\n F: FnMut(&mut World, &mut Resources) + 'static,\n\n{\n\n fn local_fn(self) -> LocalFn {\n\n LocalFn(Box::new(self))\n\n }\n\n}\n\n\n\nimpl IntoLocalFn for LocalFn {\n\n fn local_fn(self) -> LocalFn {\n\n self\n\n }\n\n}\n", "file_path": "src/systems/local/function.rs", "rank": 19, "score": 78930.90257225778 }, { "content": "fn uninit_page() -> EntityPage {\n\n None\n\n}\n\n\n", "file_path": "src/storage/sparse_array.rs", "rank": 20, "score": 75094.13951576062 }, { "content": "#[inline]\n\nfn array_layout<U>(n: usize) -> Layout {\n\n Layout::array::<U>(n).unwrap()\n\n}\n", "file_path": "src/storage/component_storage.rs", "rank": 28, "score": 67513.80814456055 }, { "content": " G: Query<'a>,\n\n I: Query<'a>,\n\n E: Query<'a>,\n\n{\n\n pub(crate) unsafe fn new(\n\n entities: &'a [Entity],\n\n sparse: G::SparseArrays,\n\n include: I::SparseArrays,\n\n exclude: E::SparseArrays,\n\n components: G::ComponentPtrs,\n\n ) -> Self {\n\n Self { entities: entities.iter(), sparse, include, exclude, components }\n\n }\n\n}\n\n\n\nimpl<'a, G, I, E> Iterator for SparseIter<'a, G, I, E>\n\nwhere\n\n G: Query<'a>,\n\n I: Query<'a>,\n\n E: Query<'a>,\n", "file_path": "src/query/iter/sparse.rs", "rank": 29, "score": 64035.52056887289 }, { "content": " F: FnMut(B, Self::Item) -> B,\n\n {\n\n for &entity in self.entities {\n\n if E::excludes_split(self.exclude, entity) && I::includes_split(self.include, entity) {\n\n if let Some(index) = G::get_index_from_split(self.sparse, entity) {\n\n unsafe {\n\n init = f(init, G::get_from_sparse_components(self.components, index));\n\n }\n\n }\n\n }\n\n }\n\n\n\n init\n\n }\n\n}\n\n\n\nimpl<'a, G, I, E> EntityIterator for SparseIter<'a, G, I, E>\n\nwhere\n\n G: Query<'a>,\n\n I: Query<'a>,\n", "file_path": "src/query/iter/sparse.rs", "rank": 30, "score": 64032.30010623106 }, { "content": "use crate::query::{EntityIterator, Query};\n\nuse crate::storage::Entity;\n\nuse std::slice::Iter as SliceIter;\n\n\n\n/// Iterator over ungrouped storages.\n\npub struct SparseIter<'a, G, I, E>\n\nwhere\n\n G: Query<'a>,\n\n I: Query<'a>,\n\n E: Query<'a>,\n\n{\n\n entities: SliceIter<'a, Entity>,\n\n sparse: G::SparseArrays,\n\n include: I::SparseArrays,\n\n exclude: E::SparseArrays,\n\n components: G::ComponentPtrs,\n\n}\n\n\n\nimpl<'a, G, I, E> SparseIter<'a, G, I, E>\n\nwhere\n", "file_path": "src/query/iter/sparse.rs", "rank": 31, "score": 64031.07093985635 }, { "content": "use crate::query::{EntityIterator, Query};\n\nuse crate::storage::Entity;\n\n\n\n/// Iterator over grouped storages. Extremely fast.\n\npub struct DenseIter<'a, G>\n\nwhere\n\n G: Query<'a>,\n\n{\n\n index: usize,\n\n entities: &'a [Entity],\n\n components: G::ComponentPtrs,\n\n}\n\n\n\nimpl<'a, G> DenseIter<'a, G>\n\nwhere\n\n G: Query<'a>,\n\n{\n\n pub(crate) unsafe fn new(entities: &'a [Entity], components: G::ComponentPtrs) -> Self {\n\n Self { index: 0, entities, components }\n\n }\n", "file_path": "src/query/iter/dense.rs", "rank": 32, "score": 64029.52151141627 }, { "content": " where\n\n Self: Sized,\n\n F: FnMut(B, (Entity, Self::Item)) -> B,\n\n {\n\n for &entity in self.entities {\n\n if E::excludes_split(self.exclude, entity) && I::includes_split(self.include, entity) {\n\n if let Some(index) = G::get_index_from_split(self.sparse, entity) {\n\n unsafe {\n\n init = f(\n\n init,\n\n (entity, G::get_from_sparse_components(self.components, index)),\n\n );\n\n }\n\n }\n\n }\n\n }\n\n\n\n init\n\n }\n\n}\n", "file_path": "src/query/iter/sparse.rs", "rank": 33, "score": 64026.20954839604 }, { "content": " E: Query<'a>,\n\n{\n\n fn next_with_entity(&mut self) -> Option<(Entity, Self::Item)> {\n\n loop {\n\n let entity = *self.entities.next()?;\n\n\n\n if E::excludes_split(self.exclude, entity) && I::includes_split(self.include, entity) {\n\n if let Some(index) = G::get_index_from_split(self.sparse, entity) {\n\n unsafe {\n\n return Some((\n\n entity,\n\n G::get_from_sparse_components(self.components, index),\n\n ));\n\n }\n\n }\n\n }\n\n }\n\n }\n\n\n\n fn fold_with_entity<B, F>(self, mut init: B, mut f: F) -> B\n", "file_path": "src/query/iter/sparse.rs", "rank": 34, "score": 64024.724737812365 }, { "content": "}\n\n\n\nimpl<'a, G> Iterator for DenseIter<'a, G>\n\nwhere\n\n G: Query<'a>,\n\n{\n\n type Item = G::Item;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n let index = self.index;\n\n\n\n if index >= self.entities.len() {\n\n return None;\n\n }\n\n\n\n self.index += 1;\n\n\n\n unsafe { Some(G::get_from_dense_components(self.components, index)) }\n\n }\n\n\n", "file_path": "src/query/iter/dense.rs", "rank": 35, "score": 64022.819781038954 }, { "content": "{\n\n type Item = G::Item;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n loop {\n\n let entity = *self.entities.next()?;\n\n\n\n if E::excludes_split(self.exclude, entity) && I::includes_split(self.include, entity) {\n\n if let Some(index) = G::get_index_from_split(self.sparse, entity) {\n\n unsafe {\n\n return Some(G::get_from_sparse_components(self.components, index));\n\n }\n\n }\n\n }\n\n }\n\n }\n\n\n\n fn fold<B, F>(self, mut init: B, mut f: F) -> B\n\n where\n\n Self: Sized,\n", "file_path": "src/query/iter/sparse.rs", "rank": 36, "score": 64022.77842837052 }, { "content": " fn fold<B, F>(mut self, mut init: B, mut f: F) -> B\n\n where\n\n Self: Sized,\n\n F: FnMut(B, Self::Item) -> B,\n\n {\n\n while self.index < self.entities.len() {\n\n unsafe {\n\n init = f(init, G::get_from_dense_components(self.components, self.index));\n\n }\n\n\n\n self.index += 1;\n\n }\n\n\n\n init\n\n }\n\n}\n\n\n\nimpl<'a, G> EntityIterator for DenseIter<'a, G>\n\nwhere\n\n G: Query<'a>,\n", "file_path": "src/query/iter/dense.rs", "rank": 37, "score": 64021.80139200461 }, { "content": " Self: Sized,\n\n F: FnMut(B, (Entity, Self::Item)) -> B,\n\n {\n\n while self.index < self.entities.len() {\n\n unsafe {\n\n init = f(\n\n init,\n\n (\n\n *self.entities.get_unchecked(self.index),\n\n G::get_from_dense_components(self.components, self.index),\n\n ),\n\n );\n\n }\n\n\n\n self.index += 1;\n\n }\n\n\n\n init\n\n }\n\n}\n", "file_path": "src/query/iter/dense.rs", "rank": 38, "score": 64017.298406632886 }, { "content": "{\n\n fn next_with_entity(&mut self) -> Option<(Entity, Self::Item)> {\n\n let index = self.index;\n\n\n\n if index >= self.entities.len() {\n\n return None;\n\n }\n\n\n\n self.index += 1;\n\n\n\n unsafe {\n\n Some((\n\n *self.entities.get_unchecked(index),\n\n G::get_from_dense_components(self.components, index),\n\n ))\n\n }\n\n }\n\n\n\n fn fold_with_entity<B, F>(mut self, mut init: B, mut f: F) -> B\n\n where\n", "file_path": "src/query/iter/dense.rs", "rank": 39, "score": 64015.45983417686 }, { "content": "pub use self::dense::*;\n\npub use self::entities::*;\n\npub use self::iter::*;\n\npub use self::sparse::*;\n\n\n\nmod dense;\n\nmod entities;\n\nmod iter;\n\nmod sparse;\n", "file_path": "src/query/iter/mod.rs", "rank": 40, "score": 64014.87966241926 }, { "content": "/// Like `fetch_add`, but returns `None` on overflow instead of wrapping.\n\nfn atomic_increment_u32(value: &AtomicU32) -> Option<u32> {\n\n let mut prev = value.load(Ordering::Relaxed);\n\n\n\n while prev != u32::MAX {\n\n match value.compare_exchange_weak(prev, prev + 1, Ordering::Relaxed, Ordering::Relaxed) {\n\n Ok(prev) => return Some(prev),\n\n Err(next_prev) => prev = next_prev,\n\n }\n\n }\n\n\n\n None\n\n}\n", "file_path": "src/storage/entity_storage.rs", "rank": 41, "score": 63495.47615010888 }, { "content": "/// Like `fetch_sub`, but returns `None` on underflow instead of wrapping.\n\nfn atomic_decrement_usize(value: &AtomicUsize) -> Option<usize> {\n\n let mut prev = value.load(Ordering::Relaxed);\n\n\n\n while prev != 0 {\n\n match value.compare_exchange_weak(prev, prev - 1, Ordering::Relaxed, Ordering::Relaxed) {\n\n Ok(prev) => return Some(prev),\n\n Err(next_prev) => prev = next_prev,\n\n }\n\n }\n\n\n\n None\n\n}\n\n\n", "file_path": "src/storage/entity_storage.rs", "rank": 42, "score": 63495.47615010888 }, { "content": "use crate::components::GroupInfo;\n\nuse crate::storage::{Component, Entity, SparseArray};\n\nuse crate::world::{Comp, CompMut};\n\nuse std::ops::RangeBounds;\n\n\n\n#[doc(hidden)]\n\n#[allow(clippy::len_without_is_empty)]\n\npub unsafe trait ComponentView<'a> {\n\n type Item: 'a;\n\n type Component: Component;\n\n type ComponentSlice: 'a;\n\n\n\n fn len(&self) -> usize;\n\n\n\n fn group_info(&self) -> Option<GroupInfo<'a>>;\n\n\n\n fn get(self, entity: Entity) -> Option<Self::Item>;\n\n\n\n fn contains(self, entity: Entity) -> bool;\n\n\n", "file_path": "src/query/component_view.rs", "rank": 43, "score": 62639.20129388281 }, { "content": " fn split(self) -> (&'a [Entity], &'a SparseArray, *mut Self::Component);\n\n\n\n unsafe fn get_from_component_ptr(component: *mut Self::Component) -> Self::Item;\n\n\n\n unsafe fn get_entities_unchecked<R>(self, range: R) -> &'a [Entity]\n\n where\n\n R: RangeBounds<usize>;\n\n\n\n unsafe fn get_components_unchecked<R>(self, range: R) -> Self::ComponentSlice\n\n where\n\n R: RangeBounds<usize>;\n\n\n\n unsafe fn get_entities_components_unchecked<R>(\n\n self,\n\n range: R,\n\n ) -> (&'a [Entity], Self::ComponentSlice)\n\n where\n\n R: RangeBounds<usize>;\n\n}\n\n\n", "file_path": "src/query/component_view.rs", "rank": 44, "score": 62635.47498012373 }, { "content": " }\n\n\n\n fn contains(self, entity: Entity) -> bool {\n\n $ty::contains(self, entity)\n\n }\n\n\n\n fn split(self) -> (&'a [Entity], &'a SparseArray, *mut Self::Component) {\n\n let (entities, sparse, components) = $ty::split(self);\n\n (entities, sparse, components.as_ptr() as *mut _)\n\n }\n\n\n\n unsafe fn get_from_component_ptr(component: *mut Self::Component) -> Self::Item {\n\n &*component\n\n }\n\n\n\n unsafe fn get_entities_unchecked<R>(self, range: R) -> &'a [Entity]\n\n where\n\n R: RangeBounds<usize>,\n\n {\n\n let bounds = (range.start_bound().cloned(), range.end_bound().cloned());\n", "file_path": "src/query/component_view.rs", "rank": 45, "score": 62634.551707657505 }, { "content": "\n\n unsafe fn get_from_component_ptr(component: *mut Self::Component) -> Self::Item {\n\n &mut *component\n\n }\n\n\n\n unsafe fn get_entities_unchecked<R>(self, range: R) -> &'a [Entity]\n\n where\n\n R: RangeBounds<usize>,\n\n {\n\n let bounds = (range.start_bound().cloned(), range.end_bound().cloned());\n\n CompMut::entities(self).get_unchecked(bounds)\n\n }\n\n\n\n unsafe fn get_components_unchecked<R>(self, range: R) -> Self::ComponentSlice\n\n where\n\n R: RangeBounds<usize>,\n\n {\n\n let bounds = (range.start_bound().cloned(), range.end_bound().cloned());\n\n CompMut::components_mut(self).get_unchecked_mut(bounds)\n\n }\n", "file_path": "src/query/component_view.rs", "rank": 46, "score": 62633.29161656247 }, { "content": " $ty::entities(self).get_unchecked(bounds)\n\n }\n\n\n\n unsafe fn get_components_unchecked<R>(self, range: R) -> Self::ComponentSlice\n\n where\n\n R: RangeBounds<usize>,\n\n {\n\n let bounds = (range.start_bound().cloned(), range.end_bound().cloned());\n\n $ty::components(self).get_unchecked(bounds)\n\n }\n\n\n\n unsafe fn get_entities_components_unchecked<R>(\n\n self,\n\n range: R,\n\n ) -> (&'a [Entity], Self::ComponentSlice)\n\n where\n\n R: RangeBounds<usize>,\n\n {\n\n let bounds = (range.start_bound().cloned(), range.end_bound().cloned());\n\n\n", "file_path": "src/query/component_view.rs", "rank": 47, "score": 62632.692896881505 }, { "content": "\n\n unsafe fn get_entities_components_unchecked<R>(\n\n self,\n\n range: R,\n\n ) -> (&'a [Entity], Self::ComponentSlice)\n\n where\n\n R: RangeBounds<usize>,\n\n {\n\n let (entities, _, components) = CompMut::split_mut(self);\n\n let bounds = (range.start_bound().cloned(), range.end_bound().cloned());\n\n\n\n (entities.get_unchecked(bounds), components.get_unchecked_mut(bounds))\n\n }\n\n}\n", "file_path": "src/query/component_view.rs", "rank": 48, "score": 62632.31916913492 }, { "content": "macro_rules! impl_shared_component_view {\n\n ($ty:ident) => {\n\n unsafe impl<'a, T> ComponentView<'a> for &'a $ty<'a, T>\n\n where\n\n T: Component,\n\n {\n\n type Item = &'a T;\n\n type Component = T;\n\n type ComponentSlice = &'a [T];\n\n\n\n fn len(&self) -> usize {\n\n $ty::len(self)\n\n }\n\n\n\n fn group_info(&self) -> Option<GroupInfo<'a>> {\n\n $ty::group_info(self)\n\n }\n\n\n\n fn get(self, entity: Entity) -> Option<Self::Item> {\n\n $ty::get(self, entity)\n", "file_path": "src/query/component_view.rs", "rank": 49, "score": 62631.712322152955 }, { "content": " fn len(&self) -> usize {\n\n CompMut::len(self)\n\n }\n\n\n\n fn group_info(&self) -> Option<GroupInfo<'a>> {\n\n CompMut::group_info(self)\n\n }\n\n\n\n fn get(self, entity: Entity) -> Option<Self::Item> {\n\n CompMut::get_mut(self, entity)\n\n }\n\n\n\n fn contains(self, entity: Entity) -> bool {\n\n CompMut::contains(self, entity)\n\n }\n\n\n\n fn split(self) -> (&'a [Entity], &'a SparseArray, *mut Self::Component) {\n\n let (entities, sparse, components) = CompMut::split_mut(self);\n\n (entities, sparse, components.as_mut_ptr())\n\n }\n", "file_path": "src/query/component_view.rs", "rank": 50, "score": 62630.58349709836 }, { "content": " (\n\n $ty::entities(self).get_unchecked(bounds),\n\n $ty::components(self).get_unchecked(bounds),\n\n )\n\n }\n\n }\n\n };\n\n}\n\n\n\nimpl_shared_component_view!(Comp);\n\nimpl_shared_component_view!(CompMut);\n\n\n\nunsafe impl<'a, 'b, T> ComponentView<'a> for &'a mut CompMut<'b, T>\n\nwhere\n\n T: Component,\n\n{\n\n type Item = &'a mut T;\n\n type Component = T;\n\n type ComponentSlice = &'a mut [T];\n\n\n", "file_path": "src/query/component_view.rs", "rank": 51, "score": 62628.76351089652 }, { "content": "fn update_velocity(mut vel: CompMut<Velocity>, frz: Comp<Frozen>) {\n\n println!(\"[Update velocities]\");\n\n\n\n (&mut vel).include(&frz).for_each_with_entity(|(e, vel)| {\n\n println!(\"{:?} is frozen. Set its velocity to (0, 0)\", e);\n\n\n\n *vel = Velocity(0, 0);\n\n });\n\n\n\n println!();\n\n}\n\n\n", "file_path": "examples/components.rs", "rank": 52, "score": 59654.74588191147 }, { "content": "fn update_position(mut pos: CompMut<Position>, vel: Comp<Velocity>) {\n\n println!(\"[Update positions]\");\n\n\n\n (&mut pos, &vel).for_each_with_entity(|(e, (pos, vel))| {\n\n pos.0 += vel.0;\n\n pos.1 += vel.1;\n\n\n\n println!(\"{:?}, {:?}, {:?}\", e, *pos, vel);\n\n });\n\n\n\n println!();\n\n}\n\n\n", "file_path": "examples/components.rs", "rank": 53, "score": 59654.74588191147 }, { "content": "fn main() {\n\n let mut schedule = Schedule::builder()\n\n .add_system(raise_lava)\n\n .add_system(fall_in_lava)\n\n .add_local_fn(destroy_fallen_in_lava)\n\n .build();\n\n\n\n let mut world = World::default();\n\n schedule.set_up(&mut world);\n\n\n\n world.create((Position { y: 0 },));\n\n world.create((Position { y: 1 },));\n\n world.create((Position { y: 2 },));\n\n world.create((Position { y: 3 },));\n\n world.create((Position { y: 4 },));\n\n world.create((Position { y: 5 },));\n\n\n\n let mut resources = Resources::default();\n\n resources.insert(Lava { height: 0 });\n\n resources.insert(FallenInLava { entities: Vec::new() });\n\n\n\n for _ in 0..3 {\n\n schedule.run_seq(&mut world, &mut resources);\n\n }\n\n}\n", "file_path": "examples/resources.rs", "rank": 54, "score": 55813.21555645055 }, { "content": "fn main() {\n\n let mut schedule =\n\n Schedule::builder().add_system(update_health).add_system(update_movement).build();\n\n\n\n let mut world = World::default();\n\n schedule.set_up(&mut world);\n\n\n\n world.bulk_create((0..100).map(|i| (Position(0, 0), Velocity(i, i), Hp(100), HpRegen(i))));\n\n\n\n let mut resources = Resources::default();\n\n\n\n for _ in 0..5 {\n\n schedule.run(&mut world, &mut resources);\n\n }\n\n}\n", "file_path": "examples/parallelism.rs", "rank": 55, "score": 55813.21555645055 }, { "content": "fn main() {\n\n let mut schedule = Schedule::builder().add_system(print_sprites).build();\n\n\n\n let layout = Layout::builder()\n\n .add_group(<(Position, Sprite)>::group())\n\n .add_group(<(Position, Sprite, Transparent)>::group())\n\n .build();\n\n\n\n let mut world = World::with_layout(&layout);\n\n schedule.set_up(&mut world);\n\n\n\n world.create((Position(0, 0), Sprite { id: 0 }));\n\n world.create((Position(1, 1), Sprite { id: 1 }));\n\n world.create((Position(2, 2), Sprite { id: 2 }, Transparent));\n\n world.create((Position(3, 3), Sprite { id: 3 }, Transparent));\n\n\n\n let mut resources = Resources::default();\n\n\n\n schedule.run_seq(&mut world, &mut resources);\n\n}\n", "file_path": "examples/layout.rs", "rank": 56, "score": 55813.21555645055 }, { "content": "enum SimpleScheduleStep {\n\n System(System),\n\n LocalSystem(LocalSystem),\n\n LocalFn(LocalFn),\n\n Barrier,\n\n}\n\n\n\nimpl fmt::Debug for SimpleScheduleStep {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match self {\n\n Self::System(_) => write!(f, \"SimpleScheduleStep::System\"),\n\n Self::LocalSystem(_) => write!(f, \"SimpleScheduleStep::LocalSystem\"),\n\n Self::LocalFn(_) => write!(f, \"SimpleScheduleStep::LocalFn\"),\n\n Self::Barrier => write!(f, \"SimpleScheduleStep::Barrier\"),\n\n }\n\n }\n\n}\n\n\n\n/// Enables creating a `Schedule` using the builder pattern.\n\n#[derive(Default, Debug)]\n", "file_path": "src/systems/schedule.rs", "rank": 57, "score": 55265.53045477289 }, { "content": "#[test]\n\nfn test_register() {\n\n let mut world = World::default();\n\n\n\n assert!(!world.is_registered(&TypeId::of::<A>()));\n\n assert!(!world.is_registered(&TypeId::of::<B>()));\n\n\n\n world.register::<A>();\n\n world.register::<B>();\n\n\n\n assert!(world.is_registered(&TypeId::of::<A>()));\n\n assert!(world.is_registered(&TypeId::of::<B>()));\n\n}\n\n\n", "file_path": "tests/world.rs", "rank": 58, "score": 54348.512504242 }, { "content": "#[test]\n\nfn test_crud() {\n\n let mut resources = Resources::default();\n\n\n\n // Insert\n\n assert!(!resources.contains(&TypeId::of::<A>()));\n\n assert_eq!(resources.insert(A(0)), None);\n\n assert_eq!(resources.insert(A(1)), Some(A(0)));\n\n assert!(resources.contains(&TypeId::of::<A>()));\n\n\n\n // Borrow\n\n assert_eq!(*resources.borrow::<A>().unwrap(), A(1));\n\n\n\n // Remove\n\n assert_eq!(resources.remove::<A>(), Some(A(1)));\n\n assert_eq!(resources.remove::<A>(), None);\n\n assert_eq!(resources.remove::<B>(), None);\n\n assert!(!resources.contains(&TypeId::of::<A>()));\n\n assert!(!resources.contains(&TypeId::of::<B>()));\n\n\n\n // Clear\n\n resources.insert(A(0));\n\n resources.insert(B(0));\n\n resources.clear();\n\n assert!(!resources.contains(&TypeId::of::<A>()));\n\n assert!(!resources.contains(&TypeId::of::<B>()));\n\n}\n", "file_path": "tests/resources.rs", "rank": 59, "score": 54348.512504242 }, { "content": "/// Helper trait for building a `LayoutGroup` from a `Component` tuple.\n\npub trait LayoutGroupDescriptor {\n\n /// Builds a `LayoutGroup` with the given component types.\n\n fn group() -> LayoutGroup;\n\n}\n\n\n\nmacro_rules! impl_layout_group_descriptor {\n\n ($($comp:ident),+) => {\n\n impl<$($comp),+> LayoutGroupDescriptor for ($($comp,)+)\n\n where\n\n $($comp: Component,)+\n\n {\n\n fn group() -> LayoutGroup {\n\n LayoutGroup::new(vec![$(ComponentInfo::new::<$comp>()),+])\n\n }\n\n }\n\n };\n\n}\n\n\n\nimpl_layout_group_descriptor!(A, B);\n\nimpl_layout_group_descriptor!(A, B, C);\n", "file_path": "src/layout/group.rs", "rank": 60, "score": 50179.50542071198 }, { "content": "/// Trait automatically implemented for all types that can be used as resources.\n\npub trait Resource: Downcast {\n\n // Empty\n\n}\n\n\n\nimpl_downcast!(Resource);\n\n\n\nimpl<T> Resource for T\n\nwhere\n\n T: Downcast,\n\n{\n\n // Empty\n\n}\n", "file_path": "src/resources/resource.rs", "rank": 61, "score": 49429.52043938644 }, { "content": "/// Helper trait for creating a system from a function.\n\npub trait IntoSystem<Params> {\n\n /// Creates a system.\n\n fn system(self) -> System;\n\n}\n\n\n\nimpl IntoSystem<()> for System {\n\n fn system(self) -> System {\n\n self\n\n }\n\n}\n\n\n\nmacro_rules! impl_into_system {\n\n ($($param:ident),*) => {\n\n impl<Func, $($param),*> IntoSystem<($($param,)*)> for Func\n\n where\n\n Func: Send + 'static,\n\n for<'a> &'a mut Func: FnMut($($param),*)\n\n + FnMut($(<$param as BorrowLocalSystemData>::Item),*)\n\n + Send,\n\n $($param: SystemParam,)*\n", "file_path": "src/systems/parallel/system.rs", "rank": 62, "score": 48275.04463772534 }, { "content": "/// Helper trait for creating a local system from a function.\n\npub trait IntoLocalSystem<Params> {\n\n /// Creates a local system.\n\n fn local_system(self) -> LocalSystem;\n\n}\n\n\n\nimpl IntoLocalSystem<()> for LocalSystem {\n\n fn local_system(self) -> LocalSystem {\n\n self\n\n }\n\n}\n\n\n\nmacro_rules! impl_into_system {\n\n ($($param:ident),*) => {\n\n impl<Func, $($param),*> IntoLocalSystem<($($param,)*)> for Func\n\n where\n\n Func: Send + 'static,\n\n for<'a> &'a mut Func: FnMut($($param),*)\n\n + FnMut($(<$param as BorrowLocalSystemData>::Item),*)\n\n + Send,\n\n $($param: SystemParam,)*\n", "file_path": "src/systems/local/system.rs", "rank": 63, "score": 47208.90677745834 }, { "content": "/// Trait implemented by local system parameters to borrow data.\n\npub trait BorrowLocalSystemData<'a> {\n\n /// System data to borrow.\n\n type Item: 'a;\n\n\n\n /// Borrows the system data.\n\n fn borrow(world: &'a World, resources: &'a Resources) -> Self::Item;\n\n}\n\n\n\nimpl<'a, 'b> BorrowLocalSystemData<'a> for Entities<'b> {\n\n type Item = Entities<'a>;\n\n\n\n fn borrow(world: &'a World, _resources: &'a Resources) -> Self::Item {\n\n world.borrow_entities()\n\n }\n\n}\n\n\n\nimpl<'a, 'b, T> BorrowLocalSystemData<'a> for Comp<'b, T>\n\nwhere\n\n T: Component,\n\n{\n", "file_path": "src/systems/local/borrow.rs", "rank": 64, "score": 46218.45310036221 }, { "content": "fn raise_lava(mut lava: ResMut<Lava>) {\n\n lava.height += 2;\n\n println!(\"[Lava raised to y={}]\", lava.height);\n\n}\n\n\n", "file_path": "examples/resources.rs", "rank": 65, "score": 41934.12432255455 }, { "content": "#[derive(Clone, Copy)]\n\nstruct ComponentInfo {\n\n storage_index: usize,\n\n family_mask: FamilyMask,\n\n group_mask: GroupMask,\n\n group_info: Option<StorageGroupInfo>,\n\n}\n\n\n", "file_path": "src/components/component_storages.rs", "rank": 66, "score": 41904.12302640048 }, { "content": "use crate::query::{ComponentView, QueryGroupInfo};\n\nuse crate::storage::{Entity, SparseArray};\n\nuse std::ops::RangeBounds;\n\n\n\n#[doc(hidden)]\n\npub unsafe trait Query<'a> {\n\n type Item: 'a;\n\n type Index: Copy;\n\n type ComponentPtrs: Copy;\n\n type SparseArrays: Copy + 'a;\n\n type ComponentSlices: 'a;\n\n\n\n fn group_info(&self) -> Option<QueryGroupInfo<'a>>;\n\n\n\n fn get(self, entity: Entity) -> Option<Self::Item>;\n\n\n\n fn includes(self, entity: Entity) -> bool;\n\n\n\n fn excludes(self, entity: Entity) -> bool;\n\n\n", "file_path": "src/query/query.rs", "rank": 67, "score": 41311.91062948836 }, { "content": " unsafe fn get_components_unchecked<R>(self, _range: R) -> Self::ComponentSlices\n\n where\n\n R: RangeBounds<usize>,\n\n {\n\n ()\n\n }\n\n\n\n #[inline(always)]\n\n unsafe fn get_entities_components_unchecked<R>(\n\n self,\n\n _range: R,\n\n ) -> (&'a [Entity], Self::ComponentSlices)\n\n where\n\n R: RangeBounds<usize>,\n\n {\n\n (&[], ())\n\n }\n\n}\n\n\n\nunsafe impl<'a, E> Query<'a> for E\n", "file_path": "src/query/query.rs", "rank": 68, "score": 41307.42938734797 }, { "content": " ) -> (&'a [Entity], Self::ComponentSlices)\n\n where\n\n R: RangeBounds<usize>;\n\n}\n\n\n\nunsafe impl<'a> Query<'a> for () {\n\n type Item = ();\n\n type Index = ();\n\n type ComponentPtrs = ();\n\n type SparseArrays = ();\n\n type ComponentSlices = ();\n\n\n\n #[inline(always)]\n\n fn group_info(&self) -> Option<QueryGroupInfo<'a>> {\n\n Some(QueryGroupInfo::Empty)\n\n }\n\n\n\n #[inline(always)]\n\n fn get(self, _entity: Entity) -> Option<Self::Item> {\n\n Some(())\n", "file_path": "src/query/query.rs", "rank": 69, "score": 41306.41361505984 }, { "content": " }\n\n\n\n #[inline(always)]\n\n fn includes(self, _entity: Entity) -> bool {\n\n true\n\n }\n\n\n\n #[inline(always)]\n\n fn excludes(self, _entity: Entity) -> bool {\n\n true\n\n }\n\n\n\n #[inline(always)]\n\n fn into_any_entities(self) -> Option<&'a [Entity]> {\n\n None\n\n }\n\n\n\n #[inline(always)]\n\n fn split_sparse(self) -> (Option<&'a [Entity]>, Self::SparseArrays, Self::ComponentPtrs) {\n\n (None, (), ())\n", "file_path": "src/query/query.rs", "rank": 70, "score": 41306.371741932846 }, { "content": "where\n\n E: ComponentView<'a>,\n\n{\n\n type Item = E::Item;\n\n type Index = usize;\n\n type ComponentPtrs = *mut E::Component;\n\n type SparseArrays = &'a SparseArray;\n\n type ComponentSlices = E::ComponentSlice;\n\n\n\n fn group_info(&self) -> Option<QueryGroupInfo<'a>> {\n\n let len = ComponentView::len(self);\n\n let info = ComponentView::group_info(self);\n\n Some(QueryGroupInfo::Single { len, info })\n\n }\n\n\n\n fn get(self, entity: Entity) -> Option<Self::Item> {\n\n ComponentView::get(self, entity)\n\n }\n\n\n\n fn includes(self, entity: Entity) -> bool {\n", "file_path": "src/query/query.rs", "rank": 71, "score": 41306.1650951954 }, { "content": " fn into_any_entities(self) -> Option<&'a [Entity]>;\n\n\n\n fn split_sparse(self) -> (Option<&'a [Entity]>, Self::SparseArrays, Self::ComponentPtrs);\n\n\n\n fn split_dense(self) -> (Option<&'a [Entity]>, Self::ComponentPtrs);\n\n\n\n fn split_filter(self) -> (Option<&'a [Entity]>, Self::SparseArrays);\n\n\n\n fn includes_split(sparse: Self::SparseArrays, entity: Entity) -> bool;\n\n\n\n fn excludes_split(sparse: Self::SparseArrays, entity: Entity) -> bool;\n\n\n\n fn get_index_from_split(sparse: Self::SparseArrays, entity: Entity) -> Option<Self::Index>;\n\n\n\n unsafe fn get_from_sparse_components(\n\n components: Self::ComponentPtrs,\n\n index: Self::Index,\n\n ) -> Self::Item;\n\n\n\n unsafe fn get_from_dense_components(\n", "file_path": "src/query/query.rs", "rank": 72, "score": 41305.89098299143 }, { "content": " }\n\n\n\n #[inline(always)]\n\n fn split_dense(self) -> (Option<&'a [Entity]>, Self::ComponentPtrs) {\n\n (None, ())\n\n }\n\n\n\n #[inline(always)]\n\n fn split_filter(self) -> (Option<&'a [Entity]>, Self::SparseArrays) {\n\n (None, ())\n\n }\n\n\n\n #[inline(always)]\n\n fn includes_split(_sparse: Self::SparseArrays, _entity: Entity) -> bool {\n\n true\n\n }\n\n\n\n #[inline(always)]\n\n fn excludes_split(_sparse: Self::SparseArrays, _entity: Entity) -> bool {\n\n true\n", "file_path": "src/query/query.rs", "rank": 73, "score": 41305.46322973446 }, { "content": " self.$idx.get_components_unchecked(bounds),\n\n )+)\n\n }\n\n\n\n unsafe fn get_entities_components_unchecked<R>(self, range: R) -> (&'a [Entity], Self::ComponentSlices)\n\n where\n\n R: RangeBounds<usize>,\n\n {\n\n get_entities_components!(range; $(self.$idx),+)\n\n }\n\n }\n\n };\n\n}\n\n\n\n#[rustfmt::skip]\n\nmod impls {\n\n use super::*;\n\n\n\n impl_query!((A, 0), (B, 1));\n\n impl_query!((A, 0), (B, 1), (C, 2));\n", "file_path": "src/query/query.rs", "rank": 74, "score": 41305.17182034218 }, { "content": " components: Self::ComponentPtrs,\n\n index: usize,\n\n ) -> Self::Item;\n\n\n\n unsafe fn offset_component_ptrs(\n\n components: Self::ComponentPtrs,\n\n offset: isize,\n\n ) -> Self::ComponentPtrs;\n\n\n\n unsafe fn get_entities_unchecked<R>(self, range: R) -> &'a [Entity]\n\n where\n\n R: RangeBounds<usize>;\n\n\n\n unsafe fn get_components_unchecked<R>(self, range: R) -> Self::ComponentSlices\n\n where\n\n R: RangeBounds<usize>;\n\n\n\n unsafe fn get_entities_components_unchecked<R>(\n\n self,\n\n range: R,\n", "file_path": "src/query/query.rs", "rank": 75, "score": 41304.8228892837 }, { "content": " unsafe fn get_entities_unchecked<R>(self, range: R) -> &'a [Entity]\n\n where\n\n R: RangeBounds<usize>,\n\n {\n\n <E as ComponentView>::get_entities_unchecked(self, range)\n\n }\n\n\n\n unsafe fn get_components_unchecked<R>(self, range: R) -> Self::ComponentSlices\n\n where\n\n R: RangeBounds<usize>,\n\n {\n\n <E as ComponentView>::get_components_unchecked(self, range)\n\n }\n\n\n\n unsafe fn get_entities_components_unchecked<R>(\n\n self,\n\n range: R,\n\n ) -> (&'a [Entity], Self::ComponentSlices)\n\n where\n\n R: RangeBounds<usize>,\n", "file_path": "src/query/query.rs", "rank": 76, "score": 41304.56674375217 }, { "content": " }\n\n\n\n fn split_filter(self) -> (Option<&'a [Entity]>, Self::SparseArrays) {\n\n let (entities, sparse, _) = ComponentView::split(self);\n\n (Some(entities), sparse)\n\n }\n\n\n\n fn includes_split(sparse: Self::SparseArrays, entity: Entity) -> bool {\n\n sparse.contains(entity)\n\n }\n\n\n\n fn excludes_split(sparse: Self::SparseArrays, entity: Entity) -> bool {\n\n !sparse.contains(entity)\n\n }\n\n\n\n fn get_index_from_split(sparse: Self::SparseArrays, entity: Entity) -> Option<Self::Index> {\n\n sparse.get(entity)\n\n }\n\n\n\n unsafe fn get_from_sparse_components(\n", "file_path": "src/query/query.rs", "rank": 77, "score": 41304.506752396 }, { "content": " components: Self::ComponentPtrs,\n\n index: Self::Index,\n\n ) -> Self::Item {\n\n <E as ComponentView>::get_from_component_ptr(components.add(index))\n\n }\n\n\n\n unsafe fn get_from_dense_components(\n\n components: Self::ComponentPtrs,\n\n index: usize,\n\n ) -> Self::Item {\n\n <E as ComponentView>::get_from_component_ptr(components.add(index))\n\n }\n\n\n\n unsafe fn offset_component_ptrs(\n\n components: Self::ComponentPtrs,\n\n offset: isize,\n\n ) -> Self::ComponentPtrs {\n\n components.offset(offset)\n\n }\n\n\n", "file_path": "src/query/query.rs", "rank": 78, "score": 41304.41803538195 }, { "content": " ()\n\n }\n\n\n\n #[inline(always)]\n\n unsafe fn offset_component_ptrs(\n\n _components: Self::ComponentPtrs,\n\n _offset: isize,\n\n ) -> Self::ComponentPtrs {\n\n ()\n\n }\n\n\n\n #[inline(always)]\n\n unsafe fn get_entities_unchecked<R>(self, _range: R) -> &'a [Entity]\n\n where\n\n R: RangeBounds<usize>,\n\n {\n\n &[]\n\n }\n\n\n\n #[inline(always)]\n", "file_path": "src/query/query.rs", "rank": 79, "score": 41304.39852895439 }, { "content": " unsafe fn offset_component_ptrs(components: Self::ComponentPtrs, offset: isize) -> Self::ComponentPtrs {\n\n ($(\n\n components.$idx.offset(offset),\n\n )+)\n\n }\n\n\n\n unsafe fn get_entities_unchecked<R>(self, range: R) -> &'a [Entity]\n\n where\n\n R: RangeBounds<usize>,\n\n {\n\n self.0.get_entities_unchecked(range)\n\n }\n\n\n\n unsafe fn get_components_unchecked<R>(self, range: R) -> Self::ComponentSlices\n\n where\n\n R: RangeBounds<usize>,\n\n {\n\n let bounds = (range.start_bound().cloned(), range.end_bound().cloned());\n\n\n\n ($(\n", "file_path": "src/query/query.rs", "rank": 80, "score": 41303.70232531713 }, { "content": " fn includes(self, entity: Entity) -> bool {\n\n $(self.$idx.contains(entity))&&+\n\n }\n\n\n\n fn excludes(self, entity: Entity) -> bool {\n\n $(!self.$idx.contains(entity))&&+\n\n }\n\n\n\n fn into_any_entities(self) -> Option<&'a [Entity]> {\n\n let (entities, _, _) = ComponentView::split(self.0);\n\n Some(entities)\n\n }\n\n\n\n fn split_sparse(self) -> (Option<&'a [Entity]>, Self::SparseArrays, Self::ComponentPtrs) {\n\n split_sparse!($((self.$idx, $idx)),+)\n\n }\n\n\n\n fn split_dense(self) -> (Option<&'a [Entity]>, Self::ComponentPtrs) {\n\n split_dense!($(self.$idx),+)\n\n }\n", "file_path": "src/query/query.rs", "rank": 81, "score": 41303.51022424898 }, { "content": " }\n\n\n\n #[inline(always)]\n\n fn get_index_from_split(_sparse: Self::SparseArrays, _entity: Entity) -> Option<Self::Index> {\n\n Some(())\n\n }\n\n\n\n #[inline(always)]\n\n unsafe fn get_from_sparse_components(\n\n _components: Self::ComponentPtrs,\n\n _index: Self::Index,\n\n ) -> Self::Item {\n\n ()\n\n }\n\n\n\n #[inline(always)]\n\n unsafe fn get_from_dense_components(\n\n _components: Self::ComponentPtrs,\n\n _index: usize,\n\n ) -> Self::Item {\n", "file_path": "src/query/query.rs", "rank": 82, "score": 41302.251647504076 }, { "content": " unsafe impl<'a, $($elem),+> Query<'a> for ($($elem,)+)\n\n where\n\n $($elem: ComponentView<'a>,)+\n\n {\n\n type Item = ($($elem::Item,)+);\n\n type Index = ($(replace!($elem, usize),)+);\n\n type ComponentPtrs = ($(*mut $elem::Component,)+);\n\n type SparseArrays = ($(replace!($elem, &'a SparseArray),)+);\n\n type ComponentSlices = ($($elem::ComponentSlice,)+);\n\n\n\n fn group_info(&self) -> Option<QueryGroupInfo<'a>> {\n\n query_group_info!($(self.$idx.group_info()),+)\n\n }\n\n\n\n fn get(self, entity: Entity) -> Option<Self::Item> {\n\n Some((\n\n $(self.$idx.get(entity)?,)+\n\n ))\n\n }\n\n\n", "file_path": "src/query/query.rs", "rank": 83, "score": 41302.24689236485 }, { "content": " ComponentView::contains(self, entity)\n\n }\n\n\n\n fn excludes(self, entity: Entity) -> bool {\n\n !ComponentView::contains(self, entity)\n\n }\n\n\n\n fn into_any_entities(self) -> Option<&'a [Entity]> {\n\n let (entities, _, _) = ComponentView::split(self);\n\n Some(entities)\n\n }\n\n\n\n fn split_sparse(self) -> (Option<&'a [Entity]>, Self::SparseArrays, Self::ComponentPtrs) {\n\n let (entities, sparse, components) = ComponentView::split(self);\n\n (Some(entities), sparse, components)\n\n }\n\n\n\n fn split_dense(self) -> (Option<&'a [Entity]>, Self::ComponentPtrs) {\n\n let (entities, _, components) = ComponentView::split(self);\n\n (Some(entities), components)\n", "file_path": "src/query/query.rs", "rank": 84, "score": 41302.05845633449 }, { "content": " impl_query!((A, 0), (B, 1), (C, 2), (D, 3));\n\n impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4));\n\n impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5));\n\n impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6));\n\n impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7));\n\n impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8));\n\n impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9));\n\n impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10));\n\n impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10), (L, 11));\n\n impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10), (L, 11), (M, 12));\n\n impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10), (L, 11), (M, 12), (N, 13));\n\n impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10), (L, 11), (M, 12), (N, 13), (O, 14));\n\n impl_query!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10), (L, 11), (M, 12), (N, 13), (O, 14), (P, 15));\n\n}\n", "file_path": "src/query/query.rs", "rank": 85, "score": 41300.331065021535 }, { "content": "\n\n fn split_filter(self) -> (Option<&'a [Entity]>, Self::SparseArrays) {\n\n split_filter!($(self.$idx),+)\n\n }\n\n\n\n fn includes_split(sparse: Self::SparseArrays, entity: Entity) -> bool {\n\n $(sparse.$idx.contains(entity))&&+\n\n }\n\n\n\n fn excludes_split(sparse: Self::SparseArrays, entity: Entity) -> bool {\n\n $(!sparse.$idx.contains(entity))&&+\n\n }\n\n\n\n fn get_index_from_split(\n\n sparse: Self::SparseArrays,\n\n entity: Entity,\n\n ) -> Option<Self::Index> {\n\n Some((\n\n $(sparse.$idx.get(entity)?,)+\n\n ))\n", "file_path": "src/query/query.rs", "rank": 86, "score": 41300.21521687826 }, { "content": " }\n\n\n\n unsafe fn get_from_sparse_components(\n\n components: Self::ComponentPtrs,\n\n index: Self::Index,\n\n ) -> Self::Item {\n\n ($(\n\n $elem::get_from_component_ptr(components.$idx.add(index.$idx)),\n\n )+)\n\n }\n\n\n\n unsafe fn get_from_dense_components(\n\n components: Self::ComponentPtrs,\n\n index: usize,\n\n ) -> Self::Item {\n\n ($(\n\n $elem::get_from_component_ptr(components.$idx.add(index)),\n\n )+)\n\n }\n\n\n", "file_path": "src/query/query.rs", "rank": 87, "score": 41299.45640572315 }, { "content": " {\n\n <E as ComponentView>::get_entities_components_unchecked(self, range)\n\n }\n\n}\n\n\n\nmacro_rules! replace {\n\n ($from:ident, $($to:tt)+) => {\n\n $($to)+\n\n };\n\n}\n\n\n\nmacro_rules! query_group_info {\n\n ($first:expr, $($other:expr),+) => {\n\n Some(QueryGroupInfo::Multiple($first? $(.combine($other?)?)+))\n\n };\n\n}\n\n\n\nmacro_rules! split_sparse {\n\n (($first:expr, $_:tt), $(($other:expr, $other_idx:tt)),+) => {\n\n {\n", "file_path": "src/query/query.rs", "rank": 88, "score": 41298.84955248443 }, { "content": " let (entities, first_sparse, _) = $first.split();\n\n let sparse = (first_sparse, $($other.split().1),+);\n\n\n\n (Some(entities), sparse)\n\n }\n\n };\n\n}\n\n\n\nmacro_rules! get_entities_components {\n\n ($range:expr; $first:expr, $($other:expr),+) => {\n\n {\n\n let bounds = ($range.start_bound().cloned(), $range.end_bound().cloned());\n\n let (entities, first_comp) = $first.get_entities_components_unchecked(bounds);\n\n (entities, (first_comp, $($other.get_components_unchecked(bounds),)+))\n\n }\n\n };\n\n}\n\n\n\nmacro_rules! impl_query {\n\n ($(($elem:ident, $idx:tt)),+) => {\n", "file_path": "src/query/query.rs", "rank": 89, "score": 41296.92804791458 }, { "content": " let (mut entities, first_sparse, first_comp) = $first.split();\n\n\n\n #[allow(clippy::eval_order_dependence)]\n\n let splits = (\n\n (first_sparse, first_comp),\n\n $(\n\n {\n\n let (other_entities, other_sparse, other_comp) = $other.split();\n\n\n\n if other_entities.len() < entities.len() {\n\n entities = other_entities;\n\n }\n\n\n\n (other_sparse, other_comp)\n\n },\n\n )+\n\n );\n\n\n\n let sparse = (first_sparse, $(splits.$other_idx.0),+);\n\n let comp = (first_comp, $(splits.$other_idx.1),+);\n", "file_path": "src/query/query.rs", "rank": 90, "score": 41291.88894435985 }, { "content": "\n\n (Some(entities), sparse, comp)\n\n }\n\n };\n\n}\n\n\n\nmacro_rules! split_dense {\n\n ($first:expr, $($other:expr),+) => {\n\n {\n\n let (entities, _, first_comp) = $first.split();\n\n let comps = (first_comp, $($other.split().2),+);\n\n\n\n (Some(entities), comps)\n\n }\n\n };\n\n}\n\n\n\nmacro_rules! split_filter {\n\n ($first:expr, $($other:expr),+) => {\n\n {\n", "file_path": "src/query/query.rs", "rank": 91, "score": 41291.519843949725 }, { "content": "/// Trait implemented by system parameters to borrow data.\n\npub trait BorrowSystemData<'a>: BorrowLocalSystemData<'a> {\n\n /// Borrows the system data.\n\n fn borrow(world: &'a World, resources: SyncResources<'a>) -> Self::Item;\n\n}\n\n\n\nimpl<'a, 'b> BorrowSystemData<'a> for Entities<'b> {\n\n fn borrow(world: &'a World, _resources: SyncResources<'a>) -> Self::Item {\n\n world.borrow_entities()\n\n }\n\n}\n\n\n\nimpl<'a, 'b, T> BorrowSystemData<'a> for Comp<'b, T>\n\nwhere\n\n T: Component,\n\n{\n\n fn borrow(world: &'a World, _resources: SyncResources<'a>) -> Self::Item {\n\n world.borrow::<T>()\n\n }\n\n}\n\n\n", "file_path": "src/systems/parallel/borrow.rs", "rank": 92, "score": 40693.31969217943 }, { "content": "/// Wrapper over a query that applies \"include\" and \"exclude\" filters.\n\npub struct IncludeExclude<G, I, E> {\n\n get: G,\n\n include: I,\n\n exclude: E,\n\n}\n\n\n\nimpl<'a, G, I, E> IncludeExclude<G, I, E>\n\nwhere\n\n G: Query<'a>,\n\n I: Query<'a>,\n\n E: Query<'a>,\n\n{\n\n pub(crate) fn new(get: G, include: I, exclude: E) -> Self {\n\n Self { get, include, exclude }\n\n }\n\n}\n\n\n\nimpl<'a, G, I, E> IntoCompoundQueryParts<'a> for IncludeExclude<G, I, E>\n\nwhere\n", "file_path": "src/query/compound_query.rs", "rank": 93, "score": 40181.23484162501 }, { "content": "}\n\n\n\n/// Wrapper over a query that applies an \"include\" filter.\n\npub struct Include<G, I> {\n\n get: G,\n\n include: I,\n\n}\n\n\n\nimpl<'a, G, I> Include<G, I>\n\nwhere\n\n G: Query<'a>,\n\n I: Query<'a> + Copy,\n\n{\n\n pub(crate) fn new(get: G, include: I) -> Self {\n\n Self { get, include }\n\n }\n\n\n\n /// Applies an \"exclude\" filter to the query.\n\n pub fn exclude<E>(self, exclude: E) -> IncludeExclude<G, I, E>\n\n where\n", "file_path": "src/query/compound_query.rs", "rank": 94, "score": 40180.968087303314 }, { "content": " exclude.excludes(entity) && include.includes(entity) && get.includes(entity)\n\n }\n\n\n\n fn iter(self) -> Iter<'a, Self::Get, Self::Include, Self::Exclude> {\n\n let (get, include, exclude) = self.into_compound_query_parts();\n\n Iter::new(get, include, exclude)\n\n }\n\n\n\n fn as_entity_slice(self) -> Option<&'a [Entity]> {\n\n let (get, include, exclude) = self.into_compound_query_parts();\n\n let range = group_range(get.group_info(), include.group_info(), exclude.group_info())?;\n\n unsafe { Some(get.get_entities_unchecked(range)) }\n\n }\n\n\n\n fn as_component_slices(self) -> Option<<Self::Get as Query<'a>>::ComponentSlices> {\n\n let (get, include, exclude) = self.into_compound_query_parts();\n\n let range = group_range(get.group_info(), include.group_info(), exclude.group_info())?;\n\n unsafe { Some(get.get_components_unchecked(range)) }\n\n }\n\n\n", "file_path": "src/query/compound_query.rs", "rank": 95, "score": 40179.57002952808 }, { "content": " fn for_each_with_entity<F>(self, f: F)\n\n where\n\n F: FnMut((Entity, <Self::Get as Query<'a>>::Item)),\n\n {\n\n use crate::query::iter::IntoEntityIter;\n\n\n\n self.iter().with_entity().for_each(f)\n\n }\n\n\n\n /// For grouped storages, returns all entities that match the query as a slice.\n\n #[allow(clippy::wrong_self_convention)]\n\n fn as_entity_slice(self) -> Option<&'a [Entity]>;\n\n\n\n /// For grouped storages, returns all components that match the query as slices.\n\n #[allow(clippy::wrong_self_convention)]\n\n fn as_component_slices(self) -> Option<<Self::Get as Query<'a>>::ComponentSlices>;\n\n\n\n /// For grouped storages, returns all entities and components that match the query as slices.\n\n #[allow(clippy::wrong_self_convention)]\n\n fn as_entity_and_component_slices(\n", "file_path": "src/query/compound_query.rs", "rank": 96, "score": 40178.43001628517 }, { "content": " G: Query<'a>,\n\n I: Query<'a> + Copy,\n\n E: Query<'a> + Copy,\n\n{\n\n type Get = G;\n\n type Include = I;\n\n type Exclude = E;\n\n\n\n fn into_compound_query_parts(self) -> (Self::Get, Self::Include, Self::Exclude) {\n\n (self.get, self.include, self.exclude)\n\n }\n\n}\n\n\n", "file_path": "src/query/compound_query.rs", "rank": 97, "score": 40177.69546311356 }, { "content": " E: Query<'a> + Copy,\n\n {\n\n IncludeExclude::new(self.get, self.include, exclude)\n\n }\n\n}\n\n\n\nimpl<'a, G, I> IntoCompoundQueryParts<'a> for Include<G, I>\n\nwhere\n\n G: Query<'a>,\n\n I: Query<'a> + Copy,\n\n{\n\n type Get = G;\n\n type Include = I;\n\n type Exclude = ();\n\n\n\n fn into_compound_query_parts(self) -> (Self::Get, Self::Include, Self::Exclude) {\n\n (self.get, self.include, ())\n\n }\n\n}\n\n\n", "file_path": "src/query/compound_query.rs", "rank": 98, "score": 40176.93098754932 }, { "content": " fn as_entity_and_component_slices(\n\n self,\n\n ) -> Option<(&'a [Entity], <Self::Get as Query<'a>>::ComponentSlices)> {\n\n let (get, include, exclude) = self.into_compound_query_parts();\n\n let range = group_range(get.group_info(), include.group_info(), exclude.group_info())?;\n\n unsafe { Some(get.get_entities_components_unchecked(range)) }\n\n }\n\n}\n\n\n\nimpl<'a, Q> IntoCompoundQueryParts<'a> for Q\n\nwhere\n\n Q: Query<'a>,\n\n{\n\n type Get = Q;\n\n type Include = ();\n\n type Exclude = ();\n\n\n\n fn into_compound_query_parts(self) -> (Self::Get, Self::Include, Self::Exclude) {\n\n (self, (), ())\n\n }\n", "file_path": "src/query/compound_query.rs", "rank": 99, "score": 40176.63047293771 } ]
Rust
src/techblox/parsing_tools.rs
NGnius/libfj
2b1033449e50086c2768e3bbd4dafc0d5bb257f6
use std::io::{Read, Write}; use crate::techblox::Parsable; use half::f16; pub fn parse_header_u32(reader: &mut dyn Read) -> std::io::Result<u32> { let mut u32_buf = [0; 4]; reader.read(&mut u32_buf)?; Ok(u32::from_le_bytes(u32_buf)) } pub fn parse_u8(reader: &mut dyn Read) -> std::io::Result<u8> { let mut u8_buf = [0; 1]; reader.read(&mut u8_buf)?; Ok(u8_buf[0]) } pub fn parse_u32(reader: &mut dyn Read) -> std::io::Result<u32> { let mut u32_buf = [0; 4]; reader.read(&mut u32_buf)?; Ok(u32::from_le_bytes(u32_buf)) } pub fn parse_i32(reader: &mut dyn Read) -> std::io::Result<i32> { let mut i32_buf = [0; 4]; reader.read(&mut i32_buf)?; Ok(i32::from_le_bytes(i32_buf)) } pub fn parse_u64(reader: &mut dyn Read) -> std::io::Result<u64> { let mut u64_buf = [0; 8]; reader.read(&mut u64_buf)?; Ok(u64::from_le_bytes(u64_buf)) } pub fn parse_i64(reader: &mut dyn Read) -> std::io::Result<i64> { let mut i64_buf = [0; 8]; reader.read(&mut i64_buf)?; Ok(i64::from_le_bytes(i64_buf)) } pub fn parse_f32(reader: &mut dyn Read) -> std::io::Result<f32> { let mut f32_buf = [0; 4]; reader.read(&mut f32_buf)?; Ok(f32::from_le_bytes(f32_buf)) } pub fn dump_u8(data: u8, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_u32(data: u32, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_i32(data: i32, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_u64(data: u64, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_i64(data: i64, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_f32(data: f32, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } impl Parsable for u8 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 1]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for u32 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 4]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for i32 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 4]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for u64 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 8]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for i64 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 8]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for f32 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 4]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for f16 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 2]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } }
use std::io::{Read, Write}; use crate::techblox::Parsable; use half::f16; pub fn parse_header_u32(reader: &mut dyn Read) -> std::i
pub fn parse_u8(reader: &mut dyn Read) -> std::io::Result<u8> { let mut u8_buf = [0; 1]; reader.read(&mut u8_buf)?; Ok(u8_buf[0]) } pub fn parse_u32(reader: &mut dyn Read) -> std::io::Result<u32> { let mut u32_buf = [0; 4]; reader.read(&mut u32_buf)?; Ok(u32::from_le_bytes(u32_buf)) } pub fn parse_i32(reader: &mut dyn Read) -> std::io::Result<i32> { let mut i32_buf = [0; 4]; reader.read(&mut i32_buf)?; Ok(i32::from_le_bytes(i32_buf)) } pub fn parse_u64(reader: &mut dyn Read) -> std::io::Result<u64> { let mut u64_buf = [0; 8]; reader.read(&mut u64_buf)?; Ok(u64::from_le_bytes(u64_buf)) } pub fn parse_i64(reader: &mut dyn Read) -> std::io::Result<i64> { let mut i64_buf = [0; 8]; reader.read(&mut i64_buf)?; Ok(i64::from_le_bytes(i64_buf)) } pub fn parse_f32(reader: &mut dyn Read) -> std::io::Result<f32> { let mut f32_buf = [0; 4]; reader.read(&mut f32_buf)?; Ok(f32::from_le_bytes(f32_buf)) } pub fn dump_u8(data: u8, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_u32(data: u32, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_i32(data: i32, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_u64(data: u64, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_i64(data: i64, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } pub fn dump_f32(data: f32, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&data.to_le_bytes()) } impl Parsable for u8 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 1]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for u32 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 4]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for i32 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 4]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for u64 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 8]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for i64 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 8]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for f32 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 4]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } } impl Parsable for f16 { fn parse(reader: &mut dyn Read) -> std::io::Result<Self> { let mut buf = [0; 2]; reader.read(&mut buf)?; Ok(Self::from_le_bytes(buf)) } fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> { writer.write(&self.to_le_bytes()) } }
o::Result<u32> { let mut u32_buf = [0; 4]; reader.read(&mut u32_buf)?; Ok(u32::from_le_bytes(u32_buf)) }
function_block-function_prefixed
[ { "content": "pub fn lookup_hashname(hash: u32, data: &mut dyn Read) ->\n\n std::io::Result<Box<dyn Block>> {\n\n Ok(match hash {\n\n 1357220432 /*StandardBlockEntityDescriptorV4*/ => Box::new(BlockEntity::parse(data)?),\n\n 2281299333 /*PilotSeatEntityDescriptorV4*/ => Box::new(PilotSeatEntity::parse(data)?),\n\n 1360086092 /*PassengerSeatEntityDescriptorV4*/ => Box::new(PassengerSeatEntity::parse(data)?),\n\n 1757314505 /*EngineBlockEntityDescriptor*/ => Box::new(EngineBlockEntity::parse(data)?),\n\n 3586818581 /*JointBlockEntityDescriptorV3*/ => Box::new(JointBlockEntity::parse(data)?),\n\n 3789998433 /*DampedAngularSpringEntityDescriptorV4*/ => Box::new(DampedAngularSpringEntity::parse(data)?),\n\n 2892049599 /*DampedSpringEntityDescriptorV5*/ => Box::new(DampedSpringEntity::parse(data)?),\n\n 1156723746 /*WheelRigEntityDescriptor*/ => Box::new(WheelRigEntity::parse(data)?),\n\n 1864425618 /*WheelRigSteerableEntityDescriptor*/ => Box::new(WheelRigSteerableEntity::parse(data)?),\n\n 1517625162 /*TyreEntityDescriptorV1*/ => Box::new(TyreEntity::parse(data)?),\n\n _ => {\n\n #[cfg(debug_assertions)]\n\n println!(\"Unknown hash ID {} (missing entry for {})\", hash, lookup_name_by_hash(hash).unwrap_or(\"<Unknown>\"));\n\n return Err(std::io::Error::new(std::io::ErrorKind::Other, format!(\"Unrecognised hash {}\", hash)))\n\n }\n\n })\n\n}\n\n\n", "file_path": "src/techblox/blocks/lookup_tables.rs", "rank": 0, "score": 178792.4807260625 }, { "content": "/// Convert a Robocraft robot to a 3D model in Wavefront OBJ format using the provided lookup table function.\n\npub fn cubes_to_model_with_lut<F: FnMut(u32) -> Vec<Quad<Vertex>>>(robot: robocraft::Cubes, mut lut: F) -> obj::Obj {\n\n let mut positions = Vec::<[f32; 3]>::new(); // vertex positions\n\n let mut normals = Vec::<[f32; 3]>::new(); // vertex normals\n\n let mut objects = Vec::<obj::Object>::new(); // blocks\n\n let mut last = 0;\n\n for cube in robot.into_iter() {\n\n // generate simple cube for every block\n\n // TODO rotate blocks\n\n let vertices = lut(cube.id); // Use lookup table to find correct id <-> block translation\n\n let rotation: Quaternion<_> = cube_rotation_to_quat(cube.orientation);\n\n positions.extend::<Vec::<[f32; 3]>>(\n\n vertices.clone().into_iter().vertex(|v|\n\n {\n\n let rotated = rotation * Vector3{x: v.pos.x * SCALE, y: v.pos.y * SCALE, z: v.pos.z * SCALE};\n\n [rotated.x + (cube.x as f32), rotated.y + (cube.y as f32), rotated.z + (cube.z as f32)]\n\n })\n\n .vertices()\n\n .collect()\n\n );\n\n normals.extend::<Vec::<[f32; 3]>>(\n", "file_path": "src/convert/robocraft_3d.rs", "rank": 14, "score": 97325.10287902744 }, { "content": "pub fn hashname(name: &str) -> u32 {\n\n hash32_with_seed(name, HASH_SEED)\n\n}\n\n\n", "file_path": "src/techblox/murmur.rs", "rank": 15, "score": 81156.12386262314 }, { "content": "pub fn brute_force(hash: u32) -> String {\n\n let (tx, rx) = channel::<String>();\n\n let mut start = Vec::<u8>::new();\n\n thread::spawn(move || brute_force_letter(hash, &mut start, &tx, 1));\n\n //println!(\"All brute force possibilities explored\");\n\n if let Ok(res) = rx.recv_timeout(std::time::Duration::from_secs(30)) {\n\n return res;\n\n } else {\n\n return \"\".to_string();\n\n }\n\n}\n\n\n", "file_path": "src/techblox/murmur.rs", "rank": 16, "score": 79323.12301509832 }, { "content": "/// Convert a Robocraft robot's orientation enum into a physical rotation\n\npub fn cube_rotation_to_quat(orientation: u8) -> Quaternion<f32> {\n\n ROTATIONS[orientation as usize].into()\n\n}\n\n\n", "file_path": "src/convert/robocraft_3d.rs", "rank": 17, "score": 74304.1858841113 }, { "content": "#[proc_macro_derive(Parsable)]\n\npub fn derive_parsable(struc: TokenStream) -> TokenStream {\n\n let ast: &DeriveInput = &syn::parse(struc).unwrap();\n\n let name = &ast.ident;\n\n if let Data::Struct(data_struct) = &ast.data {\n\n let mut p_fields_gen = vec![];\n\n let mut d_fields_gen = vec![];\n\n for field in &data_struct.fields {\n\n let field_ident = &field.ident.clone().expect(\"Expected named field\");\n\n let field_type = &field.ty;\n\n p_fields_gen.push(\n\n quote! {\n\n #field_ident: <#field_type>::parse(data)?\n\n }\n\n );\n\n d_fields_gen.push(\n\n quote! {\n\n self.#field_ident.dump(data)?;\n\n }\n\n );\n\n }\n", "file_path": "parsable_macro_derive/src/lib.rs", "rank": 18, "score": 73132.46444277416 }, { "content": "/// Convert a Robocraft robot to a 3D model in Wavefront OBJ format.\n\npub fn cubes_to_model(robot: robocraft::Cubes) -> obj::Obj {\n\n cubes_to_model_with_lut(robot, default_model_lut)\n\n}\n\n\n", "file_path": "src/convert/robocraft_3d.rs", "rank": 19, "score": 72774.54158359488 }, { "content": "pub fn default_model_lut(id: u32) -> Vec<Quad<Vertex>> {\n\n // TODO generate non-cube blocks properly\n\n match id {\n\n _ => Cube::new().collect(),\n\n }\n\n}\n", "file_path": "src/convert/robocraft_3d.rs", "rank": 20, "score": 71283.21359256297 }, { "content": "pub fn lookup_name_by_hash(hash: u32) -> Option<&'static str> {\n\n for name in HASHNAMES {\n\n if crate::techblox::hashname(name) == hash {\n\n return Some(name);\n\n }\n\n }\n\n None\n\n}\n", "file_path": "src/techblox/blocks/lookup_tables.rs", "rank": 21, "score": 68570.72557184429 }, { "content": "fn brute_force_endings(hash: u32, start: &mut Vec<u8>, tx: &Sender<String>) {\n\n start.extend(HASHNAME_ENDING); // add ending\n\n let last_elem = start.len()-1;\n\n for num in ASCII_NUMBERS {\n\n start[last_elem] = *num;\n\n if hash32_with_seed(&start, HASH_SEED) == hash {\n\n let result = String::from_utf8(start.clone()).unwrap();\n\n println!(\"Found match `{}`\", result);\n\n tx.send(result).unwrap();\n\n }\n\n }\n\n start.truncate(start.len()-HASHNAME_ENDING.len()); // remove ending\n\n}\n", "file_path": "src/techblox/murmur.rs", "rank": 22, "score": 64796.73475880767 }, { "content": "fn brute_force_letter(hash: u32, start: &mut Vec<u8>, tx: &Sender<String>, threadity: usize) {\n\n if start.len() > 0 {\n\n brute_force_endings(hash, start, tx);\n\n }\n\n if start.len() >= MAX_LENGTH { // do not continue extending forever\n\n //handles.pop().unwrap().join().unwrap();\n\n return;\n\n }\n\n let mut handles = Vec::<thread::JoinHandle::<_>>::new();\n\n start.push(65); // add letter\n\n let last_elem = start.len()-1;\n\n for letter in ASCII_LETTERS {\n\n start[last_elem] = *letter;\n\n if threadity > 0 {\n\n //thread::sleep(std::time::Duration::from_millis(50));\n\n let mut new_start = start.clone();\n\n let new_tx = tx.clone();\n\n handles.push(thread::spawn(move || brute_force_letter(hash, &mut new_start, &new_tx, threadity-1)));\n\n } else {\n\n brute_force_letter(hash, start, tx, threadity);\n\n }\n\n }\n\n for handle in handles {\n\n handle.join().unwrap()\n\n }\n\n start.truncate(last_elem);\n\n}\n\n\n", "file_path": "src/techblox/murmur.rs", "rank": 23, "score": 60482.78000919841 }, { "content": "/// Token generator for authenticated API endpoints\n\npub trait ITokenProvider {\n\n /// Retrieve the token to use\n\n fn token(&self) -> Result<String, ()>;\n\n}\n\n\n\n/// Token provider which uses DEFAULT_TOKEN\n\npub struct DefaultTokenProvider {\n\n}\n\n\n\nimpl ITokenProvider for DefaultTokenProvider {\n\n fn token(&self) -> Result<String, ()> {\n\n Ok(DEFAULT_TOKEN.to_string())\n\n }\n\n}\n", "file_path": "src/robocraft/auth.rs", "rank": 24, "score": 48677.94729141648 }, { "content": "/// Standard trait for parsing Techblox game save data.\n\npub trait Parsable {\n\n /// Process information from raw data.\n\n fn parse(reader: &mut dyn Read) -> std::io::Result<Self> where Self: Sized;\n\n /// Convert struct data back into raw bytes\n\n fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize>;\n\n}\n\n\n", "file_path": "src/techblox/entity_traits.rs", "rank": 25, "score": 48677.94729141648 }, { "content": "#[cfg(feature = \"techblox\")]\n\n#[test]\n\nfn hash_tb_name() {\n\n for name in HASHNAMES {\n\n println!(\"MurmurHash3: {} -> {}\", name, crate::techblox::EntityHeader::from_name(name, 0, 0, 0).hash);\n\n }\n\n}\n\n\n", "file_path": "tests/techblox_parsing.rs", "rank": 26, "score": 44577.35005451393 }, { "content": "/// Entity descriptor containing serialized components.\n\npub trait SerializedEntityDescriptor: Parsable {\n\n /// Count of entity components that this descriptor contains\n\n fn serialized_components() -> u8 where Self: Sized;\n\n /// Components that this entity is comprised of\n\n fn components<'a>(&'a self) -> Vec<&'a dyn SerializedEntityComponent>;\n\n /// Components that this entity is comprised of, for modification\n\n fn components_mut<'a>(&'a mut self) -> Vec<&'a mut dyn SerializedEntityComponent>;\n\n /// Hash of descriptor name\n\n fn hash_name(&self) -> u32;\n\n /// Hash of descriptor name\n\n fn hash(s: &str) -> u32 where Self: Sized {\n\n crate::techblox::hashname(s)\n\n }\n\n}\n\n\n", "file_path": "src/techblox/entity_traits.rs", "rank": 27, "score": 44236.099393166674 }, { "content": "#[cfg(feature = \"robocraft\")]\n\n#[test]\n\nfn robocraft_account() -> Result<(), ()> {\n\n let token_maybe = robocraft::AuthenticatedTokenProvider::with_username(\"FJAPIC00L\", \"P4$$w0rd\");\n\n assert!(token_maybe.is_ok());\n\n let token_provider = token_maybe.unwrap();\n\n let account_maybe = token_provider.get_account_info();\n\n assert!(account_maybe.is_ok());\n\n let account = account_maybe.unwrap();\n\n assert_eq!(account.display_name, \"FJAPIC00L\");\n\n assert_eq!(account.created_date, \"2019-01-18T14:48:09\");\n\n Ok(())\n\n}\n", "file_path": "tests/robocraft_auth.rs", "rank": 28, "score": 43293.90245446641 }, { "content": "/// Serializable entity component.\n\n/// Components are the atomic unit of entities.\n\npub trait SerializedEntityComponent: Parsable + Any {\n\n /// Raw size of struct, in bytes.\n\n fn size() -> usize where Self: Sized {\n\n std::mem::size_of::<Self>()\n\n }\n\n}\n", "file_path": "src/techblox/entity_traits.rs", "rank": 29, "score": 42977.75151882213 }, { "content": "#[cfg(feature = \"techblox\")]\n\n#[test]\n\nfn techblox_gamesave_parse_all() -> Result<(), ()> {\n\n let mut in_file = File::open(GAMESAVE_PATH_ALL).map_err(|_| ())?;\n\n let mut buf = Vec::new();\n\n in_file.read_to_end(&mut buf).map_err(|_| ())?;\n\n let gs = techblox::GameSave::parse(&mut buf.as_slice()).map_err(|_| ())?;\n\n\n\n // verify\n\n for i in 1..(gs.group_len as usize) {\n\n assert_eq!(gs.group_headers[i-1].hash, gs.group_headers[i].hash);\n\n //println!(\"#{} count {} vs {}\", i, gs.group_headers[i-1].component_count, gs.group_headers[i].component_count);\n\n assert_eq!(gs.group_headers[i-1].component_count, gs.group_headers[i].component_count);\n\n }\n\n for i in 0..(gs.group_len as usize) {\n\n assert_eq!(gs.group_headers[i].component_count, techblox::BlockGroupEntity::serialized_components());\n\n assert_eq!(gs.group_headers[i].hash, gs.cube_groups[i].hash_name());\n\n /*let pos = format!(\"({}, {}, {})\", gs.cube_groups[i].block_group_transform.block_group_grid_position.x, gs.cube_groups[i].block_group_transform.block_group_grid_position.y, gs.cube_groups[i].block_group_transform.block_group_grid_position.z);\n\n let rot = format!(\"({}, {}, {}, {})\", gs.cube_groups[i].block_group_transform.block_group_grid_rotation.value.x, gs.cube_groups[i].block_group_transform.block_group_grid_rotation.value.y, gs.cube_groups[i].block_group_transform.block_group_grid_rotation.value.z,\n\n gs.cube_groups[i].block_group_transform.block_group_grid_rotation.value.w);\n\n println!(\"block id: {}, position: {}, rotation: {}\", gs.cube_groups[i].saved_block_group_id.saved_block_group_id, pos, rot);*/\n\n }\n", "file_path": "tests/techblox_parsing.rs", "rank": 30, "score": 42237.62029962032 }, { "content": "#[cfg(feature = \"cardlife\")]\n\n#[test]\n\nfn live_api_init() -> Result<(), ()> {\n\n cardlife::LiveAPI::new();\n\n Ok(())\n\n}\n\n\n\n#[cfg(feature = \"cardlife\")]\n\n#[tokio::test]\n\nasync fn live_api_init_auth() -> Result<(), ()> {\n\n let live = cardlife::LiveAPI::login_email(EMAIL, PASSWORD).await;\n\n assert!(live.is_err()); // invalid credentials\n\n Ok(())\n\n}\n\n\n\n#[cfg(feature = \"cardlife\")]\n\n#[tokio::test]\n\nasync fn live_api_authenticate() -> Result<(), ()> {\n\n let mut live = cardlife::LiveAPI::new();\n\n let result = live.authenticate_email(EMAIL, PASSWORD).await;\n\n assert!(result.is_err()); // invalid credentials\n\n /*let auth_info = result.unwrap();\n", "file_path": "tests/cardlife_live.rs", "rank": 31, "score": 42237.62029962032 }, { "content": "#[cfg(feature = \"techblox\")]\n\n#[test]\n\nfn techblox_gamesave_parse() -> Result<(), ()> {\n\n let mut f = File::open(GAMESAVE_PATH).map_err(|_| ())?;\n\n let mut buf = Vec::new();\n\n f.read_to_end(&mut buf).map_err(|_| ())?;\n\n let gs = techblox::GameSave::parse(&mut buf.as_slice()).map_err(|_| ())?;\n\n for i in 1..(gs.group_len as usize) {\n\n assert_eq!(gs.group_headers[i-1].hash, gs.group_headers[i].hash);\n\n //println!(\"#{} count {} vs {}\", i, gs.group_headers[i-1].component_count, gs.group_headers[i].component_count);\n\n assert_eq!(gs.group_headers[i-1].component_count, gs.group_headers[i].component_count);\n\n }\n\n for i in 0..(gs.group_len as usize) {\n\n assert_eq!(gs.group_headers[i].component_count, techblox::BlockGroupEntity::serialized_components());\n\n assert_eq!(gs.group_headers[i].hash, gs.cube_groups[i].hash_name());\n\n }\n\n for i in 1..(gs.cube_len as usize) {\n\n //assert_eq!(gs.cube_headers[i-1].hash, gs.cube_headers[i].hash);\n\n //println!(\"#{} count {} vs {}\", i, gs.cube_headers[i-1].component_count, gs.cube_headers[i].component_count);\n\n if gs.cube_headers[i-1].hash == gs.cube_headers[i].hash {\n\n assert_eq!(gs.group_headers[i-1].component_count, gs.group_headers[i].component_count);\n\n }\n", "file_path": "tests/techblox_parsing.rs", "rank": 32, "score": 42237.62029962032 }, { "content": "#[cfg(feature = \"cardlife\")]\n\n#[test]\n\nfn clre_server_init() -> Result<(), ()> {\n\n assert!(cardlife::CLreServer::new(\"http://localhost:5030\").is_ok());\n\n Ok(())\n\n}\n\n\n\n/*\n\n#[cfg(feature = \"cardlife\")]\n\n#[tokio::test]\n\nasync fn clre_server_game() -> Result<(), ()> {\n\n let server = cardlife::CLreServer::new(\"http://localhost:5030\").unwrap();\n\n let result = server.game_info().await;\n\n assert!(result.is_ok());\n\n let game_info = result.unwrap();\n\n assert_eq!(game_info.admin_password, \"\");\n\n assert_eq!(game_info.game_host_type, 1);\n\n println!(\"GameInfo.to_string() -> `{}`\", game_info.to_string());\n\n Ok(())\n\n}\n\n\n\n#[cfg(feature = \"cardlife\")]\n", "file_path": "tests/clre_server.rs", "rank": 33, "score": 42237.62029962032 }, { "content": "#[cfg(feature = \"robocraft\")]\n\n#[test]\n\nfn robocraft_auth_login() -> Result<(), ()> {\n\n let token_maybe = robocraft::AuthenticatedTokenProvider::with_email(\"melon.spoik@gmail.com\", \"P4$$w0rd\");\n\n assert!(token_maybe.is_ok());\n\n let token_maybe = robocraft::AuthenticatedTokenProvider::with_username(\"FJAPIC00L\", \"P4$$w0rd\");\n\n assert!(token_maybe.is_ok());\n\n let token_p = token_maybe.unwrap();\n\n let raw_token_maybe = token_p.token();\n\n assert!(raw_token_maybe.is_ok());\n\n println!(\"Token: {}\", raw_token_maybe.unwrap());\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/robocraft_auth.rs", "rank": 34, "score": 42237.62029962032 }, { "content": "//#[test]\n\nfn techblox_gamesave_brute_force() -> Result<(), ()> {\n\n // this is slow and not very important, so it's probably better to not test this\n\n let mut f = File::open(GAMESAVE_PATH).map_err(|_| ())?;\n\n let mut buf = Vec::new();\n\n f.read_to_end(&mut buf).map_err(|_| ())?;\n\n let gs = techblox::GameSave::parse(&mut buf.as_slice()).map_err(|_| ())?;\n\n println!(\"murmurhash3: {} -> {}\", gs.group_headers[0].guess_name(), gs.group_headers[0].hash);\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/techblox_parsing.rs", "rank": 35, "score": 41259.23500498432 }, { "content": "#[cfg(feature = \"techblox\")]\n\n#[test]\n\nfn techblox_gamesave_block_groups() -> Result<(), ()> {\n\n let mut in_file = File::open(GAMESAVE_PATH_ALL).map_err(|_| ())?;\n\n let mut buf = Vec::new();\n\n in_file.read_to_end(&mut buf).map_err(|_| ())?;\n\n let gs = techblox::GameSave::parse(&mut buf.as_slice()).map_err(|_| ())?;\n\n\n\n for block_trait in &gs.cube_entities {\n\n let block: &blocks::BlockEntity = block_trait.as_ref().as_ref();\n\n //println!(\"Block @ ({}, {}, {})\", block.pos_component.position.x, block.pos_component.position.y, block.pos_component.position.z);\n\n assert!(is_in_block_groups(block.group_component.current_block_group, &gs.cube_groups));\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/techblox_parsing.rs", "rank": 36, "score": 41259.23500498432 }, { "content": "#[cfg(feature = \"robocraft\")]\n\n#[test]\n\nfn robocraft_factory_api_init() -> Result<(), ()> {\n\n robocraft::FactoryAPI::new();\n\n Ok(())\n\n}\n\n\n\n#[cfg(feature = \"robocraft\")]\n\n#[tokio::test]\n\nasync fn robocraft_factory_default_query() -> Result<(), ()> {\n\n let api = robocraft::FactoryAPI::new();\n\n let result = api.list().await;\n\n assert!(result.is_ok());\n\n let robo_info = result.unwrap();\n\n assert_ne!(robo_info.response.roboshop_items.len(), 0);\n\n assert_eq!(robo_info.status_code, 200);\n\n for robot in &robo_info.response.roboshop_items {\n\n assert_ne!(robot.item_name, \"\");\n\n assert_ne!(robot.added_by, \"\");\n\n assert_ne!(robot.added_by_display_name, \"\");\n\n assert_ne!(robot.thumbnail, \"\");\n\n println!(\"FactoryRobotListInfo.to_string() -> `{}`\", robot.to_string());\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/robocraft_factory.rs", "rank": 37, "score": 41259.23500498432 }, { "content": "#[cfg(feature = \"techblox\")]\n\n#[test]\n\nfn techblox_gamesave_perfect_parse() -> Result<(), ()> {\n\n let mut in_file = File::open(GAMESAVE_PATH_ALL).map_err(|_| ())?;\n\n let mut buf = Vec::new();\n\n in_file.read_to_end(&mut buf).map_err(|_| ())?;\n\n let gs = techblox::GameSave::parse(&mut buf.as_slice()).map_err(|_| ())?;\n\n let mut out_file = OpenOptions::new()\n\n .write(true)\n\n .truncate(true)\n\n .create(true)\n\n .open(GAMESAVE_PATH_OUT)\n\n .map_err(|_| ())?;\n\n gs.dump(&mut out_file).map_err(|_| ())?;\n\n assert_eq!(in_file.stream_position().unwrap(), out_file.stream_position().unwrap());\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/techblox_parsing.rs", "rank": 38, "score": 41259.23500498432 }, { "content": "#[test]\n\n#[cfg(all(feature = \"simple\", feature = \"robocraft\"))]\n\nfn robocraft_factory_query_simple() -> Result<(), ()> {\n\n let result = robocraft_simple::FactoryAPI::new().list();\n\n assert!(result.is_ok());\n\n let robo_info = result.unwrap();\n\n assert_factory_list(robo_info)?;\n\n Ok(())\n\n}\n\n\n\n\n", "file_path": "tests/robocraft_factory_simple.rs", "rank": 39, "score": 40350.43610026025 }, { "content": "#[test]\n\n#[cfg(all(feature = \"simple\", feature = \"robocraft\"))]\n\nfn robocraft_factory_robot_query() -> Result<(), ()> {\n\n let api = robocraft_simple::FactoryAPI::new();\n\n let result = api.get(6478345 /* featured robot id*/);\n\n assert!(result.is_ok());\n\n let bot_info = result.unwrap();\n\n assert_ne!(bot_info.response.item_name, \"\");\n\n assert_eq!(bot_info.response.item_id, 6478345);\n\n assert_ne!(bot_info.response.cube_data, \"\");\n\n assert_ne!(bot_info.response.colour_data, \"\");\n\n Ok(())\n\n}\n", "file_path": "tests/robocraft_factory_simple.rs", "rank": 40, "score": 40350.43610026025 }, { "content": "#[test]\n\n#[cfg(all(feature = \"simple\", feature = \"robocraft\"))]\n\nfn robocraft_factory_player_query() -> Result<(), ()> {\n\n // hard-coding a user inevitably fails, so that's grab one from the front page\n\n let username = robocraft_simple::FactoryAPI::new()\n\n .list()\n\n .unwrap() // covered by another test case\n\n .response\n\n .roboshop_items[0]\n\n .added_by\n\n .clone();\n\n let result = builder()\n\n .text(username) // there is a featured robot by this user, so this should never fail\n\n .text_search_type(robocraft::FactoryTextSearchType::Player)\n\n .items_per_page(10)\n\n .send();\n\n assert!(result.is_ok());\n\n assert_factory_list(result.unwrap())\n\n}\n\n\n", "file_path": "tests/robocraft_factory_simple.rs", "rank": 41, "score": 40350.43610026025 }, { "content": "#[cfg(feature = \"robocraft\")]\n\nfn builder() -> robocraft::FactorySearchBuilder {\n\n robocraft::FactoryAPI::new().list_builder()\n\n}\n\n\n", "file_path": "tests/robocraft_factory.rs", "rank": 42, "score": 40156.10220704279 }, { "content": "#[test]\n\n#[cfg(all(feature = \"simple\", feature = \"robocraft\"))]\n\nfn robocraft_factory_custom_query_simple() -> Result<(), ()> {\n\n let result = builder()\n\n .movement_or(robocraft::FactoryMovementType::Wheels)\n\n .weapon_or(robocraft::FactoryWeaponType::Laser)\n\n .page(2)\n\n .items_per_page(10)\n\n .send();\n\n assert!(result.is_ok());\n\n let robo_info = result.unwrap();\n\n assert_ne!(robo_info.response.roboshop_items.len(), 0);\n\n //assert_eq!(robo_info.response.roboshop_items.len(), 16); the API behaviour is weird, I swear it's not me!\n\n assert!(robo_info.response.roboshop_items.len() >= 10);\n\n assert_eq!(robo_info.status_code, 200);\n\n for robot in &robo_info.response.roboshop_items {\n\n assert_ne!(robot.item_name, \"\");\n\n assert_ne!(robot.added_by, \"\");\n\n assert_ne!(robot.added_by_display_name, \"\");\n\n assert_ne!(robot.thumbnail, \"\");\n\n println!(\"FactoryRobotListInfo.to_string() -> `{}`\", robot.to_string());\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/robocraft_factory_simple.rs", "rank": 43, "score": 39504.05466253266 }, { "content": "#[cfg(all(feature = \"simple\", feature = \"robocraft\"))]\n\n#[test]\n\nfn robocraft_factory_api_init_simple() -> Result<(), ()> {\n\n robocraft_simple::FactoryAPI::new();\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/robocraft_factory_simple.rs", "rank": 44, "score": 39504.05466253266 }, { "content": "pub trait Block: SerializedEntityDescriptor + AsRef<BlockEntity> {}\n\n\n\nimpl Block for BlockEntity {}\n", "file_path": "src/techblox/blocks/block_entity.rs", "rank": 45, "score": 38753.07438656656 }, { "content": "#[cfg(all(feature = \"simple\", feature = \"robocraft\"))]\n\nfn builder() -> robocraft_simple::FactorySearchBuilder {\n\n robocraft_simple::FactoryAPI::new().list_builder()\n\n}\n\n\n", "file_path": "tests/robocraft_factory_simple.rs", "rank": 46, "score": 38400.92186459113 }, { "content": "#[cfg(feature = \"techblox\")]\n\nfn is_in_block_groups(id: i32, block_groups: &Vec<techblox::BlockGroupEntity>) -> bool {\n\n for bg in block_groups {\n\n if bg.saved_block_group_id.saved_block_group_id == id {\n\n return true;\n\n }\n\n }\n\n false\n\n}\n", "file_path": "tests/techblox_parsing.rs", "rank": 47, "score": 31117.98301622717 }, { "content": "#[cfg(feature = \"robocraft\")]\n\nfn assert_factory_list(robo_info: robocraft::FactoryInfo<robocraft::RoboShopItemsInfo>) -> Result<(), ()> {\n\n assert_ne!(robo_info.response.roboshop_items.len(), 0);\n\n assert_eq!(robo_info.status_code, 200);\n\n for robot in &robo_info.response.roboshop_items {\n\n assert_ne!(robot.item_name, \"\");\n\n assert_ne!(robot.added_by, \"\");\n\n assert_ne!(robot.added_by_display_name, \"\");\n\n assert_ne!(robot.thumbnail, \"\");\n\n println!(\"FactoryRobotListInfo.to_string() -> `{}`\", robot.to_string());\n\n }\n\n Ok(())\n\n}\n\n\n\n#[cfg(feature = \"robocraft\")]\n\n#[tokio::test]\n\nasync fn robocraft_factory_custom_query() -> Result<(), ()> {\n\n let api = robocraft::FactoryAPI::new();\n\n let result = api.list_builder()\n\n .movement_or(robocraft::FactoryMovementType::Wheels)\n\n .weapon_or(robocraft::FactoryWeaponType::Laser)\n", "file_path": "tests/robocraft_factory.rs", "rank": 48, "score": 30585.804365754226 }, { "content": "#[cfg(all(feature = \"simple\", feature = \"robocraft\"))]\n\nfn assert_factory_list(robo_info: robocraft::FactoryInfo<robocraft::RoboShopItemsInfo>) -> Result<(), ()> {\n\n assert_ne!(robo_info.response.roboshop_items.len(), 0);\n\n assert_eq!(robo_info.status_code, 200);\n\n for robot in &robo_info.response.roboshop_items {\n\n assert_ne!(robot.item_name, \"\");\n\n assert_ne!(robot.added_by, \"\");\n\n assert_ne!(robot.added_by_display_name, \"\");\n\n assert_ne!(robot.thumbnail, \"\");\n\n println!(\"FactoryRobotListInfo.to_string() -> `{}`\", robot.to_string());\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/robocraft_factory_simple.rs", "rank": 49, "score": 30068.89163015817 }, { "content": " \n\n fn parse_colour_data(&mut self, reader: &mut dyn Read) -> Result<usize, ()> {\n\n let mut buf = [0; 4];\n\n if let Ok(len) = reader.read(&mut buf) {\n\n if len != 4 {\n\n return Err(());\n\n }\n\n self.colour = buf[0];\n\n } else {\n\n return Err(());\n\n }\n\n Ok(4)\n\n }\n\n \n\n /// Dump the raw cube data as used in the Robocraft CRF.\n\n ///\n\n /// This is useless by itself, use `Cubes.dump()` for a valid robot.\n\n pub fn dump_cube_data(&self) -> [u8; 8] {\n\n let id_buf = self.id.to_le_bytes();\n\n [id_buf[0], id_buf[1], id_buf[2], id_buf[3], self.x, self.y, self.z, self.orientation]\n", "file_path": "src/robocraft/cubes.rs", "rank": 54, "score": 13.129867163492886 }, { "content": " let final_gen = quote! {\n\n impl Parsable for #name {\n\n fn parse(data: &mut dyn std::io::Read) -> std::io::Result<Self> {\n\n Ok(Self{\n\n #(#p_fields_gen),*\n\n })\n\n }\n\n\n\n fn dump(&self, data: &mut dyn std::io::Write) -> std::io::Result<usize> {\n\n let mut write_count: usize = 0;\n\n #(write_count += #d_fields_gen;)*\n\n Ok(write_count)\n\n }\n\n }\n\n };\n\n return final_gen.into();\n\n } else {\n\n panic!(\"Expected Parsable auto-trait to be applied to struct\");\n\n }\n\n}\n", "file_path": "parsable_macro_derive/src/lib.rs", "rank": 55, "score": 12.415375482981524 }, { "content": " /// The cube id\n\n pub id: u32,\n\n /// The cube's x position (left to right)\n\n pub x: u8, // left to right\n\n /// The cube's y position (bottom to top)\n\n pub y: u8, // bottom to top\n\n /// The cube's z position (back to front)\n\n pub z: u8, // back to front\n\n /// The cube's orientation\n\n pub orientation: u8,\n\n /// The cube's colour, one of the 24 possible colours in Robocraft\n\n pub colour: u8,\n\n}\n\n\n\nimpl Cube {\n\n fn parse_cube_data(&mut self, reader: &mut dyn Read) -> Result<usize, ()> {\n\n let mut buf = [0; 4];\n\n // read cube id\n\n if let Ok(len) = reader.read(&mut buf) {\n\n if len != 4 {\n", "file_path": "src/robocraft/cubes.rs", "rank": 56, "score": 12.048967743401061 }, { "content": " /// In general, you should use `Cubes::from<FactoryRobotGetInfo>(data)` instead of this lower-level function.\n\n pub fn parse(cube_data: &mut Vec<u8>, colour_data: &mut Vec<u8>) -> Result<Self, ()> {\n\n // read first 4 bytes (cube count) from both arrays and make sure they match\n\n let mut cube_buf = [0; 4];\n\n let mut colour_buf = [0; 4];\n\n let mut cube_slice = cube_data.as_slice();\n\n let mut colour_slice = colour_data.as_slice();\n\n if let Ok(len) = cube_slice.read(&mut cube_buf) {\n\n if len != 4 {\n\n //println!(\"Failed reading cube_data len\");\n\n return Err(());\n\n }\n\n } else {\n\n //println!(\"Failed to read cube_data\");\n\n return Err(());\n\n }\n\n if let Ok(len) = colour_slice.read(&mut colour_buf) {\n\n if len != 4 {\n\n //println!(\"Failed reading colour_data len\");\n\n return Err(());\n", "file_path": "src/robocraft/cubes.rs", "rank": 58, "score": 10.541402333127072 }, { "content": "use std::io::{Read, Write};\n\nuse std::any::Any;\n\n\n\n/// Standard trait for parsing Techblox game save data.\n", "file_path": "src/techblox/entity_traits.rs", "rank": 59, "score": 10.35135919490985 }, { "content": " fn components_mut<'a>(&'a mut self) -> Vec<&'a mut dyn SerializedEntityComponent> {\n\n vec![&mut self.settings_component]\n\n }\n\n\n\n fn hash_name(&self) -> u32 {\n\n Self::hash(\"GlobalWireSettingsEntityDescriptor\") // 1820064641\n\n }\n\n}\n\n\n\n/// Wire settings applied to the whole game save\n\n#[derive(Copy, Clone, Parsable)]\n\npub struct GlobalWireSettingsEntityStruct {\n\n /// Is using obsolete wiring system? (bool)\n\n pub obsolete: u8,\n\n}\n\n\n\nimpl SerializedEntityComponent for GlobalWireSettingsEntityStruct {}\n", "file_path": "src/techblox/blocks/wire_entity.rs", "rank": 60, "score": 10.10539117916995 }, { "content": "pub struct SerializedPhysicsCameraEntity {\n\n /// In-game camera location information\n\n pub cam_component: SerializedCameraEntityStruct,\n\n}\n\n\n\nimpl SerializedEntityDescriptor for SerializedPhysicsCameraEntity {\n\n fn serialized_components() -> u8 {\n\n 1\n\n }\n\n\n\n fn components<'a>(&'a self) -> Vec<&'a dyn SerializedEntityComponent> {\n\n vec![&self.cam_component]\n\n }\n\n\n\n fn components_mut<'a>(&'a mut self) -> Vec<&'a mut dyn SerializedEntityComponent> {\n\n vec![&mut self.cam_component]\n\n }\n\n\n\n fn hash_name(&self) -> u32 {\n\n Self::hash(\"CharacterCameraEntityDescriptorV1\") // 3850144645\n", "file_path": "src/techblox/camera.rs", "rank": 61, "score": 8.911569894585908 }, { "content": " })\n\n }\n\n\n\n fn dump(&self, writer: &mut dyn Write) -> std::io::Result<usize> {\n\n let mut write_count: usize = 0;\n\n // version\n\n write_count += self.version.year().dump(writer)?;\n\n write_count += self.version.month().dump(writer)?;\n\n write_count += self.version.day().dump(writer)?;\n\n // unused separator \\/\n\n write_count += self.ticks.dump(writer)?;\n\n write_count += self.cube_len.dump(writer)?;\n\n // unused separator \\/\n\n write_count += self.max_entity_id.dump(writer)?;\n\n write_count += self.group_len.dump(writer)?;\n\n\n\n // dump block groups\n\n for i in 0..self.group_len as usize {\n\n write_count += self.group_headers[i].dump(writer)?;\n\n write_count += self.cube_groups[i].dump(writer)?;\n", "file_path": "src/techblox/gamesave.rs", "rank": 62, "score": 8.622971001569269 }, { "content": "use chrono::{naive::NaiveDate, Datelike};\n\nuse std::io::{Read, Write};\n\n\n\nuse crate::techblox::{EntityHeader, BlockGroupEntity, parse_i64, parse_u32, Parsable,\n\nSerializedFlyCamEntity, SerializedPhysicsCameraEntity};\n\nuse crate::techblox::blocks::{lookup_hashname, SerializedWireEntity, SerializedGlobalWireSettingsEntity, Block};\n\n\n\n/// A collection of cubes and other data from a GameSave.techblox file\n\n//#[derive(Clone)]\n\npub struct GameSave {\n\n /// Game version that this save was created by.\n\n /// This may affect how the rest of the save file was parsed.\n\n pub version: NaiveDate,\n\n\n\n /// Time when file was saved, corresponding to ticks since 0 AD\n\n /// https://docs.microsoft.com/en-us/dotnet/api/system.datetime.ticks?view=netframework-4.7.2\n\n /// Not used for deserialization so not required to be sensible.\n\n pub ticks: i64,\n\n\n\n /// Amount of cubes present in the save data, as claimed by the file header.\n", "file_path": "src/techblox/gamesave.rs", "rank": 63, "score": 8.361618630116187 }, { "content": " fn components_mut<'a>(&'a mut self) -> Vec<&'a mut dyn SerializedEntityComponent> {\n\n vec![&mut self.save_data_component]\n\n }\n\n\n\n fn hash_name(&self) -> u32 {\n\n Self::hash(\"WireEntityDescriptorMock\") // 1818308818\n\n }\n\n}\n\n\n\n/// Wire connection information that is saved.\n\n#[derive(Copy, Clone, Parsable)]\n\npub struct WireSaveDataStruct {\n\n /// Wire source block index in save\n\n pub source_block_index: u32,\n\n /// Wire destination block index in save\n\n pub destination_block_index: u32,\n\n /// Wire source port index\n\n pub source_port_usage: u8,\n\n /// Wire destination port index\n\n pub destination_port_usage: u8,\n", "file_path": "src/techblox/blocks/wire_entity.rs", "rank": 64, "score": 8.353557945143216 }, { "content": " \n\n // setting buyable to false while using the default token provider will cause HTTP status 500 error\n\n /// Retrieve only items which are buyable for current account? (default: false)\n\n /// Buyable means that the account owns all blocks required.\n\n /// This will cause an error when using DEFAULT_TOKEN\n\n pub fn buyable(mut self, b: bool) -> Self {\n\n self.payload.buyable = b;\n\n self\n\n }\n\n \n\n /// Retrieve items with featured robot at start? (default: false)\n\n pub fn prepend_featured(mut self, b: bool) -> Self {\n\n self.payload.prepend_featured_robot = b;\n\n self\n\n }\n\n \n\n /// Retrieve default robot list? (default: false)\n\n /// The default page is the CRF landing page (I think?)\n\n pub fn default_page(mut self, b: bool) -> Self {\n\n self.payload.default_page = b;\n", "file_path": "src/robocraft/factory_request_builder.rs", "rank": 65, "score": 8.190034097913898 }, { "content": " vec![&self.saved_block_group_id,\n\n &self.block_group_transform]\n\n }\n\n\n\n fn components_mut<'a>(&'a mut self) -> Vec<&'a mut dyn SerializedEntityComponent> {\n\n vec![&mut self.saved_block_group_id,\n\n &mut self.block_group_transform]\n\n }\n\n\n\n fn hash_name(&self) -> u32 {\n\n Self::hash(\"BlockGroupEntityDescriptorV0\")\n\n }\n\n}\n\n\n\n/// Saved block group identifier entity component.\n\n#[derive(Clone, Copy, Parsable)]\n\npub struct SavedBlockGroupIdComponent {\n\n /// Block group identifier\n\n pub saved_block_group_id: i32,\n\n}\n", "file_path": "src/techblox/block_group_entity.rs", "rank": 66, "score": 8.116730397801504 }, { "content": " }\n\n \n\n /* // this appears to not do anything (removed to prevent confusion)\n\n // use text_search_type(FactoryTextSearchType::Player) instead\n\n pub fn players_only(mut self, p: bool) -> Self {\n\n self.payload.player_filter = p;\n\n self\n\n }\n\n */\n\n \n\n /// Override movement filter\n\n pub fn movement_raw(mut self, filter: String) -> Self {\n\n self.payload.movement_filter = filter.clone();\n\n self.payload.movement_category_filter = filter.clone();\n\n self\n\n }\n\n \n\n /// Add allowed movement type\n\n pub fn movement_or(mut self, movement_type: FactoryMovementType) -> Self {\n\n if self.payload.movement_filter == \"\" {\n", "file_path": "src/robocraft_simple/factory_request_builder.rs", "rank": 67, "score": 8.081172034089114 }, { "content": " fn components_mut<'a>(&'a mut self) -> Vec<&'a mut dyn SerializedEntityComponent> {\n\n vec![&mut self.rb_component]\n\n }\n\n\n\n fn hash_name(&self) -> u32 {\n\n Self::hash(\"FlyCamEntityDescriptorV0\") // 252528354\n\n }\n\n}\n\n\n\n/// Physical object info for simulation\n\n#[derive(Copy, Clone, Parsable)]\n\npub struct SerializedRigidBodyEntityStruct {\n\n /// Rigid body location\n\n pub position: UnityFloat3,\n\n}\n\n\n\nimpl SerializedEntityComponent for SerializedRigidBodyEntityStruct {}\n\n\n\n/// Player simulation camera entity descriptor.\n\n#[derive(Copy, Clone, Parsable)]\n", "file_path": "src/techblox/camera.rs", "rank": 68, "score": 7.9339443014449085 }, { "content": " /// Use this to write a modified robot to file.\n\n /// This is the inverse of `Cubes::parse(...)`.\n\n ///\n\n /// I'm not sure what this would actually be useful for...\n\n pub fn dump(&self) -> (Vec<u8>, Vec<u8>) {\n\n let mut cube_buf = Vec::new();\n\n let mut colour_buf = Vec::new();\n\n cube_buf.extend(&self.provided_len.to_le_bytes());\n\n colour_buf.extend(&self.provided_len.to_le_bytes());\n\n for c in self.into_iter() {\n\n cube_buf.extend(&c.dump_cube_data());\n\n colour_buf.extend(&c.dump_colour_data());\n\n }\n\n (cube_buf, colour_buf)\n\n }\n\n \n\n /// Get the actual amount of cubes.\n\n ///\n\n /// This differs from `provided_len` by being the amount of cubes parsed (successfully), instead of something parsed from block data.\n\n /// For any valid robot data, `data.provided_len == data.len()`.\n", "file_path": "src/robocraft/cubes.rs", "rank": 69, "score": 7.909563658988659 }, { "content": " self\n\n }\n\n \n\n /// Set fields which text filter searches\n\n pub fn text_search_type(mut self, search_type: FactoryTextSearchType) -> Self {\n\n self.payload.text_search_field = search_type as isize;\n\n self\n\n }\n\n \n\n // setting buyable to false while using the default token provider will cause HTTP status 500 error\n\n /// Only search robots which can be bought by the current account?\n\n pub fn buyable(mut self, b: bool) -> Self {\n\n self.payload.buyable = b;\n\n self\n\n }\n\n \n\n /// Prepend a featured robot to the response?\n\n pub fn prepend_featured(mut self, b: bool) -> Self {\n\n self.payload.prepend_featured_robot = b;\n\n self\n", "file_path": "src/robocraft_simple/factory_request_builder.rs", "rank": 70, "score": 7.897825997763528 }, { "content": "use reqwest::{Client, Error};\n\nuse url::{Url};\n\n\n\nuse crate::robocraft::{ITokenProvider, DefaultTokenProvider, FactoryInfo, FactorySearchBuilder, RoboShopItemsInfo, FactoryRobotGetInfo};\n\nuse crate::robocraft::factory_json::ListPayload;\n\n\n\n/// Community Factory Robot root URL\n\npub const FACTORY_DOMAIN: &str = \"https://factory.robocraftgame.com/\";\n\n\n\n/// CRF API implementation\n\npub struct FactoryAPI {\n\n client: Client,\n\n token: Box<dyn ITokenProvider>,\n\n}\n\n\n\nimpl FactoryAPI {\n\n /// Create a new instance, using `DefaultTokenProvider`.\n\n pub fn new() -> FactoryAPI {\n\n FactoryAPI {\n\n client: Client::new(),\n", "file_path": "src/robocraft/factory.rs", "rank": 71, "score": 7.800397816496569 }, { "content": " /// Order list by order_type\n\n pub fn order(mut self, order_type: FactoryOrderType) -> Self {\n\n self.payload.order = order_type as isize;\n\n self\n\n }\n\n \n\n /* // this appears to not do anything (removed to prevent confusion)\n\n // use text_search_type(FactoryTextSearchType::Player) instead\n\n pub fn players_only(mut self, p: bool) -> Self {\n\n self.payload.player_filter = p;\n\n self\n\n }\n\n */\n\n \n\n /// Retrieve items with movement type.\n\n ///\n\n /// Multiple calls to this function will cause logical OR behaviour.\n\n /// e.g. results will contain robots with Wheels OR Aerofoils (or both).\n\n pub fn movement_or(mut self, movement_type: FactoryMovementType) -> Self {\n\n if self.payload.movement_filter == \"\" {\n", "file_path": "src/robocraft/factory_request_builder.rs", "rank": 72, "score": 7.638856275187019 }, { "content": "use std::convert::AsRef;\n\n\n\nuse crate::techblox::{SerializedEntityDescriptor, Parsable, SerializedEntityComponent,\n\nblocks::{BlockEntity, Block}};\n\nuse libfj_parsable_macro_derive::*;\n\n\n\n/// Tire entity descriptor\n\n#[derive(Copy, Clone, Parsable)]\n\npub struct TyreEntity {\n\n /// parent block entity\n\n pub block: BlockEntity,\n\n}\n\n\n\nimpl SerializedEntityDescriptor for TyreEntity {\n\n fn serialized_components() -> u8 {\n\n BlockEntity::serialized_components()\n\n }\n\n\n\n fn components<'a>(&'a self) -> Vec<&'a dyn SerializedEntityComponent> {\n\n self.block.components()\n", "file_path": "src/techblox/blocks/tyre.rs", "rank": 73, "score": 7.557332582660521 }, { "content": " }\n\n }\n\n\n\n /// Create a new instance and login using email\n\n pub async fn login_email(email: &str, password: &str) -> Result<LiveAPI, Error> {\n\n let mut instance = LiveAPI::new();\n\n let result = instance.authenticate_email(email, password).await;\n\n if let Ok(response) = result {\n\n instance.auth = Some(response);\n\n return Ok(instance);\n\n } else {\n\n return Err(result.err().unwrap());\n\n }\n\n }\n\n \n\n /// Login using email and password\n\n pub async fn authenticate_email(&mut self, email: &str, password: &str) -> Result<AuthenticationInfo, Error> {\n\n let url = Url::parse(AUTHENTICATION_DOMAIN)\n\n .unwrap()\n\n .join(\"api/auth/authenticate\")\n", "file_path": "src/cardlife/live.rs", "rank": 74, "score": 7.524724834189589 }, { "content": " }\n\n\n\n fn components<'a>(&'a self) -> Vec<&'a dyn SerializedEntityComponent> {\n\n let mut c = self.block.components();\n\n c.push(&self.tweak_component);\n\n c.push(&self.joint_component);\n\n return c;\n\n }\n\n\n\n fn components_mut<'a>(&'a mut self) -> Vec<&'a mut dyn SerializedEntityComponent> {\n\n let mut c = self.block.components_mut();\n\n c.push(&mut self.tweak_component);\n\n c.push(&mut self.joint_component);\n\n return c;\n\n }\n\n\n\n fn hash_name(&self) -> u32 {\n\n Self::hash(\"WheelRigEntityDescriptor\") // 1156723746\n\n }\n\n}\n", "file_path": "src/techblox/blocks/wheel_rig.rs", "rank": 75, "score": 7.473148228842055 }, { "content": "use std::convert::AsRef;\n\n\n\nuse crate::techblox::{SerializedEntityDescriptor, Parsable, SerializedEntityComponent, blocks::{BlockEntity, Block}};\n\nuse libfj_parsable_macro_derive::*;\n\n\n\n/// Pilot seat entity descriptor (V4)\n\n#[derive(Copy, Clone, Parsable)]\n\npub struct PilotSeatEntity {\n\n /// parent block entity\n\n pub block: BlockEntity,\n\n /// Seat following camera component\n\n pub cam_component: SeatFollowCamComponent,\n\n}\n\n\n\nimpl SerializedEntityDescriptor for PilotSeatEntity {\n\n fn serialized_components() -> u8 {\n\n BlockEntity::serialized_components() + 1\n\n }\n\n\n\n fn components<'a>(&'a self) -> Vec<&'a dyn SerializedEntityComponent> {\n", "file_path": "src/techblox/blocks/pilot_seat.rs", "rank": 76, "score": 7.445423014836685 }, { "content": " WheelRigEntity::serialized_components() + 1\n\n }\n\n\n\n fn components<'a>(&'a self) -> Vec<&'a dyn SerializedEntityComponent> {\n\n let mut c = self.block.components();\n\n c.push(&self.tweak_component);\n\n return c;\n\n }\n\n\n\n fn components_mut<'a>(&'a mut self) -> Vec<&'a mut dyn SerializedEntityComponent> {\n\n let mut c = self.block.components_mut();\n\n c.push(&mut self.tweak_component);\n\n return c;\n\n }\n\n\n\n fn hash_name(&self) -> u32 {\n\n Self::hash(\"WheelRigSteerableEntityDescriptor\") // 1864425618\n\n }\n\n}\n\n\n", "file_path": "src/techblox/blocks/wheel_rig.rs", "rank": 77, "score": 7.419126344620569 }, { "content": "use std::convert::AsRef;\n\n\n\nuse crate::techblox::{SerializedEntityDescriptor, Parsable, SerializedEntityComponent,\n\nblocks::{BlockEntity, Block}};\n\nuse libfj_parsable_macro_derive::*;\n\n\n\n/// Joint block entity descriptor\n\n#[derive(Copy, Clone, Parsable)]\n\npub struct JointBlockEntity {\n\n /// parent block entity\n\n pub block: BlockEntity,\n\n}\n\n\n\nimpl SerializedEntityDescriptor for JointBlockEntity {\n\n fn serialized_components() -> u8 {\n\n BlockEntity::serialized_components()\n\n }\n\n\n\n fn components<'a>(&'a self) -> Vec<&'a dyn SerializedEntityComponent> {\n\n self.block.components()\n", "file_path": "src/techblox/blocks/joint.rs", "rank": 78, "score": 7.418507453354648 }, { "content": " }\n\n\n\n fn components<'a>(&'a self) -> Vec<&'a dyn SerializedEntityComponent> {\n\n let mut c = self.block.components();\n\n c.push(&self.tweak_component);\n\n c.push(&self.spring_component);\n\n return c;\n\n }\n\n\n\n fn components_mut<'a>(&'a mut self) -> Vec<&'a mut dyn SerializedEntityComponent> {\n\n let mut c = self.block.components_mut();\n\n c.push(&mut self.tweak_component);\n\n c.push(&mut self.spring_component);\n\n return c;\n\n }\n\n\n\n fn hash_name(&self) -> u32 {\n\n Self::hash(\"DampedAngularSpringEntityDescriptorV4\") // 3789998433\n\n }\n\n}\n", "file_path": "src/techblox/blocks/spring.rs", "rank": 79, "score": 7.409348028461849 }, { "content": "use ureq::{Agent, Error, Response};\n\nuse url::Url;\n\nuse serde_json::{to_string};\n\n\n\nuse crate::robocraft::{ITokenProvider, DefaultTokenProvider, FACTORY_DOMAIN, FactoryInfo, RoboShopItemsInfo, FactoryRobotGetInfo};\n\nuse crate::robocraft::{ListPayload};\n\nuse crate::robocraft_simple::FactorySearchBuilder;\n\n\n\n/// Simpler CRF API implementation.\n\n/// Refer to libfj::robocraft::FactoryAPI for in-depth documentation.\n\n/// The only API difference is that this API is blocking (i.e. no async).\n\n/// This version also works with Wine and Proton since it does not rely on tokio.\n\npub struct FactoryAPI {\n\n client: Agent,\n\n token: Box<dyn ITokenProvider>,\n\n}\n\n\n\nimpl FactoryAPI {\n\n /// Create a new instance using `DefaultTokenProvider`.\n\n pub fn new() -> FactoryAPI {\n", "file_path": "src/robocraft_simple/factory.rs", "rank": 80, "score": 7.260620748130334 }, { "content": " fn components<'a>(&'a self) -> Vec<&'a dyn SerializedEntityComponent> {\n\n let mut c = self.block.components();\n\n c.push(&self.tweak_component);\n\n return c;\n\n }\n\n\n\n fn components_mut<'a>(&'a mut self) -> Vec<&'a mut dyn SerializedEntityComponent> {\n\n let mut c = self.block.components_mut();\n\n c.push(&mut self.tweak_component);\n\n return c;\n\n }\n\n\n\n fn hash_name(&self) -> u32 {\n\n Self::hash(\"EngineBlockEntityDescriptor\") // 1757314505\n\n }\n\n}\n\n\n\nimpl AsRef<BlockEntity> for EngineBlockEntity {\n\n fn as_ref(&self) -> &BlockEntity {\n\n &self.block\n", "file_path": "src/techblox/blocks/engine.rs", "rank": 81, "score": 7.255291055733656 }, { "content": "pub use joint::{JointBlockEntity};\n\npub use pilot_seat::{PilotSeatEntity, SeatFollowCamComponent};\n\npub use passenger_seat::PassengerSeatEntity;\n\npub(crate) use lookup_tables::*;\n\npub use spring::{DampedAngularSpringEntity, TweakableJointDampingComponent, DampedAngularSpringROStruct,\n\nDampedSpringEntity, DampedSpringROStruct};\n\npub use tyre::{TyreEntity};\n\npub use wheel_rig::{WheelRigEntity, WheelRigTweakableStruct, WheelRigSteerableEntity, WheelRigSteerableTweakableStruct};\n\npub use wire_entity::{SerializedWireEntity, WireSaveDataStruct, SerializedGlobalWireSettingsEntity, GlobalWireSettingsEntityStruct};\n", "file_path": "src/techblox/blocks/mod.rs", "rank": 82, "score": 7.230585428564488 }, { "content": "impl SerializedEntityDescriptor for DampedSpringEntity {\n\n fn serialized_components() -> u8 {\n\n BlockEntity::serialized_components() + 2\n\n }\n\n\n\n fn components<'a>(&'a self) -> Vec<&'a dyn SerializedEntityComponent> {\n\n let mut c = self.block.components();\n\n c.push(&self.tweak_component);\n\n c.push(&self.spring_component);\n\n return c;\n\n }\n\n\n\n fn components_mut<'a>(&'a mut self) -> Vec<&'a mut dyn SerializedEntityComponent> {\n\n let mut c = self.block.components_mut();\n\n c.push(&mut self.tweak_component);\n\n c.push(&mut self.spring_component);\n\n return c;\n\n }\n\n\n\n fn hash_name(&self) -> u32 {\n", "file_path": "src/techblox/blocks/spring.rs", "rank": 83, "score": 7.225846996808462 }, { "content": "use crate::techblox::{SerializedEntityComponent, SerializedEntityDescriptor, Parsable};\n\n\n\nuse libfj_parsable_macro_derive::*;\n\n\n\n/// Wire save data\n\n#[derive(Copy, Clone, Parsable)]\n\npub struct SerializedWireEntity {\n\n /// Wiring save data component\n\n pub save_data_component: WireSaveDataStruct,\n\n}\n\n\n\nimpl SerializedEntityDescriptor for SerializedWireEntity {\n\n fn serialized_components() -> u8 {\n\n 1\n\n }\n\n\n\n fn components<'a>(&'a self) -> Vec<&'a dyn SerializedEntityComponent> {\n\n vec![&self.save_data_component]\n\n }\n\n\n", "file_path": "src/techblox/blocks/wire_entity.rs", "rank": 84, "score": 7.215385511447453 }, { "content": " pub fn max_cpu(mut self, max: isize) -> Self {\n\n self.payload.maximum_cpu = max;\n\n self\n\n }\n\n \n\n /// Removem minimum CPU limit\n\n pub fn no_minimum_cpu(mut self) -> Self {\n\n self.payload.minimum_cpu = -1;\n\n self\n\n }\n\n \n\n /// Remove maximum CPU limit\n\n pub fn no_maximum_cpu(mut self) -> Self {\n\n self.payload.maximum_cpu = -1;\n\n self\n\n }\n\n \n\n /// Set text filter\n\n pub fn text(mut self, t: String) -> Self {\n\n self.payload.text_filter = t;\n", "file_path": "src/robocraft_simple/factory_request_builder.rs", "rank": 85, "score": 7.183551146738871 }, { "content": " fn components<'a>(&'a self) -> Vec<&'a dyn SerializedEntityComponent> {\n\n let mut c = self.block.components();\n\n c.push(&self.cam_component);\n\n return c;\n\n }\n\n\n\n fn components_mut<'a>(&'a mut self) -> Vec<&'a mut dyn SerializedEntityComponent> {\n\n let mut c = self.block.components_mut();\n\n c.push(&mut self.cam_component);\n\n return c;\n\n }\n\n\n\n fn hash_name(&self) -> u32 {\n\n Self::hash(\"PassengerSeatEntityDescriptorV4\") // 1360086092\n\n }\n\n}\n\n\n\nimpl AsRef<BlockEntity> for PassengerSeatEntity {\n\n fn as_ref(&self) -> &BlockEntity {\n\n &self.block\n\n }\n\n}\n\n\n\nimpl Block for PassengerSeatEntity {}\n", "file_path": "src/techblox/blocks/passenger_seat.rs", "rank": 86, "score": 7.069742352217905 }, { "content": " pub cube_len: u32,\n\n\n\n /// Maximum block entity identifier in the game save.\n\n /// Not used for deserialization so not required to be correct.\n\n pub max_entity_id: u32,\n\n\n\n /// Amount of block groups, as claimed by the file header.\n\n pub group_len: u32,\n\n\n\n /// Entity group descriptors for block group entities.\n\n pub group_headers: Vec<EntityHeader>,\n\n\n\n /// Block group entities.\n\n pub cube_groups: Vec<BlockGroupEntity>,\n\n\n\n /// Entity group descriptors for block entities.\n\n pub cube_headers: Vec<EntityHeader>,\n\n\n\n /// Blocks\n\n pub cube_entities: Vec<Box<dyn Block>>,\n", "file_path": "src/techblox/gamesave.rs", "rank": 87, "score": 7.059971573818728 }, { "content": "//! Techblox APIs and functionality (WIP).\n\n\n\npub mod blocks;\n\nmod camera;\n\nmod gamesave;\n\nmod entity_header;\n\nmod entity_traits;\n\nmod block_group_entity;\n\nmod unity_types;\n\n#[allow(dead_code)]\n\nmod parsing_tools;\n\nmod murmur;\n\n\n\npub use camera::{SerializedFlyCamEntity, SerializedRigidBodyEntityStruct,\n\nSerializedPhysicsCameraEntity, SerializedCameraEntityStruct};\n\npub use gamesave::{GameSave};\n\npub use entity_header::{EntityHeader, EntityGroupID};\n\npub use entity_traits::{Parsable, SerializedEntityComponent, SerializedEntityDescriptor};\n\npub use block_group_entity::{BlockGroupEntity, BlockGroupTransformEntityComponent, SavedBlockGroupIdComponent};\n\npub use unity_types::{UnityFloat3, UnityHalf3, UnityFloat4, UnityQuaternion, UnityFloat4x4};\n\npub(crate) use parsing_tools::*;\n\npub(crate) use murmur::*;\n", "file_path": "src/techblox/mod.rs", "rank": 88, "score": 7.031449201484708 }, { "content": "//! Cardlife vanilla and modded (CLre) APIs (WIP).\n\n//! LiveAPI and CLreServer are mostly complete, but some other APIs are missing.\n\n\n\nmod client;\n\n\n\nmod server;\n\nmod server_json;\n\npub use self::server_json::{GameInfo, StatusInfo};\n\npub use self::server::{CLreServer};\n\n\n\nmod live;\n\nmod live_json;\n\npub use self::live::{LiveAPI};\n\npub use self::live_json::{AuthenticationInfo, LobbyInfo, LiveGameInfo};\n\npub(crate) use self::live_json::{AuthenticationPayload, LobbyPayload};\n", "file_path": "src/cardlife/mod.rs", "rank": 89, "score": 6.971722152116537 }, { "content": "use crate::techblox::{Parsable};\n\nuse libfj_parsable_macro_derive::*;\n\nuse half::f16;\n\n\n\n/// Unity-like floating-point vector for 3-dimensional space.\n\n#[derive(Clone, Copy, Parsable)]\n\npub struct UnityFloat3 {\n\n /// x coordinate\n\n pub x: f32,\n\n /// y coordinate\n\n pub y: f32,\n\n /// z coordinate\n\n pub z: f32,\n\n}\n\n\n\n/// Unity-like half-precision vector for 3-dimensional space.\n\n#[derive(Clone, Copy, Parsable)]\n\npub struct UnityHalf3 {\n\n /// x coordinate\n\n pub x: f16,\n", "file_path": "src/techblox/unity_types.rs", "rank": 90, "score": 6.968324028581046 }, { "content": " pub flycam_entity: SerializedFlyCamEntity,\n\n\n\n /// Entity group descriptor for player simulation mode camera\n\n pub phycam_header: EntityHeader,\n\n\n\n /// Player simulation mode camera\n\n pub phycam_entity: SerializedPhysicsCameraEntity,\n\n}\n\n\n\nimpl Parsable for GameSave {\n\n /// Process a Techblox save file from raw bytes.\n\n fn parse(data: &mut dyn Read) -> std::io::Result<Self> {\n\n // parse version\n\n let year = parse_u32(data)?; // parsed as i32 in-game for some reason\n\n let month = parse_u32(data)?;\n\n let day = parse_u32(data)?;\n\n let date = NaiveDate::from_ymd(year as i32, month, day);\n\n let ticks = parse_i64(data)?; // unused\n\n let cube_count = parse_u32(data)?; // parsed as i32 in-game for some reason\n\n let max_e_id = parse_u32(data)?; // unused\n", "file_path": "src/techblox/gamesave.rs", "rank": 91, "score": 6.937150611855193 }, { "content": "use crate::techblox::{SerializedEntityDescriptor, Parsable, SerializedEntityComponent, UnityFloat3, UnityHalf3};\n\n\n\nuse libfj_parsable_macro_derive::*;\n\n\n\n/// Player editing camera entity descriptor.\n\n#[derive(Copy, Clone, Parsable)]\n\npub struct SerializedFlyCamEntity {\n\n /// Player camera in-game location\n\n pub rb_component: SerializedRigidBodyEntityStruct,\n\n}\n\n\n\nimpl SerializedEntityDescriptor for SerializedFlyCamEntity {\n\n fn serialized_components() -> u8 {\n\n 2\n\n }\n\n\n\n fn components<'a>(&'a self) -> Vec<&'a dyn SerializedEntityComponent> {\n\n vec![&self.rb_component]\n\n }\n\n\n", "file_path": "src/techblox/camera.rs", "rank": 92, "score": 6.879014695647632 }, { "content": " token: Box::new(DefaultTokenProvider{}),\n\n }\n\n }\n\n \n\n /// Create a new instance using the provided token provider.\n\n pub fn with_auth(token_provider: Box<dyn ITokenProvider>) -> FactoryAPI {\n\n FactoryAPI {\n\n client: Client::new(),\n\n token: token_provider,\n\n }\n\n }\n\n \n\n /// Retrieve CRF robots on the main page.\n\n ///\n\n /// For searching, use `list_builder()` instead.\n\n pub async fn list(&self) -> Result<FactoryInfo<RoboShopItemsInfo>, Error> {\n\n let url = Url::parse(FACTORY_DOMAIN)\n\n .unwrap()\n\n .join(\"/api/roboShopItems/list\")\n\n .unwrap();\n", "file_path": "src/robocraft/factory.rs", "rank": 93, "score": 6.879014695647632 }, { "content": "use crate::techblox::{UnityFloat3, UnityQuaternion, SerializedEntityComponent, SerializedEntityDescriptor, Parsable};\n\nuse libfj_parsable_macro_derive::*;\n\n\n\n/// Block group entity descriptor.\n\n#[derive(Clone, Copy, Parsable)]\n\npub struct BlockGroupEntity {\n\n /// Block group identifier\n\n pub saved_block_group_id: SavedBlockGroupIdComponent,\n\n /// Block group location information\n\n pub block_group_transform: BlockGroupTransformEntityComponent,\n\n}\n\n\n\nimpl BlockGroupEntity {}\n\n\n\nimpl SerializedEntityDescriptor for BlockGroupEntity {\n\n fn serialized_components() -> u8 {\n\n 2\n\n }\n\n\n\n fn components<'a>(&'a self) -> Vec<&'a dyn SerializedEntityComponent> {\n", "file_path": "src/techblox/block_group_entity.rs", "rank": 94, "score": 6.825931177243287 }, { "content": "use serde::{Deserialize, Serialize};\n\nuse ureq::{Agent, Error};\n\nuse serde_json::{to_string, from_slice};\n\n\n\nuse crate::robocraft::ITokenProvider;\n\n\n\n/// Token provider for an existing Robocraft account.\n\n///\n\n/// Steam accounts are not supported.\n\npub struct AuthenticatedTokenProvider {\n\n /// The account's username\n\n pub username: String,\n\n /// The account's password\n\n pub password: String,\n\n /// Ureq HTTP client\n\n client: Agent,\n\n}\n\n\n\nimpl AuthenticatedTokenProvider {\n\n pub fn with_email(email: &str, password: &str) -> Result<Self, Error> {\n", "file_path": "src/robocraft/account.rs", "rank": 95, "score": 6.772079691747928 }, { "content": "//! Simple, blocking Robocraft API\n\n\n\nmod factory;\n\nmod factory_request_builder;\n\npub use factory::{FactoryAPI};\n\npub use factory_request_builder::{FactorySearchBuilder};\n", "file_path": "src/robocraft_simple/mod.rs", "rank": 96, "score": 6.744075279537219 }, { "content": " self\n\n }\n\n \n\n /// Retrieve items with any maximum CPU\n\n pub fn no_maximum_cpu(mut self) -> Self {\n\n self.payload.maximum_cpu = -1;\n\n self\n\n }\n\n \n\n /// Retrieve items which match text\n\n pub fn text(mut self, t: String) -> Self {\n\n self.payload.text_filter = t;\n\n self\n\n }\n\n \n\n /// Text filter searches search_type\n\n pub fn text_search_type(mut self, search_type: FactoryTextSearchType) -> Self {\n\n self.payload.text_search_field = search_type as isize;\n\n self\n\n }\n", "file_path": "src/robocraft/factory_request_builder.rs", "rank": 97, "score": 6.553996387568952 }, { "content": " let mut c = self.block.components();\n\n c.push(&self.cam_component);\n\n return c;\n\n }\n\n\n\n fn components_mut<'a>(&'a mut self) -> Vec<&'a mut dyn SerializedEntityComponent> {\n\n let mut c = self.block.components_mut();\n\n c.push(&mut self.cam_component);\n\n return c;\n\n }\n\n\n\n fn hash_name(&self) -> u32 {\n\n Self::hash(\"PilotSeatEntityDescriptorV4\") // 2281299333\n\n }\n\n}\n\n\n\nimpl AsRef<BlockEntity> for PilotSeatEntity {\n\n fn as_ref(&self) -> &BlockEntity {\n\n &self.block\n\n }\n", "file_path": "src/techblox/blocks/pilot_seat.rs", "rank": 98, "score": 6.530260224192047 }, { "content": " token,\n\n }\n\n }\n\n \n\n /// Set page number\n\n pub fn page(mut self, page_number: isize) -> Self {\n\n self.payload.page = page_number;\n\n self\n\n }\n\n \n\n /// Set page size\n\n pub fn items_per_page(mut self, page_size: isize) -> Self {\n\n self.payload.page_size = page_size;\n\n self\n\n }\n\n \n\n /// Set results ordering\n\n pub fn order(mut self, order_type: FactoryOrderType) -> Self {\n\n self.payload.order = order_type as isize;\n\n self\n", "file_path": "src/robocraft_simple/factory_request_builder.rs", "rank": 99, "score": 6.519891283333518 } ]
Rust
fork-off/src/fetching.rs
aleph-zero-foundation/aleph-node
7c4e6a4948e661cbe46d8957cf0e0eab901d8ed3
use std::{collections::HashMap, sync::Arc}; use crate::Storage; use futures::future::join_all; use log::info; use parking_lot::Mutex; use reqwest::Client; use serde_json::Value; use crate::types::{BlockHash, Get, StorageKey, StorageValue}; const KEYS_BATCH_SIZE: u32 = 1000; pub struct StateFetcher { client: Client, http_rpc_endpoint: String, } async fn make_request_and_parse_result<T: serde::de::DeserializeOwned>( client: &Client, endpoint: &str, body: Value, ) -> T { let mut response: Value = client .post(endpoint) .json(&body) .send() .await .expect("Storage request has failed") .json() .await .expect("Could not deserialize response as JSON"); let result = response["result"].take(); serde_json::from_value(result).expect("Incompatible type of the result") } fn construct_json_body(method_name: &str, params: Value) -> Value { serde_json::json!({ "jsonrpc": "2.0", "id": 1, "method": method_name, "params": params }) } fn block_hash_body(block_num: Option<u32>) -> Value { let params = serde_json::json!([block_num]); construct_json_body("chain_getBlockHash", params) } fn get_storage_value_body(key: StorageKey, block_hash: Option<BlockHash>) -> Value { let params = serde_json::json!([key.get(), block_hash.map(Get::get)]); construct_json_body("state_getStorage", params) } fn get_keys_paged_body( prefix: StorageKey, count: u32, start_key: Option<StorageKey>, block_hash: Option<BlockHash>, ) -> Value { let params = serde_json::json!([ prefix.get(), count, start_key.map(Get::get), block_hash.map(Get::get) ]); construct_json_body("state_getKeysPaged", params) } impl StateFetcher { pub fn new(http_rpc_endpoint: String) -> Self { StateFetcher { client: Client::new(), http_rpc_endpoint, } } async fn value_fetching_worker( http_rpc_endpoint: String, id: usize, block: BlockHash, input: Arc<Mutex<Vec<StorageKey>>>, output: Arc<Mutex<Storage>>, ) { const LOG_PROGRESS_FREQUENCY: usize = 500; let fetcher = StateFetcher::new(http_rpc_endpoint); loop { let maybe_key = { let mut keys = input.lock(); keys.pop() }; let key = match maybe_key { Some(key) => key, None => break, }; let value = fetcher.get_value(key.clone(), block.clone()).await; let mut output_guard = output.lock(); output_guard.insert(key, value); if output_guard.len() % LOG_PROGRESS_FREQUENCY == 0 { info!("Fetched {} values", output_guard.len()); } } info!("Worker {:?} finished", id); } async fn make_request<T: serde::de::DeserializeOwned>(&self, body: Value) -> T { make_request_and_parse_result::<T>(&self.client, &self.http_rpc_endpoint, body).await } pub async fn get_most_recent_block(&self) -> BlockHash { let body = block_hash_body(None); let block: String = self.make_request(body).await; BlockHash::new(&block) } async fn get_keys_range( &self, count: u32, start_key: Option<StorageKey>, block_hash: Option<BlockHash>, ) -> Vec<StorageKey> { let prefix = StorageKey::new(""); let body = get_keys_paged_body(prefix, count, start_key, block_hash); let keys: Vec<StorageKey> = self.make_request(body).await; keys } async fn get_all_keys(&self, block_hash: BlockHash) -> Vec<StorageKey> { let mut last_key_fetched = None; let mut all_keys = Vec::new(); loop { let new_keys = self .get_keys_range(KEYS_BATCH_SIZE, last_key_fetched, Some(block_hash.clone())) .await; all_keys.extend_from_slice(&new_keys); info!( "Got {} new keys and have {} in total", new_keys.len(), all_keys.len() ); if new_keys.len() < KEYS_BATCH_SIZE as usize { break; } last_key_fetched = Some(new_keys.last().unwrap().clone()); } all_keys } async fn get_value(&self, key: StorageKey, block_hash: BlockHash) -> StorageValue { let body = get_storage_value_body(key, Some(block_hash)); self.make_request(body).await } async fn get_values( &self, keys: Vec<StorageKey>, block_hash: BlockHash, num_workers: u32, ) -> Storage { let n_keys = keys.len(); let input = Arc::new(Mutex::new(keys)); let output = Arc::new(Mutex::new(HashMap::with_capacity(n_keys))); let mut workers = Vec::new(); for id in 0..(num_workers as usize) { workers.push(StateFetcher::value_fetching_worker( self.http_rpc_endpoint.clone(), id, block_hash.clone(), input.clone(), output.clone(), )); } info!("Started {} workers to download values.", workers.len()); join_all(workers).await; assert!(input.lock().is_empty(), "Not all keys were fetched"); let mut guard = output.lock(); std::mem::take(&mut guard) } pub async fn get_full_state_at( &self, num_workers: u32, fetch_block: Option<BlockHash>, ) -> Storage { let block = if let Some(block) = fetch_block { block } else { self.get_most_recent_block().await }; info!("Fetching state at block {:?}", block); let keys = self.get_all_keys(block.clone()).await; self.get_values(keys, block, num_workers).await } pub async fn get_full_state_at_best_block(&self, num_workers: u32) -> Storage { self.get_full_state_at(num_workers, None).await } }
use std::{collections::HashMap, sync::Arc}; use crate::Storage; use futures::future::join_all; use log::info; use parking_lot::Mutex; use reqwest::Client; use serde_json::Value; use crate::types::{BlockHash, Get, StorageKey, StorageValue}; const KEYS_BATCH_SIZE: u32 = 1000; pub struct StateFetcher { client: Client, http_rpc_endpoint: String, } async fn make_request_and_parse_result<T: serde::de::DeserializeOwned>( client: &Client, endpoint: &str, body: Value, ) -> T { let mut response: Value = client .post(endpoint) .json(&body) .send() .await .expect("Storage request has failed") .json() .await .expect("Could not deserialize response as JSON"); let result = response["result"].take(); serde_json::from_value(result).expect("Incompatible type of the result") } fn construct_json_body(method_name: &str, params: Value) -> Value { serde_json::json!({ "jsonrpc": "2.0", "id": 1, "method": method_name, "params": params }) } fn block_hash_body(block_num: Option<u32>) -> Value { let params = serde_json::json!([block_num]); construct_json_body("chain_getBlockHash", params) } fn get_storage_value_body(key: StorageKey, block_hash: Option<BlockHash>) -> Value { let params = serde_json::json!([key.get(), block_hash.map(Get::get)]); construct_json_body("state_getStorage", params) } fn get_keys_paged_body( prefix: StorageKey, count: u32, start_key: Option<StorageKey>, block_hash: Option<BlockHash>, ) -> Value { let params = serde_json::json!([ prefix.get(), count, start_key.map(Get::get), block_hash.map(Get::get) ]); construct_json_body("state_getKeysPaged", params) } impl StateFetcher { pub fn new(http_rpc_endpoint: String) -> Self { StateFetcher { client: Client::new(), http_rpc_endpoint, } } async fn value_fetching_worker( http_rpc_endpoint: String, id: usize, block: BlockHash, input: Arc<Mutex<Vec<StorageKey>>>, output: Arc<Mutex<Storage>>, ) { const LOG_PROGRESS_FREQUENCY: usize = 500; let fetcher = StateFetcher::new(http_rpc_endpoint); loop { let maybe_key = { let mut keys = input.lock(); keys.pop() }; let key = match maybe_key { Some(key) => key, None => break, }; let value = fetcher.get_value(key.clone(), block.clone()).await; let mut output_guard
, output_guard.len()); } } info!("Worker {:?} finished", id); } async fn make_request<T: serde::de::DeserializeOwned>(&self, body: Value) -> T { make_request_and_parse_result::<T>(&self.client, &self.http_rpc_endpoint, body).await } pub async fn get_most_recent_block(&self) -> BlockHash { let body = block_hash_body(None); let block: String = self.make_request(body).await; BlockHash::new(&block) } async fn get_keys_range( &self, count: u32, start_key: Option<StorageKey>, block_hash: Option<BlockHash>, ) -> Vec<StorageKey> { let prefix = StorageKey::new(""); let body = get_keys_paged_body(prefix, count, start_key, block_hash); let keys: Vec<StorageKey> = self.make_request(body).await; keys } async fn get_all_keys(&self, block_hash: BlockHash) -> Vec<StorageKey> { let mut last_key_fetched = None; let mut all_keys = Vec::new(); loop { let new_keys = self .get_keys_range(KEYS_BATCH_SIZE, last_key_fetched, Some(block_hash.clone())) .await; all_keys.extend_from_slice(&new_keys); info!( "Got {} new keys and have {} in total", new_keys.len(), all_keys.len() ); if new_keys.len() < KEYS_BATCH_SIZE as usize { break; } last_key_fetched = Some(new_keys.last().unwrap().clone()); } all_keys } async fn get_value(&self, key: StorageKey, block_hash: BlockHash) -> StorageValue { let body = get_storage_value_body(key, Some(block_hash)); self.make_request(body).await } async fn get_values( &self, keys: Vec<StorageKey>, block_hash: BlockHash, num_workers: u32, ) -> Storage { let n_keys = keys.len(); let input = Arc::new(Mutex::new(keys)); let output = Arc::new(Mutex::new(HashMap::with_capacity(n_keys))); let mut workers = Vec::new(); for id in 0..(num_workers as usize) { workers.push(StateFetcher::value_fetching_worker( self.http_rpc_endpoint.clone(), id, block_hash.clone(), input.clone(), output.clone(), )); } info!("Started {} workers to download values.", workers.len()); join_all(workers).await; assert!(input.lock().is_empty(), "Not all keys were fetched"); let mut guard = output.lock(); std::mem::take(&mut guard) } pub async fn get_full_state_at( &self, num_workers: u32, fetch_block: Option<BlockHash>, ) -> Storage { let block = if let Some(block) = fetch_block { block } else { self.get_most_recent_block().await }; info!("Fetching state at block {:?}", block); let keys = self.get_all_keys(block.clone()).await; self.get_values(keys, block, num_workers).await } pub async fn get_full_state_at_best_block(&self, num_workers: u32) -> Storage { self.get_full_state_at(num_workers, None).await } }
= output.lock(); output_guard.insert(key, value); if output_guard.len() % LOG_PROGRESS_FREQUENCY == 0 { info!("Fetched {} values"
function_block-random_span
[ { "content": "fn json_req(method: &str, params: Value, id: u32) -> Value {\n\n json!({\n\n \"method\": method,\n\n \"params\": params,\n\n \"jsonrpc\": \"2.0\",\n\n \"id\": id.to_string(),\n\n })\n\n}\n\n\n", "file_path": "aleph-client/src/rpc.rs", "rank": 0, "score": 517468.0964673677 }, { "content": "/// Computes hash of given pallet's call. You can use that to pass result to `state.getKeys` RPC call.\n\n/// * `pallet` name of the pallet\n\n/// * `call` name of the pallet's call\n\n///\n\n/// # Example\n\n/// ```\n\n/// use aleph_client::get_storage_key;\n\n///\n\n/// let staking_nominate_storage_key = get_storage_key(\"Staking\", \"Nominators\");\n\n/// assert_eq!(staking_nominate_storage_key, String::from(\"5f3e4907f716ac89b6347d15ececedca9c6a637f62ae2af1c7e31eed7e96be04\"));\n\n/// ```\n\npub fn get_storage_key(pallet: &str, call: &str) -> String {\n\n let bytes = storage_key(pallet, call);\n\n let storage_key = StorageKey(bytes.into());\n\n hex::encode(storage_key.0)\n\n}\n", "file_path": "aleph-client/src/lib.rs", "rank": 1, "score": 418154.1460007492 }, { "content": "pub fn rotate_keys_raw_result<C: AnyConnection>(connection: &C) -> Result<String, &'static str> {\n\n // we need to escape two characters from RPC result which is escaped quote\n\n rotate_keys_base(connection, |keys| Some(keys.trim_matches('\\\"').to_string()))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn given_some_input_when_state_query_storage_at_json_then_json_is_as_expected() {\n\n let storage_keys = vec![\n\n StorageKey(vec![0, 1, 2, 3, 4, 5]),\n\n StorageKey(vec![9, 8, 7, 6, 5]),\n\n ];\n\n let expected_json_string = r#\"\n\n{\n\n \"id\": \"1\",\n\n \"jsonrpc\": \"2.0\",\n\n \"method\":\"state_queryStorageAt\",\n", "file_path": "aleph-client/src/rpc.rs", "rank": 3, "score": 404356.8488919007 }, { "content": "fn construct_json_body(method_name: &str, params: Value) -> Value {\n\n serde_json::json!({\n\n \"jsonrpc\": \"2.0\",\n\n \"id\": 1,\n\n \"method\": method_name,\n\n \"params\": params\n\n })\n\n}\n\n\n", "file_path": "peer-verification/src/verifier.rs", "rank": 5, "score": 355531.18503144075 }, { "content": "pub fn rotate_keys<C: AnyConnection>(connection: &C) -> Result<SessionKeys, &'static str> {\n\n rotate_keys_base(connection, |keys| match SessionKeys::try_from(keys) {\n\n Ok(keys) => Some(keys),\n\n Err(_) => None,\n\n })\n\n}\n\n\n", "file_path": "aleph-client/src/rpc.rs", "rank": 6, "score": 343072.2803054753 }, { "content": "pub fn keypair_from_string(seed: &str) -> KeyPair {\n\n KeyPair::from_string(seed, None).expect(\"Can't create pair from seed value\")\n\n}\n\n\n", "file_path": "aleph-client/src/lib.rs", "rank": 7, "score": 342884.01254930673 }, { "content": "pub fn author_rotate_keys_json() -> Value {\n\n json_req(\"author_rotateKeys\", Value::Null, 1)\n\n}\n\n\n", "file_path": "aleph-client/src/rpc.rs", "rank": 8, "score": 320999.8837334994 }, { "content": "/// Merges two vesting schedules (at indices `idx1` and `idx2`) of the signer of `connection`.\n\n///\n\n/// Fails if transaction could not have been sent.\n\n///\n\n/// *Note*: This function returns `Ok(_)` even if the account has no active vesting schedules, or\n\n/// it has fewer schedules than `max(idx1, idx2) - 1` and thus the extrinsic was not successful.\n\npub fn merge_schedules(connection: SignedConnection, idx1: u32, idx2: u32) -> Result<()> {\n\n let who = connection.signer();\n\n let xt = compose_extrinsic!(\n\n connection.as_connection(),\n\n PALLET,\n\n \"merge_schedules\",\n\n idx1,\n\n idx2\n\n );\n\n\n\n let block_hash = try_send_xt(&connection, xt, Some(\"Merge vesting schedules\"), Finalized)?\n\n .expect(\"For `Finalized` status a block hash should be returned\");\n\n\n\n info!(target: \"aleph-client\", \n\n \"Merging vesting schedules (indices: {} and {}) for the account {:?}. Finalized in block {:?}\", \n\n idx1, idx2, account_from_keypair(&who), block_hash);\n\n Ok(())\n\n}\n", "file_path": "aleph-client/src/vesting.rs", "rank": 9, "score": 320657.535949386 }, { "content": "pub fn read_json_from_file(path: String) -> Value {\n\n let content = file_content(path);\n\n serde_json::from_str(&content).expect(\"Could not deserialize file to json format\")\n\n}\n\n\n", "file_path": "fork-off/src/fsio.rs", "rank": 10, "score": 304699.6558797312 }, { "content": "/// Get the number of the current session.\n\npub fn get_current<C: AnyConnection>(connection: &C) -> u32 {\n\n connection\n\n .as_connection()\n\n .get_storage_value(\"Session\", \"CurrentIndex\", None)\n\n .unwrap()\n\n .unwrap_or(0)\n\n}\n\n\n", "file_path": "aleph-client/src/session.rs", "rank": 11, "score": 288833.28449892567 }, { "content": "fn parse_balances(s: &str) -> Result<(AccountId, Balance), Box<dyn Error + Send + Sync + 'static>> {\n\n let sep_pos = s.find('=').ok_or(\"Invalid ACCOUNT=BALANCE: no `=` found\")?;\n\n\n\n let account_raw: String = s[..sep_pos].parse()?;\n\n let account = AccountId::new(&account_raw);\n\n let balance = s[sep_pos + 1..].parse()?;\n\n Ok((account, balance))\n\n}\n", "file_path": "fork-off/src/config.rs", "rank": 12, "score": 288444.35909232555 }, { "content": "pub fn get_current_era<C: AnyConnection>(connection: &C) -> u32 {\n\n let current_era = connection\n\n .as_connection()\n\n .get_storage_value(\"Staking\", \"ActiveEra\", None)\n\n .expect(\"Failed to decode ActiveEra extrinsic!\")\n\n .expect(\"ActiveEra is empty in the storage!\");\n\n info!(target: \"aleph-client\", \"Current era is {}\", current_era);\n\n current_era\n\n}\n\n\n", "file_path": "aleph-client/src/staking.rs", "rank": 13, "score": 285469.7631954098 }, { "content": "/// Calls `pallet_vesting::vest_other` by the signer of `connection` on behalf of `vest_account`,\n\n/// i.e. makes all unlocked balances of `vest_account` transferable.\n\n///\n\n/// Fails if transaction could not have been sent.\n\n///\n\n/// *Note*: This function returns `Ok(_)` even if the account has no active vesting schedules\n\n/// and thus the extrinsic was not successful. However, semantically it is still correct.\n\npub fn vest_other(connection: SignedConnection, vest_account: AccountId) -> Result<()> {\n\n let xt = compose_extrinsic!(\n\n connection.as_connection(),\n\n PALLET,\n\n \"vest_other\",\n\n GenericAddress::Id(vest_account.clone())\n\n );\n\n let block_hash = try_send_xt(&connection, xt, Some(\"Vesting on behalf\"), Finalized)?\n\n .expect(\"For `Finalized` status a block hash should be returned\");\n\n info!(target: \"aleph-client\", \"Vesting on behalf of the account {:?}. Finalized in block {:?}\", vest_account, block_hash);\n\n Ok(())\n\n}\n\n\n", "file_path": "aleph-client/src/vesting.rs", "rank": 14, "score": 282117.55100327707 }, { "content": "pub fn get_parent<B, C>(client: &C, block: &BlockHashNum<B>) -> Option<BlockHashNum<B>>\n\nwhere\n\n B: BlockT,\n\n C: HeaderBackend<B>,\n\n{\n\n if block.num.is_zero() {\n\n return None;\n\n }\n\n if let Some(header) = client\n\n .header(BlockId::Hash(block.hash))\n\n .expect(\"client must respond\")\n\n {\n\n Some((*header.parent_hash(), block.num - <NumberFor<B>>::one()).into())\n\n } else {\n\n warn!(target: \"aleph-data-store\", \"Trying to fetch the parent of an unknown block {:?}.\", block);\n\n None\n\n }\n\n}\n\n\n", "file_path": "finality-aleph/src/data_io/data_provider.rs", "rank": 15, "score": 282039.9412005105 }, { "content": "pub trait Get<T = String> {\n\n fn get(self) -> T;\n\n}\n\n\n", "file_path": "fork-off/src/types.rs", "rank": 17, "score": 281283.41778710997 }, { "content": "fn start_rpc_client_thread(url: String) -> Result<RunningRpcClient, String> {\n\n let (tx, rx) = std::sync::mpsc::sync_channel(0);\n\n let rpc_client = Arc::new(Mutex::new(None));\n\n let connect_rpc_client = Arc::clone(&rpc_client);\n\n let join = thread::Builder::new()\n\n .name(\"client\".to_owned())\n\n .spawn(|| -> WsResult<()> {\n\n connect(url, move |out| {\n\n tx.send(out).expect(\"main thread was already stopped\");\n\n WsHandler {\n\n next_handler: connect_rpc_client.clone(),\n\n }\n\n })\n\n })\n\n .map_err(|_| \"unable to spawn WebSocket's thread\")?;\n\n let out = rx.recv().map_err(|_| \"WebSocket's unexpectedly died\")?;\n\n Ok(RunningRpcClient {\n\n ws_sender: out,\n\n client_handle: join,\n\n client: rpc_client,\n\n })\n\n}\n\n\n", "file_path": "flooder/src/ws_rpc_client.rs", "rank": 18, "score": 280427.177632418 }, { "content": "pub fn multi_bond(node: &str, bonders: &[KeyPair], stake: Balance) {\n\n bonders.par_iter().for_each(|bonder| {\n\n let connection = create_connection(node)\n\n .set_signer(bonder.clone())\n\n .try_into()\n\n .expect(\"Signer has been set\");\n\n\n\n let controller_account = account_from_keypair(bonder);\n\n bond(&connection, stake, &controller_account, XtStatus::InBlock);\n\n });\n\n}\n\n\n", "file_path": "aleph-client/src/staking.rs", "rank": 19, "score": 278950.2203151389 }, { "content": "fn state_query_storage_at_json(storage_keys: &[StorageKey]) -> Value {\n\n json_req(\n\n \"state_queryStorageAt\",\n\n Value::Array(vec![\n\n Value::Array(\n\n storage_keys\n\n .iter()\n\n .map(|storage_key| Value::String(hex::encode(storage_key)))\n\n .collect::<Vec<_>>(),\n\n ),\n\n Value::Null,\n\n ]),\n\n 1,\n\n )\n\n}\n\n\n", "file_path": "aleph-client/src/rpc.rs", "rank": 20, "score": 278210.0082128633 }, { "content": "/// Returns the address extended by the peer id, unless it already contained another peer id.\n\npub fn add_matching_peer_id(mut address: Multiaddr, peer_id: PeerId) -> Option<Multiaddr> {\n\n match get_peer_id(&address) {\n\n Some(peer) => match peer == peer_id {\n\n true => Some(address),\n\n false => None,\n\n },\n\n None => {\n\n address.0.push(Protocol::P2p(peer_id.0.into()));\n\n Some(address)\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{add_matching_peer_id, get_common_peer_id, get_peer_id, is_p2p};\n\n use crate::network::manager::testing::address;\n\n\n\n #[test]\n\n fn non_p2p_addresses_are_not_p2p() {\n", "file_path": "finality-aleph/src/network/manager/addresses.rs", "rank": 21, "score": 276330.6092708938 }, { "content": "pub fn get_payout_for_era<C: AnyConnection>(connection: &C, era: u32) -> u128 {\n\n connection\n\n .as_connection()\n\n .get_storage_map(\"Staking\", \"ErasValidatorReward\", era, None)\n\n .expect(\"Failed to decode ErasValidatorReward\")\n\n .expect(\"ErasValidatoReward is empty in the storage\")\n\n}\n", "file_path": "aleph-client/src/staking.rs", "rank": 22, "score": 272473.12257318577 }, { "content": "/// Unless `address` already contains protocol, we prepend to it `ws://`.\n\nfn ensure_protocol(address: &str) -> String {\n\n if address.starts_with(&Protocol::Ws.to_string())\n\n || address.starts_with(&Protocol::Wss.to_string())\n\n {\n\n return address.to_string();\n\n }\n\n format!(\"{}{}\", Protocol::default().to_string(), address)\n\n}\n\n\n", "file_path": "aleph-client/src/lib.rs", "rank": 23, "score": 271223.45714120264 }, { "content": "pub fn create_custom_connection<Client: FromStr + RpcClient>(\n\n address: &str,\n\n) -> Result<Api<sr25519::Pair, Client, PlainTipExtrinsicParams>, <Client as FromStr>::Err> {\n\n loop {\n\n let client = Client::from_str(&ensure_protocol(address))?;\n\n match Api::<sr25519::Pair, _, _>::new(client) {\n\n Ok(api) => return Ok(api),\n\n Err(why) => {\n\n warn!(\n\n \"[+] Can't create_connection because {:?}, will try again in 1s\",\n\n why\n\n );\n\n sleep(Duration::from_millis(1000));\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "aleph-client/src/lib.rs", "rank": 24, "score": 270689.9266645373 }, { "content": "pub fn wait_for_next_era<C: AnyConnection>(connection: &C) -> anyhow::Result<BlockNumber> {\n\n wait_for_era_completion(connection, get_current_era(connection) + 1)\n\n}\n\n\n", "file_path": "aleph-client/src/staking.rs", "rank": 25, "score": 269279.649514893 }, { "content": "pub fn account_from_keypair(keypair: &KeyPair) -> AccountId {\n\n AccountId::from(keypair.public())\n\n}\n\n\n", "file_path": "aleph-client/src/lib.rs", "rank": 26, "score": 264368.77666365134 }, { "content": "fn entry_prompt(name: &'static str) -> String {\n\n format!(\"----{}\", name)\n\n}\n\n\n", "file_path": "aleph-client/src/debug/mod.rs", "rank": 27, "score": 260731.61200552667 }, { "content": "fn pallet_prompt(name: &'static str) -> String {\n\n format!(\"-----------{}-----------\", name)\n\n}\n\n\n", "file_path": "aleph-client/src/debug/mod.rs", "rank": 28, "score": 260731.61200552667 }, { "content": "pub fn create_connection(address: &str) -> Connection {\n\n create_custom_connection(address).expect(\"Connection should be created\")\n\n}\n\n\n", "file_path": "aleph-client/src/lib.rs", "rank": 29, "score": 260728.49147708376 }, { "content": "/// Calls `pallet_vesting::vest` for the signer of `connection`, i.e. makes all unlocked balances\n\n/// transferable.\n\n///\n\n/// Fails if transaction could not have been sent.\n\n///\n\n/// *Note*: This function returns `Ok(_)` even if the account has no active vesting schedules\n\n/// and thus the extrinsic was not successful. However, semantically it is still correct.\n\npub fn vest(connection: SignedConnection) -> Result<()> {\n\n let vester = connection.signer();\n\n let xt = compose_extrinsic!(connection.as_connection(), PALLET, \"vest\");\n\n let block_hash = try_send_xt(&connection, xt, Some(\"Vesting\"), Finalized)?\n\n .expect(\"For `Finalized` status a block hash should be returned\");\n\n info!(\n\n target: \"aleph-client\", \"Vesting for the account {:?}. Finalized in block {:?}\",\n\n account_from_keypair(&vester), block_hash\n\n );\n\n Ok(())\n\n}\n\n\n", "file_path": "aleph-client/src/vesting.rs", "rank": 30, "score": 260472.4387547652 }, { "content": "pub fn accounts_seeds_to_keys(seeds: &[String]) -> Vec<KeyPair> {\n\n seeds\n\n .iter()\n\n .map(String::as_str)\n\n .map(keypair_from_string)\n\n .collect()\n\n}\n\n\n", "file_path": "e2e-tests/src/accounts.rs", "rank": 31, "score": 259691.0393107081 }, { "content": "/// Abstraction for requesting justifications for finalized blocks and stale blocks.\n\npub trait RequestBlocks<B: Block>: Clone + Send + Sync + 'static {\n\n /// Request the justification for the given block\n\n fn request_justification(&self, hash: &B::Hash, number: NumberFor<B>);\n\n\n\n /// Request the given block -- this is supposed to be used only for \"old forks\".\n\n fn request_stale_block(&self, hash: B::Hash, number: NumberFor<B>);\n\n\n\n /// Clear all pending justification requests. We need this function in case\n\n /// we requested a justification for a block, which will never get it.\n\n fn clear_justification_requests(&self);\n\n}\n\n\n\n/// What do do with a specific piece of data.\n\n/// Note that broadcast does not specify the protocol, as we only broadcast Generic messages in this sense.\n\n#[derive(Debug, PartialEq, Eq, Clone)]\n\npub enum DataCommand {\n\n Broadcast,\n\n SendTo(PeerId, Protocol),\n\n}\n\n\n", "file_path": "finality-aleph/src/network/mod.rs", "rank": 32, "score": 255264.10913325747 }, { "content": "// this should be extracted to common code\n\npub fn get_validators_seeds(config: &Config) -> Vec<String> {\n\n match config.validators_seeds {\n\n Some(ref seeds) => seeds.clone(),\n\n None => (0..config.validators_count)\n\n .map(|seed| format!(\"//{}\", seed))\n\n .collect(),\n\n }\n\n}\n\n\n", "file_path": "e2e-tests/src/accounts.rs", "rank": 33, "score": 251496.335927956 }, { "content": "fn send_proposals_of_each_len(blocks: Vec<Block>, test_handler: &mut TestHandler) {\n\n for i in 1..=MAX_DATA_BRANCH_LEN {\n\n let blocks_branch = blocks[0..(i as usize)].to_vec();\n\n let test_data: TestData = vec![aleph_data_from_blocks(blocks_branch)];\n\n test_handler.send_data(test_data.clone());\n\n }\n\n}\n\n\n\n#[tokio::test]\n\nasync fn correct_messages_go_through_with_late_import() {\n\n run_test(|mut test_handler| async move {\n\n let blocks = test_handler\n\n .initialize_single_branch(MAX_DATA_BRANCH_LEN * 10)\n\n .await;\n\n\n\n send_proposals_of_each_len(blocks.clone(), &mut test_handler);\n\n\n\n test_handler\n\n .assert_no_message_out(\"Data Store let through a message with not yet imported blocks\")\n\n .await;\n", "file_path": "finality-aleph/src/testing/data_store.rs", "rank": 34, "score": 249268.2423785277 }, { "content": "pub fn derive_user_account_from_numeric_seed(seed: u32) -> KeyPair {\n\n trace!(\"Generating account from numeric seed {}\", seed);\n\n keypair_from_string(&format!(\"//{}\", seed))\n\n}\n\n\n", "file_path": "benches/payout-stakers/src/main.rs", "rank": 35, "score": 247712.44273411616 }, { "content": "pub fn session_id_from_block_num<B: Block>(num: NumberFor<B>, period: SessionPeriod) -> SessionId {\n\n SessionId(num.saturated_into::<u32>() / period.0)\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash, Ord, PartialOrd, Encode, Decode)]\n\npub struct SessionId(pub u32);\n\n\n\n#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash, Ord, PartialOrd, Encode, Decode)]\n\npub struct SessionPeriod(pub u32);\n", "file_path": "finality-aleph/src/session.rs", "rank": 36, "score": 243912.98715753062 }, { "content": "fn storage_key(module: &str, version: &str) -> [u8; 32] {\n\n let pallet_name = sp_core::hashing::twox_128(module.as_bytes());\n\n let postfix = sp_core::hashing::twox_128(version.as_bytes());\n\n let mut final_key = [0u8; 32];\n\n final_key[..16].copy_from_slice(&pallet_name);\n\n final_key[16..].copy_from_slice(&postfix);\n\n final_key\n\n}\n\n\n", "file_path": "aleph-client/src/lib.rs", "rank": 37, "score": 243534.49357466103 }, { "content": "fn treasury_approve(proposal_id: u32, connection: &RootConnection) -> anyhow::Result<()> {\n\n send_treasury_approval(proposal_id, connection);\n\n wait_for_approval(connection, proposal_id)\n\n}\n\n\n", "file_path": "e2e-tests/src/test/treasury.rs", "rank": 38, "score": 242279.95628905465 }, { "content": "fn treasury_reject(proposal_id: u32, connection: &RootConnection) -> anyhow::Result<()> {\n\n let (c, p) = (connection.clone(), proposal_id);\n\n let listener = thread::spawn(move || wait_for_rejection(&c, p));\n\n send_treasury_rejection(proposal_id, connection);\n\n listener.join().unwrap()\n\n}\n\n\n", "file_path": "e2e-tests/src/test/treasury.rs", "rank": 39, "score": 242279.95628905465 }, { "content": "pub fn get_free_balance<C: AnyConnection>(connection: &C, account: &AccountId) -> Balance {\n\n match connection\n\n .as_connection()\n\n .get_account_data(account)\n\n .expect(\"Should be able to access account data\")\n\n {\n\n Some(account_data) => account_data.free,\n\n // Account may have not been initialized yet or liquidated due to the lack of funds.\n\n None => 0,\n\n }\n\n}\n\n\n", "file_path": "aleph-client/src/account.rs", "rank": 40, "score": 242272.5949075654 }, { "content": "pub fn bonded<C: AnyConnection>(connection: &C, stash: &KeyPair) -> Option<AccountId> {\n\n let account_id = AccountId::from(stash.public());\n\n connection\n\n .as_connection()\n\n .get_storage_map(\"Staking\", \"Bonded\", &account_id, None)\n\n .unwrap_or_else(|_| panic!(\"Failed to obtain Bonded for account id {}\", account_id))\n\n}\n\n\n\n/// Since PR #10982 changed `pallet_staking::StakingLedger` to be generic over\n\n/// `T: pallet_staking::Config` (somehow breaking consistency with similar structures in other\n\n/// pallets) we have no easy way of retrieving ledgers from storage. Thus, we chose cloning\n\n/// (relevant part of) this struct instead of implementing `Config` trait.\n\n#[derive(PartialEq, Eq, Clone, Debug, Encode, Decode)]\n\npub struct StakingLedger {\n\n pub stash: AccountId,\n\n #[codec(compact)]\n\n pub total: Balance,\n\n #[codec(compact)]\n\n pub active: Balance,\n\n pub unlocking: BoundedVec<UnlockChunk<Balance>, MaxUnlockingChunks>,\n\n}\n\n\n", "file_path": "aleph-client/src/staking.rs", "rank": 41, "score": 240415.27108864073 }, { "content": "pub fn file_content(path: String) -> String {\n\n fs::read_to_string(&path).unwrap_or_else(|_| panic!(\"Could not read file: `{}`\", path))\n\n}\n\n\n", "file_path": "fork-off/src/fsio.rs", "rank": 42, "score": 239974.84430974466 }, { "content": "pub fn read_phrase(phrase: String) -> String {\n\n let file = PathBuf::from(&phrase);\n\n if file.is_file() {\n\n fs::read_to_string(phrase).unwrap().trim_end().to_owned()\n\n } else {\n\n phrase\n\n }\n\n}\n", "file_path": "flooder/src/config.rs", "rank": 43, "score": 239974.84430974466 }, { "content": "/// Returns all active schedules of `who`. If `who` does not have any active vesting schedules,\n\n/// an empty container is returned.\n\n///\n\n/// Fails if storage could have not been read.\n\npub fn get_schedules<C: AnyConnection>(\n\n connection: &C,\n\n who: AccountId,\n\n) -> Result<Vec<VestingSchedule>> {\n\n connection\n\n .as_connection()\n\n .get_storage_map::<AccountId, Vec<VestingSchedule>>(PALLET, \"Vesting\", who, None)?\n\n .map_or_else(|| Ok(vec![]), Ok)\n\n}\n\n\n", "file_path": "aleph-client/src/vesting.rs", "rank": 44, "score": 234115.56003548688 }, { "content": "pub fn get_sudo_key(config: &Config) -> KeyPair {\n\n keypair_from_string(&config.sudo_seed)\n\n}\n", "file_path": "e2e-tests/src/accounts.rs", "rank": 45, "score": 233949.5279048704 }, { "content": "fn wait_for_rejection<C: AnyConnection>(connection: &C, proposal_id: u32) -> anyhow::Result<()> {\n\n wait_for_event(\n\n connection,\n\n (\"Treasury\", \"Rejected\"),\n\n |e: ProposalRejectedEvent| {\n\n info!(\"[+] Rejected proposal {:?}\", e.proposal_id);\n\n proposal_id.eq(&e.proposal_id)\n\n },\n\n )\n\n .map(|_| ())\n\n}\n", "file_path": "e2e-tests/src/test/treasury.rs", "rank": 46, "score": 233078.77007279635 }, { "content": "fn wait_for_approval<C: AnyConnection>(connection: &C, proposal_id: u32) -> anyhow::Result<()> {\n\n loop {\n\n let approvals: Vec<u32> = connection\n\n .as_connection()\n\n .get_storage_value(\"Treasury\", \"Approvals\", None)\n\n .unwrap()\n\n .unwrap();\n\n if approvals.contains(&proposal_id) {\n\n info!(\"[+] Proposal {:?} approved successfully\", proposal_id);\n\n return Ok(());\n\n } else {\n\n info!(\n\n \"[+] Still waiting for approval for proposal {:?}\",\n\n proposal_id\n\n );\n\n sleep(Duration::from_millis(500))\n\n }\n\n }\n\n}\n\n\n", "file_path": "e2e-tests/src/test/treasury.rs", "rank": 47, "score": 233078.77007279635 }, { "content": "pub fn last_block_of_session<B: Block>(\n\n session_id: SessionId,\n\n period: SessionPeriod,\n\n) -> NumberFor<B> {\n\n ((session_id.0 + 1) * period.0 - 1).into()\n\n}\n\n\n", "file_path": "finality-aleph/src/session.rs", "rank": 48, "score": 232875.4461117471 }, { "content": "pub fn first_block_of_session<B: Block>(\n\n session_id: SessionId,\n\n period: SessionPeriod,\n\n) -> NumberFor<B> {\n\n (session_id.0 * period.0).into()\n\n}\n\n\n", "file_path": "finality-aleph/src/session.rs", "rank": 49, "score": 232875.4461117471 }, { "content": "pub fn wait_for_finalized_block<C: AnyConnection>(\n\n connection: &C,\n\n block_number: u32,\n\n) -> AnyResult<u32> {\n\n let (sender, receiver) = channel();\n\n connection\n\n .as_connection()\n\n .subscribe_finalized_heads(sender)?;\n\n\n\n while let Ok(header) = receiver\n\n .recv()\n\n .map(|h| serde_json::from_str::<Header>(&h).expect(\"Should deserialize header\"))\n\n {\n\n info!(target: \"aleph-client\", \"Received header for a block number {:?}\", header.number);\n\n\n\n if header.number.ge(&block_number) {\n\n return Ok(block_number);\n\n }\n\n }\n\n\n\n Err(anyhow!(\"Waiting for finalization is no longer possible\"))\n\n}\n", "file_path": "aleph-client/src/waiting.rs", "rank": 50, "score": 231073.88679721038 }, { "content": "pub fn new_session_validators(validators: &[u64]) -> impl Iterator<Item = (&u64, AuthorityId)> {\n\n validators\n\n .iter()\n\n .zip(to_authorities(validators).into_iter())\n\n}\n\n\n", "file_path": "pallets/aleph/src/mock.rs", "rank": 51, "score": 231051.82322664166 }, { "content": "pub fn get_validators_keys(config: &Config) -> Vec<KeyPair> {\n\n accounts_seeds_to_keys(&get_validators_seeds(config))\n\n}\n\n\n", "file_path": "e2e-tests/src/accounts.rs", "rank": 52, "score": 228763.6979041562 }, { "content": "pub fn aleph_data_from_blocks(blocks: Vec<Block>) -> AlephData<Block> {\n\n let headers = blocks.into_iter().map(|b| b.header().clone()).collect();\n\n aleph_data_from_headers(headers)\n\n}\n\n\n", "file_path": "finality-aleph/src/testing/mocks/proposal.rs", "rank": 53, "score": 227645.25299562828 }, { "content": "fn get_nonce(connection: &Connection, account: &AccountId) -> u32 {\n\n connection\n\n .get_account_info(account)\n\n .map(|acc_opt| acc_opt.map_or_else(|| 0, |acc| acc.nonce))\n\n .expect(\"retrieved nonce's value\")\n\n}\n\n\n", "file_path": "flooder/src/main.rs", "rank": 54, "score": 225994.5344106394 }, { "content": "pub fn nominate(connection: &SignedConnection, nominee_account_id: &AccountId) {\n\n let xt = connection\n\n .as_connection()\n\n .staking_nominate(vec![GenericAddress::Id(nominee_account_id.clone())]);\n\n send_xt(connection, xt, Some(\"nominate\"), XtStatus::InBlock);\n\n}\n\n\n", "file_path": "aleph-client/src/staking.rs", "rank": 55, "score": 225668.04530146028 }, { "content": "/// Returns the peer id associated with this multiaddress if it exists and is unique.\n\npub fn get_peer_id(address: &Multiaddr) -> Option<PeerId> {\n\n address\n\n .0\n\n .iter()\n\n .fold(UniquePeerId::Unknown, |result, protocol| {\n\n result.accumulate(peer_id(&protocol))\n\n })\n\n .into_option()\n\n}\n\n\n", "file_path": "finality-aleph/src/network/manager/addresses.rs", "rank": 56, "score": 223842.67515041697 }, { "content": "/// `panic`able utility wrapper for `try_send_xt`.\n\npub fn send_xt<T: Encode, C: AnyConnection>(\n\n connection: &C,\n\n xt: Extrinsic<T>,\n\n xt_name: Option<&'static str>,\n\n xt_status: XtStatus,\n\n) -> Option<H256> {\n\n try_send_xt(connection, xt, xt_name, xt_status).expect(\"Should manage to send extrinsic\")\n\n}\n\n\n", "file_path": "aleph-client/src/lib.rs", "rank": 57, "score": 222817.70641725796 }, { "content": "pub fn set_keys(connection: &SignedConnection, new_keys: Keys, status: XtStatus) {\n\n let xt = compose_extrinsic!(\n\n connection.as_connection(),\n\n \"Session\",\n\n \"set_keys\",\n\n new_keys,\n\n 0u8\n\n );\n\n send_xt(connection, xt, Some(\"set_keys\"), status);\n\n}\n\n\n", "file_path": "aleph-client/src/session.rs", "rank": 58, "score": 221710.70551699336 }, { "content": "/// Returns the peer id contained in the set of multiaddresses if it's unique and present in every\n\n/// address, None otherwise.\n\npub fn get_common_peer_id(addresses: &[Multiaddr]) -> Option<PeerId> {\n\n addresses\n\n .iter()\n\n .fold(UniquePeerId::Unknown, |result, address| {\n\n result.accumulate_strict(get_peer_id(address))\n\n })\n\n .into_option()\n\n}\n\n\n", "file_path": "finality-aleph/src/network/manager/addresses.rs", "rank": 59, "score": 221514.24104050742 }, { "content": "/// For a given set of validators, generates key pairs for the corresponding controllers.\n\nfn generate_controllers_for_validators(validator_count: u32) -> Vec<KeyPair> {\n\n (0..validator_count)\n\n .map(|seed| keypair_from_string(&format!(\"//{}//Controller\", seed)))\n\n .collect::<Vec<_>>()\n\n}\n\n\n", "file_path": "benches/payout-stakers/src/main.rs", "rank": 60, "score": 220840.28504926493 }, { "content": "/// Sends transaction `xt` using `connection`.\n\n///\n\n/// If `tx_status` is either `Finalized` or `InBlock`, additionally returns hash of the containing\n\n/// block. `xt_name` is used only for logging purposes.\n\n///\n\n/// Recoverable.\n\npub fn try_send_xt<T: Encode, C: AnyConnection>(\n\n connection: &C,\n\n xt: Extrinsic<T>,\n\n xt_name: Option<&'static str>,\n\n xt_status: XtStatus,\n\n) -> ApiResult<Option<H256>> {\n\n let hash = connection\n\n .as_connection()\n\n .send_extrinsic(xt.hex_encode(), xt_status)?\n\n .ok_or_else(|| Error::Other(String::from(\"Could not get tx/block hash\").into()))?;\n\n\n\n match xt_status {\n\n XtStatus::Finalized | XtStatus::InBlock => {\n\n info!(target: \"aleph-client\",\n\n \"Transaction `{}` was included in block with hash {}.\",\n\n xt_name.unwrap_or_default(), hash);\n\n Ok(Some(hash))\n\n }\n\n // Other variants either do not return (see https://github.com/scs/substrate-api-client/issues/175)\n\n // or return xt hash, which is kinda useless here.\n\n _ => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "aleph-client/src/lib.rs", "rank": 61, "score": 220057.53127726272 }, { "content": "pub fn rotate_keys_base<C: AnyConnection, F, R>(\n\n connection: &C,\n\n rpc_result_mapper: F,\n\n) -> Result<R, &'static str>\n\nwhere\n\n F: Fn(String) -> Option<R>,\n\n{\n\n match connection\n\n .as_connection()\n\n .get_request(author_rotate_keys_json())\n\n {\n\n Ok(maybe_keys) => match maybe_keys {\n\n Some(keys) => match rpc_result_mapper(keys) {\n\n Some(keys) => Ok(keys),\n\n None => Err(\"Failed to parse keys from string result\"),\n\n },\n\n None => Err(\"Failed to retrieve keys from chain\"),\n\n },\n\n Err(_) => Err(\"Connection does not work\"),\n\n }\n\n}\n\n\n", "file_path": "aleph-client/src/rpc.rs", "rank": 62, "score": 219992.49174547524 }, { "content": "/// Get key pair based on seed file or default when seed file is not provided.\n\nfn get_sudoer_keypair(root_seed_file: Option<String>) -> KeyPair {\n\n match root_seed_file {\n\n Some(root_seed_file) => {\n\n let root_seed = std::fs::read_to_string(&root_seed_file)\n\n .unwrap_or_else(|_| panic!(\"Failed to read file {}\", root_seed_file));\n\n keypair_from_string(root_seed.trim())\n\n }\n\n None => AccountKeyring::Alice.pair(),\n\n }\n\n}\n\n\n", "file_path": "benches/payout-stakers/src/main.rs", "rank": 63, "score": 218244.26055111556 }, { "content": "/// Submits candidate validators via controller accounts.\n\n/// We assume stash == validator != controller.\n\nfn send_validate_txs(address: &str, controllers: Vec<KeyPair>) {\n\n controllers.par_iter().for_each(|controller| {\n\n let mut rng = thread_rng();\n\n let connection = SignedConnection::new(address, controller.clone());\n\n staking_validate(&connection, rng.gen::<u8>() % 100, XtStatus::InBlock);\n\n });\n\n}\n\n\n", "file_path": "benches/payout-stakers/src/main.rs", "rank": 64, "score": 218162.5749390198 }, { "content": "pub fn read_snapshot_from_file(path: String) -> Storage {\n\n let snapshot: Storage =\n\n serde_json::from_str(&fs::read_to_string(&path).expect(\"Could not read snapshot file\"))\n\n .expect(\"could not parse from snapshot\");\n\n info!(\"Read snapshot of {} key-val pairs\", snapshot.len());\n\n snapshot\n\n}\n", "file_path": "fork-off/src/fsio.rs", "rank": 65, "score": 218071.20421500358 }, { "content": "pub fn get_tx_fee_info<C: AnyConnection, Call: Encode>(\n\n connection: &C,\n\n tx: &Extrinsic<Call>,\n\n) -> FeeInfo {\n\n let unadjusted_weight = connection\n\n .as_connection()\n\n .get_payment_info(&tx.hex_encode(), None)\n\n .expect(\"Should access payment info\")\n\n .expect(\"Payment info should be present\")\n\n .weight as Balance;\n\n\n\n let fee = connection\n\n .as_connection()\n\n .get_fee_details(&tx.hex_encode(), None)\n\n .expect(\"Should access fee details\")\n\n .expect(\"Should read fee details\");\n\n let inclusion_fee = fee.inclusion_fee.expect(\"Transaction should be payable\");\n\n\n\n FeeInfo {\n\n fee_without_weight: inclusion_fee.base_fee + inclusion_fee.len_fee + fee.tip,\n\n unadjusted_weight,\n\n adjusted_weight: inclusion_fee.adjusted_weight_fee,\n\n }\n\n}\n\n\n", "file_path": "aleph-client/src/fee.rs", "rank": 66, "score": 217298.35326363446 }, { "content": "pub fn address(text: &str) -> ScMultiaddr {\n\n text.parse().unwrap()\n\n}\n\n\n", "file_path": "finality-aleph/src/network/manager/testing.rs", "rank": 68, "score": 213918.3876403912 }, { "content": "type BlockNumber = u32;\n", "file_path": "flooder/src/main.rs", "rank": 69, "score": 213871.2616499659 }, { "content": "fn send_treasury_rejection(proposal_id: u32, connection: &RootConnection) -> GovernanceTransaction {\n\n let xt = compose_extrinsic!(\n\n connection.as_connection(),\n\n \"Treasury\",\n\n \"reject_proposal\",\n\n Compact(proposal_id)\n\n );\n\n send_xt(\n\n connection,\n\n xt.clone(),\n\n Some(\"treasury rejection\"),\n\n XtStatus::Finalized,\n\n );\n\n xt\n\n}\n\n\n", "file_path": "e2e-tests/src/test/treasury.rs", "rank": 70, "score": 212976.49316646 }, { "content": "fn send_treasury_approval(proposal_id: u32, connection: &RootConnection) -> GovernanceTransaction {\n\n let xt = compose_extrinsic!(\n\n connection.as_connection(),\n\n \"Treasury\",\n\n \"approve_proposal\",\n\n Compact(proposal_id)\n\n );\n\n send_xt(\n\n connection,\n\n xt.clone(),\n\n Some(\"treasury approval\"),\n\n XtStatus::Finalized,\n\n );\n\n xt\n\n}\n\n\n", "file_path": "e2e-tests/src/test/treasury.rs", "rank": 71, "score": 212976.49316646 }, { "content": "pub fn get_next_fee_multiplier<C: AnyConnection>(connection: &C) -> u128 {\n\n connection\n\n .as_connection()\n\n .get_storage_value(\"TransactionPayment\", \"NextFeeMultiplier\", None)\n\n .expect(\"Should access storage\")\n\n .expect(\"Key `NextFeeMultiplier` should be present in storage\")\n\n}\n", "file_path": "aleph-client/src/fee.rs", "rank": 72, "score": 212298.70746985168 }, { "content": "pub fn save_snapshot_to_file(snapshot: Storage, path: String) {\n\n let data = serde_json::to_vec_pretty(&snapshot).unwrap();\n\n info!(\n\n \"Writing snapshot of {} key-val pairs and {} total bytes\",\n\n snapshot.len(),\n\n data.len()\n\n );\n\n write_to_file(path, &data);\n\n}\n\n\n", "file_path": "fork-off/src/fsio.rs", "rank": 73, "score": 211809.66937735537 }, { "content": "pub fn write_to_file(write_to_path: String, data: &[u8]) {\n\n let mut file = match fs::OpenOptions::new()\n\n .write(true)\n\n .truncate(true)\n\n .open(&write_to_path)\n\n {\n\n Ok(file) => file,\n\n Err(error) => match error.kind() {\n\n ErrorKind::NotFound => match File::create(&write_to_path) {\n\n Ok(file) => file,\n\n Err(why) => panic!(\"Cannot create file: {:?}\", why),\n\n },\n\n _ => panic!(\"Unexpected error when creating file: {}\", &write_to_path),\n\n },\n\n };\n\n\n\n file.write_all(data).expect(\"Could not write to file\");\n\n}\n\n\n", "file_path": "fork-off/src/fsio.rs", "rank": 74, "score": 211809.66937735537 }, { "content": "pub fn finalization(config: &Config) -> anyhow::Result<()> {\n\n let connection = create_connection(&config.node);\n\n wait_for_finalized_block(&connection, 1)?;\n\n Ok(())\n\n}\n", "file_path": "e2e-tests/src/test/finalization.rs", "rank": 75, "score": 211632.14693294448 }, { "content": "fn element_prompt(el: String) -> String {\n\n format!(\"\\t{}\", el)\n\n}\n\n\n", "file_path": "aleph-client/src/debug/mod.rs", "rank": 76, "score": 210509.18294331757 }, { "content": "pub fn batch_transactions(config: &Config) -> anyhow::Result<()> {\n\n const NUMBER_OF_TRANSACTIONS: usize = 100;\n\n\n\n let (connection, to) = setup_for_transfer(config);\n\n\n\n let call = compose_call!(\n\n connection.as_connection().metadata,\n\n \"Balances\",\n\n \"transfer\",\n\n GenericAddress::Id(to),\n\n Compact(1000u128)\n\n );\n\n let mut transactions = Vec::new();\n\n for _i in 0..NUMBER_OF_TRANSACTIONS {\n\n transactions.push(call.clone());\n\n }\n\n\n\n let extrinsic =\n\n compose_extrinsic!(connection.as_connection(), \"Utility\", \"batch\", transactions);\n\n\n", "file_path": "e2e-tests/src/test/utility.rs", "rank": 77, "score": 209554.40625156125 }, { "content": "pub fn treasury_access(config: &Config) -> anyhow::Result<()> {\n\n let proposer = get_validators_keys(config)[0].clone();\n\n let beneficiary = AccountId::from(proposer.public());\n\n let connection = SignedConnection::new(&config.node, proposer);\n\n\n\n propose_treasury_spend(10u128, &beneficiary, &connection);\n\n propose_treasury_spend(100u128, &beneficiary, &connection);\n\n let proposals_counter = get_proposals_counter(&connection);\n\n assert!(proposals_counter >= 2, \"Proposal was not created\");\n\n\n\n let sudo = get_sudo_key(config);\n\n let connection = RootConnection::new(&config.node, sudo);\n\n\n\n treasury_approve(proposals_counter - 2, &connection)?;\n\n treasury_reject(proposals_counter - 1, &connection)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e-tests/src/test/treasury.rs", "rank": 78, "score": 209554.40625156125 }, { "content": "pub fn fee_calculation(config: &Config) -> anyhow::Result<()> {\n\n // An initial transfer is needed to establish the fee multiplier.\n\n let (connection, to) = setup_for_transfer(config);\n\n let transfer_value = 1000u128;\n\n balances_transfer(&connection, &to, transfer_value, XtStatus::Finalized);\n\n\n\n // An example transaction for which we will query fee details at different traffic level.\n\n let tx = prepare_transaction(&connection);\n\n\n\n let (actual_multiplier, fee_info) = check_current_fees(&connection, &tx);\n\n assert_no_scaling(\n\n actual_multiplier,\n\n fee_info,\n\n \"In the beginning the fee multiplier should be equal to the minimum value\",\n\n \"In the beginning fees should not be scaled\",\n\n );\n\n\n\n // The target saturation level is set to 25%, so unless we cross this limit,\n\n // the fees should not increase. Note that effectively it is 18.75% of the whole block.\n\n let root_connection = RootConnection::from(connection.clone());\n", "file_path": "e2e-tests/src/test/fee.rs", "rank": 79, "score": 209554.40625156125 }, { "content": "pub fn channeling_fee(config: &Config) -> anyhow::Result<()> {\n\n let (connection, to) = setup_for_transfer(config);\n\n let treasury = get_treasury_account();\n\n\n\n let possibly_treasury_gain_from_staking = calculate_staking_treasury_addition(&connection);\n\n let treasury_balance_before = get_free_balance(&connection, &treasury);\n\n let issuance_before = get_total_issuance(&connection);\n\n info!(\n\n \"[+] Treasury balance before tx: {}. Total issuance: {}.\",\n\n treasury_balance_before, issuance_before\n\n );\n\n\n\n let tx = balances_transfer(&connection, &to, 1000u128, XtStatus::Finalized);\n\n let treasury_balance_after = get_free_balance(&connection, &treasury);\n\n let issuance_after = get_total_issuance(&connection);\n\n check_treasury_issuance(\n\n possibly_treasury_gain_from_staking,\n\n treasury_balance_after,\n\n issuance_before,\n\n issuance_after,\n", "file_path": "e2e-tests/src/test/treasury.rs", "rank": 80, "score": 209554.40625156125 }, { "content": "pub fn token_transfer(config: &Config) -> anyhow::Result<()> {\n\n let (connection, to) = setup_for_transfer(config);\n\n\n\n let balance_before = get_free_balance(&connection, &to);\n\n info!(\"[+] Account {} balance before tx: {}\", to, balance_before);\n\n\n\n let transfer_value = 1000u128;\n\n balances_transfer(&connection, &to, transfer_value, XtStatus::Finalized);\n\n\n\n let balance_after = get_free_balance(&connection, &to);\n\n info!(\"[+] Account {} balance after tx: {}\", to, balance_after);\n\n\n\n assert_eq!(\n\n balance_before + transfer_value,\n\n balance_after,\n\n \"before = {}, after = {}, tx = {}\",\n\n balance_before,\n\n balance_after,\n\n transfer_value\n\n );\n\n\n\n Ok(())\n\n}\n", "file_path": "e2e-tests/src/test/transfer.rs", "rank": 81, "score": 209554.40625156125 }, { "content": "// 0. validators stash and controllers are already endowed, bonded and validated in a genesis block\n\n// 1. endow nominators stash accounts balances\n\n// 3. bond controller account to stash account, stash = controller and set controller to StakerStatus::Nominate\n\n// 4. wait for new era\n\n// 5. send payout stakers tx\n\npub fn staking_era_payouts(config: &Config) -> anyhow::Result<()> {\n\n let (stashes_accounts_key_pairs, validator_accounts) = get_validator_stashes_key_pairs(config);\n\n\n\n let node = &config.node;\n\n let sender = validator_accounts[0].clone();\n\n let connection = SignedConnection::new(node, sender);\n\n let stashes_accounts = convert_authorities_to_account_id(&stashes_accounts_key_pairs);\n\n\n\n balances_batch_transfer(&connection, stashes_accounts, MIN_NOMINATOR_BOND + TOKEN);\n\n staking_multi_bond(node, &stashes_accounts_key_pairs, MIN_NOMINATOR_BOND);\n\n\n\n stashes_accounts_key_pairs\n\n .par_iter()\n\n .zip(validator_accounts.par_iter())\n\n .for_each(|(nominator, nominee)| {\n\n let connection = SignedConnection::new(node, nominator.clone());\n\n let nominee_account_id = AccountId::from(nominee.public());\n\n staking_nominate(&connection, &nominee_account_id)\n\n });\n\n\n", "file_path": "e2e-tests/src/test/staking.rs", "rank": 82, "score": 207552.17153285694 }, { "content": "// 1. decrease number of validators from 4 to 3\n\n// 2. endow stash account balances\n\n// 3. bond controller account to the stash account, stash != controller and set controller to StakerStatus::Validate\n\n// 4. call bonded, double check bonding\n\n// 5. set keys for controller account from validator's rotate_keys()\n\n// 6. set controller to StakerStatus::Validate, call ledger to double-check storage state\n\n// 7. add 4th validator which is the new stash account\n\n// 8. wait for next era\n\n// 9. claim rewards for the stash account\n\npub fn staking_new_validator(config: &Config) -> anyhow::Result<()> {\n\n let controller_seed = \"//Controller\";\n\n let controller = keypair_from_string(controller_seed);\n\n let controller_account = AccountId::from(controller.public());\n\n let stash_seed = \"//Stash\";\n\n let stash = keypair_from_string(stash_seed);\n\n let stash_account = AccountId::from(stash.public());\n\n let (_, mut validator_accounts) = get_validator_stashes_key_pairs(config);\n\n let node = &config.node;\n\n let _ = validator_accounts.remove(0);\n\n // signer of this connection is sudo, the same node which in this test is used as the new one\n\n // it's essential since keys from rotate_keys() needs to be run against that node\n\n let root_connection: RootConnection = SignedConnection::new(node, get_sudo_key(config)).into();\n\n\n\n change_members(\n\n &root_connection,\n\n Some(convert_authorities_to_account_id(&validator_accounts)),\n\n Some(vec![]),\n\n Some(4),\n\n XtStatus::InBlock,\n", "file_path": "e2e-tests/src/test/staking.rs", "rank": 83, "score": 207548.92547247175 }, { "content": "pub fn change_validators(config: &Config) -> anyhow::Result<()> {\n\n let accounts = get_validators_keys(config);\n\n let sudo = get_sudo_key(config);\n\n\n\n let connection = RootConnection::new(&config.node, sudo);\n\n\n\n let reserved_before: Vec<AccountId> = connection\n\n .as_connection()\n\n .get_storage_value(\"Elections\", \"ReservedMembers\", None)?\n\n .unwrap();\n\n\n\n let non_reserved_before: Vec<AccountId> = connection\n\n .as_connection()\n\n .get_storage_value(\"Elections\", \"NonReservedMembers\", None)?\n\n .unwrap();\n\n\n\n let members_per_session_before: u32 = connection\n\n .as_connection()\n\n .get_storage_value(\"Elections\", \"MembersPerSession\", None)?\n\n .unwrap();\n", "file_path": "e2e-tests/src/test/validators_change.rs", "rank": 84, "score": 207544.20026577666 }, { "content": "pub fn members_rotate(config: &Config) -> anyhow::Result<()> {\n\n let node = &config.node;\n\n let accounts = get_validators_keys(config);\n\n let sender = accounts.first().expect(\"Using default accounts\").to_owned();\n\n let connection = SignedConnection::new(node, sender);\n\n\n\n let sudo = get_sudo_key(config);\n\n\n\n let root_connection = RootConnection::new(node, sudo);\n\n\n\n let reserved_members: Vec<_> = get_reserved_members(config)\n\n .iter()\n\n .map(|pair| AccountId::from(pair.public()))\n\n .collect();\n\n\n\n let non_reserved_members = get_non_reserved_members(config)\n\n .iter()\n\n .map(|pair| AccountId::from(pair.public()))\n\n .collect();\n\n\n", "file_path": "e2e-tests/src/test/validators_rotate.rs", "rank": 85, "score": 207544.20026577666 }, { "content": "fn get_non_reserved_members_for_session(config: &Config, session: u32) -> Vec<AccountId> {\n\n // Test assumption\n\n const FREE_SEATS: u32 = 2;\n\n\n\n let mut non_reserved = vec![];\n\n\n\n let validators_seeds = get_validators_seeds(config);\n\n let non_reserved_nodes_order_from_runtime = validators_seeds[2..].to_vec();\n\n let non_reserved_nodes_order_from_runtime_len = non_reserved_nodes_order_from_runtime.len();\n\n\n\n for i in (FREE_SEATS * session)..(FREE_SEATS * (session + 1)) {\n\n non_reserved.push(\n\n non_reserved_nodes_order_from_runtime\n\n [i as usize % non_reserved_nodes_order_from_runtime_len]\n\n .clone(),\n\n );\n\n }\n\n\n\n accounts_seeds_to_keys(&non_reserved)\n\n .iter()\n\n .map(|pair| AccountId::from(pair.public()))\n\n .collect()\n\n}\n\n\n", "file_path": "e2e-tests/src/test/validators_rotate.rs", "rank": 86, "score": 205737.8856664196 }, { "content": "fn fill_blocks(target_ratio: u32, blocks: u32, connection: &RootConnection) {\n\n for _ in 0..blocks {\n\n let xt = compose_extrinsic!(\n\n connection.as_connection(),\n\n \"System\",\n\n \"fill_block\",\n\n target_ratio * 10_000_000\n\n );\n\n send_xt(connection, xt, Some(\"fill block\"), XtStatus::InBlock);\n\n }\n\n}\n", "file_path": "e2e-tests/src/test/fee.rs", "rank": 87, "score": 205050.45748696278 }, { "content": "pub fn transfer(\n\n connection: &SignedConnection,\n\n target: &AccountId,\n\n value: u128,\n\n status: XtStatus,\n\n) -> TransferTransaction {\n\n let xt = connection\n\n .as_connection()\n\n .balance_transfer(GenericAddress::Id(target.clone()), value);\n\n send_xt(connection, xt.clone(), Some(\"transfer\"), status);\n\n xt\n\n}\n\n\n", "file_path": "aleph-client/src/transfer.rs", "rank": 88, "score": 204066.0407123558 }, { "content": "pub fn bond(\n\n connection: &SignedConnection,\n\n initial_stake: Balance,\n\n controller_account_id: &AccountId,\n\n status: XtStatus,\n\n) {\n\n let controller_account_id = GenericAddress::Id(controller_account_id.clone());\n\n\n\n let xt = connection.as_connection().staking_bond(\n\n controller_account_id,\n\n initial_stake,\n\n RewardDestination::Staked,\n\n );\n\n send_xt(connection, xt, Some(\"bond\"), status);\n\n}\n\n\n", "file_path": "aleph-client/src/staking.rs", "rank": 89, "score": 204066.0407123558 }, { "content": "pub fn validate(\n\n connection: &SignedConnection,\n\n validator_commission_percentage: u8,\n\n status: XtStatus,\n\n) {\n\n let prefs = ValidatorPrefs {\n\n blocked: false,\n\n commission: Perbill::from_percent(validator_commission_percentage as u32),\n\n };\n\n let xt = compose_extrinsic!(connection.as_connection(), \"Staking\", \"validate\", prefs);\n\n send_xt(connection, xt, Some(\"validate\"), status);\n\n}\n\n\n", "file_path": "aleph-client/src/staking.rs", "rank": 90, "score": 204066.0407123558 }, { "content": "pub fn era_payouts_calculated_correctly(config: &Config) -> anyhow::Result<()> {\n\n normal_era_payout(config)?;\n\n force_era_payout(config)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e-tests/src/test/era_payout.rs", "rank": 91, "score": 203713.63615821226 }, { "content": "fn assert_no_blocks_except_genesis(client: &TestClient) {\n\n assert!(\n\n client.header(&BlockId::Number(1)).unwrap().is_none(),\n\n \"Client is aware of some blocks beyond genesis\"\n\n );\n\n}\n\n\n\nimpl ClientChainBuilder {\n\n pub fn new(client: Arc<TestClient>, client_builder: Arc<TestClient>) -> Self {\n\n // Below we enforce that both clients are \"empty\" and agree with each other.\n\n assert_eq!(client.info(), client_builder.info());\n\n assert_no_blocks_except_genesis(&*client);\n\n assert_no_blocks_except_genesis(&*client_builder);\n\n ClientChainBuilder {\n\n client,\n\n client_builder,\n\n unique_seed: 0,\n\n }\n\n }\n\n\n", "file_path": "finality-aleph/src/testing/client_chain_builder.rs", "rank": 92, "score": 202112.07999576014 }, { "content": "/// Performs a vested transfer from the signer of `connection` to `receiver` according to\n\n/// `schedule`.\n\n///\n\n/// Fails if transaction could not have been sent.\n\npub fn vested_transfer(\n\n connection: SignedConnection,\n\n receiver: AccountId,\n\n schedule: VestingSchedule,\n\n) -> Result<()> {\n\n let xt = compose_extrinsic!(\n\n connection.as_connection(),\n\n PALLET,\n\n \"vested_transfer\",\n\n GenericAddress::Id(receiver.clone()),\n\n schedule\n\n );\n\n let block_hash = try_send_xt(&connection, xt, Some(\"Vested transfer\"), Finalized)?\n\n .expect(\"For `Finalized` status a block hash should be returned\");\n\n info!(target: \"aleph-client\", \"Vested transfer to the account {:?}. Finalized in block {:?}\", receiver, block_hash);\n\n Ok(())\n\n}\n\n\n", "file_path": "aleph-client/src/vesting.rs", "rank": 93, "score": 201610.68240988196 }, { "content": "pub fn batch_nominate(\n\n connection: &RootConnection,\n\n nominator_nominee_pairs: &[(&AccountId, &AccountId)],\n\n) {\n\n let metadata = &connection.as_connection().metadata;\n\n\n\n let batch_nominate_calls = nominator_nominee_pairs\n\n .iter()\n\n .cloned()\n\n .map(|(nominator, nominee)| {\n\n let nominate_call = compose_call!(\n\n metadata,\n\n \"Staking\",\n\n \"nominate\",\n\n vec![GenericAddress::Id(nominee.clone())]\n\n );\n\n compose_call!(\n\n metadata,\n\n \"Sudo\",\n\n \"sudo_as\",\n", "file_path": "aleph-client/src/staking.rs", "rank": 94, "score": 201605.86707398854 }, { "content": "pub fn batch_bond(\n\n connection: &RootConnection,\n\n stash_controller_accounts: &[(&AccountId, &AccountId)],\n\n bond_value: u128,\n\n reward_destination: RewardDestination<GenericAddress>,\n\n) {\n\n let metadata = &connection.as_connection().metadata;\n\n\n\n let batch_bond_calls = stash_controller_accounts\n\n .iter()\n\n .cloned()\n\n .map(|(stash_account, controller_account)| {\n\n let bond_call = compose_call!(\n\n metadata,\n\n \"Staking\",\n\n \"bond\",\n\n GenericAddress::Id(controller_account.clone()),\n\n Compact(bond_value),\n\n reward_destination.clone()\n\n );\n", "file_path": "aleph-client/src/staking.rs", "rank": 95, "score": 201605.86707398854 }, { "content": "pub fn payout_stakers(\n\n stash_connection: &SignedConnection,\n\n stash_account: &AccountId,\n\n era_number: BlockNumber,\n\n) {\n\n let xt = compose_extrinsic!(\n\n stash_connection.as_connection(),\n\n \"Staking\",\n\n \"payout_stakers\",\n\n stash_account,\n\n era_number\n\n );\n\n\n\n send_xt(\n\n stash_connection,\n\n xt,\n\n Some(\"payout stakers\"),\n\n XtStatus::InBlock,\n\n );\n\n}\n\n\n", "file_path": "aleph-client/src/staking.rs", "rank": 96, "score": 201605.86707398854 }, { "content": "pub fn change_members(\n\n sudo_connection: &RootConnection,\n\n new_reserved_members: Option<Vec<AccountId>>,\n\n new_non_reserved_members: Option<Vec<AccountId>>,\n\n members_per_session: Option<u32>,\n\n status: XtStatus,\n\n) {\n\n info!(target: \"aleph-client\", \"New members: reserved: {:#?}, non_reserved: {:#?}, members_per_session: {:?}\", new_reserved_members, new_non_reserved_members, members_per_session);\n\n let call = compose_call!(\n\n sudo_connection.as_connection().metadata,\n\n \"Elections\",\n\n \"change_members\",\n\n new_reserved_members,\n\n new_non_reserved_members,\n\n members_per_session\n\n );\n\n let xt = compose_extrinsic!(\n\n sudo_connection.as_connection(),\n\n \"Sudo\",\n\n \"sudo_unchecked_weight\",\n\n call,\n\n 0_u64\n\n );\n\n send_xt(sudo_connection, xt, Some(\"change_members\"), status);\n\n}\n\n\n", "file_path": "aleph-client/src/session.rs", "rank": 97, "score": 201605.86707398854 }, { "content": "pub fn batch_transfer(\n\n connection: &SignedConnection,\n\n account_keys: Vec<AccountId>,\n\n endowment: u128,\n\n) {\n\n let batch_endow = account_keys\n\n .into_iter()\n\n .map(|account_id| {\n\n compose_call!(\n\n connection.as_connection().metadata,\n\n \"Balances\",\n\n \"transfer\",\n\n GenericAddress::Id(account_id),\n\n Compact(endowment)\n\n )\n\n })\n\n .collect::<Vec<_>>();\n\n\n\n let xt = compose_extrinsic!(connection.as_connection(), \"Utility\", \"batch\", batch_endow);\n\n send_xt(\n\n connection,\n\n xt,\n\n Some(\"batch of endow balances\"),\n\n XtStatus::InBlock,\n\n );\n\n}\n", "file_path": "aleph-client/src/transfer.rs", "rank": 98, "score": 201605.86707398854 }, { "content": "fn get_authorities_for_session<C: AnyConnection>(connection: &C, session: u32) -> Vec<AccountId> {\n\n const SESSION_PERIOD: u32 = 30;\n\n let first_block = SESSION_PERIOD * session;\n\n\n\n let block = connection\n\n .as_connection()\n\n .get_block_hash(Some(first_block))\n\n .expect(\"Api call should succeed\")\n\n .expect(\"Session already started so the first block should be present\");\n\n\n\n connection\n\n .as_connection()\n\n .get_storage_value(\"Session\", \"Validators\", Some(block))\n\n .expect(\"Api call should succeed\")\n\n .expect(\"Authorities should always be present\")\n\n}\n\n\n", "file_path": "e2e-tests/src/test/validators_rotate.rs", "rank": 99, "score": 201347.28331645764 } ]
Rust
src/language_features/hover.rs
jcai849/kak-lsp
9444ad4bcb7019c1ff34c2b2ac8493b0ff2aba08
use crate::context::*; use crate::markup::*; use crate::types::*; use crate::util::*; use itertools::Itertools; use lsp_types::request::*; use lsp_types::*; use serde::Deserialize; use url::Url; pub fn text_document_hover(meta: EditorMeta, params: EditorParams, ctx: &mut Context) { let params = PositionParams::deserialize(params).unwrap(); let req_params = HoverParams { text_document_position_params: TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri: Url::from_file_path(&meta.buffile).unwrap(), }, position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(), }, work_done_progress_params: Default::default(), }; ctx.call::<HoverRequest, _>(meta, req_params, move |ctx: &mut Context, meta, result| { editor_hover(meta, params, result, ctx) }); } pub fn editor_hover( meta: EditorMeta, params: PositionParams, result: Option<Hover>, ctx: &mut Context, ) { let diagnostics = ctx.diagnostics.get(&meta.buffile); let pos = get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(); let diagnostics = diagnostics .map(|x| { x.iter() .filter(|x| { let start = x.range.start; let end = x.range.end; (start.line < pos.line && pos.line < end.line) || (start.line == pos.line && pos.line == end.line && start.character <= pos.character && pos.character <= end.character) || (start.line == pos.line && pos.line <= end.line && start.character <= pos.character) || (start.line <= pos.line && end.line == pos.line && pos.character <= end.character) }) .filter_map(|x| { let face = x .severity .map(|sev| match sev { DiagnosticSeverity::ERROR => FACE_INFO_DIAGNOSTIC_ERROR, DiagnosticSeverity::WARNING => FACE_INFO_DIAGNOSTIC_WARNING, DiagnosticSeverity::INFORMATION => FACE_INFO_DIAGNOSTIC_INFO, DiagnosticSeverity::HINT => FACE_INFO_DIAGNOSTIC_HINT, _ => { warn!("Unexpected DiagnosticSeverity: {:?}", sev); FACE_INFO_DEFAULT } }) .unwrap_or(FACE_INFO_DEFAULT); if !x.message.is_empty() { Some(format!( "• {{{}}}{}{{{}}}", face, escape_brace(x.message.trim()) .replace("\n", "\n "), FACE_INFO_DEFAULT, )) } else { None } }) .join("\n") }) .unwrap_or_else(String::new); let force_plaintext = ctx .config .language .get(&ctx.language_id) .and_then(|l| l.workaround_server_sends_plaintext_labeled_as_markdown) .unwrap_or(false); let contents = match result { None => "".to_string(), Some(result) => match result.contents { HoverContents::Scalar(contents) => { marked_string_to_kakoune_markup(contents, force_plaintext) } HoverContents::Array(contents) => contents .into_iter() .map(|md| marked_string_to_kakoune_markup(md, force_plaintext)) .filter(|markup| !markup.is_empty()) .join(&format!( "\n{{{}}}---{{{}}}\n", FACE_INFO_RULE, FACE_INFO_DEFAULT )), HoverContents::Markup(contents) => match contents.kind { MarkupKind::Markdown => markdown_to_kakoune_markup(contents.value, force_plaintext), MarkupKind::PlainText => contents.value, }, }, }; if contents.is_empty() && diagnostics.is_empty() { return; } let command = format!( "lsp-show-hover {} %§{}§ %§{}§", params.position, contents.replace("§", "§§"), diagnostics.replace("§", "§§") ); ctx.exec(meta, command); } trait PlainText { fn plaintext(self) -> String; } impl PlainText for MarkedString { fn plaintext(self) -> String { match self { MarkedString::String(contents) => contents, MarkedString::LanguageString(contents) => contents.value, } } }
use crate::context::*; use crate::markup::*; use crate::types::*; use crate::util::*; use itertools::Itertools; use lsp_types::request::*; use lsp_types::*; use serde::Deserialize; use url::Url; pub fn text_document_hover(meta: EditorMeta, params: EditorParams, ctx: &mut Context) { let params = PositionParams::deserialize(params).unwrap(); let req_params = HoverParams { text_document_position_params: TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri: Url::from_file_path(&meta.buffile).unwrap(), }, position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(), }, work_done_progress_params: Default::default(), }; ctx.call::<HoverRequest, _>(meta, req_params, move |ctx: &mut Context, meta, result| { editor_hover(meta, params, result, ctx) }); } pub fn editor_hover( meta: EditorMeta, params: PositionParams, result: Option<Hover>, ctx: &mut Context, ) { let diagnostics = ctx.diagnostics.get(&meta.buffile); let pos = get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(); let diagnostics = diagnostics .map(|x| { x.iter() .filter(|x| { let start = x.range.start; let end = x.range.end; (start.line < pos.line && pos.line < end.line) || (start.line == pos.line && pos.line == end.line && start.character <= pos.character && pos.character <= end.character) || (start.line == pos.line && pos.line <= end.line && start.character <= pos.character) || (start.line <= pos.line && end.line == pos.line && pos.character <= end.character) }) .filter_map(|x| { let face = x .severity .map(|sev| match sev { DiagnosticSeverity::ERROR => FACE_INFO_DIAGNOSTIC_ERROR, DiagnosticSeverity::WARNING => FACE_INFO_DIAGNOSTIC_WARNING, DiagnosticSeverity::INFORMATION => FACE_INFO_DIAGNOSTIC_INFO, DiagnosticSeverity::HINT => FACE_INFO_DIAGNOSTIC_HINT, _ => { warn!("Unexpected DiagnosticSeverity: {:?}", sev); FACE_INFO_DEFAULT } }) .unwrap_or(FACE_INFO_DEFAULT); if !x.message.is_empty() { Some(format!( "• {{{}}}{}{{{}}}", face, escape_brace(x.message.trim()) .replace("\n", "\n "), FACE_INFO_DEFAULT, )) } else { None } }) .join("\n") }) .unwrap_or_else(String::new); let force_plaintext = ctx .config .language .get(&ctx.language_id) .and_then(|l| l.workaround_server_sends_plaintext_labeled_as_markdown) .unwrap_or(false); let contents = match result { None => "".to_string(), Some(result) => match result.contents { HoverContents::Scalar(contents) => { marked_string_to_kakoune_markup(contents, force_plaintext) } HoverContents::Array(contents) => contents .into_iter() .map(|md| marked_string_to_kakoune_markup(md, force_plaintext)) .filter(|markup| !markup.is_empty()) .join(&format!( "\n{{{}}}---{{{}}}\n", FACE_INFO_RULE, FACE_INFO_DEFAULT )), HoverContents::Markup(contents) => match contents.kind { MarkupKind::Markdown => markdown_to_kakoune_markup(contents.value, force_plaintext), MarkupKind::PlainText => contents.value, }, }, }; if contents.is_empty() && diagnostics.is_empty() { return; } let command = format!( "lsp-show-hover {} %§{}§ %§{}§", params.position, contents.replace("§", "§§"), diagnostics.replace("§", "§§") ); ctx.exec(meta, command); } trait PlainText { fn plaintext(self) -> String; } impl PlainText for MarkedString {
}
fn plaintext(self) -> String { match self { MarkedString::String(contents) => contents, MarkedString::LanguageString(contents) => contents.value, } }
function_block-full_function
[ { "content": "pub fn text_document_formatting(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = FormattingOptions::deserialize(params)\n\n .expect(\"Params should follow FormattingOptions structure\");\n\n let req_params = DocumentFormattingParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n options: params,\n\n work_done_progress_params: Default::default(),\n\n };\n\n ctx.call::<Formatting, _>(\n\n meta,\n\n req_params,\n\n move |ctx: &mut Context, meta: EditorMeta, result: Option<Vec<TextEdit>>| {\n\n let text_edits = result\n\n .unwrap_or_else(Vec::new)\n\n .into_iter()\n\n .map(OneOf::Left)\n\n .collect::<Vec<_>>();\n\n super::range_formatting::editor_range_formatting(meta, &text_edits, ctx)\n\n },\n\n );\n\n}\n", "file_path": "src/language_features/formatting.rs", "rank": 0, "score": 342776.5195091632 }, { "content": "pub fn editor_diagnostics(meta: EditorMeta, ctx: &mut Context) {\n\n let content = ctx\n\n .diagnostics\n\n .iter()\n\n .flat_map(|(filename, diagnostics)| {\n\n diagnostics\n\n .iter()\n\n .map(|x| {\n\n let p = get_kakoune_position(filename, &x.range.start, ctx).unwrap();\n\n format!(\n\n \"{}:{}:{}: {}:{}\",\n\n short_file_path(filename, &ctx.root_path),\n\n p.line,\n\n p.column,\n\n match x.severity {\n\n Some(DiagnosticSeverity::ERROR) => \"error\",\n\n Some(DiagnosticSeverity::HINT) => \"hint\",\n\n Some(DiagnosticSeverity::INFORMATION) => \"info\",\n\n Some(DiagnosticSeverity::WARNING) | None => \"warning\",\n\n Some(_) => {\n", "file_path": "src/diagnostics.rs", "rank": 1, "score": 337253.8788971207 }, { "content": "pub fn execute_command(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = EditorExecuteCommand::deserialize(params)\n\n .expect(\"Params should follow ExecuteCommand structure\");\n\n let req_params = ExecuteCommandParams {\n\n command: params.command,\n\n // arguments is quoted to avoid parsing issues\n\n arguments: serde_json::from_str(&params.arguments).unwrap(),\n\n work_done_progress_params: Default::default(),\n\n };\n\n match &*req_params.command {\n\n \"rust-analyzer.applySourceChange\" => {\n\n rust_analyzer::apply_source_change(meta, req_params, ctx);\n\n }\n\n _ => {\n\n ctx.call::<ExecuteCommand, _>(meta, req_params, move |_: &mut Context, _, _| ());\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/workspace.rs", "rank": 2, "score": 328993.8653982326 }, { "content": "pub fn apply_source_change(meta: EditorMeta, params: ExecuteCommandParams, ctx: &mut Context) {\n\n let arg = params\n\n .arguments\n\n .into_iter()\n\n .next()\n\n .expect(\"Missing source change\");\n\n let SourceChange {\n\n workspace_edit:\n\n SnippetWorkspaceEdit {\n\n changes,\n\n document_changes,\n\n },\n\n cursor_position,\n\n ..\n\n } = serde_json::from_value(arg).expect(\"Invalid source change\");\n\n if let Some(document_changes) = document_changes {\n\n for op in document_changes {\n\n match op {\n\n SnippetDocumentChangeOperation::Op(resource_op) => {\n\n if let Err(e) = workspace::apply_document_resource_op(&meta, resource_op, ctx) {\n", "file_path": "src/language_features/rust_analyzer.rs", "rank": 3, "score": 322516.9396512873 }, { "content": "pub fn inheritance(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = KakouneInheritanceParams::deserialize(params).unwrap();\n\n let req_params = InheritanceParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(),\n\n levels: params.levels,\n\n derived: params.derived,\n\n };\n\n ctx.call::<InheritanceRequest, _>(meta, req_params, move |ctx: &mut Context, meta, result| {\n\n goto::goto(meta, result.map(GotoDefinitionResponse::Array), ctx);\n\n });\n\n}\n\n\n\n// $ccls/call\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct CallParams {\n", "file_path": "src/language_features/ccls.rs", "rank": 4, "score": 322235.9720030439 }, { "content": "pub fn call(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = KakouneCallParams::deserialize(params).unwrap();\n\n let req_params = CallParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(),\n\n callee: params.callee,\n\n };\n\n ctx.call::<CallRequest, _>(meta, req_params, move |ctx: &mut Context, meta, result| {\n\n goto::goto(meta, result.map(GotoDefinitionResponse::Array), ctx);\n\n });\n\n}\n\n\n\n// $ccls/member\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct MemberParams {\n\n pub text_document: TextDocumentIdentifier,\n", "file_path": "src/language_features/ccls.rs", "rank": 5, "score": 322235.9720030439 }, { "content": "pub fn member(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = KakouneMemberParams::deserialize(params).unwrap();\n\n let req_params = MemberParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(),\n\n kind: params.kind,\n\n };\n\n ctx.call::<MemberRequest, _>(meta, req_params, move |ctx: &mut Context, meta, result| {\n\n goto::goto(meta, result.map(GotoDefinitionResponse::Array), ctx)\n\n });\n\n}\n\n\n\n// Semantic Highlighting\n\n\n\nenum_from_primitive! {\n\n#[derive(Debug, Eq, PartialEq, Copy, Clone)]\n\npub enum StorageClass {\n\n None = 0,\n", "file_path": "src/language_features/ccls.rs", "rank": 6, "score": 322235.972003044 }, { "content": "pub fn vars(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = PositionParams::deserialize(params).unwrap();\n\n let req_params = VarsParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(),\n\n };\n\n ctx.call::<VarsRequest, _>(meta, req_params, move |ctx: &mut Context, meta, result| {\n\n goto::goto(meta, result.map(GotoDefinitionResponse::Array), ctx);\n\n });\n\n}\n\n\n\n// $ccls/inheritance\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct InheritanceParams {\n\n pub text_document: TextDocumentIdentifier,\n\n pub position: Position,\n", "file_path": "src/language_features/ccls.rs", "rank": 7, "score": 322235.972003044 }, { "content": "pub fn navigate(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = KakouneNavigateParams::deserialize(params).unwrap();\n\n let req_params = NavigateParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(),\n\n direction: params.direction,\n\n };\n\n ctx.call::<NavigateRequest, _>(\n\n meta,\n\n req_params,\n\n move |ctx: &mut Context, meta, response| {\n\n goto::goto(meta, response, ctx);\n\n },\n\n );\n\n}\n\n\n\n// The following are more granular, c/c++ specific find-defintion style methods.\n\n// Reference: https://github.com/MaskRay/ccls/wiki/LanguageClient-neovim#cross-reference-extensions\n", "file_path": "src/language_features/ccls.rs", "rank": 8, "score": 322235.9720030439 }, { "content": "// TODO handle version, so change is not applied if buffer is modified (and need to show a warning)\n\npub fn editor_rename(meta: EditorMeta, result: Option<WorkspaceEdit>, ctx: &mut Context) {\n\n if result.is_none() {\n\n return;\n\n }\n\n let result = result.unwrap();\n\n workspace::apply_edit(meta, result, ctx);\n\n}\n", "file_path": "src/language_features/rename.rs", "rank": 9, "score": 315930.9730856478 }, { "content": "pub fn goto(meta: EditorMeta, result: Option<GotoDefinitionResponse>, ctx: &mut Context) {\n\n let locations = match result {\n\n Some(GotoDefinitionResponse::Scalar(location)) => vec![location],\n\n Some(GotoDefinitionResponse::Array(locations)) => locations,\n\n Some(GotoDefinitionResponse::Link(locations)) => locations\n\n .into_iter()\n\n .map(\n\n |LocationLink {\n\n target_uri: uri,\n\n target_range: range,\n\n ..\n\n }| Location { uri, range },\n\n )\n\n .collect(),\n\n None => return,\n\n };\n\n match locations.len() {\n\n 0 => {}\n\n 1 => {\n\n goto_location(meta, &locations[0], ctx);\n\n }\n\n _ => {\n\n goto_locations(meta, &locations, ctx);\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/language_features/goto.rs", "rank": 10, "score": 315930.9730856478 }, { "content": "pub fn did_change_configuration(meta: EditorMeta, mut params: EditorParams, ctx: &mut Context) {\n\n let mut default_settings = toml::value::Table::new();\n\n\n\n let raw_settings = params\n\n .as_table_mut()\n\n .and_then(|t| t.get_mut(\"settings\"))\n\n .and_then(|t| t.as_table_mut())\n\n .unwrap_or(&mut default_settings);\n\n\n\n let config_param = raw_settings.remove(\"lsp_config\");\n\n let config = config_param\n\n .as_ref()\n\n .map(|config| {\n\n config\n\n .as_str()\n\n .expect(\"Parameter \\\"lsp_config\\\" must be a string\")\n\n })\n\n .unwrap_or(\"\");\n\n\n\n let settings = parse_dynamic_config(&meta, ctx, config)\n", "file_path": "src/workspace.rs", "rank": 11, "score": 313846.4003011288 }, { "content": "pub fn inlay_hints(meta: EditorMeta, _params: EditorParams, ctx: &mut Context) {\n\n let req_params = InlayHintsParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n };\n\n ctx.call::<InlayHints, _>(meta, req_params, move |ctx, meta, response| {\n\n inlay_hints_response(meta, response, ctx)\n\n });\n\n}\n\n\n", "file_path": "src/language_features/rust_analyzer.rs", "rank": 13, "score": 312116.52295314195 }, { "content": "pub fn text_document_implementation(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = PositionParams::deserialize(params).unwrap();\n\n let req_params = GotoDefinitionParams {\n\n text_document_position_params: TextDocumentPositionParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(),\n\n },\n\n partial_result_params: Default::default(),\n\n work_done_progress_params: Default::default(),\n\n };\n\n ctx.call::<GotoImplementation, _>(meta, req_params, move |ctx: &mut Context, meta, result| {\n\n goto(meta, result, ctx);\n\n });\n\n}\n\n\n", "file_path": "src/language_features/goto.rs", "rank": 14, "score": 312116.52295314195 }, { "content": "pub fn text_document_definition(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = PositionParams::deserialize(params).unwrap();\n\n let req_params = GotoDefinitionParams {\n\n text_document_position_params: TextDocumentPositionParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(),\n\n },\n\n partial_result_params: Default::default(),\n\n work_done_progress_params: Default::default(),\n\n };\n\n ctx.call::<GotoDefinition, _>(meta, req_params, move |ctx: &mut Context, meta, result| {\n\n goto(meta, result, ctx);\n\n });\n\n}\n\n\n", "file_path": "src/language_features/goto.rs", "rank": 15, "score": 312116.52295314195 }, { "content": "pub fn text_document_references(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = PositionParams::deserialize(params).unwrap();\n\n let req_params = ReferenceParams {\n\n text_document_position: TextDocumentPositionParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(),\n\n },\n\n context: ReferenceContext {\n\n include_declaration: true,\n\n },\n\n partial_result_params: Default::default(),\n\n work_done_progress_params: Default::default(),\n\n };\n\n ctx.call::<References, _>(meta, req_params, move |ctx: &mut Context, meta, result| {\n\n goto(meta, result.map(GotoDefinitionResponse::Array), ctx);\n\n });\n\n}\n", "file_path": "src/language_features/goto.rs", "rank": 16, "score": 312116.52295314195 }, { "content": "pub fn text_document_rename(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = TextDocumentRenameParams::deserialize(params).unwrap();\n\n let req_params = RenameParams {\n\n text_document_position: TextDocumentPositionParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(),\n\n },\n\n new_name: params.new_name,\n\n work_done_progress_params: Default::default(),\n\n };\n\n ctx.call::<Rename, _>(meta, req_params, move |ctx: &mut Context, meta, result| {\n\n editor_rename(meta, result, ctx)\n\n });\n\n}\n\n\n", "file_path": "src/language_features/rename.rs", "rank": 17, "score": 312116.52295314195 }, { "content": "pub fn text_document_highlights(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = PositionParams::deserialize(params).unwrap();\n\n let req_params = DocumentHighlightParams {\n\n text_document_position_params: TextDocumentPositionParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(),\n\n },\n\n partial_result_params: Default::default(),\n\n work_done_progress_params: Default::default(),\n\n };\n\n ctx.call::<DocumentHighlightRequest, _>(\n\n meta,\n\n req_params,\n\n move |ctx: &mut Context, meta, result| editor_document_highlights(meta, result, ctx),\n\n );\n\n}\n\n\n", "file_path": "src/language_features/highlights.rs", "rank": 18, "score": 312116.52295314195 }, { "content": "pub fn text_document_codeaction(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = CodeActionsParams::deserialize(params)\n\n .expect(\"Params should follow CodeActionsParams structure\");\n\n let position = get_lsp_position(&meta.buffile, &params.position, ctx).unwrap();\n\n\n\n let buff_diags = ctx.diagnostics.get(&meta.buffile);\n\n\n\n let diagnostics: Vec<Diagnostic> = if let Some(buff_diags) = buff_diags {\n\n buff_diags\n\n .iter()\n\n .filter(|d| d.range.start.line <= position.line && position.line <= d.range.end.line)\n\n .cloned()\n\n .collect()\n\n } else {\n\n Vec::new()\n\n };\n\n\n\n let req_params = CodeActionParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n", "file_path": "src/language_features/codeaction.rs", "rank": 19, "score": 312116.52295314195 }, { "content": "pub fn tokens_request(meta: EditorMeta, _params: EditorParams, ctx: &mut Context) {\n\n let req_params = SemanticTokensParams {\n\n partial_result_params: Default::default(),\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n work_done_progress_params: Default::default(),\n\n };\n\n ctx.call::<SemanticTokensFullRequest, _>(meta, req_params, move |ctx, meta, response| {\n\n if let Some(response) = response {\n\n tokens_response(meta, response, ctx);\n\n }\n\n });\n\n}\n\n\n", "file_path": "src/language_features/semantic_tokens.rs", "rank": 20, "score": 312116.52295314195 }, { "content": "pub fn text_document_completion(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = TextDocumentCompletionParams::deserialize(params).unwrap();\n\n let req_params = CompletionParams {\n\n text_document_position: TextDocumentPositionParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(),\n\n },\n\n context: None,\n\n work_done_progress_params: Default::default(),\n\n partial_result_params: Default::default(),\n\n };\n\n ctx.call::<Completion, _>(meta, req_params, |ctx: &mut Context, meta, result| {\n\n editor_completion(meta, params, result, ctx)\n\n });\n\n}\n\n\n", "file_path": "src/language_features/completion.rs", "rank": 21, "score": 312116.52295314195 }, { "content": "pub fn goto_location(meta: EditorMeta, Location { uri, range }: &Location, ctx: &mut Context) {\n\n let path = uri.to_file_path().unwrap();\n\n let path_str = path.to_str().unwrap();\n\n if let Some(contents) = get_file_contents(path_str, ctx) {\n\n let pos = lsp_range_to_kakoune(range, &contents, ctx.offset_encoding).start;\n\n let command = format!(\n\n \"eval -try-client %opt{{jumpclient}} -verbatim -- edit -existing {} {} {}\",\n\n editor_quote(path_str),\n\n pos.line,\n\n pos.column,\n\n );\n\n ctx.exec(meta, command);\n\n }\n\n}\n\n\n", "file_path": "src/language_features/goto.rs", "rank": 22, "score": 309679.1381033022 }, { "content": "pub fn switch_source_header(meta: EditorMeta, ctx: &mut Context) {\n\n let req_params = TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n };\n\n ctx.call::<SwitchSourceHeaderRequest, _>(\n\n meta,\n\n req_params,\n\n move |ctx: &mut Context, meta, response| {\n\n if let Some(response) = response {\n\n let command = format!(\n\n \"eval -try-client %opt{{jumpclient}} -verbatim -- edit -existing {}\",\n\n editor_quote(response.to_file_path().unwrap().to_str().unwrap()),\n\n );\n\n ctx.exec(meta, command);\n\n }\n\n },\n\n );\n\n}\n", "file_path": "src/language_features/clangd.rs", "rank": 23, "score": 309418.99676242436 }, { "content": "pub fn text_document_type_definition(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = PositionParams::deserialize(params).unwrap();\n\n let req_params = GotoDefinitionParams {\n\n text_document_position_params: TextDocumentPositionParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(),\n\n },\n\n partial_result_params: Default::default(),\n\n work_done_progress_params: Default::default(),\n\n };\n\n ctx.call::<GotoTypeDefinition, _>(meta, req_params, move |ctx: &mut Context, meta, result| {\n\n goto(meta, result, ctx);\n\n });\n\n}\n\n\n", "file_path": "src/language_features/goto.rs", "rank": 24, "score": 307457.632516367 }, { "content": "pub fn capabilities(meta: EditorMeta, ctx: &mut Context) {\n\n // NOTE controller should park request for capabilities until they are available thus it should\n\n // be safe to unwrap here (otherwise something unexpectedly wrong and it's better to panic)\n\n\n\n let server_capabilities = ctx.capabilities.as_ref().unwrap();\n\n\n\n let mut features: Vec<String> = vec![];\n\n\n\n match server_capabilities\n\n .hover_provider\n\n .as_ref()\n\n .unwrap_or(&HoverProviderCapability::Simple(false))\n\n {\n\n HoverProviderCapability::Simple(false) => (),\n\n _ => features.push(\"lsp-hover\".to_string()),\n\n }\n\n\n\n if server_capabilities.completion_provider.is_some() {\n\n features.push(\"lsp-completion (hooked on InsertIdle)\".to_string());\n\n }\n", "file_path": "src/general.rs", "rank": 25, "score": 307369.0670174831 }, { "content": "pub fn workspace_symbol(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = WorkspaceSymbolParams::deserialize(params)\n\n .expect(\"Params should follow WorkspaceSymbolParams structure\");\n\n ctx.call::<WorkspaceSymbol, _>(meta, params, move |ctx: &mut Context, meta, result| {\n\n editor_workspace_symbol(meta, result, ctx)\n\n });\n\n}\n\n\n", "file_path": "src/workspace.rs", "rank": 26, "score": 306402.87805025734 }, { "content": "pub fn organize_imports(meta: EditorMeta, ctx: &mut Context) {\n\n let file_uri = Url::from_file_path(&meta.buffile).unwrap();\n\n\n\n let file_uri: String = file_uri.into();\n\n let req_params = ExecuteCommandParams {\n\n command: \"java.edit.organizeImports\".to_string(),\n\n arguments: vec![serde_json::json!(file_uri)],\n\n ..ExecuteCommandParams::default()\n\n };\n\n ctx.call::<ExecuteCommand, _>(\n\n meta,\n\n req_params,\n\n move |ctx: &mut Context, meta, response| {\n\n if let Some(response) = response {\n\n organize_imports_response(meta, serde_json::from_value(response).unwrap(), ctx);\n\n }\n\n },\n\n );\n\n}\n\n\n", "file_path": "src/language_features/eclipse_jdt_ls.rs", "rank": 27, "score": 304647.6555925973 }, { "content": "pub fn text_document_signature_help(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = PositionParams::deserialize(params).unwrap();\n\n let req_params = SignatureHelpParams {\n\n context: None,\n\n text_document_position_params: TextDocumentPositionParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(),\n\n },\n\n work_done_progress_params: Default::default(),\n\n };\n\n ctx.call::<SignatureHelpRequest, _>(\n\n meta,\n\n req_params,\n\n move |ctx: &mut Context, meta, result| editor_signature_help(meta, params, result, ctx),\n\n );\n\n}\n\n\n", "file_path": "src/language_features/signature_help.rs", "rank": 28, "score": 303038.09197036945 }, { "content": "pub fn apply_edit_from_editor(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = EditorApplyEdit::deserialize(params).expect(\"Failed to parse params\");\n\n let edit = WorkspaceEdit::deserialize(serde_json::from_str::<Value>(&params.edit).unwrap())\n\n .expect(\"Failed to parse edit\");\n\n\n\n apply_edit(meta, edit, ctx);\n\n}\n\n\n", "file_path": "src/workspace.rs", "rank": 29, "score": 301554.98991729855 }, { "content": "pub fn text_document_document_symbol(meta: EditorMeta, ctx: &mut Context) {\n\n let req_params = DocumentSymbolParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n partial_result_params: Default::default(),\n\n work_done_progress_params: Default::default(),\n\n };\n\n ctx.call::<DocumentSymbolRequest, _>(\n\n meta,\n\n req_params,\n\n move |ctx: &mut Context, meta, result| editor_document_symbol(meta, result, ctx),\n\n );\n\n}\n\n\n", "file_path": "src/language_features/document_symbol.rs", "rank": 30, "score": 300151.41125303705 }, { "content": "pub fn publish_diagnostics(params: Params, ctx: &mut Context) {\n\n let params: PublishDiagnosticsParams = params.parse().expect(\"Failed to parse params\");\n\n let session = ctx.session.clone();\n\n let client = None;\n\n let path = params.uri.to_file_path().unwrap();\n\n let buffile = path.to_str().unwrap();\n\n ctx.diagnostics\n\n .insert(buffile.to_string(), params.diagnostics);\n\n let document = ctx.documents.get(buffile);\n\n if document.is_none() {\n\n return;\n\n }\n\n let document = document.unwrap();\n\n let version = document.version;\n\n let diagnostics = &ctx.diagnostics[buffile];\n\n let ranges = diagnostics\n\n .iter()\n\n .sorted_unstable_by_key(|x| x.severity)\n\n .rev()\n\n .map(|x| {\n", "file_path": "src/diagnostics.rs", "rank": 31, "score": 299608.372441879 }, { "content": "pub fn tokens_response(meta: EditorMeta, tokens: SemanticTokensResult, ctx: &mut Context) {\n\n let legend = match ctx.capabilities.as_ref().unwrap().semantic_tokens_provider {\n\n Some(SemanticTokensOptions(SemanticTokensOptions { ref legend, .. }))\n\n | Some(SemanticTokensRegistrationOptions(SemanticTokensRegistrationOptions {\n\n semantic_tokens_options: SemanticTokensOptions { ref legend, .. },\n\n ..\n\n })) => legend,\n\n None => return,\n\n };\n\n let document = match ctx.documents.get(&meta.buffile) {\n\n Some(document) => document,\n\n None => return,\n\n };\n\n let tokens = match tokens {\n\n SemanticTokensResult::Tokens(tokens) => tokens.data,\n\n SemanticTokensResult::Partial(partial) => partial.data,\n\n };\n\n let mut line = 0;\n\n let mut start = 0;\n\n let ranges = tokens\n", "file_path": "src/language_features/semantic_tokens.rs", "rank": 32, "score": 297727.13499400206 }, { "content": "pub fn text_document_did_change(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = TextDocumentDidChangeParams::deserialize(params)\n\n .expect(\"Params should follow TextDocumentDidChangeParams structure\");\n\n let uri = Url::from_file_path(&meta.buffile).unwrap();\n\n let version = meta.version;\n\n let old_version = ctx\n\n .documents\n\n .get(&meta.buffile)\n\n .map(|doc| doc.version)\n\n .unwrap_or(0);\n\n if old_version >= version {\n\n return;\n\n }\n\n let document = Document {\n\n version,\n\n text: Rope::from_str(&params.draft),\n\n };\n\n ctx.documents.insert(meta.buffile.clone(), document);\n\n ctx.diagnostics.insert(meta.buffile.clone(), Vec::new());\n\n let params = DidChangeTextDocumentParams {\n", "file_path": "src/text_sync.rs", "rank": 33, "score": 296975.231389536 }, { "content": "pub fn text_document_did_open(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = TextDocumentDidOpenParams::deserialize(params)\n\n .expect(\"Params should follow TextDocumentDidOpenParams structure\");\n\n let language_id = ctx.language_id.clone();\n\n let params = DidOpenTextDocumentParams {\n\n text_document: TextDocumentItem {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n language_id,\n\n version: meta.version,\n\n text: params.draft,\n\n },\n\n };\n\n let document = Document {\n\n version: meta.version,\n\n text: Rope::from_str(&params.text_document.text),\n\n };\n\n ctx.documents.insert(meta.buffile, document);\n\n ctx.notify::<DidOpenTextDocument>(params);\n\n}\n\n\n", "file_path": "src/text_sync.rs", "rank": 34, "score": 296975.23138953606 }, { "content": "pub fn text_document_did_close(meta: EditorMeta, ctx: &mut Context) {\n\n ctx.documents.remove(&meta.buffile);\n\n let uri = Url::from_file_path(&meta.buffile).unwrap();\n\n let params = DidCloseTextDocumentParams {\n\n text_document: TextDocumentIdentifier { uri },\n\n };\n\n ctx.notify::<DidCloseTextDocument>(params);\n\n}\n\n\n", "file_path": "src/text_sync.rs", "rank": 35, "score": 292445.4828572107 }, { "content": "pub fn text_document_did_save(meta: EditorMeta, ctx: &mut Context) {\n\n let uri = Url::from_file_path(&meta.buffile).unwrap();\n\n let params = DidSaveTextDocumentParams {\n\n text_document: TextDocumentIdentifier { uri },\n\n text: None,\n\n };\n\n ctx.notify::<DidSaveTextDocument>(params);\n\n}\n", "file_path": "src/text_sync.rs", "rank": 36, "score": 292445.4828572107 }, { "content": "pub fn goto_locations(meta: EditorMeta, locations: &[Location], ctx: &mut Context) {\n\n let select_location = locations\n\n .iter()\n\n .group_by(|Location { uri, .. }| uri.to_file_path().unwrap())\n\n .into_iter()\n\n .map(|(path, locations)| {\n\n let path_str = path.to_str().unwrap();\n\n let contents = match get_file_contents(path_str, ctx) {\n\n Some(contents) => contents,\n\n None => return \"\".into(),\n\n };\n\n locations\n\n .map(|Location { range, .. }| {\n\n let pos = lsp_range_to_kakoune(range, &contents, ctx.offset_encoding).start;\n\n if range.start.line as usize >= contents.len_lines() {\n\n return \"\".into();\n\n }\n\n format!(\n\n \"{}:{}:{}:{}\",\n\n short_file_path(path_str, &ctx.root_path),\n", "file_path": "src/language_features/goto.rs", "rank": 37, "score": 290483.8355318017 }, { "content": "pub fn initialize(root_path: &str, meta: EditorMeta, ctx: &mut Context) {\n\n let initialization_options = request_initialization_options_from_kakoune(&meta, ctx);\n\n #[allow(deprecated)] // for root_path\n\n let params = InitializeParams {\n\n capabilities: ClientCapabilities {\n\n workspace: Some(WorkspaceClientCapabilities {\n\n apply_edit: Some(false),\n\n workspace_edit: Some(WorkspaceEditClientCapabilities {\n\n document_changes: Some(true),\n\n resource_operations: Some(vec![\n\n ResourceOperationKind::Create,\n\n ResourceOperationKind::Delete,\n\n ResourceOperationKind::Rename,\n\n ]),\n\n failure_handling: Some(FailureHandlingKind::Abort),\n\n normalizes_line_endings: Some(false),\n\n change_annotation_support: Some(\n\n ChangeAnnotationWorkspaceEditClientCapabilities {\n\n groups_on_label: None,\n\n },\n", "file_path": "src/general.rs", "rank": 38, "score": 278281.66279641504 }, { "content": "pub fn publish_semantic_highlighting(params: Params, ctx: &mut Context) {\n\n let params: PublishSemanticHighlightingParams =\n\n params.parse().expect(\"Failed to parse semhl params\");\n\n let session = ctx.session.clone();\n\n let client = None;\n\n let path = params.uri.to_file_path().unwrap();\n\n let buffile = path.to_str().unwrap();\n\n let document = ctx.documents.get(buffile);\n\n if document.is_none() {\n\n return;\n\n }\n\n let document = document.unwrap();\n\n let version = document.version;\n\n let ranges = params\n\n .symbols\n\n .iter()\n\n .flat_map(|x| {\n\n let face = x.get_face();\n\n let offset_encoding = ctx.offset_encoding.to_owned();\n\n x.ranges.iter().filter_map(move |r| {\n", "file_path": "src/language_features/cquery.rs", "rank": 39, "score": 270625.3153650191 }, { "content": "pub fn publish_semantic_highlighting(params: Params, ctx: &mut Context) {\n\n let params: PublishSemanticHighlightingParams =\n\n params.parse().expect(\"Failed to parse semhl params\");\n\n let path = params.uri.to_file_path().unwrap();\n\n let buffile = path.to_str().unwrap();\n\n let document = match ctx.documents.get(buffile) {\n\n Some(document) => document,\n\n None => return,\n\n };\n\n let meta = match ctx.meta_for_buffer(buffile) {\n\n Some(meta) => meta,\n\n None => return,\n\n };\n\n let ranges = params\n\n .symbols\n\n .iter()\n\n .flat_map(|x| {\n\n let face = x.get_face();\n\n let offset_encoding = ctx.offset_encoding.to_owned();\n\n x.ls_ranges.iter().filter_map(move |r| {\n", "file_path": "src/language_features/ccls.rs", "rank": 40, "score": 270625.3153650191 }, { "content": "pub fn configuration(params: Params, ctx: &mut Context) -> Result<Value, jsonrpc_core::Error> {\n\n let params = params.parse::<ConfigurationParams>()?;\n\n\n\n let meta = ctx.meta_for_session();\n\n let dynamic_settings = request_dynamic_configuration_from_kakoune(&meta, ctx);\n\n let settings = dynamic_settings\n\n .and_then(|cfg| cfg.settings.as_ref().cloned())\n\n .or_else(|| {\n\n ctx.config\n\n .language\n\n .get(&ctx.language_id)\n\n .and_then(|conf| conf.settings.as_ref().cloned())\n\n });\n\n\n\n let items = params\n\n .items\n\n .iter()\n\n .map(|item| {\n\n // There's also a `scopeUri`, which lists the file/folder\n\n // that the config should apply to. But kak-lsp doesn't\n", "file_path": "src/workspace.rs", "rank": 41, "score": 267521.67665005836 }, { "content": "pub fn inlay_hints_response(meta: EditorMeta, inlay_hints: Vec<InlayHint>, ctx: &mut Context) {\n\n let document = match ctx.documents.get(&meta.buffile) {\n\n Some(document) => document,\n\n None => return,\n\n };\n\n let ranges = inlay_hints\n\n .into_iter()\n\n .map(|InlayHint { range, kind, label }| {\n\n let range = lsp_range_to_kakoune(&range, &document.text, ctx.offset_encoding);\n\n let label = escape_tuple_element(&label);\n\n match kind {\n\n InlayKind::TypeHint => {\n\n let pos = KakounePosition {\n\n line: range.end.line,\n\n column: range.end.column + 1,\n\n };\n\n editor_quote(&format!(\"{}+0|{{InlayHint}}{{\\\\}}: {}\", pos, label))\n\n }\n\n InlayKind::ParameterHint => {\n\n editor_quote(&format!(\"{}+0|{{InlayHint}}{{\\\\}}{}: \", range.start, label))\n", "file_path": "src/language_features/rust_analyzer.rs", "rank": 42, "score": 264220.12035643915 }, { "content": "pub fn exit(ctx: &mut Context) {\n\n ctx.notify::<Exit>(());\n\n}\n\n\n", "file_path": "src/general.rs", "rank": 43, "score": 255421.8316790378 }, { "content": "pub fn start(cmd: &str, args: &[String]) -> Result<LanguageServerTransport, String> {\n\n info!(\"Starting Language server `{} {}`\", cmd, args.join(\" \"));\n\n let mut child = match Command::new(cmd)\n\n .args(args)\n\n .stdin(Stdio::piped())\n\n .stdout(Stdio::piped())\n\n .stderr(Stdio::piped())\n\n .spawn()\n\n {\n\n Ok(c) => c,\n\n Err(err) => {\n\n return Err(match err.kind() {\n\n ErrorKind::NotFound | ErrorKind::PermissionDenied => format!(\"{}: {}\", err, cmd),\n\n _ => format!(\"{}\", err),\n\n })\n\n }\n\n };\n\n\n\n let writer = BufWriter::new(child.stdin.take().expect(\"Failed to open stdin\"));\n\n let reader = BufReader::new(child.stdout.take().expect(\"Failed to open stdout\"));\n", "file_path": "src/language_server_transport.rs", "rank": 44, "score": 252130.13994583767 }, { "content": "/// Apply text edits to the file pointed by uri either by asking Kakoune to modify corresponding\n\n/// buffer or by editing file directly when it's not open in editor.\n\npub fn apply_text_edits(meta: &EditorMeta, uri: &Url, edits: Vec<TextEdit>, ctx: &Context) {\n\n let edits = edits.into_iter().map(OneOf::Left).collect::<Vec<_>>();\n\n apply_annotated_text_edits(meta, uri, &edits, ctx)\n\n}\n\n\n", "file_path": "src/text_edit.rs", "rank": 45, "score": 248679.11803386052 }, { "content": "pub fn dispatch_pending_editor_requests(mut ctx: &mut Context) {\n\n let mut requests = std::mem::take(&mut ctx.pending_requests);\n\n\n\n for msg in requests.drain(..) {\n\n dispatch_editor_request(msg, &mut ctx);\n\n }\n\n}\n\n\n", "file_path": "src/controller.rs", "rank": 46, "score": 247533.07632735575 }, { "content": "/// Start the main event loop.\n\n///\n\n/// This function starts editor transport and routes incoming editor requests to controllers.\n\n/// One controller is spawned per unique route, which is essentially a product of editor session,\n\n/// file type (represented as language id) and project (represented as project root path).\n\n///\n\n/// `initial_request` could be passed to avoid extra synchronization churn if event loop is started\n\n/// as a result of request from editor.\n\npub fn start(config: &Config, initial_request: Option<String>) -> i32 {\n\n info!(\"Starting main event loop\");\n\n\n\n let editor = editor_transport::start(&config.server.session, initial_request);\n\n if let Err(code) = editor {\n\n return code;\n\n }\n\n let editor = editor.unwrap();\n\n\n\n let languages = config.language.clone();\n\n let filetypes = filetype_to_language_id_map(config);\n\n\n\n let mut controllers: Controllers = HashMap::default();\n\n\n\n let timeout = config.server.timeout;\n\n\n\n 'event_loop: loop {\n\n let timeout_channel = if timeout > 0 {\n\n after(Duration::from_secs(timeout))\n\n } else {\n", "file_path": "src/session.rs", "rank": 47, "score": 242201.90014843512 }, { "content": "/// Represent list of symbol information as filetype=grep buffer content.\n\n/// Paths are converted into relative to project root.\n\npub fn format_symbol_information(items: Vec<SymbolInformation>, ctx: &Context) -> String {\n\n items\n\n .into_iter()\n\n .map(|symbol| {\n\n let SymbolInformation {\n\n location,\n\n name,\n\n kind,\n\n ..\n\n } = symbol;\n\n let filename = location.uri.to_file_path().unwrap();\n\n let filename_str = filename.to_str().unwrap();\n\n let position = get_kakoune_position(filename_str, &location.range.start, ctx)\n\n .unwrap_or_else(|| KakounePosition {\n\n line: location.range.start.line + 1,\n\n column: location.range.start.character + 1,\n\n });\n\n let description = format!(\"{:?} {}\", kind, name);\n\n format!(\n\n \"{}:{}:{}:{}\",\n", "file_path": "src/util.rs", "rank": 48, "score": 234642.3637741778 }, { "content": "/// Convert language filetypes configuration into a more lookup-friendly form.\n\npub fn filetype_to_language_id_map(config: &Config) -> HashMap<String, String> {\n\n let mut filetypes = HashMap::default();\n\n for (language_id, language) in &config.language {\n\n for filetype in &language.filetypes {\n\n filetypes.insert(filetype.clone(), language_id.clone());\n\n }\n\n }\n\n filetypes\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 49, "score": 234213.61283673136 }, { "content": "pub fn start(session: &str, initial_request: Option<String>) -> Result<EditorTransport, i32> {\n\n // NOTE 1024 is arbitrary\n\n let channel_capacity = 1024;\n\n\n\n let (sender, receiver) = bounded(channel_capacity);\n\n let mut path = temp_dir();\n\n path.push(&session);\n\n if path.exists() {\n\n if UnixStream::connect(&path).is_err() {\n\n if fs::remove_file(&path).is_err() {\n\n error!(\n\n \"Failed to clean up dead session at {}\",\n\n path.to_str().unwrap()\n\n );\n\n return Err(1);\n\n };\n\n } else {\n\n error!(\"Server is already running for session {}\", session);\n\n return Err(1);\n\n }\n", "file_path": "src/editor_transport.rs", "rank": 50, "score": 198458.84475420346 }, { "content": "/// Ensure that textDocument/didOpen is sent for the given buffer before any other request, if possible.\n\n///\n\n/// kak-lsp tries to not bother Kakoune side of the plugin with bookkeeping status of kak-lsp server\n\n/// itself and lsp servers run by it. It is possible that kak-lsp server or lsp server dies at some\n\n/// point while Kakoune session is still running. That session can send a request for some already\n\n/// open (opened before kak-lsp/lsp exit) buffer. In this case, kak-lsp/lsp server will be restarted\n\n/// by the incoming request. `ensure_did_open` tries to sneak in `textDocument/didOpen` request for\n\n/// this buffer then as the specification requires to send such request before other requests for\n\n/// the file.\n\n///\n\n/// In a normal situation, such extra request is not required, and `ensure_did_open` short-circuits\n\n/// most of the time in `if buffile.is_empty() || ctx.documents.contains_key(buffile)` condition.\n\nfn ensure_did_open(request: &EditorRequest, mut ctx: &mut Context) {\n\n let buffile = &request.meta.buffile;\n\n if buffile.is_empty() || ctx.documents.contains_key(buffile) {\n\n return;\n\n };\n\n if request.method == notification::DidChangeTextDocument::METHOD {\n\n return text_document_did_open(request.meta.clone(), request.params.clone(), &mut ctx);\n\n }\n\n match read_document(buffile) {\n\n Ok(draft) => {\n\n let mut params = toml::value::Table::default();\n\n params.insert(\"draft\".to_string(), toml::Value::String(draft));\n\n text_document_did_open(request.meta.clone(), toml::Value::Table(params), &mut ctx);\n\n }\n\n Err(err) => error!(\n\n \"Failed to read file {} to simulate textDocument/didOpen: {}\",\n\n buffile, err\n\n ),\n\n };\n\n}\n", "file_path": "src/controller.rs", "rank": 51, "score": 198204.2007304829 }, { "content": "fn dispatch_editor_request(request: EditorRequest, mut ctx: &mut Context) {\n\n ensure_did_open(&request, ctx);\n\n let meta = request.meta;\n\n let params = request.params;\n\n let method: &str = &request.method;\n\n let ranges: Option<Vec<Range>> = request.ranges;\n\n match method {\n\n notification::DidOpenTextDocument::METHOD => {\n\n text_document_did_open(meta, params, &mut ctx);\n\n }\n\n notification::DidChangeTextDocument::METHOD => {\n\n text_document_did_change(meta, params, &mut ctx);\n\n }\n\n notification::DidCloseTextDocument::METHOD => {\n\n text_document_did_close(meta, &mut ctx);\n\n }\n\n notification::DidSaveTextDocument::METHOD => {\n\n text_document_did_save(meta, &mut ctx);\n\n }\n\n notification::DidChangeConfiguration::METHOD => {\n", "file_path": "src/controller.rs", "rank": 52, "score": 194894.44875174324 }, { "content": "/// Get the contents of a file.\n\n/// Searches ctx.documents first and falls back to reading the file directly.\n\npub fn get_file_contents(filename: &str, ctx: &Context) -> Option<Rope> {\n\n if let Some(doc) = ctx.documents.get(filename) {\n\n return Some(doc.text.clone());\n\n }\n\n\n\n match read_document(filename) {\n\n Ok(text) => Some(Rope::from_str(&text)),\n\n Err(err) => {\n\n error!(\"Failed to read file {}: {}\", filename, err);\n\n None\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 53, "score": 193905.33851176477 }, { "content": "/// Transpile the contents of an `lsp_types::MarkedString` into Kakoune markup\n\npub fn marked_string_to_kakoune_markup(contents: MarkedString, have_plaintext: bool) -> String {\n\n match contents {\n\n MarkedString::String(s) => markdown_to_kakoune_markup(s, have_plaintext),\n\n MarkedString::LanguageString(s) => {\n\n format!(\n\n \"{{{}}}{}{{{}}}\",\n\n FACE_INFO_BLOCK,\n\n escape_brace(&s.value),\n\n FACE_INFO_DEFAULT\n\n )\n\n }\n\n }\n\n}\n", "file_path": "src/markup.rs", "rank": 54, "score": 190418.04452997408 }, { "content": "fn dispatch_server_request(request: MethodCall, ctx: &mut Context) {\n\n let method: &str = &request.method;\n\n let result = match method {\n\n request::ApplyWorkspaceEdit::METHOD => {\n\n workspace::apply_edit_from_server(request.params, ctx)\n\n }\n\n request::WorkspaceConfiguration::METHOD => workspace::configuration(request.params, ctx),\n\n _ => {\n\n warn!(\"Unsupported method: {}\", method);\n\n Err(jsonrpc_core::Error::new(\n\n jsonrpc_core::ErrorCode::MethodNotFound,\n\n ))\n\n }\n\n };\n\n\n\n ctx.reply(request.id, result);\n\n}\n\n\n", "file_path": "src/controller.rs", "rank": 55, "score": 184364.28922344942 }, { "content": "pub fn read_document(filename: &str) -> io::Result<String> {\n\n // We can ignore invalid UTF-8 since we only use this to compute positions. The width of\n\n // the replacement character is 1, which should usually be correct.\n\n Ok(String::from_utf8_lossy(&fs::read(filename)?).to_string())\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 56, "score": 183850.97604599159 }, { "content": "/// Start controller.\n\n///\n\n/// Controller spawns language server for the given language and project root (passed as `route`).\n\n/// Then it takes care of dispatching editor requests to this language server and dispatching\n\n/// responses back to editor.\n\npub fn start(\n\n to_editor: Sender<EditorResponse>,\n\n from_editor: Receiver<EditorRequest>,\n\n route: &Route,\n\n initial_request: EditorRequest,\n\n config: Config,\n\n) {\n\n let lang_srv: language_server_transport::LanguageServerTransport;\n\n let offset_encoding;\n\n {\n\n // should be fine to unwrap because request was already routed which means language is configured\n\n let lang = &config.language[&route.language];\n\n offset_encoding = lang.offset_encoding;\n\n lang_srv = match language_server_transport::start(&lang.command, &lang.args) {\n\n Ok(ls) => ls,\n\n Err(err) => {\n\n // If we think that the server command is not from the default config, then we\n\n // send a prominent error to the editor, since it's likely configuration error.\n\n let might_be_from_default_config =\n\n !lang.command.contains('/') && !lang.command.contains(' ');\n", "file_path": "src/controller.rs", "rank": 57, "score": 178881.95180668763 }, { "content": "fn writer_loop(mut writer: impl Write, receiver: &Receiver<ServerMessage>) -> io::Result<()> {\n\n for request in receiver {\n\n let request = match request {\n\n ServerMessage::Request(request) => serde_json::to_string(&request),\n\n ServerMessage::Response(response) => serde_json::to_string(&response),\n\n }?;\n\n debug!(\"To server: {}\", request);\n\n write!(\n\n writer,\n\n \"Content-Length: {}\\r\\n\\r\\n{}\",\n\n request.len(),\n\n request\n\n )?;\n\n writer.flush()?;\n\n }\n\n // NOTE we rely on the assumption that language server will exit when its stdin is closed\n\n // without need to kill child process\n\n debug!(\"Received signal to stop language server, closing pipe\");\n\n Ok(())\n\n}\n", "file_path": "src/language_server_transport.rs", "rank": 58, "score": 177009.51633749818 }, { "content": "pub fn editor_range_formatting(\n\n meta: EditorMeta,\n\n text_edits: &[OneOf<TextEdit, AnnotatedTextEdit>],\n\n ctx: &mut Context,\n\n) {\n\n let cmd = ctx.documents.get(&meta.buffile).and_then(|document| {\n\n apply_text_edits_to_buffer(\n\n &meta.client,\n\n None,\n\n text_edits,\n\n &document.text,\n\n ctx.offset_encoding,\n\n )\n\n });\n\n match cmd {\n\n Some(cmd) => ctx.exec(meta, cmd),\n\n // Nothing to do, but sending command back to the editor is required to handle case when\n\n // editor is blocked waiting for response via fifo.\n\n None => ctx.exec(meta, \"nop\"),\n\n }\n\n}\n", "file_path": "src/language_features/range_formatting.rs", "rank": 59, "score": 164872.3354861639 }, { "content": "pub fn text_document_range_formatting(\n\n meta: EditorMeta,\n\n params: EditorParams,\n\n ranges: Vec<Range>,\n\n ctx: &mut Context,\n\n) {\n\n let params = FormattingOptions::deserialize(params)\n\n .expect(\"Params should follow FormattingOptions structure\");\n\n let req_params = ranges\n\n .into_iter()\n\n .map(|range| DocumentRangeFormattingParams {\n\n text_document: TextDocumentIdentifier {\n\n uri: Url::from_file_path(&meta.buffile).unwrap(),\n\n },\n\n range,\n\n options: params.clone(),\n\n work_done_progress_params: Default::default(),\n\n })\n\n .collect();\n\n ctx.batch_call::<RangeFormatting, _>(\n", "file_path": "src/language_features/range_formatting.rs", "rank": 60, "score": 161124.95403920033 }, { "content": "pub fn find_project_root(language: &str, markers: &[String], path: &str) -> String {\n\n if let Ok(force_root) = env::var(\"KAK_LSP_FORCE_PROJECT_ROOT\") {\n\n debug!(\n\n \"Using $KAK_LSP_FORCE_PROJECT_ROOT as project root: \\\"{}\\\"\",\n\n force_root\n\n );\n\n return force_root;\n\n }\n\n let vars = gather_env_roots(language);\n\n if vars.is_empty() {\n\n roots_by_marker(markers, path)\n\n } else {\n\n roots_by_env(&vars, path).unwrap_or_else(|| roots_by_marker(markers, path))\n\n }\n\n}\n\n\n", "file_path": "src/project_root.rs", "rank": 61, "score": 160061.3958828012 }, { "content": "pub trait IntoParams {\n\n fn into_params(self) -> Result<Params, Error>;\n\n}\n\n\n\nimpl<T> IntoParams for T\n\nwhere\n\n T: Serialize,\n\n{\n\n fn into_params(self) -> Result<Params, Error> {\n\n let json_value = serde_json::to_value(self)?;\n\n\n\n let params = match json_value {\n\n Value::Null => Params::None,\n\n Value::Bool(_) | Value::Number(_) | Value::String(_) => Params::Array(vec![json_value]),\n\n Value::Array(vec) => Params::Array(vec),\n\n Value::Object(map) => Params::Map(map),\n\n };\n\n\n\n Ok(params)\n\n }\n", "file_path": "src/types.rs", "rank": 62, "score": 156137.6636340968 }, { "content": "/// Escape Kakoune string wrapped into single quote\n\npub fn editor_escape(s: &str) -> String {\n\n s.replace(\"'\", \"''\")\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 63, "score": 151580.28609176984 }, { "content": "/// Espace opening braces for Kakoune markup strings\n\npub fn escape_brace(s: &str) -> String {\n\n s.replace(\"{\", \"\\\\{\")\n\n}\n\n\n", "file_path": "src/markup.rs", "rank": 64, "score": 151580.28609176984 }, { "content": "/// Convert to Kakoune string by wrapping into quotes and escaping\n\npub fn editor_quote(s: &str) -> String {\n\n format!(\"'{}'\", editor_escape(s))\n\n}\n\n\n\n#[allow(dead_code)]\n", "file_path": "src/util.rs", "rank": 65, "score": 151580.28609176984 }, { "content": "pub fn roots_by_marker(roots: &[String], path: &str) -> String {\n\n let mut src = PathBuf::from(path);\n\n // For scratch buffers we get a bare filename.\n\n if !src.is_absolute() {\n\n src = env::current_dir().expect(\"cannot access current directory\");\n\n }\n\n while !src.is_dir() {\n\n src.pop();\n\n }\n\n\n\n for root in roots {\n\n let mut pwd = src.clone();\n\n loop {\n\n // unwrap should be safe here because we walk up path previously converted from str\n\n let matches = glob(pwd.join(root).to_str().unwrap());\n\n if let Ok(mut m) = matches {\n\n if m.next().is_some() {\n\n // ditto unwrap\n\n let root_dir = pwd.to_str().unwrap().to_string();\n\n info!(\n", "file_path": "src/project_root.rs", "rank": 66, "score": 151509.70619603572 }, { "content": "fn setup_logger(config: &Config, matches: &clap::ArgMatches<'_>) -> slog_scope::GlobalLoggerGuard {\n\n let mut verbosity = matches.occurrences_of(\"v\") as u8;\n\n\n\n if verbosity == 0 {\n\n verbosity = config.verbosity\n\n }\n\n\n\n let level = match verbosity {\n\n 0 => Severity::Error,\n\n 1 => Severity::Warning,\n\n 2 => Severity::Info,\n\n 3 => Severity::Debug,\n\n _ => Severity::Trace,\n\n };\n\n\n\n let logger = if let Some(log_path) = matches.value_of(\"log\") {\n\n let mut builder = FileLoggerBuilder::new(log_path);\n\n builder.level(level);\n\n builder.build().unwrap()\n\n } else {\n", "file_path": "src/main.rs", "rank": 67, "score": 151479.9394504826 }, { "content": "pub fn lsp_position_to_kakoune(\n\n position: &Position,\n\n text: &Rope,\n\n offset_encoding: OffsetEncoding,\n\n) -> KakounePosition {\n\n match offset_encoding {\n\n OffsetEncoding::Utf8 => lsp_position_to_kakoune_utf_8_code_units(position),\n\n // Not a proper UTF-16 code units handling, but works within BMP\n\n OffsetEncoding::Utf16 => lsp_position_to_kakoune_utf_8_code_points(position, text),\n\n }\n\n}\n\n\n", "file_path": "src/position.rs", "rank": 68, "score": 149006.66108177672 }, { "content": "pub fn kakoune_position_to_lsp(\n\n position: &KakounePosition,\n\n text: &Rope,\n\n offset_encoding: OffsetEncoding,\n\n) -> Position {\n\n match offset_encoding {\n\n OffsetEncoding::Utf8 => kakoune_position_to_lsp_utf_8_code_units(position),\n\n // Not a proper UTF-16 code units handling, but works within BMP\n\n OffsetEncoding::Utf16 => kakoune_position_to_lsp_utf_8_code_points(position, text),\n\n }\n\n}\n\n\n", "file_path": "src/position.rs", "rank": 69, "score": 149006.66108177672 }, { "content": "/// Escape Kakoune tuple element, as used in option types \"completions\", \"line-specs\" and\n\n/// \"range-specs\".\n\npub fn escape_tuple_element(s: &str) -> String {\n\n s.replace(\"\\\\\", \"\\\\\\\\\").replace(\"|\", \"\\\\|\")\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 70, "score": 148256.44901582986 }, { "content": "/// Escape Kakoune string wrapped into double quote\n\npub fn editor_escape_double_quotes(s: &str) -> String {\n\n s.replace(\"\\\"\", \"\\\"\\\"\")\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 71, "score": 145186.01287083607 }, { "content": "/// Convert to Kakoune string by wrapping into double quotes and escaping\n\npub fn editor_quote_double_quotes(s: &str) -> String {\n\n format!(\"\\\"{}\\\"\", editor_escape_double_quotes(s))\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 72, "score": 145185.95204556338 }, { "content": "/// Transpile Markdown into Kakoune's markup syntax using faces for highlighting\n\npub fn markdown_to_kakoune_markup<S: AsRef<str>>(markdown: S, have_plaintext: bool) -> String {\n\n let markdown = markdown.as_ref();\n\n if have_plaintext {\n\n return escape_brace(markdown);\n\n }\n\n let parser = Parser::new(markdown);\n\n let mut markup = String::with_capacity(markdown.len());\n\n\n\n // State to indicate a code block\n\n let mut is_codeblock = false;\n\n // State to indicate a block quote\n\n let mut is_blockquote = false;\n\n // State to indicate that at least one text line in a block quote\n\n // has been emitted\n\n let mut has_blockquote_text = false;\n\n // A stack to track nested lists.\n\n // The value tracks ordered vs unordered and the current entry number.\n\n let mut list_stack: Vec<Option<u64>> = vec![];\n\n // A stack to track the current 'base' face.\n\n // Certain tags can be nested, in which case it is not correct to just emit `{default}`\n", "file_path": "src/markup.rs", "rank": 73, "score": 139854.05130297586 }, { "content": "pub fn parse_dynamic_config(\n\n meta: &EditorMeta,\n\n ctx: &mut Context,\n\n config: &str,\n\n) -> Option<DynamicLanguageConfig> {\n\n debug!(\"lsp_config:\\n{}\", config);\n\n let mut config: DynamicConfig = match toml::from_str(config) {\n\n Ok(cfg) => cfg,\n\n Err(e) => {\n\n let msg = format!(\"failed to parse %opt{{lsp_config}}: {}\", e);\n\n ctx.exec(\n\n meta.clone(),\n\n format!(\"lsp-show-error {}\", editor_quote(&msg)),\n\n );\n\n panic!(\"{}\", msg)\n\n }\n\n };\n\n config.language.remove(&ctx.language_id)\n\n}\n\n\n", "file_path": "src/settings.rs", "rank": 74, "score": 139254.22256731807 }, { "content": "pub fn format_document_symbol(\n\n items: Vec<DocumentSymbol>,\n\n meta: &EditorMeta,\n\n ctx: &Context,\n\n) -> String {\n\n items\n\n .into_iter()\n\n .map(|symbol| {\n\n let DocumentSymbol {\n\n range, name, kind, ..\n\n } = symbol;\n\n let position =\n\n get_kakoune_position(&meta.buffile, &range.start, ctx).unwrap_or_else(|| {\n\n KakounePosition {\n\n line: range.start.line + 1,\n\n column: range.start.character + 1,\n\n }\n\n });\n\n let description = format!(\"{:?} {}\", kind, name);\n\n format!(\n\n \"{}:{}:{}:{}\",\n\n short_file_path(&meta.buffile, &ctx.root_path),\n\n position.line,\n\n position.column,\n\n description\n\n )\n\n })\n\n .join(\"\\n\")\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 75, "score": 139241.64055361506 }, { "content": "/// Wrapper for kakoune_position_to_lsp which uses context to get buffer content and offset encoding.\n\npub fn get_lsp_position(\n\n filename: &str,\n\n position: &KakounePosition,\n\n ctx: &Context,\n\n) -> Option<Position> {\n\n ctx.documents\n\n .get(filename)\n\n .map(|document| kakoune_position_to_lsp(position, &document.text, ctx.offset_encoding))\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 76, "score": 139102.81658997093 }, { "content": "/// Wrapper for lsp_position_to_kakoune which uses context to get buffer content and offset encoding.\n\n/// Reads the file directly if it is not present in context (is not open in editor).\n\npub fn get_kakoune_position(\n\n filename: &str,\n\n position: &Position,\n\n ctx: &Context,\n\n) -> Option<KakounePosition> {\n\n get_file_contents(filename, ctx)\n\n .map(|text| lsp_position_to_kakoune(position, &text, ctx.offset_encoding))\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 77, "score": 139102.29843926887 }, { "content": "// Take flattened tables like \"a.b = 1\" and produce \"{\"a\":{\"b\":1}}\".\n\npub fn explode_string_table(\n\n raw_settings: &toml::value::Table,\n\n) -> serde_json::value::Map<String, Value> {\n\n let mut settings = serde_json::Map::new();\n\n\n\n for (raw_key, raw_value) in raw_settings.iter() {\n\n let mut key_parts = raw_key.split('.');\n\n let local_key = match key_parts.next_back() {\n\n Some(name) => name,\n\n None => {\n\n warn!(\"Got a setting with an empty local name: {:?}\", raw_key);\n\n continue;\n\n }\n\n };\n\n\n\n let value: Value = match raw_value.clone().try_into() {\n\n Ok(value) => value,\n\n Err(e) => {\n\n warn!(\"Could not convert setting {:?} to JSON: {}\", raw_value, e,);\n\n continue;\n", "file_path": "src/settings.rs", "rank": 78, "score": 139088.92856505967 }, { "content": "/// Convert LSP Range to Kakoune's range-spec.\n\npub fn lsp_range_to_kakoune(\n\n range: &Range,\n\n text: &Rope,\n\n offset_encoding: OffsetEncoding,\n\n) -> KakouneRange {\n\n match offset_encoding {\n\n OffsetEncoding::Utf8 => lsp_range_to_kakoune_utf_8_code_units(range),\n\n // Not a proper UTF-16 code units handling, but works within BMP\n\n OffsetEncoding::Utf16 => lsp_range_to_kakoune_utf_8_code_points(range, text),\n\n }\n\n}\n\n\n", "file_path": "src/position.rs", "rank": 79, "score": 139088.92856505967 }, { "content": "pub fn editor_completion(\n\n meta: EditorMeta,\n\n params: TextDocumentCompletionParams,\n\n result: Option<CompletionResponse>,\n\n ctx: &mut Context,\n\n) {\n\n if result.is_none() {\n\n return;\n\n }\n\n\n\n let items = match result.unwrap() {\n\n CompletionResponse::Array(items) => items,\n\n CompletionResponse::List(list) => list.items,\n\n };\n\n\n\n // Length of the longest label in the current completion list\n\n let maxlen = items.iter().map(|x| x.label.len()).max().unwrap_or(0);\n\n let snippet_prefix_re = Regex::new(r\"^[^\\[\\(<\\n\\$]+\").unwrap();\n\n\n\n let mut inferred_offset: Option<u32> = None;\n", "file_path": "src/language_features/completion.rs", "rank": 81, "score": 134053.60403037816 }, { "content": "fn request(config: &Config) {\n\n let mut input = Vec::new();\n\n stdin()\n\n .read_to_end(&mut input)\n\n .expect(\"Failed to read stdin\");\n\n let mut path = util::temp_dir();\n\n path.push(&config.server.session);\n\n if let Ok(mut stream) = UnixStream::connect(&path) {\n\n stream\n\n .write_all(&input)\n\n .expect(\"Failed to send stdin to server\");\n\n } else {\n\n spin_up_server(&input);\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 82, "score": 131519.84562615113 }, { "content": "pub fn editor_code_actions(\n\n meta: EditorMeta,\n\n result: Option<CodeActionResponse>,\n\n ctx: &mut Context,\n\n params: CodeActionsParams,\n\n) {\n\n let result = match result {\n\n Some(result) => result,\n\n None => return,\n\n };\n\n\n\n for cmd in &result {\n\n match cmd {\n\n CodeActionOrCommand::Command(cmd) => info!(\"Command: {:?}\", cmd),\n\n CodeActionOrCommand::CodeAction(action) => info!(\"Action: {:?}\", action),\n\n }\n\n }\n\n\n\n let titles_and_commands = result\n\n .iter()\n", "file_path": "src/language_features/codeaction.rs", "rank": 83, "score": 130786.46582309436 }, { "content": "pub fn editor_document_highlights(\n\n meta: EditorMeta,\n\n result: Option<Vec<DocumentHighlight>>,\n\n ctx: &mut Context,\n\n) {\n\n let document = ctx.documents.get(&meta.buffile);\n\n if document.is_none() {\n\n return;\n\n }\n\n let document = document.unwrap();\n\n let ranges = match result {\n\n Some(highlights) => highlights\n\n .into_iter()\n\n .map(|highlight| {\n\n format!(\n\n \"{}|{}\",\n\n lsp_range_to_kakoune(&highlight.range, &document.text, ctx.offset_encoding),\n\n if highlight.kind == Some(DocumentHighlightKind::WRITE) {\n\n \"ReferenceBind\"\n\n } else {\n", "file_path": "src/language_features/highlights.rs", "rank": 84, "score": 130786.46582309436 }, { "content": "pub fn editor_document_symbol(\n\n meta: EditorMeta,\n\n result: Option<DocumentSymbolResponse>,\n\n ctx: &mut Context,\n\n) {\n\n let content = match result {\n\n Some(DocumentSymbolResponse::Flat(result)) => {\n\n if result.is_empty() {\n\n return;\n\n }\n\n format_symbol_information(result, ctx)\n\n }\n\n Some(DocumentSymbolResponse::Nested(result)) => {\n\n if result.is_empty() {\n\n return;\n\n }\n\n format_document_symbol(result, &meta, ctx)\n\n }\n\n None => {\n\n return;\n\n }\n\n };\n\n let command = format!(\n\n \"lsp-show-document-symbol {} {}\",\n\n editor_quote(&ctx.root_path),\n\n editor_quote(&content),\n\n );\n\n ctx.exec(meta, command);\n\n}\n", "file_path": "src/language_features/document_symbol.rs", "rank": 85, "score": 127767.82695737724 }, { "content": "pub fn editor_signature_help(\n\n meta: EditorMeta,\n\n params: PositionParams,\n\n result: Option<SignatureHelp>,\n\n ctx: &mut Context,\n\n) {\n\n if let Some(result) = result {\n\n let active_signature = result.active_signature.unwrap_or(0);\n\n if let Some(active_signature) = result.signatures.get(active_signature as usize) {\n\n // TODO decide how to use it\n\n // let active_parameter = result.active_parameter.unwrap_or(0);\n\n let contents = &active_signature.label;\n\n let command = format!(\n\n \"lsp-show-signature-help {} {}\",\n\n params.position,\n\n editor_quote(contents)\n\n );\n\n ctx.exec(meta, command);\n\n }\n\n }\n\n}\n", "file_path": "src/language_features/signature_help.rs", "rank": 86, "score": 127767.82695737724 }, { "content": "pub fn organize_imports_response(\n\n meta: EditorMeta,\n\n result: Option<WorkspaceEdit>,\n\n ctx: &mut Context,\n\n) {\n\n let result = match result {\n\n Some(result) => result,\n\n None => return,\n\n };\n\n\n\n // Double JSON serialization is performed to prevent parsing args as a TOML\n\n // structure when they are passed back via lsp-apply-workspace-edit.\n\n let edit = &serde_json::to_string(&result).unwrap();\n\n let edit = editor_quote(&serde_json::to_string(&edit).unwrap());\n\n let select_cmd = format!(\"lsp-apply-workspace-edit {}\", edit);\n\n\n\n ctx.exec(meta, select_cmd);\n\n}\n", "file_path": "src/language_features/eclipse_jdt_ls.rs", "rank": 88, "score": 124970.3747555064 }, { "content": "pub fn roots_by_env(roots: &HashSet<PathBuf>, path: &str) -> Option<String> {\n\n let p = PathBuf::from(path);\n\n let pwd = if p.is_file() {\n\n p.parent().unwrap().to_path_buf()\n\n } else {\n\n p\n\n };\n\n roots\n\n .iter()\n\n .find(|x| pwd.starts_with(&x))\n\n .map(|x| x.to_str().unwrap().to_string())\n\n}\n", "file_path": "src/project_root.rs", "rank": 89, "score": 117714.96718766911 }, { "content": "// TODO handle version, so change is not applied if buffer is modified (and need to show a warning)\n\npub fn apply_edit(\n\n meta: EditorMeta,\n\n edit: WorkspaceEdit,\n\n ctx: &mut Context,\n\n) -> ApplyWorkspaceEditResponse {\n\n if let Some(document_changes) = edit.document_changes {\n\n match document_changes {\n\n DocumentChanges::Edits(edits) => {\n\n for edit in edits {\n\n apply_annotated_text_edits(&meta, &edit.text_document.uri, &edit.edits, ctx);\n\n }\n\n }\n\n DocumentChanges::Operations(ops) => {\n\n for op in ops {\n\n match op {\n\n DocumentChangeOperation::Edit(edit) => {\n\n apply_annotated_text_edits(\n\n &meta,\n\n &edit.text_document.uri,\n\n &edit.edits,\n", "file_path": "src/workspace.rs", "rank": 90, "score": 111510.06243322504 }, { "content": "pub fn apply_edit_from_server(\n\n params: Params,\n\n ctx: &mut Context,\n\n) -> Result<Value, jsonrpc_core::Error> {\n\n let params: ApplyWorkspaceEditParams = params.parse()?;\n\n let meta = ctx.meta_for_session();\n\n let response = apply_edit(meta, params.edit, ctx);\n\n Ok(serde_json::to_value(response).unwrap())\n\n}\n", "file_path": "src/workspace.rs", "rank": 91, "score": 108930.16626370912 }, { "content": "pub fn editor_workspace_symbol(\n\n meta: EditorMeta,\n\n result: Option<Vec<SymbolInformation>>,\n\n ctx: &mut Context,\n\n) {\n\n if result.is_none() {\n\n return;\n\n }\n\n let result = result.unwrap();\n\n let content = format_symbol_information(result, ctx);\n\n let command = format!(\n\n \"lsp-show-workspace-symbol {} {}\",\n\n editor_quote(&ctx.root_path),\n\n editor_quote(&content),\n\n );\n\n ctx.exec(meta, command);\n\n}\n\n\n", "file_path": "src/workspace.rs", "rank": 92, "score": 108930.16626370912 }, { "content": "/// When server is not running it's better to cancel blocking request.\n\n/// Because server can take a long time to initialize or can fail to start.\n\n/// We assume that it's less annoying for user to just repeat command later\n\n/// than to wait, cancel, and repeat.\n\nfn cancel_blocking_request(fifo: String) {\n\n debug!(\"Blocking request but LSP server is not running\");\n\n let command = \"lsp-show-error 'language server is not running, cancelling blocking request'\";\n\n std::fs::write(fifo, command).expect(\"Failed to write command to fifo\");\n\n}\n\n\n", "file_path": "src/session.rs", "rank": 93, "score": 107868.42004973328 }, { "content": "/// Get a line from a Rope\n\n///\n\n/// If the line number is out-of-bounds, this will return the\n\n/// last line. This is useful because the language server might\n\n/// use a large value to convey \"end of file\".\n\npub fn get_line(line_number: usize, text: &Rope) -> RopeSlice {\n\n text.line(min(line_number, text.len_lines() - 1))\n\n}\n\n\n", "file_path": "src/position.rs", "rank": 94, "score": 107408.09306836622 }, { "content": "pub fn apply_document_resource_op(\n\n _meta: &EditorMeta,\n\n op: ResourceOp,\n\n _ctx: &mut Context,\n\n) -> io::Result<()> {\n\n match op {\n\n ResourceOp::Create(op) => {\n\n let path = op.uri.to_file_path().unwrap();\n\n let ignore_if_exists = if let Some(options) = op.options {\n\n !options.overwrite.unwrap_or(false) && options.ignore_if_exists.unwrap_or(false)\n\n } else {\n\n false\n\n };\n\n if ignore_if_exists && path.exists() {\n\n Ok(())\n\n } else {\n\n fs::write(&path, [])\n\n }\n\n }\n\n ResourceOp::Delete(op) => {\n", "file_path": "src/workspace.rs", "rank": 95, "score": 106562.65141171886 }, { "content": "pub fn request_initialization_options_from_kakoune(\n\n meta: &EditorMeta,\n\n ctx: &mut Context,\n\n) -> Option<Value> {\n\n let section = {\n\n let language = ctx.config.language.get(&ctx.language_id).unwrap();\n\n match &language.settings_section {\n\n Some(section) => section.clone(),\n\n None => return None,\n\n }\n\n };\n\n\n\n let settings = request_dynamic_configuration_from_kakoune(meta, ctx)\n\n .and_then(|cfg| cfg.settings)\n\n .and_then(|settings| settings.get(&section).cloned());\n\n if settings.is_some() {\n\n return settings;\n\n }\n\n\n\n let legacy_settings = request_legacy_initialization_options_from_kakoune(meta, ctx);\n", "file_path": "src/settings.rs", "rank": 96, "score": 106562.65141171886 }, { "content": "pub fn request_dynamic_configuration_from_kakoune(\n\n meta: &EditorMeta,\n\n ctx: &mut Context,\n\n) -> Option<DynamicLanguageConfig> {\n\n let fifo = temp_fifo()?;\n\n ctx.exec(\n\n meta.clone(),\n\n format!(\"lsp-get-config {}\", editor_quote(&fifo.path)),\n\n );\n\n let config = std::fs::read_to_string(&fifo.path).unwrap();\n\n parse_dynamic_config(meta, ctx, &config)\n\n}\n\n\n", "file_path": "src/settings.rs", "rank": 97, "score": 106562.65141171886 }, { "content": "pub fn gather_env_roots(language: &str) -> HashSet<PathBuf> {\n\n let prefix = format!(\"KAK_LSP_PROJECT_ROOT_{}\", language.to_uppercase());\n\n debug!(\"Searching for vars starting with {}\", prefix);\n\n env::vars()\n\n .filter(|(k, _v)| k.starts_with(&prefix))\n\n .map(|(_k, v)| PathBuf::from(v))\n\n .collect()\n\n}\n\n\n", "file_path": "src/project_root.rs", "rank": 98, "score": 106076.60601400796 }, { "content": "/// Apply text edits to the file pointed by uri either by asking Kakoune to modify corresponding\n\n/// buffer or by editing file directly when it's not open in editor.\n\npub fn apply_annotated_text_edits(\n\n meta: &EditorMeta,\n\n uri: &Url,\n\n edits: &[OneOf<TextEdit, AnnotatedTextEdit>],\n\n ctx: &Context,\n\n) {\n\n if let Some(document) = uri\n\n .to_file_path()\n\n .ok()\n\n .and_then(|path| path.to_str().and_then(|buffile| ctx.documents.get(buffile)))\n\n {\n\n let meta = meta.clone();\n\n match apply_text_edits_to_buffer(\n\n &meta.client,\n\n Some(uri),\n\n edits,\n\n &document.text,\n\n ctx.offset_encoding,\n\n ) {\n\n Some(cmd) => ctx.exec(meta, cmd),\n\n // Nothing to do, but sending command back to the editor is required to handle case when\n\n // editor is blocked waiting for response via fifo.\n\n None => ctx.exec(meta, \"nop\"),\n\n }\n\n } else if let Err(e) = apply_text_edits_to_file(uri, edits, ctx.offset_encoding) {\n\n error!(\"Failed to apply edits to file {} ({})\", uri, e);\n\n }\n\n}\n\n\n", "file_path": "src/text_edit.rs", "rank": 99, "score": 104385.57026669542 } ]
Rust
crates/storage/src/traits/impls/tuples.rs
tetcoin/ink
8609b374ed19d23a48382393caee8c02bcf5f86a
use crate::traits::{ KeyPtr, PackedLayout, SpreadLayout, }; use pro_primitives::Key; macro_rules! impl_layout_for_tuple { ( $($frag:ident),* $(,)? ) => { impl<$($frag),*> SpreadLayout for ($($frag),* ,) where $( $frag: SpreadLayout, )* { const FOOTPRINT: u64 = 0 $(+ <$frag as SpreadLayout>::FOOTPRINT)*; const REQUIRES_DEEP_CLEAN_UP: bool = false $(|| <$frag as SpreadLayout>::REQUIRES_DEEP_CLEAN_UP)*; fn push_spread(&self, ptr: &mut KeyPtr) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as SpreadLayout>::push_spread($frag, ptr); )* } fn clear_spread(&self, ptr: &mut KeyPtr) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as SpreadLayout>::clear_spread($frag, ptr); )* } fn pull_spread(ptr: &mut KeyPtr) -> Self { ( $( <$frag as SpreadLayout>::pull_spread(ptr), )* ) } } impl<$($frag),*> PackedLayout for ($($frag),* ,) where $( $frag: PackedLayout, )* { #[inline] fn push_packed(&self, at: &Key) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as PackedLayout>::push_packed($frag, at); )* } #[inline] fn clear_packed(&self, at: &Key) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as PackedLayout>::clear_packed($frag, at); )* } #[inline] fn pull_packed(&mut self, at: &Key) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as PackedLayout>::pull_packed($frag, at); )* } } } } impl_layout_for_tuple!(A); impl_layout_for_tuple!(A, B); impl_layout_for_tuple!(A, B, C); impl_layout_for_tuple!(A, B, C, D); impl_layout_for_tuple!(A, B, C, D, E); impl_layout_for_tuple!(A, B, C, D, E, F); impl_layout_for_tuple!(A, B, C, D, E, F, G); impl_layout_for_tuple!(A, B, C, D, E, F, G, H); impl_layout_for_tuple!(A, B, C, D, E, F, G, H, I); impl_layout_for_tuple!(A, B, C, D, E, F, G, H, I, J); #[cfg(test)] mod tests { use crate::push_pull_works_for_primitive; type TupleSix = (i32, u32, String, u8, bool, Box<Option<i32>>); push_pull_works_for_primitive!( TupleSix, [ ( -1, 1, String::from("foobar"), 13, true, Box::new(Some(i32::MIN)) ), ( i32::MIN, u32::MAX, String::from("❤ ♡ ❤ ♡ ❤"), Default::default(), false, Box::new(Some(i32::MAX)) ), ( Default::default(), Default::default(), Default::default(), Default::default(), Default::default(), Default::default() ) ] ); }
use crate::traits::{ KeyPtr, PackedLayout, SpreadLayout, }; use pro_primitives::Key; macro_rules! impl_layout_for_tuple { ( $($frag:ident),* $(,)? ) => { impl<$($frag),*> SpreadLayout for ($($frag),* ,) where $( $frag: SpreadLayout, )* { const FOOTPRINT: u64 = 0 $(+ <$frag as SpreadLayout>::FOOTPRINT)*; const REQUIRES_DEEP_CLEAN_UP: bool = false $(|| <$frag as SpreadLayout>::REQUIRES_DEEP_CLEAN_UP)*; fn push_spread(&self, ptr: &mut KeyPtr) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as SpreadLayout>::push_spread($frag, ptr
Default::default() ) ] ); }
); )* } fn clear_spread(&self, ptr: &mut KeyPtr) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as SpreadLayout>::clear_spread($frag, ptr); )* } fn pull_spread(ptr: &mut KeyPtr) -> Self { ( $( <$frag as SpreadLayout>::pull_spread(ptr), )* ) } } impl<$($frag),*> PackedLayout for ($($frag),* ,) where $( $frag: PackedLayout, )* { #[inline] fn push_packed(&self, at: &Key) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as PackedLayout>::push_packed($frag, at); )* } #[inline] fn clear_packed(&self, at: &Key) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as PackedLayout>::clear_packed($frag, at); )* } #[inline] fn pull_packed(&mut self, at: &Key) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as PackedLayout>::pull_packed($frag, at); )* } } } } impl_layout_for_tuple!(A); impl_layout_for_tuple!(A, B); impl_layout_for_tuple!(A, B, C); impl_layout_for_tuple!(A, B, C, D); impl_layout_for_tuple!(A, B, C, D, E); impl_layout_for_tuple!(A, B, C, D, E, F); impl_layout_for_tuple!(A, B, C, D, E, F, G); impl_layout_for_tuple!(A, B, C, D, E, F, G, H); impl_layout_for_tuple!(A, B, C, D, E, F, G, H, I); impl_layout_for_tuple!(A, B, C, D, E, F, G, H, I, J); #[cfg(test)] mod tests { use crate::push_pull_works_for_primitive; type TupleSix = (i32, u32, String, u8, bool, Box<Option<i32>>); push_pull_works_for_primitive!( TupleSix, [ ( -1, 1, String::from("foobar"), 13, true, Box::new(Some(i32::MIN)) ), ( i32::MIN, u32::MAX, String::from("❤ ♡ ❤ ♡ ❤"), Default::default(), false, Box::new(Some(i32::MAX)) ), ( Default::default(), Default::default(), Default::default(), Default::default(), Default::default(),
random
[ { "content": "/// Asserts that the given `footprint` is below `FOOTPRINT_CLEANUP_THRESHOLD`.\n\nfn assert_footprint_threshold(footprint: u64) {\n\n let footprint_threshold = crate::traits::FOOTPRINT_CLEANUP_THRESHOLD;\n\n assert!(\n\n footprint <= footprint_threshold,\n\n \"cannot clean-up a storage entity with a footprint of {}. maximum threshold for clean-up is {}.\",\n\n footprint,\n\n footprint_threshold,\n\n );\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{\n\n EntryState,\n\n LazyCell,\n\n StorageEntry,\n\n };\n\n use crate::{\n\n traits::{\n\n KeyPtr,\n", "file_path": "crates/storage/src/lazy/lazy_cell.rs", "rank": 0, "score": 237548.83137973223 }, { "content": "#[inline]\n\npub fn forward_pull_packed<T>(ptr: &mut KeyPtr) -> T\n\nwhere\n\n T: PackedLayout,\n\n{\n\n pull_packed_root::<T>(&ptr.next_for::<T>())\n\n}\n\n\n\n/// Pushes an instance of type `T` in packed fashion to the contract storage.\n\n///\n\n/// Stores the instance to the storage location identified by `ptr`.\n\n/// The storage entity is expected to be encodable in its packed form.\n\n///\n\n/// # Note\n\n///\n\n/// Use this utility function to use a packed push operation for the type\n\n/// instead of a spreaded push operation.\n", "file_path": "crates/storage/src/traits/impls/mod.rs", "rank": 1, "score": 226032.70914395544 }, { "content": "#[inline]\n\npub fn forward_push_packed<T>(entity: &T, ptr: &mut KeyPtr)\n\nwhere\n\n T: PackedLayout,\n\n{\n\n push_packed_root::<T>(entity, &ptr.next_for::<T>())\n\n}\n\n\n\n/// Clears an instance of type `T` in packed fashion from the contract storage.\n\n///\n\n/// Clears the instance from the storage location identified by `ptr`.\n\n/// The cleared storage entity is expected to be encoded in its packed form.\n\n///\n\n/// # Note\n\n///\n\n/// Use this utility function to use a packed clear operation for the type\n\n/// instead of a spreaded clear operation.\n", "file_path": "crates/storage/src/traits/impls/mod.rs", "rank": 2, "score": 218134.1068650061 }, { "content": "#[inline]\n\npub fn forward_clear_packed<T>(entity: &T, ptr: &mut KeyPtr)\n\nwhere\n\n T: PackedLayout,\n\n{\n\n clear_packed_root::<T>(entity, &ptr.next_for::<T>())\n\n}\n", "file_path": "crates/storage/src/traits/impls/mod.rs", "rank": 3, "score": 218134.1068650061 }, { "content": "fn clike_enum_layout(key_ptr: &mut KeyPtr) -> Layout {\n\n EnumLayout::new(\n\n key_ptr.advance_by(1),\n\n vec![\n\n (Discriminant(0), StructLayout::new(vec![])),\n\n (Discriminant(1), StructLayout::new(vec![])),\n\n (Discriminant(2), StructLayout::new(vec![])),\n\n ],\n\n )\n\n .into()\n\n}\n\n\n", "file_path": "crates/metadata/src/layout/tests.rs", "rank": 4, "score": 215695.61229645857 }, { "content": "fn unbounded_hashing_layout(key_ptr: &mut KeyPtr) -> Layout {\n\n let root_key = key_ptr.advance_by(1);\n\n HashLayout::new(\n\n root_key,\n\n HashingStrategy::new(\n\n CryptoHasher::Blake2x256,\n\n b\"pro storage hashmap\".to_vec(),\n\n Vec::new(),\n\n ),\n\n CellLayout::new::<(i32, bool)>(LayoutKey::from(root_key)),\n\n )\n\n .into()\n\n}\n\n\n", "file_path": "crates/metadata/src/layout/tests.rs", "rank": 5, "score": 215695.61229645857 }, { "content": "fn tuple_struct_layout(key_ptr: &mut KeyPtr) -> Layout {\n\n StructLayout::new(vec![\n\n FieldLayout::new(\n\n None,\n\n CellLayout::new::<i32>(LayoutKey::from(key_ptr.advance_by(1))),\n\n ),\n\n FieldLayout::new(\n\n None,\n\n CellLayout::new::<i64>(LayoutKey::from(key_ptr.advance_by(1))),\n\n ),\n\n ])\n\n .into()\n\n}\n\n\n", "file_path": "crates/metadata/src/layout/tests.rs", "rank": 6, "score": 215695.61229645857 }, { "content": "fn mixed_enum_layout(key_ptr: &mut KeyPtr) -> Layout {\n\n EnumLayout::new(\n\n *key_ptr.advance_by(1),\n\n vec![\n\n (Discriminant(0), StructLayout::new(vec![])),\n\n {\n\n let mut variant_key_ptr = key_ptr.clone();\n\n (\n\n Discriminant(1),\n\n StructLayout::new(vec![\n\n FieldLayout::new(\n\n None,\n\n CellLayout::new::<i32>(LayoutKey::from(\n\n variant_key_ptr.advance_by(1),\n\n )),\n\n ),\n\n FieldLayout::new(\n\n None,\n\n CellLayout::new::<i64>(LayoutKey::from(\n\n variant_key_ptr.advance_by(1),\n", "file_path": "crates/metadata/src/layout/tests.rs", "rank": 7, "score": 215695.61229645857 }, { "content": "fn named_fields_struct_layout(key_ptr: &mut KeyPtr) -> Layout {\n\n StructLayout::new(vec![\n\n FieldLayout::new(\n\n \"a\",\n\n CellLayout::new::<i32>(LayoutKey::from(key_ptr.advance_by(1))),\n\n ),\n\n FieldLayout::new(\n\n \"b\",\n\n CellLayout::new::<i64>(LayoutKey::from(key_ptr.advance_by(1))),\n\n ),\n\n ])\n\n .into()\n\n}\n\n\n", "file_path": "crates/metadata/src/layout/tests.rs", "rank": 8, "score": 213263.89235621475 }, { "content": "pub fn weight_to_fee(gas: u64, output: &mut &mut [u8]) {\n\n let mut output_len = output.len() as u32;\n\n {\n\n unsafe {\n\n sys::seal_weight_to_fee(\n\n gas,\n\n Ptr32Mut::from_slice(output),\n\n Ptr32Mut::from_ref(&mut output_len),\n\n )\n\n };\n\n }\n\n extract_from_slice(output, output_len as usize);\n\n}\n\n\n", "file_path": "crates/env/src/engine/on_chain/ext.rs", "rank": 9, "score": 209967.37719532923 }, { "content": "fn bench_key_ptr_advance_by(c: &mut Criterion) {\n\n let key = Key::from([0x00; 32]);\n\n c.bench_function(\"KeyPtr2::advance_by copy\", |b| {\n\n b.iter(|| {\n\n let mut key_ptr = KeyPtr::from(key.clone());\n\n let _ = black_box(key_ptr.advance_by(1));\n\n })\n\n });\n\n}\n\n\n", "file_path": "crates/primitives/benches/bench.rs", "rank": 10, "score": 188930.5443942713 }, { "content": "fn bench_key_add_assign_u64(c: &mut Criterion) {\n\n let key = Key::from([0x00; 32]);\n\n c.bench_function(\"Key2::add_assign(u64)\", |b| {\n\n b.iter(|| {\n\n let mut copy = black_box(key);\n\n let _ = black_box(copy += 1u64);\n\n })\n\n });\n\n}\n\n\n", "file_path": "crates/primitives/benches/bench.rs", "rank": 11, "score": 185926.4136617674 }, { "content": "fn bench_key_ptr_advance_by_repeat(c: &mut Criterion) {\n\n let key = Key::from([0x00; 32]);\n\n let mut key_ptr = KeyPtr::from(key.clone());\n\n c.bench_function(\"KeyPtr2::advance_by reuse\", |b| {\n\n b.iter(|| {\n\n let _ = black_box(key_ptr.advance_by(1));\n\n })\n\n });\n\n}\n", "file_path": "crates/primitives/benches/bench.rs", "rank": 12, "score": 185915.74383540443 }, { "content": "fn bench_key_add_assign_u64_wrap(c: &mut Criterion) {\n\n let key = Key::from([0xFF; 32]);\n\n c.bench_function(\"Key2::add_assign(u64) - wrap\", |b| {\n\n b.iter(|| {\n\n let mut copy = black_box(key);\n\n let _ = black_box(copy += 1u64);\n\n })\n\n });\n\n}\n\n\n", "file_path": "crates/primitives/benches/bench.rs", "rank": 13, "score": 183045.56275015778 }, { "content": "fn bench_key_add_assign_u64_one_ofvl(c: &mut Criterion) {\n\n let key = Key::from([\n\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00,\n\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\n ]);\n\n c.bench_function(\"Key2::add_assign(u64) - 1 ofvl\", |b| {\n\n b.iter(|| {\n\n let mut copy = black_box(key);\n\n let _ = black_box(copy += 1u64);\n\n })\n\n });\n\n}\n\n\n", "file_path": "crates/primitives/benches/bench.rs", "rank": 14, "score": 180290.1454255978 }, { "content": "fn bench_key_add_assign_u64_two_ofvls(c: &mut Criterion) {\n\n let key = Key::from([\n\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n\n 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\n ]);\n\n c.bench_function(\"Key2::add_assign(u64) - 2 ofvls\", |b| {\n\n b.iter(|| {\n\n let mut copy = black_box(key);\n\n let _ = black_box(copy += 1u64);\n\n })\n\n });\n\n}\n\n\n", "file_path": "crates/primitives/benches/bench.rs", "rank": 15, "score": 180290.1454255978 }, { "content": "fn bench_key_add_assign_u64_three_ofvls(c: &mut Criterion) {\n\n let key = Key::from([\n\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,\n\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\n ]);\n\n c.bench_function(\"Key2::add_assign(u64) - 3 ofvls\", |b| {\n\n b.iter(|| {\n\n let mut copy = black_box(key);\n\n let _ = black_box(copy += 1u64);\n\n })\n\n });\n\n}\n\n\n", "file_path": "crates/primitives/benches/bench.rs", "rank": 16, "score": 180290.1454255978 }, { "content": "/// Returns always the same `KeyPtr`.\n\nfn key_ptr() -> KeyPtr {\n\n let root_key = Key::from([0x42; 32]);\n\n KeyPtr::from(root_key)\n\n}\n\n\n", "file_path": "crates/storage/src/collections/hashmap/tests.rs", "rank": 17, "score": 167821.4685775745 }, { "content": "fn main() {}\n", "file_path": "crates/lang/macro/tests/ui/fail/C-01-constructor-self-mut.rs", "rank": 18, "score": 162922.05204796186 }, { "content": "pub fn input(output: &mut &mut [u8]) {\n\n let mut output_len = output.len() as u32;\n\n {\n\n unsafe {\n\n sys::seal_input(\n\n Ptr32Mut::from_slice(output),\n\n Ptr32Mut::from_ref(&mut output_len),\n\n )\n\n };\n\n }\n\n extract_from_slice(output, output_len as usize);\n\n}\n\n\n", "file_path": "crates/env/src/engine/on_chain/ext.rs", "rank": 19, "score": 157175.49955168588 }, { "content": "fn extract_from_slice(output: &mut &mut [u8], new_len: usize) {\n\n debug_assert!(new_len <= output.len());\n\n let tmp = core::mem::take(output);\n\n *output = &mut tmp[..new_len];\n\n}\n\n\n", "file_path": "crates/env/src/engine/on_chain/ext.rs", "rank": 20, "score": 149166.96461842785 }, { "content": "pub fn random(subject: &[u8], output: &mut &mut [u8]) {\n\n let mut output_len = output.len() as u32;\n\n {\n\n unsafe {\n\n sys::seal_random(\n\n Ptr32::from_slice(subject),\n\n subject.len() as u32,\n\n Ptr32Mut::from_slice(output),\n\n Ptr32Mut::from_ref(&mut output_len),\n\n )\n\n };\n\n }\n\n extract_from_slice(output, output_len as usize);\n\n}\n\n\n", "file_path": "crates/env/src/engine/on_chain/ext.rs", "rank": 21, "score": 147976.0703552091 }, { "content": "fn bench_populated_cache(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"Bench: populated cache\");\n\n group.bench_function(\"fill_bitstash\", |b| {\n\n b.iter(|| populated_cache::fill_bitstash())\n\n });\n\n group.bench_function(\"one_put\", |b| {\n\n b.iter_batched_ref(\n\n || create_large_stash(),\n\n |stash| one_put(stash),\n\n BatchSize::SmallInput,\n\n )\n\n });\n\n group.finish();\n\n}\n\n\n\nmod empty_cache {\n\n use super::*;\n\n\n\n /// Executes `put` operations on a new `BitStash` exactly `BENCH_ALLOCATIONS` times.\n\n pub fn fill_bitstash() {\n\n push_stash();\n\n let mut stash = pull_stash();\n\n for _ in 0..BENCH_ALLOCATIONS {\n\n black_box(stash.put());\n\n }\n\n }\n\n}\n\n\n", "file_path": "crates/storage/benches/bench_bitstash.rs", "rank": 22, "score": 144459.4843227046 }, { "content": "/// In this case we lazily instantiate a `BitStash` by first creating and storing\n\n/// into the contract storage. We then load the stash from storage lazily in each\n\n/// benchmark iteration.\n\nfn bench_empty_cache(c: &mut Criterion) {\n\n let _ = pro_env::test::run_test::<pro_env::DefaultEnvironment, _>(|_| {\n\n let mut group = c.benchmark_group(\"Bench: empty cache\");\n\n group\n\n .bench_function(\"fill_bitstash\", |b| b.iter(|| empty_cache::fill_bitstash()));\n\n group.bench_function(\"one_put\", |b| {\n\n b.iter_batched_ref(\n\n || {\n\n let stash = create_large_stash();\n\n push_stash_by_ref(&stash);\n\n pull_stash()\n\n },\n\n |stash| one_put(stash),\n\n BatchSize::SmallInput,\n\n )\n\n });\n\n group.finish();\n\n Ok(())\n\n })\n\n .unwrap();\n\n}\n", "file_path": "crates/storage/benches/bench_bitstash.rs", "rank": 23, "score": 144459.4843227046 }, { "content": "/// In this case we lazily instantiate a `StorageVec` by first `create_and_store`-ing\n\n/// into the contract storage. We then load the vec from storage lazily in each\n\n/// benchmark iteration.\n\nfn bench_clear_empty_cache(c: &mut Criterion) {\n\n let _ = pro_env::test::run_test::<pro_env::DefaultEnvironment, _>(|_| {\n\n let mut group = c.benchmark_group(\"Compare: `clear` and `pop_all` (empty cache)\");\n\n group.bench_function(\"clear\", |b| b.iter(|| empty_cache::clear()));\n\n group.bench_function(\"pop_all\", |b| b.iter(|| empty_cache::pop_all()));\n\n group.finish();\n\n Ok(())\n\n })\n\n .unwrap();\n\n}\n\n\n", "file_path": "crates/storage/benches/bench_vec.rs", "rank": 24, "score": 142456.90150213754 }, { "content": "fn bench_set_empty_cache(c: &mut Criterion) {\n\n let _ = pro_env::test::run_test::<pro_env::DefaultEnvironment, _>(|_| {\n\n let mut group = c.benchmark_group(\"Compare: `set` and `deref_mut` (empty cache)\");\n\n group.bench_function(BenchmarkId::new(\"set\", 0), |b| {\n\n b.iter(|| empty_cache::set())\n\n });\n\n group.bench_function(BenchmarkId::new(\"deref_mut\", 0), |b| {\n\n b.iter(|| empty_cache::deref_mut())\n\n });\n\n group.finish();\n\n Ok(())\n\n })\n\n .unwrap();\n\n}\n", "file_path": "crates/storage/benches/bench_lazy.rs", "rank": 25, "score": 142456.90150213754 }, { "content": "/// In this case we lazily instantiate a `StorageVec` by first `create_and_store`-ing\n\n/// into the contract storage. We then load the vec from storage lazily in each\n\n/// benchmark iteration.\n\nfn bench_put_empty_cache(c: &mut Criterion) {\n\n let _ = pro_env::test::run_test::<pro_env::DefaultEnvironment, _>(|_| {\n\n let mut group = c.benchmark_group(\"Compare: `set` and `get_mut` (empty cache)\");\n\n group.bench_function(\"set\", |b| b.iter(|| empty_cache::set()));\n\n group.bench_function(\"get_mut\", |b| b.iter(|| empty_cache::get_mut()));\n\n group.finish();\n\n Ok(())\n\n })\n\n .unwrap();\n\n}\n", "file_path": "crates/storage/benches/bench_vec.rs", "rank": 26, "score": 142456.90150213754 }, { "content": "fn bench_put_populated_cache(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"Compare: `set` and `get_mut` (populated cache)\");\n\n group.bench_with_input(BenchmarkId::new(\"set\", 0), test_values(), |b, i| {\n\n b.iter(|| populated_cache::set(i))\n\n });\n\n group.bench_with_input(BenchmarkId::new(\"get_mut\", 0), test_values(), |b, i| {\n\n b.iter(|| populated_cache::get_mut(i))\n\n });\n\n group.finish();\n\n}\n\n\n", "file_path": "crates/storage/benches/bench_vec.rs", "rank": 27, "score": 142456.90150213754 }, { "content": "fn bench_set_populated_cache(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"Compare: `set` and `deref_mut` (populated cache)\");\n\n group.bench_function(BenchmarkId::new(\"set\", 0), |b| {\n\n b.iter(|| populated_cache::set())\n\n });\n\n group.bench_function(BenchmarkId::new(\"deref_mut\", 0), |b| {\n\n b.iter(|| populated_cache::deref_mut())\n\n });\n\n group.finish();\n\n}\n\n\n", "file_path": "crates/storage/benches/bench_lazy.rs", "rank": 28, "score": 142456.90150213754 }, { "content": "fn bench_clear_populated_cache(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"Compare: `clear` and `pop_all` (populated cache)\");\n\n let test_values = [b'A', b'B', b'C', b'D', b'E', b'F'];\n\n group.bench_with_input(\"clear\", &test_values, |b, i| {\n\n b.iter(|| populated_cache::clear(i))\n\n });\n\n group.bench_with_input(\"pop_all\", &test_values, |b, i| {\n\n b.iter(|| populated_cache::pop_all(i))\n\n });\n\n group.finish();\n\n}\n\n\n\nmod empty_cache {\n\n use super::*;\n\n\n\n /// In this case we lazily load the vec from storage using `pull_spread`.\n\n /// This will just load lazily and won't pull anything from the storage.\n\n pub fn clear() {\n\n push_storage_vec();\n\n let mut vec = pull_storage_vec();\n", "file_path": "crates/storage/benches/bench_vec.rs", "rank": 29, "score": 142456.90150213754 }, { "content": "pub fn get_storage(key: &[u8], output: &mut &mut [u8]) -> Result {\n\n let mut output_len = output.len() as u32;\n\n let ret_code = {\n\n unsafe {\n\n sys::seal_get_storage(\n\n Ptr32::from_slice(key),\n\n Ptr32Mut::from_slice(output),\n\n Ptr32Mut::from_ref(&mut output_len),\n\n )\n\n }\n\n };\n\n extract_from_slice(output, output_len as usize);\n\n ret_code.into()\n\n}\n\n\n", "file_path": "crates/env/src/engine/on_chain/ext.rs", "rank": 30, "score": 142353.3604711018 }, { "content": "fn bench_push_empty_cache(c: &mut Criterion) {\n\n bench_heap_sizes::<_, _, Push>(\n\n c,\n\n \"BinaryHeap::push (empty cache)\",\n\n binary_heap::init_storage,\n\n NewHeap::lazy,\n\n );\n\n}\n\n\n", "file_path": "crates/storage/benches/bench_binary_heap.rs", "rank": 31, "score": 140543.45253255928 }, { "content": "fn bench_pop_populated_cache(c: &mut Criterion) {\n\n bench_heap_sizes::<_, _, Pop>(\n\n c,\n\n \"BinaryHeap::pop (populated cache)\",\n\n |_: Key, _: &[u32]| {},\n\n NewHeap::populated,\n\n );\n\n}\n\n\n", "file_path": "crates/storage/benches/bench_binary_heap.rs", "rank": 32, "score": 140543.45253255928 }, { "content": "/// In this case we lazily instantiate a `StorageStash` by first `create_and_store`-ing\n\n/// into the contract storage. We then load the stash from storage lazily in each\n\n/// benchmark iteration.\n\nfn bench_remove_occupied_empty_cache(c: &mut Criterion) {\n\n let _ = pro_env::test::run_test::<pro_env::DefaultEnvironment, _>(|_| {\n\n let mut group = c.benchmark_group(\n\n \"Compare: `remove_occupied_all` and `take_all` (empty cache)\",\n\n );\n\n group.bench_function(\"remove_occupied_all\", |b| {\n\n b.iter(|| empty_cache::remove_occupied_all())\n\n });\n\n group.bench_function(\"take_all\", |b| b.iter(|| empty_cache::take_all()));\n\n group.finish();\n\n Ok(())\n\n })\n\n .unwrap();\n\n}\n", "file_path": "crates/storage/benches/bench_stash.rs", "rank": 33, "score": 140543.45253255928 }, { "content": "fn bench_remove_occupied_populated_cache(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\n\n \"Compare: `remove_occupied_all` and `take_all` (populated cache)\",\n\n );\n\n let test_values = [b'A', b'B', b'C', b'D', b'E', b'F'];\n\n group.bench_with_input(\"remove_occupied_all\", &test_values, |b, i| {\n\n b.iter(|| populated_cache::remove_occupied_all(i))\n\n });\n\n group.bench_with_input(\"take_all\", &test_values, |b, i| {\n\n b.iter(|| populated_cache::take_all(i))\n\n });\n\n group.finish();\n\n}\n\n\n\nmod empty_cache {\n\n use super::*;\n\n\n\n /// In this case we lazily load the stash from storage using `pull_spread`.\n\n /// This will just load lazily and won't pull anything from the storage.\n\n pub fn remove_occupied_all() {\n", "file_path": "crates/storage/benches/bench_stash.rs", "rank": 34, "score": 140543.45253255928 }, { "content": "fn bench_push_populated_cache(c: &mut Criterion) {\n\n bench_heap_sizes::<_, _, Push>(\n\n c,\n\n \"BinaryHeap::push (populated cache)\",\n\n |_: Key, _: &[u32]| {},\n\n NewHeap::populated,\n\n );\n\n}\n\n\n", "file_path": "crates/storage/benches/bench_binary_heap.rs", "rank": 35, "score": 140543.45253255928 }, { "content": "fn bench_pop_empty_cache(c: &mut Criterion) {\n\n bench_heap_sizes::<_, _, Pop>(\n\n c,\n\n \"BinaryHeap::pop (empty cache)\",\n\n binary_heap::init_storage,\n\n NewHeap::lazy,\n\n );\n\n}\n\n\n", "file_path": "crates/storage/benches/bench_binary_heap.rs", "rank": 36, "score": 140543.45253255928 }, { "content": "/// Generates the tokens for the `SpreadLayout` footprint of some type.\n\nfn footprint(s: &synstructure::Structure) -> TokenStream2 {\n\n let variant_footprints = s\n\n .variants()\n\n .iter()\n\n .map(|variant| {\n\n variant\n\n .ast()\n\n .fields\n\n .iter()\n\n .map(|field| &field.ty)\n\n .map(|ty| quote! { <#ty as ::pro_storage::traits::SpreadLayout>::FOOTPRINT })\n\n .fold(quote! { 0u64 }, |lhs, rhs| {\n\n quote! { (#lhs + #rhs) }\n\n })\n\n })\n\n .collect::<Vec<_>>();\n\n max_n(&variant_footprints[..])\n\n}\n\n\n", "file_path": "crates/storage/derive/src/spread_layout.rs", "rank": 37, "score": 138855.5982045765 }, { "content": "/// Set to true to disable clearing storage\n\n///\n\n/// # Note\n\n///\n\n/// Useful for benchmarking because it ensures the initialized storage is maintained across runs,\n\n/// because lazy storage structures automatically clear their associated cells when they are dropped.\n\npub fn set_clear_storage_disabled(disable: bool) {\n\n <EnvInstance as OnInstance>::on_instance(|instance| {\n\n instance.clear_storage_disabled = disable\n\n })\n\n}\n\n\n\n/// The default accounts.\n\npub struct DefaultAccounts<T>\n\nwhere\n\n T: Environment,\n\n{\n\n /// The predefined `ALICE` account holding substantial amounts of value.\n\n pub alice: T::AccountId,\n\n /// The predefined `BOB` account holding some amounts of value.\n\n pub bob: T::AccountId,\n\n /// The predefined `CHARLIE` account holding some amounts of value.\n\n pub charlie: T::AccountId,\n\n /// The predefined `DJANGO` account holding no value.\n\n pub django: T::AccountId,\n\n /// The predefined `EVE` account holding no value.\n\n pub eve: T::AccountId,\n\n /// The predefined `FRANK` account holding no value.\n\n pub frank: T::AccountId,\n\n}\n\n\n", "file_path": "crates/env/src/engine/off_chain/test_api.rs", "rank": 38, "score": 137385.25944264213 }, { "content": "/// Executes only a single `put` operation on the stash.\n\npub fn one_put(stash: &mut BitStash) {\n\n black_box(stash.put());\n\n}\n\n\n", "file_path": "crates/storage/benches/bench_bitstash.rs", "rank": 39, "score": 136531.91069084243 }, { "content": "pub fn call_chain_extension(func_id: u32, input: &[u8], output: &mut &mut [u8]) -> u32 {\n\n let mut output_len = output.len() as u32;\n\n let ret_code = {\n\n unsafe {\n\n sys::seal_call_chain_extension(\n\n func_id,\n\n Ptr32::from_slice(input),\n\n input.len() as u32,\n\n Ptr32Mut::from_slice(output),\n\n Ptr32Mut::from_ref(&mut output_len),\n\n )\n\n }\n\n };\n\n extract_from_slice(output, output_len as usize);\n\n ret_code.into_u32()\n\n}\n\n\n", "file_path": "crates/env/src/engine/on_chain/ext.rs", "rank": 40, "score": 132359.34541802565 }, { "content": "/// Returns `true` if the given iterator yields at least one attribute of the form\n\n/// `#[pro(..)]` or `#[pro]`.\n\n///\n\n/// # Note\n\n///\n\n/// This does not check at this point whether the pro! attribute is valid since\n\n/// this check is optimized for efficiency.\n\npub fn contains_pro_attributes<'a, I>(attrs: I) -> bool\n\nwhere\n\n I: IntoIterator<Item = &'a syn::Attribute>,\n\n{\n\n attrs.into_iter().any(|attr| attr.path.is_ident(\"pro\"))\n\n}\n\n\n", "file_path": "crates/lang/ir/src/ir/attrs.rs", "rank": 41, "score": 130368.56453654508 }, { "content": "/// Returns the price for the specified amount of gas.\n\n///\n\n/// # Errors\n\n///\n\n/// If the returned value cannot be properly decoded.\n\npub fn weight_to_fee<T>(gas: u64) -> Result<T::Balance>\n\nwhere\n\n T: Environment,\n\n{\n\n <EnvInstance as OnInstance>::on_instance(|instance| {\n\n TypedEnvBackend::weight_to_fee::<T>(instance, gas)\n\n })\n\n}\n\n\n", "file_path": "crates/env/src/api.rs", "rank": 42, "score": 125809.44347482754 }, { "content": "/// Conduct the BLAKE2 128-bit hash and place the result into `output`.\n\npub fn blake2b_128(input: &[u8], output: &mut [u8; 16]) {\n\n blake2b_var(16, input, output)\n\n}\n\n\n", "file_path": "crates/env/src/engine/off_chain/hashing.rs", "rank": 43, "score": 125485.77045301895 }, { "content": "/// Conduct the BLAKE2 256-bit hash and place the result into `output`.\n\npub fn blake2b_256(input: &[u8], output: &mut [u8; 32]) {\n\n blake2b_var(32, input, output)\n\n}\n\n\n", "file_path": "crates/env/src/engine/off_chain/hashing.rs", "rank": 44, "score": 125485.77045301895 }, { "content": "/// Conduct the KECCAK 256-bit hash and place the result into `output`.\n\npub fn keccak_256(input: &[u8], output: &mut [u8; 32]) {\n\n use ::sha3::{\n\n digest::{\n\n generic_array::GenericArray,\n\n FixedOutput as _,\n\n },\n\n Digest as _,\n\n };\n\n let mut hasher = ::sha3::Keccak256::new();\n\n hasher.update(input);\n\n hasher.finalize_into(<&mut GenericArray<u8, _>>::from(&mut output[..]));\n\n}\n\n\n", "file_path": "crates/env/src/engine/off_chain/hashing.rs", "rank": 45, "score": 125485.77045301895 }, { "content": "/// Conduct the SHA2 256-bit hash and place the result into `output`.\n\npub fn sha2_256(input: &[u8], output: &mut [u8; 32]) {\n\n use ::sha2::{\n\n digest::{\n\n generic_array::GenericArray,\n\n FixedOutput as _,\n\n },\n\n Digest as _,\n\n };\n\n let mut hasher = ::sha2::Sha256::new();\n\n hasher.update(input);\n\n hasher.finalize_into(<&mut GenericArray<u8, _>>::from(&mut output[..]));\n\n}\n", "file_path": "crates/env/src/engine/off_chain/hashing.rs", "rank": 46, "score": 125485.77045301895 }, { "content": "pub fn storage_layout_derive(mut s: synstructure::Structure) -> TokenStream2 {\n\n s.bind_with(|_| synstructure::BindStyle::Move)\n\n .add_bounds(synstructure::AddBounds::Generics)\n\n .underscore_const(true);\n\n match s.ast().data {\n\n syn::Data::Struct(_) => storage_layout_struct(&s),\n\n syn::Data::Enum(_) => storage_layout_enum(&s),\n\n _ => panic!(\"cannot derive `StorageLayout` for Rust `union` items\"),\n\n }\n\n}\n", "file_path": "crates/storage/derive/src/storage_layout.rs", "rank": 47, "score": 124744.45966549311 }, { "content": "/// Derives `pro_storage`'s `PackedLayout` trait for the given `struct` or `enum`.\n\npub fn packed_layout_derive(mut s: synstructure::Structure) -> TokenStream2 {\n\n s.bind_with(|_| synstructure::BindStyle::Move)\n\n .add_bounds(synstructure::AddBounds::Generics)\n\n .underscore_const(true);\n\n let pull_body = s.each(|binding| {\n\n quote! { ::pro_storage::traits::PackedLayout::pull_packed(#binding, __key); }\n\n });\n\n let push_body = s.each(|binding| {\n\n quote! { ::pro_storage::traits::PackedLayout::push_packed(#binding, __key); }\n\n });\n\n let clear_body = s.each(|binding| {\n\n quote! { ::pro_storage::traits::PackedLayout::clear_packed(#binding, __key); }\n\n });\n\n s.gen_impl(quote! {\n\n gen impl ::pro_storage::traits::PackedLayout for @Self {\n\n fn pull_packed(&mut self, __key: &::pro_primitives::Key) {\n\n match self { #pull_body }\n\n }\n\n fn push_packed(&self, __key: &::pro_primitives::Key) {\n\n match self { #push_body }\n\n }\n\n fn clear_packed(&self, __key: &::pro_primitives::Key) {\n\n match self { #clear_body }\n\n }\n\n }\n\n })\n\n}\n", "file_path": "crates/storage/derive/src/packed_layout.rs", "rank": 48, "score": 124744.45966549311 }, { "content": "/// Derives `pro_storage`'s `SpreadLayout` trait for the given `struct` or `enum`.\n\npub fn spread_layout_derive(mut s: synstructure::Structure) -> TokenStream2 {\n\n s.bind_with(|_| synstructure::BindStyle::Move)\n\n .add_bounds(synstructure::AddBounds::Generics)\n\n .underscore_const(true);\n\n match s.ast().data {\n\n syn::Data::Struct(_) => spread_layout_struct_derive(&s),\n\n syn::Data::Enum(_) => spread_layout_enum_derive(&s),\n\n _ => {\n\n panic!(\n\n \"cannot derive `SpreadLayout` or `PackedLayout` for Rust `union` items\"\n\n )\n\n }\n\n }\n\n}\n", "file_path": "crates/storage/derive/src/spread_layout.rs", "rank": 49, "score": 124744.45966549311 }, { "content": "/// Helper routine implementing variable size BLAKE2b hash computation.\n\nfn blake2b_var(size: usize, input: &[u8], output: &mut [u8]) {\n\n use ::blake2::digest::{\n\n Update as _,\n\n VariableOutput as _,\n\n };\n\n let mut blake2 = blake2::VarBlake2b::new_keyed(&[], size);\n\n blake2.update(input);\n\n blake2.finalize_variable(|result| output.copy_from_slice(result));\n\n}\n\n\n", "file_path": "crates/env/src/engine/off_chain/hashing.rs", "rank": 50, "score": 122054.57812976392 }, { "content": "fn main() {}\n", "file_path": "crates/lang/macro/tests/ui/fail/C-12-const-constructor.rs", "rank": 51, "score": 121563.03450715562 }, { "content": "#[cfg(debug_assertions)]\n\n#[test]\n\n#[should_panic(expected = \"index out of bounds: the len is 3 but the index is 3\")]\n\nfn index_mut_out_of_bounds_works() {\n\n let test_values = [b'a', b'b', b'c'];\n\n let mut stash = test_values.iter().copied().collect::<StorageStash<_>>();\n\n let _ = &mut stash[test_values.len() as u32];\n\n}\n\n\n", "file_path": "crates/storage/src/collections/stash/tests.rs", "rank": 52, "score": 121458.68116772923 }, { "content": "#[test]\n\n#[should_panic(expected = \"index out of bounds: the len is 3 but the index is 3\")]\n\nfn index_mut_out_of_bounds_works() {\n\n let test_values = [b'a', b'b', b'c'];\n\n let mut vec = vec_from_slice(&test_values);\n\n let _ = &mut vec[test_values.len() as u32];\n\n}\n\n\n", "file_path": "crates/storage/src/collections/smallvec/tests.rs", "rank": 53, "score": 121458.68116772923 }, { "content": "#[test]\n\n#[should_panic(expected = \"indexed vacant entry: at index 1\")]\n\nfn index_mut_vacant_works() {\n\n let test_values = [b'a', b'b', b'c'];\n\n let mut stash = test_values.iter().copied().collect::<StorageStash<_>>();\n\n assert_eq!(stash.take(1), Some(b'b'));\n\n let _ = &mut stash[1];\n\n}\n\n\n", "file_path": "crates/storage/src/collections/stash/tests.rs", "rank": 54, "score": 121458.68116772923 }, { "content": "#[test]\n\nfn peek_mut_works() {\n\n let data = vec![2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1];\n\n let mut heap = heap_from_slice(&data);\n\n assert_eq!(heap.peek(), Some(&10));\n\n {\n\n let mut top = heap.peek_mut().unwrap();\n\n *top -= 2;\n\n }\n\n assert_eq!(heap.peek(), Some(&9));\n\n}\n\n\n", "file_path": "crates/storage/src/collections/binary_heap/tests.rs", "rank": 55, "score": 121458.68116772923 }, { "content": "#[test]\n\n#[should_panic(expected = \"index out of bounds: the len is 3 but the index is 3\")]\n\nfn index_mut_out_of_bounds_works() {\n\n let test_values = [b'a', b'b', b'c'];\n\n let mut vec = vec_from_slice(&test_values);\n\n let _ = &mut vec[test_values.len() as u32];\n\n}\n\n\n", "file_path": "crates/storage/src/collections/vec/tests.rs", "rank": 56, "score": 121458.68116772923 }, { "content": "fn main() {}\n", "file_path": "crates/lang/macro/tests/ui/fail/H-03-use-forbidden-idents.rs", "rank": 57, "score": 119552.58174196807 }, { "content": "fn main() {}\n", "file_path": "crates/lang/macro/tests/ui/fail/M-03-message-returns-self.rs", "rank": 58, "score": 119541.87805881332 }, { "content": "fn main() {}\n", "file_path": "crates/lang/macro/tests/ui/fail/C-00-constructor-self-ref.rs", "rank": 59, "score": 119541.87805881332 }, { "content": "fn main() {}\n", "file_path": "crates/lang/macro/tests/ui/fail/C-02-constructor-self-val.rs", "rank": 60, "score": 119541.87805881332 }, { "content": "#[test]\n\nfn empty_peek_mut_works() {\n\n let mut empty = BinaryHeap::<i32>::new();\n\n assert!(empty.peek_mut().is_none());\n\n}\n\n\n", "file_path": "crates/storage/src/collections/binary_heap/tests.rs", "rank": 61, "score": 119456.09834716219 }, { "content": "#[test]\n\nfn peek_mut_pop_works() {\n\n let data = vec![2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1];\n\n let mut heap = heap_from_slice(&data);\n\n assert_eq!(heap.peek(), Some(&10));\n\n {\n\n let mut top = heap.peek_mut().unwrap();\n\n *top -= 2;\n\n assert_eq!(PeekMut::pop(top), 8);\n\n }\n\n assert_eq!(heap.peek(), Some(&9));\n\n}\n\n\n", "file_path": "crates/storage/src/collections/binary_heap/tests.rs", "rank": 62, "score": 119456.09834716219 }, { "content": "fn main() {}\n", "file_path": "crates/lang/macro/tests/ui/fail/M-02-message-missing-self-arg.rs", "rank": 63, "score": 117626.520085533 }, { "content": "/// Conducts the crypto hash of the given input and stores the result in `output`.\n\npub fn hash_bytes<H>(input: &[u8], output: &mut <H as HashOutput>::Type)\n\nwhere\n\n H: CryptoHash,\n\n{\n\n <EnvInstance as OnInstance>::on_instance(|instance| {\n\n instance.hash_bytes::<H>(input, output)\n\n })\n\n}\n\n\n", "file_path": "crates/env/src/api.rs", "rank": 64, "score": 113982.11491551358 }, { "content": "/// Conducts the crypto hash of the given encoded input and stores the result in `output`.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// # use pro_env::hash::{Sha2x256, HashOutput};\n\n/// const EXPECTED: [u8; 32] = [\n\n/// 243, 242, 58, 110, 205, 68, 100, 244, 187, 55, 188, 248, 29, 136, 145, 115,\n\n/// 186, 134, 14, 175, 178, 99, 183, 21, 4, 94, 92, 69, 199, 207, 241, 179,\n\n/// ];\n\n/// let encodable = (42, \"foo\", true); // Implements `scale::Encode`\n\n/// let mut output = <Sha2x256 as HashOutput>::Type::default(); // 256-bit buffer\n\n/// pro_env::hash_encoded::<Sha2x256, _>(&encodable, &mut output);\n\n/// assert_eq!(output, EXPECTED);\n\n/// ```\n\npub fn hash_encoded<H, T>(input: &T, output: &mut <H as HashOutput>::Type)\n\nwhere\n\n H: CryptoHash,\n\n T: scale::Encode,\n\n{\n\n <EnvInstance as OnInstance>::on_instance(|instance| {\n\n instance.hash_encoded::<H, T>(input, output)\n\n })\n\n}\n", "file_path": "crates/env/src/api.rs", "rank": 65, "score": 110709.13905450783 }, { "content": "#[inline]\n\n#[doc(hidden)]\n\npub fn execute_message_mut<E, M, F>(\n\n accepts_payments: AcceptsPayments,\n\n enables_dynamic_storage_allocator: EnablesDynamicStorageAllocator,\n\n f: F,\n\n) -> Result<()>\n\nwhere\n\n E: Environment,\n\n M: MessageMut,\n\n F: FnOnce(&mut <M as FnState>::State) -> <M as FnOutput>::Output,\n\n{\n\n let accepts_payments: bool = accepts_payments.into();\n\n let enables_dynamic_storage_allocator: bool =\n\n enables_dynamic_storage_allocator.into();\n\n if !accepts_payments {\n\n deny_payment::<E>()?;\n\n }\n\n if enables_dynamic_storage_allocator {\n\n alloc::initialize(ContractPhase::Call);\n\n }\n\n let root_key = Key::from([0x00; 32]);\n", "file_path": "crates/lang/src/dispatcher.rs", "rank": 66, "score": 109944.8359741075 }, { "content": "fn bench_heap_sizes<I, H, B>(c: &mut Criterion, name: &str, init: I, new_test_heap: H)\n\nwhere\n\n I: Fn(Key, &[u32]),\n\n H: Fn(Key, Vec<u32>) -> NewHeap,\n\n B: Benchmark,\n\n{\n\n let _ = pro_env::test::run_test::<pro_env::DefaultEnvironment, _>(|_| {\n\n let mut group = c.benchmark_group(name);\n\n group.warm_up_time(Duration::from_secs(6));\n\n group.measurement_time(Duration::from_secs(10));\n\n\n\n for (key, size) in [(0u8, 8u32), (1, 16), (2, 32), (3, 64)].iter() {\n\n let root_key = Key::from([*key; 32]);\n\n let test_values = test_values(*size);\n\n\n\n // perform one time initialization for this heap size\n\n init(root_key, &test_values);\n\n\n\n let test_heap = new_test_heap(root_key, test_values);\n\n <B as Benchmark>::bench(&mut group, *size, test_heap)\n\n }\n\n\n\n group.finish();\n\n Ok(())\n\n })\n\n .unwrap();\n\n}\n\n\n", "file_path": "crates/storage/benches/bench_binary_heap.rs", "rank": 67, "score": 104816.47635695487 }, { "content": "#[doc(hidden)]\n\npub trait MessageMut: FnInput + FnOutput + FnSelector + FnState {\n\n const CALLABLE: fn(\n\n &mut <Self as FnState>::State,\n\n <Self as FnInput>::Input,\n\n ) -> <Self as FnOutput>::Output;\n\n}\n\n\n\n/// Indicates that some compile time expression is expected to be `true`.\n", "file_path": "crates/lang/src/traits.rs", "rank": 68, "score": 102500.79485457213 }, { "content": "/// Generates the tokens for the `SpreadLayout` `REQUIRES_DEEP_CLEAN_UP` constant for the given structure.\n\nfn requires_deep_clean_up(s: &synstructure::Structure) -> TokenStream2 {\n\n s.variants()\n\n .iter()\n\n .map(|variant| {\n\n variant\n\n .ast()\n\n .fields\n\n .iter()\n\n .map(|field| &field.ty)\n\n .map(|ty| quote! { <#ty as ::pro_storage::traits::SpreadLayout>::REQUIRES_DEEP_CLEAN_UP })\n\n .fold(quote! { false }, |lhs, rhs| {\n\n quote! { (#lhs || #rhs) }\n\n })\n\n })\n\n .fold(quote! { false }, |lhs, rhs| {\n\n quote! { (#lhs || #rhs) }\n\n })\n\n}\n\n\n", "file_path": "crates/storage/derive/src/spread_layout.rs", "rank": 69, "score": 93520.24385413484 }, { "content": "/// Returns the amount of storage cells used by the account `account_id`.\n\n///\n\n/// Returns `None` if the `account_id` is non-existent.\n\npub fn count_used_storage_cells<T>(account_id: &T::AccountId) -> Result<usize>\n\nwhere\n\n T: Environment,\n\n{\n\n <EnvInstance as OnInstance>::on_instance(|instance| {\n\n instance\n\n .accounts\n\n .get_account::<T>(account_id)\n\n .ok_or_else(|| AccountError::no_account_for_id::<T>(account_id))\n\n .map_err(Into::into)\n\n .and_then(|account| account.count_used_storage_cells().map_err(Into::into))\n\n })\n\n}\n\n\n", "file_path": "crates/env/src/engine/off_chain/test_api.rs", "rank": 70, "score": 91201.89889081151 }, { "content": "/// Extension trait to make `KeyPtr` simpler to use for `T: SpreadLayout` types.\n\npub trait ExtKeyPtr {\n\n /// Advances the key pointer by the same amount of the footprint of the\n\n /// generic type parameter of `T` and returns the old value.\n\n fn next_for<T>(&mut self) -> &Key\n\n where\n\n T: SpreadLayout;\n\n}\n\n\n\nimpl ExtKeyPtr for KeyPtr {\n\n fn next_for<T>(&mut self) -> &Key\n\n where\n\n T: SpreadLayout,\n\n {\n\n self.advance_by(<T as SpreadLayout>::FOOTPRINT)\n\n }\n\n}\n", "file_path": "crates/storage/src/traits/keyptr.rs", "rank": 71, "score": 91098.17172125888 }, { "content": "use pro_lang as pro;\n\n\n\n#[pro::contract]\n\nmod noop {\n\n #[pro(storage)]\n\n pub struct Noop {}\n\n\n\n impl Noop {\n\n #[pro(constructor)]\n\n pub fn self_mut_arg(&mut self) -> Self {\n\n Self {}\n\n }\n\n\n\n #[pro(message)]\n\n pub fn noop(&self) {}\n\n }\n\n}\n\n\n", "file_path": "crates/lang/macro/tests/ui/fail/C-01-constructor-self-mut.rs", "rank": 72, "score": 88884.90525705913 }, { "content": "/// A pack of 64 bits.\n\ntype Bits64 = u64;\n\n\n\n/// A storage bit vector.\n\n///\n\n/// # Note\n\n///\n\n/// Organizes its bits in chunks of 256 bits.\n\n/// Allows to `push`, `pop`, inspect and manipulate the underlying bits.\n\n#[derive(Debug)]\n\npub struct Bitvec {\n\n /// The length of the bit vector.\n\n len: Lazy<u32>,\n\n /// The bits of the bit vector.\n\n ///\n\n /// Organized in packs of 256 bits.\n\n bits: StorageVec<Bits256>,\n\n}\n\n\n\nimpl Bitvec {\n\n /// Creates a new empty bit vector.\n", "file_path": "crates/storage/src/collections/bitvec/mod.rs", "rank": 73, "score": 83240.70778171325 }, { "content": "#[test]\n\nfn trim_docs() {\n\n // given\n\n let name = \"foo\";\n\n let cs = ConstructorSpec::from_name(name)\n\n .selector(123_456_789u32.to_be_bytes())\n\n .docs(vec![\" foobar \"])\n\n .done();\n\n let mut registry = Registry::new();\n\n let compact_spec = cs.into_portable(&mut registry);\n\n\n\n // when\n\n let json = serde_json::to_value(&compact_spec).unwrap();\n\n let deserialized: ConstructorSpec<PortableForm<String>> =\n\n serde_json::from_value(json.clone()).unwrap();\n\n\n\n // then\n\n assert_eq!(\n\n json,\n\n json!({\n\n \"name\": [\"foo\"],\n\n \"selector\": \"0x075bcd15\",\n\n \"args\": [],\n\n \"docs\": [\"foobar\"]\n\n })\n\n );\n\n assert_eq!(deserialized.docs, compact_spec.docs);\n\n}\n", "file_path": "crates/metadata/src/tests.rs", "rank": 74, "score": 81546.58926159094 }, { "content": "fn main() {\n\n hashmap_backend::run();\n\n lazyhmap_backend::run();\n\n}\n", "file_path": "crates/storage/benches/bench_hashmap.rs", "rank": 75, "score": 81546.58926159094 }, { "content": "/// Creates a `BitStash` and pushes it to the contract storage.\n\nfn push_stash() {\n\n let stash = BitStash::default();\n\n let root_key = Key::from([0x00; 32]);\n\n SpreadLayout::push_spread(&stash, &mut KeyPtr::from(root_key));\n\n}\n\n\n", "file_path": "crates/storage/benches/bench_bitstash.rs", "rank": 76, "score": 80342.86292778954 }, { "content": "#[test]\n\nfn spec_contract_json() {\n\n // given\n\n let contract: ContractSpec = ContractSpec::new()\n\n .constructors(vec![\n\n ConstructorSpec::from_name(\"new\")\n\n .selector([94u8, 189u8, 136u8, 214u8])\n\n .args(vec![MessageParamSpec::new(\"init_value\")\n\n .of_type(TypeSpec::with_name_segs::<i32, _>(\n\n vec![\"i32\"].into_iter().map(AsRef::as_ref),\n\n ))\n\n .done()])\n\n .docs(Vec::new())\n\n .done(),\n\n ConstructorSpec::from_name(\"default\")\n\n .selector([2u8, 34u8, 255u8, 24u8])\n\n .args(Vec::new())\n\n .docs(Vec::new())\n\n .done(),\n\n ])\n\n .messages(vec![\n", "file_path": "crates/metadata/src/tests.rs", "rank": 77, "score": 80342.86292778954 }, { "content": "#[test]\n\nfn get_works() {\n\n let expected_keys = [\n\n b\"\\\n\n \\x0A\\x0F\\xF5\\x30\\xBD\\x5A\\xB6\\x67\\\n\n \\x85\\xC9\\x74\\x6D\\x01\\x33\\xD7\\xE1\\\n\n \\x24\\x40\\xC4\\x67\\xA9\\xF0\\x6D\\xCA\\\n\n \\xE7\\xED\\x2E\\x78\\x32\\x77\\xE9\\x10\",\n\n b\"\\\n\n \\x11\\x5A\\xC0\\xB2\\x29\\xA5\\x34\\x10\\\n\n \\xB0\\xC0\\x2D\\x47\\x49\\xDC\\x7A\\x09\\\n\n \\xB9\\x6D\\xF9\\x51\\xB6\\x1D\\x4F\\x3B\\\n\n \\x4E\\x75\\xAC\\x3B\\x14\\x57\\x47\\x96\",\n\n ];\n\n assert_eq!(DynamicAllocation(0).key(), Key::from(*expected_keys[0]));\n\n assert_eq!(DynamicAllocation(1).key(), Key::from(*expected_keys[1]));\n\n}\n", "file_path": "crates/storage/src/alloc/allocation.rs", "rank": 78, "score": 80342.86292778954 }, { "content": "#[test]\n\nfn test_hash_blake2_128() {\n\n let mut output = [0x00_u8; 16];\n\n crate::hash_bytes::<crate::hash::Blake2x128>(TEST_INPUT, &mut output);\n\n assert_eq!(\n\n output,\n\n [180, 158, 48, 21, 171, 163, 217, 175, 145, 160, 25, 159, 213, 142, 103, 242]\n\n );\n\n}\n", "file_path": "crates/env/src/tests.rs", "rank": 79, "score": 80342.86292778954 }, { "content": "#[test]\n\nfn alloc_works() {\n\n run_default_test(|| {\n\n assert_eq!(alloc(), DynamicAllocation(0));\n\n })\n\n}\n\n\n\ncfg_if::cfg_if! {\n\n if #[cfg(miri)] {\n\n // We need to lower the test allocations because miri's stacked borrows\n\n // analysis currently is super linear for some work loads.\n\n // Read more here: https://github.com/rust-lang/miri/issues/1367\n\n const TEST_ALLOCATIONS: u32 = 10;\n\n } else {\n\n const TEST_ALLOCATIONS: u32 = 10_000;\n\n }\n\n}\n\n\n", "file_path": "crates/storage/src/alloc/tests.rs", "rank": 80, "score": 80342.86292778954 }, { "content": "#[test]\n\nfn test_hash_blake2_256() {\n\n let mut output = [0x00_u8; 32];\n\n crate::hash_bytes::<crate::hash::Blake2x256>(TEST_INPUT, &mut output);\n\n assert_eq!(\n\n output,\n\n [\n\n 244, 247, 235, 182, 194, 161, 28, 69, 34, 106, 237, 7, 57, 87, 190, 12, 92,\n\n 171, 91, 176, 135, 52, 247, 94, 8, 112, 94, 183, 140, 101, 208, 120\n\n ]\n\n );\n\n}\n\n\n", "file_path": "crates/env/src/tests.rs", "rank": 81, "score": 80342.86292778954 }, { "content": "#[test]\n\nfn test_hash_keccak_256() {\n\n let mut output = [0x00_u8; 32];\n\n crate::hash_bytes::<crate::hash::Keccak256>(TEST_INPUT, &mut output);\n\n assert_eq!(\n\n output,\n\n [\n\n 24, 230, 209, 59, 127, 30, 158, 244, 60, 177, 132, 150, 167, 244, 64, 69,\n\n 184, 123, 185, 44, 211, 199, 208, 179, 14, 64, 126, 140, 217, 69, 36, 216\n\n ]\n\n );\n\n}\n\n\n", "file_path": "crates/env/src/tests.rs", "rank": 82, "score": 80342.86292778954 }, { "content": "#[test]\n\n#[should_panic(expected = \"invalid dynamic storage allocation\")]\n\nfn free_out_of_bounds() {\n\n run_default_test(|| {\n\n free(DynamicAllocation(0));\n\n })\n\n}\n\n\n", "file_path": "crates/storage/src/alloc/tests.rs", "rank": 83, "score": 80342.86292778954 }, { "content": "#[test]\n\nfn test_hash_sha2_256() {\n\n let mut output = [0x00_u8; 32];\n\n crate::hash_bytes::<crate::hash::Sha2x256>(TEST_INPUT, &mut output);\n\n assert_eq!(\n\n output,\n\n [\n\n 136, 15, 25, 218, 88, 54, 49, 152, 115, 168, 147, 189, 207, 171, 243, 129,\n\n 161, 76, 15, 141, 197, 106, 111, 213, 19, 197, 133, 219, 181, 233, 195, 120\n\n ]\n\n );\n\n}\n\n\n", "file_path": "crates/env/src/tests.rs", "rank": 84, "score": 80342.86292778954 }, { "content": "#[test]\n\nfn free_works() {\n\n run_default_test(|| {\n\n // Check that this pattern does not panic.\n\n free(alloc());\n\n })\n\n}\n\n\n", "file_path": "crates/storage/src/alloc/tests.rs", "rank": 85, "score": 80342.86292778954 }, { "content": "#[test]\n\nfn get_works() {\n\n let elems = [b'A', b'B', b'C', b'D'];\n\n let mut vec = vec_from_slice(&elems);\n\n for (n, mut expected) in elems.iter().copied().enumerate() {\n\n let n = n as u32;\n\n assert_eq!(vec.get(n), Some(&expected));\n\n assert_eq!(vec.get_mut(n), Some(&mut expected));\n\n assert_eq!(&vec[n], &expected);\n\n assert_eq!(&mut vec[n], &mut expected);\n\n }\n\n let len = vec.len();\n\n assert_eq!(vec.get(len), None);\n\n assert_eq!(vec.get_mut(len), None);\n\n}\n\n\n", "file_path": "crates/storage/src/collections/smallvec/tests.rs", "rank": 86, "score": 79197.94922047737 }, { "content": "#[test]\n\nfn insert_works() {\n\n let mut hmap = <StorageHashMap<u8, i32>>::new();\n\n // Start with an empty hash map.\n\n assert_eq!(hmap.len(), 0);\n\n assert_eq!(hmap.get(&b'A'), None);\n\n // Insert first value.\n\n hmap.insert(b'A', 1);\n\n assert_eq!(hmap.len(), 1);\n\n assert_eq!(hmap.get(&b'A'), Some(&1));\n\n assert_eq!(hmap.get_mut(&b'A'), Some(&mut 1));\n\n // Update the inserted value.\n\n hmap.insert(b'A', 2);\n\n assert_eq!(hmap.len(), 1);\n\n assert_eq!(hmap.get(&b'A'), Some(&2));\n\n assert_eq!(hmap.get_mut(&b'A'), Some(&mut 2));\n\n // Insert another value.\n\n hmap.insert(b'B', 3);\n\n assert_eq!(hmap.len(), 2);\n\n assert_eq!(hmap.get(&b'B'), Some(&3));\n\n assert_eq!(hmap.get_mut(&b'B'), Some(&mut 3));\n\n}\n\n\n", "file_path": "crates/storage/src/collections/hashmap/tests.rs", "rank": 87, "score": 79197.94922047737 }, { "content": "#[test]\n\n#[should_panic(expected = \"encountered empty storage cell\")]\n\nfn drop_works() {\n\n pro_env::test::run_test::<pro_env::DefaultEnvironment, _>(|_| {\n\n let root_key = Key::from([0x42; 32]);\n\n\n\n // if the setup panics it should not cause the test to pass\n\n let setup_result = std::panic::catch_unwind(|| {\n\n let vec = vec_from_slice(&[b'a', b'b', b'c', b'd']);\n\n SpreadLayout::push_spread(&vec, &mut KeyPtr::from(root_key));\n\n let _ = <SmallVec<u8, U4> as SpreadLayout>::pull_spread(&mut KeyPtr::from(\n\n root_key,\n\n ));\n\n // vec is dropped which should clear the cells\n\n });\n\n assert!(setup_result.is_ok(), \"setup should not panic\");\n\n\n\n let contract_id = pro_env::test::get_current_contract_account_id::<\n\n pro_env::DefaultEnvironment,\n\n >()\n\n .expect(\"Cannot get contract id\");\n\n let used_cells = pro_env::test::count_used_storage_cells::<\n", "file_path": "crates/storage/src/collections/smallvec/tests.rs", "rank": 88, "score": 79197.94922047737 }, { "content": "#[test]\n\nfn get_works() {\n\n // Empty hash map.\n\n let hmap = <StorageHashMap<u8, i32>>::new();\n\n assert_eq!(hmap.get(&b'A'), None);\n\n assert_eq!(hmap.get(&b'E'), None);\n\n // Filled hash map: `get`\n\n let hmap = filled_hmap();\n\n assert_eq!(hmap.get(&b'A'), Some(&1));\n\n assert_eq!(hmap.get(&b'B'), Some(&2));\n\n assert_eq!(hmap.get(&b'C'), Some(&3));\n\n assert_eq!(hmap.get(&b'D'), Some(&4));\n\n assert_eq!(hmap.get(&b'E'), None);\n\n // Filled hash map: `get_mut`\n\n let mut hmap = hmap;\n\n assert_eq!(hmap.get_mut(&b'A'), Some(&mut 1));\n\n assert_eq!(hmap.get_mut(&b'B'), Some(&mut 2));\n\n assert_eq!(hmap.get_mut(&b'C'), Some(&mut 3));\n\n assert_eq!(hmap.get_mut(&b'D'), Some(&mut 4));\n\n assert_eq!(hmap.get_mut(&b'E'), None);\n\n}\n\n\n", "file_path": "crates/storage/src/collections/hashmap/tests.rs", "rank": 89, "score": 79197.94922047737 }, { "content": "/// Creates a storage vector and pushes it to the contract storage.\n\nfn push_storage_vec() {\n\n let vec = storage_vec_from_slice(test_values());\n\n let root_key = Key::from([0x00; 32]);\n\n SpreadLayout::push_spread(&vec, &mut KeyPtr::from(root_key));\n\n}\n\n\n", "file_path": "crates/storage/benches/bench_vec.rs", "rank": 90, "score": 79197.94922047737 }, { "content": "#[test]\n\nfn take_works() {\n\n // Empty hash map.\n\n let mut hmap = <StorageHashMap<u8, i32>>::new();\n\n assert_eq!(hmap.take(&b'A'), None);\n\n assert_eq!(hmap.take(&b'E'), None);\n\n // Filled hash map: `get`\n\n let mut hmap = filled_hmap();\n\n assert_eq!(hmap.len(), 4);\n\n assert_eq!(hmap.take(&b'A'), Some(1));\n\n assert_eq!(hmap.len(), 3);\n\n assert_eq!(hmap.take(&b'A'), None);\n\n assert_eq!(hmap.len(), 3);\n\n assert_eq!(hmap.take(&b'B'), Some(2));\n\n assert_eq!(hmap.len(), 2);\n\n assert_eq!(hmap.take(&b'C'), Some(3));\n\n assert_eq!(hmap.len(), 1);\n\n assert_eq!(hmap.take(&b'D'), Some(4));\n\n assert_eq!(hmap.len(), 0);\n\n assert_eq!(hmap.take(&b'E'), None);\n\n assert_eq!(hmap.len(), 0);\n\n}\n\n\n", "file_path": "crates/storage/src/collections/hashmap/tests.rs", "rank": 91, "score": 79197.94922047737 }, { "content": "#[test]\n\nfn from_iterator_works() {\n\n let some_primes = [b'A', b'B', b'C', b'D'];\n\n assert_eq!(some_primes.iter().copied().collect::<SmallVec<_, U4>>(), {\n\n let mut vec = SmallVec::new();\n\n for prime in &some_primes {\n\n vec.push(*prime)\n\n }\n\n vec\n\n });\n\n}\n\n\n", "file_path": "crates/storage/src/collections/smallvec/tests.rs", "rank": 92, "score": 79197.94922047737 }, { "content": "#[test]\n\nfn defrag_works() {\n\n let expected = [(b'A', 1), (b'D', 4)]\n\n .iter()\n\n .copied()\n\n .collect::<StorageHashMap<u8, i32>>();\n\n // Defrag without limits:\n\n let mut hmap = filled_hmap();\n\n assert_eq!(hmap.defrag(None), 0);\n\n assert_eq!(hmap.take(&b'B'), Some(2));\n\n assert_eq!(hmap.take(&b'C'), Some(3));\n\n assert_eq!(hmap.defrag(None), 2);\n\n assert_eq!(hmap.defrag(None), 0);\n\n assert_eq!(hmap, expected);\n\n // Defrag with limits:\n\n let mut hmap = [(b'A', 1), (b'B', 2), (b'C', 3), (b'D', 4)]\n\n .iter()\n\n .copied()\n\n .collect::<StorageHashMap<u8, i32>>();\n\n assert_eq!(hmap.defrag(None), 0);\n\n assert_eq!(hmap.take(&b'B'), Some(2));\n\n assert_eq!(hmap.take(&b'C'), Some(3));\n\n assert_eq!(hmap.defrag(Some(1)), 1);\n\n assert_eq!(hmap.defrag(Some(1)), 1);\n\n assert_eq!(hmap.defrag(Some(1)), 0);\n\n assert_eq!(hmap, expected);\n\n}\n\n\n", "file_path": "crates/storage/src/collections/hashmap/tests.rs", "rank": 93, "score": 79197.94922047737 }, { "content": "#[test]\n\n#[should_panic(expected = \"storage entry was empty\")]\n\nfn drop_works() {\n\n pro_env::test::run_test::<pro_env::DefaultEnvironment, _>(|_| {\n\n let root_key = Key::from([0x42; 32]);\n\n\n\n // if the setup panics it should not cause the test to pass\n\n let setup_result = std::panic::catch_unwind(|| {\n\n let hmap = filled_hmap();\n\n SpreadLayout::push_spread(&hmap, &mut KeyPtr::from(root_key));\n\n let _ = <StorageHashMap<u8, i32> as SpreadLayout>::pull_spread(\n\n &mut KeyPtr::from(root_key),\n\n );\n\n // hmap is dropped which should clear the cells\n\n });\n\n assert!(setup_result.is_ok(), \"setup should not panic\");\n\n\n\n let contract_id = pro_env::test::get_current_contract_account_id::<\n\n pro_env::DefaultEnvironment,\n\n >()\n\n .expect(\"Cannot get contract id\");\n\n let used_cells = pro_env::test::count_used_storage_cells::<\n", "file_path": "crates/storage/src/collections/hashmap/tests.rs", "rank": 94, "score": 79197.94922047737 }, { "content": "#[test]\n\n#[should_panic]\n\nfn from_iterator_too_many() {\n\n let some_primes = [b'A', b'B', b'C', b'D', b'E'];\n\n let _ = some_primes.iter().copied().collect::<SmallVec<_, U4>>();\n\n}\n\n\n", "file_path": "crates/storage/src/collections/smallvec/tests.rs", "rank": 95, "score": 79197.94922047737 }, { "content": "#[test]\n\nfn new_works() {\n\n run_test(|_| {\n\n let mut expected = 1;\n\n let mut boxed = StorageBox::new(expected);\n\n assert_eq!(StorageBox::get(&boxed), &expected);\n\n assert_eq!(StorageBox::get_mut(&mut boxed), &mut expected);\n\n assert_eq!(Deref::deref(&boxed), &expected);\n\n assert_eq!(DerefMut::deref_mut(&mut boxed), &mut expected);\n\n assert_eq!(AsRef::as_ref(&boxed), &expected);\n\n assert_eq!(AsMut::as_mut(&mut boxed), &mut expected);\n\n assert_eq!(Borrow::<i32>::borrow(&boxed), &expected);\n\n assert_eq!(BorrowMut::<i32>::borrow_mut(&mut boxed), &mut expected);\n\n })\n\n}\n\n\n", "file_path": "crates/storage/src/alloc/boxed/tests.rs", "rank": 96, "score": 79197.94922047737 }, { "content": "#[test]\n\nfn swap_works() {\n\n let elems = [b'A', b'B', b'C', b'D'];\n\n let mut vec = vec_from_slice(&elems);\n\n\n\n // Swap at same position is a no-op.\n\n for index in 0..elems.len() as u32 {\n\n vec.swap(index, index);\n\n assert_eq_slice(&vec, &elems);\n\n }\n\n\n\n // Swap first and second\n\n vec.swap(0, 1);\n\n assert_eq_slice(&vec, &[b'B', b'A', b'C', b'D']);\n\n // Swap third and last\n\n vec.swap(2, 3);\n\n assert_eq_slice(&vec, &[b'B', b'A', b'D', b'C']);\n\n // Swap first and last\n\n vec.swap(0, 3);\n\n assert_eq_slice(&vec, &[b'C', b'A', b'D', b'B']);\n\n}\n\n\n", "file_path": "crates/storage/src/collections/smallvec/tests.rs", "rank": 97, "score": 79197.94922047737 }, { "content": "#[test]\n\nfn new_works() {\n\n // `StorageHashMap::new`\n\n let hmap = <StorageHashMap<u8, i32>>::new();\n\n assert!(hmap.is_empty());\n\n assert_eq!(hmap.len(), 0);\n\n assert!(hmap.iter().next().is_none());\n\n // `StorageHashMap::default`\n\n let default = <StorageHashMap<u8, i32> as Default>::default();\n\n assert!(default.is_empty());\n\n assert_eq!(default.len(), 0);\n\n assert!(default.iter().next().is_none());\n\n // `StorageHashMap::new` and `StorageHashMap::default` should be equal.\n\n assert_eq!(hmap, default);\n\n}\n\n\n", "file_path": "crates/storage/src/collections/hashmap/tests.rs", "rank": 98, "score": 79197.94922047737 }, { "content": "#[test]\n\nfn from_iterator_works() {\n\n let test_values = [(b'A', 1), (b'B', 2), (b'C', 3), (b'D', 4)];\n\n let hmap = test_values\n\n .iter()\n\n .copied()\n\n .collect::<StorageHashMap<u8, i32>>();\n\n assert!(!hmap.is_empty());\n\n assert_eq!(hmap.len(), 4);\n\n assert_eq!(hmap, {\n\n let mut hmap = <StorageHashMap<u8, i32>>::new();\n\n for (key, value) in &test_values {\n\n assert_eq!(hmap.insert(*key, *value), None);\n\n }\n\n hmap\n\n });\n\n}\n\n\n", "file_path": "crates/storage/src/collections/hashmap/tests.rs", "rank": 99, "score": 79197.94922047737 } ]
Rust
crates/api/src/event/mouse.rs
michalsieron/orbtk
f0d53cd645f55f632173a89aee2fa85edbd9e96f
use std::rc::Rc; use crate::{ prelude::*, proc_macros::{Event, IntoHandler}, shell::MouseButton, utils::*, }; pub fn check_mouse_condition(mouse_position: Point, widget: &WidgetContainer<'_>) -> bool { let enabled = widget.get::<bool>("enabled"); if !enabled { return false; } let bounds = widget.get::<Rectangle>("bounds"); let position = widget.get::<Point>("position"); let mut rect = Rectangle::new((0.0, 0.0), bounds.width(), bounds.height()); rect.set_x(position.x()); rect.set_y(position.y()); rect.contains(mouse_position) } #[derive(Event)] pub struct MouseMoveEvent { pub position: Point, } #[derive(Event)] pub struct ScrollEvent { pub delta: Point, } #[derive(Debug, Copy, Clone)] pub struct Mouse { pub button: MouseButton, pub position: Point, } #[derive(Event)] pub struct MouseUpEvent { pub button: MouseButton, pub position: Point, } #[derive(Event)] pub struct ClickEvent { pub position: Point, } #[derive(Event)] pub struct MouseDownEvent { pub button: MouseButton, pub position: Point, } #[derive(Event)] pub struct GlobalMouseUpEvent { pub button: MouseButton, pub position: Point, } pub type MouseHandlerFunction = dyn Fn(&mut StatesContext, Mouse) -> bool + 'static; pub type PositionHandlerFunction = dyn Fn(&mut StatesContext, Point) -> bool + 'static; pub type GlobalMouseHandlerFunction = dyn Fn(&mut StatesContext, Mouse) + 'static; pub struct ClickEventHandler { handler: Rc<PositionHandlerFunction>, } impl Into<Rc<dyn EventHandler>> for ClickEventHandler { fn into(self) -> Rc<dyn EventHandler> { Rc::new(self) } } impl EventHandler for ClickEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<ClickEvent>() .ok() .map_or(false, |event| (self.handler)(state_context, event.position)) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<ClickEvent>() } } #[derive(IntoHandler)] pub struct MouseDownEventHandler { handler: Rc<MouseHandlerFunction>, } impl EventHandler for MouseDownEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<MouseDownEvent>() .ok() .map_or(false, |event| { (self.handler)( state_context, Mouse { button: event.button, position: event.position, }, ) }) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<MouseDownEvent>() } } #[derive(IntoHandler)] pub struct GlobalMouseUpEventHandler { handler: Rc<GlobalMouseHandlerFunction>, } impl EventHandler for GlobalMouseUpEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<GlobalMouseUpEvent>() .ok() .map_or(false, |event| { (self.handler)( state_context, Mouse { button: event.button, position: event.position, }, ); false }) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<GlobalMouseUpEvent>() } } #[derive(IntoHandler)] pub struct MouseUpEventHandler { handler: Rc<MouseHandlerFunction>, } impl EventHandler for MouseUpEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<MouseUpEvent>() .ok() .map_or(false, |event| { (self.handler)( state_context, Mouse { button: event.button, position: event.position, }, ) }) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<MouseUpEvent>() } } #[derive(IntoHandler)] pub struct MouseMoveEventHandler { handler: Rc<PositionHandlerFunction>, } impl EventHandler for MouseMoveEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<MouseMoveEvent>() .ok() .map_or(false, |event| (self.handler)(state_context, event.position)) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<MouseMoveEvent>() } } #[derive(IntoHandler)] pub struct ScrollEventHandler { handler: Rc<PositionHandlerFunction>, } impl EventHandler for ScrollEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<ScrollEvent>() .ok() .map_or(false, |event| (self.handler)(state_context, event.delta)) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<ScrollEvent>() } } pub trait MouseHandler: Sized + Widget { fn on_click<H: Fn(&mut StatesContext, Point) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(ClickEventHandler { handler: Rc::new(handler), }) } fn on_mouse_down<H: Fn(&mut StatesContext, Mouse) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(MouseDownEventHandler { handler: Rc::new(handler), }) } fn on_mouse_up<H: Fn(&mut StatesContext, Mouse) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(MouseUpEventHandler { handler: Rc::new(handler), }) } fn on_global_mouse_up<H: Fn(&mut StatesContext, Mouse) + 'static>(self, handler: H) -> Self { self.insert_handler(GlobalMouseUpEventHandler { handler: Rc::new(handler), }) } fn on_mouse_move<H: Fn(&mut StatesContext, Point) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(MouseMoveEventHandler { handler: Rc::new(handler), }) } fn on_scroll<H: Fn(&mut StatesContext, Point) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(ScrollEventHandler { handler: Rc::new(handler), }) } }
use std::rc::Rc; use crate::{ prelude::*, proc_macros::{Event, IntoHandler}, shell::MouseButton, utils::*, }; pub fn check_mouse_condition(mouse_position: Point, widget: &WidgetContainer<'_>) -> bool { let enabled = widget.get::<bool>("enabled"); if !enabled { return false; } let bounds = widget.get::<Rectangle>("bounds"); let position = widget.get::<Point>("position"); let mut rect = Rectangle::new((0.0, 0.0), bounds.width(), bounds.height()); rect.set_x(position.x()); rect.set_y(position.y()); rect.contains(mouse_position) } #[derive(Event)] pub struct MouseMoveEvent { pub position: Point, } #[derive(Event)] pub struct ScrollEvent { pub delta: Point, } #[derive(Debug, Copy, Clone)] pub struct Mouse { pub button: MouseButton, pub position: Point, } #[derive(Event)] pub struct MouseUpEvent { pub button: MouseButton, pub position: Point, } #[derive(Event)] pub struct ClickEvent { pub position: Point, } #[derive(Event)] pub struct MouseDownEvent { pub button: MouseButton, pub position: Point, } #[derive(Event)] pub struct GlobalMouseUpEvent { pub button: MouseButton, pub position: Point, } pub type MouseHandlerFunction = dyn Fn(&mut StatesContext, Mouse) -> bool + 'static; pub type PositionHandlerFunction = dyn Fn(&mut StatesContext, Point) -> bool + 'static; pub type GlobalMouseHandlerFunction = dyn Fn(&mut StatesContext, Mouse) + 'static; pub struct ClickEventHandler { handler: Rc<PositionHandlerFunction>, } impl Into<Rc<dyn EventHandler>> for ClickEventHandler { fn into(self) -> Rc<dyn EventHandler> { Rc::new(self) } } impl EventHandler for ClickEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<ClickEvent>() .ok() .map_or(false, |event| (self.handler)(state_context, event.position)) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<ClickEvent>() } } #[derive(IntoHandler)] pub struct MouseDownEventHandler { handler: Rc<MouseHandlerFunction>, } impl EventHandler for MouseDownEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<MouseDownEvent>() .ok() .map_or(false, |event| { (self.handler)( state_context, Mouse { button: event.button, position: event.position, }, ) }) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<MouseDownEvent>() } } #[derive(IntoHandler)] pub struct GlobalMouseUpEventHandler { handler: Rc<GlobalMouseHandlerFunction>, } impl EventHandler for GlobalMouseUpEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<GlobalMouseUpEvent>() .ok() .map_or(false, |event| { (self.handler)( state_context, Mouse { button: event.button, position: event.position, }, ); false }) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<GlobalMouseUpEvent>() } } #[derive(IntoHandler)] pub struct MouseUpEventHandler { handler: Rc<MouseHandlerFunction>, } impl EventHandler for MouseUpEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<MouseUpEvent>() .ok() .map_or(false, |event| { (self.handler)( state_context, Mouse { button: event.button, position: event.position, }, ) }) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<MouseUpEvent>() } } #[derive(IntoHandler)] pub struct MouseMoveEventHandler { handler: Rc<PositionHandlerFunction>, } impl EventHandler for MouseMoveEventHandler {
fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<MouseMoveEvent>() } } #[derive(IntoHandler)] pub struct ScrollEventHandler { handler: Rc<PositionHandlerFunction>, } impl EventHandler for ScrollEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<ScrollEvent>() .ok() .map_or(false, |event| (self.handler)(state_context, event.delta)) } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<ScrollEvent>() } } pub trait MouseHandler: Sized + Widget { fn on_click<H: Fn(&mut StatesContext, Point) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(ClickEventHandler { handler: Rc::new(handler), }) } fn on_mouse_down<H: Fn(&mut StatesContext, Mouse) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(MouseDownEventHandler { handler: Rc::new(handler), }) } fn on_mouse_up<H: Fn(&mut StatesContext, Mouse) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(MouseUpEventHandler { handler: Rc::new(handler), }) } fn on_global_mouse_up<H: Fn(&mut StatesContext, Mouse) + 'static>(self, handler: H) -> Self { self.insert_handler(GlobalMouseUpEventHandler { handler: Rc::new(handler), }) } fn on_mouse_move<H: Fn(&mut StatesContext, Point) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(MouseMoveEventHandler { handler: Rc::new(handler), }) } fn on_scroll<H: Fn(&mut StatesContext, Point) -> bool + 'static>(self, handler: H) -> Self { self.insert_handler(ScrollEventHandler { handler: Rc::new(handler), }) } }
fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<MouseMoveEvent>() .ok() .map_or(false, |event| (self.handler)(state_context, event.position)) }
function_block-full_function
[ { "content": "fn get_mouse_button(button: event::MouseButton) -> MouseButton {\n\n match button {\n\n event::MouseButton::Wheel => MouseButton::Middle,\n\n event::MouseButton::Right => MouseButton::Right,\n\n _ => MouseButton::Left,\n\n }\n\n}\n\n\n", "file_path": "crates/shell/src/web/window.rs", "rank": 1, "score": 288705.7134744631 }, { "content": "/// Toggles the selector state`.\n\npub fn toggle_flag(flag: &str, widget: &mut WidgetContainer) {\n\n if !widget.has::<bool>(flag) {\n\n return;\n\n }\n\n\n\n let value = *widget.get::<bool>(flag);\n\n\n\n if let Some(selector) = widget.try_get_mut::<Selector>(\"selector\") {\n\n if value {\n\n selector.set_state(flag);\n\n } else {\n\n selector.clear_state();\n\n }\n\n }\n\n}\n\n\n\n/// Used to define the `parent_type`of a widget.\n\npub enum ParentType {\n\n /// No children could be added to the widget.\n\n None,\n\n\n\n /// Only one child could be added to the widget.\n\n Single,\n\n\n\n /// Multiple children could be added to the widget.\n\n Multi,\n\n}\n\n\n", "file_path": "crates/api/src/widget_base/mod.rs", "rank": 3, "score": 240321.0148466796 }, { "content": "/// Creates a `WindowAdapter` and a `WindowSettings` object from a window builder closure.\n\npub fn create_window<F: Fn(&mut BuildContext) -> Entity + 'static>(\n\n app_name: impl Into<String>,\n\n theme: Theme,\n\n request_sender: mpsc::Sender<ShellRequest<WindowAdapter>>,\n\n create_fn: F,\n\n) -> (WindowAdapter, WindowSettings, mpsc::Receiver<WindowRequest>) {\n\n let app_name = app_name.into();\n\n let mut world: World<Tree, StringComponentStore, render::RenderContext2D> =\n\n World::from_stores(Tree::default(), StringComponentStore::default());\n\n\n\n let (sender, receiver) = mpsc::channel();\n\n\n\n let registry = Rc::new(RefCell::new(Registry::new()));\n\n\n\n if app_name.is_empty() {\n\n registry\n\n .borrow_mut()\n\n .register(\"settings\", Settings::default());\n\n } else {\n\n registry\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 4, "score": 236073.59756911203 }, { "content": "pub trait ChangedHandler: Sized + Widget {\n\n /// Register a on property changed handler.\n\n fn on_changed<H: Fn(&mut StatesContext, Entity, &str) + 'static>(self, handler: H) -> Self {\n\n self.insert_handler(ChangedEventHandler {\n\n handler: Rc::new(handler),\n\n })\n\n }\n\n}\n", "file_path": "crates/api/src/event/editable.rs", "rank": 5, "score": 219546.28206995525 }, { "content": "pub trait KeyDownHandler: Sized + Widget {\n\n /// Inserts a handler.\n\n fn on_key_down<H: Fn(&mut StatesContext, KeyEvent) -> bool + 'static>(\n\n self,\n\n handler: H,\n\n ) -> Self {\n\n self.insert_handler(KeyDownEventHandler {\n\n handler: Rc::new(handler),\n\n })\n\n }\n\n\n\n /// Handles events triggered by a specific key.\n\n fn on_key_down_key<H: Fn() -> bool + 'static>(self, key: Key, handler: H) -> Self {\n\n self.on_key_down(\n\n move |_, event| {\n\n if event.key == key {\n\n handler()\n\n } else {\n\n false\n\n }\n\n },\n\n )\n\n }\n\n}\n", "file_path": "crates/api/src/event/key.rs", "rank": 6, "score": 219546.28206995525 }, { "content": "pub trait SelectionChangedHandler: Sized + Widget {\n\n /// Inserts a click handler.\n\n fn on_selection_changed<H: Fn(&mut StatesContext, Entity, Vec<usize>) + 'static>(\n\n self,\n\n handler: H,\n\n ) -> Self {\n\n self.insert_handler(SelectionChangedEventHandler {\n\n handler: Rc::new(handler),\n\n })\n\n }\n\n}\n\n\n\n#[derive(Clone, Event)]\n\n/// This event occurs when a property of a widget is updated.\n\npub struct ChangedEvent(pub Entity, pub String);\n\n\n\n/// Used to define a property changed callback.\n\npub type ChangedHandlerFn = dyn Fn(&mut StatesContext, Entity, &str) + 'static;\n\n\n\n#[derive(IntoHandler)]\n", "file_path": "crates/api/src/event/editable.rs", "rank": 7, "score": 215105.86373070063 }, { "content": "/// Mark the widget and shared widgets as dirty.\n\npub fn mark_as_dirty(\n\n key: &str,\n\n entity: Entity,\n\n ecm: &mut EntityComponentManager<Tree, StringComponentStore>,\n\n) {\n\n let root = ecm.entity_store().root();\n\n\n\n for entity in ecm.component_store().entities_of_component(key, entity) {\n\n *ecm.component_store_mut()\n\n .get_mut::<bool>(\"dirty\", entity)\n\n .unwrap() = true;\n\n\n\n if let Ok(dirty_widgets) = ecm\n\n .component_store_mut()\n\n .get_mut::<Vec<Entity>>(\"dirty_widgets\", root)\n\n {\n\n // don't add the same widget twice in a row\n\n if dirty_widgets.is_empty() || *dirty_widgets.last().unwrap() != entity {\n\n dirty_widgets.push(entity);\n\n }\n", "file_path": "crates/api/src/widget_base/widget_container.rs", "rank": 8, "score": 198858.64455898455 }, { "content": "/// This trait is used to define an event handler.\n\npub trait EventHandler {\n\n /// Handles an `event` by the given `widget`. If it returns `true` the event will not be forwarded.\n\n fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool;\n\n\n\n /// Check if the handler could handle the given event box.\n\n fn handles_event(&self, event: &EventBox) -> bool;\n\n}\n", "file_path": "crates/api/src/event/event_handler.rs", "rank": 9, "score": 198006.30898587566 }, { "content": "#[derive(Clone)]\n\nstruct PipelineWrapper(pub Box<dyn PipelineTrait>);\n\n\n\nimpl PartialEq for PipelineWrapper {\n\n fn eq(&self, _: &Self) -> bool {\n\n true\n\n }\n\n}\n\n\n\n// Used to sent render tasks to render thread.\n", "file_path": "crates/render/src/concurrent/mod.rs", "rank": 10, "score": 192770.20605912327 }, { "content": "pub fn get_all_children(children: &mut Vec<Entity>, parent: Entity, tree: &Tree) {\n\n for child in &tree.children[&parent] {\n\n children.push(*child);\n\n get_all_children(children, *child, tree);\n\n }\n\n}\n\n\n\n// -- Helpers --\n", "file_path": "crates/api/src/widget_base/context.rs", "rank": 11, "score": 190389.18030398383 }, { "content": "#[test]\n\nfn test_add() {\n\n const EXPECTED_RESULT: Point = Point { x: 13., y: 9. };\n\n const ERROR_MARGIN: f64 = 0.00001;\n\n\n\n let left_side = Point::new(5., 7.);\n\n let right_side = Point::new(8., 2.);\n\n\n\n let result = left_side + right_side;\n\n\n\n assert!((result.x - EXPECTED_RESULT.x).abs() < ERROR_MARGIN);\n\n assert!((result.y - EXPECTED_RESULT.y).abs() < ERROR_MARGIN);\n\n}\n", "file_path": "crates/utils/src/point.rs", "rank": 12, "score": 183041.11317790637 }, { "content": "#[test]\n\nfn test_distance() {\n\n const EXPECTED_RESULT: f64 = 9.48683;\n\n const ERROR_MARGIN: f64 = 0.00001;\n\n\n\n let point_positive = Point::new(1., 5.);\n\n let point_negative = Point::new(-2., -4.);\n\n\n\n assert!(((point_positive.distance(point_negative) - EXPECTED_RESULT).abs() < ERROR_MARGIN));\n\n assert!(((point_negative.distance(point_positive) - EXPECTED_RESULT).abs() < ERROR_MARGIN));\n\n}\n\n\n", "file_path": "crates/utils/src/point.rs", "rank": 13, "score": 183041.11317790637 }, { "content": "#[test]\n\nfn test_sub() {\n\n const EXPECTED_RESULT: Point = Point { x: -3., y: 5. };\n\n const ERROR_MARGIN: f64 = 0.00001;\n\n\n\n let left_side = Point::new(5., 7.);\n\n let right_side = Point::new(8., 2.);\n\n\n\n let result = left_side - right_side;\n\n\n\n assert!((result.x - EXPECTED_RESULT.x).abs() < ERROR_MARGIN);\n\n assert!((result.y - EXPECTED_RESULT.y).abs() < ERROR_MARGIN);\n\n}\n\n\n", "file_path": "crates/utils/src/point.rs", "rank": 14, "score": 183041.11317790637 }, { "content": "pub fn register_property<P: Component>(\n\n ctx: &mut BuildContext,\n\n key: &str,\n\n entity: Entity,\n\n property: P,\n\n) {\n\n ctx.register_property(key, entity, property);\n\n}\n", "file_path": "crates/api/src/widget_base/build_context.rs", "rank": 15, "score": 172233.05619219903 }, { "content": "/// Used to define an event.\n\npub trait Event: Any {\n\n fn strategy(&self) -> EventStrategy {\n\n EventStrategy::BottomUp\n\n }\n\n}\n\n\n\npub type EventHandlerMap = BTreeMap<Entity, Vec<Rc<dyn EventHandler>>>;\n\n\n\npub type TriggerHandler = dyn Fn(&mut StatesContext, Entity) + 'static;\n", "file_path": "crates/api/src/event/mod.rs", "rank": 16, "score": 168523.49444758162 }, { "content": "#[proc_macro_derive(IntoHandler)]\n\npub fn derive_into_handler(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n let ident = &input.ident;\n\n\n\n let gen = quote! {\n\n impl Into<Rc<dyn EventHandler>> for #ident {\n\n fn into(self) -> Rc<dyn EventHandler> {\n\n Rc::new(self)\n\n }\n\n }\n\n };\n\n\n\n TokenStream::from(gen)\n\n}\n\n\n", "file_path": "crates/proc-macros/src/lib.rs", "rank": 17, "score": 167398.70149960532 }, { "content": "#[proc_macro_derive(Event)]\n\npub fn derive_event(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n let ident = &input.ident;\n\n\n\n let gen = quote! {\n\n impl Event for #ident {}\n\n };\n\n\n\n TokenStream::from(gen)\n\n}\n\n\n", "file_path": "crates/proc-macros/src/lib.rs", "rank": 18, "score": 167089.09422278474 }, { "content": "// helper to request MainViewState\n\nfn state<'a>(id: Entity, states: &'a mut StatesContext) -> &'a mut MainViewState {\n\n states.get_mut(id)\n\n}\n", "file_path": "examples/widgets.rs", "rank": 19, "score": 163064.94003595976 }, { "content": "#[proc_macro_derive(WidgetCtx, attributes(property))]\n\npub fn derive_widget_ctx(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n let ident = &input.ident;\n\n\n\n let helper = ident.to_string().as_str().to_snake();\n\n let helper = syn::Ident::new(helper.as_str(), Span::call_site());\n\n\n\n let name = syn::Ident::new(format!(\"{}Ctx\", ident).as_str(), Span::call_site());\n\n let mut generated = vec![];\n\n\n\n if let syn::Data::Struct(DataStruct { ref fields, .. }) = input.data {\n\n let filter_fields = fields\n\n .iter()\n\n .filter(|f| f.attrs.iter().any(|attr| attr.path.is_ident(\"property\")));\n\n\n\n for field in filter_fields {\n\n let field_name = field\n\n .clone()\n\n .ident\n", "file_path": "crates/proc-macros/src/lib.rs", "rank": 20, "score": 162811.50258045108 }, { "content": "/// The `Widget` trait is used to define a new widget.\n\npub trait Widget: Template {\n\n /// Creates a new widget.\n\n fn new() -> Self;\n\n\n\n /// Creates a new widget.\n\n #[inline(always)]\n\n #[deprecated = \"Use new instead\"]\n\n fn create() -> Self {\n\n Self::new()\n\n }\n\n\n\n // This method will always be overwritten by the `widget!` macros.\n\n fn attach<P: Component + Debug>(self, _: AttachedProperty<P>) -> Self {\n\n self\n\n }\n\n\n\n /// Builds the widget and returns the template of the widget.\n\n fn build(self, ctx: &mut BuildContext) -> Entity;\n\n\n\n /// Inerts a new event handler.\n\n fn insert_handler(self, handler: impl Into<Rc<dyn EventHandler>>) -> Self;\n\n\n\n /// Appends a child to the widget.\n\n fn child(self, child: Entity) -> Self;\n\n}\n", "file_path": "crates/api/src/widget_base/mod.rs", "rank": 21, "score": 161096.43931327178 }, { "content": "/// Does nothing. This function is only use by the web backend.\n\npub fn initialize() {}\n\n\n\n/// Represents an application shell that could handle multiple windows.\n\npub struct Shell<A: 'static>\n\nwhere\n\n A: WindowAdapter,\n\n{\n\n window_shells: Vec<Window<A>>,\n\n requests: mpsc::Receiver<ShellRequest<A>>,\n\n}\n\n\n\nimpl<A> Shell<A>\n\nwhere\n\n A: WindowAdapter,\n\n{\n\n /// Creates a new application shell.\n\n pub fn new(requests: mpsc::Receiver<ShellRequest<A>>) -> Self {\n\n Shell {\n\n window_shells: vec![],\n\n requests,\n", "file_path": "crates/shell/src/minifb/mod.rs", "rank": 22, "score": 159638.14957931705 }, { "content": "/// Does nothing. self function is only use by the web backend.\n\npub fn initialize() {}\n\n\n\n/// Represents an application shell that could handle multiple windows.\n\npub struct Shell<A: 'static>\n\nwhere\n\n A: WindowAdapter,\n\n{\n\n window_shells: Vec<Window<A>>,\n\n requests: mpsc::Receiver<ShellRequest<A>>,\n\n event_loop: Vec<EventLoop<()>>,\n\n}\n\n\n\nimpl<A> Shell<A>\n\nwhere\n\n A: WindowAdapter,\n\n{\n\n /// Creates a new application shell.\n\n pub fn new(requests: mpsc::Receiver<ShellRequest<A>>) -> Self {\n\n Shell {\n\n window_shells: vec![],\n", "file_path": "crates/shell/src/glutin/mod.rs", "rank": 23, "score": 159638.08526053056 }, { "content": "/// Initializes web stuff.\n\npub fn initialize() {\n\n set_panic_hook();\n\n stdweb::initialize();\n\n}\n\n\n\n/// Represents an application shell that could handle multiple windows.\n\npub struct Shell<A: 'static>\n\nwhere\n\n A: WindowAdapter,\n\n{\n\n window_shells: Vec<Window<A>>,\n\n requests: mpsc::Receiver<ShellRequest<A>>,\n\n}\n\n\n\nimpl<A> Shell<A>\n\nwhere\n\n A: WindowAdapter,\n\n{\n\n /// Creates a new application shell.\n\n pub fn new(requests: mpsc::Receiver<ShellRequest<A>>) -> Self {\n", "file_path": "crates/shell/src/web/mod.rs", "rank": 24, "score": 159633.1838438528 }, { "content": "pub fn print_tree(\n\n entity: Entity,\n\n depth: usize,\n\n ecm: &mut EntityComponentManager<Tree, StringComponentStore>,\n\n) {\n\n let name = ecm.component_store().get::<String>(\"name\", entity).unwrap();\n\n\n\n let selector = if let Ok(selector) = ecm.component_store().get::<Selector>(\"selector\", entity) {\n\n selector.clone()\n\n } else {\n\n Selector::default()\n\n };\n\n\n\n crate::shell::CONSOLE.log(format!(\n\n \"{}{} (entity: {}{})\",\n\n \"| \".repeat(depth),\n\n name,\n\n entity.0,\n\n selector\n\n ));\n\n\n\n for child in ecm.entity_store().clone().children.get(&entity).unwrap() {\n\n print_tree(*child, depth + 1, ecm);\n\n }\n\n}\n", "file_path": "crates/api/src/systems/init_system.rs", "rank": 25, "score": 153777.48799156485 }, { "content": "/// Creates OrbTks default dark theme.\n\npub fn dark_theme() -> Theme {\n\n Theme::from_config(\n\n ThemeConfig::from(DARK_THEME_RON)\n\n .extend(ThemeConfig::from(COLORS_RON))\n\n .extend(ThemeConfig::from(FONTS_RON)),\n\n )\n\n}\n\n\n", "file_path": "crates/theme/src/lib.rs", "rank": 26, "score": 151878.51027095976 }, { "content": "/// Creates OrbTks default light theme.\n\npub fn light_theme() -> Theme {\n\n Theme::from_config(\n\n ThemeConfig::from(LIGHT_THEME_RON)\n\n .extend(ThemeConfig::from(COLORS_RON))\n\n .extend(ThemeConfig::from(FONTS_RON)),\n\n )\n\n}\n", "file_path": "crates/theme/src/lib.rs", "rank": 27, "score": 151878.51027095976 }, { "content": "fn default_or(key: &str, default_value: f64, ctx: &mut Context) -> Decimal {\n\n let property = ctx.widget().clone_or_default(key);\n\n\n\n match Decimal::from_f64(property) {\n\n Some(val) => val,\n\n None => Decimal::from_f64(default_value).unwrap(),\n\n }\n\n}\n\n\n\nimpl State for NumericBoxState {\n\n fn init(&mut self, _: &mut Registry, ctx: &mut Context) {\n\n self.input = ctx.entity_of_child(ID_INPUT).expect(\n\n \"NumericBoxState\n\n .init(): the child input could not be found!\",\n\n );\n\n self.min = default_or(\"min\", 0.0, ctx);\n\n self.max = default_or(\"max\", MAX, ctx);\n\n self.step = default_or(\"step\", 1.0, ctx);\n\n self.current_value = default_or(\"val\", 0.0, ctx);\n\n\n", "file_path": "crates/widgets/src/numeric_box.rs", "rank": 28, "score": 151623.29313020213 }, { "content": "fn change_button_title(title: &str, ctx: &mut Context) {\n\n let btn = ctx.entity_of_child(BTN_ID).unwrap();\n\n ctx.get_widget(btn)\n\n .set::<String16>(\"text\", String16::from(title));\n\n}\n\n\n\nwidget!(MainView<MainViewState>);\n\n\n\nimpl Template for MainView {\n\n fn template(self, id: Entity, bc: &mut BuildContext) -> Self {\n\n self.name(\"MainView\").margin(16.0).child(\n\n Stack::new()\n\n .id(STACK_ID)\n\n .h_align(\"center\")\n\n .spacing(16.0)\n\n .child(\n\n Button::new()\n\n .id(BTN_ID)\n\n .v_align(\"top\")\n\n .h_align(\"center\")\n", "file_path": "examples/popup.rs", "rank": 29, "score": 149187.50692782123 }, { "content": "fn component<C: Component + Clone>(\n\n ecm: &mut EntityComponentManager<Tree, StringComponentStore>,\n\n entity: Entity,\n\n component: &str,\n\n) -> C {\n\n ecm.component_store()\n\n .get::<C>(component, entity)\n\n .unwrap()\n\n .clone()\n\n}\n\n\n", "file_path": "crates/api/src/layout/mod.rs", "rank": 30, "score": 146360.61767895066 }, { "content": "/// Returns the value of a property of a widget if it exists otherwise the given value.\n\npub fn get_property_or_value<T>(\n\n key: &str,\n\n entity: Entity,\n\n store: &StringComponentStore,\n\n value: T,\n\n) -> T\n\nwhere\n\n T: Clone + Component,\n\n{\n\n if let Ok(property) = store.get::<T>(key, entity).map(|r| r.clone()) {\n\n return property;\n\n }\n\n value\n\n}\n\n\n\n/// Use to build a property or to share it.\n\n#[derive(PartialEq, Debug)]\n\npub enum PropertySource<P: Component + Debug> {\n\n Source(Entity),\n\n KeySource(String, Entity),\n\n Value(P),\n\n}\n\n\n\nimpl<P: Component + Debug> From<Entity> for PropertySource<P> {\n\n fn from(entity: Entity) -> Self {\n\n PropertySource::Source(entity)\n\n }\n\n}\n\n\n", "file_path": "crates/api/src/properties/mod.rs", "rank": 31, "score": 146337.2667735839 }, { "content": "fn offset(size: f64, child_size: f64, current_offset: f64, delta: f64) -> f64 {\n\n (current_offset + delta).min(0.).max(size - child_size)\n\n}\n\n\n\n// --- Helpers --\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_offset() {\n\n let width = 100.;\n\n let child_width = 200.0;\n\n\n\n assert_eq!(offset(width, child_width, 0., -10.), -10.);\n\n assert_eq!(offset(width, child_width, 0., -200.), -100.);\n\n assert_eq!(offset(width, child_width, 0., 200.), 0.);\n\n }\n\n}\n", "file_path": "crates/widgets/src/scroll_viewer.rs", "rank": 32, "score": 144810.93906220177 }, { "content": "fn try_component<C: Component + Clone>(\n\n ecm: &mut EntityComponentManager<Tree, StringComponentStore>,\n\n entity: Entity,\n\n component: &str,\n\n) -> Option<C> {\n\n if let Ok(c) = ecm.component_store().get::<C>(component, entity) {\n\n return Some(c.clone());\n\n }\n\n\n\n None\n\n}\n\n\n", "file_path": "crates/api/src/layout/mod.rs", "rank": 33, "score": 143654.4480163607 }, { "content": "fn create_header(ctx: &mut BuildContext, text: &str) -> Entity {\n\n TextBlock::new().text(text).style(\"header\").build(ctx)\n\n}\n\n\n", "file_path": "examples/widgets.rs", "rank": 34, "score": 142267.7095974832 }, { "content": "#[derive(Default, AsAny)]\n\nstruct WindowState {\n\n actions: VecDeque<Action>,\n\n background: Brush,\n\n title: String,\n\n}\n\n\n\nimpl WindowState {\n\n fn push_action(&mut self, action: Action) {\n\n self.actions.push_front(action);\n\n }\n\n\n\n fn resize(&self, width: f64, height: f64, ctx: &mut Context) {\n\n window(ctx.widget()).bounds_mut().set_size(width, height);\n\n window(ctx.widget())\n\n .constraint_mut()\n\n .set_size(width, height);\n\n }\n\n\n\n fn active_changed(&self, active: bool, ctx: &mut Context) {\n\n window(ctx.widget()).set_active(active);\n", "file_path": "crates/widgets/src/window.rs", "rank": 35, "score": 142056.32496348253 }, { "content": "/// Finds th parent of the `target_child`. The parent of the `target_child` must be the given `parent` or\n\n/// a child of the given parent.\n\npub fn find_parent(tree: &Tree, target_child: Entity, parent: Entity) -> Option<Entity> {\n\n if tree.children[&parent].contains(&target_child) {\n\n return Some(parent);\n\n }\n\n\n\n for child in &tree.children[&parent] {\n\n let parent = find_parent(tree, target_child, *child);\n\n if parent.is_some() {\n\n return parent;\n\n }\n\n }\n\n\n\n return None;\n\n}\n\n\n", "file_path": "crates/api/src/widget_base/context.rs", "rank": 36, "score": 141424.78251610708 }, { "content": "// internal type to handle dirty widgets.\n\ntype DirtyWidgets = Vec<Entity>;\n\n\n", "file_path": "crates/widgets/src/window.rs", "rank": 37, "score": 141397.7472881275 }, { "content": "fn is_single_tasks(task: &RenderTask) -> bool {\n\n match task {\n\n RenderTask::Start() => true,\n\n RenderTask::SetBackground(_) => true,\n\n RenderTask::Resize { .. } => true,\n\n RenderTask::RegisterFont { .. } => true,\n\n RenderTask::DrawRenderTarget { .. } => true,\n\n RenderTask::DrawImage { .. } => true,\n\n RenderTask::DrawImageWithClip { .. } => true,\n\n RenderTask::DrawPipeline { .. } => true,\n\n RenderTask::SetTransform { .. } => true,\n\n RenderTask::Terminate { .. } => true,\n\n _ => false,\n\n }\n\n}\n\n\n\nimpl RenderWorker {\n\n fn new(\n\n width: f64,\n\n height: f64,\n", "file_path": "crates/render/src/concurrent/mod.rs", "rank": 38, "score": 141115.74025521474 }, { "content": "// todo: documentation\n\npub trait Spacer {\n\n /// Gets left.\n\n fn left(&self) -> f64;\n\n\n\n /// Sets left.\n\n fn set_left(&mut self, left: f64);\n\n\n\n /// Gets top.\n\n fn top(&self) -> f64;\n\n\n\n /// Sets top.\n\n fn set_top(&mut self, top: f64);\n\n\n\n /// Gets right.\n\n fn right(&self) -> f64;\n\n\n\n /// Sets right.\n\n fn set_right(&mut self, right: f64);\n\n\n\n /// Gets bottom.\n", "file_path": "crates/utils/src/spacer.rs", "rank": 39, "score": 139246.69313510007 }, { "content": "/// Contains a set of getters and setters to read and write to a border.\n\npub trait Bordered {\n\n /// Gets the thickness.\n\n fn border_thickness(&self) -> Thickness;\n\n\n\n /// Sets the border thickness.\n\n fn set_border_thickness(&mut self, thickness: Thickness);\n\n\n\n /// Gets the border brush.\n\n fn border_brush(&self) -> &Brush;\n\n\n\n /// Sets the border brush.\n\n fn set_border_brush(&mut self, brush: Brush);\n\n\n\n /// Gets the border radius.\n\n fn border_radius(&self) -> f64;\n\n\n\n /// Sets the border radius.\n\n fn set_border_radius(&mut self, radius: f64);\n\n\n\n /// Gets the complete border.\n", "file_path": "crates/utils/src/border.rs", "rank": 40, "score": 139246.69313510007 }, { "content": "#[derive(Default, AsAny)]\n\nstruct BarState {\n\n indicator: Entity,\n\n}\n\n\n\nimpl State for BarState {\n\n fn init(&mut self, registry: &mut Registry, ctx: &mut Context) {\n\n self.indicator = ctx\n\n .entity_of_child(ID_INDICATOR)\n\n .expect(\"BarState.init(): Child could not be found!\");\n\n self.update_post_layout(registry, ctx);\n\n }\n\n\n\n fn update_post_layout(&mut self, _: &mut Registry, ctx: &mut Context) {\n\n let val = ctx.widget().clone_or_default::<f64>(\"val\");\n\n let max_width = ctx.widget().get::<Rectangle>(\"bounds\").width()\n\n - ctx.widget().get::<Thickness>(\"padding\").left()\n\n - ctx.widget().get::<Thickness>(\"padding\").right();\n\n let new_width = calculate_width(val, max_width);\n\n\n\n ctx.get_widget(self.indicator)\n\n .get_mut::<Constraint>(\"constraint\")\n\n .set_width(new_width);\n\n }\n\n}\n\n\n", "file_path": "crates/widgets/src/progress_bar.rs", "rank": 41, "score": 138918.22836029954 }, { "content": "fn component_or_default<C: Component + Clone + Default>(\n\n ecm: &mut EntityComponentManager<Tree, StringComponentStore>,\n\n entity: Entity,\n\n component: &str,\n\n) -> C {\n\n ecm.component_store()\n\n .get::<C>(component, entity)\n\n .map(Clone::clone)\n\n .unwrap_or_default()\n\n}\n\n\n", "file_path": "crates/api/src/layout/mod.rs", "rank": 42, "score": 137732.2666860744 }, { "content": "fn calculate_thumb_x_from_val(\n\n val: f64,\n\n min: f64,\n\n max: f64,\n\n track_width: f64,\n\n thumb_width: f64,\n\n) -> f64 {\n\n (val / (max - min)) * (track_width - thumb_width)\n\n}\n\n\n\n// --- Helpers --\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_calculate_thumb_x() {\n\n assert_eq!(0.0, calculate_thumb_x(-1000.0, 32.0, 0.0, 100.0));\n\n assert_eq!(0.0, calculate_thumb_x(0.0, 32.0, 0.0, 100.0));\n", "file_path": "crates/widgets/src/slider.rs", "rank": 43, "score": 135728.17278768827 }, { "content": "#[proc_macro_derive(AsAny)]\n\npub fn derive_as_any(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n let ident = &input.ident;\n\n\n\n let gen = quote! {\n\n impl AsAny for #ident {\n\n fn as_any(&self) -> &dyn Any {\n\n self\n\n }\n\n\n\n fn as_any_mut(&mut self) -> &mut dyn Any {\n\n self\n\n }\n\n }\n\n };\n\n\n\n TokenStream::from(gen)\n\n}\n\n\n", "file_path": "crates/proc-macros/src/lib.rs", "rank": 44, "score": 134154.58006490688 }, { "content": "pub trait AsAny: Any {\n\n fn as_any(&self) -> &dyn Any;\n\n\n\n fn as_any_mut(&mut self) -> &mut dyn Any;\n\n}\n\n\n\n/// Used to define a state of a [`widget`].\n\n/// \n\n/// The state holds the logic of a widget which makes it interactive.\n\n/// The state of a widget is made of a struct which implements this trait with its fields and its methods.\n\n/// A state of a widget is represented by the current values of its properties.\n\n/// Each state has to implement this trait.\n\n/// Each state has to derive or implement the [Default](https://doc.rust-lang.org/std/default/trait.Default.html) and the [`AsAny`] traits.\n\n/// A state is operating on the properties (components) of the widget, its parent or children, or the state's fields.\n\n/// It is not mandatory to have a state for a widget (in this case it will be static).\n\n/// \n\n/// # Example\n\n/// ```\n\n/// use orbtk::prelude::*;\n\n/// \n", "file_path": "crates/api/src/widget_base/state.rs", "rank": 45, "score": 132160.8514412645 }, { "content": "#[proc_macro_derive(Pipeline)]\n\npub fn derive_pipeline(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n let ident = &input.ident;\n\n\n\n let gen = quote! {\n\n impl PipelineTrait for #ident {\n\n fn box_eq(&self, other: &dyn Any) -> bool {\n\n other.downcast_ref::<Self>().map_or(false, |a| self == a)\n\n }\n\n fn as_any(&self) -> &dyn Any {\n\n self\n\n }\n\n fn clone_box(&self) -> Box<dyn PipelineTrait> {\n\n Box::new(self.clone())\n\n }\n\n }\n\n };\n\n\n\n TokenStream::from(gen)\n\n}\n\n\n", "file_path": "crates/proc-macros/src/lib.rs", "rank": 46, "score": 131829.32472378414 }, { "content": "fn calculate_thumb_x(mouse_x: f64, thumb_width: f64, slider_x: f64, track_width: f64) -> f64 {\n\n (mouse_x - slider_x - thumb_width)\n\n .max(0.0)\n\n .min(track_width - thumb_width)\n\n}\n\n\n", "file_path": "crates/widgets/src/slider.rs", "rank": 47, "score": 130571.8139724661 }, { "content": "#[derive(Clone, PartialEq)]\n\nstruct EmptyRenderPipeline;\n\n\n\nimpl render::PipelineTrait for EmptyRenderPipeline {\n\n fn box_eq(&self, other: &dyn Any) -> bool {\n\n other.downcast_ref::<Self>().map_or(false, |a| self == a)\n\n }\n\n fn as_any(&self) -> &dyn Any {\n\n self\n\n }\n\n\n\n fn clone_box(&self) -> Box<dyn render::PipelineTrait> {\n\n Box::new(self.clone())\n\n }\n\n}\n\n\n\nimpl render::RenderPipeline for EmptyRenderPipeline {\n\n fn draw(&self, _: &mut render::RenderTarget) {}\n\n}\n\n\n\n/// RenderPipeline object.\n", "file_path": "crates/api/src/properties/widget/render_pipeline.rs", "rank": 48, "score": 130475.86851481911 }, { "content": "pub trait State: AsAny {\n\n /// Init is used for setting up the initial state of a widget, setting up fields to starting values and registering service(s).\n\n /// It is called after the widget is created.\n\n /// \n\n /// # Arguments\n\n /// * `_registry`: Provides access to the global Service Registry.\n\n /// * `_ctx`: Represents the context of the current widget.Lets you manipulate the widget tree.\n\n fn init(&mut self, _registry: &mut Registry, _ctx: &mut Context) {}\n\n\n\n /// Used to cleanup the state and is called after window close is requested.\n\n /// # Arguments\n\n /// * `_registry`: Provides access to the global Service Registry.\n\n /// * `_ctx`: Represents the context of the current widget.Allows manipulation of the widget tree.\n\n fn cleanup(&mut self, _registry: &mut Registry, _ctx: &mut Context) {}\n\n\n\n /// Updates the state of a widget **before layout is calculated** for the given context when the widget becomes \"dirty\",\n\n /// (e.g.: a property of a widget is changed or an [`event`] is fired)\n\n /// \n\n /// # Arguments\n\n /// * `_registry`: Provides access to the global Service Registry.\n", "file_path": "crates/api/src/widget_base/state.rs", "rank": 49, "score": 129195.82004637795 }, { "content": "// helper to request MainViewState\n\nfn state<'a>(id: Entity, states: &'a mut StatesContext) -> &'a mut MainViewState {\n\n states.get_mut(id)\n\n}\n", "file_path": "examples/settings.rs", "rank": 50, "score": 129079.31442929074 }, { "content": "// helper to request MainViewState\n\nfn state<'a>(id: Entity, states: &'a mut StatesContext) -> &'a mut MainViewState {\n\n states.get_mut(id)\n\n}\n", "file_path": "examples/calculator.rs", "rank": 51, "score": 129079.31442929074 }, { "content": "type SelectedItem = Option<Entity>;\n\n\n", "file_path": "crates/widgets/src/combo_box.rs", "rank": 52, "score": 127725.07520876479 }, { "content": "/// The `Template` trait defines the template of a particular type of a widget.\n\n/// \n\n/// A widget's `Template` consists three type of objects:\n\n/// * default values of its properties, children, handlers\n\n/// * a render object\n\n/// * a layout object\n\npub trait Template: Sized {\n\n /// Builds the template of the widget and returns it.\n\n /// \n\n /// # Arguments\n\n /// * `_id`: The id (Entity) of the instantiated widget in the Entity Store\n\n /// * `_context`: The BuildContext used to build and instantiate new widgets\n\n /// \n\n /// # Example\n\n /// Define a widget called MyWidget with min, max and val properties with type of usize,\n\n /// and then set default values and add a TextBlock child.\n\n /// \n\n /// ```\n\n /// widget!(MyWidget {\n\n /// min: usize,\n\n /// max: usize,\n\n /// val: usize\n\n /// });\n\n /// \n\n /// impl Template for MyWidget {\n\n /// fn template(self, _id: Entity, context: &mut BuildContext) -> Self {\n", "file_path": "crates/api/src/widget_base/template.rs", "rank": 53, "score": 126401.6130760278 }, { "content": "use crate::{event::EventBox, widget_base::StatesContext};\n\n\n\n/// This trait is used to define an event handler.\n", "file_path": "crates/api/src/event/event_handler.rs", "rank": 54, "score": 125188.16734149113 }, { "content": "fn component_try_mut<'a, C: Component>(\n\n ecm: &'a mut EntityComponentManager<Tree, StringComponentStore>,\n\n entity: Entity,\n\n component: &str,\n\n) -> Option<&'a mut C> {\n\n ecm.component_store_mut()\n\n .get_mut::<C>(component, entity)\n\n .ok()\n\n}\n", "file_path": "crates/api/src/layout/mod.rs", "rank": 55, "score": 121948.09089011107 }, { "content": "use core::ops::{Add, Sub};\n\n\n\n// todo: documentation\n\n#[derive(Copy, Clone, Default, Debug, PartialEq)]\n\npub struct Point {\n\n x: f64,\n\n y: f64,\n\n}\n\n\n\nimpl Point {\n\n pub fn new(x: f64, y: f64) -> Self {\n\n Point { x, y }\n\n }\n\n\n\n /// Returns the distance between this `Point` and the given `Point`.\n\n pub fn distance(&self, other: Self) -> f64 {\n\n ((self.x - other.x).powf(2.) + (self.y - other.y).powf(2.)).sqrt()\n\n }\n\n\n\n pub fn x(&self) -> f64 {\n", "file_path": "crates/utils/src/point.rs", "rank": 56, "score": 121296.89967554496 }, { "content": " self.x\n\n }\n\n\n\n pub fn y(&self) -> f64 {\n\n self.y\n\n }\n\n\n\n pub fn set_x(&mut self, x: impl Into<f64>) {\n\n self.x = x.into();\n\n }\n\n\n\n pub fn set_y(&mut self, y: impl Into<f64>) {\n\n self.y = y.into();\n\n }\n\n}\n\n\n\nimpl Sub for Point {\n\n type Output = Self;\n\n\n\n fn sub(self, other: Self) -> Self {\n", "file_path": "crates/utils/src/point.rs", "rank": 57, "score": 121288.69330939413 }, { "content": " Point::new(t, t)\n\n }\n\n}\n\n\n\nimpl From<i32> for Point {\n\n fn from(t: i32) -> Self {\n\n Point::new(t as f64, t as f64)\n\n }\n\n}\n\n\n\nimpl From<(f64, f64)> for Point {\n\n fn from(t: (f64, f64)) -> Self {\n\n Point::new(t.0, t.1)\n\n }\n\n}\n\n\n\nimpl From<(i32, i32)> for Point {\n\n fn from(s: (i32, i32)) -> Point {\n\n Point::from((s.0 as f64, s.1 as f64))\n\n }\n\n}\n\n\n\n#[test]\n", "file_path": "crates/utils/src/point.rs", "rank": 58, "score": 121280.21954825567 }, { "content": " Self {\n\n x: self.x - other.x,\n\n y: self.y - other.y,\n\n }\n\n }\n\n}\n\n\n\nimpl Add for Point {\n\n type Output = Self;\n\n\n\n fn add(self, other: Self) -> Self {\n\n Self {\n\n x: self.x + other.x,\n\n y: self.y + other.y,\n\n }\n\n }\n\n}\n\n\n\nimpl From<f64> for Point {\n\n fn from(t: f64) -> Self {\n", "file_path": "crates/utils/src/point.rs", "rank": 59, "score": 121279.33805777036 }, { "content": "pub use crate::*;\n", "file_path": "crates/utils/src/prelude.rs", "rank": 60, "score": 121278.93378370951 }, { "content": "pub use std::{\n\n any::{Any, TypeId},\n\n cell::RefCell,\n\n collections::{HashMap, HashSet},\n\n fmt::Debug,\n\n rc::Rc,\n\n};\n\n\n\npub use crate::*;\n", "file_path": "crates/widgets/src/prelude.rs", "rank": 61, "score": 119691.87756342701 }, { "content": "use super::behaviors::MouseBehavior;\n\n\n\nuse crate::{api::prelude::*, prelude::*, proc_macros::*, theme::prelude::*};\n\n\n\nwidget!(\n\n /// The `Button` widget can be clicked by user. It's used to perform an action.\n\n ///\n\n /// **style:** `button`\n\n Button: MouseHandler {\n\n /// Sets or shares the background property.\n\n background: Brush,\n\n\n\n /// Sets or shares the border radius property.\n\n border_radius: f64,\n\n\n\n /// Sets or shares the border thickness property.\n\n border_width: Thickness,\n\n\n\n /// Sets or shares the border brush property.\n\n border_brush: Brush,\n", "file_path": "crates/widgets/src/button.rs", "rank": 62, "score": 119664.01931806581 }, { "content": " icon_brush: Brush,\n\n\n\n /// Sets or share the icon font size property.\n\n icon_size: f64,\n\n\n\n /// Sets or shares the icon font property.\n\n icon_font: String,\n\n\n\n /// Sets or shares the pressed property.\n\n pressed: bool,\n\n\n\n /// Sets or shares the spacing between icon and text.\n\n spacing: f64\n\n }\n\n);\n\n\n\nimpl Template for Button {\n\n fn template(self, id: Entity, ctx: &mut BuildContext) -> Self {\n\n self.name(\"Button\")\n\n .style(\"button\")\n", "file_path": "crates/widgets/src/button.rs", "rank": 63, "score": 119649.6783614966 }, { "content": " .enabled(id)\n\n .target(id.0)\n\n .child(\n\n Container::new()\n\n .background(id)\n\n .border_radius(id)\n\n .border_width(id)\n\n .border_brush(id)\n\n .padding(id)\n\n .opacity(id)\n\n .child(\n\n Stack::new()\n\n .orientation(\"horizontal\")\n\n .spacing(id)\n\n .h_align(\"center\")\n\n .child(\n\n FontIconBlock::new()\n\n .v_align(\"center\")\n\n .icon(id)\n\n .icon_brush(id)\n", "file_path": "crates/widgets/src/button.rs", "rank": 64, "score": 119638.62346562691 }, { "content": " .height(36.0)\n\n .min_width(64.0)\n\n .background(colors::LYNCH_COLOR)\n\n .border_radius(4.0)\n\n .border_width(0.0)\n\n .border_brush(\"transparent\")\n\n .padding((16.0, 0.0, 16.0, 0.0))\n\n .foreground(colors::LINK_WATER_COLOR)\n\n .text(\"\")\n\n .font_size(fonts::FONT_SIZE_12)\n\n .font(\"Roboto-Regular\")\n\n .icon(\"\")\n\n .icon_font(\"MaterialIcons-Regular\")\n\n .icon_size(fonts::ICON_FONT_SIZE_12)\n\n .icon_brush(colors::LINK_WATER_COLOR)\n\n .pressed(false)\n\n .spacing(8.0)\n\n .child(\n\n MouseBehavior::new()\n\n .pressed(id)\n", "file_path": "crates/widgets/src/button.rs", "rank": 65, "score": 119638.24346727894 }, { "content": " .icon_size(id)\n\n .icon_font(id)\n\n .opacity(id)\n\n .build(ctx),\n\n )\n\n .child(\n\n TextBlock::new()\n\n .v_align(\"center\")\n\n .foreground(id)\n\n .text(id)\n\n .font_size(id)\n\n .font(id)\n\n .opacity(id)\n\n .build(ctx),\n\n )\n\n .build(ctx),\n\n )\n\n .build(ctx),\n\n )\n\n .build(ctx),\n\n )\n\n }\n\n}\n", "file_path": "crates/widgets/src/button.rs", "rank": 66, "score": 119635.1992544191 }, { "content": "\n\n /// Sets or shares the padding property.\n\n padding: Thickness,\n\n\n\n /// Sets or shares the foreground property.\n\n foreground: Brush,\n\n\n\n /// Sets or shares the text property.\n\n text: String16,\n\n\n\n /// Sets or share the font size property.\n\n font_size: f64,\n\n\n\n /// Sets or shares the font property.\n\n font: String,\n\n\n\n /// Sets or shares the icon property.\n\n icon: String,\n\n\n\n /// Sets or shares the icon brush property.\n", "file_path": "crates/widgets/src/button.rs", "rank": 67, "score": 119635.1992544191 }, { "content": "fn main() {\n\n // use this only if you want to run it as web application.\n\n orbtk::initialize();\n\n\n\n Application::new()\n\n .window(|ctx| {\n\n Window::new()\n\n .title(\"OrbTk - widgets example\")\n\n .position((100, 100))\n\n .size(468, 730)\n\n .resizeable(true)\n\n .child(MainView::new().build(ctx))\n\n .build(ctx)\n\n })\n\n .run();\n\n}\n\n\n", "file_path": "examples/widgets.rs", "rank": 81, "score": 117316.00829239632 }, { "content": "use super::behaviors::{MouseBehavior, SelectionBehavior};\n\n\n\nuse crate::{api::prelude::*, prelude::*, proc_macros::*, theme::prelude::*};\n\n\n\nwidget!(\n\n /// The `ToggleButton` widget can be clicked by user and could switch between selected / not selected.\n\n /// It's used to perform an action.\n\n ///\n\n /// **style:** `toggle-button`\n\n ToggleButton: MouseHandler {\n\n /// Sets or shares the background property.\n\n background: Brush,\n\n\n\n /// Sets or shares the border radius property.\n\n border_radius: f64,\n\n\n\n /// Sets or shares the border thickness property.\n\n border_width: Thickness,\n\n\n\n /// Sets or shares the border brush property.\n", "file_path": "crates/widgets/src/toggle_button.rs", "rank": 82, "score": 116139.30576732542 }, { "content": "impl Template for ToggleButton {\n\n fn template(self, id: Entity, ctx: &mut BuildContext) -> Self {\n\n self.name(\"ToggleButton\")\n\n .style(\"button\")\n\n .selected(false)\n\n .height(36.0)\n\n .min_width(64.0)\n\n .background(colors::LYNCH_COLOR)\n\n .border_radius(4.0)\n\n .border_width(0.0)\n\n .border_brush(\"transparent\")\n\n .padding((16.0, 0.0, 16.0, 0.0))\n\n .foreground(colors::LINK_WATER_COLOR)\n\n .text(\"\")\n\n .font_size(fonts::FONT_SIZE_12)\n\n .font(\"Roboto-Regular\")\n\n .icon(\"\")\n\n .icon_font(\"MaterialIcons-Regular\")\n\n .icon_size(fonts::ICON_FONT_SIZE_12)\n\n .icon_brush(colors::LINK_WATER_COLOR)\n", "file_path": "crates/widgets/src/toggle_button.rs", "rank": 83, "score": 116121.29396546964 }, { "content": " .pressed(false)\n\n .spacing(8.0)\n\n .child(\n\n MouseBehavior::new()\n\n .pressed(id)\n\n .enabled(id)\n\n .target(id.0)\n\n .child(\n\n SelectionBehavior::new()\n\n .selected(id)\n\n .enabled(id)\n\n .target(id.0)\n\n .child(\n\n Container::new()\n\n .background(id)\n\n .border_radius(id)\n\n .border_width(id)\n\n .border_brush(id)\n\n .padding(id)\n\n .child(\n", "file_path": "crates/widgets/src/toggle_button.rs", "rank": 84, "score": 116119.42125591464 }, { "content": " /// Sets or shares the icon brush property.\n\n icon_brush: Brush,\n\n\n\n /// Sets or shares the icon font size property.\n\n icon_size: f64,\n\n\n\n /// Sets or shares the icon font property.\n\n icon_font: String,\n\n\n\n /// Sets or shares the pressed property.\n\n pressed: bool,\n\n\n\n /// Sets or shares the selected property.\n\n selected: bool,\n\n\n\n /// Sets or shares the spacing between icon and text.\n\n spacing: f64\n\n }\n\n);\n\n\n", "file_path": "crates/widgets/src/toggle_button.rs", "rank": 85, "score": 116115.76143926715 }, { "content": " Stack::new()\n\n .orientation(\"horizontal\")\n\n .spacing(id)\n\n .v_align(\"center\")\n\n .h_align(\"center\")\n\n .child(\n\n FontIconBlock::new()\n\n .v_align(\"center\")\n\n .icon(id)\n\n .icon_brush(id)\n\n .icon_size(id)\n\n .icon_font(id)\n\n .build(ctx),\n\n )\n\n .child(\n\n TextBlock::new()\n\n .v_align(\"center\")\n\n .foreground(id)\n\n .text(id)\n\n .font_size(id)\n", "file_path": "crates/widgets/src/toggle_button.rs", "rank": 86, "score": 116111.22683404083 }, { "content": " .font(id)\n\n .build(ctx),\n\n )\n\n .build(ctx),\n\n )\n\n .build(ctx),\n\n )\n\n .build(ctx),\n\n )\n\n .build(ctx),\n\n )\n\n }\n\n}\n", "file_path": "crates/widgets/src/toggle_button.rs", "rank": 87, "score": 116111.22683404083 }, { "content": " border_brush: Brush,\n\n\n\n /// Sets or shares the padding property.\n\n padding: Thickness,\n\n\n\n /// Sets or shares the foreground property.\n\n foreground: Brush,\n\n\n\n /// Sets or shares the text property.\n\n text: String16,\n\n\n\n /// Sets or shares the font size property.\n\n font_size: f64,\n\n\n\n /// Sets or shares the font property.\n\n font: String,\n\n\n\n /// Sets or shares the icon property.\n\n icon: String,\n\n\n", "file_path": "crates/widgets/src/toggle_button.rs", "rank": 88, "score": 116111.22683404083 }, { "content": "fn adjust_max(min: f64, max: f64) -> f64 {\n\n if max < min {\n\n return min;\n\n }\n\n\n\n max\n\n}\n\n\n", "file_path": "crates/widgets/src/slider.rs", "rank": 89, "score": 114819.04956190032 }, { "content": "fn adjust_min(min: f64, max: f64) -> f64 {\n\n if min > max {\n\n return max;\n\n }\n\n\n\n min\n\n}\n\n\n", "file_path": "crates/widgets/src/slider.rs", "rank": 90, "score": 114819.04956190032 }, { "content": "fn main() {\n\n Application::new()\n\n .window(|ctx| {\n\n Window::new()\n\n .title(\"OrbTk - tab widget example\")\n\n .position((100.0, 100.0))\n\n .size(600.0, 500.0)\n\n .resizeable(true)\n\n .child(\n\n TabWidget::new()\n\n .tab(\n\n \"Tab header 1\",\n\n TextBlock::new().text(\"Tab content 1\").build(ctx),\n\n )\n\n .tab(\n\n \"Tab header 2\",\n\n TextBlock::new().text(\"Tab content 2\").build(ctx),\n\n )\n\n .tab(\n\n \"Tab header 3\",\n\n TextBlock::new().text(\"Tab content 3\").build(ctx),\n\n )\n\n .build(ctx),\n\n )\n\n .build(ctx)\n\n })\n\n .run();\n\n}\n", "file_path": "examples/tab_widget.rs", "rank": 91, "score": 114554.32134762785 }, { "content": "fn generate_operation_button(\n\n ctx: &mut BuildContext,\n\n id: Entity,\n\n sight: char,\n\n primary: bool,\n\n column: usize,\n\n column_span: usize,\n\n row: usize,\n\n) -> Entity {\n\n let style = if primary {\n\n \"button_calculator_primary\"\n\n } else {\n\n \"button_calculator\"\n\n };\n\n\n\n let button = Button::new()\n\n .style(style)\n\n .min_size(48.0, 48.0)\n\n .text(sight.to_string())\n\n .on_click(move |states, _| -> bool {\n", "file_path": "examples/calculator.rs", "rank": 92, "score": 113859.80988323793 }, { "content": "fn generate_digit_button(\n\n ctx: &mut BuildContext,\n\n id: Entity,\n\n sight: char,\n\n primary: bool,\n\n column: usize,\n\n column_span: usize,\n\n row: usize,\n\n) -> Entity {\n\n let style = if primary {\n\n \"button_calculator_primary\"\n\n } else {\n\n \"button_calculator\"\n\n };\n\n\n\n let button = Button::new()\n\n .style(style)\n\n .min_size(48.0, 48.0)\n\n .text(sight.to_string())\n\n .on_click(move |states, _| -> bool {\n\n state(id, states).action(Action::Digit(sight));\n\n true\n\n })\n\n .attach(Grid::column(column))\n\n .attach(Grid::row(row))\n\n .attach(Grid::column_span(column_span));\n\n\n\n button.build(ctx)\n\n}\n\n\n", "file_path": "examples/calculator.rs", "rank": 93, "score": 113859.80988323793 }, { "content": " self.action = None;\n\n }\n\n }\n\n\n\n fn update_post_layout(&mut self, _: &mut Registry, ctx: &mut Context) {\n\n if self.has_delta {\n\n mouse_behavior(ctx.widget()).set_delta(Point::default());\n\n self.has_delta = false;\n\n }\n\n }\n\n}\n\n\n\nwidget!(\n\n /// The `MouseBehavior` widget is used to handle internal the pressed behavior of a widget.\n\n ///\n\n /// **style:** `check-box`\n\n MouseBehavior<MouseBehaviorState>: MouseHandler {\n\n /// Sets or shares the target of the behavior.\n\n target: u32,\n\n\n", "file_path": "crates/widgets/src/behaviors/mouse_behavior.rs", "rank": 94, "score": 112788.02013156576 }, { "content": " toggle_flag(\"pressed\", &mut ctx.get_widget(target));\n\n\n\n if check_mouse_condition(p.position, &ctx.widget()) {\n\n let parent = ctx.entity_of_parent().unwrap();\n\n ctx.push_event_by_entity(\n\n ClickEvent {\n\n position: p.position,\n\n },\n\n parent,\n\n )\n\n }\n\n }\n\n Action::Scroll(p) => {\n\n mouse_behavior(ctx.widget()).set_position(p);\n\n self.has_delta = true;\n\n }\n\n };\n\n\n\n ctx.get_widget(target).update(false);\n\n\n", "file_path": "crates/widgets/src/behaviors/mouse_behavior.rs", "rank": 95, "score": 112783.97732472057 }, { "content": " /// Sets or shares the pressed property.\n\n pressed: bool,\n\n\n\n /// Sets or shares the (wheel, scroll) delta property.\n\n delta: Point\n\n }\n\n);\n\n\n\nimpl Template for MouseBehavior {\n\n fn template(self, id: Entity, _: &mut BuildContext) -> Self {\n\n self.name(\"MouseBehavior\")\n\n .delta(0.0)\n\n .pressed(false)\n\n .on_mouse_down(move |states, m| {\n\n states\n\n .get_mut::<MouseBehaviorState>(id)\n\n .action(Action::Press(m));\n\n false\n\n })\n\n .on_mouse_up(move |states, m| {\n", "file_path": "crates/widgets/src/behaviors/mouse_behavior.rs", "rank": 96, "score": 112782.07714409611 }, { "content": "use crate::{api::prelude::*, proc_macros::*};\n\n\n\n#[derive(Debug, Copy, Clone)]\n", "file_path": "crates/widgets/src/behaviors/mouse_behavior.rs", "rank": 97, "score": 112781.17713157876 }, { "content": " fn update(&mut self, _: &mut Registry, ctx: &mut Context) {\n\n if !mouse_behavior(ctx.widget()).enabled() {\n\n return;\n\n }\n\n\n\n if let Some(action) = self.action {\n\n let target: Entity = (*mouse_behavior(ctx.widget()).target()).into();\n\n\n\n match action {\n\n Action::Press(_) => {\n\n mouse_behavior(ctx.widget()).set_pressed(true);\n\n toggle_flag(\"pressed\", &mut ctx.get_widget(target));\n\n }\n\n Action::Release(p) => {\n\n if !*mouse_behavior(ctx.widget()).pressed() {\n\n self.action = None;\n\n return;\n\n }\n\n\n\n mouse_behavior(ctx.widget()).set_pressed(false);\n", "file_path": "crates/widgets/src/behaviors/mouse_behavior.rs", "rank": 98, "score": 112776.6655707155 }, { "content": " states\n\n .get_mut::<MouseBehaviorState>(id)\n\n .action(Action::Release(m));\n\n false\n\n })\n\n .on_scroll(move |states, p| {\n\n states\n\n .get_mut::<MouseBehaviorState>(id)\n\n .action(Action::Scroll(p));\n\n false\n\n })\n\n }\n\n}\n", "file_path": "crates/widgets/src/behaviors/mouse_behavior.rs", "rank": 99, "score": 112767.30993006052 } ]
Rust
day10/src/main.rs
jtempest/advent_of_code_2019-rs
d1da25c963428fe1d1cb8a26bf80cc777979c110
use aoc::geom::{Dimensions, Vector2D}; use std::collections::HashSet; use std::fmt; #[derive(Debug)] struct AsteroidField { asteroids: HashSet<Vector2D>, dimensions: Dimensions, } impl AsteroidField { fn new(input: &str) -> AsteroidField { let lines = input.trim().lines(); let dimensions = Dimensions { width: lines.clone().next().unwrap().len(), height: lines.clone().count(), }; let asteroids = lines .enumerate() .flat_map(|(y, li)| { assert_eq!(li.len(), dimensions.width); li.trim() .chars() .enumerate() .filter(|(_, c)| *c == '#') .map(move |(x, _)| Vector2D { x: x as i64, y: y as i64, }) }) .collect(); AsteroidField { asteroids, dimensions, } } fn find_best_monitoring_asteroid(&self) -> (Vector2D, usize) { self.asteroids .iter() .copied() .map(|a| (a, self.num_visible_asteroids(a))) .max_by(|a, b| a.1.cmp(&b.1)) .unwrap() } fn num_visible_asteroids(&self, pos: Vector2D) -> usize { self.asteroids .iter() .copied() .map(|t| t - pos) .filter(|offset| *offset != Vector2D::zero()) .map(clock_position) .collect::<HashSet<_>>() .len() } fn vaporisation_order(&self, station_pos: Vector2D) -> Vec<Vector2D> { assert!(self.asteroids.contains(&station_pos)); let mut offsets = self .asteroids .iter() .map(|a| *a - station_pos) .filter(|o| *o != Vector2D::zero()) .map(|o| (clock_position(o) as u32, o)) .collect::<Vec<_>>(); offsets.sort_by(|a, b| { a.0.cmp(&b.0) .then(a.1.manhattan_length().cmp(&b.1.manhattan_length())) }); const FULL_ROTATION: u32 = std::u16::MAX as u32; let mut all_angles = HashSet::new(); for (angle, _) in offsets.iter_mut() { while all_angles.contains(angle) { *angle += FULL_ROTATION; } all_angles.insert(*angle); } offsets.sort_by(|a, b| a.0.cmp(&b.0)); offsets.into_iter().map(|(_, o)| o + station_pos).collect() } } impl fmt::Display for AsteroidField { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for coord in self.dimensions.iter() { if coord.x == 0 { writeln!(f)?; } let is_roid = self.asteroids.contains(&coord); let c = if is_roid { '#' } else { '.' }; write!(f, "{}", c)?; } Ok(()) } } fn clock_position(offset: Vector2D) -> u16 { use std::f64::consts::PI; const TWO_PI: f64 = PI * 2.0; let angle = (-offset.x as f64).atan2(offset.y as f64); let dist = (angle + PI) / TWO_PI; ((dist * std::u16::MAX as f64) + 1.0) as u16 } fn day10() -> (usize, usize) { const DAY10_INPUT: &str = include_str!("day10_input.txt"); let field = AsteroidField::new(DAY10_INPUT); let best = field.find_best_monitoring_asteroid(); let part1 = best.1; let order = field.vaporisation_order(best.0); let target = order[199]; let part2 = ((target.x * 100) + target.y) as usize; (part1, part2) } fn main() { let (part1, part2) = day10(); println!("part1 = {}", part1); println!("part1 = {}", part2); } #[cfg(test)] mod test { use super::*; #[test] fn test_clock_position() { assert_eq!(clock_position(Vector2D { x: 0, y: -1 }), 0); assert_eq!(clock_position(Vector2D { x: 1, y: 0 }), 16384); assert_eq!(clock_position(Vector2D { x: 0, y: 1 }), 32768); assert_eq!(clock_position(Vector2D { x: -1, y: 0 }), 49152); let clockwise = [ Vector2D { x: 0, y: -1 }, Vector2D { x: 1, y: -1 }, Vector2D { x: 1, y: 0 }, Vector2D { x: 1, y: 1 }, Vector2D { x: 0, y: 1 }, Vector2D { x: -1, y: 1 }, Vector2D { x: -1, y: 0 }, Vector2D { x: -1, y: -1 }, ]; for i in 0..(clockwise.len() - 1) { assert!(clock_position(clockwise[i]) < clock_position(clockwise[i + 1])); } } const EXAMPLE_FIELDS: [&str; 5] = [ include_str!("day10_example1.txt"), include_str!("day10_example2.txt"), include_str!("day10_example3.txt"), include_str!("day10_example4.txt"), include_str!("day10_example5.txt"), ]; #[test] fn test_find_best_monitoring_asteroid() { check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[0], (Vector2D { x: 3, y: 4 }, 8)); check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[1], (Vector2D { x: 5, y: 8 }, 33)); check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[2], (Vector2D { x: 1, y: 2 }, 35)); check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[3], (Vector2D { x: 6, y: 3 }, 41)); check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[4], (Vector2D { x: 11, y: 13 }, 210)); } fn check_find_best_monitoring_asteroid(input: &str, expected: (Vector2D, usize)) { let best = AsteroidField::new(input).find_best_monitoring_asteroid(); assert_eq!(best, expected); } #[test] fn test_vaporisation_order() { let field = AsteroidField::new(EXAMPLE_FIELDS[4]); let pos = field.find_best_monitoring_asteroid().0; let order = field.vaporisation_order(pos); assert_eq!(order.len(), 299); assert_eq!(order[0], Vector2D { x: 11, y: 12 }); assert_eq!(order[1], Vector2D { x: 12, y: 1 }); assert_eq!(order[2], Vector2D { x: 12, y: 2 }); assert_eq!(order[9], Vector2D { x: 12, y: 8 }); assert_eq!(order[19], Vector2D { x: 16, y: 0 }); assert_eq!(order[49], Vector2D { x: 16, y: 9 }); assert_eq!(order[99], Vector2D { x: 10, y: 16 }); assert_eq!(order[198], Vector2D { x: 9, y: 6 }); assert_eq!(order[199], Vector2D { x: 8, y: 2 }); assert_eq!(order[200], Vector2D { x: 10, y: 9 }); assert_eq!(order[298], Vector2D { x: 11, y: 1 }); } #[test] fn test_day10() { let (part1, part2) = day10(); assert_eq!(part1, 292); assert_eq!(part2, 317); } }
use aoc::geom::{Dimensions, Vector2D}; use std::collections::HashSet; use std::fmt; #[derive(Debug)] struct AsteroidField { asteroids: HashSet<Vector2D>, dimensions: Dimensions, } impl AsteroidField { fn new(input: &str) -> AsteroidField { let lines = input.trim().lines(); let dimensions = Dimensions { width: lines.clone().next().unwrap().len(), height: lines.clone().count(), }; let asteroids = lines .enumerate() .flat_map(|(y, li)| { assert_eq!(li.len(), dimensions.width); li.trim() .chars() .enumerate() .filter(|(_, c)| *c == '#') .map(move |(x, _)| Vector2D { x: x as i64, y: y as i64, }) }) .collect(); AsteroidField { asteroids, dimensions, } } fn find_best_monitoring_asteroid(&self) -> (Vector2D, usize) { self.asteroids .iter() .copied() .map(|a| (a, self.num_visible_asteroids(a))) .max_by(|a, b| a.1.cmp(&b.1)) .unwrap() } fn num_visible_asteroids(&self, pos: Vector2D) -> usize { self.asteroids .iter() .copied() .map(|t| t - pos) .filter(|offset| *offset != Vector2D::zero()) .map(clock_position) .collect::<HashSet<_>>() .len() } fn vaporisation_order(&self, station_pos: Vector2D) -> Vec<Vector2D> { assert!(self.asteroids.contains(&station_pos)); let mut offsets = self .asteroids .iter() .map(|a| *a - station_pos) .filter(|o| *o != Vector2D::zero()) .map(|o| (clock_position(o) as u32, o)) .collect::<Vec<_>>(); offsets.sort_by(|a, b| { a.0.cmp(&b.0) .then(a.1.manhattan_length().cmp(&b.1.manhattan_length())) }); const FULL_ROTATION: u32 = std::u16::MAX as u32; let mut all_angles = HashSet::new(); for (angle, _) in offsets.iter_mut() { while all_angles.contains(angle) { *angle += FULL_ROTATION; } all_angles.insert(*angle); } offsets.sort_by(|a, b| a.0.cmp(&b.0)); offsets.into_iter().map(|(_, o)| o + station_pos).collect() } } impl fmt::Display for AsteroidField { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for coord in self.dimensions.iter() { if coord.x == 0 { writeln!(f)?; } let is_roid = self.asteroids.contains(&coord); let c = if is_roid { '#' } else { '.' }; write!(f, "{}", c)?; } Ok(()) } } fn clock_position(offset: Vector2D) -> u16 { use std::f64::consts::PI; const TWO_PI: f64 = PI * 2.0; let angle = (-offset.x as f64).atan2(offset.y as f64); let dist = (angle + PI) / TWO_PI; ((dist * std::u16::MAX as f64) + 1.0) as u16 } fn day10() -> (usize, usize) { const DAY10_INPUT: &str = include_str!("day10_input.txt"); let field = AsteroidField::new(DAY10_INPUT); let best = field.find_best_monitoring_asteroid(); let part1 = best.1; let order = field.vaporisation_order(best.0); let target = order[199]; let part2 = ((target.x * 100) + target.y) as usize; (part1, part2) } fn main() { let (part1, part2) = day10(); println!("part1 = {}", part1); println!("part1 = {}", part2); } #[cfg(test)] mod test { use super::*; #[test] fn test_clock_position() { assert_eq!(clock_position(Vector2D { x: 0, y: -1 }), 0); assert_eq!(clock_position(Vector2D { x: 1, y: 0 }), 16384); assert_eq!(clock_position(Vector2D { x: 0, y: 1 }), 32768); assert_eq!(clock_position(Vector2D { x: -1, y: 0 }), 49152); let clockwise = [ Vector2D { x: 0, y: -1 }, Vector2D { x: 1, y: -1 }, Vector2D { x: 1, y: 0 }, Vector2D { x: 1, y: 1 }, Vector2D { x: 0, y: 1 }, Vector2D { x: -1, y: 1 }, Vector2D { x: -1, y: 0 }, Vector2D { x: -1, y: -1 }, ]; for i in 0..(clockwise.len() - 1) { assert!(clock_position(clockwise[i]) < clock_position(clockwise[i + 1])); } } const EXAMPLE_FIELDS: [&str; 5] = [ include_str!("day10_example1.txt"), include_str!("day10_example2.txt"), include_str!("day10_example3.txt"), include_str!("day10_example4.txt"), include_str!("day10_example5.txt"), ]; #[test] fn test_find_best_monitoring_asteroid() { check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[0], (Vector2D { x: 3, y: 4 }, 8)); check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[1], (Vector2D { x: 5, y: 8 }, 33)); check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[2], (Vector2D { x: 1, y: 2 }, 35)); check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[3], (Vector2D { x: 6, y: 3 }, 41)); check_find_best_monitoring_asteroid(EXAMPLE_FIELDS[4], (Vector2D { x: 11, y: 13 }, 210)); } fn check_find_best_monitoring_asteroid(input: &str, expected: (Vector2D, usize)) { let best = AsteroidField::new(input).find_best_monitoring_asteroid(); assert_eq!(best, expected); } #[test] fn test_vaporisation_order() { let field = AsteroidField::new(EXAMPLE_FIELDS[4]); let pos = field.find_best_monitoring_asteroid().0; let order = field.vaporisation_order(pos); assert_eq!(order.len(), 299); assert_eq!(order[0], Vector2D { x: 11, y: 12 }); assert_eq!(order[1], Vector2D { x: 12, y: 1 }); assert_eq!(order[2], Vector2D { x: 12, y: 2 }); assert_eq!(order[9], Vector2D { x: 12, y: 8 }); assert_eq!(order[19], Vector2D { x: 16, y: 0 }); assert_eq!(order[49], Vector2D { x: 16, y: 9 });
#[test] fn test_day10() { let (part1, part2) = day10(); assert_eq!(part1, 292); assert_eq!(part2, 317); } }
assert_eq!(order[99], Vector2D { x: 10, y: 16 }); assert_eq!(order[198], Vector2D { x: 9, y: 6 }); assert_eq!(order[199], Vector2D { x: 8, y: 2 }); assert_eq!(order[200], Vector2D { x: 10, y: 9 }); assert_eq!(order[298], Vector2D { x: 11, y: 1 }); }
function_block-function_prefix_line
[ { "content": "fn max_signal<R: Iterator<Item = i64>, F: Fn(&mut Amplifier) -> i64>(\n\n program: &Program,\n\n settings: R,\n\n run_func: F,\n\n) -> i64 {\n\n let num_settings = settings.size_hint().1.unwrap();\n\n (settings)\n\n .permutations(num_settings)\n\n .fold(0, |max, settings| {\n\n cmp::max(max, run_func(&mut Amplifier::new(&program, &settings)))\n\n })\n\n}\n\n\n", "file_path": "day07/src/main.rs", "rank": 0, "score": 265232.74644383386 }, { "content": "pub fn cartograph<'a>(input: &'a str) -> impl Iterator<Item = (Vector2D, char)> + 'a {\n\n input.lines().enumerate().flat_map(|(y, line)| {\n\n line.chars().enumerate().map(move |(x, c)| {\n\n let x = x as i64;\n\n let y = y as i64;\n\n (Vector2D { x, y }, c)\n\n })\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn vector2d_add() {\n\n assert_eq!(\n\n Vector2D { x: 1, y: 2 } + Vector2D { x: -10, y: 15 },\n\n Vector2D { x: -9, y: 17 }\n\n );\n", "file_path": "aoc/src/geom/vector2d.rs", "rank": 2, "score": 248071.81544432827 }, { "content": "fn depths_iter(depth: i64) -> impl Iterator<Item = i64> {\n\n let (min, max) = (-depth, depth);\n\n min..=max\n\n}\n\n\n\nimpl fmt::Display for RecursiveGrid {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n for (n, grid) in self.depths().zip(self.grids.iter()) {\n\n writeln!(f, \"Depth {}\", n)?;\n\n writeln!(f, \"{}\", grid)?\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n const EXAMPLE: &str = include_str!(\"example.txt\");\n", "file_path": "day24/src/main.rs", "rank": 4, "score": 230525.7305188573 }, { "content": "fn run_program(program: &str) -> i64 {\n\n let mut machine = Machine::from_source(DAY21_INPUT);\n\n let _prompt = machine.run_as_ascii();\n\n program\n\n .lines()\n\n .filter(|line| !line.is_empty())\n\n .for_each(|line| machine.input_ascii(line));\n\n machine.run_as_iter().last().unwrap()\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_day21() {\n\n assert_eq!(day21_part1(), 19_362_259);\n\n assert_eq!(day21_part2(), 1_141_066_762);\n\n }\n\n}\n", "file_path": "day21/src/main.rs", "rank": 6, "score": 193282.09419355931 }, { "content": "fn read_tiles(input: &str) -> (HashSet<Vector2D>, HashMap<Vector2D, char>, Vector2D) {\n\n let mut tiles = HashSet::new();\n\n let mut portal_tiles = HashMap::new();\n\n let mut dimensions = Dimensions::new();\n\n for (pos, c) in geom::cartograph(input) {\n\n if c == '.' {\n\n tiles.insert(pos);\n\n } else if c.is_alphabetic() {\n\n portal_tiles.insert(pos, c);\n\n }\n\n dimensions.expand_to_fit(pos);\n\n }\n\n\n\n let centre = Vector2D {\n\n x: (dimensions.width / 2) as i64,\n\n y: (dimensions.height / 2) as i64,\n\n };\n\n\n\n (tiles, portal_tiles, centre)\n\n}\n\n\n", "file_path": "day20/src/main.rs", "rank": 7, "score": 182912.53523574132 }, { "content": "fn day05_part2() -> i64 {\n\n Machine::from_source_with_input(DAY05_INPUT, 5)\n\n .run()\n\n .unwrap()\n\n}\n\n\n", "file_path": "day05/src/main.rs", "rank": 8, "score": 181562.95003991207 }, { "content": "fn day23_part2() -> i64 {\n\n run_network(NetworkMode::Part2)\n\n}\n\n\n", "file_path": "day23/src/main.rs", "rank": 9, "score": 181562.95003991207 }, { "content": "fn day21_part2() -> i64 {\n\n run_program(PART2_PROGRAM)\n\n}\n\n\n", "file_path": "day21/src/main.rs", "rank": 10, "score": 181562.95003991207 }, { "content": "fn day02_part2() -> i64 {\n\n let target = 19_690_720;\n\n for n in 0..100 {\n\n for v in 0..100 {\n\n let out = run_machine(&DAY02_PROGRAM, n, v);\n\n if out == target {\n\n return (100 * n) + v;\n\n }\n\n }\n\n }\n\n panic!(\"Failed to find answer\");\n\n}\n\n\n", "file_path": "day02/src/main.rs", "rank": 11, "score": 181562.95003991207 }, { "content": "fn day17_part2() -> i64 {\n\n // These functions were produced by inspection, but I expect that the way\n\n // to produce them programmtically would be to:\n\n //\n\n // - Produce a single long route by traversing the scaffolds travelling as\n\n // far as possible each step.\n\n //\n\n // - Starting from the end, find the longest sequence which is repeated\n\n // elsewhere in the route and replace those instructions with the function\n\n // name. Repeat until you have three functions, assuming that they cover\n\n // the entire sequence.\n\n\n\n const MAIN_SEQUENCE: &str = \"A,B,A,B,C,C,B,C,B,A\";\n\n const FUNCTIONS: [&str; 3] = [\"R,12,L,8,R,12\", \"R,8,R,6,R,6,R,8\", \"R,8,L,8,R,8,R,4,R,4\"];\n\n\n\n let mut machine = Machine::from_source(DAY17_INPUT);\n\n machine.write(0, 2);\n\n\n\n input_sequence(&mut machine, MAIN_SEQUENCE);\n\n for f in &FUNCTIONS {\n\n input_sequence(&mut machine, f);\n\n }\n\n input_sequence(&mut machine, \"n\");\n\n\n\n machine.run_as_iter().last().unwrap()\n\n}\n\n\n", "file_path": "day17/src/main.rs", "rank": 12, "score": 181562.95003991207 }, { "content": "fn day13_part2() -> i64 {\n\n let mut cabinet = ArcadeCabinet::new();\n\n cabinet.play();\n\n cabinet.score()\n\n}\n\n\n\nconst DAY13_INPUT: &str = include_str!(\"day13_input.txt\");\n\n\n", "file_path": "day13/src/main.rs", "rank": 13, "score": 181562.95003991207 }, { "content": "fn day17_part1() -> i64 {\n\n let mut m = Machine::from_source(DAY17_INPUT);\n\n let output = m.run_as_ascii();\n\n let ascii = ASCIIOutput::new(&output);\n\n let intersections = ascii.find_intersections();\n\n intersections.iter().map(|p| p.x * p.y).sum()\n\n}\n\n\n", "file_path": "day17/src/main.rs", "rank": 14, "score": 181546.49923973824 }, { "content": "fn day02_part1() -> i64 {\n\n run_machine(&DAY02_PROGRAM, 12, 2)\n\n}\n\n\n", "file_path": "day02/src/main.rs", "rank": 15, "score": 181546.49923973824 }, { "content": "fn day21_part1() -> i64 {\n\n run_program(PART1_PROGRAM)\n\n}\n\n\n", "file_path": "day21/src/main.rs", "rank": 16, "score": 181546.49923973824 }, { "content": "fn day23_part1() -> i64 {\n\n run_network(NetworkMode::Part1)\n\n}\n\n\n", "file_path": "day23/src/main.rs", "rank": 17, "score": 181546.49923973824 }, { "content": "fn day05_part1() -> i64 {\n\n let output = Machine::from_source_with_input(DAY05_INPUT, 1)\n\n .run_as_iter()\n\n .collect::<Vec<_>>();\n\n assert!(!output.is_empty());\n\n let (last, rest) = output.split_last().unwrap();\n\n assert!(rest.iter().all(|o| *o == 0), \"Failed a TEST\");\n\n *last\n\n}\n\n\n", "file_path": "day05/src/main.rs", "rank": 18, "score": 181546.49923973824 }, { "content": "fn input_sequence(machine: &mut Machine, seq: &str) {\n\n let _prompt = machine.run_as_ascii();\n\n machine.input_ascii(seq);\n\n}\n\n\n\nconst DAY17_INPUT: &str = include_str!(\"day17_input.txt\");\n\n\n", "file_path": "day17/src/main.rs", "rank": 19, "score": 179338.153073948 }, { "content": "#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n\nstruct Vector3D([i64; 3]);\n\n\n\nimpl Index<usize> for Vector3D {\n\n type Output = i64;\n\n fn index(&self, idx: usize) -> &i64 {\n\n &self.0[idx]\n\n }\n\n}\n\n\n\nimpl Vector3D {\n\n fn energy(self) -> i64 {\n\n self.0.iter().map(|x| x.abs()).sum()\n\n }\n\n}\n\n\n", "file_path": "day12/src/main.rs", "rank": 20, "score": 177495.26186494005 }, { "content": "fn parse_number<T: FromStr>(line: &str) -> Result<T, String> {\n\n line.split_ascii_whitespace()\n\n .last()\n\n .map(|word| word.parse::<T>())\n\n .unwrap()\n\n .map(Ok)\n\n .map_err(|_| \"Missing N\")?\n\n}\n\n\n", "file_path": "day22/src/main.rs", "rank": 21, "score": 176684.59110451795 }, { "content": "fn first_repeat_biodiversity(input: &str) -> usize {\n\n let mut grid = Grid::from(input);\n\n let mut seen = HashSet::new();\n\n while seen.insert(grid.clone()) {\n\n grid = grid.next();\n\n }\n\n grid.biodiversity()\n\n}\n\n\n", "file_path": "day24/src/main.rs", "rank": 23, "score": 164203.77897457714 }, { "content": "fn day09() -> (i64, i64) {\n\n let program = Program::from(DAY09_INPUT);\n\n let part1 = Machine::new(&program).run_with_input(1).unwrap();\n\n let part2 = Machine::new(&program).run_with_input(2).unwrap();\n\n (part1, part2)\n\n}\n\n\n", "file_path": "day09/src/main.rs", "rank": 24, "score": 160366.98500196254 }, { "content": "fn day07() -> (i64, i64) {\n\n const DAY07_INPUT: &str = include_str!(\"day07_input.txt\");\n\n let program = Program::from(DAY07_INPUT);\n\n (\n\n max_thruster_signal(&program),\n\n max_feedback_thruster_signal(&program),\n\n )\n\n}\n\n\n", "file_path": "day07/src/main.rs", "rank": 25, "score": 160366.98500196254 }, { "content": "fn find_quickest_route(input: &str) -> Result<usize, String> {\n\n KeyMap::try_from(input)?\n\n .find_quickest_path_to_all_keys()\n\n .ok_or_else(|| \"Failed to find a route\".into())\n\n}\n\n\n", "file_path": "day18/src/main.rs", "rank": 26, "score": 152662.22787812975 }, { "content": "fn repeat_recursive_n_times(input: &str, n: usize) -> RecursiveGrid {\n\n let mut grid = RecursiveGrid::from(input);\n\n for _ in 0..n {\n\n grid = grid.next();\n\n }\n\n grid\n\n}\n\n\n", "file_path": "day24/src/main.rs", "rank": 27, "score": 152662.22787812978 }, { "content": "fn day19_part2() -> usize {\n\n const SIDE_LENGTH: usize = 100;\n\n\n\n // lines before y=4 have gaps in\n\n let mut locator = TractorBeamLocator::default();\n\n let mut row_start = 0;\n\n for y in 4.. {\n\n // find first location horizontally in the beam\n\n row_start = (row_start..).find(|&x| locator.has_beam(x, y)).unwrap();\n\n\n\n // search this row until we can't contain the square horizontally\n\n for x in row_start.. {\n\n if !locator.has_beam(x + SIDE_LENGTH - 1, y) {\n\n break;\n\n }\n\n if locator.has_beam(x, y + SIDE_LENGTH - 1) {\n\n return (x * 10_000) + y;\n\n }\n\n }\n\n }\n\n unreachable!();\n\n}\n\n\n", "file_path": "day19/src/main.rs", "rank": 28, "score": 151964.28765439618 }, { "content": "fn day03_part2() -> usize {\n\n let (p1, p2) = DAY03_INPUT.clone();\n\n find_shortest_intersection_walk(p1, p2)\n\n}\n\n\n", "file_path": "day03/src/main.rs", "rank": 29, "score": 151964.28765439618 }, { "content": "fn day06_part2() -> usize {\n\n OrbitMap::new(DAY06_INPUT).find_num_transits(\"YOU\", \"SAN\")\n\n}\n\n\n", "file_path": "day06/src/main.rs", "rank": 30, "score": 151964.28765439618 }, { "content": "fn day18_part2() -> usize {\n\n find_quickest_route_in_quadrants(DAY18_INPUT).unwrap()\n\n}\n\n\n", "file_path": "day18/src/main.rs", "rank": 31, "score": 151964.28765439618 }, { "content": "fn day20_part2() -> usize {\n\n Map::from(DAY20_INPUT).find_shortest_route_recursive()\n\n}\n\n\n", "file_path": "day20/src/main.rs", "rank": 32, "score": 151964.28765439618 }, { "content": "fn day03_part1() -> usize {\n\n let (p1, p2) = DAY03_INPUT.clone();\n\n find_closest_intersection_distance(p1, p2)\n\n}\n\n\n", "file_path": "day03/src/main.rs", "rank": 33, "score": 151947.83685422235 }, { "content": "fn day18_part1() -> usize {\n\n find_quickest_route(DAY18_INPUT).unwrap()\n\n}\n\n\n", "file_path": "day18/src/main.rs", "rank": 34, "score": 151947.83685422235 }, { "content": "fn day20_part1() -> usize {\n\n Map::from(DAY20_INPUT).find_shortest_route()\n\n}\n\n\n", "file_path": "day20/src/main.rs", "rank": 35, "score": 151947.83685422235 }, { "content": "fn day24_part1() -> usize {\n\n first_repeat_biodiversity(DAY24_INPUT)\n\n}\n\n\n", "file_path": "day24/src/main.rs", "rank": 36, "score": 151947.83685422235 }, { "content": "fn day13_part1() -> usize {\n\n let mut cabinet = ArcadeCabinet::new();\n\n cabinet.run();\n\n cabinet\n\n .render()\n\n .chars()\n\n .filter(|&c| c == char::from(Tile::Block))\n\n .count()\n\n}\n\n\n", "file_path": "day13/src/main.rs", "rank": 37, "score": 151947.83685422235 }, { "content": "fn day19_part1() -> usize {\n\n let mut locator = TractorBeamLocator::default();\n\n (0..50)\n\n .flat_map(|x| (0..50).map(move |y| (x, y)))\n\n .filter(|&(x, y)| locator.has_beam(x, y))\n\n .count()\n\n}\n\n\n", "file_path": "day19/src/main.rs", "rank": 38, "score": 151947.83685422235 }, { "content": "fn day22_part1() -> usize {\n\n let shuffled = Deck::with_shuffles(10_007, DAY22_INPUT).unwrap();\n\n shuffled.find_card(2019).unwrap()\n\n}\n\n\n", "file_path": "day22/src/main.rs", "rank": 39, "score": 151947.83685422235 }, { "content": "fn day06_part1() -> usize {\n\n OrbitMap::new(DAY06_INPUT).total_orbits()\n\n}\n\n\n", "file_path": "day06/src/main.rs", "rank": 40, "score": 151947.83685422235 }, { "content": "fn find_quickest_route_in_quadrants(input: &str) -> Result<usize, String> {\n\n KeyMap::make_quadrants(input)?\n\n .find_quickest_path_to_all_keys()\n\n .ok_or_else(|| \"Failed to find a route\".into())\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n const EXAMPLE1: &str = include_str!(\"input/example1.txt\");\n\n const EXAMPLE2: &str = include_str!(\"input/example2.txt\");\n\n const EXAMPLE3: &str = include_str!(\"input/example3.txt\");\n\n const EXAMPLE4: &str = include_str!(\"input/example4.txt\");\n\n const EXAMPLE5: &str = include_str!(\"input/example5.txt\");\n\n\n\n #[test]\n\n fn test_quickest_route() {\n\n check_quickest_route(EXAMPLE1, 8);\n\n check_quickest_route(EXAMPLE2, 86);\n", "file_path": "day18/src/main.rs", "rank": 41, "score": 149828.55834706206 }, { "content": "fn run_machine(program: &Program, noun: i64, verb: i64) -> i64 {\n\n let mut p = (*program).clone();\n\n p.write(1, noun);\n\n p.write(2, verb);\n\n let mut m = Machine::new(&p);\n\n m.run();\n\n m.read(0)\n\n}\n\n\n", "file_path": "day02/src/main.rs", "rank": 42, "score": 144188.03522662644 }, { "content": "fn day12() -> (i64, u64) {\n\n let vectors = parse_vectors(DAY12_INPUT);\n\n\n\n let mut data = SystemData::new(&vectors);\n\n for _ in 0..1000 {\n\n data.step();\n\n }\n\n let part1 = data.energy();\n\n\n\n let part2 = find_cycle_length(&vectors);\n\n\n\n (part1, part2)\n\n}\n\n\n\nconst DAY12_INPUT: &str = \"<x=-7, y=17, z=-11>\\n\\\n\n <x=9, y=12, z=5>\\n\\\n\n <x=-9, y=0, z=-4>\\n\\\n\n <x=4, y=6, z=0>\\n\";\n\n\n", "file_path": "day12/src/main.rs", "rank": 43, "score": 143512.7592812175 }, { "content": "fn day08_part1(img: &Image) -> usize {\n\n let layer = img\n\n .layers\n\n .iter()\n\n .map(|x| (x, x.count(0)))\n\n .min_by(|a, b| a.1.cmp(&b.1))\n\n .unwrap()\n\n .0;\n\n\n\n layer.count(1) * layer.count(2)\n\n}\n\n\n", "file_path": "day08/src/main.rs", "rank": 44, "score": 141549.96696439828 }, { "content": "fn day11_part1(program: &Program) -> usize {\n\n let mut robot = HullPaintingRobot::new(&program);\n\n robot.run_to_completion(0);\n\n robot.panels().len()\n\n}\n\n\n", "file_path": "day11/src/main.rs", "rank": 45, "score": 141549.96696439828 }, { "content": "fn first_eight_after_100_phases(signal: &str) -> String {\n\n let mut transform = Transform::new(signal);\n\n for _ in 0..100 {\n\n transform.advance();\n\n }\n\n let out = transform.signal();\n\n String::from(&out[..8])\n\n}\n\n\n", "file_path": "day16/src/main.rs", "rank": 46, "score": 132868.60268719884 }, { "content": "fn run_network(mode: NetworkMode) -> i64 {\n\n let num_machines = 50;\n\n\n\n let program = Program::from(DAY23_INPUT);\n\n let mut machines: Vec<_> = (0..num_machines)\n\n .map(|i| NetworkComputer::new(&program, i))\n\n .collect();\n\n let mut queue = VecDeque::new();\n\n let mut nat = None;\n\n let mut last_delivered_nat: Option<Packet> = None;\n\n\n\n loop {\n\n // empty queue => send Nones until messages are added\n\n if queue.is_empty() {\n\n for m in &mut machines {\n\n let msgs = m.run(None);\n\n if !msgs.is_empty() {\n\n queue.extend(msgs);\n\n break;\n\n }\n", "file_path": "day23/src/main.rs", "rank": 47, "score": 132511.33932678844 }, { "content": "fn max_thruster_signal(program: &Program) -> i64 {\n\n max_signal(&program, 0..=4, Amplifier::run)\n\n}\n\n\n", "file_path": "day07/src/main.rs", "rank": 48, "score": 132511.33932678844 }, { "content": "fn max_feedback_thruster_signal(program: &Program) -> i64 {\n\n max_signal(&program, 5..=9, Amplifier::run_feedback)\n\n}\n\n\n", "file_path": "day07/src/main.rs", "rank": 49, "score": 130205.07184821201 }, { "content": "struct DeckIter {\n\n deck: Deck,\n\n n: u64,\n\n}\n\n\n\nimpl Iterator for DeckIter {\n\n type Item = u64;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n let result = self.deck.nth_card(self.n);\n\n self.n += 1;\n\n\n\n let iter_length = self.deck.size + 1;\n\n self.n = self.n.mod_floor(&iter_length);\n\n\n\n result\n\n }\n\n}\n\n\n\nimpl TryFrom<Vec<u64>> for Deck {\n", "file_path": "day22/src/main.rs", "rank": 50, "score": 129386.43424193695 }, { "content": "fn parse_vectors(input: &str) -> Vec<Vector3D> {\n\n static RE: Lazy<Regex> =\n\n Lazy::new(|| Regex::new(r\"<x=\\s*(-?\\d+),\\s*y=\\s*(-?\\d+),\\s*z=\\s*(-?\\d+)>\").unwrap());\n\n\n\n RE.captures_iter(input)\n\n .map(|cap| {\n\n Vector3D([\n\n cap[1].parse::<i64>().unwrap(),\n\n cap[2].parse::<i64>().unwrap(),\n\n cap[3].parse::<i64>().unwrap(),\n\n ])\n\n })\n\n .collect_vec()\n\n}\n\n\n\nconst NUM_BODIES: usize = 4;\n\n\n", "file_path": "day12/src/main.rs", "rank": 51, "score": 127691.74025869748 }, { "content": "fn main() {\n\n let part1 = day17_part1();\n\n println!(\"part1 = {}\", part1);\n\n\n\n let part2 = day17_part2();\n\n println!(\"part2 = {}\", part2);\n\n}\n\n\n", "file_path": "day17/src/main.rs", "rank": 52, "score": 127644.0882085432 }, { "content": "fn main() {\n\n let (p1, p2) = day04();\n\n println!(\"part1 = {}\", p1);\n\n println!(\"part2 = {}\", p2);\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_password_validity() {\n\n assert!(Password::new(111_111).is_valid());\n\n assert!(!Password::new(223_450).is_valid());\n\n assert!(!Password::new(123_789).is_valid());\n\n\n\n assert!(Password::new(112_233).is_valid_part2());\n\n assert!(!Password::new(123_444).is_valid_part2());\n\n assert!(Password::new(111_122).is_valid_part2());\n\n }\n\n\n\n #[test]\n\n fn test_day04() {\n\n let (p1, p2) = day04();\n\n assert_eq!(p1, 1650);\n\n assert_eq!(p2, 1129);\n\n }\n\n}\n", "file_path": "day04/src/main.rs", "rank": 53, "score": 127644.0882085432 }, { "content": "fn main() {\n\n let part1 = day16_part1();\n\n println!(\"part1 = {}\", part1);\n\n\n\n let part2 = day16_part2();\n\n println!(\"part2 = {}\", part2);\n\n}\n\n\n", "file_path": "day16/src/main.rs", "rank": 54, "score": 127644.0882085432 }, { "content": "fn main() {\n\n println!(\"part1 = {}\", day13_part1());\n\n println!(\"part2 = {}\", day13_part2());\n\n}\n\n\n", "file_path": "day13/src/main.rs", "rank": 55, "score": 127644.0882085432 }, { "content": "fn main() {\n\n let (part1, part2) = day15();\n\n println!(\"part1 = {}\", part1);\n\n println!(\"part2 = {}\", part2);\n\n}\n\n\n", "file_path": "day15/src/main.rs", "rank": 56, "score": 127644.0882085432 }, { "content": "fn main() {\n\n println!(\"part1 = {}\", day05_part1());\n\n println!(\"part2 = {}\", day05_part2());\n\n}\n", "file_path": "day05/src/main.rs", "rank": 57, "score": 127644.0882085432 }, { "content": "fn main() {\n\n let (part1, part2) = day09();\n\n println!(\"part1 = {}\", part1);\n\n println!(\"part2 = {}\", part2);\n\n}\n", "file_path": "day09/src/main.rs", "rank": 58, "score": 127644.0882085432 }, { "content": "fn main() {\n\n let (part1, part2) = day12();\n\n println!(\"part1 = {}\", part1);\n\n println!(\"part2 = {}\", part2);\n\n}\n\n\n", "file_path": "day12/src/main.rs", "rank": 59, "score": 127644.0882085432 }, { "content": "fn main() {\n\n println!(\"part1 = {}\", day23_part1());\n\n println!(\"part2 = {}\", day23_part2());\n\n}\n\n\n", "file_path": "day23/src/main.rs", "rank": 60, "score": 127644.0882085432 }, { "content": "fn main() {\n\n println!(\"part1 = {}\", day22_part1());\n\n println!(\"part2 = {}\", day22_part2());\n\n}\n\n\n", "file_path": "day22/src/main.rs", "rank": 61, "score": 127644.0882085432 }, { "content": "fn main() {\n\n println!(\"part1 = {}\", day06_part1());\n\n println!(\"part2 = {}\", day06_part2());\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_examples() {\n\n const DAY06_EXAMPLE: &str = include_str!(\"day06_example.txt\");\n\n let map = OrbitMap::new(DAY06_EXAMPLE);\n\n assert_eq!(map.total_orbits(), 42);\n\n\n\n const DAY06_EXAMPLE_TRANSIT: &str = include_str!(\"day06_example_transit.txt\");\n\n let transit_map = OrbitMap::new(DAY06_EXAMPLE_TRANSIT);\n\n assert_eq!(transit_map.find_num_transits(\"YOU\", \"SAN\"), 4);\n\n }\n\n\n\n #[test]\n\n fn test_day06() {\n\n assert_eq!(day06_part1(), 315_757);\n\n assert_eq!(day06_part2(), 481);\n\n }\n\n}\n", "file_path": "day06/src/main.rs", "rank": 62, "score": 127644.0882085432 }, { "content": "fn main() {\n\n println!(\"part1 = {}\", day01_part1());\n\n println!(\"part2 = {}\", day01_part2());\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_fuel_required() {\n\n assert_eq!(fuel_required(12), 2);\n\n assert_eq!(fuel_required(14), 2);\n\n assert_eq!(fuel_required(1969), 654);\n\n assert_eq!(fuel_required(100_756), 33583);\n\n }\n\n\n\n #[test]\n\n fn test_total_fuel_required() {\n\n assert_eq!(total_fuel_required(14), 2);\n", "file_path": "day01/src/main.rs", "rank": 63, "score": 127644.0882085432 }, { "content": "fn main() {\n\n println!(\"part1 = {}\", day03_part1());\n\n println!(\"part2 = {}\", day03_part2());\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_find_closest_intersection_distance_examples() {\n\n let check = |wire1, wire2, expected_distance| {\n\n let p1 = Path::new(wire1);\n\n let p2 = Path::new(wire2);\n\n assert_eq!(\n\n find_closest_intersection_distance(p1, p2),\n\n expected_distance\n\n );\n\n };\n\n\n", "file_path": "day03/src/main.rs", "rank": 64, "score": 127644.0882085432 }, { "content": "fn main() {\n\n let (part1, part2) = day07();\n\n println!(\"part1 = {}\", part1);\n\n println!(\"part2 = {}\", part2);\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n fn check_max_signal(program: &str, expected_amplitude: i64) {\n\n let program = Program::from(program);\n\n let signal = max_thruster_signal(&program);\n\n assert_eq!(signal, expected_amplitude);\n\n }\n\n\n\n #[test]\n\n fn test_max_thruster_signal() {\n\n check_max_signal(\"3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0\", 43210);\n\n\n", "file_path": "day07/src/main.rs", "rank": 65, "score": 127644.0882085432 }, { "content": "fn main() {\n\n println!(\"part1 = {}\", day20_part1());\n\n println!(\"part2 = {}\", day20_part2());\n\n}\n\n\n", "file_path": "day20/src/main.rs", "rank": 66, "score": 127644.0882085432 }, { "content": "fn main() {\n\n println!(\"part1 = {}\", day19_part1());\n\n println!(\"part2 = {}\", day19_part2());\n\n}\n\n\n", "file_path": "day19/src/main.rs", "rank": 67, "score": 127644.0882085432 }, { "content": "fn main() {\n\n println!(\"part1 = {}\", day18_part1());\n\n println!(\"part1 = {}\", day18_part2());\n\n}\n\n\n", "file_path": "day18/src/main.rs", "rank": 68, "score": 127644.0882085432 }, { "content": "fn main() {\n\n println!(\"part1 = {}\", day02_part1());\n\n println!(\"part2 = {}\", day02_part2());\n\n}\n", "file_path": "day02/src/main.rs", "rank": 69, "score": 127644.0882085432 }, { "content": "fn main() {\n\n println!(\"part1 = {}\", day24_part1());\n\n println!(\"part2 = {}\", day24_part2());\n\n}\n\n\n", "file_path": "day24/src/main.rs", "rank": 70, "score": 127644.0882085432 }, { "content": "fn main() {\n\n let part1 = day14_part1();\n\n println!(\"part1 = {}\", part1);\n\n\n\n let part2 = day14_part2();\n\n println!(\"part2 = {}\", part2);\n\n}\n\n\n", "file_path": "day14/src/main.rs", "rank": 71, "score": 127644.0882085432 }, { "content": "fn main() {\n\n println!(\"part1 = {}\", day21_part1());\n\n println!(\"part2 = {}\", day21_part2());\n\n}\n\n\n", "file_path": "day21/src/main.rs", "rank": 72, "score": 127644.0882085432 }, { "content": "fn main() {\n\n let (part1, part2) = day11();\n\n println!(\"part1 = {}\", part1);\n\n println!(\"part2 = {}\", part2);\n\n}\n", "file_path": "day11/src/main.rs", "rank": 73, "score": 127644.0882085432 }, { "content": "fn main() {\n\n let (part1, part2) = day08();\n\n println!(\"part1 = {}\", part1);\n\n println!(\"part2 = {}\", part2);\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_day08() {\n\n let (part1, part2) = day08();\n\n assert_eq!(part1, 1703);\n\n assert_eq!(part2, \"HCGFE\");\n\n }\n\n}\n", "file_path": "day08/src/main.rs", "rank": 74, "score": 127644.0882085432 }, { "content": "fn main() {\n\n let args = env::args().collect_vec();\n\n if args.len() >= 2 && args[1] == \"--interactive\" {\n\n let mut droid = Droid::new();\n\n droid.interactive_loop();\n\n } else {\n\n println!(\"{}\", day25_part1())\n\n }\n\n}\n\n\n", "file_path": "day25/src/main.rs", "rank": 75, "score": 127644.0882085432 }, { "content": "fn layers(data: &str, dimensions: Dimensions) -> Layers {\n\n Layers {\n\n remaining: data,\n\n dimensions,\n\n layer_length: dimensions.area(),\n\n }\n\n}\n\n\n", "file_path": "day08/src/main.rs", "rank": 76, "score": 127463.62871507928 }, { "content": "fn day04() -> (usize, usize) {\n\n let mut p = Password::new(178_416);\n\n let mut part1 = 0;\n\n let mut part2 = 0;\n\n while p != Password::new(676_461) {\n\n p.increment();\n\n if p.is_valid() {\n\n part1 += 1;\n\n if p.is_valid_part2() {\n\n part2 += 1;\n\n }\n\n }\n\n }\n\n (part1, part2)\n\n}\n\n\n", "file_path": "day04/src/main.rs", "rank": 77, "score": 124941.33249783692 }, { "content": "fn day15() -> (usize, usize) {\n\n let mut droid = RepairDroid::new();\n\n while !droid.explored_everything() {\n\n droid.explore_one_tile();\n\n }\n\n\n\n if RENDER_FINAL_STATE {\n\n clear_console();\n\n println!(\"{}\", droid.render());\n\n }\n\n\n\n let part1 = droid.distance_of_oxygen_from_start().unwrap();\n\n let part2 = droid.time_for_oxygen_to_percolate().unwrap();\n\n\n\n (part1, part2)\n\n}\n\n\n", "file_path": "day15/src/main.rs", "rank": 78, "score": 124941.33249783692 }, { "content": "fn minimum_ore_per_fuel(factory_spec: &'static str) -> u64 {\n\n let mut factory = NanoFactory::from(factory_spec);\n\n factory.make(ChemicalQuantity::from(\"1 FUEL\"));\n\n factory.ore_used\n\n}\n\n\n", "file_path": "day14/src/main.rs", "rank": 79, "score": 123426.66625643003 }, { "content": "#[test]\n\nfn test_day05() {\n\n assert_eq!(day05_part1(), 13_933_662);\n\n assert_eq!(day05_part2(), 2_369_720);\n\n}\n\n\n", "file_path": "day05/src/main.rs", "rank": 80, "score": 122896.8454985536 }, { "content": "#[test]\n\nfn test_day09() {\n\n let (part1, part2) = day09();\n\n assert_eq!(part1, 2_351_176_124);\n\n assert_eq!(part2, 73_110);\n\n}\n\n\n", "file_path": "day09/src/main.rs", "rank": 81, "score": 122896.8454985536 }, { "content": "#[test]\n\nfn test_day11() {\n\n let (part1, part2) = day11();\n\n assert_eq!(part1, 1883);\n\n assert_eq!(part2, \"APUGURFH\");\n\n}\n\n\n", "file_path": "day11/src/main.rs", "rank": 82, "score": 122896.84549855358 }, { "content": "#[test]\n\nfn test_day02() {\n\n assert_eq!(day02_part1(), 11_590_668);\n\n assert_eq!(day02_part2(), 2254);\n\n}\n\n\n", "file_path": "day02/src/main.rs", "rank": 83, "score": 122896.8454985536 }, { "content": "fn max_fuel_per_trillion_ore(factory_spec: &'static str) -> u64 {\n\n let trillion = 1_000_000_000_000;\n\n let ore_for_one_fuel = minimum_ore_per_fuel(factory_spec);\n\n let mut factory = NanoFactory::from(factory_spec);\n\n let mut lower = trillion / ore_for_one_fuel;\n\n let mut upper = trillion;\n\n loop {\n\n let mid = (lower + upper) / 2;\n\n factory.make(ChemicalQuantity {\n\n name: \"FUEL\",\n\n quantity: mid,\n\n });\n\n if factory.ore_used > trillion {\n\n upper = mid;\n\n } else {\n\n lower = mid;\n\n }\n\n if (upper - lower) == 1 {\n\n break lower;\n\n }\n\n factory.reset();\n\n }\n\n}\n\n\n\nconst DAY14_INPUT: &str = include_str!(\"day14_input.txt\");\n\n\n", "file_path": "day14/src/main.rs", "rank": 84, "score": 121453.1423094889 }, { "content": "fn parse_techniques(input: &str) -> Result<Vec<Technique>, String> {\n\n let mut instructions = Vec::new();\n\n for line in input.lines() {\n\n instructions.push(Technique::try_from(line)?);\n\n }\n\n Ok(instructions)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_deal_into_new_stack() {\n\n let mut deck = Deck::new(11);\n\n deck.shuffle(Technique::try_from(\"deal into new stack\").unwrap());\n\n assert_eq!(\n\n deck,\n\n vec![10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0].try_into().unwrap()\n\n );\n", "file_path": "day22/src/main.rs", "rank": 85, "score": 120705.50215674183 }, { "content": "fn day24_part2() -> u64 {\n\n repeat_recursive_n_times(DAY24_INPUT, 200).count_bugs()\n\n}\n\n\n", "file_path": "day24/src/main.rs", "rank": 86, "score": 117800.4519393334 }, { "content": "fn day16_part2() -> String {\n\n let _part1_timer = Timer::new(\"part2\");\n\n\n\n let offset = DAY16_INPUT[..7].parse::<usize>().unwrap();\n\n let mut components = DAY16_INPUT\n\n .repeat(10_000)\n\n .chars()\n\n .skip(offset)\n\n .map(|d| d.to_digit(10).unwrap() as Digit)\n\n .collect::<Vec<_>>();\n\n\n\n components.reverse();\n\n\n\n let len = components.len();\n\n for _ in 0..100 {\n\n let mut sum = 0;\n\n let mut next = Vec::<Digit>::with_capacity(len);\n\n for c in &components {\n\n sum += c;\n\n sum %= 10;\n", "file_path": "day16/src/main.rs", "rank": 87, "score": 117800.4519393334 }, { "content": "fn day14_part2() -> u64 {\n\n max_fuel_per_trillion_ore(DAY14_INPUT)\n\n}\n\n\n", "file_path": "day14/src/main.rs", "rank": 88, "score": 117800.4519393334 }, { "content": "fn day01_part2() -> i32 {\n\n DAY01_INPUT.iter().copied().map(total_fuel_required).sum()\n\n}\n\n\n", "file_path": "day01/src/main.rs", "rank": 89, "score": 117800.4519393334 }, { "content": "fn day22_part2() -> u64 {\n\n let size = 119_315_717_514_047;\n\n let n = 101_741_582_076_661;\n\n let shuffled = Deck::with_shuffles_n_times(size, DAY22_INPUT, n).unwrap();\n\n shuffled.nth_card(2020).unwrap()\n\n}\n\n\n", "file_path": "day22/src/main.rs", "rank": 90, "score": 117800.4519393334 }, { "content": "fn day01_part1() -> i32 {\n\n DAY01_INPUT.iter().copied().map(fuel_required).sum()\n\n}\n\n\n", "file_path": "day01/src/main.rs", "rank": 91, "score": 117784.00113915956 }, { "content": "fn day16_part1() -> String {\n\n let _part1_timer = Timer::new(\"part1\");\n\n first_eight_after_100_phases(DAY16_INPUT)\n\n}\n\n\n", "file_path": "day16/src/main.rs", "rank": 92, "score": 117784.00113915956 }, { "content": "fn day25_part1() -> u64 {\n\n let mut droid = Droid::new();\n\n droid.pick_up_items();\n\n let output = droid.find_correctly_weighted_items().unwrap();\n\n\n\n let re = Regex::new(r\"\\d+\").unwrap();\n\n let caps = re.captures(&output).unwrap();\n\n let password = caps.get(0).unwrap();\n\n password.as_str().parse::<u64>().unwrap()\n\n}\n\n\n", "file_path": "day25/src/main.rs", "rank": 93, "score": 117784.00113915958 }, { "content": "fn day14_part1() -> u64 {\n\n minimum_ore_per_fuel(DAY14_INPUT)\n\n}\n\n\n", "file_path": "day14/src/main.rs", "rank": 94, "score": 117784.00113915956 }, { "content": "#[derive(PartialEq)]\n\nstruct Password([u8; 6]);\n\n\n\nimpl Password {\n\n fn new(num: u32) -> Password {\n\n let mut p = Password([0; 6]);\n\n let digits = num\n\n .to_string()\n\n .chars()\n\n .map(|d| d.to_digit(10).unwrap() as u8)\n\n .collect::<Vec<_>>();\n\n for (n, v) in digits.into_iter().enumerate() {\n\n p.0[n] = v;\n\n }\n\n p\n\n }\n\n\n\n fn is_valid(&self) -> bool {\n\n let p = &self.0;\n\n (\n\n // two adjacent equal digits\n", "file_path": "day04/src/main.rs", "rank": 95, "score": 117669.14218783955 }, { "content": "fn day11() -> (usize, String) {\n\n const DAY11_INPUT: &str = include_str!(\"day11_input.txt\");\n\n let program = Program::from(DAY11_INPUT);\n\n let part1 = day11_part1(&program);\n\n let part2 = day11_part2(&program);\n\n (part1, part2)\n\n}\n\n\n", "file_path": "day11/src/main.rs", "rank": 96, "score": 115970.62884399382 }, { "content": "fn day08() -> (usize, String) {\n\n const DAY08_INPUT: &str = include_str!(\"day08_input.txt\");\n\n let img = Image::new(\n\n DAY08_INPUT,\n\n Dimensions {\n\n width: 25,\n\n height: 6,\n\n },\n\n );\n\n (day08_part1(&img), day08_part2(&img))\n\n}\n\n\n", "file_path": "day08/src/main.rs", "rank": 97, "score": 115970.62884399382 }, { "content": "fn day11_part2(program: &Program) -> String {\n\n let mut robot = HullPaintingRobot::new(&program);\n\n robot.run_to_completion(1);\n\n\n\n let rendered = robot.render_panels();\n\n let width = rendered.find('\\n').unwrap();\n\n\n\n // Image begins at index 1 from inspection of output\n\n let letter_width = LETTER_IMAGE_DIMENSIONS.width;\n\n iter::successors(Some(1), |x| Some(x + letter_width + 1))\n\n .take_while(|x| ((*x) + LETTER_IMAGE_DIMENSIONS.width) < width)\n\n .map(|x| {\n\n rendered\n\n .lines()\n\n .map(move |line| line[x..(x + letter_width)].chars())\n\n .flatten()\n\n .map(|c| c != ' ')\n\n .collect()\n\n })\n\n .map(LetterImage)\n\n .map(ocr)\n\n .map(|result| result.character)\n\n .collect()\n\n}\n\n\n", "file_path": "day11/src/main.rs", "rank": 98, "score": 109340.94372554854 }, { "content": "fn day08_part2(img: &Image) -> String {\n\n let rendered = img.render();\n\n iter::successors(Some(0), |x| Some(x + 5))\n\n .take_while(|x| (*x) < rendered.dimensions.width)\n\n .map(|x| Vector2D { x: x as i64, y: 0 })\n\n .map(|offset| rendered.sub_image(offset, LETTER_IMAGE_DIMENSIONS))\n\n .map(|sub| sub.layer(0).iter().map(|(_, c)| (*c) > 0).collect())\n\n .map(LetterImage)\n\n .map(|letter| ocr(letter).character)\n\n .collect()\n\n}\n\n\n", "file_path": "day08/src/main.rs", "rank": 99, "score": 109340.94372554854 } ]
Rust
crates/server/src/ctrl/gateway/ready.rs
Lantern-chat/server
7dfc00130dd4f8ee6a7b9efac9b7866ebf067e6d
use futures::{StreamExt, TryStreamExt}; use hashbrown::{hash_map::Entry, HashMap}; use schema::Snowflake; use thorn::pg::Json; use crate::{ ctrl::{auth::Authorization, util::encrypted_asset::encrypt_snowflake_opt, Error, SearchMode}, permission_cache::PermMute, ServerState, }; pub async fn ready( state: ServerState, conn_id: Snowflake, auth: Authorization, ) -> Result<sdk::models::events::Ready, Error> { use sdk::models::*; log::trace!("Processing Ready Event for {}", auth.user_id); let db = state.db.read.get().await?; let perms_future = async { state.perm_cache.add_reference(auth.user_id).await; super::refresh::refresh_room_perms(&state, &db, auth.user_id).await }; let user_future = async { let row = db .query_one_cached_typed( || { use schema::*; use thorn::*; Query::select() .and_where(AggUsers::Id.equals(Var::of(Users::Id))) .cols(&[ /* 0*/ AggUsers::Username, /* 1*/ AggUsers::Discriminator, /* 2*/ AggUsers::Flags, /* 3*/ AggUsers::Email, /* 4*/ AggUsers::CustomStatus, /* 5*/ AggUsers::Biography, /* 6*/ AggUsers::Preferences, /* 7*/ AggUsers::AvatarId, ]) .from_table::<AggUsers>() .limit_n(1) }, &[&auth.user_id], ) .await?; Ok::<_, Error>(User { id: auth.user_id, username: row.try_get(0)?, discriminator: row.try_get(1)?, flags: UserFlags::from_bits_truncate(row.try_get(2)?), email: Some(row.try_get(3)?), avatar: encrypt_snowflake_opt(&state, row.try_get(7)?), status: row.try_get(4)?, bio: row.try_get(5)?, preferences: { let value: Option<Json<_>> = row.try_get(6)?; value.map(|v| v.0) }, }) }; let parties_future = async { let rows = db .query_cached_typed( || { use schema::*; use thorn::*; Query::select() .cols(&[ /* 0*/ Party::Id, /* 1*/ Party::OwnerId, /* 2*/ Party::Name, /* 3*/ Party::AvatarId, /* 4*/ Party::Description, /* 5*/ Party::DefaultRoom, ]) .col(/*6*/ PartyMember::Position) .from( Party::left_join_table::<PartyMember>() .on(PartyMember::PartyId.equals(Party::Id)), ) .and_where(PartyMember::UserId.equals(Var::of(Users::Id))) .and_where(Party::DeletedAt.is_null()) }, &[&auth.user_id], ) .await?; let mut parties = HashMap::with_capacity(rows.len()); let mut ids = Vec::with_capacity(rows.len()); for row in rows { let id = row.try_get(0)?; ids.push(id); parties.insert( id, Party { partial: PartialParty { id, name: row.try_get(2)?, description: row.try_get(4)?, }, owner: row.try_get(1)?, security: SecurityFlags::empty(), roles: Vec::new(), emotes: Vec::new(), avatar: encrypt_snowflake_opt(&state, row.try_get(3)?), position: row.try_get(6)?, default_room: row.try_get(5)?, }, ); } let (roles, emotes) = futures::future::join( async { crate::ctrl::party::roles::get_roles_raw(&db, state.clone(), SearchMode::Many(&ids)) .await? .try_collect::<Vec<_>>() .await }, async { crate::ctrl::party::emotes::get_custom_emotes_raw(&db, SearchMode::Many(&ids)) .await? .try_collect::<Vec<_>>() .await }, ) .await; let (roles, emotes) = (roles?, emotes?); for role in roles { if let Some(party) = parties.get_mut(&role.party_id) { party.roles.push(role); } } for emote in emotes { if let Some(party) = parties.get_mut(&emote.party_id) { party.emotes.push(Emote::Custom(emote)); } } Ok::<_, Error>(parties.into_iter().map(|(_, v)| v).collect()) }; let (user, parties) = match tokio::join!(user_future, parties_future, perms_future) { (Ok(user), Ok(parties), Ok(())) => (user, parties), (Err(e), _, _) | (_, Err(e), _) | (_, _, Err(e)) => { log::warn!("Error during ready event: {e}"); state.perm_cache.remove_reference(auth.user_id).await; return Err(e); } }; Ok(events::Ready { user, dms: Vec::new(), parties, session: conn_id, }) } /* fn select_members() -> impl AnyQuery { use schema::*; Query::select() .and_where(PartyMember::PartyId.equals(Builtin::any(Var::of(SNOWFLAKE_ARRAY)))) .cols(&[PartyMember::PartyId, PartyMember::Nickname]) .cols(&[ Users::Id, Users::Username, Users::Discriminator, Users::Flags, ]) .col(RoleMembers::RoleId) .from( RoleMembers::right_join( Users::left_join_table::<PartyMember>().on(Users::Id.equals(PartyMember::UserId)), ) .on(RoleMembers::UserId.equals(Users::Id)), ) } fn select_members_old() -> impl AnyQuery { use schema::*; Query::select() .and_where(PartyMember::PartyId.equals(Builtin::any(Var::of(SNOWFLAKE_ARRAY)))) .cols(&[PartyMember::PartyId, PartyMember::Nickname]) .cols(&[ Users::Id, Users::Username, Users::Discriminator, Users::Flags, ]) .expr( Query::select() .from_table::<RoleMembers>() .expr(Builtin::array_agg(RoleMembers::RoleId)) .and_where(RoleMembers::UserId.equals(Users::Id)) .as_value(), ) .from(Users::left_join_table::<PartyMember>().on(Users::Id.equals(PartyMember::UserId))) } fn select_emotes() -> impl AnyQuery { use schema::*; Query::select() } */
use futures::{StreamExt, TryStreamExt}; use hashbrown::{hash_map::Entry, HashMap}; use schema::Snowflake; use thorn::pg::Json; use crate::{ ctrl::{auth::Authorization, util::encrypted_ass
async { crate::ctrl::party::emotes::get_custom_emotes_raw(&db, SearchMode::Many(&ids)) .await? .try_collect::<Vec<_>>() .await }, ) .await; let (roles, emotes) = (roles?, emotes?); for role in roles { if let Some(party) = parties.get_mut(&role.party_id) { party.roles.push(role); } } for emote in emotes { if let Some(party) = parties.get_mut(&emote.party_id) { party.emotes.push(Emote::Custom(emote)); } } Ok::<_, Error>(parties.into_iter().map(|(_, v)| v).collect()) }; let (user, parties) = match tokio::join!(user_future, parties_future, perms_future) { (Ok(user), Ok(parties), Ok(())) => (user, parties), (Err(e), _, _) | (_, Err(e), _) | (_, _, Err(e)) => { log::warn!("Error during ready event: {e}"); state.perm_cache.remove_reference(auth.user_id).await; return Err(e); } }; Ok(events::Ready { user, dms: Vec::new(), parties, session: conn_id, }) } /* fn select_members() -> impl AnyQuery { use schema::*; Query::select() .and_where(PartyMember::PartyId.equals(Builtin::any(Var::of(SNOWFLAKE_ARRAY)))) .cols(&[PartyMember::PartyId, PartyMember::Nickname]) .cols(&[ Users::Id, Users::Username, Users::Discriminator, Users::Flags, ]) .col(RoleMembers::RoleId) .from( RoleMembers::right_join( Users::left_join_table::<PartyMember>().on(Users::Id.equals(PartyMember::UserId)), ) .on(RoleMembers::UserId.equals(Users::Id)), ) } fn select_members_old() -> impl AnyQuery { use schema::*; Query::select() .and_where(PartyMember::PartyId.equals(Builtin::any(Var::of(SNOWFLAKE_ARRAY)))) .cols(&[PartyMember::PartyId, PartyMember::Nickname]) .cols(&[ Users::Id, Users::Username, Users::Discriminator, Users::Flags, ]) .expr( Query::select() .from_table::<RoleMembers>() .expr(Builtin::array_agg(RoleMembers::RoleId)) .and_where(RoleMembers::UserId.equals(Users::Id)) .as_value(), ) .from(Users::left_join_table::<PartyMember>().on(Users::Id.equals(PartyMember::UserId))) } fn select_emotes() -> impl AnyQuery { use schema::*; Query::select() } */
et::encrypt_snowflake_opt, Error, SearchMode}, permission_cache::PermMute, ServerState, }; pub async fn ready( state: ServerState, conn_id: Snowflake, auth: Authorization, ) -> Result<sdk::models::events::Ready, Error> { use sdk::models::*; log::trace!("Processing Ready Event for {}", auth.user_id); let db = state.db.read.get().await?; let perms_future = async { state.perm_cache.add_reference(auth.user_id).await; super::refresh::refresh_room_perms(&state, &db, auth.user_id).await }; let user_future = async { let row = db .query_one_cached_typed( || { use schema::*; use thorn::*; Query::select() .and_where(AggUsers::Id.equals(Var::of(Users::Id))) .cols(&[ /* 0*/ AggUsers::Username, /* 1*/ AggUsers::Discriminator, /* 2*/ AggUsers::Flags, /* 3*/ AggUsers::Email, /* 4*/ AggUsers::CustomStatus, /* 5*/ AggUsers::Biography, /* 6*/ AggUsers::Preferences, /* 7*/ AggUsers::AvatarId, ]) .from_table::<AggUsers>() .limit_n(1) }, &[&auth.user_id], ) .await?; Ok::<_, Error>(User { id: auth.user_id, username: row.try_get(0)?, discriminator: row.try_get(1)?, flags: UserFlags::from_bits_truncate(row.try_get(2)?), email: Some(row.try_get(3)?), avatar: encrypt_snowflake_opt(&state, row.try_get(7)?), status: row.try_get(4)?, bio: row.try_get(5)?, preferences: { let value: Option<Json<_>> = row.try_get(6)?; value.map(|v| v.0) }, }) }; let parties_future = async { let rows = db .query_cached_typed( || { use schema::*; use thorn::*; Query::select() .cols(&[ /* 0*/ Party::Id, /* 1*/ Party::OwnerId, /* 2*/ Party::Name, /* 3*/ Party::AvatarId, /* 4*/ Party::Description, /* 5*/ Party::DefaultRoom, ]) .col(/*6*/ PartyMember::Position) .from( Party::left_join_table::<PartyMember>() .on(PartyMember::PartyId.equals(Party::Id)), ) .and_where(PartyMember::UserId.equals(Var::of(Users::Id))) .and_where(Party::DeletedAt.is_null()) }, &[&auth.user_id], ) .await?; let mut parties = HashMap::with_capacity(rows.len()); let mut ids = Vec::with_capacity(rows.len()); for row in rows { let id = row.try_get(0)?; ids.push(id); parties.insert( id, Party { partial: PartialParty { id, name: row.try_get(2)?, description: row.try_get(4)?, }, owner: row.try_get(1)?, security: SecurityFlags::empty(), roles: Vec::new(), emotes: Vec::new(), avatar: encrypt_snowflake_opt(&state, row.try_get(3)?), position: row.try_get(6)?, default_room: row.try_get(5)?, }, ); } let (roles, emotes) = futures::future::join( async { crate::ctrl::party::roles::get_roles_raw(&db, state.clone(), SearchMode::Many(&ids)) .await? .try_collect::<Vec<_>>() .await },
random
[ { "content": "pub fn gateway(route: Route<crate::ServerState>) -> Response {\n\n let addr = match real_ip::get_real_ip(&route) {\n\n Ok(addr) => addr,\n\n Err(_) => return ApiError::bad_request().into_response(),\n\n };\n\n\n\n let query = match route.query() {\n\n Some(Ok(query)) => query,\n\n None => Default::default(),\n\n _ => return ApiError::bad_request().into_response(),\n\n };\n\n\n\n // TODO: Move this into FTL websocket part?\n\n let state = route.state.clone();\n\n\n\n let mut config = WebSocketConfig::default();\n\n //config.max_message_size = Some(1024 * 512); // 512KIB\n\n config.max_send_queue = Some(1);\n\n\n\n match Ws::new(route, Some(config)) {\n\n Ok(ws) => ws\n\n .on_upgrade(move |ws| client_connected(ws, query, addr, state))\n\n .into_response(),\n\n Err(e) => e.into_response(),\n\n }\n\n}\n", "file_path": "crates/server/src/web/routes/api/v1/gateway.rs", "rank": 0, "score": 75332.04210341668 }, { "content": "type ListenerTable = HashMap<Snowflake, AbortHandle>;\n\n\n", "file_path": "crates/server/src/web/gateway/socket/mod.rs", "rank": 1, "score": 70130.65945162644 }, { "content": "use std::f32::consts::PI;\n\nuse std::io;\n\n\n\nuse byteorder::BigEndian;\n\nuse byteorder::ReadBytesExt;\n\n\n\nuse crate::common::{linear_to_srgb, srgb_to_linear};\n\n\n", "file_path": "crates/blurhash/src/decode.rs", "rank": 2, "score": 38861.3918406682 }, { "content": "use std::f32::consts::PI;\n\nuse std::io;\n\n\n\nuse byteorder::BigEndian;\n\nuse byteorder::WriteBytesExt;\n\n\n\nuse crate::common::{linear_to_srgb, roundup4, srgb_to_linear};\n\n\n\n#[inline(always)]\n", "file_path": "crates/blurhash/src/encode.rs", "rank": 3, "score": 38861.15325616789 }, { "content": "#![allow(unused_imports)]\n\n\n\n#[macro_use]\n\nextern crate serde;\n\n\n\nextern crate tracing as log;\n\n\n\nuse std::{convert::Infallible, future::Future, net::SocketAddr};\n\n\n\nuse futures::FutureExt;\n\n\n\nuse ftl::StatusCode;\n\nuse hyper::{\n\n server::conn::AddrStream,\n\n service::{make_service_fn, service_fn},\n\n Server,\n\n};\n\n\n\npub mod built {\n\n include!(concat!(env!(\"OUT_DIR\"), \"/built.rs\"));\n", "file_path": "crates/server/src/lib.rs", "rank": 4, "score": 38860.83202895116 }, { "content": "use std::{\n\n any::Any,\n\n ops::Deref,\n\n sync::{\n\n atomic::{AtomicBool, AtomicI64, Ordering},\n\n Arc,\n\n },\n\n time::Instant,\n\n};\n\n\n\nuse futures::{future::BoxFuture, FutureExt};\n\nuse schema::Snowflake;\n\nuse tokio::sync::{oneshot, Mutex, Notify, OwnedMutexGuard, Semaphore};\n\nuse util::cmap::CHashMap;\n\n\n\nuse crate::{\n\n config::Config, filesystem::store::FileStore, permission_cache::PermissionCache, queues::Queues,\n\n services::Services, session_cache::SessionCache, web::file_cache::MainFileCache, DatabasePools,\n\n};\n\nuse crate::{\n", "file_path": "crates/server/src/state.rs", "rank": 5, "score": 38860.399060945434 }, { "content": "#![allow(unused_imports)]\n\n\n\npub extern crate tokio_postgres as pg;\n\n\n\nextern crate tracing as log;\n\n\n\npub mod migrate;\n\npub mod pool;\n\n\n\npub use pg::Row;\n", "file_path": "crates/db/src/lib.rs", "rank": 6, "score": 38860.31970052781 }, { "content": "use std::str::FromStr;\n\nuse std::sync::{atomic::Ordering, Arc};\n\nuse std::{\n\n borrow::Cow,\n\n path::{Path, PathBuf},\n\n};\n\n\n\nuse futures::{Stream, StreamExt};\n\n\n\nuse pg::Connection;\n\nuse tokio::sync::mpsc;\n\n\n\nuse crate::pool::{Client, ConnectionStream, Error, Pool};\n\n\n\n#[derive(Debug, thiserror::Error)]\n\npub enum MigrationError {\n\n #[error(\"Database error: {0}\")]\n\n DatabaseError(#[from] Error),\n\n\n\n #[error(\"IO Error: {0}\")]\n", "file_path": "crates/db/src/migrate.rs", "rank": 7, "score": 38859.941978983356 }, { "content": "extern crate tracing as log;\n\nuse db::pg::NoTls;\n\nuse tracing_subscriber::{\n\n filter::{EnvFilter, LevelFilter},\n\n FmtSubscriber,\n\n};\n\n\n\npub mod allocator;\n\npub mod cli;\n\n\n\nuse futures::FutureExt;\n\n\n\n#[tokio::main(flavor = \"multi_thread\")]\n\nasync fn main() -> anyhow::Result<()> {\n\n dotenv::dotenv().ok();\n\n\n\n let args = cli::CliOptions::parse()?;\n\n\n\n let mut extreme_trace = false;\n\n\n", "file_path": "crates/main/src/main.rs", "rank": 8, "score": 38859.01804384968 }, { "content": "pub struct DatabasePools {\n\n pub read: Pool,\n\n pub write: Pool,\n\n}\n\n\n\nuse ftl::Reply;\n\nuse tokio::net::TcpListener;\n\n\n\n//use crate::net::ip_filter::IpFilter;\n\n\n\npub async fn start_server(\n\n config: config::Config,\n\n db: DatabasePools,\n\n) -> anyhow::Result<(impl Future<Output = Result<(), hyper::Error>>, ServerState)> {\n\n let (snd, rcv) = tokio::sync::oneshot::channel();\n\n let state = ServerState::new(snd, config, db);\n\n\n\n log::info!(\"Starting interval tasks...\");\n\n\n\n let ts = state.clone();\n", "file_path": "crates/server/src/lib.rs", "rank": 9, "score": 38858.27878689898 }, { "content": "use std::str::FromStr;\n\n\n\nuse hmac::{Hmac, Mac};\n\nuse sha2::Sha256;\n\n\n", "file_path": "crates/totp/src/lib.rs", "rank": 10, "score": 38858.09851308103 }, { "content": "use std::fs::File;\n\n\n\nuse image::ImageDecoder;\n\n\n\nuse blurhash::base85::{FromZ85, ToZ85};\n\n\n", "file_path": "crates/blurhash/examples/encode.rs", "rank": 11, "score": 38858.00301597034 }, { "content": "#![allow(unused)]\n\n\n\nuse std::time::SystemTime;\n\n\n\nuse time::{Date, PrimitiveDateTime};\n\nuse timestamp::Timestamp;\n\n\n\n#[inline]\n", "file_path": "crates/util/src/time.rs", "rank": 12, "score": 38857.82199412432 }, { "content": "use smol_str::SmolStr;\n\nuse util::hex::HexidecimalInt;\n\n\n\n#[inline(never)]\n\n#[no_mangle]\n", "file_path": "crates/util/examples/asm.rs", "rank": 13, "score": 38857.53570544699 }, { "content": " Self::with_hasher(num_shards, DefaultHashBuilder::new())\n\n }\n\n}\n\n\n\nlazy_static::lazy_static! {\n\n static ref NUM_CPUS: usize = num_cpus::get();\n\n}\n\n\n\nimpl<K, T> Default for CHashMap<K, T, DefaultHashBuilder> {\n\n fn default() -> Self {\n\n Self::new(Self::default_num_shards())\n\n }\n\n}\n\n\n\n/// Simple sharded hashmap using Tokio async rwlocks for the shards\n\n///\n\n/// Use as a simple replacement for `RwLock<HashMap<K, T, V>>`\n\nimpl<K, T, S> CHashMap<K, T, S>\n\nwhere\n\n S: Clone,\n", "file_path": "crates/util/src/cmap.rs", "rank": 14, "score": 38857.4782098071 }, { "content": "#![allow(deprecated)]\n\n\n\nuse criterion::{black_box, criterion_group, criterion_main, Criterion};\n\nuse util::hex::HexidecimalInt;\n\n\n", "file_path": "crates/util/benches/utils.rs", "rank": 15, "score": 38857.36715125231 }, { "content": "use smol_str::SmolStr;\n\n\n", "file_path": "crates/util/src/base64.rs", "rank": 16, "score": 38857.21518270483 }, { "content": "#[macro_export]\n\nmacro_rules! cols {\n\n ($($col:expr),*$(,)?) => {\n\n std::array::IntoIter::new([$($col),*])\n\n }\n\n}\n\n\n\npub mod codes;\n\npub use codes::*;\n\n\n\npub mod tables;\n\npub use tables::*;\n\n\n\npub mod views;\n\npub use views::*;\n\n\n\npub use thorn::pg::Type;\n\n\n\npub const SNOWFLAKE: Type = Type::INT8;\n\npub const SNOWFLAKE_ARRAY: Type = Type::INT8_ARRAY;\n\n\n\npub mod sf;\n\npub use sf::{Snowflake, SnowflakeExt};\n\n\n\npub mod flags;\n\n\n\npub mod auth;\n", "file_path": "crates/schema/src/lib.rs", "rank": 17, "score": 38857.1871091799 }, { "content": "use criterion::{black_box, criterion_group, criterion_main, Criterion};\n\n\n\nuse schema::{\n\n auth::{BotTokenKey, SplitBotToken},\n\n Snowflake, SnowflakeExt,\n\n};\n", "file_path": "crates/schema/benches/schema.rs", "rank": 18, "score": 38857.11141038026 }, { "content": "use std::borrow::Borrow;\n\nuse std::hash::{BuildHasher, Hash, Hasher};\n\nuse std::ops::{Deref, DerefMut};\n\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\n\n\npub use hashbrown::hash_map::DefaultHashBuilder;\n\nuse hashbrown::hash_map::{HashMap, RawEntryMut};\n\nuse tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};\n\n\n\npub type CHashSet<K, S = DefaultHashBuilder> = CHashMap<K, (), S>;\n\n\n\n#[derive(Debug)]\n\npub struct CHashMap<K, T, S = DefaultHashBuilder> {\n\n hash_builder: S,\n\n shards: Vec<RwLock<HashMap<K, T, S>>>,\n\n size: AtomicUsize,\n\n}\n\n\n\nimpl<K, T> CHashMap<K, T, DefaultHashBuilder> {\n\n pub fn new(num_shards: usize) -> Self {\n", "file_path": "crates/util/src/cmap.rs", "rank": 19, "score": 38856.898366809946 }, { "content": "use std::{\n\n sync::atomic::{AtomicU16, Ordering},\n\n time::{Duration, SystemTime, UNIX_EPOCH},\n\n};\n\n\n\nuse std::num::NonZeroU64;\n\n\n\npub use sdk::models::sf::{Snowflake, LANTERN_EPOCH};\n\nuse sdk::models::LANTERN_EPOCH_PDT;\n\n\n\n/// Incremenent counter to ensure unique snowflakes\n\npub static INCR: AtomicU16 = AtomicU16::new(0);\n\n/// Global instance value\n\npub static mut INST: u16 = 0;\n\n/// Global worker value\n\npub static mut WORK: u16 = 0;\n\n\n", "file_path": "crates/schema/src/sf.rs", "rank": 20, "score": 38856.85915879237 }, { "content": "extern crate tracing as log;\n\n\n\npub mod avatar;\n\npub mod read_image;\n", "file_path": "crates/processing/src/lib.rs", "rank": 21, "score": 38856.84682371583 }, { "content": "use std::path::PathBuf;\n\nuse std::{env, time::Duration};\n\n\n\nuse std::ops::Range;\n\n\n\nuse aes::{cipher::BlockCipherKey, Aes128, Aes256};\n\nuse schema::auth::BotTokenKey;\n\n\n\n#[derive(Debug, Clone)]\n\npub struct LanternConfig {\n\n pub num_parallel_tasks: usize,\n\n pub login_session_duration: Duration,\n\n pub min_user_age_in_years: u8,\n\n pub password_len: Range<usize>,\n\n pub username_len: Range<usize>,\n\n pub partyname_len: Range<usize>,\n\n pub roomname_len: Range<usize>,\n\n pub max_newlines: usize,\n\n pub message_len: Range<usize>,\n\n pub premium_message_len: Range<usize>,\n", "file_path": "crates/server/src/config.rs", "rank": 22, "score": 38856.77083304278 }, { "content": "use smol_str::SmolStr;\n\n\n\nconst CHARSET: &'static [u8] = b\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n\n", "file_path": "crates/util/src/base62.rs", "rank": 23, "score": 38856.76094609562 }, { "content": "use crate::read_image::{read_image, Image, ImageInfo, ImageReadError, Limits};\n\n\n\npub struct ProcessConfig {\n\n pub max_width: u32,\n\n pub max_pixels: u32,\n\n}\n\n\n\npub struct ProcessedImage {\n\n pub reused: bool,\n\n pub image: EncodedImage,\n\n}\n\n\n\n#[derive(Debug, thiserror::Error)]\n\npub enum ProcessingError {\n\n #[error(\"Invalid Image Format\")]\n\n InvalidImageFormat,\n\n\n\n #[error(\"Image Read Error\")]\n\n ImageReadError(#[from] ImageReadError),\n\n\n\n #[error(\"Image Too Large\")]\n\n TooLarge,\n\n\n\n #[error(\"Other: {0}\")]\n\n Other(String),\n\n}\n\n\n", "file_path": "crates/processing/src/avatar.rs", "rank": 24, "score": 38856.63157342207 }, { "content": "use db::pool::Pool;\n\n\n\n#[derive(Clone)]\n\npub struct DatabasePools {\n\n read: Pool,\n\n write: Pool,\n\n}", "file_path": "crates/server/src/db.rs", "rank": 25, "score": 38856.530681497585 }, { "content": "use smol_str::SmolStr;\n\n\n\npub enum SmolCowStr {\n\n Reused(SmolStr),\n\n Owned(String),\n\n}\n", "file_path": "crates/util/src/string.rs", "rank": 26, "score": 38856.45976659298 }, { "content": "use std::cell::UnsafeCell;\n\nuse std::rc::Rc;\n\n\n\nuse rand::rngs::{adapter::ReseedingRng, OsRng};\n\nuse rand::{Rng, RngCore, SeedableRng};\n\nuse rand_chacha::ChaCha20Core;\n\n\n\n#[derive(Clone, Debug)]\n\npub struct CryptoThreadRng {\n\n rng: Rc<UnsafeCell<ReseedingRng<ChaCha20Core, OsRng>>>,\n\n}\n\n\n\n// Number of generated bytes after which to reseed `CryptoThreadRng`.\n\n// According to benchmarks, reseeding has a noticable impact with thresholds\n\n// of 32 kB and less. We choose 128 kB to avoid significant overhead.\n\nconst THREAD_RNG_RESEED_THRESHOLD: u64 = 1024 * 128;\n\n\n\nthread_local!(\n\n // We require Rc<..> to avoid premature freeing when thread_rng is used\n\n // within thread-local destructors. See #968.\n\n static CRYPTO_THREAD_RNG_KEY: Rc<UnsafeCell<ReseedingRng<ChaCha20Core, OsRng>>> = {\n\n let r = ChaCha20Core::from_rng(OsRng).unwrap_or_else(|err|\n\n panic!(\"could not initialize thread_rng: {}\", err));\n\n let rng = ReseedingRng::new(r, THREAD_RNG_RESEED_THRESHOLD, OsRng);\n\n Rc::new(UnsafeCell::new(rng))\n\n }\n\n);\n\n\n", "file_path": "crates/util/src/rng.rs", "rank": 27, "score": 38856.40839756368 }, { "content": " use std::hash::{BuildHasher, Hash, Hasher};\n\n\n\n let mut hasher = hash_builder.build_hasher();\n\n\n\n if idx >> 31 == 0 {\n\n ipv4.get_unchecked(idx as usize).hash(&mut hasher);\n\n } else {\n\n ipv6.get_unchecked(idx as usize & INDEX_MASK).hash(&mut hasher);\n\n }\n\n\n\n hasher.finish()\n\n });\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n", "file_path": "crates/iplist/src/lib.rs", "rank": 28, "score": 38856.32254948384 }, { "content": "\n\n PartyCreate,\n\n PartyUpdate,\n\n PartyDelete,\n\n\n\n RoomCreated,\n\n RoomUpdated,\n\n RoomDeleted,\n\n\n\n /// Per-party member information updated\n\n MemberUpdated,\n\n /// Member joined party\n\n MemberJoined,\n\n /// Member left party\n\n MemberLeft,\n\n /// Member was banned, only sent if proper intent was used\n\n MemberBan,\n\n /// Member was unbanned, only sent if proper intent was used\n\n MemberUnban,\n\n\n", "file_path": "crates/schema/src/codes.rs", "rank": 29, "score": 38856.19821451272 }, { "content": "\n\n // if the existing PNG buffer is somehow smaller, use that\n\n // could happen with a very-optimized PNG from photoshop or something\n\n if try_use_existing && buffer.len() < output.buffer.len() {\n\n log::trace!(\n\n \"PNG Encoder got worse compression than original, {} vs {}\",\n\n buffer.len(),\n\n output.buffer.len()\n\n );\n\n\n\n reused = true;\n\n output.buffer = buffer;\n\n }\n\n\n\n Ok(ProcessedImage {\n\n reused,\n\n image: output,\n\n })\n\n }\n\n Err(e) => Err(ProcessingError::Other(e.to_string())),\n", "file_path": "crates/processing/src/avatar.rs", "rank": 30, "score": 38856.11057874658 }, { "content": "use std::cell::Cell;\n\n\n\nuse serde::ser::{Serialize, SerializeSeq, Serializer};\n\n\n\npub struct SerializeFromIter<I>(Cell<Option<I>>);\n\n\n\nimpl<I> SerializeFromIter<I> {\n\n pub fn new(iter: I) -> Self {\n\n Self(Cell::new(Some(iter)))\n\n }\n\n}\n\n\n\nimpl<I, T> Serialize for SerializeFromIter<I>\n\nwhere\n\n I: IntoIterator<Item = T>,\n\n T: Serialize,\n\n{\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: Serializer,\n", "file_path": "crates/util/src/serde.rs", "rank": 31, "score": 38856.11057874658 }, { "content": "\n\n Ok(self.check(token, time))\n\n }\n\n\n\n pub fn url(&self, label: &str, issuer: &str) -> String {\n\n let secret = base32::encode(base32::Alphabet::RFC4648 { padding: false }, self.key);\n\n\n\n format!(\"otpauth://totp/{label}?secret={secret}&issuer={issuer}&digits={DIGITS}&algorithm=SHA256\")\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::time::SystemTime;\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn print_totps() {\n\n const TEST_TIMES: &[u64] = &[59, 1111111109, 1111111111, 1234567890, 2000000000, 20000000000];\n", "file_path": "crates/totp/src/lib.rs", "rank": 32, "score": 38856.08236345215 }, { "content": " i += 1;\n\n }\n\n\n\n x\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_base62() {\n\n let input = \"NfUJBUoglqu1588eP4Ulx4\";\n\n\n\n let x = decode128(input);\n\n let y = encode128(x);\n\n\n\n assert_eq!(y, input);\n\n\n\n let input = 235623462346;\n", "file_path": "crates/util/src/base62.rs", "rank": 33, "score": 38855.97674139503 }, { "content": "use std::fmt::{self, Debug, Display, Formatter, LowerHex};\n\nuse std::str::FromStr;\n\n\n\nuse smol_str::SmolStr;\n\n\n\n/// Integer wrapper that can `FromStr` and `Display` hexidecimal values.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\n#[repr(transparent)]\n\npub struct HexidecimalInt<T>(pub T);\n\n\n\npub unsafe trait SafeInt: Sized + LowerHex + Copy {\n\n type Bytes: Default + AsRef<[u8]> + AsMut<[u8]> + Debug;\n\n type HexBytes: Default + AsRef<[u8]> + AsMut<[u8]> + Debug;\n\n\n\n fn __from_be_bytes(bytes: Self::Bytes) -> Self;\n\n fn __to_be_bytes(self) -> Self::Bytes;\n\n}\n\n\n\nmacro_rules! impl_safe_int {\n\n ($($ty:ty: $bytes:expr),*) => {$(\n", "file_path": "crates/util/src/hex.rs", "rank": 34, "score": 38855.97329594945 }, { "content": " #[inline(always)]\n\n fn next_u64(&mut self) -> u64 {\n\n // SAFETY: We must make sure to stop using `rng` before anyone else\n\n // creates another mutable reference\n\n let rng = unsafe { &mut *self.rng.get() };\n\n rng.next_u64()\n\n }\n\n\n\n fn fill_bytes(&mut self, dest: &mut [u8]) {\n\n // SAFETY: We must make sure to stop using `rng` before anyone else\n\n // creates another mutable reference\n\n let rng = unsafe { &mut *self.rng.get() };\n\n rng.fill_bytes(dest)\n\n }\n\n\n\n fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {\n\n // SAFETY: We must make sure to stop using `rng` before anyone else\n\n // creates another mutable reference\n\n let rng = unsafe { &mut *self.rng.get() };\n\n rng.try_fill_bytes(dest)\n\n }\n\n}\n\n\n\nimpl rand::CryptoRng for CryptoThreadRng {}\n\n\n", "file_path": "crates/util/src/rng.rs", "rank": 35, "score": 38855.921854217435 }, { "content": "use std::sync::{\n\n atomic::{AtomicBool, Ordering},\n\n Arc,\n\n};\n\n\n\nuse tokio::sync::mpsc::{self, error::TrySendError};\n\n\n\npub struct LaggyReceiver<T> {\n\n lagged: Arc<AtomicBool>,\n\n rx: mpsc::Receiver<T>,\n\n}\n\n\n\npub struct LaggySender<T> {\n\n lagged: Arc<AtomicBool>,\n\n tx: mpsc::Sender<T>,\n\n}\n\n\n\nimpl<T> Clone for LaggySender<T> {\n\n fn clone(&self) -> Self {\n\n LaggySender {\n\n lagged: self.lagged.clone(),\n\n tx: self.tx.clone(),\n\n }\n\n }\n\n}\n\n\n", "file_path": "crates/util/src/laggy.rs", "rank": 36, "score": 38855.89757385231 }, { "content": "#![allow(unused)]\n\n\n\nuse std::{\n\n cmp::Ordering,\n\n net::{IpAddr, Ipv4Addr, Ipv6Addr},\n\n ops::Range,\n\n};\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\n#[repr(u8)]\n", "file_path": "crates/iplist/src/lib.rs", "rank": 37, "score": 38855.826948943984 }, { "content": "pub mod tasks {\n\n pub mod cn_cleanup;\n\n pub mod event_cleanup;\n\n pub mod file_cache_cleanup;\n\n pub mod id_lock_cleanup;\n\n pub mod item_cache_cleanup;\n\n pub mod perm_cache_cleanup;\n\n pub mod record_metrics;\n\n pub mod rl_cleanup;\n\n pub mod session_cleanup;\n\n pub mod totp_cleanup;\n\n\n\n pub mod events;\n\n}\n\n\n\npub use state::ServerState;\n\n\n\nuse db::pool::Pool;\n\n\n\n#[derive(Clone)]\n", "file_path": "crates/server/src/lib.rs", "rank": 38, "score": 38855.777836566966 }, { "content": "// Based on rustc_serialize::base64\n\n// and also ZeroMQ's reference implementation\n\n\n\npub use self::FromZ85Error::*;\n\npub use self::ToZ85Error::*;\n\n\n\nuse std::error;\n\nuse std::fmt;\n\n\n\nconst CHARS: &[u8] = b\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#\";\n\n\n\nconst BYTE_OFFSETS: &[i8] = &[\n\n -0x01, 0x44, -0x01, 0x54, 0x53, 0x52, 0x48, -0x01, 0x4B, 0x4C, 0x46, 0x41, -0x01, 0x3F, 0x3E, 0x45, 0x00,\n\n 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x40, -0x01, 0x49, 0x42, 0x4A, 0x47, 0x51, 0x24,\n\n 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,\n\n 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x4D, -0x01, 0x4E, 0x43, -0x01, -0x01, 0x0A, 0x0B, 0x0C,\n\n 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D,\n\n 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x4F, -0x01, 0x50, -0x01, -0x01,\n\n];\n\n\n", "file_path": "crates/blurhash/src/base85.rs", "rank": 39, "score": 38855.563180753845 }, { "content": "use super::*;\n\n\n\npub const UINT2: Type = Type::INT4;\n\n\n\nthorn::tables! {\n\n pub struct Host in Lantern {\n\n Migration: Type::INT8,\n\n Migrated: Type::TIMESTAMP,\n\n }\n\n\n\n pub struct Metrics in Lantern {\n\n Ts: Type::TIMESTAMP,\n\n\n\n Mem: Type::INT8,\n\n Upload: Type::INT8,\n\n\n\n Reqs: Type::INT4,\n\n Errs: Type::INT4,\n\n Conns: Type::INT4,\n\n Events: Type::INT4,\n", "file_path": "crates/schema/src/tables.rs", "rank": 40, "score": 38855.188824072495 }, { "content": "\n\n let s = match hex::encode_to_slice(bytes.as_ref(), buf.as_mut()) {\n\n Err(_) => unsafe { std::hint::unreachable_unchecked() },\n\n Ok(_) => unsafe { std::str::from_utf8_unchecked(buf.as_ref()) },\n\n };\n\n\n\n // size * 2 <= 22, max inline size of SmolStr\n\n if std::mem::size_of::<Self>() <= 11 {\n\n SmolStr::new_inline(s)\n\n } else {\n\n SmolStr::new(s)\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n\n\n use super::*;\n\n\n", "file_path": "crates/util/src/hex.rs", "rank": 41, "score": 38855.10316302756 }, { "content": "\n\n pub struct Reactions in Lantern {\n\n EmoteId: Emotes::Id,\n\n MsgId: Messages::Id,\n\n UserIds: SNOWFLAKE_ARRAY,\n\n }\n\n\n\n pub struct Invite in Lantern {\n\n Id: SNOWFLAKE,\n\n PartyId: Party::Id,\n\n UserId: Users::Id,\n\n Expires: Type::TIMESTAMP,\n\n Uses: Type::INT2,\n\n Description: Type::TEXT,\n\n Vanity: Type::TEXT,\n\n }\n\n\n\n pub struct Rooms in Lantern {\n\n Id: SNOWFLAKE,\n\n PartyId: SNOWFLAKE,\n", "file_path": "crates/schema/src/tables.rs", "rank": 42, "score": 38855.023438835655 }, { "content": " assert!(idx < MAX_LEN);\n\n self.ipv4.push(ip);\n\n idx as u32\n\n }\n\n IpAddr::V6(ip) => {\n\n ip.hash(&mut hasher);\n\n let idx = self.ipv6.len();\n\n assert!(idx < MAX_LEN);\n\n self.ipv6.push(ip);\n\n idx as u32 | (1 << 31)\n\n }\n\n };\n\n\n\n unsafe { self.set.insert_no_grow(hasher.finish(), idx) };\n\n }\n\n }\n\n\n\n fn hash(&self, ip: &IpAddr) -> u64 {\n\n use std::hash::{BuildHasher, Hash, Hasher};\n\n\n", "file_path": "crates/iplist/src/lib.rs", "rank": 43, "score": 38855.023438835655 }, { "content": "\n\n /// Vec<Option<Vec<u8>>>\n\n Preview: Type::BYTEA_ARRAY,\n\n }\n\n\n\n pub struct AggFriends in Lantern {\n\n UserId: Users::Id,\n\n FriendId: Users::Id,\n\n Flags: Type::INT2,\n\n Note: Type::VARCHAR,\n\n }\n\n\n\n pub struct AggRoomPerms in Lantern {\n\n RoomId: Overwrites::RoomId,\n\n UserId: Overwrites::UserId,\n\n Perms: Type::INT8,\n\n }\n\n}\n\n\n\nuse smol_str::SmolStr;\n", "file_path": "crates/schema/src/views.rs", "rank": 44, "score": 38854.99807794862 }, { "content": " let max_width = config.max_width;\n\n\n\n let mut width = info.width;\n\n let height = info.height;\n\n\n\n let try_use_existing = format == ImageFormat::Png && width == height && width <= max_width;\n\n\n\n // crop out the center\n\n if width != height {\n\n let mut x = 0;\n\n let mut y = 0;\n\n let mut new_width = width;\n\n let mut new_height = height;\n\n\n\n if width > height {\n\n x = (width - height) / 2;\n\n new_width = height;\n\n } else {\n\n y = (height - width) / 2;\n\n new_height = width;\n", "file_path": "crates/processing/src/avatar.rs", "rank": 45, "score": 38854.99807794862 }, { "content": " this\n\n }\n\n\n\n // Recreate IpSet without freeing memory\n\n pub fn refresh(&mut self, ips: &[IpAddr]) {\n\n use std::hash::{BuildHasher, Hash, Hasher};\n\n\n\n self.ipv4.clear();\n\n self.ipv6.clear();\n\n\n\n self.set.clear();\n\n self.set.reserve(ips.len(), |_| 0); // there are no elements to rehash\n\n\n\n for &ip in ips {\n\n let mut hasher = self.hash_builder.build_hasher();\n\n\n\n let idx = match ip {\n\n IpAddr::V4(ip) => {\n\n ip.hash(&mut hasher);\n\n let idx = self.ipv4.len();\n", "file_path": "crates/iplist/src/lib.rs", "rank": 46, "score": 38854.90217339474 }, { "content": " pub fn contains(&self, ip: IpAddr) -> bool {\n\n self.sorted\n\n .binary_search_by(|idx| self.values.compare_ip(*idx, ip))\n\n .is_ok()\n\n }\n\n\n\n pub fn insert(&mut self, ip: IpAddr) {\n\n if let Err(idx) = self\n\n .sorted\n\n .binary_search_by(|idx| self.values.compare_ip(*idx, ip))\n\n {\n\n self.sorted.insert(idx, self.values.insert(ip));\n\n }\n\n }\n\n}\n\n\n\nuse hashbrown::{hash_map::DefaultHashBuilder, raw::RawTable};\n\n\n\n#[derive(Default, Clone)]\n\npub struct IpSet {\n", "file_path": "crates/iplist/src/lib.rs", "rank": 47, "score": 38854.85729589581 }, { "content": " // if write-config requested, do this before saving\n\n if args.write_config {\n\n config.configure();\n\n }\n\n\n\n if initialized || args.write_config {\n\n log::info!(\"Saving config to: {}\", args.config_path.display());\n\n config.save(&args.config_path).await?;\n\n\n\n log::info!(\"Save complete, exiting.\");\n\n return Ok(());\n\n }\n\n\n\n config.configure();\n\n\n\n let db = {\n\n use db::pool::{Pool, PoolConfig};\n\n\n\n let mut db_config = config.db.db_str.parse::<db::pg::Config>()?;\n\n db_config.dbname(\"lantern\");\n", "file_path": "crates/main/src/main.rs", "rank": 48, "score": 38854.81429666322 }, { "content": "use std::path::PathBuf;\n\n\n\n#[derive(Debug)]\n\npub struct CliOptions {\n\n pub verbose: Option<u8>,\n\n pub config_path: PathBuf,\n\n pub write_config: bool,\n\n}\n\n\n\nimpl CliOptions {\n\n pub fn parse() -> Result<Self, anyhow::Error> {\n\n let mut pargs = pico_args::Arguments::from_env();\n\n\n\n if pargs.contains([\"-h\", \"--help\"]) {\n\n print!(\"{}\", HELP);\n\n std::process::exit(0);\n\n }\n\n\n\n if pargs.contains([\"-V\", \"--version\"]) {\n\n println!(\"Lantern Server {}\", server::built::PKG_VERSION);\n", "file_path": "crates/main/src/cli.rs", "rank": 49, "score": 38854.81429666322 }, { "content": "\n\nimpl SnowflakeExt for Snowflake {\n\n #[inline]\n\n fn encrypt(self, key: aes::cipher::BlockCipherKey<aes::Aes128>) -> u128 {\n\n use aes::{BlockEncrypt, NewBlockCipher};\n\n\n\n let mut block = unsafe { std::mem::transmute([self, self]) };\n\n\n\n let cipher = aes::Aes128::new(&key);\n\n\n\n cipher.encrypt_block(&mut block);\n\n\n\n unsafe { std::mem::transmute(block) }\n\n }\n\n\n\n fn low_complexity(self) -> u64 {\n\n const ID_MASK: u64 = 0b11111_11111;\n\n let raw = self.to_u64();\n\n\n\n // shift high bits of timestamp down, since the timestamp occupies the top 42 bits,\n", "file_path": "crates/schema/src/sf.rs", "rank": 50, "score": 38854.71428063712 }, { "content": "\n\n fn encrypt(self, key: aes::cipher::BlockCipherKey<aes::Aes128>) -> u128;\n\n\n\n #[inline]\n\n fn decrypt(block: u128, key: aes::cipher::BlockCipherKey<aes::Aes128>) -> Option<Snowflake> {\n\n use aes::{BlockDecrypt, NewBlockCipher};\n\n\n\n let mut block = unsafe { std::mem::transmute(block) };\n\n\n\n let cipher = aes::Aes128::new(&key);\n\n\n\n cipher.decrypt_block(&mut block);\n\n\n\n let [l, _]: [u64; 2] = unsafe { std::mem::transmute(block) };\n\n\n\n NonZeroU64::new(l).map(Snowflake)\n\n }\n\n\n\n fn low_complexity(self) -> u64;\n\n}\n", "file_path": "crates/schema/src/sf.rs", "rank": 51, "score": 38854.69545904717 }, { "content": "use super::*;\n\n\n\nthorn::tables! {\n\n pub struct AggMentions in Lantern {\n\n Kinds: Type::INT4_ARRAY,\n\n Ids: SNOWFLAKE_ARRAY,\n\n }\n\n\n\n pub struct AggMessages in Lantern {\n\n MsgId: Messages::Id,\n\n UserId: Messages::UserId,\n\n RoomId: Messages::RoomId,\n\n PartyId: Rooms::PartyId,\n\n Kind: Messages::Kind,\n\n Nickname: PartyMember::Nickname,\n\n Username: Users::Username,\n\n Discriminator: Users::Discriminator,\n\n UserFlags: Users::Flags,\n\n AvatarId: UserAvatars::FileId,\n\n ThreadId: Threads::Id,\n", "file_path": "crates/schema/src/views.rs", "rank": 52, "score": 38854.65890621361 }, { "content": " /// https://datatracker.ietf.org/doc/html/rfc6238#appendix-A\n\n pub fn generate_raw(&self, time: u64) -> u32 {\n\n let ctr = (time / self.step).to_be_bytes();\n\n\n\n let hash = {\n\n let mut mac = HmacSha256::new_from_slice(self.key).expect(\"Invalid key\");\n\n mac.update(&ctr);\n\n mac.finalize().into_bytes()\n\n };\n\n\n\n // get last byte and use it as an index to read in a word\n\n let offset = (hash[hash.len() - 1] & 0xF) as usize;\n\n let binary = {\n\n let mut buf = [0u8; 4];\n\n buf.copy_from_slice(&hash[offset..offset + 4]);\n\n\n\n 0x7fff_ffff & u32::from_be_bytes(buf)\n\n };\n\n\n\n binary % 10u32.pow(DIGITS as u32)\n", "file_path": "crates/totp/src/lib.rs", "rank": 53, "score": 38854.62373832203 }, { "content": " /// Create a snowflake at the given unix epoch (milliseconds)\n\n fn at_ms(ms: u64) -> Snowflake {\n\n // offset by Lantern epoch\n\n Self::at_ms_since_lantern_epoch(ms - LANTERN_EPOCH)\n\n }\n\n\n\n fn at_ms_since_lantern_epoch(ms: u64) -> Snowflake {\n\n // update incremenent counter, making sure it wraps at 12 bits\n\n let incr = INCR\n\n .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |incr| {\n\n Some((incr + 1) & 0xFFF)\n\n })\n\n .unwrap() as u64;\n\n\n\n // get global IDs\n\n let inst = unsafe { INST as u64 };\n\n let worker = unsafe { WORK as u64 };\n\n\n\n // check inst and worker only use 5 bits\n\n debug_assert!(inst < (1 << 6));\n", "file_path": "crates/schema/src/sf.rs", "rank": 54, "score": 38854.62373832203 }, { "content": " // shifting it down by 42 will leave only the high bits\n\n let ts_high = raw >> 42;\n\n // shift IDs down to lsb and mask them out\n\n let ids = (raw >> 12) & ID_MASK;\n\n // combine 22 timestamp bits with 10 id bits, placing the IDs first\n\n let high = ts_high | (ids << 22);\n\n // to get the low timestamp bits, shift out high bits,\n\n // then shift back down, then shift down again to lsb\n\n let ts_low = (raw << 22) >> 44;\n\n\n\n // to get low bits, shift timestamp over to make room for increment counter, then OR with counter\n\n let low = (ts_low << 12) | (raw & 0xFFF);\n\n\n\n // recombine\n\n (high << 32) | low\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_snowflake_ser() {\n\n assert!(serde_json::to_string(&Snowflake::now()).unwrap().contains(\"\\\"\"));\n\n }\n\n}\n", "file_path": "crates/schema/src/sf.rs", "rank": 55, "score": 38854.41050388771 }, { "content": " InvalidZ85Byte(_, _) => \"invalid character\",\n\n InvalidZ85Length(_) => \"invalid length\",\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Display for FromZ85Error {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n fmt::Debug::fmt(&self, f)\n\n }\n\n}\n\n\n\n#[derive(Clone, Copy)]\n\npub enum ToZ85Error {\n\n /// The input had an invalid length\n\n InvalidZ85InputSize(usize),\n\n}\n\n\n\nimpl fmt::Display for ToZ85Error {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n", "file_path": "crates/blurhash/src/base85.rs", "rank": 56, "score": 38852.80253084034 }, { "content": " let key = base32::decode(base32::Alphabet::RFC4648 { padding: false }, \"JBSWY3DPEHPK3PXP\").unwrap();\n\n\n\n println!(\"Keylen: {}\", key.len());\n\n\n\n let totp = TOTP6 {\n\n key: &key,\n\n skew: 0,\n\n step: 30,\n\n };\n\n\n\n println!(\"{}\", totp.url(\"test\", \"testing\"));\n\n println!(\"{}\", totp.generate(now));\n\n\n\n //for t in 0..100000000 {\n\n // assert_eq!(totp.generate_backup(t).len(), 13);\n\n //}\n\n }\n\n}\n", "file_path": "crates/totp/src/lib.rs", "rank": 57, "score": 38852.80253084034 }, { "content": "\n\nimpl<K, T, S> Deref for ReadValue<'_, K, T, S> {\n\n type Target = T;\n\n\n\n fn deref(&self) -> &Self::Target {\n\n self.value\n\n }\n\n}\n\n\n\nimpl<K, T, S> Deref for WriteValue<'_, K, T, S> {\n\n type Target = T;\n\n\n\n fn deref(&self) -> &Self::Target {\n\n self.value\n\n }\n\n}\n\n\n\nimpl<K, T, S> DerefMut for WriteValue<'_, K, T, S> {\n\n fn deref_mut(&mut self) -> &mut Self::Target {\n\n self.value\n", "file_path": "crates/util/src/cmap.rs", "rank": 58, "score": 38852.80253084034 }, { "content": " let step_time = (basestep + i) * self.step;\n\n\n\n if self.generate_raw(step_time) == token {\n\n return true;\n\n }\n\n }\n\n\n\n false\n\n }\n\n\n\n pub fn check_str(&self, token: &str, time: u64) -> Result<bool, <u32 as FromStr>::Err> {\n\n if token.len() != DIGITS {\n\n return Ok(false);\n\n }\n\n\n\n let token: u32 = token.parse()?;\n\n\n\n if token >= (10u32.pow(DIGITS as u32)) {\n\n return Ok(false);\n\n }\n", "file_path": "crates/totp/src/lib.rs", "rank": 59, "score": 38852.80253084034 }, { "content": " unsafe impl SafeInt for $ty {\n\n type Bytes = [u8; $bytes];\n\n type HexBytes = [u8; $bytes * 2];\n\n\n\n #[inline(always)]\n\n fn __from_be_bytes(bytes: Self::Bytes) -> Self {\n\n <$ty>::from_be_bytes(bytes)\n\n }\n\n\n\n #[inline(always)]\n\n fn __to_be_bytes(self) -> Self::Bytes {\n\n self.to_be_bytes()\n\n }\n\n }\n\n )*}\n\n}\n\n\n\nimpl_safe_int!(i8: 1, i16: 2, i32: 4, i64: 8, i128: 16, u8: 1, u16: 2, u32: 4, u64: 8, u128: 16);\n\n\n\nimpl<T: SafeInt> FromStr for HexidecimalInt<T> {\n", "file_path": "crates/util/src/hex.rs", "rank": 60, "score": 38852.80253084034 }, { "content": " self.batch_hash_and_sort(keys, cache);\n\n\n\n if cache.is_empty() {\n\n return;\n\n }\n\n\n\n let mut i = 0;\n\n loop {\n\n let current_shard = cache[i].2;\n\n let shard = unsafe { self.shards.get_unchecked(current_shard).read().await };\n\n\n\n while cache[i].2 == current_shard {\n\n f(\n\n cache[i].0,\n\n shard.raw_entry().from_key_hashed_nocheck(cache[i].1, cache[i].0),\n\n );\n\n i += 1;\n\n\n\n if i >= cache.len() {\n\n return;\n", "file_path": "crates/util/src/cmap.rs", "rank": 61, "score": 38852.80253084034 }, { "content": " let key = hex::decode(\"3132333435363738393031323334353637383930313233343536373839303132\").unwrap();\n\n\n\n let totp = TOTP8 {\n\n key: &key,\n\n skew: 0,\n\n step: 30,\n\n };\n\n\n\n for t in TEST_TIMES {\n\n println!(\"{}: {}\", t, totp.generate(*t));\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_now_totp() {\n\n let now = SystemTime::now()\n\n .duration_since(SystemTime::UNIX_EPOCH)\n\n .unwrap()\n\n .as_secs();\n\n\n", "file_path": "crates/totp/src/lib.rs", "rank": 62, "score": 38852.80253084034 }, { "content": " for c in s[..11].iter() {\n\n let y = match *c as char {\n\n '0'..='9' => c - 48,\n\n 'A'..='Z' => c - 29,\n\n 'a'..='z' => c - 87,\n\n _ => return 0,\n\n };\n\n\n\n x += y as u64 * POWERS[i];\n\n i += 1;\n\n }\n\n\n\n x\n\n}\n\n\n", "file_path": "crates/util/src/base62.rs", "rank": 63, "score": 38852.80253084034 }, { "content": " pub fn try_send(&self, message: T) -> Result<(), TrySendError<T>> {\n\n match self.tx.try_send(message) {\n\n Ok(()) => Ok(()),\n\n Err(e) => {\n\n if let TrySendError::Full(_) = e {\n\n self.lagged.store(true, Ordering::SeqCst);\n\n }\n\n Err(e)\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl<T> LaggyReceiver<T> {\n\n /// If this returns Err, then the channel lagged and should be terminated\n\n pub async fn recv(&mut self) -> Result<Option<T>, LaggyRecvError> {\n\n if self.lagged.load(Ordering::SeqCst) {\n\n return Err(LaggyRecvError::Lagged);\n\n }\n\n\n\n Ok(self.rx.recv().await)\n\n }\n\n}\n", "file_path": "crates/util/src/laggy.rs", "rank": 64, "score": 38852.80253084034 }, { "content": " self.size.fetch_sub(1, Ordering::Relaxed);\n\n Some(occupied.remove())\n\n }\n\n RawEntryMut::Vacant(_) => None,\n\n }\n\n }\n\n\n\n pub async fn insert(&self, key: K, value: T) -> Option<T> {\n\n let (hash, shard_idx) = self.hash_and_shard(&key);\n\n unsafe {\n\n let mut shard = self.shards.get_unchecked(shard_idx).write().await;\n\n\n\n let entry = shard.raw_entry_mut().from_key_hashed_nocheck(hash, &key);\n\n\n\n match entry {\n\n RawEntryMut::Occupied(mut occupied) => Some(occupied.insert(value)),\n\n RawEntryMut::Vacant(vacant) => {\n\n vacant.insert_hashed_nocheck(hash, key, value);\n\n self.size.fetch_add(1, Ordering::Relaxed);\n\n None\n", "file_path": "crates/util/src/cmap.rs", "rank": 65, "score": 38852.80253084034 }, { "content": " }\n\n }\n\n }\n\n }\n\n\n\n pub async fn get_or_insert(&self, key: &K, on_insert: impl FnOnce() -> T) -> ReadValue<'_, K, T, S>\n\n where\n\n K: Clone,\n\n {\n\n let (hash, shard_idx) = self.hash_and_shard(key);\n\n\n\n let mut shard = unsafe { self.shards.get_unchecked(shard_idx).write().await };\n\n\n\n let (_, value) = shard\n\n .raw_entry_mut()\n\n .from_key_hashed_nocheck(hash, key)\n\n .or_insert_with(|| {\n\n self.size.fetch_add(1, Ordering::Relaxed);\n\n (key.clone(), on_insert())\n\n });\n", "file_path": "crates/util/src/cmap.rs", "rank": 66, "score": 38852.80253084034 }, { "content": "\n\n ReadValue {\n\n value: unsafe { std::mem::transmute(value) },\n\n _lock: RwLockWriteGuard::downgrade(shard),\n\n }\n\n }\n\n\n\n pub async fn get_mut_or_insert(&self, key: &K, on_insert: impl FnOnce() -> T) -> WriteValue<'_, K, T, S>\n\n where\n\n K: Clone,\n\n {\n\n let (hash, shard_idx) = self.hash_and_shard(key);\n\n\n\n let mut shard = unsafe { self.shards.get_unchecked(shard_idx).write().await };\n\n\n\n let (_, value) = shard\n\n .raw_entry_mut()\n\n .from_key_hashed_nocheck(hash, key)\n\n .or_insert_with(|| {\n\n self.size.fetch_add(1, Ordering::Relaxed);\n", "file_path": "crates/util/src/cmap.rs", "rank": 67, "score": 38852.80253084034 }, { "content": "\n\n let x = encode128(input);\n\n let y = decode128(&x);\n\n\n\n println!(\"{}\", x);\n\n\n\n assert_eq!(y, input);\n\n }\n\n}\n", "file_path": "crates/util/src/base62.rs", "rank": 68, "score": 38852.80253084034 }, { "content": " ));\n\n\n\n assert!(is_of_age_inner(\n\n min_age,\n\n datetime!(2017 - 03 - 01 00:00),\n\n date!(2004 - 02 - 29)\n\n ));\n\n\n\n assert!(!is_of_age_inner(\n\n min_age,\n\n datetime!(2020 - 02 - 27 23:59),\n\n date!(2007 - 02 - 28)\n\n ));\n\n\n\n assert!(is_of_age_inner(\n\n min_age,\n\n datetime!(2020 - 02 - 28 00:00),\n\n date!(2007 - 02 - 28)\n\n ));\n\n\n", "file_path": "crates/util/src/time.rs", "rank": 69, "score": 38852.80253084034 }, { "content": " #[test]\n\n fn test_age() {\n\n let min_age = 13;\n\n\n\n assert!(!is_of_age_inner(\n\n min_age,\n\n datetime!(2020 - 01 - 03 23:59),\n\n date!(2007 - 01 - 04)\n\n ));\n\n\n\n assert!(is_of_age_inner(\n\n min_age,\n\n datetime!(2020 - 01 - 04 00:00),\n\n date!(2007 - 01 - 04)\n\n ));\n\n\n\n assert!(!is_of_age_inner(\n\n min_age,\n\n datetime!(2017 - 02 - 28 23:59),\n\n date!(2004 - 02 - 29)\n", "file_path": "crates/util/src/time.rs", "rank": 70, "score": 38852.80253084034 }, { "content": " self.size.fetch_sub(1, Ordering::Relaxed);\n\n }\n\n retained\n\n });\n\n }\n\n }\n\n\n\n #[inline]\n\n pub fn shards(&self) -> &[RwLock<HashMap<K, T, S>>] {\n\n &self.shards\n\n }\n\n\n\n #[inline]\n\n pub fn len(&self) -> usize {\n\n self.size.load(Ordering::Relaxed)\n\n }\n\n\n\n #[inline]\n\n pub fn is_empty(&self) -> bool {\n\n self.len() == 0\n", "file_path": "crates/util/src/cmap.rs", "rank": 71, "score": 38852.80253084034 }, { "content": " tb(date!(2005 - 03 - 02), date!(2020 - 03 - 02));\n\n\n\n // no leap years\n\n tb(date!(2005 - 03 - 28), date!(2021 - 03 - 28));\n\n tb(date!(2005 - 02 - 28), date!(2021 - 02 - 28));\n\n\n\n // regular dates\n\n tb(date!(2005 - 02 - 02), date!(2021 - 02 - 02));\n\n tb(date!(2005 - 07 - 28), date!(2021 - 07 - 28));\n\n tb(date!(2005 - 01 - 28), date!(2021 - 01 - 28));\n\n\n\n // mixed regular dates\n\n tb(date!(2004 - 02 - 02), date!(2021 - 02 - 02));\n\n tb(date!(2004 - 07 - 28), date!(2021 - 07 - 28));\n\n tb(date!(2004 - 01 - 28), date!(2021 - 01 - 28));\n\n tb(date!(2004 - 02 - 02), date!(2020 - 02 - 02));\n\n tb(date!(2004 - 07 - 28), date!(2020 - 07 - 28));\n\n tb(date!(2004 - 01 - 28), date!(2020 - 01 - 28));\n\n }\n\n\n", "file_path": "crates/util/src/time.rs", "rank": 72, "score": 38852.80253084034 }, { "content": "\n\n#[inline]\n\n#[cold]\n", "file_path": "crates/util/src/likely.rs", "rank": 73, "score": 38852.80253084034 }, { "content": " }\n\n\n\n // birthdays are leap years\n\n tb(date!(2004 - 02 - 29), date!(2020 - 02 - 29));\n\n tb(date!(2004 - 03 - 29), date!(2020 - 03 - 29));\n\n tb(date!(2004 - 02 - 23), date!(2020 - 02 - 23));\n\n tb(date!(2004 - 03 - 23), date!(2021 - 03 - 23));\n\n tb(date!(2004 - 02 - 28), date!(2021 - 02 - 28));\n\n tb(date!(2004 - 02 - 29), date!(2021 - 03 - 01));\n\n tb(date!(2004 - 03 - 01), date!(2021 - 03 - 01));\n\n tb(date!(2004 - 03 - 02), date!(2021 - 03 - 02));\n\n tb(date!(2004 - 03 - 03), date!(2021 - 03 - 03));\n\n\n\n // current year is leap year\n\n tb(date!(2005 - 03 - 01), date!(2020 - 03 - 01));\n\n tb(date!(2005 - 02 - 23), date!(2020 - 02 - 23));\n\n tb(date!(2005 - 02 - 28), date!(2020 - 02 - 28));\n\n tb(date!(2005 - 03 - 28), date!(2020 - 03 - 28));\n\n tb(date!(2005 - 02 - 23), date!(2020 - 02 - 23));\n\n tb(date!(2005 - 03 - 01), date!(2020 - 03 - 01));\n", "file_path": "crates/util/src/time.rs", "rank": 74, "score": 38852.80253084034 }, { "content": " 2955688905823059073916326510592,\n\n 183252712161029662582812243656704,\n\n 11361668153983839080134359106715648,\n\n 704423425546998022968330264616370176,\n\n 43674252383913877424036476406214950912,\n\n ];\n\n\n\n let s = s.as_bytes();\n\n let mut x = 0;\n\n let mut i = 0;\n\n\n\n for c in s[..22].iter() {\n\n let y = match *c as char {\n\n '0'..='9' => c - 48,\n\n 'A'..='Z' => c - 29,\n\n 'a'..='z' => c - 87,\n\n _ => return 0,\n\n };\n\n\n\n x += y as u128 * POWERS[i];\n", "file_path": "crates/util/src/base62.rs", "rank": 75, "score": 38852.80253084034 }, { "content": "}\n\n\n\npub struct WriteValue<'a, K, T, S> {\n\n _lock: RwLockWriteGuard<'a, HashMap<K, T, S>>,\n\n value: &'a mut T,\n\n}\n\n\n\npub struct EntryValue<'a, K, T, S> {\n\n pub lock: RwLockWriteGuard<'a, HashMap<K, T, S>>,\n\n pub entry: RawEntryMut<'a, K, T, S>,\n\n}\n\n\n\nimpl<'a, K, T, S> WriteValue<'a, K, T, S> {\n\n pub fn downgrade(this: WriteValue<'a, K, T, S>) -> ReadValue<'a, K, T, S> {\n\n ReadValue {\n\n _lock: RwLockWriteGuard::downgrade(this._lock),\n\n value: this.value,\n\n }\n\n }\n\n}\n", "file_path": "crates/util/src/cmap.rs", "rank": 76, "score": 38852.80253084034 }, { "content": " K: Clone,\n\n T: Default,\n\n {\n\n self.get_mut_or_insert(key, Default::default).await\n\n }\n\n\n\n fn batch_hash_and_sort<'a, Q: 'a, I>(&self, keys: I, cache: &mut Vec<(&'a Q, u64, usize)>)\n\n where\n\n K: Borrow<Q>,\n\n Q: Hash + Eq,\n\n I: IntoIterator<Item = &'a Q>,\n\n {\n\n cache.truncate(0);\n\n\n\n cache.extend(keys.into_iter().map(|key| {\n\n let (hash, shard) = self.hash_and_shard(key);\n\n (key, hash, shard)\n\n }));\n\n\n\n if !cache.is_empty() {\n", "file_path": "crates/util/src/cmap.rs", "rank": 77, "score": 38852.80253084034 }, { "content": "{\n\n pub fn default_num_shards() -> usize {\n\n *NUM_CPUS * 32\n\n }\n\n\n\n pub fn with_hasher(num_shards: usize, hash_builder: S) -> Self {\n\n CHashMap {\n\n shards: (0..num_shards)\n\n .into_iter()\n\n .map(|_| RwLock::new(HashMap::with_hasher(hash_builder.clone())))\n\n .collect(),\n\n hash_builder,\n\n size: AtomicUsize::new(0),\n\n }\n\n }\n\n}\n\n\n\npub struct ReadValue<'a, K, T, S> {\n\n _lock: RwLockReadGuard<'a, HashMap<K, T, S>>,\n\n value: &'a T,\n", "file_path": "crates/util/src/cmap.rs", "rank": 78, "score": 38852.80253084034 }, { "content": " cache.sort_unstable_by_key(|(_, _, shard)| *shard);\n\n }\n\n }\n\n\n\n // TODO: Rewrite this to take unique shards into a small Vec,\n\n // then iterate over them concurrently to avoid blocking on any single one\n\n pub async fn batch_read<'a, Q: 'a, I, F>(\n\n &self,\n\n keys: I,\n\n cache: Option<&mut Vec<(&'a Q, u64, usize)>>,\n\n mut f: F,\n\n ) where\n\n K: Borrow<Q>,\n\n Q: Hash + Eq,\n\n I: IntoIterator<Item = &'a Q>,\n\n F: FnMut(&'a Q, Option<(&K, &T)>),\n\n {\n\n let mut own_cache = Vec::new();\n\n let cache = cache.unwrap_or(&mut own_cache);\n\n\n", "file_path": "crates/util/src/cmap.rs", "rank": 79, "score": 38852.80253084034 }, { "content": "\n\n (key.clone(), on_insert())\n\n });\n\n\n\n WriteValue {\n\n value: unsafe { std::mem::transmute(value) },\n\n _lock: shard,\n\n }\n\n }\n\n\n\n pub async fn get_or_default(&self, key: &K) -> ReadValue<'_, K, T, S>\n\n where\n\n K: Clone,\n\n T: Default,\n\n {\n\n self.get_or_insert(key, Default::default).await\n\n }\n\n\n\n pub async fn get_mut_or_default(&self, key: &K) -> WriteValue<'_, K, T, S>\n\n where\n", "file_path": "crates/util/src/cmap.rs", "rank": 80, "score": 38852.80253084034 }, { "content": " }\n\n\n\n pub fn generate(&self, time: u64) -> String {\n\n format!(\"{1:00$}\", DIGITS, self.generate_raw(time))\n\n }\n\n\n\n pub fn check(&self, token: u32, time: u64) -> bool {\n\n // TODO: Figure out this math\n\n // skew is measured in seconds\n\n //let n = if self.skew > 0 {\n\n // // convert the seconds into number of steps around current step\n\n // (self.skew * 2) / self.step + 1\n\n //} else {\n\n // 0\n\n //};\n\n\n\n let n = 0;\n\n\n\n let basestep = time / self.step - n;\n\n for i in 0..n * 2 + 1 {\n", "file_path": "crates/totp/src/lib.rs", "rank": 81, "score": 38852.80253084034 }, { "content": " }\n\n}\n\n\n\nimpl<K, T, S> CHashMap<K, T, S>\n\nwhere\n\n K: Hash + Eq,\n\n S: BuildHasher,\n\n{\n\n pub fn hash_builder(&self) -> &S {\n\n &self.hash_builder\n\n }\n\n\n\n pub async fn retain<F>(&self, f: F)\n\n where\n\n F: Fn(&K, &mut T) -> bool,\n\n {\n\n for shard in &self.shards {\n\n shard.write().await.retain(|k, v| {\n\n let retained = f(k, v);\n\n if !retained {\n", "file_path": "crates/util/src/cmap.rs", "rank": 82, "score": 38852.80253084034 }, { "content": " }\n\n\n\n pub fn try_maybe_contains_hash(&self, hash: u64) -> bool {\n\n let shard_idx = hash as usize % self.shards.len();\n\n\n\n let shard = unsafe { self.shards.get_unchecked(shard_idx) };\n\n\n\n if let Ok(shard) = shard.try_read() {\n\n shard.raw_entry().from_hash(hash, |_| true).is_some()\n\n } else {\n\n false\n\n }\n\n }\n\n\n\n pub async fn contains<Q: ?Sized>(&self, key: &Q) -> bool\n\n where\n\n K: Borrow<Q>,\n\n Q: Hash + Eq,\n\n {\n\n self.contains_hash(self.hash_and_shard(key).0).await\n", "file_path": "crates/util/src/cmap.rs", "rank": 83, "score": 38852.80253084034 }, { "content": " }\n\n\n\n pub async fn contains_hash(&self, hash: u64) -> bool {\n\n let shard_idx = hash as usize % self.shards.len();\n\n\n\n let shard = unsafe { self.shards.get_unchecked(shard_idx) };\n\n\n\n shard.read().await.raw_entry().from_hash(hash, |_| true).is_some()\n\n }\n\n\n\n #[inline]\n\n fn hash_and_shard<Q: ?Sized>(&self, key: &Q) -> (u64, usize)\n\n where\n\n Q: Hash + Eq,\n\n {\n\n let mut hasher = self.hash_builder.build_hasher();\n\n key.hash(&mut hasher);\n\n let hash = hasher.finish();\n\n (hash, hash as usize % self.shards.len())\n\n }\n", "file_path": "crates/util/src/cmap.rs", "rank": 84, "score": 38852.80253084034 }, { "content": "#![allow(unused)]\n\n\n\npub struct Encoding {\n\n base_map: [u8; 256],\n\n leader: u8,\n\n}\n\n\n", "file_path": "crates/util/src/base.rs", "rank": 85, "score": 38852.80253084034 }, { "content": "#[derive(Clone, Copy)]\n\npub enum FromZ85Error {\n\n /// The input contained a character not part of the Z85 format\n\n InvalidZ85Byte(u8, usize),\n\n /// The input had an invalid length\n\n InvalidZ85Length(usize),\n\n}\n\n\n\nimpl fmt::Debug for FromZ85Error {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match *self {\n\n InvalidZ85Byte(ch, idx) => write!(f, \"Invalid character '{}' at position {}.\", ch, idx),\n\n InvalidZ85Length(len) => write!(f, \"Invalid length {}.\", len),\n\n }\n\n }\n\n}\n\n\n\nimpl error::Error for FromZ85Error {\n\n fn description(&self) -> &str {\n\n match *self {\n", "file_path": "crates/blurhash/src/base85.rs", "rank": 86, "score": 38852.80253084034 }, { "content": " let (hash, shard_idx) = self.hash_and_shard(key);\n\n\n\n let shard = unsafe { self.shards.get_unchecked(shard_idx).read().await };\n\n\n\n match shard.raw_entry().from_key_hashed_nocheck(hash, key) {\n\n Some((_, value)) => Some(ReadValue {\n\n // cast lifetime, but it's fine because we own it while the lock is valid\n\n value: unsafe { std::mem::transmute(value) },\n\n _lock: shard,\n\n }),\n\n None => None,\n\n }\n\n }\n\n\n\n pub async fn get_mut<Q: ?Sized>(&self, key: &Q) -> Option<WriteValue<'_, K, T, S>>\n\n where\n\n K: Borrow<Q>,\n\n Q: Hash + Eq,\n\n {\n\n let (hash, shard_idx) = self.hash_and_shard(key);\n", "file_path": "crates/util/src/cmap.rs", "rank": 87, "score": 38852.80253084034 }, { "content": " 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n\n 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n\n];\n\n\n\nconst fn ceil_div(n: u8, d: u8) -> u8 {\n\n let r = n / d;\n\n if n % d == 0 {\n\n r\n\n } else {\n\n r + 1\n\n }\n\n}\n", "file_path": "crates/util/src/base.rs", "rank": 88, "score": 38852.80253084034 }, { "content": " {\n\n match self.0.take() {\n\n None => serializer.serialize_none(),\n\n Some(seq) => {\n\n let iter = seq.into_iter();\n\n let mut seq = serializer.serialize_seq(iter.size_hint().1)?;\n\n\n\n for value in iter {\n\n seq.serialize_element(&value)?;\n\n }\n\n\n\n seq.end()\n\n }\n\n }\n\n }\n\n}\n", "file_path": "crates/util/src/serde.rs", "rank": 89, "score": 38852.80253084034 }, { "content": " #[test]\n\n fn test_hex() {\n\n let num: u64 = 0xFF_DEAD_BEEF_EE_AA_04;\n\n\n\n let h = HexidecimalInt(num);\n\n\n\n let a = h.to_string();\n\n let b = h.to_hex();\n\n\n\n assert_eq!(a, b);\n\n\n\n assert_eq!(HexidecimalInt::<u64>::from_str(a.as_str()), Ok(h));\n\n }\n\n}\n", "file_path": "crates/util/src/hex.rs", "rank": 90, "score": 38852.80253084034 }, { "content": " type Err = hex::FromHexError;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n let mut bytes = T::Bytes::default();\n\n // NOTE: This decodes as Big Endian\n\n hex::decode_to_slice(s, bytes.as_mut())?;\n\n Ok(HexidecimalInt(T::__from_be_bytes(bytes)))\n\n }\n\n}\n\n\n\nimpl<T: SafeInt> Display for HexidecimalInt<T> {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {\n\n write!(f, \"{:01$x}\", self.0, std::mem::size_of::<Self>() * 2)\n\n }\n\n}\n\n\n\nimpl<T: SafeInt> HexidecimalInt<T> {\n\n pub fn to_hex(&self) -> SmolStr {\n\n let bytes = self.0.__to_be_bytes();\n\n let mut buf = T::HexBytes::default();\n", "file_path": "crates/util/src/hex.rs", "rank": 91, "score": 38852.80253084034 }, { "content": " assert!(!is_of_age_inner(\n\n min_age,\n\n datetime!(2020 - 03 - 27 23:59),\n\n date!(2007 - 03 - 28)\n\n ));\n\n\n\n assert!(is_of_age_inner(\n\n min_age,\n\n datetime!(2020 - 03 - 28 00:00),\n\n date!(2007 - 03 - 28)\n\n ));\n\n\n\n assert!(is_of_age_inner(\n\n min_age,\n\n datetime!(2020 - 06 - 28 00:00),\n\n date!(2007 - 06 - 28)\n\n ));\n\n\n\n assert!(!is_of_age_inner(\n\n min_age,\n", "file_path": "crates/util/src/time.rs", "rank": 92, "score": 38852.80253084034 }, { "content": "\n\n pub async fn get_cloned<Q: ?Sized>(&self, key: &Q) -> Option<T>\n\n where\n\n K: Borrow<Q>,\n\n Q: Hash + Eq,\n\n T: Clone,\n\n {\n\n let (hash, shard_idx) = self.hash_and_shard(key);\n\n let shard = unsafe { self.shards.get_unchecked(shard_idx).read().await };\n\n shard\n\n .raw_entry()\n\n .from_key_hashed_nocheck(hash, key)\n\n .map(|(_, value)| value.clone())\n\n }\n\n\n\n pub async fn get<Q: ?Sized>(&self, key: &Q) -> Option<ReadValue<'_, K, T, S>>\n\n where\n\n K: Borrow<Q>,\n\n Q: Hash + Eq,\n\n {\n", "file_path": "crates/util/src/cmap.rs", "rank": 93, "score": 38852.80253084034 }, { "content": "//pub mod base62;\n\npub mod base;\n\npub mod base64;\n\npub mod cmap;\n\npub mod hex;\n\npub mod laggy;\n\npub mod likely;\n\npub mod rng;\n\npub mod serde;\n\npub mod string;\n\npub mod time;\n", "file_path": "crates/util/src/lib.rs", "rank": 94, "score": 38852.80253084034 }, { "content": " }\n\n }\n\n }\n\n }\n\n\n\n // TODO: Same as with `batch_read`\n\n pub async fn batch_write<'a, Q: 'a, I, F>(\n\n &self,\n\n keys: I,\n\n cache: Option<&mut Vec<(&'a Q, u64, usize)>>,\n\n mut f: F,\n\n ) where\n\n K: Borrow<Q>,\n\n Q: Hash + Eq,\n\n I: IntoIterator<Item = &'a Q>,\n\n F: FnMut(&'a Q, hashbrown::hash_map::RawEntryMut<K, T, S>),\n\n {\n\n let mut own_cache = Vec::new();\n\n let cache = cache.unwrap_or(&mut own_cache);\n\n\n", "file_path": "crates/util/src/cmap.rs", "rank": 95, "score": 38852.80253084034 }, { "content": " self.batch_hash_and_sort(keys, cache);\n\n\n\n if cache.is_empty() {\n\n return;\n\n }\n\n\n\n let mut i = 0;\n\n loop {\n\n let current_shard = cache[i].2;\n\n let mut shard = unsafe { self.shards.get_unchecked(current_shard).write().await };\n\n\n\n while cache[i].2 == current_shard {\n\n f(\n\n cache[i].0,\n\n shard\n\n .raw_entry_mut()\n\n .from_key_hashed_nocheck(cache[i].1, cache[i].0),\n\n );\n\n i += 1;\n\n\n\n if i >= cache.len() {\n\n return;\n\n }\n\n }\n\n }\n\n }\n\n}\n", "file_path": "crates/util/src/cmap.rs", "rank": 96, "score": 38852.80253084034 }, { "content": " datetime!(2020 - 06 - 27 23:59),\n\n date!(2007 - 06 - 28)\n\n ));\n\n\n\n assert!(is_of_age_inner(\n\n min_age,\n\n datetime!(2020 - 06 - 26 23:59),\n\n date!(2007 - 06 - 25)\n\n ));\n\n }\n\n}\n", "file_path": "crates/util/src/time.rs", "rank": 97, "score": 38852.80253084034 }, { "content": "\n\n let mut shard = unsafe { self.shards.get_unchecked(shard_idx).write().await };\n\n\n\n match shard.raw_entry_mut().from_key_hashed_nocheck(hash, key) {\n\n RawEntryMut::Occupied(mut entry) => Some(WriteValue {\n\n // cast lifetime, but it's fine because we own it while the lock is valid\n\n value: unsafe { std::mem::transmute(entry.get_mut()) },\n\n _lock: shard,\n\n }),\n\n _ => None,\n\n }\n\n }\n\n\n\n pub async fn entry<Q: ?Sized>(&self, key: &Q) -> EntryValue<'_, K, T, S>\n\n where\n\n K: Borrow<Q>,\n\n Q: Hash + Eq,\n\n {\n\n let (hash, shard_idx) = self.hash_and_shard(key);\n\n\n", "file_path": "crates/util/src/cmap.rs", "rank": 98, "score": 38852.80253084034 }, { "content": " let mut shard = unsafe { self.shards.get_unchecked(shard_idx).write().await };\n\n\n\n let entry = shard.raw_entry_mut().from_key_hashed_nocheck(hash, key);\n\n\n\n EntryValue {\n\n entry: unsafe { std::mem::transmute(entry) },\n\n lock: shard,\n\n }\n\n }\n\n\n\n pub async fn remove<Q: ?Sized>(&self, key: &Q) -> Option<T>\n\n where\n\n K: Borrow<Q>,\n\n Q: Hash + Eq,\n\n {\n\n let (hash, shard_idx) = self.hash_and_shard(&key);\n\n let mut shard = unsafe { self.shards.get_unchecked(shard_idx).write().await };\n\n\n\n match shard.raw_entry_mut().from_key_hashed_nocheck(hash, key) {\n\n RawEntryMut::Occupied(occupied) => {\n", "file_path": "crates/util/src/cmap.rs", "rank": 99, "score": 38852.80253084034 } ]
Rust
src/db/model/stardust/block/output/nft.rs
grtlr/inx-chronicle
9d9da951b97c0db2c65b66eb87e0491c653863f3
use std::str::FromStr; use bee_block_stardust::output as bee; use serde::{Deserialize, Serialize}; use super::{Feature, NativeToken, OutputAmount, UnlockCondition}; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct NftId(#[serde(with = "serde_bytes")] pub Box<[u8]>); impl NftId { pub fn from_output_id_str(s: &str) -> Result<Self, crate::db::error::Error> { Ok(bee::NftId::from(bee::OutputId::from_str(s)?).into()) } } impl From<bee::NftId> for NftId { fn from(value: bee::NftId) -> Self { Self(value.to_vec().into_boxed_slice()) } } impl TryFrom<NftId> for bee::NftId { type Error = crate::db::error::Error; fn try_from(value: NftId) -> Result<Self, Self::Error> { Ok(bee::NftId::new(value.0.as_ref().try_into()?)) } } impl FromStr for NftId { type Err = crate::db::error::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(bee::NftId::from_str(s)?.into()) } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct NftOutput { amount: OutputAmount, native_tokens: Box<[NativeToken]>, nft_id: NftId, unlock_conditions: Box<[UnlockCondition]>, features: Box<[Feature]>, immutable_features: Box<[Feature]>, } impl From<&bee::NftOutput> for NftOutput { fn from(value: &bee::NftOutput) -> Self { Self { amount: value.amount(), native_tokens: value.native_tokens().iter().map(Into::into).collect(), nft_id: (*value.nft_id()).into(), unlock_conditions: value.unlock_conditions().iter().map(Into::into).collect(), features: value.features().iter().map(Into::into).collect(), immutable_features: value.immutable_features().iter().map(Into::into).collect(), } } } impl TryFrom<NftOutput> for bee::NftOutput { type Error = crate::db::error::Error; fn try_from(value: NftOutput) -> Result<Self, Self::Error> { Ok(Self::build_with_amount(value.amount, value.nft_id.try_into()?)? .with_native_tokens( Vec::from(value.native_tokens) .into_iter() .map(TryInto::try_into) .collect::<Result<Vec<_>, _>>()?, ) .with_unlock_conditions( Vec::from(value.unlock_conditions) .into_iter() .map(TryInto::try_into) .collect::<Result<Vec<_>, _>>()?, ) .with_features( Vec::from(value.features) .into_iter() .map(TryInto::try_into) .collect::<Result<Vec<_>, _>>()?, ) .with_immutable_features( Vec::from(value.immutable_features) .into_iter() .map(TryInto::try_into) .collect::<Result<Vec<_>, _>>()?, ) .finish()?) } } #[cfg(test)] pub(crate) mod test { use mongodb::bson::{from_bson, to_bson}; use super::*; use crate::db::model::stardust::block::output::{ feature::test::{get_test_issuer_block, get_test_metadata_block, get_test_sender_block, get_test_tag_block}, native_token::test::get_test_native_token, unlock_condition::test::{ get_test_address_condition, get_test_expiration_condition, get_test_storage_deposit_return_condition, get_test_timelock_condition, }, }; #[test] fn test_nft_id_bson() { let nft_id = NftId::from(rand_nft_id()); let bson = to_bson(&nft_id).unwrap(); assert_eq!(nft_id, from_bson::<NftId>(bson).unwrap()); } #[test] fn test_nft_output_bson() { let output = get_test_nft_output(); let bson = to_bson(&output).unwrap(); assert_eq!(output, from_bson::<NftOutput>(bson).unwrap()); } pub(crate) fn rand_nft_id() -> bee::NftId { bee_test::rand::bytes::rand_bytes_array().into() } pub(crate) fn get_test_nft_output() -> NftOutput { NftOutput::from( &bee::NftOutput::build_with_amount(100, rand_nft_id()) .unwrap() .with_native_tokens(vec![get_test_native_token().try_into().unwrap()]) .with_unlock_conditions(vec![ get_test_address_condition(bee_test::rand::address::rand_address().into()) .try_into() .unwrap(), get_test_storage_deposit_return_condition(bee_test::rand::address::rand_address().into(), 1) .try_into() .unwrap(), get_test_timelock_condition(1, 1).try_into().unwrap(), get_test_expiration_condition(bee_test::rand::address::rand_address().into(), 1, 1) .try_into() .unwrap(), ]) .with_features(vec![ get_test_sender_block(bee_test::rand::address::rand_address().into()) .try_into() .unwrap(), get_test_metadata_block().try_into().unwrap(), get_test_tag_block().try_into().unwrap(), ]) .with_immutable_features(vec![ get_test_issuer_block(bee_test::rand::address::rand_address().into()) .try_into() .unwrap(), get_test_metadata_block().try_into().unwrap(), ]) .finish() .unwrap(), ) } }
use std::str::FromStr; use bee_block_stardust::output as bee; use serde::{Deserialize, Serialize}; use super::{Feature, NativeToken, OutputAmount, UnlockCondition}; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct NftId(#[serde(with = "serde_bytes")] pub Box<[u8]>); impl NftId { pub fn from_output_id_str(s: &str) -> Result<Self, crate::db::error::Error> { Ok(bee::NftId::from(bee::OutputId::from_str(s)?).into()) } } impl From<bee::NftId> for NftId { fn from(value: bee::NftId) -> Self { Self(value.to_vec().into_boxed_slice()) } } impl TryFrom<NftId> for bee::NftId { type Error = crate::db::error::Error; fn try_from(value: NftId) -> Result<Self, Self::Error> { Ok(bee::NftId::new(value.0.as_ref().try_into()?)) } } impl FromStr for NftId { type Err = crate::db::error::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(bee::NftId::from_str(s)?.into()) } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct NftOutput { amount: OutputAmount, native_tokens: Box<[NativeToken]>, nft_id: NftId, unlock_conditions: Box<[UnlockCondition]>, features: Box<[Feature]>, immutable_features: Box<[Feature]>, } impl From<&bee::NftOutput> for NftOutput { fn from(value: &bee::NftOutput) -> Self { Self { amount: value.amount(), native_tokens: value.native_tokens().iter().map(Into::into).collect(), nft_id: (*value.nft_id()).into(), unlock_conditions: value.unlock_conditions().iter().map(Into::into).collect(), features: value.features().iter().map(Into::into).collect(), immutable_features: value.immutable_features().iter().map(Into::into).collect(), } } } impl TryFrom<NftOutput> for bee::NftOutput { type Error = crate::db::error::Error; fn try_from(value: NftOutput) -> Result<Self, Self::Error> { Ok(Self::build_with_amount(value.amount, value.nft_id.try_into()?)? .with_native_tokens( Vec::from(value.native_tokens) .into_iter() .map(TryInto::try_into) .collect::<Result<Vec<_>, _>>()?, ) .with_unlock_conditions( Vec::from(value.unlock_conditions) .into_iter() .map(TryInto::try_into) .co
.try_into() .unwrap(), get_test_metadata_block().try_into().unwrap(), get_test_tag_block().try_into().unwrap(), ]) .with_immutable_features(vec![ get_test_issuer_block(bee_test::rand::address::rand_address().into()) .try_into() .unwrap(), get_test_metadata_block().try_into().unwrap(), ]) .finish() .unwrap(), ) } }
llect::<Result<Vec<_>, _>>()?, ) .with_features( Vec::from(value.features) .into_iter() .map(TryInto::try_into) .collect::<Result<Vec<_>, _>>()?, ) .with_immutable_features( Vec::from(value.immutable_features) .into_iter() .map(TryInto::try_into) .collect::<Result<Vec<_>, _>>()?, ) .finish()?) } } #[cfg(test)] pub(crate) mod test { use mongodb::bson::{from_bson, to_bson}; use super::*; use crate::db::model::stardust::block::output::{ feature::test::{get_test_issuer_block, get_test_metadata_block, get_test_sender_block, get_test_tag_block}, native_token::test::get_test_native_token, unlock_condition::test::{ get_test_address_condition, get_test_expiration_condition, get_test_storage_deposit_return_condition, get_test_timelock_condition, }, }; #[test] fn test_nft_id_bson() { let nft_id = NftId::from(rand_nft_id()); let bson = to_bson(&nft_id).unwrap(); assert_eq!(nft_id, from_bson::<NftId>(bson).unwrap()); } #[test] fn test_nft_output_bson() { let output = get_test_nft_output(); let bson = to_bson(&output).unwrap(); assert_eq!(output, from_bson::<NftOutput>(bson).unwrap()); } pub(crate) fn rand_nft_id() -> bee::NftId { bee_test::rand::bytes::rand_bytes_array().into() } pub(crate) fn get_test_nft_output() -> NftOutput { NftOutput::from( &bee::NftOutput::build_with_amount(100, rand_nft_id()) .unwrap() .with_native_tokens(vec![get_test_native_token().try_into().unwrap()]) .with_unlock_conditions(vec![ get_test_address_condition(bee_test::rand::address::rand_address().into()) .try_into() .unwrap(), get_test_storage_deposit_return_condition(bee_test::rand::address::rand_address().into(), 1) .try_into() .unwrap(), get_test_timelock_condition(1, 1).try_into().unwrap(), get_test_expiration_condition(bee_test::rand::address::rand_address().into(), 1, 1) .try_into() .unwrap(), ]) .with_features(vec![ get_test_sender_block(bee_test::rand::address::rand_address().into())
random
[ { "content": "/// Spawn a tokio task. The provided name will be used to configure the task if console tracing is enabled.\n\npub fn spawn_task<F>(name: &str, task: F) -> tokio::task::JoinHandle<F::Output>\n\nwhere\n\n F: 'static + Future + Send,\n\n F::Output: 'static + Send,\n\n{\n\n log::trace!(\"Spawning task {}\", name);\n\n #[cfg(all(tokio_unstable, feature = \"console\"))]\n\n return tokio::task::Builder::new().name(name).spawn(task);\n\n #[cfg(not(all(tokio_unstable, feature = \"console\")))]\n\n return tokio::spawn(task);\n\n}\n", "file_path": "src/runtime/mod.rs", "rank": 0, "score": 87670.2227589914 }, { "content": "#[allow(missing_docs)]\n\npub trait AsyncFn<'a, O> {\n\n type Output: 'a + Future<Output = O> + Send;\n\n fn call(self, cx: &'a mut RuntimeScope) -> Self::Output;\n\n}\n\nimpl<'a, Fn, Fut, O> AsyncFn<'a, O> for Fn\n\nwhere\n\n Fn: FnOnce(&'a mut RuntimeScope) -> Fut,\n\n Fut: 'a + Future<Output = O> + Send,\n\n{\n\n type Output = Fut;\n\n fn call(self, cx: &'a mut RuntimeScope) -> Self::Output {\n\n (self)(cx)\n\n }\n\n}\n\n\n\n/// Starting point for the runtime.\n\npub struct Runtime;\n\n\n\nimpl Runtime {\n\n /// Launches a new root runtime scope.\n", "file_path": "src/runtime/mod.rs", "rank": 1, "score": 66805.71014828084 }, { "content": "type Receiver<A> = ShutdownStream<EnvelopeStream<A>>;\n\n\n\n/// The context that an actor can use to interact with the runtime.\n\npub struct ActorContext<A: Actor> {\n\n pub(crate) scope: RuntimeScope,\n\n pub(crate) handle: Addr<A>,\n\n pub(crate) receiver: Receiver<A>,\n\n}\n\n\n\nimpl<A: Actor> ActorContext<A> {\n\n pub(crate) fn new(scope: RuntimeScope, handle: Addr<A>, receiver: Receiver<A>) -> Self {\n\n Self {\n\n handle,\n\n scope,\n\n receiver,\n\n }\n\n }\n\n\n\n /// Spawn a new supervised child actor.\n\n pub async fn spawn_child<OtherA, Cfg>(&mut self, actor: Cfg) -> Addr<OtherA>\n", "file_path": "src/runtime/actor/context.rs", "rank": 2, "score": 39006.20110108172 }, { "content": "/// Helper methods for spawning actors.\n\npub trait ConfigureActor: Actor {\n\n /// Merges acustom stream in addition to the event stream.\n\n fn with_stream<S, E>(self, stream: S) -> SpawnConfig<Self>\n\n where\n\n S: 'static + Stream<Item = E> + Unpin + Send,\n\n E: 'static + DynEvent<Self>,\n\n {\n\n SpawnConfig::<Self>::new(self).with_stream(stream)\n\n }\n\n\n\n /// Sets whether the actor's address should be added to the registry.\n\n fn with_registration(self, enable: bool) -> SpawnConfig<Self> {\n\n SpawnConfig::<Self>::new(self).with_registration(enable)\n\n }\n\n}\n\nimpl<A: Actor> ConfigureActor for A {}\n", "file_path": "src/runtime/config.rs", "rank": 3, "score": 36690.197974326926 }, { "content": " value.parse::<Self::Value>().map_err(serde::de::Error::custom)\n\n }\n\n }\n\n\n\n deserializer.deserialize_str(Helper(PhantomData))\n\n }\n\n\n\n /// Serialize T using [`Display`]\n\n pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n T: Display,\n\n S: Serializer,\n\n {\n\n serializer.collect_str(&value)\n\n }\n\n}\n", "file_path": "src/types/mod.rs", "rank": 4, "score": 34993.24283178644 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\n#![allow(missing_docs)] // TODO: Add missing comments\n\n\n\n// TODO Rework visibility of these modules\n\n\n\npub mod error;\n\n#[cfg(feature = \"stardust\")]\n\npub mod stardust;\n\n\n\npub mod stringify {\n\n use std::{fmt::Display, marker::PhantomData, str::FromStr};\n\n\n\n use serde::{de::Visitor, Deserializer, Serializer};\n\n\n\n /// Deserialize T using [`FromStr`]\n\n pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>\n\n where\n\n D: Deserializer<'de>,\n", "file_path": "src/types/mod.rs", "rank": 5, "score": 34990.6013099337 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse std::array::TryFromSliceError;\n\n\n\nuse thiserror::Error;\n\n\n\n#[allow(missing_docs)]\n\n#[derive(Debug, Error)]\n\npub enum Error {\n\n #[error(transparent)]\n\n BeeError(#[from] bee_block_stardust::Error),\n\n #[error(\"failed to convert to model type: {0}\")]\n\n DtoEncodingFailed(#[from] TryFromSliceError),\n\n}\n", "file_path": "src/db/error.rs", "rank": 6, "score": 34984.49854501665 }, { "content": " T: FromStr,\n\n T::Err: Display,\n\n {\n\n struct Helper<S>(PhantomData<S>);\n\n\n\n impl<'de, S> Visitor<'de> for Helper<S>\n\n where\n\n S: FromStr,\n\n <S as FromStr>::Err: Display,\n\n {\n\n type Value = S;\n\n\n\n fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(formatter, \"a string\")\n\n }\n\n\n\n fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>\n\n where\n\n E: serde::de::Error,\n\n {\n", "file_path": "src/types/mod.rs", "rank": 7, "score": 34983.14690040162 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse std::error::Error;\n\n\n\nuse thiserror::Error;\n\n\n\nuse super::{actor::addr::SendError, registry::ScopeId};\n\n\n\n#[allow(missing_docs)]\n\n#[derive(Error, Debug)]\n\npub enum RuntimeError {\n\n #[error(\"Scope {0:x} aborted\")]\n\n AbortedScope(ScopeId),\n\n #[error(\"Actor exited with error: {0}\")]\n\n ActorError(String),\n\n #[error(\"Dependency notification canceled\")]\n\n CanceledDepNotification,\n\n #[error(\"Invalid scope\")]\n\n InvalidScope,\n", "file_path": "src/runtime/error.rs", "rank": 8, "score": 34980.83799038266 }, { "content": " #[error(\"Missing dependency: {0}\")]\n\n MissingDependency(String),\n\n #[error(\"Error launching scope: {0}\")]\n\n ScopeLaunchError(Box<dyn Error + Send + Sync>),\n\n #[error(transparent)]\n\n SendError(#[from] SendError),\n\n #[error(\"Task exited with error: {0}\")]\n\n TaskError(Box<dyn Error + Send + Sync>),\n\n}\n", "file_path": "src/runtime/error.rs", "rank": 9, "score": 34973.23166349134 }, { "content": "#[async_trait]\n\npub trait HandleEvent<E>: Actor {\n\n #[allow(missing_docs)]\n\n async fn handle_event(\n\n &mut self,\n\n cx: &mut ActorContext<Self>,\n\n event: E,\n\n state: &mut Self::State,\n\n ) -> Result<(), Self::Error>;\n\n}\n\n\n", "file_path": "src/runtime/actor/event.rs", "rank": 10, "score": 34449.105504244224 }, { "content": "/// A dynamic event that can be sent to an actor which implements `HandleEvent` for it.\n\npub trait DynEvent<A: Actor>: Send {\n\n #[allow(missing_docs)]\n\n fn handle<'a>(\n\n self: Box<Self>,\n\n cx: &'a mut ActorContext<A>,\n\n actor: &'a mut A,\n\n state: &'a mut A::State,\n\n ) -> Pin<Box<dyn core::future::Future<Output = Result<(), A::Error>> + Send + 'a>>\n\n where\n\n Self: 'a;\n\n}\n\n\n\nimpl<A, E> DynEvent<A> for E\n\nwhere\n\n A: HandleEvent<E>,\n\n E: Send,\n\n{\n\n fn handle<'a>(\n\n self: Box<Self>,\n\n cx: &'a mut ActorContext<A>,\n", "file_path": "src/runtime/actor/event.rs", "rank": 11, "score": 34093.85891979395 }, { "content": "#[async_trait]\n\npub trait Actor: Send + Sync + Sized {\n\n /// Custom data that is passed to all actor methods.\n\n type State: Send;\n\n /// Custom error type that is returned by all actor methods.\n\n type Error: Error + Send;\n\n\n\n /// Set this actor's name, primarily for debugging purposes.\n\n fn name(&self) -> Cow<'static, str> {\n\n std::any::type_name::<Self>().into()\n\n }\n\n\n\n /// Start the actor, and create the internal state.\n\n async fn init(&mut self, cx: &mut ActorContext<Self>) -> Result<Self::State, Self::Error>;\n\n\n\n /// Run the actor event loop\n\n async fn run(&mut self, cx: &mut ActorContext<Self>, state: &mut Self::State) -> Result<(), Self::Error> {\n\n while let Some(evt) = cx.inbox().next().await {\n\n // Handle the event\n\n evt.handle(cx, self, state).await?;\n\n }\n", "file_path": "src/runtime/actor/mod.rs", "rank": 12, "score": 34093.85891979395 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse thiserror::Error;\n\n\n\nuse super::Actor;\n\n\n\n#[allow(missing_docs)]\n\n#[derive(Error, Debug)]\n\npub enum ActorError<A: Actor> {\n\n #[error(\"Actor aborted\")]\n\n Aborted,\n\n #[error(\"Actor panicked\")]\n\n Panic,\n\n #[error(\"Actor error: {0}\")]\n\n Result(A::Error),\n\n}\n", "file_path": "src/runtime/actor/error.rs", "rank": 13, "score": 33738.926213888946 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::output::feature as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::db::{self, model::stardust::block::Address};\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(tag = \"kind\")]\n\npub enum Feature {\n\n #[serde(rename = \"sender\")]\n\n Sender { address: Address },\n\n #[serde(rename = \"issuer\")]\n\n Issuer { address: Address },\n\n #[serde(rename = \"metadata\")]\n\n Metadata {\n\n #[serde(with = \"serde_bytes\")]\n\n data: Box<[u8]>,\n\n },\n", "file_path": "src/db/model/stardust/block/output/feature.rs", "rank": 14, "score": 30478.51565697097 }, { "content": " data: b.tag().to_vec().into_boxed_slice(),\n\n },\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<Feature> for bee::Feature {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: Feature) -> Result<Self, Self::Error> {\n\n Ok(match value {\n\n Feature::Sender { address } => bee::Feature::Sender(bee::SenderFeature::new(address.try_into()?)),\n\n Feature::Issuer { address } => bee::Feature::Issuer(bee::IssuerFeature::new(address.try_into()?)),\n\n Feature::Metadata { data } => bee::Feature::Metadata(bee::MetadataFeature::new(data.into())?),\n\n Feature::Tag { data } => bee::Feature::Tag(bee::TagFeature::new(data.into())?),\n\n })\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/db/model/stardust/block/output/feature.rs", "rank": 15, "score": 30472.99062937429 }, { "content": " #[serde(rename = \"tag\")]\n\n Tag {\n\n #[serde(with = \"serde_bytes\")]\n\n data: Box<[u8]>,\n\n },\n\n}\n\n\n\nimpl From<&bee::Feature> for Feature {\n\n fn from(value: &bee::Feature) -> Self {\n\n match value {\n\n bee::Feature::Sender(a) => Self::Sender {\n\n address: (*a.address()).into(),\n\n },\n\n bee::Feature::Issuer(a) => Self::Issuer {\n\n address: (*a.address()).into(),\n\n },\n\n bee::Feature::Metadata(b) => Self::Metadata {\n\n data: b.data().to_vec().into_boxed_slice(),\n\n },\n\n bee::Feature::Tag(b) => Self::Tag {\n", "file_path": "src/db/model/stardust/block/output/feature.rs", "rank": 16, "score": 30470.540946128946 }, { "content": "pub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn test_feature_bson() {\n\n let block = get_test_sender_block(bee_test::rand::address::rand_address().into());\n\n let bson = to_bson(&block).unwrap();\n\n assert_eq!(block, from_bson::<Feature>(bson).unwrap());\n\n\n\n let block = get_test_issuer_block(bee_test::rand::address::rand_address().into());\n\n let bson = to_bson(&block).unwrap();\n\n assert_eq!(block, from_bson::<Feature>(bson).unwrap());\n\n\n\n let block = get_test_metadata_block();\n\n let bson = to_bson(&block).unwrap();\n\n assert_eq!(block, from_bson::<Feature>(bson).unwrap());\n\n\n\n let block = get_test_tag_block();\n", "file_path": "src/db/model/stardust/block/output/feature.rs", "rank": 17, "score": 30469.498698125066 }, { "content": " let bson = to_bson(&block).unwrap();\n\n assert_eq!(block, from_bson::<Feature>(bson).unwrap());\n\n }\n\n\n\n pub(crate) fn get_test_sender_block(address: Address) -> Feature {\n\n Feature::Sender { address }\n\n }\n\n\n\n pub(crate) fn get_test_issuer_block(address: Address) -> Feature {\n\n Feature::Issuer { address }\n\n }\n\n\n\n pub(crate) fn get_test_metadata_block() -> Feature {\n\n Feature::Metadata {\n\n data: \"Foo\".as_bytes().to_vec().into_boxed_slice(),\n\n }\n\n }\n\n\n\n pub(crate) fn get_test_tag_block() -> Feature {\n\n Feature::Tag {\n\n data: \"Bar\".as_bytes().to_vec().into_boxed_slice(),\n\n }\n\n }\n\n}\n", "file_path": "src/db/model/stardust/block/output/feature.rs", "rank": 18, "score": 30465.46247948909 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse std::str::FromStr;\n\n\n\nuse bee_block_stardust::output as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::{feature::Feature, native_token::NativeToken, unlock_condition::UnlockCondition, OutputAmount};\n\nuse crate::db;\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(transparent)]\n\npub struct AliasId(#[serde(with = \"serde_bytes\")] pub Box<[u8]>);\n\n\n\nimpl AliasId {\n\n pub fn from_output_id_str(s: &str) -> Result<Self, db::error::Error> {\n\n Ok(bee::AliasId::from(bee::OutputId::from_str(s)?).into())\n\n }\n\n}\n", "file_path": "src/db/model/stardust/block/output/alias.rs", "rank": 20, "score": 36.09001199915694 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse std::{mem::size_of, str::FromStr};\n\n\n\nuse bee_block_stardust::output as bee;\n\nuse primitive_types::U256;\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(transparent)]\n\npub struct TokenAmount(#[serde(with = \"serde_bytes\")] pub Box<[u8]>);\n\n\n\nimpl From<&U256> for TokenAmount {\n\n fn from(value: &U256) -> Self {\n\n let mut amount = vec![0; size_of::<U256>()];\n\n value.to_little_endian(&mut amount);\n\n Self(amount.into_boxed_slice())\n\n }\n\n}\n", "file_path": "src/db/model/stardust/block/output/native_token.rs", "rank": 21, "score": 34.612846308399554 }, { "content": " fn try_from(value: TokenId) -> Result<Self, Self::Error> {\n\n Ok(bee::TokenId::new(value.0.as_ref().try_into()?))\n\n }\n\n}\n\n\n\nimpl FromStr for TokenId {\n\n type Err = crate::db::error::Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n Ok(bee::TokenId::from_str(s)?.into())\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(tag = \"kind\")]\n\npub enum TokenScheme {\n\n #[serde(rename = \"simple\")]\n\n Simple {\n\n minted_tokens: TokenAmount,\n\n melted_tokens: TokenAmount,\n", "file_path": "src/db/model/stardust/block/output/native_token.rs", "rank": 22, "score": 34.36740987630125 }, { "content": "\n\nimpl TryFrom<Ed25519Address> for bee::Ed25519Address {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: Ed25519Address) -> Result<Self, Self::Error> {\n\n Ok(bee::Ed25519Address::new(value.0.as_ref().try_into()?))\n\n }\n\n}\n\n\n\nimpl FromStr for Ed25519Address {\n\n type Err = db::error::Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n Ok(bee::Ed25519Address::from_str(s)?.into())\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub enum Address {\n\n #[serde(rename = \"ed25519\")]\n", "file_path": "src/db/model/stardust/block/address.rs", "rank": 23, "score": 33.67548102198131 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::output as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct TreasuryOutput {\n\n #[serde(with = \"crate::db::model::util::stringify\")]\n\n amount: u64,\n\n}\n\n\n\nimpl From<&bee::TreasuryOutput> for TreasuryOutput {\n\n fn from(value: &bee::TreasuryOutput) -> Self {\n\n Self { amount: value.amount() }\n\n }\n\n}\n\n\n\nimpl TryFrom<TreasuryOutput> for bee::TreasuryOutput {\n\n type Error = crate::db::error::Error;\n", "file_path": "src/db/model/stardust/block/output/treasury.rs", "rank": 24, "score": 33.04334477958183 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::output as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::{Feature, NativeToken, OutputAmount, UnlockCondition};\n\nuse crate::db;\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct BasicOutput {\n\n #[serde(with = \"crate::db::model::util::stringify\")]\n\n pub amount: OutputAmount,\n\n pub native_tokens: Box<[NativeToken]>,\n\n pub unlock_conditions: Box<[UnlockCondition]>,\n\n pub features: Box<[Feature]>,\n\n}\n\n\n\nimpl From<&bee::BasicOutput> for BasicOutput {\n\n fn from(value: &bee::BasicOutput) -> Self {\n", "file_path": "src/db/model/stardust/block/output/basic.rs", "rank": 25, "score": 31.710407127840426 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse std::str::FromStr;\n\n\n\nuse bee_block_stardust::payload::milestone as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::db;\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(transparent)]\n\npub struct MilestoneId(#[serde(with = \"serde_bytes\")] pub Box<[u8]>);\n\n\n\nimpl From<bee::MilestoneId> for MilestoneId {\n\n fn from(value: bee::MilestoneId) -> Self {\n\n Self(value.to_vec().into_boxed_slice())\n\n }\n\n}\n\n\n", "file_path": "src/db/model/stardust/block/payload/milestone/milestone_id.rs", "rank": 26, "score": 30.106047655708498 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse std::str::FromStr;\n\n\n\nuse bee_block_stardust::address as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::{AliasId, NftId};\n\nuse crate::db;\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(transparent)]\n\npub struct Ed25519Address(#[serde(with = \"serde_bytes\")] pub Box<[u8]>);\n\n\n\nimpl From<bee::Ed25519Address> for Ed25519Address {\n\n fn from(value: bee::Ed25519Address) -> Self {\n\n Self(value.to_vec().into_boxed_slice())\n\n }\n\n}\n", "file_path": "src/db/model/stardust/block/address.rs", "rank": 27, "score": 29.557758216320487 }, { "content": "\n\nimpl From<TokenAmount> for U256 {\n\n fn from(value: TokenAmount) -> Self {\n\n U256::from_little_endian(value.0.as_ref())\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(transparent)]\n\npub struct TokenId(#[serde(with = \"serde_bytes\")] pub Box<[u8]>);\n\n\n\nimpl From<bee::TokenId> for TokenId {\n\n fn from(value: bee::TokenId) -> Self {\n\n Self(value.to_vec().into_boxed_slice())\n\n }\n\n}\n\n\n\nimpl TryFrom<TokenId> for bee::TokenId {\n\n type Error = crate::db::error::Error;\n\n\n", "file_path": "src/db/model/stardust/block/output/native_token.rs", "rank": 28, "score": 29.393494374262996 }, { "content": " fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n Ok(bee::TransactionId::from_str(s)?.into())\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct TransactionPayload {\n\n pub id: TransactionId,\n\n pub essence: TransactionEssence,\n\n pub unlocks: Box<[Unlock]>,\n\n}\n\n\n\nimpl From<&bee::TransactionPayload> for TransactionPayload {\n\n fn from(value: &bee::TransactionPayload) -> Self {\n\n Self {\n\n id: value.id().into(),\n\n essence: value.essence().into(),\n\n unlocks: value.unlocks().iter().map(Into::into).collect(),\n\n }\n\n }\n", "file_path": "src/db/model/stardust/block/payload/transaction.rs", "rank": 29, "score": 28.72080659119756 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse std::str::FromStr;\n\n\n\nuse bee_block_stardust as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::db;\n\n\n\n#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Hash, Ord, PartialOrd, Eq)]\n\n#[serde(transparent)]\n\npub struct BlockId(#[serde(with = \"serde_bytes\")] pub Box<[u8]>);\n\n\n\nimpl BlockId {\n\n pub fn to_hex(&self) -> String {\n\n prefix_hex::encode(self.0.as_ref())\n\n }\n\n}\n\n\n", "file_path": "src/db/model/stardust/block/block_id.rs", "rank": 30, "score": 27.36981843211264 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse std::str::FromStr;\n\n\n\nuse bee_block_stardust::payload::transaction as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::db::{\n\n self,\n\n model::stardust::block::{Input, Output, Payload, Unlock},\n\n};\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(transparent)]\n\npub struct TransactionId(#[serde(with = \"serde_bytes\")] pub Box<[u8]>);\n\n\n\nimpl TransactionId {\n\n pub fn to_hex(&self) -> String {\n\n prefix_hex::encode(self.0.as_ref())\n", "file_path": "src/db/model/stardust/block/payload/transaction.rs", "rank": 31, "score": 26.64255921580733 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::payload as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::MilestoneId;\n\nuse crate::db;\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct TreasuryTransactionPayload {\n\n input_milestone_id: MilestoneId,\n\n #[serde(with = \"crate::db::model::util::stringify\")]\n\n output_amount: u64,\n\n}\n\n\n\nimpl From<&bee::TreasuryTransactionPayload> for TreasuryTransactionPayload {\n\n fn from(value: &bee::TreasuryTransactionPayload) -> Self {\n\n Self {\n\n input_milestone_id: (*value.input().milestone_id()).into(),\n", "file_path": "src/db/model/stardust/block/payload/treasury_transaction.rs", "rank": 32, "score": 26.611025616323033 }, { "content": " }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct AliasOutput {\n\n #[serde(with = \"crate::db::model::util::stringify\")]\n\n pub amount: OutputAmount,\n\n pub native_tokens: Box<[NativeToken]>,\n\n pub alias_id: AliasId,\n\n pub state_index: u32,\n\n #[serde(with = \"serde_bytes\")]\n\n pub state_metadata: Box<[u8]>,\n\n pub foundry_counter: u32,\n\n pub unlock_conditions: Box<[UnlockCondition]>,\n\n pub features: Box<[Feature]>,\n\n pub immutable_features: Box<[Feature]>,\n\n}\n\n\n\nimpl From<&bee::AliasOutput> for AliasOutput {\n\n fn from(value: &bee::AliasOutput) -> Self {\n", "file_path": "src/db/model/stardust/block/output/alias.rs", "rank": 33, "score": 26.149619843713786 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::output as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::{Feature, NativeToken, OutputAmount, TokenScheme, UnlockCondition};\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct FoundryOutput {\n\n #[serde(with = \"crate::db::model::util::stringify\")]\n\n amount: OutputAmount,\n\n native_tokens: Box<[NativeToken]>,\n\n #[serde(with = \"crate::db::model::util::stringify\")]\n\n serial_number: u32,\n\n token_scheme: TokenScheme,\n\n unlock_conditions: Box<[UnlockCondition]>,\n\n features: Box<[Feature]>,\n\n immutable_features: Box<[Feature]>,\n\n}\n", "file_path": "src/db/model/stardust/block/output/foundry.rs", "rank": 34, "score": 26.12426148443932 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nmod milestone_id;\n\n\n\nuse bee_block_stardust::payload::milestone as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\npub use self::milestone_id::MilestoneId;\n\nuse super::super::{Address, BlockId, Signature, TreasuryTransactionPayload};\n\nuse crate::db::{self, model::tangle::MilestoneIndex};\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct MilestonePayload {\n\n pub essence: MilestoneEssence,\n\n pub signatures: Box<[Signature]>,\n\n}\n\n\n\nimpl From<&bee::MilestonePayload> for MilestonePayload {\n\n fn from(value: &bee::MilestonePayload) -> Self {\n", "file_path": "src/db/model/stardust/block/payload/milestone/mod.rs", "rank": 36, "score": 25.179831518874128 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::input as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::{MilestoneId, OutputId};\n\nuse crate::db;\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(tag = \"kind\")]\n\npub enum Input {\n\n #[serde(rename = \"utxo\")]\n\n Utxo(OutputId),\n\n #[serde(rename = \"treasury\")]\n\n Treasury { milestone_id: MilestoneId },\n\n}\n\n\n\nimpl From<&bee::Input> for Input {\n\n fn from(value: &bee::Input) -> Self {\n", "file_path": "src/db/model/stardust/block/input.rs", "rank": 37, "score": 25.103931370870264 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::payload::tagged_data as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::db;\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct TaggedDataPayload {\n\n #[serde(with = \"serde_bytes\")]\n\n tag: Box<[u8]>,\n\n #[serde(with = \"serde_bytes\")]\n\n data: Box<[u8]>,\n\n}\n\n\n\nimpl From<&bee::TaggedDataPayload> for TaggedDataPayload {\n\n fn from(value: &bee::TaggedDataPayload) -> Self {\n\n Self {\n\n tag: value.tag().to_vec().into_boxed_slice(),\n", "file_path": "src/db/model/stardust/block/payload/tagged_data.rs", "rank": 38, "score": 24.856066478316635 }, { "content": " fn try_from(value: Address) -> Result<Self, Self::Error> {\n\n Ok(match value {\n\n Address::Ed25519(a) => Self::Ed25519(a.try_into()?),\n\n Address::Alias(a) => Self::Alias(bee::AliasAddress::new(a.try_into()?)),\n\n Address::Nft(a) => Self::Nft(bee::NftAddress::new(a.try_into()?)),\n\n })\n\n }\n\n}\n\n\n\nimpl FromStr for Address {\n\n type Err = crate::db::error::Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n Ok(bee::Address::try_from_bech32(s)?.1.into())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n", "file_path": "src/db/model/stardust/block/address.rs", "rank": 39, "score": 24.439889503655344 }, { "content": " <S as FromStr>::Err: Display,\n\n {\n\n type Value = S;\n\n\n\n fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(formatter, \"a string\")\n\n }\n\n\n\n fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>\n\n where\n\n E: serde::de::Error,\n\n {\n\n value.parse::<Self::Value>().map_err(serde::de::Error::custom)\n\n }\n\n }\n\n\n\n deserializer.deserialize_str(Helper(PhantomData))\n\n }\n\n\n\n /// Serialize T using [`Display`]\n\n pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n T: Display,\n\n S: Serializer,\n\n {\n\n serializer.collect_str(&value)\n\n }\n\n}\n", "file_path": "src/db/model/util.rs", "rank": 40, "score": 23.961842867266995 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_rest_api_stardust::types::dtos as bee;\n\nuse mongodb::bson::Bson;\n\nuse serde::{Deserialize, Serialize};\n\nuse thiserror::Error;\n\n\n\n#[derive(Error, Debug)]\n\n#[error(\"Unexpected ledger inclusion state: {0}\")]\n\n#[allow(missing_docs)]\n\npub struct UnexpectedLedgerInclusionState(u8);\n\n\n\n/// A block's ledger inclusion state.\n\n#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]\n\n#[repr(u8)]\n\npub enum LedgerInclusionState {\n\n /// A conflicting block, ex. a double spend\n\n #[serde(rename = \"conflicting\")]\n\n Conflicting = 0,\n", "file_path": "src/db/model/ledger/inclusion_state.rs", "rank": 41, "score": 23.76084883446346 }, { "content": " fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n Ok(bee::OutputId::from_str(s)?.into())\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(tag = \"kind\")]\n\npub enum Output {\n\n #[serde(rename = \"treasury\")]\n\n Treasury(TreasuryOutput),\n\n #[serde(rename = \"basic\")]\n\n Basic(BasicOutput),\n\n #[serde(rename = \"alias\")]\n\n Alias(AliasOutput),\n\n #[serde(rename = \"foundry\")]\n\n Foundry(FoundryOutput),\n\n #[serde(rename = \"nft\")]\n\n Nft(NftOutput),\n\n}\n\n\n", "file_path": "src/db/model/stardust/block/output/mod.rs", "rank": 42, "score": 23.648804900528674 }, { "content": "}\n\n\n\nimpl TryFrom<TransactionPayload> for bee::TransactionPayload {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: TransactionPayload) -> Result<Self, Self::Error> {\n\n Ok(bee::TransactionPayload::new(\n\n value.essence.try_into()?,\n\n bee_block_stardust::unlock::Unlocks::new(\n\n Vec::from(value.unlocks)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )?,\n\n )?)\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(tag = \"kind\")]\n", "file_path": "src/db/model/stardust/block/payload/transaction.rs", "rank": 43, "score": 23.215282489757737 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\npub mod stringify {\n\n use std::{fmt::Display, marker::PhantomData, str::FromStr};\n\n\n\n use serde::{de::Visitor, Deserializer, Serializer};\n\n\n\n /// Deserialize T using [`FromStr`]\n\n pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>\n\n where\n\n D: Deserializer<'de>,\n\n T: FromStr,\n\n T::Err: Display,\n\n {\n\n struct Helper<S>(PhantomData<S>);\n\n\n\n impl<'de, S> Visitor<'de> for Helper<S>\n\n where\n\n S: FromStr,\n", "file_path": "src/db/model/util.rs", "rank": 44, "score": 23.13810229907445 }, { "content": "impl TryFrom<MilestoneId> for bee::MilestoneId {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: MilestoneId) -> Result<Self, Self::Error> {\n\n Ok(bee::MilestoneId::new(value.0.as_ref().try_into()?))\n\n }\n\n}\n\n\n\nimpl FromStr for MilestoneId {\n\n type Err = db::error::Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n Ok(bee::MilestoneId::from_str(s)?.into())\n\n }\n\n}\n", "file_path": "src/db/model/stardust/block/payload/milestone/milestone_id.rs", "rank": 45, "score": 22.958602639007996 }, { "content": "\n\nimpl From<bee::AliasId> for AliasId {\n\n fn from(value: bee::AliasId) -> Self {\n\n Self(value.to_vec().into_boxed_slice())\n\n }\n\n}\n\n\n\nimpl TryFrom<AliasId> for bee::AliasId {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: AliasId) -> Result<Self, Self::Error> {\n\n Ok(bee::AliasId::new(value.0.as_ref().try_into()?))\n\n }\n\n}\n\n\n\nimpl FromStr for AliasId {\n\n type Err = db::error::Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n Ok(bee::AliasId::from_str(s)?.into())\n", "file_path": "src/db/model/stardust/block/output/alias.rs", "rank": 46, "score": 22.834998870756234 }, { "content": "impl From<bee::BlockId> for BlockId {\n\n fn from(value: bee::BlockId) -> Self {\n\n Self(value.to_vec().into_boxed_slice())\n\n }\n\n}\n\n\n\nimpl TryFrom<BlockId> for bee::BlockId {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: BlockId) -> Result<Self, Self::Error> {\n\n Ok(bee::BlockId::new(value.0.as_ref().try_into()?))\n\n }\n\n}\n\n\n\nimpl FromStr for BlockId {\n\n type Err = db::error::Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n Ok(bee::BlockId::from_str(s)?.into())\n\n }\n\n}\n", "file_path": "src/db/model/stardust/block/block_id.rs", "rank": 47, "score": 22.83499887075623 }, { "content": "\n\nimpl From<&bee::FoundryOutput> for FoundryOutput {\n\n fn from(value: &bee::FoundryOutput) -> Self {\n\n Self {\n\n amount: value.amount(),\n\n native_tokens: value.native_tokens().iter().map(Into::into).collect(),\n\n serial_number: value.serial_number(),\n\n token_scheme: value.token_scheme().into(),\n\n unlock_conditions: value.unlock_conditions().iter().map(Into::into).collect(),\n\n features: value.features().iter().map(Into::into).collect(),\n\n immutable_features: value.immutable_features().iter().map(Into::into).collect(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<FoundryOutput> for bee::FoundryOutput {\n\n type Error = crate::db::error::Error;\n\n\n\n fn try_from(value: FoundryOutput) -> Result<Self, Self::Error> {\n\n Ok(\n", "file_path": "src/db/model/stardust/block/output/foundry.rs", "rank": 48, "score": 22.778379798486295 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse std::{fmt, ops};\n\n\n\nuse bee_block_stardust::payload::milestone as bee;\n\nuse derive_more::{Add, Deref, DerefMut, Sub};\n\nuse mongodb::bson::Bson;\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[derive(\n\n Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Debug, Default, Serialize, Deserialize, Add, Sub, Deref, DerefMut,\n\n)]\n\n#[serde(transparent)]\n\npub struct MilestoneIndex(pub u32);\n\n\n\nimpl fmt::Display for MilestoneIndex {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{}\", self.0)\n\n }\n", "file_path": "src/db/model/tangle/milestone_index.rs", "rank": 50, "score": 22.17223422134414 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::{BlockId, Payload};\n\nuse crate::db;\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct Block {\n\n #[serde(rename = \"_id\")]\n\n pub block_id: BlockId,\n\n pub protocol_version: u8,\n\n pub parents: Box<[BlockId]>,\n\n pub payload: Option<Payload>,\n\n #[serde(with = \"crate::db::model::util::stringify\")]\n\n pub nonce: u64,\n\n}\n\n\n", "file_path": "src/db/model/stardust/block/block_inner.rs", "rank": 51, "score": 21.671838894159656 }, { "content": "impl From<&bee::NativeToken> for NativeToken {\n\n fn from(value: &bee::NativeToken) -> Self {\n\n Self {\n\n token_id: TokenId(value.token_id().to_vec().into_boxed_slice()),\n\n amount: value.amount().into(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<NativeToken> for bee::NativeToken {\n\n type Error = crate::db::error::Error;\n\n\n\n fn try_from(value: NativeToken) -> Result<Self, Self::Error> {\n\n Ok(Self::new(value.token_id.try_into()?, value.amount.into())?)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n", "file_path": "src/db/model/stardust/block/output/native_token.rs", "rank": 52, "score": 21.556598965674347 }, { "content": " binary_parameters.into_vec(),\n\n )?),\n\n })\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct MigratedFundsEntry {\n\n #[serde(with = \"serde_bytes\")]\n\n tail_transaction_hash: Box<[u8]>,\n\n address: Address,\n\n #[serde(with = \"crate::db::model::util::stringify\")]\n\n amount: u64,\n\n}\n\n\n\nimpl From<&bee::option::MigratedFundsEntry> for MigratedFundsEntry {\n\n fn from(value: &bee::option::MigratedFundsEntry) -> Self {\n\n Self {\n\n tail_transaction_hash: value.tail_transaction_hash().as_ref().to_vec().into_boxed_slice(),\n\n address: (*value.address()).into(),\n", "file_path": "src/db/model/stardust/block/payload/milestone/mod.rs", "rank": 53, "score": 21.35895805178624 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::output::unlock_condition as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::db::model::stardust::block::Address;\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(tag = \"kind\")]\n\npub enum UnlockCondition {\n\n #[serde(rename = \"address\")]\n\n Address { address: Address },\n\n #[serde(rename = \"storage_deposit_return\")]\n\n StorageDepositReturn {\n\n return_address: Address,\n\n #[serde(with = \"crate::db::model::util::stringify\")]\n\n amount: u64,\n\n },\n\n #[serde(rename = \"timelock\")]\n", "file_path": "src/db/model/stardust/block/output/unlock_condition.rs", "rank": 54, "score": 21.355774380620126 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\n//! Holds the `MongoDb` type and its config.\n\n\n\nuse mongodb::{\n\n bson::{doc, Document},\n\n error::Error,\n\n options::{ClientOptions, Credential},\n\n Client,\n\n};\n\nuse serde::{Deserialize, Serialize};\n\n\n\n/// A handle to the underlying `MongoDB` database.\n\n#[derive(Clone, Debug)]\n\npub struct MongoDb(pub(crate) mongodb::Database);\n\n\n\nimpl MongoDb {\n\n const NAME: &'static str = \"chronicle\";\n\n const DEFAULT_CONNECT_URL: &'static str = \"mongodb://localhost:27017\";\n", "file_path": "src/db/mongodb.rs", "rank": 55, "score": 21.34022585295147 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::signature as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::db;\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(tag = \"kind\")]\n\npub enum Signature {\n\n #[serde(rename = \"ed25519\")]\n\n Ed25519 {\n\n #[serde(with = \"serde_bytes\")]\n\n public_key: Box<[u8]>,\n\n #[serde(with = \"serde_bytes\")]\n\n signature: Box<[u8]>,\n\n },\n\n}\n\n\n", "file_path": "src/db/model/stardust/block/signature.rs", "rank": 56, "score": 21.300086168130687 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nmod feature;\n\nmod native_token;\n\nmod unlock_condition;\n\n\n\n// The different output types\n\nmod alias;\n\nmod basic;\n\nmod foundry;\n\nmod nft;\n\npub(crate) mod treasury;\n\n\n\nuse std::str::FromStr;\n\n\n\nuse bee_block_stardust::output as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\npub use self::{\n", "file_path": "src/db/model/stardust/block/output/mod.rs", "rank": 57, "score": 21.24821609632967 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse mongodb::{\n\n bson::{self, doc},\n\n error::Error,\n\n options::UpdateOptions,\n\n results::UpdateResult,\n\n};\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::db::MongoDb;\n\n\n\n/// Provides the information about the status of the node.\n\n#[derive(Clone, Debug, Serialize, Deserialize)]\n\npub struct Status {\n\n network_name: String,\n\n}\n\n\n\nimpl Status {\n", "file_path": "src/db/model/status.rs", "rank": 58, "score": 21.128588517329273 }, { "content": " Ok(match value {\n\n TokenScheme::Simple {\n\n minted_tokens,\n\n melted_tokens,\n\n maximum_supply,\n\n } => bee::TokenScheme::Simple(bee::SimpleTokenScheme::new(\n\n minted_tokens.into(),\n\n melted_tokens.into(),\n\n maximum_supply.into(),\n\n )?),\n\n })\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct NativeToken {\n\n pub token_id: TokenId,\n\n pub amount: TokenAmount,\n\n}\n\n\n", "file_path": "src/db/model/stardust/block/output/native_token.rs", "rank": 59, "score": 20.623337945957992 }, { "content": " }\n\n}\n\n\n\nimpl From<bee::TransactionId> for TransactionId {\n\n fn from(value: bee::TransactionId) -> Self {\n\n Self(value.to_vec().into_boxed_slice())\n\n }\n\n}\n\n\n\nimpl TryFrom<TransactionId> for bee::TransactionId {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: TransactionId) -> Result<Self, Self::Error> {\n\n Ok(bee::TransactionId::new(value.0.as_ref().try_into()?))\n\n }\n\n}\n\n\n\nimpl FromStr for TransactionId {\n\n type Err = db::error::Error;\n\n\n", "file_path": "src/db/model/stardust/block/payload/transaction.rs", "rank": 60, "score": 20.554203722332048 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::semantic as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]\n\n#[repr(u8)]\n\npub enum ConflictReason {\n\n None = 0,\n\n InputUtxoAlreadySpent = 1,\n\n InputUtxoAlreadySpentInThisMilestone = 2,\n\n InputUtxoNotFound = 3,\n\n CreatedConsumedAmountMismatch = 4,\n\n InvalidSignature = 5,\n\n TimelockNotExpired = 6,\n\n InvalidNativeTokens = 7,\n\n StorageDepositReturnUnfulfilled = 8,\n\n InvalidUnlock = 9,\n\n InputsCommitmentsMismatch = 10,\n", "file_path": "src/db/model/ledger/conflict_reason.rs", "rank": 61, "score": 20.44885610409105 }, { "content": " output_amount: value.output().amount(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<TreasuryTransactionPayload> for bee::TreasuryTransactionPayload {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: TreasuryTransactionPayload) -> Result<Self, Self::Error> {\n\n Ok(Self::new(\n\n bee_block_stardust::input::TreasuryInput::new(value.input_milestone_id.try_into()?),\n\n bee_block_stardust::output::TreasuryOutput::new(value.output_amount)?,\n\n )?)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n", "file_path": "src/db/model/stardust/block/payload/treasury_transaction.rs", "rank": 62, "score": 20.38456749838572 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::unlock as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::Signature;\n\nuse crate::db;\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(tag = \"kind\")]\n\npub enum Unlock {\n\n #[serde(rename = \"signature\")]\n\n Signature { signature: Signature },\n\n #[serde(rename = \"reference\")]\n\n Reference { index: u16 },\n\n #[serde(rename = \"alias\")]\n\n Alias { index: u16 },\n\n #[serde(rename = \"nft\")]\n\n Nft { index: u16 },\n", "file_path": "src/db/model/stardust/block/unlock.rs", "rank": 63, "score": 20.27793925813303 }, { "content": "\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct MilestoneEssence {\n\n pub index: MilestoneIndex,\n\n pub timestamp: u32,\n\n pub previous_milestone_id: MilestoneId,\n\n pub parents: Box<[BlockId]>,\n\n #[serde(with = \"serde_bytes\")]\n\n pub confirmed_merkle_proof: Box<[u8]>,\n\n #[serde(with = \"serde_bytes\")]\n\n pub applied_merkle_proof: Box<[u8]>,\n\n #[serde(with = \"serde_bytes\")]\n\n pub metadata: Vec<u8>,\n\n pub options: Box<[MilestoneOption]>,\n\n}\n\n\n\nimpl From<&bee::MilestoneEssence> for MilestoneEssence {\n\n fn from(value: &bee::MilestoneEssence) -> Self {\n\n Self {\n\n index: value.index().0.into(),\n", "file_path": "src/db/model/stardust/block/payload/milestone/mod.rs", "rank": 64, "score": 20.157908414323174 }, { "content": " alias::{AliasId, AliasOutput},\n\n basic::BasicOutput,\n\n feature::Feature,\n\n foundry::FoundryOutput,\n\n native_token::{NativeToken, TokenScheme},\n\n nft::{NftId, NftOutput},\n\n treasury::TreasuryOutput,\n\n unlock_condition::UnlockCondition,\n\n};\n\nuse crate::db::model::stardust::block::TransactionId;\n\n\n\npub type OutputAmount = u64;\n\npub type OutputIndex = u16;\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct OutputId {\n\n pub transaction_id: TransactionId,\n\n pub index: OutputIndex,\n\n}\n\n\n", "file_path": "src/db/model/stardust/block/output/mod.rs", "rank": 65, "score": 20.066784692885715 }, { "content": "\n\n#[derive(\n\n Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Debug, Default, Serialize, Deserialize, Add, Sub, Deref, DerefMut,\n\n)]\n\n#[serde(transparent)]\n\npub struct MilestoneTimestamp(pub u32);\n\n\n\nimpl From<u32> for MilestoneTimestamp {\n\n fn from(value: u32) -> Self {\n\n MilestoneTimestamp(value)\n\n }\n\n}\n\n\n\nimpl From<MilestoneTimestamp> for Bson {\n\n fn from(value: MilestoneTimestamp) -> Self {\n\n Bson::from(value.0)\n\n }\n\n}\n\n\n\n/// A milestone's metadata.\n", "file_path": "src/db/model/stardust/milestone.rs", "rank": 66, "score": 19.998217854294253 }, { "content": "#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]\n\npub struct MongoDbConfig {\n\n pub(crate) connect_url: String,\n\n pub(crate) username: Option<String>,\n\n pub(crate) password: Option<String>,\n\n pub(crate) suffix: Option<String>,\n\n}\n\n\n\nimpl MongoDbConfig {\n\n /// Creates a new [`MongoDbConfig`].\n\n pub fn new() -> Self {\n\n Self::default()\n\n }\n\n\n\n /// Sets the connect URL.\n\n pub fn with_connect_url(mut self, connect_url: impl Into<String>) -> Self {\n\n self.connect_url = connect_url.into();\n\n self\n\n }\n\n\n", "file_path": "src/db/mongodb.rs", "rank": 67, "score": 19.767436291469625 }, { "content": "impl From<bee::OutputId> for OutputId {\n\n fn from(value: bee::OutputId) -> Self {\n\n Self {\n\n transaction_id: (*value.transaction_id()).into(),\n\n index: value.index(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<OutputId> for bee::OutputId {\n\n type Error = crate::db::error::Error;\n\n\n\n fn try_from(value: OutputId) -> Result<Self, Self::Error> {\n\n Ok(bee::OutputId::new(value.transaction_id.try_into()?, value.index)?)\n\n }\n\n}\n\n\n\nimpl FromStr for OutputId {\n\n type Err = crate::db::error::Error;\n\n\n", "file_path": "src/db/model/stardust/block/output/mod.rs", "rank": 68, "score": 19.735425182396664 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::payload as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nmod milestone;\n\nmod tagged_data;\n\nmod transaction;\n\nmod treasury_transaction;\n\n\n\npub use self::{\n\n milestone::{MilestoneEssence, MilestoneId, MilestoneOption, MilestonePayload},\n\n tagged_data::TaggedDataPayload,\n\n transaction::{TransactionEssence, TransactionId, TransactionPayload},\n\n treasury_transaction::TreasuryTransactionPayload,\n\n};\n\nuse crate::db;\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n", "file_path": "src/db/model/stardust/block/payload/mod.rs", "rank": 69, "score": 19.633098736772176 }, { "content": "impl SendError {\n\n pub fn new(msg: impl Into<String>) -> Self {\n\n Self(msg.into())\n\n }\n\n}\n\n\n\nimpl<S: Into<String>> From<S> for SendError {\n\n fn from(msg: S) -> Self {\n\n Self::new(msg)\n\n }\n\n}\n\n\n\n/// An actor handle, used to send events.\n\n#[derive(Debug)]\n\npub struct Addr<A: Actor> {\n\n pub(crate) scope: ScopeView,\n\n pub(crate) sender: UnboundedSender<Envelope<A>>,\n\n}\n\n\n\nimpl<A: Actor> Addr<A> {\n", "file_path": "src/runtime/actor/addr.rs", "rank": 70, "score": 19.41041485121869 }, { "content": " Self {\n\n amount: value.amount(),\n\n native_tokens: value.native_tokens().iter().map(Into::into).collect(),\n\n unlock_conditions: value.unlock_conditions().iter().map(Into::into).collect(),\n\n features: value.features().iter().map(Into::into).collect(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<BasicOutput> for bee::BasicOutput {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: BasicOutput) -> Result<Self, Self::Error> {\n\n Ok(Self::build_with_amount(value.amount)?\n\n .with_native_tokens(\n\n Vec::from(value.native_tokens)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n", "file_path": "src/db/model/stardust/block/output/basic.rs", "rank": 71, "score": 18.72776787342149 }, { "content": " amount: value.amount(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<MigratedFundsEntry> for bee::option::MigratedFundsEntry {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: MigratedFundsEntry) -> Result<Self, Self::Error> {\n\n Ok(Self::new(\n\n bee::option::TailTransactionHash::new(value.tail_transaction_hash.as_ref().try_into()?)?,\n\n value.address.try_into()?,\n\n value.amount,\n\n )?)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n const TAIL_TRANSACTION_HASH1: [u8; 49] = [\n", "file_path": "src/db/model/stardust/block/payload/milestone/mod.rs", "rank": 72, "score": 18.51336287566566 }, { "content": "/// Address analytics result.\n\n#[cfg(feature = \"analytics\")]\n\n#[derive(Clone, Debug, Serialize, Deserialize)]\n\npub struct AddressAnalyticsResult {\n\n /// The number of addresses used in the time period.\n\n pub total_addresses: u64,\n\n /// The number of addresses that received tokens in the time period.\n\n pub recv_addresses: u64,\n\n /// The number of addresses that sent tokens in the time period.\n\n pub send_addresses: u64,\n\n}\n\n\n\n#[cfg(feature = \"analytics\")]\n\nimpl MongoDb {\n\n /// Create aggregate statistics of all addresses.\n\n pub async fn aggregate_addresses(\n\n &self,\n\n start_milestone: MilestoneIndex,\n\n end_milestone: MilestoneIndex,\n\n ) -> Result<Option<AddressAnalyticsResult>, Error> {\n", "file_path": "src/db/model/stardust/block/mod.rs", "rank": 73, "score": 18.468652522391714 }, { "content": "\n\n fn try_from(value: TreasuryOutput) -> Result<Self, Self::Error> {\n\n Ok(Self::new(value.amount)?)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn test_treasury_output_bson() {\n\n let output = TreasuryOutput::from(&bee_test::rand::output::rand_treasury_output());\n\n let bson = to_bson(&output).unwrap();\n\n assert_eq!(output, from_bson::<TreasuryOutput>(bson).unwrap());\n\n }\n\n}\n", "file_path": "src/db/model/stardust/block/output/treasury.rs", "rank": 75, "score": 18.01606670101996 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse futures::stream::Stream;\n\nuse mongodb::{\n\n bson::{self, doc},\n\n error::Error,\n\n options::{FindOptions, UpdateOptions},\n\n results::UpdateResult,\n\n};\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::db::{model::tangle::MilestoneIndex, MongoDb};\n\n\n\n/// A record indicating that a milestone is completed.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct SyncRecord {\n\n /// The index of the milestone that was completed.\n\n pub milestone_index: MilestoneIndex,\n\n /// Whether the milestone has been written to an archive file.\n", "file_path": "src/db/model/sync.rs", "rank": 76, "score": 17.81250059780992 }, { "content": " pub metadata: Option<Metadata>,\n\n}\n\n\n\nimpl BlockRecord {\n\n /// The stardust blocks collection name.\n\n pub const COLLECTION: &'static str = \"stardust_blocks\";\n\n\n\n /// Creates a new block record.\n\n pub fn new(block: Block, raw: Vec<u8>) -> Self {\n\n Self {\n\n inner: block,\n\n raw,\n\n metadata: None,\n\n }\n\n }\n\n}\n\n\n\n#[cfg(feature = \"inx\")]\n\nimpl TryFrom<inx::proto::Block> for BlockRecord {\n\n type Error = inx::Error;\n", "file_path": "src/db/model/stardust/block/mod.rs", "rank": 77, "score": 17.808883252755784 }, { "content": " Self {\n\n amount: value.amount(),\n\n native_tokens: value.native_tokens().iter().map(Into::into).collect(),\n\n alias_id: (*value.alias_id()).into(),\n\n state_index: value.state_index(),\n\n state_metadata: value.state_metadata().to_vec().into_boxed_slice(),\n\n foundry_counter: value.foundry_counter(),\n\n unlock_conditions: value.unlock_conditions().iter().map(Into::into).collect(),\n\n features: value.features().iter().map(Into::into).collect(),\n\n immutable_features: value.immutable_features().iter().map(Into::into).collect(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<AliasOutput> for bee::AliasOutput {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: AliasOutput) -> Result<Self, Self::Error> {\n\n Ok(Self::build_with_amount(value.amount, value.alias_id.try_into()?)?\n\n .with_native_tokens(\n", "file_path": "src/db/model/stardust/block/output/alias.rs", "rank": 78, "score": 17.7723159836793 }, { "content": " data: value.data().to_vec().into_boxed_slice(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<TaggedDataPayload> for bee::TaggedDataPayload {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: TaggedDataPayload) -> Result<Self, Self::Error> {\n\n Ok(bee::TaggedDataPayload::new(value.tag.into(), value.data.into())?)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n\n use super::*;\n\n\n\n #[test]\n", "file_path": "src/db/model/stardust/block/payload/tagged_data.rs", "rank": 79, "score": 17.60735887552077 }, { "content": " maximum_supply: TokenAmount,\n\n },\n\n}\n\n\n\nimpl From<&bee::TokenScheme> for TokenScheme {\n\n fn from(value: &bee::TokenScheme) -> Self {\n\n match value {\n\n bee::TokenScheme::Simple(a) => Self::Simple {\n\n minted_tokens: a.minted_tokens().into(),\n\n melted_tokens: a.melted_tokens().into(),\n\n maximum_supply: a.maximum_supply().into(),\n\n },\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<TokenScheme> for bee::TokenScheme {\n\n type Error = crate::db::error::Error;\n\n\n\n fn try_from(value: TokenScheme) -> Result<Self, Self::Error> {\n", "file_path": "src/db/model/stardust/block/output/native_token.rs", "rank": 80, "score": 16.885698954811172 }, { "content": " }\n\n}\n\n\n\nimpl TryFrom<Payload> for bee::Payload {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: Payload) -> Result<Self, Self::Error> {\n\n Ok(match value {\n\n Payload::Transaction(p) => bee::Payload::Transaction(Box::new((*p).try_into()?)),\n\n Payload::Milestone(p) => bee::Payload::Milestone(Box::new((*p).try_into()?)),\n\n Payload::TreasuryTransaction(p) => bee::Payload::TreasuryTransaction(Box::new((*p).try_into()?)),\n\n Payload::TaggedData(p) => bee::Payload::TaggedData(Box::new((*p).try_into()?)),\n\n })\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n", "file_path": "src/db/model/stardust/block/payload/mod.rs", "rank": 81, "score": 16.727298233505273 }, { "content": " pub fn take_internal_state(self) -> Option<A::State> {\n\n self.internal_state\n\n }\n\n\n\n /// Gets the error that occurred.\n\n pub fn error(&self) -> &ActorError<A> {\n\n &self.error\n\n }\n\n\n\n /// Takes the error that occurred.\n\n pub fn take_error(self) -> ActorError<A> {\n\n self.error\n\n }\n\n}\n\n\n\nimpl<A: Actor> Debug for ErrorReport<A>\n\nwhere\n\n A: Debug,\n\n A::State: Debug,\n\n{\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n f.debug_struct(\"ErrorReport\")\n\n .field(\"actor\", &self.actor)\n\n .field(\"internal_state\", &self.internal_state)\n\n .field(\"error\", &self.error)\n\n .finish()\n\n }\n\n}\n", "file_path": "src/runtime/actor/report.rs", "rank": 82, "score": 16.18137617887588 }, { "content": " pub fn with_registration(mut self, enable: bool) -> Self {\n\n self.config.set_add_to_registry(enable);\n\n self\n\n }\n\n}\n\n\n\nimpl<A> From<A> for SpawnConfig<A> {\n\n fn from(actor: A) -> Self {\n\n Self::new(actor)\n\n }\n\n}\n\n\n\npub(crate) struct SpawnConfigInner<A> {\n\n pub(crate) stream: Option<EnvelopeStream<A>>,\n\n pub(crate) add_to_registry: bool,\n\n}\n\n\n\nimpl<A: Debug> Debug for SpawnConfigInner<A> {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n f.debug_struct(\"SpawnConfigInner\")\n", "file_path": "src/runtime/config.rs", "rank": 83, "score": 16.168524493591026 }, { "content": " Report::Error(error) => Some(error.take_error()),\n\n }\n\n }\n\n}\n\n\n\nimpl<A: Actor> Debug for Report<A>\n\nwhere\n\n A: Debug,\n\n A::State: Debug,\n\n{\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n match self {\n\n Self::Success(arg0) => f.debug_tuple(\"Success\").field(arg0).finish(),\n\n Self::Error(arg0) => f.debug_tuple(\"Error\").field(arg0).finish(),\n\n }\n\n }\n\n}\n\n\n\n/// A report that an actor finished running with an error\n\npub struct SuccessReport<A: Actor> {\n", "file_path": "src/runtime/actor/report.rs", "rank": 84, "score": 16.12208222598673 }, { "content": " bee::UnlockCondition::ImmutableAliasAddress(a) => Self::ImmutableAliasAddress {\n\n address: (*a.address()).into(),\n\n },\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<UnlockCondition> for bee::UnlockCondition {\n\n type Error = crate::db::error::Error;\n\n\n\n fn try_from(value: UnlockCondition) -> Result<Self, Self::Error> {\n\n Ok(match value {\n\n UnlockCondition::Address { address } => {\n\n Self::Address(bee::AddressUnlockCondition::new(address.try_into()?))\n\n }\n\n UnlockCondition::StorageDepositReturn { return_address, amount } => Self::StorageDepositReturn(\n\n bee::StorageDepositReturnUnlockCondition::new(return_address.try_into()?, amount)?,\n\n ),\n\n UnlockCondition::Timelock {\n\n milestone_index,\n", "file_path": "src/db/model/stardust/block/output/unlock_condition.rs", "rank": 85, "score": 15.987587389791932 }, { "content": "#[derive(Serialize, Deserialize)]\n\npub struct MilestoneRecord {\n\n /// The [`MilestoneId`](MilestoneId) of the milestone.\n\n #[serde(rename = \"_id\")]\n\n pub milestone_id: MilestoneId,\n\n /// The milestone index.\n\n pub milestone_index: MilestoneIndex,\n\n /// The timestamp of the milestone.\n\n pub milestone_timestamp: MilestoneTimestamp,\n\n /// The milestone's payload.\n\n pub payload: MilestonePayload,\n\n}\n\n\n\nimpl MilestoneRecord {\n\n /// The stardust milestone collection name.\n\n pub const COLLECTION: &'static str = \"stardust_milestones\";\n\n}\n\n\n\n#[cfg(feature = \"inx\")]\n\nimpl TryFrom<inx::proto::Milestone> for MilestoneRecord {\n", "file_path": "src/db/model/stardust/milestone.rs", "rank": 86, "score": 15.45569636659191 }, { "content": "}\n\n\n\nimpl PartialEq<MilestoneIndex> for u32 {\n\n fn eq(&self, x: &MilestoneIndex) -> bool {\n\n *self == x.0\n\n }\n\n}\n\n\n\nimpl From<bee::MilestoneIndex> for MilestoneIndex {\n\n fn from(value: bee::MilestoneIndex) -> Self {\n\n Self(value.0)\n\n }\n\n}\n\n\n\nimpl From<MilestoneIndex> for bee::MilestoneIndex {\n\n fn from(value: MilestoneIndex) -> Self {\n\n Self(value.0)\n\n }\n\n}\n\n\n", "file_path": "src/db/model/tangle/milestone_index.rs", "rank": 87, "score": 15.334440441565258 }, { "content": "}\n\n\n\nimpl From<&bee::Unlock> for Unlock {\n\n fn from(value: &bee::Unlock) -> Self {\n\n match value {\n\n bee::Unlock::Signature(s) => Self::Signature {\n\n signature: s.signature().into(),\n\n },\n\n bee::Unlock::Reference(r) => Self::Reference { index: r.index() },\n\n bee::Unlock::Alias(a) => Self::Alias { index: a.index() },\n\n bee::Unlock::Nft(n) => Self::Nft { index: n.index() },\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<Unlock> for bee::Unlock {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: Unlock) -> Result<Self, Self::Error> {\n\n Ok(match value {\n", "file_path": "src/db/model/stardust/block/unlock.rs", "rank": 88, "score": 15.314485771366737 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::{ConflictReason, LedgerInclusionState};\n\nuse crate::db::model::tangle::MilestoneIndex;\n\n\n\n/// Block metadata.\n\n#[derive(Clone, Debug, Serialize, Deserialize)]\n\npub struct Metadata {\n\n /// Status of the solidification process.\n\n pub is_solid: bool,\n\n /// Indicates that the block should be promoted.\n\n pub should_promote: bool,\n\n /// Indicates that the block should be reattached.\n\n pub should_reattach: bool,\n\n /// The milestone index referencing the block.\n\n pub referenced_by_milestone_index: MilestoneIndex,\n\n /// The corresponding milestone index.\n", "file_path": "src/db/model/ledger/metadata.rs", "rank": 89, "score": 15.222142379617118 }, { "content": "impl From<&bee::Output> for Output {\n\n fn from(value: &bee::Output) -> Self {\n\n match value {\n\n bee::Output::Treasury(o) => Self::Treasury(o.into()),\n\n bee::Output::Basic(o) => Self::Basic(o.into()),\n\n bee::Output::Alias(o) => Self::Alias(o.into()),\n\n bee::Output::Foundry(o) => Self::Foundry(o.into()),\n\n bee::Output::Nft(o) => Self::Nft(o.into()),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<Output> for bee::Output {\n\n type Error = crate::db::error::Error;\n\n\n\n fn try_from(value: Output) -> Result<Self, Self::Error> {\n\n Ok(match value {\n\n Output::Treasury(o) => bee::Output::Treasury(o.try_into()?),\n\n Output::Basic(o) => bee::Output::Basic(o.try_into()?),\n\n Output::Alias(o) => bee::Output::Alias(o.try_into()?),\n", "file_path": "src/db/model/stardust/block/output/mod.rs", "rank": 90, "score": 15.101347453724497 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse std::fmt::Debug;\n\n\n\nuse super::{error::ActorError, Actor};\n\n\n\n/// An actor exit report.\n\npub enum Report<A: Actor> {\n\n /// Actor exited successfully.\n\n Success(SuccessReport<A>),\n\n /// Actor exited with an error.\n\n Error(ErrorReport<A>),\n\n}\n\n\n\nimpl<A: Actor> Report<A> {\n\n /// Gets the actor.\n\n pub fn actor(&self) -> &A {\n\n match self {\n\n Report::Success(success) => success.actor(),\n", "file_path": "src/runtime/actor/report.rs", "rank": 91, "score": 14.958064948804477 }, { "content": " if let bee_block_stardust::address::Address::Alias(alias_address) = bee_address {\n\n Self::ImmutableAliasAddress(bee::ImmutableAliasAddressUnlockCondition::new(alias_address))\n\n } else {\n\n Err(bee_block_stardust::Error::InvalidAddressKind(bee_address.kind()))?\n\n }\n\n }\n\n })\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn test_unlock_condition_bson() {\n\n let block = get_test_address_condition(bee_test::rand::address::rand_address().into());\n\n let bson = to_bson(&block).unwrap();\n", "file_path": "src/db/model/stardust/block/output/unlock_condition.rs", "rank": 92, "score": 14.9175782864935 }, { "content": " pub fn send<E: 'static + DynEvent<A>>(&self, event: E) -> Result<(), RuntimeError>\n\n where\n\n Self: Sized,\n\n {\n\n self.sender\n\n .send(Box::new(event))\n\n .map_err(|_| RuntimeError::SendError(\"Failed to send event\".into()))\n\n }\n\n\n\n /// Returns whether the actor's event channel is closed.\n\n pub fn is_closed(&self) -> bool {\n\n self.sender.is_closed()\n\n }\n\n}\n\n\n\nimpl<A: Actor> Clone for Addr<A> {\n\n fn clone(&self) -> Self {\n\n Self {\n\n scope: self.scope.clone(),\n\n sender: self.sender.clone(),\n", "file_path": "src/runtime/actor/addr.rs", "rank": 93, "score": 14.719422135796911 }, { "content": "impl From<&bee::Signature> for Signature {\n\n fn from(value: &bee::Signature) -> Self {\n\n match value {\n\n bee::Signature::Ed25519(signature) => Self::Ed25519 {\n\n public_key: signature.public_key().to_vec().into_boxed_slice(),\n\n signature: signature.signature().to_vec().into_boxed_slice(),\n\n },\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<Signature> for bee::Signature {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: Signature) -> Result<Self, Self::Error> {\n\n Ok(match value {\n\n Signature::Ed25519 { public_key, signature } => bee::Signature::Ed25519(bee::Ed25519Signature::new(\n\n public_key.as_ref().try_into()?,\n\n signature.as_ref().try_into()?,\n\n )),\n", "file_path": "src/db/model/stardust/block/signature.rs", "rank": 94, "score": 14.486725805307724 }, { "content": " Ed25519(Ed25519Address),\n\n #[serde(rename = \"alias\")]\n\n Alias(AliasId),\n\n #[serde(rename = \"nft\")]\n\n Nft(NftId),\n\n}\n\n\n\nimpl From<bee::Address> for Address {\n\n fn from(value: bee::Address) -> Self {\n\n match value {\n\n bee::Address::Ed25519(a) => Self::Ed25519(Ed25519Address::from(a)),\n\n bee::Address::Alias(a) => Self::Alias((*a.alias_id()).into()),\n\n bee::Address::Nft(a) => Self::Nft((*a.nft_id()).into()),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<Address> for bee::Address {\n\n type Error = crate::db::error::Error;\n\n\n", "file_path": "src/db/model/stardust/block/address.rs", "rank": 95, "score": 14.454901252194365 }, { "content": "impl From<LedgerInclusionState> for Bson {\n\n fn from(l: LedgerInclusionState) -> Self {\n\n Bson::Int32((l as u8).into())\n\n }\n\n}\n\n\n\n#[cfg(feature = \"stardust\")]\n\nimpl From<bee::LedgerInclusionStateDto> for LedgerInclusionState {\n\n fn from(value: bee::LedgerInclusionStateDto) -> Self {\n\n match value {\n\n bee::LedgerInclusionStateDto::Conflicting => Self::Conflicting,\n\n bee::LedgerInclusionStateDto::Included => Self::Included,\n\n bee::LedgerInclusionStateDto::NoTransaction => Self::NoTransaction,\n\n }\n\n }\n\n}\n\n\n\n#[cfg(feature = \"stardust\")]\n\nimpl From<LedgerInclusionState> for bee::LedgerInclusionStateDto {\n\n fn from(value: LedgerInclusionState) -> Self {\n", "file_path": "src/db/model/ledger/inclusion_state.rs", "rank": 96, "score": 14.09777857425858 }, { "content": "impl From<bee::Block> for Block {\n\n fn from(value: bee::Block) -> Self {\n\n Self {\n\n block_id: value.id().into(),\n\n protocol_version: value.protocol_version(),\n\n parents: value.parents().iter().map(|id| BlockId::from(*id)).collect(),\n\n payload: value.payload().map(Into::into),\n\n nonce: value.nonce(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<Block> for bee::Block {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: Block) -> Result<Self, Self::Error> {\n\n let mut builder = bee::BlockBuilder::<u64>::new(bee::parent::Parents::new(\n\n Vec::from(value.parents)\n\n .into_iter()\n\n .map(|p| p.try_into())\n", "file_path": "src/db/model/stardust/block/block_inner.rs", "rank": 97, "score": 14.079774123966851 }, { "content": " match value {\n\n bee::Input::Utxo(i) => Self::Utxo((*i.output_id()).into()),\n\n bee::Input::Treasury(i) => Self::Treasury {\n\n milestone_id: (*i.milestone_id()).into(),\n\n },\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<Input> for bee::Input {\n\n type Error = db::error::Error;\n\n\n\n fn try_from(value: Input) -> Result<Self, Self::Error> {\n\n Ok(match value {\n\n Input::Utxo(i) => bee::Input::Utxo(bee::UtxoInput::new(i.transaction_id.try_into()?, i.index)?),\n\n Input::Treasury { milestone_id } => bee::Input::Treasury(bee::TreasuryInput::new(milestone_id.try_into()?)),\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/db/model/stardust/block/input.rs", "rank": 98, "score": 13.74010871267352 }, { "content": "\n\npub use self::{address::*, block_id::*, block_inner::*, input::*, output::*, payload::*, signature::*, unlock::*};\n\nuse crate::db::{\n\n model::{\n\n ledger::{LedgerInclusionState, Metadata},\n\n tangle::MilestoneIndex,\n\n },\n\n MongoDb,\n\n};\n\n\n\n/// Chronicle Block record.\n\n#[derive(Clone, Debug, Serialize, Deserialize)]\n\npub struct BlockRecord {\n\n /// The block.\n\n #[serde(flatten)]\n\n pub inner: Block,\n\n /// The raw bytes of the block.\n\n #[serde(with = \"serde_bytes\")]\n\n pub raw: Vec<u8>,\n\n /// The block's metadata.\n", "file_path": "src/db/model/stardust/block/mod.rs", "rank": 99, "score": 13.49000403200129 } ]
Rust
route-rs-runtime/src/link/primitive/output_channel_link.rs
scgruber/route-rs
8c8cd4b3376c1c394960184b419b05acf32e30a8
use crate::link::{Link, LinkBuilder, PacketStream}; use futures::prelude::*; use futures::task::{Context, Poll}; use std::pin::Pin; #[derive(Default)] pub struct OutputChannelLink<Packet> { in_stream: Option<PacketStream<Packet>>, channel_sender: Option<crossbeam::Sender<Packet>>, } impl<Packet> OutputChannelLink<Packet> { pub fn new() -> Self { OutputChannelLink { in_stream: None, channel_sender: None, } } pub fn channel(self, channel_sender: crossbeam::Sender<Packet>) -> Self { OutputChannelLink { in_stream: self.in_stream, channel_sender: Some(channel_sender), } } } impl<Packet: Send + 'static> LinkBuilder<Packet, ()> for OutputChannelLink<Packet> { fn ingressors(self, mut in_streams: Vec<PacketStream<Packet>>) -> Self { assert_eq!( in_streams.len(), 1, "OutputChannelLink may only take 1 input stream" ); if self.in_stream.is_some() { panic!("OutputChannelLink may only take 1 input stream"); } OutputChannelLink { in_stream: Some(in_streams.remove(0)), channel_sender: self.channel_sender, } } fn ingressor(self, in_stream: PacketStream<Packet>) -> Self { if self.in_stream.is_some() { panic!("OutputChannelLink may only take 1 input stream"); } OutputChannelLink { in_stream: Some(in_stream), channel_sender: self.channel_sender, } } fn build_link(self) -> Link<()> { match (self.in_stream, self.channel_sender) { (None, _) => panic!("Cannot build link! Missing input streams"), (_, None) => panic!("Cannot build link! Missing channel"), (Some(in_stream), Some(sender)) => ( vec![Box::new(StreamToChannel { stream: in_stream, channel_sender: sender, })], vec![], ), } } } struct StreamToChannel<Packet> { stream: PacketStream<Packet>, channel_sender: crossbeam::Sender<Packet>, } impl<Packet> Future for StreamToChannel<Packet> { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { loop { if self.channel_sender.is_full() { cx.waker().clone().wake(); return Poll::Pending; } match ready!(Pin::new(&mut self.stream).poll_next(cx)) { Some(packet) => self .channel_sender .try_send(packet) .expect("OutputChannelLink::poll: try_send shouldn't fail"), None => return Poll::Ready(()), } } } } #[cfg(test)] mod tests { use super::*; use crate::utils::test::harness::{initialize_runtime, run_link}; use crate::utils::test::packet_generators::immediate_stream; use crossbeam::crossbeam_channel; use std::thread; #[test] #[should_panic] fn panics_when_built_without_ingressor() { let (s, _r) = crossbeam::unbounded(); OutputChannelLink::<()>::new().channel(s).build_link(); } #[test] #[should_panic] fn panics_when_built_without_channel() { let packet_generator = immediate_stream(vec![]); OutputChannelLink::<()>::new() .ingressor(packet_generator) .build_link(); } #[test] #[should_panic] fn panics_when_built_with_multiple_ingressors() { let (s, _r) = crossbeam::unbounded(); let packet_generator_1 = immediate_stream(vec![]); let packet_generator_2 = immediate_stream(vec![]); OutputChannelLink::<()>::new() .ingressors(vec![packet_generator_1, packet_generator_2]) .channel(s) .build_link(); } #[test] fn immediate_packets() { let mut runtime = initialize_runtime(); let packets = vec![0, 1, 2, 420, 1337, 3, 4, 5, 6, 7, 8, 9]; let results = runtime.block_on(async { let (send, recv) = crossbeam_channel::unbounded::<i32>(); let link = OutputChannelLink::new() .ingressor(immediate_stream(packets.clone())) .channel(send) .build_link(); let link_results = run_link(link).await; (link_results, recv) }); assert!(results.0.is_empty()); assert_eq!(results.1.iter().collect::<Vec<i32>>(), packets); } #[test] fn small_queue() { let packets = vec![0, 1, 2, 420, 1337, 3, 4, 5, 6, 7, 8, 9]; let mut runtime = initialize_runtime(); let results = runtime.block_on(async { let (send, recv) = crossbeam_channel::bounded::<i32>(2); let recv_thread = thread::spawn(move || { let mut outputs = vec![]; while let Ok(n) = recv.recv() { outputs.push(n); } outputs }); let link = OutputChannelLink::new() .ingressor(immediate_stream(packets.clone())) .channel(send) .build_link(); let link_results = run_link(link).await; let output_results = recv_thread.join().unwrap(); (link_results, output_results) }); assert!(results.0.is_empty()); assert_eq!(results.1, packets); } }
use crate::link::{Link, LinkBuilder, PacketStream}; use futures::prelude::*; use futures::task::{Context, Poll}; use std::pin::Pin; #[derive(Default)] pub struct OutputChannelLink<Packet> { in_stream: Option<PacketStream<Packet>>, channel_sender: Option<crossbeam::Sender<Packet>>, } impl<Packet> OutputChannelLink<Packet> { pub fn new() -> Self { OutputChannelLink { in_stream: None, channel_sender: None, } } pub fn channel(self, channel_sender: crossbeam::Sender<Packet>) -> Self { OutputChannelLink { in_stream: self.in_stream, channel_sender: Some(channel_sender), } } } impl<Packet: Send + 'static> LinkBuilder<Packet, ()> for OutputChannelLink<Packet> { fn ingressors(self, mut in_streams: Vec<PacketStream<Packet>>) -> Self { assert_eq!( in_streams.len(), 1, "OutputChannelLink may only take 1 input stream" ); if self.in_stream.is_some() { panic!("OutputChannelLink may only take 1 input stream"); } OutputChannelLink { in_stream: Some(in_streams.remove(0)), channel_sender: self.channel_sender, } } fn ingressor(self, in_stream: PacketStream<Packet>) -> Self { if self.in_stream.is_some() { panic!("OutputChannelLink may only take 1 input stream"); } OutputChannelLink { in_stream: Some(in_stream), channel_sender: self.channel_sender, } } fn build_link(self) -> Link<()> { match (self.in_stream, self.channel_sender) { (None, _) => panic!("Cannot build link! Missing input streams"), (_, None) => panic!("Cannot build link! Missing channel"), (Some(in_stream), Some(sender)) => ( vec![Box::new(StreamToChannel { stream: in_stream, channel_sender: sender, })], vec![], ), } } } struct StreamToChannel<Packet> { stream: PacketStream<Packet>, channel_sender: crossbeam::Sender<Packet>, } impl<Packet> Future for StreamToChannel<Packet> { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { loop { if self.channel_sender.is_full() { cx.waker().clone().wake(); return Poll::Pending; } match ready!(Pin::new(&mut self.stream).poll_next(cx)) { Some(packet) => self .channel_sender .try_send(packet) .expect("OutputChannelLink::poll: try_send shouldn't fail"), None => return Poll::Ready(()), } } } } #[cfg(test)] mod tests { use super::*; use crate::utils::test::harness::{initialize_runtime, run_link}; use crate::utils::test::packet_generators::immediate_stream; use crossbeam::crossbeam_channel; use std::thread; #[test] #[should_panic] fn panics_when_built_without_ingressor() { let (s, _r) = crossbeam::unbounded(); OutputChannelLink::<()>::new().channel(s).build_link(); } #[test] #[should_panic] fn panics_when_built_without_channel() { let packet_generator = immediate_stream(vec![]); OutputChannelLink::<()>::new() .ingressor(packet_generator) .build_link(); } #[test] #[should_panic] fn panics_when_built_with_multiple_ingressors() { let (s, _r) = crossbeam::unbounded(); let packet_generator_1 = immediate_stream(vec![]); let packet_generator_2 = immediate_stream(vec![]); OutputChannelLink::<()>::new() .ingressors(vec![packet_generator_1, packet_generator_2]) .channel(s) .build_link(); } #[test] fn immediate_packets() { let mut runtime = initialize_runtime(); let packets = vec![0, 1, 2, 420, 1337, 3, 4, 5, 6, 7, 8, 9]; let results = runtime.block_on(async { let (send, recv) = crossbeam_channel::unbounded::<i32>(); let link = OutputChannelLink::new() .ingressor(immediate_stream(packets.clone())) .channel(send) .build_link(); let link_results = run_link(link).await; (link_results, recv) }); assert!(results.0.is_empty()); assert_eq!(results.1.iter().collect::<Vec<i32>>(), packets); } #[test]
}
fn small_queue() { let packets = vec![0, 1, 2, 420, 1337, 3, 4, 5, 6, 7, 8, 9]; let mut runtime = initialize_runtime(); let results = runtime.block_on(async { let (send, recv) = crossbeam_channel::bounded::<i32>(2); let recv_thread = thread::spawn(move || { let mut outputs = vec![]; while let Ok(n) = recv.recv() { outputs.push(n); } outputs }); let link = OutputChannelLink::new() .ingressor(immediate_stream(packets.clone())) .channel(send) .build_link(); let link_results = run_link(link).await; let output_results = recv_thread.join().unwrap(); (link_results, output_results) }); assert!(results.0.is_empty()); assert_eq!(results.1, packets); }
function_block-full_function
[ { "content": "struct StreamFromChannel<Packet> {\n\n channel_receiver: crossbeam::Receiver<Packet>,\n\n}\n\n\n\nimpl<Packet> Unpin for StreamFromChannel<Packet> {}\n\n\n\nimpl<Packet> Stream for StreamFromChannel<Packet> {\n\n type Item = Packet;\n\n\n\n fn poll_next(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Option<Self::Item>> {\n\n match self.channel_receiver.try_recv() {\n\n Ok(packet) => Poll::Ready(Some(packet)),\n\n Err(crossbeam_channel::TryRecvError::Empty) => Poll::Pending,\n\n Err(crossbeam_channel::TryRecvError::Disconnected) => Poll::Ready(None),\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "route-rs-runtime/src/link/primitive/input_channel_link.rs", "rank": 0, "score": 287639.1601675237 }, { "content": "pub fn even_link(stream: PacketStream<i32>) -> Link<i32> {\n\n ClassifyLink::new()\n\n .ingressor(stream)\n\n .num_egressors(2)\n\n .classifier(Even::new())\n\n .dispatcher(Box::new(|is_even| if is_even { 0 } else { 1 }))\n\n .build_link()\n\n}\n", "file_path": "route-rs-runtime/src/classifier/even.rs", "rank": 2, "score": 279909.3016661041 }, { "content": "/// Runner is a user facing helper function for running the constructed router.\n\n///\n\n/// Its only argument is a function pointer that takes no arguments and returns a Link type. This\n\n/// master link should contain all the runnables and outputs of the router, which in turn allows\n\n/// this function to initialize and start the Router.\n\n///\n\n/// In general, the `Link` returned by the router should contain only TokioRunnables and no PacketStreams,\n\n/// since production routers are self contained with all their output going to links that push the packets\n\n/// out the routers physical ports.\n\n///\n\n/// However, if the link your `link_builder()` fn provides does return egressors, this function will automatically\n\n/// hook them into `PacketCollector` links, and whatever packets come out of those egressors will be returned to you once\n\n/// the router completes operation and joins. In a production router, the router likely never stops running so\n\n/// nothing will ever get returned. Use this functionality only for testing. \n\npub fn runner<OutputPacket: Debug + Send + Clone + 'static>(\n\n link_builder: fn() -> Link<OutputPacket>,\n\n) -> Vec<Vec<OutputPacket>> {\n\n let mut runtime = runtime::Builder::new()\n\n .threaded_scheduler()\n\n .enable_all()\n\n .build()\n\n .unwrap();\n\n\n\n runtime.block_on(async {\n\n let (mut runnables, egressors) = link_builder();\n\n\n\n let (mut consumers, receivers): (\n\n Vec<TokioRunnable>,\n\n Vec<crossbeam_channel::Receiver<OutputPacket>>,\n\n ) = egressors\n\n .into_iter()\n\n .map(|egressor| {\n\n let (s, r) = crossbeam_channel::unbounded::<OutputPacket>();\n\n // TODO: Do we care about consumer IDs? Are they helpful to debug test examples?\n", "file_path": "route-rs-runtime/src/utils/runner.rs", "rank": 3, "score": 274254.1276727785 }, { "content": "pub fn fizz_buzz_link(stream: PacketStream<i32>) -> Link<i32> {\n\n ClassifyLink::new()\n\n .ingressor(stream)\n\n .num_egressors(4)\n\n .classifier(FizzBuzz::new())\n\n .dispatcher(Box::new(|fb| match fb {\n\n FizzBuzzVariant::FizzBuzz => 0,\n\n FizzBuzzVariant::Fizz => 1,\n\n FizzBuzzVariant::Buzz => 2,\n\n FizzBuzzVariant::None => 3,\n\n }))\n\n .build_link()\n\n}\n", "file_path": "route-rs-runtime/src/classifier/fizz_buzz.rs", "rank": 4, "score": 272586.1568549169 }, { "content": "/// `LinkBuilder` applies a builder pattern to create `Links`! `Links` should be created this way\n\n/// so they can be composed together\n\n///\n\n/// The two type parameters, Input and Output, refer to the input and output types of the Link.\n\n/// You can tell because the ingress/egress streams are of type `PacketStream<Input>`/`PacketStream<Output>` respectively.\n\npub trait LinkBuilder<Input, Output> {\n\n /// Links need a way to receive input from upstream.\n\n /// Some Links such as `ProcessLink` will only need at most 1, but others can accept many.\n\n /// Links that can not support the number of ingressors provided will panic. Links that already have\n\n /// ingressors will panic on calling this function, since we expect this is a user configuration error.\n\n fn ingressors(self, in_streams: Vec<PacketStream<Input>>) -> Self;\n\n\n\n /// Append ingressor to list of ingressors, works like push() for a Vector\n\n /// If the link can not support the addition of another ingressor, it will panic.\n\n fn ingressor(self, in_stream: PacketStream<Input>) -> Self;\n\n\n\n /// Provides any tokio-driven Futures needed to drive the Link, as well as handles for downstream\n\n /// `Link`s to use. This method consumes the `Link` since we want to move ownership of a `Link`'s\n\n /// runnables and egressors to the caller.\n\n fn build_link(self) -> Link<Output>;\n\n}\n\n\n", "file_path": "route-rs-runtime/src/link/mod.rs", "rank": 5, "score": 265488.76208526647 }, { "content": "/// Immediately yields a collection of packets to be poll'd.\n\n/// Thin wrapper around iter_ok.\n\npub fn immediate_stream<I>(collection: I) -> PacketStream<I::Item>\n\nwhere\n\n I: IntoIterator,\n\n I::IntoIter: Send + 'static,\n\n{\n\n Box::new(stream::iter(collection))\n\n}\n\n\n\n/*\n\n LinearIntervalGenerator\n\n\n\n Generates a series of monotonically increasing integers, starting at 0.\n\n `iterations` \"packets\" are generated in the stream. One is yielded every\n\n `duration`.\n\n*/\n\n\n\npub struct LinearIntervalGenerator {\n\n interval: Interval,\n\n iterations: usize,\n\n seq_num: i32,\n", "file_path": "route-rs-runtime/src/utils/test/packet_generators.rs", "rank": 6, "score": 238164.33315319993 }, { "content": "/// `ProcessLink` and `QueueLink` impl `ProcessLinkBuilder`, since they are required to have their\n\n/// Inputs and Outputs match that of their `Processor`.\n\npub trait ProcessLinkBuilder<P: Processor>: LinkBuilder<P::Input, P::Output> {\n\n fn processor(self, processor: P) -> Self;\n\n}\n", "file_path": "route-rs-runtime/src/link/mod.rs", "rank": 7, "score": 227762.52705832542 }, { "content": "pub fn build_link(\n\n index: usize,\n\n link_type: &str,\n\n setters: Vec<(syn::Ident, Vec<syn::Expr>)>,\n\n num_egressors: usize,\n\n) -> Vec<syn::Stmt> {\n\n let mut stmts = vec![];\n\n\n\n stmts.push(syn::Stmt::Local(syn::Local {\n\n attrs: vec![],\n\n let_token: syn::token::Let { span: fake_span() },\n\n pat: syn::Pat::Tuple(syn::PatTuple {\n\n attrs: vec![],\n\n paren_token: syn::token::Paren { span: fake_span() },\n\n elems: syn::punctuated::Punctuated::from_iter(\n\n vec![\n\n syn::Pat::Ident(syn::PatIdent {\n\n attrs: vec![],\n\n by_ref: None,\n\n mutability: Some(syn::token::Mut { span: fake_span() }),\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 8, "score": 201624.5434047595 }, { "content": "/// Generates type declaration statements\n\npub fn typedef(types: Vec<(syn::Ident, syn::Type)>) -> String {\n\n types\n\n .into_iter()\n\n .map(|(new_type, existing_type)| syn::ItemType {\n\n attrs: vec![],\n\n vis: syn::Visibility::Inherited,\n\n type_token: syn::token::Type { span: fake_span() },\n\n ident: new_type,\n\n generics: syn::Generics {\n\n lt_token: None,\n\n params: syn::punctuated::Punctuated::new(),\n\n gt_token: None,\n\n where_clause: None,\n\n },\n\n eq_token: syn::token::Eq {\n\n spans: [fake_span()],\n\n },\n\n ty: Box::new(existing_type),\n\n semi_token: syn::token::Semi {\n\n spans: [fake_span()],\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 9, "score": 191626.90244852426 }, { "content": "pub fn angle_bracketed_types(types: Vec<syn::Type>) -> syn::AngleBracketedGenericArguments {\n\n syn::AngleBracketedGenericArguments {\n\n colon2_token: None,\n\n lt_token: syn::token::Lt {\n\n spans: [fake_span()],\n\n },\n\n args: syn::punctuated::Punctuated::from_iter(\n\n types.into_iter().map(syn::GenericArgument::Type),\n\n ),\n\n gt_token: syn::token::Gt {\n\n spans: [fake_span()],\n\n },\n\n }\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 10, "score": 190149.29302140628 }, { "content": "pub fn call_chain(base: syn::Expr, mut calls: Vec<(&str, Vec<syn::Expr>)>) -> syn::Expr {\n\n match calls[..] {\n\n [] => base,\n\n _ => {\n\n let (outer_function, outer_args) = calls.pop().unwrap();\n\n call_function(\n\n expr_field(call_chain(base, calls), outer_function),\n\n outer_args,\n\n )\n\n }\n\n }\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 11, "score": 172993.95912265463 }, { "content": "pub fn initialize_runtime() -> runtime::Runtime {\n\n runtime::Builder::new()\n\n .threaded_scheduler()\n\n .enable_all()\n\n .build()\n\n .unwrap()\n\n}\n\n\n\npub async fn run_link<OutputPacket: Debug + Send + Clone + 'static>(\n\n link: Link<OutputPacket>,\n\n) -> Vec<Vec<OutputPacket>> {\n\n let (mut runnables, egressors) = link;\n\n\n\n // generate consumers for each egressors\n\n let (mut consumers, receivers): (\n\n Vec<TokioRunnable>,\n\n Vec<crossbeam_channel::Receiver<OutputPacket>>,\n\n ) = egressors\n\n .into_iter()\n\n .map(|egressor| {\n", "file_path": "route-rs-runtime/src/utils/test/harness.rs", "rank": 12, "score": 172951.94879476415 }, { "content": "/// Returns Ipv4 payload type, reads the header information to get the type\n\n/// of IpProtocol payload is included. Upon error, returns IpProtocol::Reserved.\n\npub fn get_ipv4_payload_type(\n\n data: &[u8],\n\n layer3_offset: usize,\n\n) -> Result<IpProtocol, &'static str> {\n\n if data.len() <= layer3_offset + 9 || (data[layer3_offset] & 0xF0) != 0x40 {\n\n // Either data isn't big enough, or the version field does not indicate this is\n\n // an Ipv4 packet.\n\n return Err(\"Is not an Ipv4 packet\");\n\n }\n\n Ok(IpProtocol::from(data[layer3_offset + 9]))\n\n}\n\n\n\nimpl TryFrom<EthernetFrame> for Ipv4Packet {\n\n type Error = &'static str;\n\n\n\n fn try_from(frame: EthernetFrame) -> Result<Self, Self::Error> {\n\n Ipv4Packet::from_buffer(frame.data, Some(frame.layer2_offset), frame.payload_offset)\n\n }\n\n}\n\n\n", "file_path": "route-rs-packets/src/ipv4.rs", "rank": 13, "score": 167572.38315741217 }, { "content": "/// Returns Ipv6 payload type, reads the header information to get the type\n\n/// of IpProtocol payload is included. Upon error, returns IpProtocol::Reserved.\n\npub fn get_ipv6_payload_type(\n\n data: &[u8],\n\n layer3_offset: usize,\n\n) -> Result<IpProtocol, &'static str> {\n\n if data.len() < layer3_offset + 40 || data[layer3_offset] & 0xF0 != 0x60 {\n\n // In the case of error, we return the reserved as an error.\n\n return Err(\"Is not an Ipv6 Packet\");\n\n }\n\n\n\n let mut header = IpProtocol::from(data[layer3_offset + 6]);\n\n let mut header_ext_len;\n\n let mut offset = layer3_offset + 40; // First byte of first header\n\n loop {\n\n match header {\n\n IpProtocol::HOPOPT\n\n | IpProtocol::IPv6_Opts\n\n | IpProtocol::IPv6_route\n\n | IpProtocol::IPv6_frag\n\n | IpProtocol::AH\n\n | IpProtocol::ESP\n", "file_path": "route-rs-packets/src/ipv6.rs", "rank": 14, "score": 167572.38315741217 }, { "content": "/// Simlar to logic to `park_and_wake`, with the key difference being that it\n\n/// takes a provided Arc of the task handle that we wish to park. This enables the\n\n/// callee to park their task handle in multiple locations without fear of overnotificiation.\n\n/// This is used primarily by the egressor of the JoinLink.\n\npub fn indirect_park_and_wake(\n\n task_park: &Arc<AtomicCell<TaskParkState>>,\n\n task: Arc<AtomicCell<Option<task::Waker>>>,\n\n) -> bool {\n\n swap_and_wake(task_park, TaskParkState::IndirectParked(task))\n\n}\n\n\n", "file_path": "route-rs-runtime/src/link/utils/task_park.rs", "rank": 15, "score": 158530.78538672486 }, { "content": "pub fn vec(exprs: Vec<syn::Expr>) -> syn::Expr {\n\n syn::Expr::Macro(syn::ExprMacro {\n\n attrs: vec![],\n\n mac: syn::Macro {\n\n path: simple_path(vec![ident(\"vec\")], false),\n\n bang_token: syn::token::Bang {\n\n spans: [fake_span()],\n\n },\n\n delimiter: syn::MacroDelimiter::Bracket(syn::token::Bracket { span: fake_span() }),\n\n tokens: syn::punctuated::Punctuated::<syn::Expr, syn::token::Comma>::from_iter(exprs)\n\n .to_token_stream(),\n\n },\n\n })\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 16, "score": 154565.60686015 }, { "content": "pub fn for_loop(item: syn::Pat, iterable: syn::Expr, body: Vec<syn::Stmt>) -> syn::Stmt {\n\n syn::Stmt::Expr(syn::Expr::ForLoop(syn::ExprForLoop {\n\n attrs: vec![],\n\n label: None,\n\n for_token: syn::token::For { span: fake_span() },\n\n pat: item,\n\n in_token: syn::token::In { span: fake_span() },\n\n expr: Box::new(iterable),\n\n body: syn::Block {\n\n brace_token: syn::token::Brace { span: fake_span() },\n\n stmts: body,\n\n },\n\n }))\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 17, "score": 142082.86882567412 }, { "content": "pub fn let_simple(\n\n identifier: syn::Ident,\n\n type_annotation: Option<syn::Type>,\n\n expression: syn::Expr,\n\n mutable: bool,\n\n) -> syn::Local {\n\n let id = syn::Pat::Ident(syn::PatIdent {\n\n attrs: vec![],\n\n by_ref: None,\n\n mutability: if mutable {\n\n Some(syn::token::Mut { span: fake_span() })\n\n } else {\n\n None\n\n },\n\n ident: identifier,\n\n subpat: None,\n\n });\n\n syn::Local {\n\n attrs: vec![],\n\n let_token: syn::token::Let { span: fake_span() },\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 18, "score": 141657.05887612834 }, { "content": " channel_receiver: Some(channel_receiver),\n\n }\n\n }\n\n}\n\n\n\nimpl<Packet: Send + 'static> LinkBuilder<(), Packet> for InputChannelLink<Packet> {\n\n fn ingressors(self, mut _in_streams: Vec<PacketStream<()>>) -> Self {\n\n panic!(\"InputChannelLink does not take stream ingressors\")\n\n }\n\n\n\n fn ingressor(self, _in_stream: PacketStream<()>) -> Self {\n\n panic!(\"InputChannelLink does not take any stream ingressors\")\n\n }\n\n\n\n fn build_link(self) -> Link<Packet> {\n\n if self.channel_receiver.is_none() {\n\n panic!(\"Cannot build link! Missing channel\");\n\n } else {\n\n (\n\n vec![],\n\n vec![Box::new(StreamFromChannel {\n\n channel_receiver: self.channel_receiver.unwrap(),\n\n })],\n\n )\n\n }\n\n }\n\n}\n\n\n", "file_path": "route-rs-runtime/src/link/primitive/input_channel_link.rs", "rank": 19, "score": 140117.66576086913 }, { "content": " let packets = vec![0, 1, 2, 420, 1337, 3, 4, 5, 6, 7, 8, 9];\n\n\n\n let mut runtime = initialize_runtime();\n\n let results = runtime.block_on(async {\n\n let (send, recv) = crossbeam_channel::unbounded();\n\n\n\n let link = InputChannelLink::new().channel(recv).build_link();\n\n\n\n for p in packets.clone() {\n\n match send.send(p) {\n\n Ok(_) => (),\n\n Err(e) => panic!(\"could not send to channel! {}\", e),\n\n }\n\n }\n\n drop(send);\n\n\n\n run_link(link).await\n\n });\n\n assert_eq!(results[0], packets);\n\n }\n\n}\n", "file_path": "route-rs-runtime/src/link/primitive/input_channel_link.rs", "rank": 20, "score": 140113.47566013667 }, { "content": "use crate::link::{Link, LinkBuilder, PacketStream};\n\nuse crossbeam::crossbeam_channel;\n\nuse futures::prelude::*;\n\nuse futures::task::{Context, Poll};\n\nuse std::pin::Pin;\n\n\n\n#[derive(Default)]\n\npub struct InputChannelLink<Packet> {\n\n channel_receiver: Option<crossbeam::Receiver<Packet>>,\n\n}\n\n\n\nimpl<Packet> InputChannelLink<Packet> {\n\n pub fn new() -> Self {\n\n InputChannelLink {\n\n channel_receiver: None,\n\n }\n\n }\n\n\n\n pub fn channel(self, channel_receiver: crossbeam::Receiver<Packet>) -> Self {\n\n InputChannelLink {\n", "file_path": "route-rs-runtime/src/link/primitive/input_channel_link.rs", "rank": 21, "score": 140112.52870205502 }, { "content": " use super::*;\n\n use crate::utils::test::harness::{initialize_runtime, run_link};\n\n use crate::utils::test::packet_generators::immediate_stream;\n\n\n\n #[test]\n\n #[should_panic]\n\n fn panics_when_built_with_ingressors() {\n\n InputChannelLink::<()>::new()\n\n .ingressors(vec![immediate_stream(vec![])])\n\n .build_link();\n\n }\n\n\n\n #[test]\n\n #[should_panic]\n\n fn panics_when_built_without_channel() {\n\n InputChannelLink::<()>::new().build_link();\n\n }\n\n\n\n #[test]\n\n fn immediate_packets() {\n", "file_path": "route-rs-runtime/src/link/primitive/input_channel_link.rs", "rank": 22, "score": 140111.06985053024 }, { "content": "pub fn use_glob() -> syn::UseGlob {\n\n syn::UseGlob {\n\n star_token: syn::token::Star {\n\n spans: [fake_span()],\n\n },\n\n }\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 32, "score": 139677.3807579667 }, { "content": "pub fn path(segments: Vec<(syn::Ident, Option<Vec<syn::GenericArgument>>)>) -> syn::Path {\n\n syn::Path {\n\n leading_colon: None,\n\n segments: syn::punctuated::Punctuated::from_iter(segments.into_iter().map(|(id, args)| {\n\n syn::PathSegment {\n\n ident: id,\n\n arguments: match args {\n\n None => Default::default(),\n\n Some(generic_args) => {\n\n syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {\n\n colon2_token: None,\n\n lt_token: syn::token::Lt {\n\n spans: [fake_span()],\n\n },\n\n args: syn::punctuated::Punctuated::from_iter(generic_args),\n\n gt_token: syn::token::Gt {\n\n spans: [fake_span()],\n\n },\n\n })\n\n }\n\n },\n\n }\n\n })),\n\n }\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 33, "score": 137726.7887613689 }, { "content": "pub fn expr_async(stmts: Vec<syn::Stmt>) -> syn::Expr {\n\n syn::Expr::Async(syn::ExprAsync {\n\n attrs: vec![],\n\n async_token: syn::token::Async { span: fake_span() },\n\n capture: None,\n\n block: syn::Block {\n\n brace_token: syn::token::Brace { span: fake_span() },\n\n stmts,\n\n },\n\n })\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 34, "score": 134888.95178718682 }, { "content": "fn router_runner() -> Link<EthernetFrame> {\n\n let data_v4: Vec<u8> = vec![\n\n 0xde, 0xad, 0xbe, 0xef, 0xff, 0xff, 1, 2, 3, 4, 5, 6, 8, 00, 0x45, 0, 0, 20, 0, 0, 0, 0,\n\n 64, 17, 0, 0, 192, 178, 128, 0, 10, 0, 0, 1,\n\n ];\n\n let data_v6: Vec<u8> = vec![\n\n 0xde, 0xad, 0xbe, 0xef, 0xff, 0xff, 1, 2, 3, 4, 5, 6, 0x86, 0xDD, 0x60, 0, 0, 0, 0, 4, 17,\n\n 64, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad,\n\n 0xbe, 0xef, 0x20, 0x01, 0x0d, 0xb8, 0xbe, 0xef, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0xa, 0xb,\n\n 0xc, 0xd,\n\n ];\n\n let frame1 = EthernetFrame::from_buffer(data_v4, 0).unwrap();\n\n let frame2 = EthernetFrame::from_buffer(data_v6, 0).unwrap();\n\n let packets = vec![frame1, frame2];\n\n // Create our router\n\n Router::new()\n\n .ingressors(vec![immediate_stream(packets)])\n\n .build_link()\n\n}\n\n\n", "file_path": "examples/minimal-static-router/src/main.rs", "rank": 35, "score": 133732.11967887 }, { "content": "pub fn builder(base: syn::Ident, setters: Vec<(syn::Ident, Vec<syn::Expr>)>) -> syn::Expr {\n\n let mut expr_accum = syn::Expr::Call(syn::ExprCall {\n\n attrs: vec![],\n\n func: Box::new(syn::Expr::Path(syn::ExprPath {\n\n attrs: vec![],\n\n qself: None,\n\n path: simple_path(vec![base, ident(\"new\")], false),\n\n })),\n\n paren_token: syn::token::Paren { span: fake_span() },\n\n args: Default::default(),\n\n });\n\n\n\n for (method, args) in setters {\n\n expr_accum = syn::Expr::MethodCall(syn::ExprMethodCall {\n\n attrs: vec![],\n\n receiver: Box::new(expr_accum),\n\n dot_token: syn::token::Dot {\n\n spans: [fake_span()],\n\n },\n\n method,\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 36, "score": 133105.60236373794 }, { "content": "/// Notifies a task if it resides in the `task_park`, and then sets\n\n/// the `TaskParkState` to `Dead`.\n\n/// Use when the callee is dropping and will not be able to awaken tasks\n\n/// parked here in the future.\n\npub fn die_and_wake(task_park: &Arc<AtomicCell<TaskParkState>>) {\n\n swap_and_wake(task_park, TaskParkState::Dead);\n\n}\n", "file_path": "route-rs-runtime/src/link/utils/task_park.rs", "rank": 37, "score": 132887.63549546132 }, { "content": "/// Notifies a task if it resides in the `task_park`\n\n/// Use this when you wish you wake up a task but do not wish to sleep yourself\n\npub fn unpark_and_wake(task_park: &Arc<AtomicCell<TaskParkState>>) {\n\n swap_and_wake(task_park, TaskParkState::Empty);\n\n}\n\n\n", "file_path": "route-rs-runtime/src/link/utils/task_park.rs", "rank": 38, "score": 132884.2499407834 }, { "content": "fn gen_source_imports(local_modules: Vec<&str>, runtime_modules: Vec<&str>) -> String {\n\n let mut imports = vec![];\n\n for lm in local_modules {\n\n imports.push(syn::UseTree::Path(codegen::use_path(\n\n \"crate\",\n\n syn::UseTree::Path(codegen::use_path(\n\n lm,\n\n syn::UseTree::Glob(codegen::use_glob()),\n\n )),\n\n )))\n\n }\n\n imports.push(syn::UseTree::Path(codegen::use_path(\n\n \"route_rs_runtime\",\n\n syn::UseTree::Path(codegen::use_path(\n\n \"link\",\n\n syn::UseTree::Glob(codegen::use_glob()),\n\n )),\n\n )));\n\n imports.push(syn::UseTree::Path(codegen::use_path(\n\n \"route_rs_runtime\",\n", "file_path": "route-rs-graphgen/src/main.rs", "rank": 39, "score": 128645.54162801613 }, { "content": "pub fn use_path(name: &str, cont: syn::UseTree) -> syn::UsePath {\n\n syn::UsePath {\n\n ident: ident(name),\n\n colon2_token: syn::token::Colon2 {\n\n spans: [fake_span(), fake_span()],\n\n },\n\n tree: Box::new(cont),\n\n }\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 40, "score": 125501.26950407925 }, { "content": "pub fn simple_path(segments: Vec<syn::Ident>, with_leading_colon: bool) -> syn::Path {\n\n syn::Path {\n\n leading_colon: if with_leading_colon {\n\n Some(syn::token::Colon2 {\n\n spans: [fake_span(), fake_span()],\n\n })\n\n } else {\n\n None\n\n },\n\n segments: syn::punctuated::Punctuated::from_iter(segments.into_iter().map(|s| {\n\n syn::PathSegment {\n\n ident: s,\n\n arguments: syn::PathArguments::None,\n\n }\n\n })),\n\n }\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 41, "score": 125089.24353906582 }, { "content": "/// The single egressor of ProcessLink\n\nstruct ProcessRunner<P: Processor> {\n\n in_stream: PacketStream<P::Input>,\n\n processor: P,\n\n}\n\n\n\nimpl<P: Processor> ProcessRunner<P> {\n\n fn new(in_stream: PacketStream<P::Input>, processor: P) -> Self {\n\n ProcessRunner {\n\n in_stream,\n\n processor,\n\n }\n\n }\n\n}\n\n\n\nimpl<P: Processor> Unpin for ProcessRunner<P> {}\n\n\n\nimpl<P: Processor> Stream for ProcessRunner<P> {\n\n type Item = P::Output;\n\n\n\n /// Intro to `Stream`s:\n", "file_path": "route-rs-runtime/src/link/primitive/process_link.rs", "rank": 42, "score": 124924.04746812006 }, { "content": "/// Used by a ClassifyLink to determine the kind of packet we have. Classifier::Class is then\n\n/// consumed by the dispatcher on the ClassifyLink to send it down the appropriate path.\n\npub trait Classifier {\n\n type Packet: Send + Clone;\n\n type Class: Sized;\n\n\n\n fn classify(&self, packet: &Self::Packet) -> Self::Class;\n\n}\n", "file_path": "route-rs-runtime/src/classifier/mod.rs", "rank": 43, "score": 123692.32980103735 }, { "content": "pub trait Processor {\n\n type Input: Send + Clone;\n\n type Output: Send + Clone;\n\n\n\n fn process(&mut self, packet: Self::Input) -> Option<Self::Output>;\n\n}\n", "file_path": "route-rs-runtime/src/processor/mod.rs", "rank": 44, "score": 123676.87829301915 }, { "content": "/// Generates use statements for the provided package imports\n\npub fn import(imports: &[syn::UseTree]) -> String {\n\n imports\n\n .iter()\n\n .map(|i| {\n\n syn::Item::Use(syn::ItemUse {\n\n attrs: vec![],\n\n vis: syn::Visibility::Inherited,\n\n use_token: syn::token::Use { span: fake_span() },\n\n leading_colon: None,\n\n tree: i.to_owned(),\n\n semi_token: syn::token::Semi {\n\n spans: [fake_span()],\n\n },\n\n })\n\n })\n\n .map(|i| i.to_token_stream().to_string())\n\n .collect::<Vec<String>>()\n\n .join(\"\\n\")\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 45, "score": 123534.62887044073 }, { "content": "pub fn call_function(function: syn::Expr, args: Vec<syn::Expr>) -> syn::Expr {\n\n syn::Expr::Call(syn::ExprCall {\n\n attrs: vec![],\n\n func: Box::new(function),\n\n paren_token: syn::token::Paren { span: fake_span() },\n\n args: syn::punctuated::Punctuated::from_iter(args),\n\n })\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 46, "score": 123359.78786173995 }, { "content": "fn get_array_arg<'a>(arg_matches: &'a ArgMatches, name: &str) -> Vec<&'a str> {\n\n let args: Vec<&str> = arg_matches.value_of(name).unwrap().split(',').collect();\n\n if args.eq(&[\"\"]) {\n\n vec![]\n\n } else {\n\n args\n\n }\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/main.rs", "rank": 47, "score": 122975.48561911975 }, { "content": "/// Notifies a task if it resides in the `task_park`, and\n\n/// then parks the callee task in the `task_park`.\n\n/// Use when you wish to sleep the current task\n\npub fn park_and_wake(task_park: &Arc<AtomicCell<TaskParkState>>, task: task::Waker) {\n\n if !swap_and_wake(task_park, TaskParkState::Parked(task.clone())) {\n\n task.wake();\n\n }\n\n}\n\n\n", "file_path": "route-rs-runtime/src/link/utils/task_park.rs", "rank": 48, "score": 122710.02405187082 }, { "content": "pub fn impl_struct<S, T, U>(trait_name: S, struct_name: T, body: U) -> String\n\nwhere\n\n S: Into<String>,\n\n T: Into<String>,\n\n U: Into<String>,\n\n{\n\n let trait_name_string = trait_name.into();\n\n if trait_name_string == \"\" {\n\n format!(\n\n \"impl {} {{\\n{}\\n}}\",\n\n struct_name.into(),\n\n indent(\" \", body)\n\n )\n\n } else {\n\n format!(\n\n \"impl {} for {} {{\\n{}\\n}}\",\n\n trait_name_string,\n\n struct_name.into(),\n\n indent(\" \", body)\n\n )\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 49, "score": 111634.9404875293 }, { "content": "pub fn closure(\n\n is_async: bool,\n\n is_static: bool,\n\n is_move: bool,\n\n inputs: Vec<syn::Pat>,\n\n return_type: syn::ReturnType,\n\n body: Vec<syn::Stmt>,\n\n) -> syn::Expr {\n\n syn::Expr::Closure(syn::ExprClosure {\n\n attrs: vec![],\n\n asyncness: if is_async {\n\n Some(syn::token::Async { span: fake_span() })\n\n } else {\n\n None\n\n },\n\n movability: if is_static {\n\n Some(syn::token::Static { span: fake_span() })\n\n } else {\n\n None\n\n },\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 50, "score": 108835.33567433998 }, { "content": "fn typed_function_arg(name: &str, typ: syn::Type) -> syn::FnArg {\n\n syn::FnArg::Typed(syn::PatType {\n\n attrs: vec![],\n\n pat: Box::new(syn::Pat::Ident(syn::PatIdent {\n\n attrs: vec![],\n\n by_ref: None,\n\n mutability: None,\n\n ident: ident(name),\n\n subpat: None,\n\n })),\n\n colon_token: syn::token::Colon {\n\n spans: [fake_span()],\n\n },\n\n ty: Box::new(typ),\n\n })\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 51, "score": 108198.9964117515 }, { "content": "pub fn function_def(\n\n name: syn::Ident,\n\n inputs: Vec<(&str, syn::Type)>,\n\n stmts: Vec<syn::Stmt>,\n\n return_type: syn::ReturnType,\n\n) -> syn::Item {\n\n syn::Item::Fn(syn::ItemFn {\n\n attrs: vec![],\n\n vis: syn::Visibility::Inherited,\n\n sig: syn::Signature {\n\n constness: None,\n\n asyncness: None,\n\n unsafety: None,\n\n abi: None,\n\n fn_token: syn::token::Fn { span: fake_span() },\n\n ident: name,\n\n generics: Default::default(),\n\n paren_token: syn::token::Paren { span: fake_span() },\n\n inputs: syn::punctuated::Punctuated::from_iter(\n\n inputs\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 52, "score": 106892.94989028598 }, { "content": "/// Primitive links individually implement all the flow based logic that can be combined to create more compilcated\n\n/// composite links. Users of the library should not have to implement their own primitive links, but should rather combine them into\n\n/// their own custom composite links.\n\npub mod primitive;\n\n\n\n/// Commmon utilities used by links, for instance the `task_park` utility used in primitive links to facilite sleeping and waking.\n\npub mod utils;\n\n\n\n/// All Links communicate through streams of packets. This allows them to be composable.\n\npub type PacketStream<Input> = Box<dyn futures::Stream<Item = Input> + Send + Unpin>;\n\n/// Some Links may need to be driven by Tokio. This represents a handle to something Tokio can run.\n\npub type TokioRunnable = Box<dyn futures::Future<Output = ()> + Send + Unpin>;\n\n/// LinkBuilders build this.\n\npub type Link<Output> = (Vec<TokioRunnable>, Vec<PacketStream<Output>>);\n\n\n\n/// `LinkBuilder` applies a builder pattern to create `Links`! `Links` should be created this way\n\n/// so they can be composed together\n\n///\n\n/// The two type parameters, Input and Output, refer to the input and output types of the Link.\n\n/// You can tell because the ingress/egress streams are of type `PacketStream<Input>`/`PacketStream<Output>` respectively.\n", "file_path": "route-rs-runtime/src/link/mod.rs", "rank": 53, "score": 105367.8753022018 }, { "content": "//! # What are they for?\n\n//!\n\n//! Links are an abstraction used by the runtime to link processors and classifiers together, to manage the flow of packets through the router.\n\n//! Processors and Classifiers, which implement all the non-flow business logic of the router, are loaded into links to create specfic behavior.\n\n//! Links are composed together via the `Link` trait. The `TokioRunnable` portions are handed to Tokio (some Links, such as `QueueLink`, are async\n\n//! and rely on Tokio to pull packets from the upstream.)\n\n//! When the library user uses Graphgen, Links are declared, connected, and placed into a runtime via generated code. The user does this by laying\n\n//! out their desired graph of Processors and Classifiers in a graph file, and Graphgen does all the work from there! Additionally, since all links\n\n//! must implement the LinkBuilder trait, Links are transparently composable at no cost during runtime! The most basic links that implement Poll,\n\n//! Stream and Future are Primitives. Links that are made by wrapping a collection of Links are called Composites. Link composition is a great way\n\n//! to reduce the complexity of your router, and make its design more inspectable. Users of the library are encouraged to create their own Composite\n\n//! Links by composing `Primitives` and other `CompositeLinks` together. This prevents the user from having to worry about the complexities of generically\n\n//! chaining asynchronous computation together around Channels; freeing you to focus on the business logic you would like your router to implement.\n\n\n\nuse crate::processor::Processor;\n\n\n\n/// Composites are groups of links pre-assmebled to provide higher level functionality. They are highly customizable and users of the\n\n/// library are encourged to make their own to encourage code reuse.\n\npub mod composite;\n\n\n", "file_path": "route-rs-runtime/src/link/mod.rs", "rank": 54, "score": 105347.89236203574 }, { "content": "pub mod harness;\n\npub mod packet_collectors;\n\npub mod packet_generators;\n", "file_path": "route-rs-runtime/src/utils/test/mod.rs", "rank": 55, "score": 104051.33768875363 }, { "content": "fn gen_source_pipeline(nodes: Vec<&NodeData>, edges: Vec<&EdgeData>) -> String {\n\n let (input_node, output_node) = get_io_nodes(&nodes, &edges);\n\n [\n\n String::from(\"pub struct Pipeline {}\"),\n\n codegen::impl_struct(\n\n \"route_rs_runtime::pipeline::Runner\",\n\n \"Pipeline\",\n\n [\n\n codegen::typedef(vec![\n\n (\n\n codegen::ident(\"Input\"),\n\n syn::parse_str::<syn::Type>(&input_node.node_class).unwrap(),\n\n ),\n\n (\n\n codegen::ident(\"Output\"),\n\n syn::parse_str::<syn::Type>(&output_node.node_class).unwrap(),\n\n ),\n\n ]),\n\n codegen::function_def(\n\n codegen::ident(\"run\"),\n", "file_path": "route-rs-graphgen/src/main.rs", "rank": 56, "score": 102913.40807947241 }, { "content": "\n\n/// Fairly combines all inputs into a single output, asynchronous.\n\nmod join_link;\n\npub use self::join_link::*;\n\n\n\n/// Copies all input to each of its outputs, asynchronous.\n\nmod fork_link;\n\npub use self::fork_link::*;\n\n\n\n/// Takes a channel for input and converts it to a stream.\n\nmod input_channel_link;\n\npub use self::input_channel_link::*;\n\n\n\n/// Takes a stream and converts it to a channel for output.\n\nmod output_channel_link;\n\npub use self::output_channel_link::*;\n", "file_path": "route-rs-runtime/src/link/primitive/mod.rs", "rank": 57, "score": 102371.61113848553 }, { "content": "/// Basic composite that take in M streams of a type, and outputs that same\n\n/// type to N packets.\n\nmod mton_link;\n\npub use self::mton_link::*;\n\n\n\n/// More complex composite that will take in N ingress streams of type Input,\n\n/// and transforms it using a user provided processor to M Output streams.\n\nmod m_transform_n_link;\n\npub use self::m_transform_n_link::*;\n\n\n\n/// Drops packets with weighted randomness.\n\nmod drop_link;\n\npub use self::drop_link::*;\n", "file_path": "route-rs-runtime/src/link/composite/mod.rs", "rank": 58, "score": 102366.62705011059 }, { "content": "/// A simple pull based link. It is pull based in the sense that packets are only fetched on the input\n\n/// when a packet is requested from the output. This link does not have the abilty store packets internally,\n\n/// so all packets that enter either immediatly leave or are dropped, as dictated by the processor. Both sides of\n\n/// this link are on the same thread, hence the label synchronous.\n\nmod process_link;\n\npub use self::process_link::*;\n\n\n\n/// Input packets are placed into an intermediate channel that are pulled from the output asynchronously.\n\n/// Asynchronous in that a packets may enter and leave this link asynchronously to each other. This link is\n\n/// useful for creating queues in the router, buffering, and creating `Task` boundries that can be processed on\n\n/// different threads, or even different cores. Before packets are placed into the queue to be output, they are run\n\n/// through the processor defined process function, often performing some sort of transformation.\n\n// TODO: Make QueueEgressor package public\n\nmod queue_link;\n\npub use self::queue_link::*;\n\n\n\n/// Uses processor defined classifications to sort input into different channels, a good example would\n\n/// be a flow that splits IPv4 and IPv6 packets, asynchronous.\n\nmod classify_link;\n\npub use self::classify_link::*;\n", "file_path": "route-rs-runtime/src/link/primitive/mod.rs", "rank": 59, "score": 102361.4598953456 }, { "content": "/// A cache for storing task handles.\n\npub mod task_park;\n", "file_path": "route-rs-runtime/src/link/utils/mod.rs", "rank": 60, "score": 102339.13995210218 }, { "content": "fn gen_tokio_run() -> Vec<syn::Stmt> {\n\n vec![\n\n syn::Stmt::Local(codegen::let_simple(\n\n codegen::ident(\"rt\"),\n\n None,\n\n codegen::call_chain(\n\n codegen::call_function(\n\n syn::Expr::Path(syn::ExprPath {\n\n attrs: vec![],\n\n qself: None,\n\n path: codegen::path(vec![\n\n (codegen::ident(\"runtime\"), None),\n\n (codegen::ident(\"Builder\"), None),\n\n (codegen::ident(\"new\"), None),\n\n ]),\n\n }),\n\n vec![],\n\n ),\n\n vec![\n\n (\"threaded_scheduler\", vec![]),\n", "file_path": "route-rs-graphgen/src/main.rs", "rank": 61, "score": 100448.85274071405 }, { "content": "}\n\n\n\nimpl<T: Debug> Future for ExhaustiveDrain<T> {\n\n type Output = ();\n\n\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {\n\n let drain = Pin::into_inner(self);\n\n loop {\n\n match ready!(Pin::new(&mut drain.stream).poll_next(cx)) {\n\n Some(_value) => {}\n\n None => return Poll::Ready(()),\n\n }\n\n }\n\n }\n\n}\n\n\n\n/// Exhaustive Collector works like Exhaustive Drain in that it continuously polls for packets until it\n\n/// receives a None, but it also will write that value out to the provided channel, so that the packet\n\n/// may be compared in a test.\n\npub struct ExhaustiveCollector<T: Debug> {\n", "file_path": "route-rs-runtime/src/utils/test/packet_collectors.rs", "rank": 62, "score": 99876.23374785992 }, { "content": " fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {\n\n let collector = Pin::into_inner(self);\n\n loop {\n\n match ready!(Pin::new(&mut collector.stream).poll_next(cx)) {\n\n Some(value) => {\n\n collector\n\n .packet_dump\n\n .try_send(value)\n\n .expect(\"Exhaustive Collector: Error sending to packet dump\");\n\n }\n\n None => return Poll::Ready(()),\n\n }\n\n }\n\n }\n\n}\n", "file_path": "route-rs-runtime/src/utils/test/packet_collectors.rs", "rank": 63, "score": 99870.90628405598 }, { "content": "use crate::link::PacketStream;\n\nuse crossbeam::crossbeam_channel::Sender;\n\nuse futures::prelude::*;\n\nuse futures::task::{Context, Poll};\n\nuse std::fmt::Debug;\n\nuse std::pin::Pin;\n\n\n\n/// A structure that may be handed an input stream that it will exhaustively drain from until it\n\n/// recieves a None. Useful for testing purposes.\n\npub struct ExhaustiveDrain<T: Debug> {\n\n id: usize,\n\n stream: PacketStream<T>,\n\n}\n\n\n\nimpl<T: Debug> Unpin for ExhaustiveDrain<T> {}\n\n\n\nimpl<T: Debug> ExhaustiveDrain<T> {\n\n pub fn new(id: usize, stream: PacketStream<T>) -> Self {\n\n ExhaustiveDrain { id, stream }\n\n }\n", "file_path": "route-rs-runtime/src/utils/test/packet_collectors.rs", "rank": 64, "score": 99869.69856759111 }, { "content": "}\n\n\n\nimpl<Iterable, Packet> Stream for PacketIntervalGenerator<Iterable, Packet>\n\nwhere\n\n Iterable: Iterator<Item = Packet>,\n\n Packet: Sized,\n\n{\n\n type Item = Packet;\n\n\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {\n\n let interval_generator = Pin::into_inner(self);\n\n ready!(Pin::new(&mut interval_generator.interval).poll_next(cx));\n\n match interval_generator.packets.next() {\n\n Some(packet) => Poll::Ready(Some(packet)),\n\n None => Poll::Ready(None),\n\n }\n\n }\n\n}\n", "file_path": "route-rs-runtime/src/utils/test/packet_generators.rs", "rank": 65, "score": 99860.2186493231 }, { "content": "}\n\n\n\nimpl LinearIntervalGenerator {\n\n pub fn new(duration: Duration, iterations: usize) -> Self {\n\n LinearIntervalGenerator {\n\n interval: interval(duration),\n\n iterations,\n\n seq_num: 0,\n\n }\n\n }\n\n}\n\n\n\nimpl Stream for LinearIntervalGenerator {\n\n type Item = i32;\n\n\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {\n\n ready!(Pin::new(&mut self.interval).poll_next(cx));\n\n if self.seq_num as usize > self.iterations {\n\n Poll::Ready(None)\n\n } else {\n", "file_path": "route-rs-runtime/src/utils/test/packet_generators.rs", "rank": 66, "score": 99856.16098756847 }, { "content": "use crate::link::PacketStream;\n\nuse futures::prelude::*;\n\nuse futures::task::{Context, Poll};\n\nuse std::pin::Pin;\n\nuse tokio::time::{interval, Duration, Interval};\n\n\n\n/// Immediately yields a collection of packets to be poll'd.\n\n/// Thin wrapper around iter_ok.\n", "file_path": "route-rs-runtime/src/utils/test/packet_generators.rs", "rank": 67, "score": 99852.06601757681 }, { "content": " id: usize,\n\n stream: PacketStream<T>,\n\n packet_dump: Sender<T>,\n\n}\n\n\n\nimpl<T: Debug> Unpin for ExhaustiveCollector<T> {}\n\n\n\nimpl<T: Debug> ExhaustiveCollector<T> {\n\n pub fn new(id: usize, stream: PacketStream<T>, packet_dump: Sender<T>) -> Self {\n\n ExhaustiveCollector {\n\n id,\n\n stream,\n\n packet_dump,\n\n }\n\n }\n\n}\n\n\n\nimpl<T: Debug> Future for ExhaustiveCollector<T> {\n\n type Output = ();\n\n\n", "file_path": "route-rs-runtime/src/utils/test/packet_collectors.rs", "rank": 68, "score": 99851.85951618236 }, { "content": " let next_packet = Poll::Ready(Some(self.seq_num));\n\n self.seq_num += 1;\n\n next_packet\n\n }\n\n }\n\n}\n\n\n\n/// Packet Interval Generator procduces a Stream of packets on a defined interval.AsMut\n\n///\n\n/// Which packet is next sent is determined by the Iterator, provided during creation. This\n\n/// is intended to be a full fledged packet eventually, but the trait bound is only set to\n\n/// something that is Sized. The Iterator is polled until it runs out of values, at which\n\n/// point we close the Stream by sending a Ready(None).\n\npub struct PacketIntervalGenerator<Iterable, Packet>\n\nwhere\n\n Iterable: Iterator<Item = Packet>,\n\n Packet: Sized,\n\n{\n\n interval: Interval,\n\n packets: Iterable,\n", "file_path": "route-rs-runtime/src/utils/test/packet_generators.rs", "rank": 69, "score": 99847.06331398933 }, { "content": "}\n\n\n\nimpl<Iterable, Packet> Unpin for PacketIntervalGenerator<Iterable, Packet>\n\nwhere\n\n Iterable: Iterator<Item = Packet>,\n\n Packet: Sized,\n\n{\n\n}\n\n\n\nimpl<Iterable, Packet> PacketIntervalGenerator<Iterable, Packet>\n\nwhere\n\n Iterable: Iterator<Item = Packet>,\n\n Packet: Sized,\n\n{\n\n pub fn new(duration: Duration, packets: Iterable) -> Self {\n\n PacketIntervalGenerator {\n\n interval: interval(duration),\n\n packets,\n\n }\n\n }\n", "file_path": "route-rs-runtime/src/utils/test/packet_generators.rs", "rank": 70, "score": 99838.9511795335 }, { "content": "pub fn magic_newline() -> syn::Macro {\n\n syn::Macro {\n\n path: simple_path(vec![ident(\"graphgen_magic_newline\")], false),\n\n bang_token: syn::token::Bang {\n\n spans: [fake_span()],\n\n },\n\n delimiter: syn::MacroDelimiter::Paren(syn::token::Paren { span: fake_span() }),\n\n tokens: proc_macro2::TokenStream::new(),\n\n }\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 71, "score": 98949.98295095023 }, { "content": "#[test]\n\n#[ignore]\n\nfn layer2_loopback() {\n\n // If this takes more than a second to occur, something's definitely wrong.\n\n let timeout = Duration::from_secs(1);\n\n\n\n let mut rng = rand::thread_rng();\n\n\n\n let iface_name = CString::new(\"lo\").unwrap();\n\n\n\n let side_a = afpacket::Socket::new().unwrap();\n\n let mut side_a = side_a.bind(&iface_name).unwrap();\n\n\n\n let side_b = afpacket::Socket::new().unwrap();\n\n\n\n let (tx, rx) = mpsc::channel();\n\n\n\n let thread_b = thread::spawn(move || {\n\n let mut side_b = side_b.bind(&iface_name).unwrap();\n\n side_b.set_promiscuous(true).unwrap();\n\n\n\n println!(\"b: recving packet\");\n", "file_path": "afpacket/tests/afpacket_tests.rs", "rank": 72, "score": 98892.43820036235 }, { "content": "pub fn magic_newline_stmt() -> syn::Stmt {\n\n syn::Stmt::Semi(\n\n syn::Expr::Macro(syn::ExprMacro {\n\n attrs: vec![],\n\n mac: magic_newline(),\n\n }),\n\n syn::token::Semi {\n\n spans: [fake_span()],\n\n },\n\n )\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 73, "score": 97297.3888702424 }, { "content": "#[test]\n\nfn dns_interceptor() {\n\n let test_helper = test_helper::TestHelper::new(\"dns-interceptor\", vec![\"--rustfmt\"]);\n\n\n\n test_helper.run_graphgen();\n\n test_helper.run_diff();\n\n}\n", "file_path": "route-rs-graphgen/tests/tests.rs", "rank": 74, "score": 97039.65461801819 }, { "content": "#[test]\n\nfn trivial_identity() {\n\n let test_helper = test_helper::TestHelper::new(\n\n \"trivial-identity\",\n\n vec![\n\n \"--rustfmt\",\n\n \"--local-modules\",\n\n \"packets\",\n\n \"--runtime-modules\",\n\n \"processor\",\n\n ],\n\n );\n\n\n\n test_helper.run_graphgen();\n\n test_helper.run_diff();\n\n}\n\n\n", "file_path": "route-rs-graphgen/tests/tests.rs", "rank": 75, "score": 97039.65461801819 }, { "content": "#[test]\n\n#[ignore]\n\nfn layer2_loopback() {\n\n // If this takes more than a second to occur, something's definitely wrong.\n\n let timeout = Duration::from_secs(1);\n\n\n\n let mut rt = runtime::Runtime::new().unwrap();\n\n\n\n rt.block_on(async {\n\n let mut rng = rand::thread_rng();\n\n let iface_name = CString::new(\"lo\").unwrap();\n\n\n\n let mut side_a = afpacket::AsyncBoundSocket::from_interface(&iface_name).unwrap();\n\n\n\n let (mut tx, mut rx) = mpsc::channel(1);\n\n\n\n let task_b = tokio::spawn(async move {\n\n let mut side_b = afpacket::AsyncBoundSocket::from_interface(&iface_name).unwrap();\n\n side_b.set_promiscuous(true).unwrap();\n\n\n\n println!(\"b: receiving packet\");\n\n let mut in_buffer = vec![0; 1500];\n", "file_path": "afpacket/tests/afpacket_tokio_tests.rs", "rank": 76, "score": 97039.5962478115 }, { "content": "pub fn unmagic_newlines(source: String) -> String {\n\n let re = Regex::new(\"graphgen_magic_newline\\\\s*!\\\\s*\\\\(\\\\s*\\\\)\\\\s*;\").unwrap();\n\n re.replace_all(source.as_str(), \"\\n\\n\").to_string()\n\n}\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 77, "score": 95465.82020044175 }, { "content": "/// Given an EventReader of XML source code, returns a vector of nodes and a vector of edges\n\n/// extracted from that source.\n\n///\n\n/// Nodes with the rhombus shape are considered IO types. Nodes with the default shape are\n\n/// considered Processor types.\n\nfn nodes_edges_from_xml<R: Read>(xml_source: EventReader<R>) -> (Vec<NodeData>, Vec<EdgeData>) {\n\n let mut nodes = vec![];\n\n let mut edges = vec![];\n\n\n\n for event in xml_source {\n\n if let Ok(XmlEvent::StartElement {\n\n name:\n\n OwnedName {\n\n local_name: xml_node_name,\n\n ..\n\n },\n\n attributes: attrs,\n\n ..\n\n }) = event\n\n {\n\n if xml_node_name == \"mxCell\" {\n\n if has_attr(&attrs, \"vertex\") {\n\n let styles = get_styles(&attrs);\n\n nodes.push(NodeData {\n\n xml_node_id: get_attr(&attrs, \"id\").unwrap(),\n", "file_path": "route-rs-graphgen/src/pipeline_graph.rs", "rank": 78, "score": 94962.9517325587 }, { "content": "pub fn ident(name: &str) -> syn::Ident {\n\n syn::Ident::new(name, fake_span())\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 79, "score": 93820.29986612625 }, { "content": "pub fn expr_path_ident(id: &str) -> syn::Expr {\n\n syn::Expr::Path(syn::ExprPath {\n\n attrs: vec![],\n\n qself: None,\n\n path: simple_path(vec![ident(id)], false),\n\n })\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 80, "score": 90756.0008198135 }, { "content": "/// Puts the provided text inside comments\n\npub fn comment<S: Into<String>>(text: S) -> String {\n\n text.into()\n\n .lines()\n\n .map(|l| format!(\"// {}\", l))\n\n .collect::<Vec<String>>()\n\n .join(\"\\n\")\n\n}\n\n\n\n#[cfg(test)]\n\nmod comment {\n\n use super::*;\n\n\n\n #[test]\n\n fn single_line() {\n\n assert_eq!(comment(\"Hello world\"), \"// Hello world\");\n\n }\n\n\n\n #[test]\n\n fn multi_line() {\n\n assert_eq!(comment(\"Hello\\nWorld\"), \"// Hello\\n// World\")\n\n }\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 81, "score": 89414.17054505846 }, { "content": "pub trait Runner {\n\n type Input: Sized;\n\n type Output: Sized;\n\n\n\n fn run(\n\n input_channel: crossbeam::Receiver<Self::Input>,\n\n output_channel: crossbeam::Sender<Self::Output>,\n\n ) -> ();\n\n}\n", "file_path": "route-rs-runtime/src/pipeline/runner.rs", "rank": 82, "score": 89069.08418756128 }, { "content": "fn main() {\n\n let data_v4: Vec<u8> = vec![\n\n 0xde, 0xad, 0xbe, 0xef, 0xff, 0xff, 1, 2, 3, 4, 5, 6, 8, 00, 0x45, 0, 0, 20, 0, 0, 0, 0,\n\n 64, 17, 0, 0, 192, 178, 128, 0, 10, 0, 0, 1,\n\n ];\n\n let data_v6: Vec<u8> = vec![\n\n 0xde, 0xad, 0xbe, 0xef, 0xff, 0xff, 1, 2, 3, 4, 5, 6, 0x86, 0xDD, 0x60, 0, 0, 0, 0, 4, 17,\n\n 64, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad,\n\n 0xbe, 0xef, 0x20, 0x01, 0x0d, 0xb8, 0xbe, 0xef, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0xa, 0xb,\n\n 0xc, 0xd,\n\n ];\n\n let test_frame1 = EthernetFrame::from_buffer(data_v4, 0).unwrap();\n\n let test_frame2 = EthernetFrame::from_buffer(data_v6, 0).unwrap();\n\n\n\n let results = runner(router_runner);\n\n println!(\"It finished!\");\n\n\n\n assert_eq!(results[1][0], test_frame1);\n\n assert_eq!(results[2][0], test_frame2);\n\n println!(\"Got all packets on the expected interface!\");\n\n}\n\n\n", "file_path": "examples/minimal-static-router/src/main.rs", "rank": 83, "score": 87372.78958952332 }, { "content": "/// Indents every non-blank line in the input text by the given string.\n\npub fn indent<S, T>(indentation: S, text: T) -> String\n\nwhere\n\n S: Into<String>,\n\n T: Into<String>,\n\n{\n\n let indent_string = indentation.into();\n\n text.into()\n\n .lines()\n\n .map(|l| {\n\n if !l.is_empty() {\n\n format!(\"{}{}\", indent_string, String::from(l))\n\n } else {\n\n String::from(l)\n\n }\n\n })\n\n .collect::<Vec<String>>()\n\n .join(\"\\n\")\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 84, "score": 85270.6537103141 }, { "content": "fn gen_link_decls(\n\n links: &[(XmlNodeId, Link)],\n\n processor_decls: HashMap<String, String>,\n\n) -> Vec<syn::Stmt> {\n\n let mut decl_idx: usize = 0;\n\n let mut link_decls_map = HashMap::new();\n\n let decls: Vec<Vec<syn::Stmt>> = links\n\n .iter()\n\n .map(|(id, el)| {\n\n decl_idx += 1;\n\n match el {\n\n Link::Input => {\n\n link_decls_map.insert((id.to_owned(), None), format!(\"link_{}_egress_{}\", decl_idx, 0));\n\n codegen::build_link(\n\n decl_idx,\n\n \"InputChannelLink\",\n\n vec![\n\n (codegen::ident(\"channel\"), vec![codegen::expr_path_ident(\"input_channel\")]),\n\n ],\n\n 1\n", "file_path": "route-rs-graphgen/src/main.rs", "rank": 85, "score": 83803.8406209022 }, { "content": "fn expand_join_link<'a>(\n\n feeders: &[&&EdgeData],\n\n links: &mut Vec<(String, Link)>,\n\n orig_xml_node_id: &str,\n\n link_builder: Box<dyn Fn(XmlNodeId, Option<String>) -> Link + 'a>,\n\n) {\n\n if feeders.len() == 1 {\n\n links.push((\n\n orig_xml_node_id.to_owned(),\n\n link_builder(feeders[0].source.to_owned(), feeders[0].label.to_owned()),\n\n ))\n\n } else {\n\n let join_xml_node_id = [\"join\", &orig_xml_node_id].join(\"_\");\n\n let join_feeders = feeders\n\n .iter()\n\n .map(|f| (f.source.to_owned(), f.label.to_owned()))\n\n .collect::<Vec<(XmlNodeId, Option<String>)>>();\n\n links.push((join_xml_node_id.to_owned(), Link::Join(join_feeders)));\n\n links.push((\n\n orig_xml_node_id.to_owned(),\n\n link_builder(join_xml_node_id, None),\n\n ));\n\n }\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/main.rs", "rank": 86, "score": 82717.24520617133 }, { "content": "fn gen_processor_decls(processors: &[&&NodeData]) -> (Vec<syn::Stmt>, HashMap<String, String>) {\n\n let mut decl_idx: usize = 1;\n\n let mut processor_decls_map = HashMap::new();\n\n let decls: Vec<syn::Stmt> = processors\n\n .iter()\n\n .map(|e| {\n\n let symbol = format!(\"elem_{}_{}\", decl_idx, e.node_class.to_lowercase());\n\n decl_idx += 1;\n\n processor_decls_map.insert(e.xml_node_id.to_owned(), symbol.clone());\n\n syn::Stmt::Local(codegen::let_simple(\n\n codegen::ident(symbol.as_str()),\n\n None,\n\n syn::Expr::Call(syn::ExprCall {\n\n attrs: vec![],\n\n func: Box::new(syn::Expr::Path(syn::ExprPath {\n\n attrs: vec![],\n\n qself: None,\n\n path: codegen::simple_path(\n\n vec![codegen::ident(&e.node_class), codegen::ident(\"new\")],\n\n false,\n", "file_path": "route-rs-graphgen/src/main.rs", "rank": 87, "score": 82666.4641558639 }, { "content": "pub fn expr_field(base: syn::Expr, field_name: &str) -> syn::Expr {\n\n syn::Expr::Field(syn::ExprField {\n\n attrs: vec![],\n\n base: Box::new(base),\n\n dot_token: syn::token::Dot {\n\n spans: [fake_span()],\n\n },\n\n member: syn::Member::Named(ident(field_name)),\n\n })\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/codegen.rs", "rank": 88, "score": 82613.68845394523 }, { "content": "/// Swaps in the provided TaskParkState. wakes any task that it finds currently in the `task_park`\n\n/// Returns `true` if it was able to successfully park the provided task, ie the `task_park` is not dead.\n\nfn swap_and_wake(task_park: &Arc<AtomicCell<TaskParkState>>, swap: TaskParkState) -> bool {\n\n match task_park.swap(swap) {\n\n TaskParkState::Dead => {\n\n task_park.store(TaskParkState::Dead);\n\n false\n\n }\n\n TaskParkState::Empty => true,\n\n TaskParkState::Parked(task) => {\n\n task.wake();\n\n true\n\n }\n\n TaskParkState::IndirectParked(task) => {\n\n if let Some(task) = task.swap(None) {\n\n task.wake();\n\n }\n\n true\n\n }\n\n }\n\n}\n\n\n", "file_path": "route-rs-runtime/src/link/utils/task_park.rs", "rank": 89, "score": 81448.02573405446 }, { "content": "fn get_pathbuf_arg(arg_matches: &ArgMatches, name: &str) -> PathBuf {\n\n Path::new(arg_matches.value_of(name).unwrap()).to_path_buf()\n\n}\n\n\n", "file_path": "route-rs-graphgen/src/main.rs", "rank": 90, "score": 79655.32315123694 }, { "content": " /// #4 If our upstream `PacketStream` has a packet for us, we pass it to our `processor`\n\n /// for `process`ing. Most of the time, it will yield a `Some(output_packet)` that has\n\n /// been transformed in some way. We pass that on to our egress channel and wake\n\n /// our `Egressor` that it has work to do, and continue polling our upstream `PacketStream`.\n\n ///\n\n /// #5 `processor`s may also choose to \"drop\" packets by returning `None`, so we do nothing\n\n /// and poll our upstream `PacketStream` again.\n\n ///\n\n fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {\n\n loop {\n\n if self.to_egressor.is_full() {\n\n park_and_wake(&self.task_park, cx.waker().clone());\n\n return Poll::Pending;\n\n }\n\n let input_packet_option: Option<P::Input> =\n\n ready!(Pin::new(&mut self.input_stream).poll_next(cx));\n\n\n\n match input_packet_option {\n\n None => {\n\n self.to_egressor.try_send(None).expect(\n", "file_path": "route-rs-runtime/src/link/primitive/queue_link.rs", "rank": 91, "score": 74275.88297606642 }, { "content": "\n\n /// If any of the channels are full, we await that channel to clear before processing a new packet.\n\n fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {\n\n loop {\n\n for (port, to_egressor) in self.to_egressors.iter().enumerate() {\n\n if to_egressor.is_full() {\n\n park_and_wake(&self.task_parks[port], cx.waker().clone());\n\n return Poll::Pending;\n\n }\n\n }\n\n let packet_option: Option<P> = ready!(Pin::new(&mut self.input_stream).poll_next(cx));\n\n\n\n match packet_option {\n\n None => {\n\n for to_egressor in self.to_egressors.iter() {\n\n if let Err(err) = to_egressor.try_send(None) {\n\n panic!(\"Ingressor: Drop: try_send to egressor, fail?: {:?}\", err);\n\n }\n\n }\n\n for task_park in self.task_parks.iter() {\n", "file_path": "route-rs-runtime/src/link/primitive/fork_link.rs", "rank": 92, "score": 74274.8484811455 }, { "content": "use crate::link::utils::task_park::*;\n\nuse crate::link::{Link, LinkBuilder, PacketStream, TokioRunnable};\n\nuse crossbeam::atomic::AtomicCell;\n\nuse crossbeam::crossbeam_channel;\n\nuse crossbeam::crossbeam_channel::{Receiver, Sender};\n\nuse futures::prelude::*;\n\nuse futures::task::{Context, Poll};\n\nuse std::pin::Pin;\n\nuse std::sync::Arc;\n\n\n\n#[derive(Default)]\n\npub struct JoinLink<Packet: Send + Clone> {\n\n in_streams: Option<Vec<PacketStream<Packet>>>,\n\n queue_capacity: usize,\n\n}\n\n\n\nimpl<Packet: Send + Clone> JoinLink<Packet> {\n\n pub fn new() -> Self {\n\n JoinLink {\n\n in_streams: None,\n", "file_path": "route-rs-runtime/src/link/primitive/join_link.rs", "rank": 93, "score": 74272.82941265401 }, { "content": " fn small_channel() {\n\n let mut runtime = initialize_runtime();\n\n let packets = vec![0, 1, 2, 420, 1337, 3, 4, 5, 6, 7, 8, 9, 11];\n\n let results = runtime.block_on(async {\n\n let mut input_streams: Vec<PacketStream<usize>> = Vec::new();\n\n input_streams.push(immediate_stream(packets.clone()));\n\n input_streams.push(immediate_stream(packets.clone()));\n\n\n\n let link = JoinLink::new().ingressors(input_streams).build_link();\n\n\n\n run_link(link).await\n\n });\n\n assert_eq!(results[0].len(), packets.len() * 2);\n\n }\n\n\n\n #[test]\n\n fn empty_stream() {\n\n let mut runtime = initialize_runtime();\n\n let results = runtime.block_on(async {\n\n let mut input_streams: Vec<PacketStream<usize>> = Vec::new();\n", "file_path": "route-rs-runtime/src/link/primitive/join_link.rs", "rank": 94, "score": 74271.94225128068 }, { "content": " assert_eq!(results[0].len(), packets.len() * 2);\n\n }\n\n\n\n #[test]\n\n fn fairness_test() {\n\n let mut runtime = initialize_runtime();\n\n let results = runtime.block_on(async {\n\n //If fairness changes, may need to update test\n\n let mut input_streams: Vec<PacketStream<usize>> = Vec::new();\n\n input_streams.push(immediate_stream(vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));\n\n input_streams.push(immediate_stream(vec![1, 1, 1, 1]));\n\n\n\n let link = JoinLink::new().ingressors(input_streams).build_link();\n\n\n\n run_link(link).await\n\n });\n\n assert_eq!(results[0][0..10].iter().sum::<usize>(), 4);\n\n }\n\n\n\n #[test]\n", "file_path": "route-rs-runtime/src/link/primitive/join_link.rs", "rank": 95, "score": 74271.34435412155 }, { "content": " None => return Poll::Ready(None),\n\n Some(input_packet) => {\n\n // if `processor.process` returns None, do nothing, loop around and try polling again.\n\n if let Some(output_packet) = self.processor.process(input_packet) {\n\n return Poll::Ready(Some(output_packet));\n\n }\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::processor::{Drop, Identity, TransformFrom};\n\n use crate::utils::test::harness::{initialize_runtime, run_link};\n\n use crate::utils::test::packet_generators::{immediate_stream, PacketIntervalGenerator};\n\n use core::time;\n\n\n", "file_path": "route-rs-runtime/src/link/primitive/process_link.rs", "rank": 96, "score": 74270.7900328534 }, { "content": " ///\n\n /// #2 The input_stream returns a NotReady, we sleep, with the assumption\n\n /// that whomever produced the NotReady will awaken the task in the Future.\n\n ///\n\n /// #3 We get a Ready(None), in which case we push a None onto the to_egressor\n\n /// queue and then return Ready(()), which means we enter tear-down, since there\n\n /// is no futher work to complete.\n\n /// ###\n\n /// By Sleep, we mean we return a NotReady to the runtime which will sleep the task.\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {\n\n let ingressor = Pin::into_inner(self);\n\n loop {\n\n if ingressor.to_egressor.is_full() {\n\n park_and_wake(&ingressor.task_park, cx.waker().clone()); //TODO: Change task park to cx based\n\n return Poll::Pending;\n\n }\n\n let input_packet_option: Option<Packet> =\n\n ready!(Pin::new(&mut ingressor.input_stream).poll_next(cx));\n\n\n\n match input_packet_option {\n", "file_path": "route-rs-runtime/src/link/primitive/join_link.rs", "rank": 97, "score": 74269.33040066254 }, { "content": " .queue_capacity(4)\n\n .ingressors(vec![immediate_stream(packets)])\n\n .build_link();\n\n }\n\n\n\n #[test]\n\n fn join_link() {\n\n let packets = vec![0, 1, 2, 420, 1337, 3, 4, 5, 6, 7, 8, 9, 11];\n\n\n\n let mut runtime = initialize_runtime();\n\n let results = runtime.block_on(async {\n\n let mut input_streams: Vec<PacketStream<usize>> = Vec::new();\n\n input_streams.push(immediate_stream(packets.clone()));\n\n input_streams.push(immediate_stream(packets.clone()));\n\n\n\n let link = JoinLink::new().ingressors(input_streams).build_link();\n\n\n\n run_link(link).await\n\n });\n\n assert_eq!(results[0].len(), packets.len() * 2);\n", "file_path": "route-rs-runtime/src/link/primitive/join_link.rs", "rank": 98, "score": 74269.0029373861 }, { "content": " if self.in_stream.is_none() {\n\n panic!(\"Cannot build link! Missing input streams\");\n\n } else if self.classifier.is_none() {\n\n panic!(\"Cannot build link! Missing classifier\");\n\n } else if self.dispatcher.is_none() {\n\n panic!(\"Cannot build link! Missing dispatcher\");\n\n } else if self.num_egressors.is_none() {\n\n panic!(\"Cannot build link! Missing num_egressors\");\n\n } else {\n\n let mut to_egressors: Vec<Sender<Option<C::Packet>>> = Vec::new();\n\n let mut egressors: Vec<PacketStream<C::Packet>> = Vec::new();\n\n\n\n let mut from_ingressors: Vec<Receiver<Option<C::Packet>>> = Vec::new();\n\n\n\n let mut task_parks: Vec<Arc<AtomicCell<TaskParkState>>> = Vec::new();\n\n\n\n for _ in 0..self.num_egressors.unwrap() {\n\n let (to_egressor, from_ingressor) =\n\n crossbeam_channel::bounded::<Option<C::Packet>>(self.queue_capacity);\n\n let task_park = Arc::new(AtomicCell::new(TaskParkState::Empty));\n", "file_path": "route-rs-runtime/src/link/primitive/classify_link.rs", "rank": 99, "score": 74268.49791345914 } ]
Rust
libs/user-facing-errors/src/lib.rs
ever0de/prisma-engines
4c9d4edf238ad9c4a706eb5b7201ee0b4ebee93e
#![deny(warnings, rust_2018_idioms)] mod panic_hook; pub mod common; pub mod introspection_engine; pub mod migration_engine; #[cfg(feature = "sql")] pub mod quaint; pub mod query_engine; use serde::{Deserialize, Serialize}; use std::borrow::Cow; pub use panic_hook::set_panic_hook; pub trait UserFacingError: serde::Serialize { const ERROR_CODE: &'static str; fn message(&self) -> String; } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug)] pub struct KnownError { pub message: String, pub meta: serde_json::Value, pub error_code: Cow<'static, str>, } impl KnownError { pub fn new<T: UserFacingError>(inner: T) -> KnownError { KnownError { message: inner.message(), meta: serde_json::to_value(&inner).expect("Failed to render user facing error metadata to JSON"), error_code: Cow::from(T::ERROR_CODE), } } } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct UnknownError { pub message: String, pub backtrace: Option<String>, } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct Error { is_panic: bool, #[serde(flatten)] inner: ErrorType, } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] #[serde(untagged)] enum ErrorType { Known(KnownError), Unknown(UnknownError), } impl Error { pub fn as_known(&self) -> Option<&KnownError> { match &self.inner { ErrorType::Known(err) => Some(err), ErrorType::Unknown(_) => None, } } pub fn message(&self) -> &str { match &self.inner { ErrorType::Known(err) => &err.message, ErrorType::Unknown(err) => &err.message, } } pub fn new_non_panic_with_current_backtrace(message: String) -> Self { Error { inner: ErrorType::Unknown(UnknownError { message, backtrace: Some(format!("{:?}", backtrace::Backtrace::new())), }), is_panic: false, } } pub fn from_dyn_error(err: &dyn std::error::Error) -> Self { Error { inner: ErrorType::Unknown(UnknownError { message: err.to_string(), backtrace: None, }), is_panic: false, } } pub fn new_in_panic_hook(panic_info: &std::panic::PanicInfo<'_>) -> Self { let message = panic_info .payload() .downcast_ref::<&str>() .map(|s| -> String { (*s).to_owned() }) .or_else(|| panic_info.payload().downcast_ref::<String>().map(|s| s.to_owned())) .unwrap_or_else(|| "<unknown panic>".to_owned()); let backtrace = Some(format!("{:?}", backtrace::Backtrace::new())); let location = panic_info .location() .map(|loc| format!("{}", loc)) .unwrap_or_else(|| "<unknown location>".to_owned()); Error { inner: ErrorType::Unknown(UnknownError { message: format!("[{}] {}", location, message), backtrace, }), is_panic: true, } } pub fn new_known(err: KnownError) -> Self { Error { inner: ErrorType::Known(err), is_panic: false, } } pub fn from_panic_payload(panic_payload: Box<dyn std::any::Any + Send + 'static>) -> Self { let message = Self::extract_panic_message(panic_payload).unwrap_or_else(|| "<unknown panic>".to_owned()); Error { inner: ErrorType::Unknown(UnknownError { message, backtrace: None, }), is_panic: true, } } pub fn extract_panic_message(panic_payload: Box<dyn std::any::Any + Send + 'static>) -> Option<String> { panic_payload .downcast_ref::<&str>() .map(|s| -> String { (*s).to_owned() }) .or_else(|| panic_payload.downcast_ref::<String>().map(|s| s.to_owned())) } pub fn unwrap_known(self) -> KnownError { match self.inner { ErrorType::Known(err) => err, err @ ErrorType::Unknown(_) => panic!("Expected known error, got {:?}", err), } } } pub fn new_backtrace() -> backtrace::Backtrace { backtrace::Backtrace::new() } impl From<UnknownError> for Error { fn from(unknown_error: UnknownError) -> Self { Error { inner: ErrorType::Unknown(unknown_error), is_panic: false, } } } impl From<KnownError> for Error { fn from(known_error: KnownError) -> Self { Error { is_panic: false, inner: ErrorType::Known(known_error), } } }
#![deny(warnings, rust_2018_idioms)] mod panic_hook; pub mod common; pub mod introspection_engine; pub mod migration_engine; #[cfg(feature = "sql")] pub mod quaint; pub mod query_engine; use serde::{Deserialize, Serialize}; use std::borrow::Cow; pub use panic_hook::set_panic_hook; pub trait UserFacingError: serde::Serialize { const ERROR_CODE: &'static str; fn message(&self) -> String; } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug)] pub struct KnownError { pub message: String, pub meta: serde_json::Value, pub error_code: Cow<'static, str>, } impl KnownError { pub fn new<T: UserFacingError>(inner: T) -> KnownError { KnownError { message: inner.message(), meta: serde_json::to_value(&inner).expect("Failed to render user facing error metadata to JSON"), error_code: Cow::from(T::ERROR_CODE), } } } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct UnknownError { pub message: String, pub backtrace: Option<String>, } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct Error { is_panic: bool, #[serde(flatten)] inner: ErrorType, } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] #[serde(untagged)] enum ErrorType { Known(KnownError), Unknown(UnknownError), } impl Error { pub fn as_known(&self) -> Option<&KnownError> { match &self.inner { ErrorType::Known(err) => Some(err), ErrorType::Unknown(_) => None, } } pub fn message(&self) -> &str { match &self.inner { ErrorType::Known(err) => &err.message, ErrorType::Unknown(err) => &err.message, } }
pub fn from_dyn_error(err: &dyn std::error::Error) -> Self { Error { inner: ErrorType::Unknown(UnknownError { message: err.to_string(), backtrace: None, }), is_panic: false, } } pub fn new_in_panic_hook(panic_info: &std::panic::PanicInfo<'_>) -> Self { let message = panic_info .payload() .downcast_ref::<&str>() .map(|s| -> String { (*s).to_owned() }) .or_else(|| panic_info.payload().downcast_ref::<String>().map(|s| s.to_owned())) .unwrap_or_else(|| "<unknown panic>".to_owned()); let backtrace = Some(format!("{:?}", backtrace::Backtrace::new())); let location = panic_info .location() .map(|loc| format!("{}", loc)) .unwrap_or_else(|| "<unknown location>".to_owned()); Error { inner: ErrorType::Unknown(UnknownError { message: format!("[{}] {}", location, message), backtrace, }), is_panic: true, } } pub fn new_known(err: KnownError) -> Self { Error { inner: ErrorType::Known(err), is_panic: false, } } pub fn from_panic_payload(panic_payload: Box<dyn std::any::Any + Send + 'static>) -> Self { let message = Self::extract_panic_message(panic_payload).unwrap_or_else(|| "<unknown panic>".to_owned()); Error { inner: ErrorType::Unknown(UnknownError { message, backtrace: None, }), is_panic: true, } } pub fn extract_panic_message(panic_payload: Box<dyn std::any::Any + Send + 'static>) -> Option<String> { panic_payload .downcast_ref::<&str>() .map(|s| -> String { (*s).to_owned() }) .or_else(|| panic_payload.downcast_ref::<String>().map(|s| s.to_owned())) } pub fn unwrap_known(self) -> KnownError { match self.inner { ErrorType::Known(err) => err, err @ ErrorType::Unknown(_) => panic!("Expected known error, got {:?}", err), } } } pub fn new_backtrace() -> backtrace::Backtrace { backtrace::Backtrace::new() } impl From<UnknownError> for Error { fn from(unknown_error: UnknownError) -> Self { Error { inner: ErrorType::Unknown(unknown_error), is_panic: false, } } } impl From<KnownError> for Error { fn from(known_error: KnownError) -> Self { Error { is_panic: false, inner: ErrorType::Known(known_error), } } }
pub fn new_non_panic_with_current_backtrace(message: String) -> Self { Error { inner: ErrorType::Unknown(UnknownError { message, backtrace: Some(format!("{:?}", backtrace::Backtrace::new())), }), is_panic: false, } }
function_block-full_function
[]
Rust
vm/src/atomic_ref.rs
jazz-lang/JazzLight
a0df2f6c19efdc1b640d40d4f5680900bee59dea
#![allow(unsafe_code)] #![deny(missing_docs)] use std::cell::UnsafeCell; use std::cmp; use std::fmt; use std::fmt::Debug; use std::ops::{Deref, DerefMut}; use std::sync::atomic; use std::sync::atomic::AtomicU32; pub struct AtomicRefCell<T: ?Sized> { borrow: AtomicU32, value: UnsafeCell<T>, } impl<T> AtomicRefCell<T> { #[inline] pub fn new(value: T) -> AtomicRefCell<T> { AtomicRefCell { borrow: AtomicU32::new(0), value: UnsafeCell::new(value), } } #[inline] pub fn into_inner(self) -> T { debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0); self.value.into_inner() } } impl<T: ?Sized> AtomicRefCell<T> { #[inline] pub fn borrow(&self) -> AtomicRef<T> { AtomicRef { value: unsafe { &*self.value.get() }, borrow: AtomicBorrowRef::new(&self.borrow), } } #[inline] pub fn borrow_mut(&self) -> AtomicRefMut<T> { AtomicRefMut { value: unsafe { &mut *self.value.get() }, borrow: AtomicBorrowRefMut::new(&self.borrow), } } #[inline] pub fn as_ptr(&self) -> *mut T { self.value.get() } #[inline] pub fn get_mut(&mut self) -> &mut T { debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0); unsafe { &mut *self.value.get() } } } const HIGH_BIT: u32 = !(::std::u32::MAX >> 1); const MAX_FAILED_BORROWS: u32 = HIGH_BIT + (HIGH_BIT >> 1); struct AtomicBorrowRef<'b> { borrow: &'b AtomicU32, } impl<'b> AtomicBorrowRef<'b> { #[inline] fn new(borrow: &'b AtomicU32) -> Self { let new = borrow.fetch_add(1, atomic::Ordering::Acquire) + 1; if new & HIGH_BIT != 0 { Self::do_panic(borrow, new); } AtomicBorrowRef { borrow: borrow } } #[cold] #[inline(never)] fn do_panic(borrow: &'b AtomicU32, new: u32) { if new == HIGH_BIT { borrow.fetch_sub(1, atomic::Ordering::Release); panic!("too many immutable borrows"); } else if new >= MAX_FAILED_BORROWS { println!("Too many failed borrows"); ::std::process::exit(1); } else { panic!("already mutably borrowed"); } } } impl<'b> Drop for AtomicBorrowRef<'b> { #[inline] fn drop(&mut self) { let old = self.borrow.fetch_sub(1, atomic::Ordering::Release); debug_assert!(old & HIGH_BIT == 0); } } struct AtomicBorrowRefMut<'b> { borrow: &'b AtomicU32, } impl<'b> Drop for AtomicBorrowRefMut<'b> { #[inline] fn drop(&mut self) { self.borrow.store(0, atomic::Ordering::Release); } } impl<'b> AtomicBorrowRefMut<'b> { #[inline] fn new(borrow: &'b AtomicU32) -> AtomicBorrowRefMut<'b> { let old = match borrow.compare_exchange( 0, HIGH_BIT, atomic::Ordering::Acquire, atomic::Ordering::Relaxed, ) { Ok(x) => x, Err(x) => x, }; assert!( old == 0, "already {} borrowed", if old & HIGH_BIT == 0 { "immutably" } else { "mutably" } ); AtomicBorrowRefMut { borrow: borrow } } } unsafe impl<T: ?Sized + Send + Sync> Send for AtomicRefCell<T> {} unsafe impl<T: ?Sized + Send + Sync> Sync for AtomicRefCell<T> {} impl<T: Clone> Clone for AtomicRefCell<T> { #[inline] fn clone(&self) -> AtomicRefCell<T> { AtomicRefCell::new(self.borrow().clone()) } } impl<T: Default> Default for AtomicRefCell<T> { #[inline] fn default() -> AtomicRefCell<T> { AtomicRefCell::new(Default::default()) } } impl<T: ?Sized + PartialEq> PartialEq for AtomicRefCell<T> { #[inline] fn eq(&self, other: &AtomicRefCell<T>) -> bool { *self.borrow() == *other.borrow() } } impl<T: ?Sized + Eq> Eq for AtomicRefCell<T> {} impl<T: ?Sized + PartialOrd> PartialOrd for AtomicRefCell<T> { #[inline] fn partial_cmp(&self, other: &AtomicRefCell<T>) -> Option<cmp::Ordering> { self.borrow().partial_cmp(&*other.borrow()) } } impl<T: ?Sized + Ord> Ord for AtomicRefCell<T> { #[inline] fn cmp(&self, other: &AtomicRefCell<T>) -> cmp::Ordering { self.borrow().cmp(&*other.borrow()) } } impl<T> From<T> for AtomicRefCell<T> { fn from(t: T) -> AtomicRefCell<T> { AtomicRefCell::new(t) } } impl<'b> Clone for AtomicBorrowRef<'b> { #[inline] fn clone(&self) -> AtomicBorrowRef<'b> { AtomicBorrowRef::new(self.borrow) } } pub struct AtomicRef<'b, T: ?Sized + 'b> { value: &'b T, borrow: AtomicBorrowRef<'b>, } impl<'b, T: ?Sized> Deref for AtomicRef<'b, T> { type Target = T; #[inline] fn deref(&self) -> &T { self.value } } impl<'b, T: ?Sized> AtomicRef<'b, T> { #[inline] pub fn clone(orig: &AtomicRef<'b, T>) -> AtomicRef<'b, T> { AtomicRef { value: orig.value, borrow: orig.borrow.clone(), } } #[inline] pub fn map<U: ?Sized, F>(orig: AtomicRef<'b, T>, f: F) -> AtomicRef<'b, U> where F: FnOnce(&T) -> &U, { AtomicRef { value: f(orig.value), borrow: orig.borrow, } } } impl<'b, T: ?Sized> AtomicRefMut<'b, T> { #[inline] pub fn map<U: ?Sized, F>(orig: AtomicRefMut<'b, T>, f: F) -> AtomicRefMut<'b, U> where F: FnOnce(&mut T) -> &mut U, { AtomicRefMut { value: f(orig.value), borrow: orig.borrow, } } } pub struct AtomicRefMut<'b, T: ?Sized + 'b> { value: &'b mut T, borrow: AtomicBorrowRefMut<'b>, } impl<'b, T: ?Sized> Deref for AtomicRefMut<'b, T> { type Target = T; #[inline] fn deref(&self) -> &T { self.value } } impl<'b, T: ?Sized> DerefMut for AtomicRefMut<'b, T> { #[inline] fn deref_mut(&mut self) -> &mut T { self.value } } impl<'b, T: ?Sized + Debug + 'b> Debug for AtomicRef<'b, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.value.fmt(f) } } impl<'b, T: ?Sized + Debug + 'b> Debug for AtomicRefMut<'b, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.value.fmt(f) } } impl<T: ?Sized + Debug> Debug for AtomicRefCell<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "AtomicRefCell {{ ... }}") } }
#![allow(unsafe_code)] #![deny(missing_docs)] use std::cell::UnsafeCell; use std::cmp; use std::fmt; use std::fmt::Debug; use std::ops::{Deref, DerefMut}; use std::sync::atomic; use std::sync::atomic::AtomicU32; pub struct AtomicRefCell<T: ?Sized> { borrow: AtomicU32, value: UnsafeCell<T>, } impl<T> AtomicRefCell<T> { #[inline] pub fn new(value: T) -> AtomicRefCell<T> { AtomicRefCell { borrow: AtomicU32::new(0), value: UnsafeCell::new(value), } } #[inline] pub fn into_inner(self) -> T { debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0); self.value.into_inner() } } impl<T: ?Sized> AtomicRefCell<T> { #[inline] pub fn borrow(&self) -> AtomicRef<T> { AtomicRef { value: unsafe { &*self.value.get() }, borrow: AtomicBorrowRef::new(&self.borrow), } } #[inline]
#[inline] pub fn as_ptr(&self) -> *mut T { self.value.get() } #[inline] pub fn get_mut(&mut self) -> &mut T { debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0); unsafe { &mut *self.value.get() } } } const HIGH_BIT: u32 = !(::std::u32::MAX >> 1); const MAX_FAILED_BORROWS: u32 = HIGH_BIT + (HIGH_BIT >> 1); struct AtomicBorrowRef<'b> { borrow: &'b AtomicU32, } impl<'b> AtomicBorrowRef<'b> { #[inline] fn new(borrow: &'b AtomicU32) -> Self { let new = borrow.fetch_add(1, atomic::Ordering::Acquire) + 1; if new & HIGH_BIT != 0 { Self::do_panic(borrow, new); } AtomicBorrowRef { borrow: borrow } } #[cold] #[inline(never)] fn do_panic(borrow: &'b AtomicU32, new: u32) { if new == HIGH_BIT { borrow.fetch_sub(1, atomic::Ordering::Release); panic!("too many immutable borrows"); } else if new >= MAX_FAILED_BORROWS { println!("Too many failed borrows"); ::std::process::exit(1); } else { panic!("already mutably borrowed"); } } } impl<'b> Drop for AtomicBorrowRef<'b> { #[inline] fn drop(&mut self) { let old = self.borrow.fetch_sub(1, atomic::Ordering::Release); debug_assert!(old & HIGH_BIT == 0); } } struct AtomicBorrowRefMut<'b> { borrow: &'b AtomicU32, } impl<'b> Drop for AtomicBorrowRefMut<'b> { #[inline] fn drop(&mut self) { self.borrow.store(0, atomic::Ordering::Release); } } impl<'b> AtomicBorrowRefMut<'b> { #[inline] fn new(borrow: &'b AtomicU32) -> AtomicBorrowRefMut<'b> { let old = match borrow.compare_exchange( 0, HIGH_BIT, atomic::Ordering::Acquire, atomic::Ordering::Relaxed, ) { Ok(x) => x, Err(x) => x, }; assert!( old == 0, "already {} borrowed", if old & HIGH_BIT == 0 { "immutably" } else { "mutably" } ); AtomicBorrowRefMut { borrow: borrow } } } unsafe impl<T: ?Sized + Send + Sync> Send for AtomicRefCell<T> {} unsafe impl<T: ?Sized + Send + Sync> Sync for AtomicRefCell<T> {} impl<T: Clone> Clone for AtomicRefCell<T> { #[inline] fn clone(&self) -> AtomicRefCell<T> { AtomicRefCell::new(self.borrow().clone()) } } impl<T: Default> Default for AtomicRefCell<T> { #[inline] fn default() -> AtomicRefCell<T> { AtomicRefCell::new(Default::default()) } } impl<T: ?Sized + PartialEq> PartialEq for AtomicRefCell<T> { #[inline] fn eq(&self, other: &AtomicRefCell<T>) -> bool { *self.borrow() == *other.borrow() } } impl<T: ?Sized + Eq> Eq for AtomicRefCell<T> {} impl<T: ?Sized + PartialOrd> PartialOrd for AtomicRefCell<T> { #[inline] fn partial_cmp(&self, other: &AtomicRefCell<T>) -> Option<cmp::Ordering> { self.borrow().partial_cmp(&*other.borrow()) } } impl<T: ?Sized + Ord> Ord for AtomicRefCell<T> { #[inline] fn cmp(&self, other: &AtomicRefCell<T>) -> cmp::Ordering { self.borrow().cmp(&*other.borrow()) } } impl<T> From<T> for AtomicRefCell<T> { fn from(t: T) -> AtomicRefCell<T> { AtomicRefCell::new(t) } } impl<'b> Clone for AtomicBorrowRef<'b> { #[inline] fn clone(&self) -> AtomicBorrowRef<'b> { AtomicBorrowRef::new(self.borrow) } } pub struct AtomicRef<'b, T: ?Sized + 'b> { value: &'b T, borrow: AtomicBorrowRef<'b>, } impl<'b, T: ?Sized> Deref for AtomicRef<'b, T> { type Target = T; #[inline] fn deref(&self) -> &T { self.value } } impl<'b, T: ?Sized> AtomicRef<'b, T> { #[inline] pub fn clone(orig: &AtomicRef<'b, T>) -> AtomicRef<'b, T> { AtomicRef { value: orig.value, borrow: orig.borrow.clone(), } } #[inline] pub fn map<U: ?Sized, F>(orig: AtomicRef<'b, T>, f: F) -> AtomicRef<'b, U> where F: FnOnce(&T) -> &U, { AtomicRef { value: f(orig.value), borrow: orig.borrow, } } } impl<'b, T: ?Sized> AtomicRefMut<'b, T> { #[inline] pub fn map<U: ?Sized, F>(orig: AtomicRefMut<'b, T>, f: F) -> AtomicRefMut<'b, U> where F: FnOnce(&mut T) -> &mut U, { AtomicRefMut { value: f(orig.value), borrow: orig.borrow, } } } pub struct AtomicRefMut<'b, T: ?Sized + 'b> { value: &'b mut T, borrow: AtomicBorrowRefMut<'b>, } impl<'b, T: ?Sized> Deref for AtomicRefMut<'b, T> { type Target = T; #[inline] fn deref(&self) -> &T { self.value } } impl<'b, T: ?Sized> DerefMut for AtomicRefMut<'b, T> { #[inline] fn deref_mut(&mut self) -> &mut T { self.value } } impl<'b, T: ?Sized + Debug + 'b> Debug for AtomicRef<'b, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.value.fmt(f) } } impl<'b, T: ?Sized + Debug + 'b> Debug for AtomicRefMut<'b, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.value.fmt(f) } } impl<T: ?Sized + Debug> Debug for AtomicRefCell<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "AtomicRefCell {{ ... }}") } }
pub fn borrow_mut(&self) -> AtomicRefMut<T> { AtomicRefMut { value: unsafe { &mut *self.value.get() }, borrow: AtomicBorrowRefMut::new(&self.borrow), } }
function_block-full_function
[ { "content": "pub fn new_native_fn(x: fn(&[Value]) -> Result<Value, Value>, argc: i32) -> Value {\n\n Value::Function(Ref(Function {\n\n native: true,\n\n address: x as usize,\n\n env: Value::Null,\n\n module: None,\n\n argc,\n\n }))\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 0, "score": 123499.5340342728 }, { "content": "pub fn builtin_acopy(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::Array(array) => Ok(Value::Array(Ref(array\n\n .borrow()\n\n .iter()\n\n .map(|x| x.clone())\n\n .collect::<Vec<_>>()))),\n\n _ => return Err(Value::String(Ref(\"acopy: Array expected\".to_owned()))),\n\n }\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 1, "score": 113293.92638164115 }, { "content": "pub fn builtin_apop(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::Array(array) => return Ok(array.borrow_mut().pop().unwrap_or(Value::Null)),\n\n _ => return Err(Value::String(Ref(\"Array expected\".to_owned()))),\n\n }\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 2, "score": 113293.92638164115 }, { "content": "pub fn builtin_scopy(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::String(s) => Ok(Value::String(Ref(s.borrow().to_owned()))),\n\n _ => return Err(Value::String(Ref(\"scopy: String expected\".to_owned()))),\n\n }\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 3, "score": 113293.92638164115 }, { "content": "pub fn builtin_array(args: &[Value]) -> Result<Value, Value> {\n\n Ok(Value::Array(Ref(args.to_vec())))\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 4, "score": 113293.92638164115 }, { "content": "pub fn builtin_sfind(args: &[Value]) -> Result<Value, Value> {\n\n let pat = format!(\"{}\", args[1]);\n\n match &args[0] {\n\n Value::String(s) => match s.borrow().find(&pat) {\n\n Some(result) => return Ok(Value::Int(result as _)),\n\n None => return Ok(Value::Null),\n\n },\n\n _ => return Err(Value::String(Ref(\"sfind: String expected\".to_owned()))),\n\n }\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 5, "score": 113293.92638164115 }, { "content": "pub fn builtin_typeof(args: &[Value]) -> Result<Value, Value> {\n\n let tag = args[0].tag();\n\n Ok(Value::String(Ref(match tag {\n\n ValTag::Array => \"array\",\n\n ValTag::Null => \"null\",\n\n ValTag::Float => \"float\",\n\n ValTag::Int => \"int\",\n\n ValTag::Str => \"string\",\n\n ValTag::Bool => \"bool\",\n\n ValTag::Object => \"object\",\n\n ValTag::Char => \"char\",\n\n ValTag::Func => \"function\",\n\n ValTag::User(x) => x,\n\n }\n\n .to_owned())))\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 6, "score": 113293.92638164115 }, { "content": "pub fn builtin_nargs(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::Function(fun) => Ok(Value::Int(fun.borrow().argc as _)),\n\n _ => Ok(Value::Null),\n\n }\n\n}\n", "file_path": "vm/src/builtins.rs", "rank": 7, "score": 113293.92638164115 }, { "content": "pub fn builtin_print(args: &[Value]) -> Result<Value, Value> {\n\n for val in args.iter() {\n\n print!(\"{}\", val);\n\n }\n\n Ok(Value::Null)\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 8, "score": 113293.92638164115 }, { "content": "pub fn builtin_sget(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::String(s) => Ok(s\n\n .borrow()\n\n .chars()\n\n .nth(args[1].to_int().unwrap() as usize)\n\n .map(|x| Value::String(Ref(x.to_string())))\n\n .unwrap_or(Value::Null)),\n\n _ => return Err(Value::String(Ref(\"sget: String expected\".to_owned()))),\n\n }\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 9, "score": 113293.92638164115 }, { "content": "pub fn builtin_schars(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::String(s) => Ok(Value::Array(Ref(s\n\n .borrow()\n\n .chars()\n\n .map(|x| Value::Char(x))\n\n .collect()))),\n\n _ => return Err(Value::String(Ref(\"schars: String expected\".to_owned()))),\n\n }\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 10, "score": 113293.92638164115 }, { "content": "pub fn builtin_asize(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::Array(array) => return Ok(Value::Int(array.borrow().len() as _)),\n\n _ => return Err(Value::String(Ref(\"Array expected\".to_owned()))),\n\n }\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 11, "score": 113293.92638164115 }, { "content": "pub fn builtin_string(args: &[Value]) -> Result<Value, Value> {\n\n let value = args[0].to_string();\n\n return Ok(Value::String(Ref(value)));\n\n}\n", "file_path": "vm/src/builtins.rs", "rank": 12, "score": 113293.92638164115 }, { "content": "pub fn builtin_load(args: &[Value]) -> Result<Value, Value> {\n\n let path = args[0].to_string();\n\n\n\n let libs_path: Option<&'static str> = option_env!(\"JAZZLIGHT_PATH\");\n\n let path = match libs_path {\n\n Some(lpath) if std::path::Path::new(&format!(\"{}/{}\", lpath, path)).exists() => {\n\n format!(\"{}/{}\", lpath, path)\n\n }\n\n Some(lpath) if std::path::Path::new(&format!(\"{}/{}.j\", lpath, path)).exists() => {\n\n format!(\"{}/{}.j\", lpath, path)\n\n }\n\n Some(_) => path,\n\n None => path,\n\n };\n\n let path = if std::path::Path::new(&format!(\"{}.j\", path)).exists() {\n\n format!(\"{}.j\", path)\n\n } else {\n\n path\n\n };\n\n let contents = std::fs::read(&path);\n", "file_path": "vm/src/builtins.rs", "rank": 13, "score": 113293.92638164115 }, { "content": "pub fn builtin_apush(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::Array(array) => array.borrow_mut().push(args[1].clone()),\n\n _ => return Err(Value::String(Ref(\"Array expected\".to_owned()))),\n\n }\n\n Ok(Value::Null)\n\n}\n", "file_path": "vm/src/builtins.rs", "rank": 14, "score": 113293.92638164115 }, { "content": "pub fn builtin_apply(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::Function(_) => {\n\n let array = match &args[2] {\n\n Value::Array(array) => array.borrow(),\n\n _ => {\n\n return Err(Value::String(Ref(\n\n \"apply: Array of arguments expected\".to_owned()\n\n )))\n\n }\n\n };\n\n return val_callex(args[0].clone(), args[1].clone(), &*array);\n\n }\n\n _ => Err(Value::String(Ref(\"apply: Function expected\".to_owned()))),\n\n }\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 15, "score": 113293.92638164115 }, { "content": "pub fn builtin_amake(args: &[Value]) -> Result<Value, Value> {\n\n let array = vec![Value::Null; args[0].to_int().unwrap_or(0) as usize];\n\n Ok(Value::Array(Ref(array)))\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 16, "score": 113293.92638164115 }, { "content": "pub fn builtin_instanceof(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::Object(obj) => match &args[1] {\n\n Value::Object(obj2) => match &obj.borrow().prototype {\n\n Some(proto) => return Ok(Value::Bool(Rc::ptr_eq(proto, obj2))),\n\n None => return Ok(Value::Bool(Rc::ptr_eq(obj, obj2))),\n\n },\n\n _ => return Ok(Value::Bool(false)),\n\n },\n\n _ => return Ok(Value::Bool(false)),\n\n }\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 17, "score": 113293.92638164115 }, { "content": "pub fn file_bytes(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::User(file) => {\n\n if let Some(handle) = file.borrow_mut().downcast_mut::<FileHandle>() {\n\n let file: &mut File = &mut handle.0;\n\n let mut buf = vec![];\n\n match file.read_to_end(&mut buf) {\n\n Ok(_) => {\n\n return Ok(Value::Array(Ref(buf\n\n .iter()\n\n .map(|x| Value::Int(*x as _))\n\n .collect())))\n\n }\n\n Err(e) => return Err(Value::String(Ref(e.to_string()))),\n\n }\n\n } else {\n\n return Err(Value::String(Ref(\"file_flush: File expected\".to_string())));\n\n }\n\n }\n\n _ => return Err(Value::String(Ref(\"file_flush: File expected\".to_string()))),\n\n }\n\n}\n\n\n", "file_path": "vm/src/builtins/io.rs", "rank": 18, "score": 110957.47045643907 }, { "content": "pub fn file_contents(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::User(file) => {\n\n if let Some(file) = file.borrow_mut().downcast_mut::<FileHandle>() {\n\n let file: &mut File = &mut file.0;\n\n let mut buf = String::new();\n\n match file.read_to_string(&mut buf) {\n\n Ok(_) => (),\n\n Err(e) => return Err(Value::String(Ref(e.to_string()))),\n\n }\n\n return Ok(Value::String(Ref(buf)));\n\n } else {\n\n return Err(Value::String(Ref(\n\n \"file_contents: File expected\".to_string()\n\n )));\n\n }\n\n }\n\n _ => {\n\n return Err(Value::String(\n\n Ref(\"file_contents: File expected\".to_owned()),\n\n ))\n\n }\n\n }\n\n}\n\n\n", "file_path": "vm/src/builtins/io.rs", "rank": 19, "score": 110957.47045643907 }, { "content": "pub fn file_flush(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::User(file) => {\n\n if let Some(handle) = file.borrow_mut().downcast_mut::<FileHandle>() {\n\n let file: &mut File = &mut handle.0;\n\n match file.flush() {\n\n Ok(_) => return Ok(Value::Null),\n\n Err(e) => return Err(Value::String(Ref(e.to_string()))),\n\n }\n\n } else {\n\n return Err(Value::String(Ref(\"file_flush: File expected\".to_string())));\n\n }\n\n }\n\n _ => return Err(Value::String(Ref(\"file_flush: File expected\".to_string()))),\n\n }\n\n}\n\n\n", "file_path": "vm/src/builtins/io.rs", "rank": 20, "score": 110957.47045643907 }, { "content": "pub fn file_open(args: &[Value]) -> Result<Value, Value> {\n\n let s = args[0].to_string();\n\n\n\n let file = std::fs::OpenOptions::new().write(true).read(true).open(&s);\n\n match file {\n\n Ok(file) => return Ok(Value::User(Ref(FileHandle(file)))),\n\n Err(e) => return Err(Value::String(Ref(e.to_string()))),\n\n }\n\n}\n\n\n", "file_path": "vm/src/builtins/io.rs", "rank": 21, "score": 110957.47045643907 }, { "content": "pub fn builtin_str_from_chars(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::Array(array) => {\n\n let mut chars = vec![];\n\n\n\n for ch in array.borrow().iter() {\n\n match ch {\n\n Value::Char(x) => chars.push(*x),\n\n _ => return Ok(Value::Null),\n\n }\n\n }\n\n use std::iter::FromIterator;\n\n let s = String::from_iter(chars.iter());\n\n return Ok(Value::String(Ref(s)));\n\n }\n\n Value::String(_) => return Ok(builtin_scopy(&[args[0].clone()])?),\n\n _ => return Ok(Value::Null),\n\n }\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 22, "score": 110957.47045643907 }, { "content": "pub fn file_write(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::User(file) => {\n\n if let Some(handle) = file.borrow_mut().downcast_mut::<FileHandle>() {\n\n let file: &mut File = &mut handle.0;\n\n let bytes: Vec<u8> = match &args[1] {\n\n Value::Int(x) => x.to_le_bytes().iter().map(|x| *x).collect::<Vec<_>>(),\n\n Value::Array(array) => {\n\n let mut bytes = vec![];\n\n for x in array.borrow().iter() {\n\n match x {\n\n Value::Int(x) => bytes.push(*x as u8),\n\n Value::Char(x) => bytes.extend((*x as u32).to_le_bytes().iter()),\n\n _ => {\n\n return Err(Value::String(Ref(\n\n \"Unexpected value to write\".to_owned()\n\n )))\n\n }\n\n }\n\n }\n", "file_path": "vm/src/builtins/io.rs", "rank": 23, "score": 110957.47045643907 }, { "content": "pub fn builtin_load_function(args: &[Value]) -> Result<Value, Value> {\n\n use libloading::{Library, Symbol};\n\n let lib = format!(\"{}\", args[0]);\n\n let name = format!(\"{}\", args[1]);\n\n\n\n let lib = Library::new(&lib);\n\n match lib {\n\n Ok(lib) => {\n\n let lib: Library = lib;\n\n unsafe {\n\n let entry_point: Result<Symbol<fn()>, _> =\n\n lib.get(format!(\"__jazzlight_entry_point\\0\").as_bytes());\n\n match entry_point {\n\n Ok(sym) => {\n\n sym();\n\n }\n\n Err(e) => {\n\n return Err(Value::String(Ref(format!(\n\n \"Failed to get entry point: {}\",\n\n e\n", "file_path": "vm/src/builtins.rs", "rank": 24, "score": 110957.47045643907 }, { "content": "pub fn file_write_string(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::User(file) => {\n\n if let Some(handle) = file.borrow_mut().downcast_mut::<FileHandle>() {\n\n let file: &mut File = &mut handle.0;\n\n let s = args[1].to_string();\n\n match file.write(s.as_bytes()) {\n\n Ok(count) => return Ok(Value::Int(count as _)),\n\n Err(e) => return Err(Value::String(Ref(e.to_string()))),\n\n }\n\n } else {\n\n return Err(Value::String(Ref(\"file_flush: File expected\".to_string())));\n\n }\n\n }\n\n _ => return Err(Value::String(Ref(\"file_flush: File expected\".to_string()))),\n\n }\n\n}\n\n\n", "file_path": "vm/src/builtins/io.rs", "rank": 25, "score": 108758.49877327969 }, { "content": "pub fn file_write_byte(args: &[Value]) -> Result<Value, Value> {\n\n match &args[0] {\n\n Value::User(file) => {\n\n if let Some(handle) = file.borrow_mut().downcast_mut::<FileHandle>() {\n\n let file: &mut File = &mut handle.0;\n\n match &args[1] {\n\n Value::Int(byte) => match file.write(&[*byte as u8]) {\n\n Ok(_) => return Ok(Value::Null),\n\n Err(e) => return Err(Value::String(Ref(e.to_string()))),\n\n },\n\n _ => {\n\n return Err(Value::String(Ref(\n\n \"file_write_byte: Int expected\".to_string()\n\n )))\n\n }\n\n }\n\n } else {\n\n return Err(Value::String(Ref(\n\n \"file_write_byte: File expected\".to_string()\n\n )));\n", "file_path": "vm/src/builtins/io.rs", "rank": 26, "score": 108758.49877327969 }, { "content": "pub fn val_callex(f: Value, this: Value, args: &[Value]) -> Result<Value, Value> {\n\n let mut vm = get_vm!();\n\n match f {\n\n Value::Function(f) => {\n\n let function = f.borrow();\n\n if function.native {\n\n let fun: fn(&[Value]) -> Result<Value, Value> =\n\n unsafe { std::mem::transmute(function.address) };\n\n let mut new_args = vec![this];\n\n for i in args.iter() {\n\n new_args.push(i.clone());\n\n }\n\n\n\n return fun(&new_args);\n\n } else {\n\n vm.save_state_exit();\n\n let env = vm.env.clone();\n\n let locals = vm.locals.clone();\n\n let pc = vm.pc.clone();\n\n let this_ = vm.this.clone();\n", "file_path": "vm/src/interp.rs", "rank": 27, "score": 108620.55705015153 }, { "content": "pub fn builtins_init() -> HashMap<String, Value> {\n\n let mut map = HashMap::new();\n\n\n\n map.insert(\"print\".to_owned(), new_native_fn(builtin_print, -1));\n\n map.insert(\"array\".to_owned(), new_native_fn(builtin_array, -1));\n\n map.insert(\"amake\".to_owned(), new_native_fn(builtin_amake, 1));\n\n map.insert(\"asize\".to_owned(), new_native_fn(builtin_asize, 1));\n\n map.insert(\"apush\".to_owned(), new_native_fn(builtin_apush, 2));\n\n map.insert(\"apop\".to_owned(), new_native_fn(builtin_apop, 0));\n\n map.insert(\"acopy\".to_owned(), new_native_fn(builtin_acopy, 1));\n\n map.insert(\"nargs\".to_owned(), new_native_fn(builtin_nargs, 1));\n\n map.insert(\"typeof\".to_owned(), new_native_fn(builtin_typeof, 1));\n\n map.insert(\"string\".to_owned(), new_native_fn(builtin_string, 1));\n\n map.insert(\"load\".to_owned(), new_native_fn(builtin_load, 1));\n\n map.insert(\n\n \"load_native\".to_owned(),\n\n new_native_fn(builtin_load_function, 2),\n\n );\n\n\n\n map.insert(\"scopy\".to_owned(), new_native_fn(builtin_scopy, 1));\n", "file_path": "vm/src/builtins.rs", "rank": 28, "score": 105319.77019454187 }, { "content": "#[allow(non_snake_case)]\n\npub fn P<T>(value: T) -> Arc<T> {\n\n Arc::new(value)\n\n}\n", "file_path": "src/lib.rs", "rank": 29, "score": 103714.60352399279 }, { "content": "pub fn get_builtin(field: &str) -> Option<Value> {\n\n BUILTINS.with(|builtins| builtins.get(field).cloned())\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 30, "score": 102984.32094581776 }, { "content": "pub fn gc_collect() {\n\n COLLECTOR.with(|gc: &RefCell<Gc>| {\n\n gc.borrow_mut().force_full_collect();\n\n })\n\n}\n\n\n\nimpl<T: Trace> Trace for RefCell<T> {\n\n fn trace(&self, t: &mut Tracer) {\n\n self.borrow().trace(t);\n\n }\n\n}\n", "file_path": "vm/src/gc.rs", "rank": 31, "score": 99797.42210186287 }, { "content": "pub fn file_builtins(map: &mut std::collections::HashMap<String, Value>) {\n\n map.insert(\"file_open\".to_owned(), new_native_fn(file_open, 1));\n\n map.insert(\"file_contents\".to_owned(), new_native_fn(file_contents, 1));\n\n map.insert(\"file_flush\".to_owned(), new_native_fn(file_flush, 0));\n\n map.insert(\n\n \"file_write_string\".to_owned(),\n\n new_native_fn(file_write_string, 2),\n\n );\n\n map.insert(\"file_write\".to_owned(), new_native_fn(file_write, 2));\n\n map.insert(\n\n \"file_write_byte\".to_owned(),\n\n new_native_fn(file_write_byte, 2),\n\n );\n\n map.insert(\"file_bytes\".to_owned(), new_native_fn(file_bytes, 1));\n\n}\n", "file_path": "vm/src/builtins/io.rs", "rank": 32, "score": 86321.14004280957 }, { "content": "pub fn get_field(h: u64) -> Option<String> {\n\n FIELDS.read().get(&h).cloned()\n\n}\n", "file_path": "vm/src/lib.rs", "rank": 33, "score": 81371.36263999899 }, { "content": "pub fn compile(ast: Vec<P<Expr>>) -> Context {\n\n let mut ctx = Context::new();\n\n let ast = P(Expr {\n\n pos: Position::new(\n\n ast.get(0)\n\n .map(|x| x.pos.file.clone())\n\n .unwrap_or(Arc::from(\"<>\".to_owned())),\n\n 0,\n\n 0,\n\n ),\n\n decl: ExprDecl::Block(ast.clone()),\n\n });\n\n\n\n ctx.ret_lbl = ctx.new_empty_label();\n\n ctx.compile(&ast, false);\n\n let ret_lbl = ctx.ret_lbl.clone();\n\n ctx.label_here(&ret_lbl);\n\n ctx.write(Op::Ret);\n\n\n\n if ctx.g.borrow().functions.len() != 0 || ctx.g.borrow().objects.len() != 0 {\n", "file_path": "src/codegen.rs", "rank": 35, "score": 79327.8445473654 }, { "content": "pub fn make_str(s: String, pos: Position) -> Expr {\n\n Expr {\n\n pos: pos,\n\n decl: ExprDecl::Const(Constant::Str(s)),\n\n }\n\n}\n", "file_path": "src/ast.rs", "rank": 36, "score": 79327.8445473654 }, { "content": "pub fn make_ident(i: String, pos: Position) -> Expr {\n\n Expr {\n\n pos: pos,\n\n decl: ExprDecl::Const(Constant::Ident(i)),\n\n }\n\n}\n", "file_path": "src/ast.rs", "rank": 37, "score": 79327.8445473654 }, { "content": "#[allow(non_snake_case)]\n\npub fn Ref<T>(x: T) -> Ref<T> {\n\n Rc::new(RefCell::new(x))\n\n}\n\n\n\nuse std::collections::HashMap;\n\nuse value::Value;\n\n\n\npub struct Module {\n\n pub exports: Value,\n\n pub code: Vec<opcode::Op>,\n\n pub globals: Vec<Value>,\n\n pub trace_info: HashMap<u32, (usize, String)>,\n\n}\n\n\n\n/*\n\nimpl Trace for Module {\n\n fn trace(&self) {\n\n self.exports.trace();\n\n self.globals.trace();\n\n }\n\n}*/\n\n\n\nuse parking_lot::RwLock;\n\nlazy_static::lazy_static! {\n\n pub static ref FIELDS: RwLock<HashMap<u64,String>> = RwLock::new(HashMap::new());\n\n}\n\n\n", "file_path": "vm/src/lib.rs", "rank": 38, "score": 79327.8445473654 }, { "content": "pub fn make_int(i: i64, pos: Position) -> Expr {\n\n Expr {\n\n pos: pos,\n\n decl: ExprDecl::Const(Constant::Int(i)),\n\n }\n\n}\n", "file_path": "src/ast.rs", "rank": 39, "score": 79327.8445473654 }, { "content": "pub fn make_builtin(b: String, pos: Position) -> Expr {\n\n Expr {\n\n pos: pos,\n\n decl: ExprDecl::Const(Constant::Builtin(b)),\n\n }\n\n}\n", "file_path": "src/ast.rs", "rank": 40, "score": 79327.8445473654 }, { "content": "/// Construct new VM Module from compilation context.\n\npub fn module_from_context(ctx: &mut Context) -> Ref<Module> {\n\n let m = Ref(Module {\n\n exports: Value::Object(Ref(Object {\n\n prototype: None,\n\n table: Default::default(),\n\n })),\n\n code: vec![],\n\n\n\n globals: vec![Value::Null; ctx.g.borrow().table.len()],\n\n trace_info: Default::default(),\n\n });\n\n\n\n for (i, g) in ctx.g.borrow().table.iter().enumerate() {\n\n match g {\n\n Global::Func(off, nargs) => {\n\n let func = Ref(Function {\n\n native: false,\n\n address: *off as _,\n\n argc: *nargs,\n\n env: Value::Array(Ref(vec![])),\n", "file_path": "src/codegen.rs", "rank": 42, "score": 77479.88992273452 }, { "content": "struct GcData<T: Trace + ?Sized> {\n\n metadata: Metadata,\n\n object: T,\n\n}\n\n\n\nimpl Tracer {\n\n /// Enqueue the object behind `handle` for marking and tracing.\n\n pub fn trace_handle(&mut self, handle: Handle<dyn Trace>) {\n\n let traced = handle.with(|gc| gc.traced() == self.traced);\n\n\n\n if !traced {\n\n self.worklist.push(handle.clone());\n\n }\n\n }\n\n\n\n /// Starting with the root set in `self.worklist`, marks all transitively\n\n /// reachable objects by setting their `traced` metadata field to\n\n /// `self.traced`.\n\n fn mark_all(&mut self) {\n\n let mut worklist = mem::replace(&mut self.worklist, Vec::new());\n", "file_path": "vm/src/gc.rs", "rank": 43, "score": 74041.94777699119 }, { "content": "pub fn gc_alloc<X: Trace + 'static>(x: X) -> Rooted<X> {\n\n COLLECTOR.with(|gc: &RefCell<Gc>| gc.borrow_mut().allocate(x))\n\n}\n\n\n", "file_path": "vm/src/gc.rs", "rank": 44, "score": 70769.35708285349 }, { "content": "pub fn make_call(v: P<Expr>, args: Vec<P<Expr>>, pos: Position) -> Expr {\n\n Expr {\n\n pos: pos,\n\n decl: ExprDecl::Call(v, args),\n\n }\n\n}\n", "file_path": "src/ast.rs", "rank": 45, "score": 64007.95753656089 }, { "content": "pub fn make_bin(op: String, e1: P<Expr>, e2: P<Expr>, pos: Position) -> Expr {\n\n Expr {\n\n pos: pos,\n\n decl: ExprDecl::Binop(op, e1, e2),\n\n }\n\n}\n\n\n\nimpl Expr {\n\n pub fn iter(&self, mut f: impl FnMut(&P<Expr>)) {\n\n match &self.decl {\n\n ExprDecl::Block(el) => {\n\n for e in el.iter() {\n\n f(e);\n\n }\n\n }\n\n ExprDecl::Paren(e) => f(e),\n\n ExprDecl::Field(e, _) => f(e),\n\n ExprDecl::Call(e, el) => {\n\n f(e);\n\n for x in el.iter() {\n", "file_path": "src/ast.rs", "rank": 46, "score": 60432.25857765287 }, { "content": "pub trait UserKind: mopa::Any + fmt::Debug + fmt::Display {\n\n fn get_kind(&self) -> &'static str;\n\n}\n\n/*\n\nuse crate::gc::Trace;\n\n\n\nimpl Trace for Function {\n\n fn trace(&self) {\n\n match &self.module {\n\n Some(m) => m.trace(),\n\n _ => (),\n\n }\n\n self.env.trace();\n\n }\n\n}\n\n\n\nimpl Trace for Value {\n\n fn trace(&self) {\n\n match self {\n\n Value::String(s) => s.trace(),\n", "file_path": "vm/src/value.rs", "rank": 47, "score": 59996.238913711655 }, { "content": "/// GC metadata maintained for every object on the heap.\n\nstruct Metadata {\n\n /// The \"color\" bit, indicating whether we've already traced this object\n\n /// during this collection, used to prevent unnecessary work.\n\n traced: Cell<bool>,\n\n}\n", "file_path": "vm/src/gc.rs", "rank": 48, "score": 59606.69908272594 }, { "content": "fn main() {\n\n let ops = Options::from_args();\n\n let string = ops.file.unwrap().to_str().unwrap().to_owned();\n\n let r = match Reader::from_file(&string) {\n\n Ok(r) => r,\n\n Err(e) => {\n\n eprintln!(\"Failed to open file '{}': {}\", string, e);\n\n std::process::exit(1);\n\n }\n\n };\n\n let mut ast = vec![];\n\n let mut parser = Parser::new(r, &mut ast);\n\n match parser.parse() {\n\n Ok(_) => (),\n\n Err(e) => {\n\n eprintln!(\"{}\", e);\n\n std::process::exit(1);\n\n }\n\n }\n\n let mut ctx = compile(ast);\n", "file_path": "src/main.rs", "rank": 49, "score": 55732.307993755734 }, { "content": "fn main() {\n\n let file = std::env::args().nth(1);\n\n if file.is_none() {\n\n eprintln!(\"Please select JazzLight bytecode file\");\n\n std::process::exit(1);\n\n }\n\n let file = file.unwrap();\n\n\n\n let contents = std::fs::read(&file);\n\n match contents {\n\n Ok(contents) => {\n\n let mut reader = BytecodeReader {\n\n bytes: Cursor::new(&contents),\n\n };\n\n let m = reader.read_module();\n\n let vm = get_vm!();\n\n vm.save_state_exit();\n\n match vm.interp(m) {\n\n Value::Int(x) => std::process::exit(x as _),\n\n _ => (),\n\n }\n\n }\n\n Err(e) => {\n\n eprintln!(\"{}\", e);\n\n std::process::exit(1);\n\n }\n\n }\n\n}\n", "file_path": "vm/src/main.rs", "rank": 50, "score": 54169.79191740771 }, { "content": "pub trait Trace {\n\n /// Trace all contained `Handle`s to other GC objects by calling\n\n /// `tracer.trace_handle`.\n\n fn trace(&self, _: &mut Tracer) {}\n\n}\n\n\n\npub struct Tracer {\n\n traced: bool,\n\n worklist: Vec<Handle<dyn Trace + 'static>>,\n\n}\n\n\n\nuse std::marker::Unsize;\n\nuse std::ops::CoerceUnsized;\n\npub struct Handle<T: Trace + ?Sized> {\n\n inner: Weak<GcData<T>>,\n\n}\n\n\n\nimpl<T: Trace + ?Sized + Unsize<U> + CoerceUnsized<U>, U: Trace + ?Sized> CoerceUnsized<GcData<U>>\n\n for GcData<T>\n\n{\n", "file_path": "vm/src/gc.rs", "rank": 51, "score": 51808.28645551397 }, { "content": "fn is_operator(ch: Option<char>) -> bool {\n\n ch.map(|ch| \"^+-*/%&|,=!~;:.()[]{}<>\".contains(ch))\n\n .unwrap_or(false)\n\n}\n\n\n", "file_path": "src/lexer.rs", "rank": 52, "score": 43442.51633910869 }, { "content": "fn is_digit(ch: Option<char>) -> bool {\n\n ch.map(|ch| ch.is_digit(10)).unwrap_or(false)\n\n}\n\n\n", "file_path": "src/lexer.rs", "rank": 53, "score": 43442.51633910869 }, { "content": "fn is_quote(ch: Option<char>) -> bool {\n\n ch == Some('\\\"')\n\n}\n\n\n", "file_path": "src/lexer.rs", "rank": 54, "score": 43442.51633910869 }, { "content": "fn is_identifier(ch: Option<char>) -> bool {\n\n is_identifier_start(ch) || is_digit(ch)\n\n}\n", "file_path": "src/lexer.rs", "rank": 55, "score": 43442.51633910869 }, { "content": "fn is_whitespace(ch: Option<char>) -> bool {\n\n ch.map(|ch| ch.is_whitespace()).unwrap_or(false)\n\n}\n\n\n", "file_path": "src/lexer.rs", "rank": 56, "score": 43442.51633910869 }, { "content": "fn is_newline(ch: Option<char>) -> bool {\n\n ch == Some('\\n')\n\n}\n\n\n", "file_path": "src/lexer.rs", "rank": 57, "score": 43442.51633910869 }, { "content": "fn is_identifier_start(ch: Option<char>) -> bool {\n\n match ch {\n\n Some(ch) => (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_',\n\n _ => false,\n\n }\n\n}\n\n\n", "file_path": "src/lexer.rs", "rank": 58, "score": 42360.55864047982 }, { "content": "fn is_char_quote(ch: Option<char>) -> bool {\n\n ch == Some('\\'')\n\n}\n\n\n", "file_path": "src/lexer.rs", "rank": 59, "score": 42360.55864047982 }, { "content": "fn common_init(name: String, src: String) -> Reader {\n\n let mut reader = Reader {\n\n filename: crate::P(name),\n\n src: src,\n\n pos: 0,\n\n next_pos: 0,\n\n\n\n cur: Some('\\n'),\n\n line: 0,\n\n col: 0,\n\n tabwidth: 4,\n\n };\n\n\n\n reader.advance();\n\n\n\n reader\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "src/reader.rs", "rank": 60, "score": 40223.48319680928 }, { "content": "fn is_digit_or_underscore(ch: Option<char>, base: IntBase) -> bool {\n\n ch.map(|ch| ch.is_digit(base.num()) || ch == '_')\n\n .unwrap_or(false)\n\n}\n\n\n", "file_path": "src/lexer.rs", "rank": 61, "score": 37451.11399746978 }, { "content": "}\n\n\n\nimpl Eq for Value {}\n\n\n\npub struct Object {\n\n pub prototype: Option<Ref<Object>>,\n\n pub table: LinkedHashMap<Value, Value>,\n\n}\n\n\n\nimpl Object {\n\n pub fn get(&self, value: Value) -> Option<Value> {\n\n match self.table.get(&value) {\n\n Some(value) => Some(value.clone()),\n\n None => match &self.prototype {\n\n Some(proto) => proto.borrow().get(value),\n\n None => None,\n\n },\n\n }\n\n }\n\n\n", "file_path": "vm/src/value.rs", "rank": 62, "score": 31963.05577804195 }, { "content": " array.borrow().hash(state);\n\n }\n\n Value::Object(object) => {\n\n 5.hash(state);\n\n object.borrow().hash(state);\n\n }\n\n Value::Bool(x) => {\n\n 6.hash(state);\n\n x.hash(state);\n\n }\n\n Value::Char(x) => {\n\n 7.hash(state);\n\n x.hash(state);\n\n }\n\n _ => (),\n\n }\n\n }\n\n}\n\n\n\nuse std::fmt;\n", "file_path": "vm/src/value.rs", "rank": 63, "score": 31962.63756449304 }, { "content": " pub fn set(&mut self, key: Value, value: Value) {\n\n self.table.insert(key, value);\n\n }\n\n}\n\n\n\nimpl Hash for Object {\n\n fn hash<H: Hasher>(&self, state: &mut H) {\n\n for (key, val) in self.table.iter() {\n\n key.hash(state);\n\n val.hash(state);\n\n }\n\n self.table.len().hash(state);\n\n match &self.prototype {\n\n Some(value) => value.borrow().hash(state),\n\n _ => (),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct Function {\n\n pub native: bool,\n\n pub address: usize,\n\n pub env: Value,\n\n pub module: Option<Ref<Module>>,\n\n pub argc: i32,\n\n}\n\n\n", "file_path": "vm/src/value.rs", "rank": 64, "score": 31962.46570005595 }, { "content": "use crate::*;\n\nuse hashlink::LinkedHashMap;\n\nuse std::hash::{Hash, Hasher};\n\n\n\n#[derive(Clone)]\n\npub enum Value {\n\n Null,\n\n Bool(bool),\n\n Int(i64),\n\n Float(f64),\n\n String(Ref<String>),\n\n Array(Ref<Vec<Value>>),\n\n Object(Ref<Object>),\n\n Function(Ref<Function>),\n\n Char(char),\n\n User(Ref<dyn UserKind>),\n\n}\n\n\n\n#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]\n\npub enum ValTag {\n", "file_path": "vm/src/value.rs", "rank": 65, "score": 31961.363668120543 }, { "content": " _ => false,\n\n },\n\n Value::Float(x) => match other {\n\n Value::Int(y) => *x == *y as f64,\n\n Value::Float(y) => x == y,\n\n _ => false,\n\n },\n\n Value::Char(x) => match other {\n\n Value::Int(y) => *x as u32 == *y as u32,\n\n Value::Char(y) => *x == *y,\n\n _ => false,\n\n },\n\n Value::String(s) => match other {\n\n Value::String(s2) => *s.borrow() == *s2.borrow(),\n\n _ => false,\n\n },\n\n Value::Array(x) => match other {\n\n Value::Array(y) => *x.borrow() == *y.borrow(),\n\n _ => false,\n\n },\n", "file_path": "vm/src/value.rs", "rank": 66, "score": 31960.99663525355 }, { "content": " _ => None,\n\n }\n\n }\n\n\n\n pub fn tag(&self) -> ValTag {\n\n match self {\n\n Value::Int(_) => ValTag::Int,\n\n Value::Float(_) => ValTag::Float,\n\n Value::Null => ValTag::Null,\n\n Value::Object(_) => ValTag::Object,\n\n Value::Array(_) => ValTag::Array,\n\n Value::String(_) => ValTag::Str,\n\n Value::Function(_) => ValTag::Func,\n\n Value::Bool(_) => ValTag::Bool,\n\n Value::Char(_) => ValTag::Char,\n\n Value::User(x) => ValTag::User(x.borrow().get_kind()),\n\n }\n\n }\n\n}\n\n\n", "file_path": "vm/src/value.rs", "rank": 67, "score": 31960.532841255266 }, { "content": " }\n\n\n\n pub fn to_array(&self) -> Option<Ref<Vec<Value>>> {\n\n match self {\n\n Value::Array(array) => return Some(array.clone()),\n\n _ => None,\n\n }\n\n }\n\n pub fn to_int(&self) -> Option<i64> {\n\n match self {\n\n Value::Int(x) => Some(*x),\n\n Value::Float(x) => Some(*x as i64),\n\n _ => None,\n\n }\n\n }\n\n\n\n pub fn to_float(&self) -> Option<f64> {\n\n match self {\n\n Value::Int(x) => Some(*x as f64),\n\n Value::Float(x) => Some(*x),\n", "file_path": "vm/src/value.rs", "rank": 68, "score": 31960.47492791893 }, { "content": " }\n\n }\n\n Value::User(x) => write!(f, \"{}\", x.borrow()),\n\n Value::Null => write!(f, \"null\"),\n\n Value::String(s) => write!(f, \"{}\", *s.borrow()),\n\n Value::Bool(x) => write!(f, \"{}\", x),\n\n }\n\n }\n\n}\n\n\n\nimpl PartialEq for Value {\n\n fn eq(&self, other: &Self) -> bool {\n\n match self {\n\n Value::Bool(x) => match other {\n\n Value::Bool(y) => x == y,\n\n _ => false,\n\n },\n\n Value::Int(x) => match other {\n\n Value::Int(y) => x == y,\n\n Value::Float(y) => *x == *y as i64,\n", "file_path": "vm/src/value.rs", "rank": 69, "score": 31960.255779520834 }, { "content": " Value::Object(object) => {\n\n let mut fmt = String::new();\n\n fmt.push_str(\"{\\n\");\n\n for (i, (key, val)) in object.borrow().table.iter().enumerate() {\n\n let key = key.to_string();\n\n let value = val.to_string();\n\n fmt.push_str(&format!(\" {} => {}\", key, value));\n\n if i < object.borrow().table.len() - 1 {\n\n fmt.push(',');\n\n }\n\n fmt.push('\\n');\n\n }\n\n fmt.push('}');\n\n write!(f, \"{}\", fmt)\n\n }\n\n Value::Function(func) => {\n\n if func.borrow().native {\n\n write!(f, \"<function {:x}>\", func.borrow().address)\n\n } else {\n\n write!(f, \"<function at {:x}>\", func.borrow().address)\n", "file_path": "vm/src/value.rs", "rank": 70, "score": 31960.14494928261 }, { "content": " Value::Null => match other {\n\n Value::Null => true,\n\n _ => false,\n\n },\n\n Value::Object(x) => match other {\n\n Value::Object(y) => {\n\n for ((key1, val1), (key2, val2)) in\n\n x.borrow().table.iter().zip(y.borrow().table.iter())\n\n {\n\n if (key1 != key2) || (val2 != val1) {\n\n return false;\n\n }\n\n }\n\n true\n\n }\n\n _ => false,\n\n },\n\n _ => false,\n\n }\n\n }\n", "file_path": "vm/src/value.rs", "rank": 71, "score": 31959.892138108036 }, { "content": "impl fmt::Display for Value {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match self {\n\n Value::Int(x) => write!(f, \"{}\", x),\n\n Value::Float(x) => write!(f, \"{}\", x),\n\n Value::Array(array) => {\n\n let mut fmt = String::new();\n\n fmt.push('[');\n\n for (idx, value) in array.borrow().iter().enumerate() {\n\n fmt.push_str(&value.to_string());\n\n\n\n if idx < array.borrow().len() - 1 {\n\n fmt.push(',');\n\n }\n\n }\n\n\n\n fmt.push(']');\n\n write!(f, \"{}\", fmt)\n\n }\n\n Value::Char(x) => write!(f, \"{}\", x),\n", "file_path": "vm/src/value.rs", "rank": 72, "score": 31959.585752223877 }, { "content": " Null,\n\n Bool,\n\n Int,\n\n Float,\n\n Str,\n\n Array,\n\n Object,\n\n Func,\n\n Char,\n\n User(&'static str),\n\n}\n\n\n\nimpl Value {\n\n pub fn to_bool(&self) -> bool {\n\n match self {\n\n Value::Null => false,\n\n Value::Bool(x) => *x,\n\n Value::Int(x) => {\n\n if *x == 0 {\n\n false\n", "file_path": "vm/src/value.rs", "rank": 73, "score": 31959.223437733803 }, { "content": " } else {\n\n true\n\n }\n\n }\n\n Value::Float(x) => {\n\n if *x == 0.0 {\n\n false\n\n } else {\n\n true\n\n }\n\n }\n\n _ => true,\n\n }\n\n }\n\n\n\n pub fn to_object(&self) -> Option<Ref<Object>> {\n\n match self {\n\n Value::Object(obj) => return Some(obj.clone()),\n\n _ => None,\n\n }\n", "file_path": "vm/src/value.rs", "rank": 74, "score": 31959.118078047086 }, { "content": "impl Hash for Value {\n\n fn hash<H: Hasher>(&self, state: &mut H) {\n\n match self {\n\n Value::Null => {\n\n 0.hash(state);\n\n }\n\n Value::Int(x) => {\n\n 1.hash(state);\n\n x.hash(state);\n\n }\n\n Value::Float(x) => {\n\n 2.hash(state);\n\n x.to_bits().hash(state);\n\n }\n\n Value::String(s) => {\n\n 3.hash(state);\n\n s.borrow().hash(state);\n\n }\n\n Value::Array(array) => {\n\n 4.hash(state);\n", "file_path": "vm/src/value.rs", "rank": 75, "score": 31958.96321496495 }, { "content": " Value::Array(a) => a.trace(),\n\n Value::Object(o) => o.trace(),\n\n Value::Function(f) => f.trace(),\n\n Value::User(_) => (),\n\n _ => (),\n\n }\n\n }\n\n}\n\n\n\nimpl Trace for Object {\n\n fn trace(&self) {\n\n match &self.prototype {\n\n Some(proto) => proto.trace(),\n\n _ => (),\n\n }\n\n for (key, val) in self.table.iter() {\n\n key.trace();\n\n val.trace();\n\n }\n\n }\n\n}\n\n*/\n\n\n\nmopafy!(UserKind);\n", "file_path": "vm/src/value.rs", "rank": 76, "score": 31956.464524088246 }, { "content": "use crate::*;\n\nuse value::*;\n\n\n\n#[derive(Clone)]\n\npub enum Infos {\n\n Exit,\n\n Info(\n\n Option<Ref<Module>>,\n\n usize,\n\n Value,\n\n Value,\n\n Ref<HashMap<u16, Value>>,\n\n ),\n\n}\n\n\n\nuse std::collections::HashMap;\n\n\n\npub struct Vm {\n\n pub pc: usize,\n\n pub stack: Ref<Vec<Value>>,\n", "file_path": "vm/src/interp.rs", "rank": 85, "score": 11.911949298550455 }, { "content": " false\n\n }\n\n }\n\n }\n\n pub fn stack(&self) -> std::cell::RefMut<'_, Vec<Value>> {\n\n self.stack.borrow_mut()\n\n }\n\n\n\n pub fn interp(&mut self, mut m: Ref<Module>) -> Value {\n\n use opcode::Op;\n\n macro_rules! throw {\n\n ($val: expr) => {\n\n catch!(Err($val));\n\n };\n\n }\n\n macro_rules! catch {\n\n ($e: expr) => {\n\n match $e {\n\n Ok(val) => val,\n\n Err(e) => {\n", "file_path": "vm/src/interp.rs", "rank": 86, "score": 11.22991136768386 }, { "content": "use crate::interp::*;\n\nuse crate::value::*;\n\nuse crate::*;\n\n\n\npub mod io;\n\nuse std::collections::HashMap;\n\n\n\nthread_local! {\n\n pub static BUILTINS: HashMap<String,Value> = builtins_init();\n\n}\n\n\n", "file_path": "vm/src/builtins.rs", "rank": 87, "score": 11.20754099501625 }, { "content": "use crate::value::{Function, Object};\n\nuse crate::*;\n\nuse byteorder::{LittleEndian, ReadBytesExt};\n\nuse std::io::Cursor;\n\nuse value::*;\n\n\n\npub struct BytecodeReader<'a> {\n\n pub bytes: Cursor<&'a [u8]>,\n\n}\n\n\n\npub const TAG_STRING: u8 = 0;\n\npub const TAG_FLOAT: u8 = 1;\n\npub const TAG_DBGINFO: u8 = 2;\n\npub const TAG_FUN: u8 = 3;\n\n\n\nimpl<'a> BytecodeReader<'a> {\n\n pub fn new(bytes: &'a [u8]) -> Self {\n\n Self {\n\n bytes: Cursor::new(bytes),\n\n }\n", "file_path": "vm/src/reader.rs", "rank": 88, "score": 10.911984719199618 }, { "content": " argc: argc as _,\n\n module: Some(m.clone()),\n\n };\n\n //gc_add_root(env);\n\n m.borrow_mut().globals.push(Value::Function(Ref(fun)));\n\n }\n\n TAG_DBGINFO => {\n\n m.borrow_mut().trace_info = self.read_dbginfo(&strings, code_size as _);\n\n }\n\n _ => unreachable!(),\n\n }\n\n }\n\n use opcode::Op;\n\n for _ in 0..code_size {\n\n let op = self.read_u8();\n\n let opcode = match op {\n\n 0 => Op::LoadNull,\n\n 1 => Op::LoadTrue,\n\n 2 => Op::LoadFalse,\n\n 3 => {\n", "file_path": "vm/src/reader.rs", "rank": 91, "score": 10.463073145018395 }, { "content": "use crate::*;\n\nuse byteorder::{LittleEndian, WriteBytesExt};\n\nuse value::*;\n\n\n\nuse crate::opcode::Op;\n\nuse crate::reader::{TAG_FLOAT, TAG_FUN, TAG_STRING};\n\nuse crate::value::{Function, ValTag};\n\nuse hashlink::LinkedHashMap;\n\n\n\npub struct BytecodeWriter {\n\n pub bytecode: Vec<u8>,\n\n}\n\n\n\nimpl BytecodeWriter {\n\n pub fn write_u8(&mut self, x: u8) {\n\n self.bytecode.push(x);\n\n }\n\n pub fn write_u16(&mut self, x: u16) {\n\n self.bytecode.write_u16::<LittleEndian>(x).unwrap();\n\n }\n", "file_path": "vm/src/writer.rs", "rank": 92, "score": 10.370544007961618 }, { "content": "#![feature(coerce_unsized)]\n\n#![feature(unsize)]\n\n\n\n#[macro_use]\n\nextern crate mopa;\n\n\n\n#[macro_use]\n\npub mod interp;\n\npub mod atomic_ref;\n\npub mod builtins;\n\npub mod gc;\n\n\n\npub mod jit;\n\npub mod opcode;\n\npub mod reader;\n\npub mod value;\n\npub mod writer;\n\n\n\nuse mimalloc::MiMalloc;\n\n#[global_allocator]\n", "file_path": "vm/src/lib.rs", "rank": 93, "score": 10.147995696905651 }, { "content": " }\n\n\n\n fn with<F, R>(&self, f: F) -> R\n\n where\n\n F: FnOnce(Rc<GcData<T>>) -> R,\n\n {\n\n f(self.inner.upgrade().expect(\"use after free\"))\n\n }\n\n}\n\n\n\nimpl<T: Trace + ?Sized> GcData<T> {\n\n /// Gets the value of the `traced` metadata field.\n\n ///\n\n /// The meaning of this value changes every collection and depends on GC\n\n /// state.\n\n fn traced(&self) -> bool {\n\n self.metadata.traced.get()\n\n }\n\n}\n\n\n", "file_path": "vm/src/gc.rs", "rank": 94, "score": 10.063449113428861 }, { "content": " pub fn write_u32(&mut self, x: u32) {\n\n self.bytecode.write_u32::<LittleEndian>(x).unwrap();\n\n }\n\n pub fn write_u64(&mut self, x: u64) {\n\n self.bytecode.write_u64::<LittleEndian>(x).unwrap();\n\n }\n\n\n\n pub fn write_module(&mut self, m: Ref<Module>) {\n\n let mut strings = LinkedHashMap::new();\n\n let mut i = 0;\n\n for value in m.borrow().globals.iter() {\n\n if let Value::String(s) = value {\n\n strings.insert(s.borrow().clone(), i);\n\n i += 1;\n\n }\n\n }\n\n let mut globals = vec![];\n\n for value in m.borrow().globals.iter() {\n\n match value.tag() {\n\n ValTag::Func | ValTag::Str | ValTag::Float => globals.push(value.clone()),\n", "file_path": "vm/src/writer.rs", "rank": 95, "score": 10.027411211347877 }, { "content": " pub exception_stack: Vec<(usize, Infos)>,\n\n pub info_stack: Vec<Infos>,\n\n pub env: Value,\n\n pub locals: Ref<HashMap<u16, Value>>,\n\n pub this: Value,\n\n}\n\n\n\nthread_local! {\n\n pub static VM: *mut Vm = Box::into_raw(Box::new(Vm::new()));\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! get_vm {\n\n () => {\n\n unsafe { VM.with(|vm_ptr| &mut **vm_ptr) }\n\n };\n\n}\n\n\n\nimpl Vm {\n\n pub fn new() -> Vm {\n", "file_path": "vm/src/interp.rs", "rank": 96, "score": 9.540769752763548 }, { "content": "use crate::*;\n\nuse jazzlight::opcode::*;\n\nuse jazzlight::value::*;\n\nuse jazzlight::*;\n\nuse std::cell::RefCell;\n\nuse std::rc::Rc;\n\n\n\n#[derive(Clone)]\n\npub enum UOP {\n\n Goto(String),\n\n GotoF(String),\n\n GotoT(String),\n\n Label(String),\n\n PAddr(String),\n\n Op(Op),\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Hash, Eq)]\n\npub enum Global {\n\n Var(String),\n", "file_path": "src/codegen.rs", "rank": 97, "score": 9.217347333529636 }, { "content": " self.stack().push(Value::Bool(*x.borrow() >= *y.borrow()))\n\n }\n\n _ => self.stack().push(Value::Bool(false)),\n\n },\n\n Value::Int(x) => match rhs {\n\n Value::Int(y) => self.stack().push(Value::Bool(x >= y)),\n\n Value::Float(y) => self.stack().push(Value::Bool((x as f64) >= y)),\n\n _ => self.stack().push(Value::Bool(false)),\n\n },\n\n Value::Float(x) => match rhs {\n\n Value::Int(y) => self.stack().push(Value::Bool(x >= y as f64)),\n\n Value::Float(y) => self.stack().push(Value::Bool(x >= y as f64)),\n\n _ => self.stack().push(Value::Bool(false)),\n\n },\n\n Value::Array(x) => match rhs {\n\n Value::Array(y) => self.stack().push(Value::Bool(\n\n (x.borrow().len() > y.borrow().len()) || *x.borrow() == *y.borrow(),\n\n )),\n\n _ => self.stack().push(Value::Bool(false)),\n\n },\n", "file_path": "vm/src/interp.rs", "rank": 99, "score": 8.363148446552149 } ]
Rust
dao-contracts/tests/test_kyc_voter.rs
make-software/dao-contracts
aba3ed15d4c52ad411e6cd320f7daf1ef85715ac
use casper_dao_contracts::{ DaoOwnedNftContractTest, KycVoterContractTest, ReputationContractTest, VariableRepositoryContractTest, }; use casper_dao_utils::{Address, TestContract, TestEnv}; use casper_types::U256; use speculate::speculate; speculate! { use casper_types::U256; use casper_dao_utils::Error; use std::time::Duration; use casper_dao_contracts::voting::VotingId; use casper_dao_contracts::voting::Choice; before { #[allow(unused_variables, unused_mut)] let ( applicant, another_applicant, voter, second_voter, mint_amount, vote_amount, document_hash, mut kyc_token, mut reputation_token, mut variable_repo, mut contract, mut env ) = setup(); } describe "voting" { test "kyc_token_address_is_set" { assert_eq!( contract.get_kyc_token_address(), kyc_token.address() ) } context "applicant_is_not_kyced" { before { assert_eq!(kyc_token.balance_of(applicant), U256::zero()); } test "voting_creation_succeeds" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Ok(()) ); } context "voting_is_created" { before { contract.as_account(voter).create_voting(applicant, document_hash, vote_amount).unwrap(); } test "cannot_create_next_voting_for_the_same_applicant" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Err(Error::KycAlreadyInProgress) ); } test "can_create_next_voting_for_a_different_applicant" { assert_eq!( contract.as_account(voter).create_voting(another_applicant, document_hash, vote_amount), Ok(()) ); } context "informal_voting_passed" { before { let voting_id = 0.into(); let voting = contract.get_voting(voting_id).unwrap(); env.advance_block_time_by(Duration::from_secs(voting.informal_voting_time() + 1)); contract.as_account(voter).finish_voting(voting_id).unwrap(); #[allow(unused_variables)] let voting_id: VotingId = 1.into(); } test "cannot_create_next_voting_for_the_same_applicant" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Err(Error::KycAlreadyInProgress) ); } context "passed" { before { contract.as_account(second_voter).vote(voting_id, Choice::InFavor, vote_amount).unwrap(); env.advance_block_time_by(Duration::from_secs(voting.formal_voting_time() + 1)); contract.as_account(voter).finish_voting(voting_id).unwrap(); } test "applicant_owns_kyc_token" { assert_eq!( kyc_token.balance_of(applicant), U256::one() ); } } context "rejected" { before { contract.as_account(second_voter).vote(voting_id, Choice::Against, vote_amount + U256::one()).unwrap(); env.advance_block_time_by(Duration::from_secs(voting.formal_voting_time() + 1)); contract.as_account(voter).finish_voting(voting_id).unwrap(); } test "next_voting_creation_for_the_same_applicant_succeeds" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Ok(()) ); } test "applicant_does_not_own_kyc_token" { assert_eq!( kyc_token.balance_of(applicant), U256::zero() ); } } } } } context "applicant_is_kyced" { before { kyc_token.mint(applicant, 1.into()).unwrap(); } test "voting_cannot_be_created" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Err(Error::UserKycedAlready) ); } } } } fn setup() -> ( Address, Address, Address, Address, U256, U256, U256, DaoOwnedNftContractTest, ReputationContractTest, VariableRepositoryContractTest, KycVoterContractTest, TestEnv, ) { let env = TestEnv::new(); let mut kyc_token = DaoOwnedNftContractTest::new( &env, "kyc token".to_string(), "kyt".to_string(), "".to_string(), ); let mut reputation_token = ReputationContractTest::new(&env); let mut variable_repo = VariableRepositoryContractTest::new(&env); let onboarding_voter = KycVoterContractTest::new( &env, variable_repo.address(), reputation_token.address(), kyc_token.address(), ); variable_repo .change_ownership(onboarding_voter.address()) .unwrap(); reputation_token .change_ownership(onboarding_voter.address()) .unwrap(); kyc_token .change_ownership(onboarding_voter.address()) .unwrap(); let applicant = env.get_account(1); let another_applicant = env.get_account(2); let voter = env.get_account(3); let second_voter = env.get_account(4); let mint_amount = 10_000.into(); let vote_amount = 1_000.into(); reputation_token.mint(voter, mint_amount).unwrap(); reputation_token.mint(second_voter, mint_amount).unwrap(); let document_hash = 1234.into(); ( applicant, another_applicant, voter, second_voter, mint_amount, vote_amount, document_hash, kyc_token, reputation_token, variable_repo, onboarding_voter, env, ) }
use casper_dao_contracts::{ DaoOwnedNftContractTest, KycVoterContractTest, ReputationContractTest, VariableRepositoryContractTest, }; use casper_dao_utils::{Addre
get_kyc_token_address(), kyc_token.address() ) } context "applicant_is_not_kyced" { before { assert_eq!(kyc_token.balance_of(applicant), U256::zero()); } test "voting_creation_succeeds" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Ok(()) ); } context "voting_is_created" { before { contract.as_account(voter).create_voting(applicant, document_hash, vote_amount).unwrap(); } test "cannot_create_next_voting_for_the_same_applicant" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Err(Error::KycAlreadyInProgress) ); } test "can_create_next_voting_for_a_different_applicant" { assert_eq!( contract.as_account(voter).create_voting(another_applicant, document_hash, vote_amount), Ok(()) ); } context "informal_voting_passed" { before { let voting_id = 0.into(); let voting = contract.get_voting(voting_id).unwrap(); env.advance_block_time_by(Duration::from_secs(voting.informal_voting_time() + 1)); contract.as_account(voter).finish_voting(voting_id).unwrap(); #[allow(unused_variables)] let voting_id: VotingId = 1.into(); } test "cannot_create_next_voting_for_the_same_applicant" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Err(Error::KycAlreadyInProgress) ); } context "passed" { before { contract.as_account(second_voter).vote(voting_id, Choice::InFavor, vote_amount).unwrap(); env.advance_block_time_by(Duration::from_secs(voting.formal_voting_time() + 1)); contract.as_account(voter).finish_voting(voting_id).unwrap(); } test "applicant_owns_kyc_token" { assert_eq!( kyc_token.balance_of(applicant), U256::one() ); } } context "rejected" { before { contract.as_account(second_voter).vote(voting_id, Choice::Against, vote_amount + U256::one()).unwrap(); env.advance_block_time_by(Duration::from_secs(voting.formal_voting_time() + 1)); contract.as_account(voter).finish_voting(voting_id).unwrap(); } test "next_voting_creation_for_the_same_applicant_succeeds" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Ok(()) ); } test "applicant_does_not_own_kyc_token" { assert_eq!( kyc_token.balance_of(applicant), U256::zero() ); } } } } } context "applicant_is_kyced" { before { kyc_token.mint(applicant, 1.into()).unwrap(); } test "voting_cannot_be_created" { assert_eq!( contract.as_account(voter).create_voting(applicant, document_hash, vote_amount), Err(Error::UserKycedAlready) ); } } } } fn setup() -> ( Address, Address, Address, Address, U256, U256, U256, DaoOwnedNftContractTest, ReputationContractTest, VariableRepositoryContractTest, KycVoterContractTest, TestEnv, ) { let env = TestEnv::new(); let mut kyc_token = DaoOwnedNftContractTest::new( &env, "kyc token".to_string(), "kyt".to_string(), "".to_string(), ); let mut reputation_token = ReputationContractTest::new(&env); let mut variable_repo = VariableRepositoryContractTest::new(&env); let onboarding_voter = KycVoterContractTest::new( &env, variable_repo.address(), reputation_token.address(), kyc_token.address(), ); variable_repo .change_ownership(onboarding_voter.address()) .unwrap(); reputation_token .change_ownership(onboarding_voter.address()) .unwrap(); kyc_token .change_ownership(onboarding_voter.address()) .unwrap(); let applicant = env.get_account(1); let another_applicant = env.get_account(2); let voter = env.get_account(3); let second_voter = env.get_account(4); let mint_amount = 10_000.into(); let vote_amount = 1_000.into(); reputation_token.mint(voter, mint_amount).unwrap(); reputation_token.mint(second_voter, mint_amount).unwrap(); let document_hash = 1234.into(); ( applicant, another_applicant, voter, second_voter, mint_amount, vote_amount, document_hash, kyc_token, reputation_token, variable_repo, onboarding_voter, env, ) }
ss, TestContract, TestEnv}; use casper_types::U256; use speculate::speculate; speculate! { use casper_types::U256; use casper_dao_utils::Error; use std::time::Duration; use casper_dao_contracts::voting::VotingId; use casper_dao_contracts::voting::Choice; before { #[allow(unused_variables, unused_mut)] let ( applicant, another_applicant, voter, second_voter, mint_amount, vote_amount, document_hash, mut kyc_token, mut reputation_token, mut variable_repo, mut contract, mut env ) = setup(); } describe "voting" { test "kyc_token_address_is_set" { assert_eq!( contract.
random
[ { "content": "fn setup() -> (TestEnv, ReputationContractTest) {\n\n let env = TestEnv::new();\n\n let contract = ReputationContractTest::new(&env);\n\n\n\n (env, contract)\n\n}\n\n\n", "file_path": "dao-contracts/tests/test_reputation.rs", "rank": 0, "score": 26852.55778664241 }, { "content": "#[allow(dead_code)]\n\npub fn setup_admin() -> (AdminContractTest, ReputationContractTest) {\n\n let minimum_reputation = 500.into();\n\n let informal_quorum = 500.into();\n\n let formal_quorum = 500.into();\n\n let total_onboarded = 3;\n\n\n\n let (variable_repo_contract, mut reputation_token_contract) =\n\n setup_repository_and_reputation_contracts(informal_quorum, formal_quorum, total_onboarded);\n\n\n\n #[allow(unused_mut)]\n\n let mut admin_contract = AdminContractTest::new(\n\n variable_repo_contract.get_env(),\n\n variable_repo_contract.address(),\n\n reputation_token_contract.address(),\n\n );\n\n\n\n reputation_token_contract\n\n .change_ownership(admin_contract.address())\n\n .unwrap();\n\n\n", "file_path": "dao-contracts/tests/governance_voting_common.rs", "rank": 1, "score": 24672.780999935305 }, { "content": "fn setup_with_initial_supply(amount: U256) -> (TestEnv, ReputationContractTest) {\n\n let (env, mut contract) = setup();\n\n contract.mint(env.get_account(0), amount).unwrap();\n\n\n\n (env, contract)\n\n}\n", "file_path": "dao-contracts/tests/test_reputation.rs", "rank": 2, "score": 22820.323866276605 }, { "content": "#[allow(dead_code)]\n\npub fn assert_reputation(reputation_contract: &ReputationContractTest, reputation: &[usize]) {\n\n for (account, amount) in reputation.iter().enumerate() {\n\n let address = reputation_contract.get_env().get_account(account);\n\n assert_eq!(reputation_contract.balance_of(address), U256::from(*amount));\n\n }\n\n}\n\n\n", "file_path": "dao-contracts/tests/governance_voting_common.rs", "rank": 3, "score": 21226.60879666724 }, { "content": "fn update<T: ToBytes>(contract: &mut VariableRepositoryContractTest, name: &str, value: T) {\n\n contract\n\n .update_at(name.into(), value.to_bytes().unwrap().into(), None)\n\n .unwrap();\n\n}\n", "file_path": "dao-contracts/tests/governance_voting_common.rs", "rank": 4, "score": 16636.175574743338 }, { "content": "use proc_macro2::Span;\n\nuse proc_macro2::TokenStream;\n\nuse quote::quote;\n\nuse quote::TokenStreamExt;\n\nuse syn::punctuated::Punctuated;\n\nuse syn::token::Comma;\n\nuse syn::FnArg;\n\nuse syn::ReturnType;\n\n\n\nuse super::parser::CasperContractItem;\n\nuse super::utils;\n\n\n", "file_path": "dao-macros/src/contract/contract_test.rs", "rank": 5, "score": 5.339556327969959 }, { "content": "mod access_control;\n\nmod owner;\n\nmod repository;\n\nmod staking;\n\nmod token;\n\nmod whitelist;\n\n\n\npub use access_control::AccessControl;\n\npub use owner::Owner;\n\npub use repository::{Record, Repository, RepositoryDefaults};\n\npub use staking::TokenWithStaking;\n\npub use token::Token;\n\npub use whitelist::Whitelist;\n\n\n\npub mod events {\n\n use super::*;\n\n pub use owner::events::*;\n\n pub use repository::events::*;\n\n pub use staking::events::*;\n\n pub use token::events::*;\n\n pub use whitelist::events::*;\n\n}\n", "file_path": "dao-modules/src/lib.rs", "rank": 6, "score": 5.210629983316907 }, { "content": "use convert_case::Casing;\n\nuse proc_macro2::TokenStream;\n\nuse quote::{format_ident, quote, TokenStreamExt};\n\n\n\nuse crate::contract::utils;\n\n\n\nuse super::CasperContractItem;\n\n\n", "file_path": "dao-macros/src/contract/contract_bin.rs", "rank": 7, "score": 5.101837488274723 }, { "content": "mod ballot;\n\nmod governance_voting;\n\npub mod kyc_info;\n\npub mod onboarding_info;\n\n\n\npub use ballot::Ballot;\n\npub use ballot::Choice;\n\npub use ballot::VotingId;\n\npub use governance_voting::consts;\n\npub use governance_voting::events::*;\n\npub use governance_voting::voting;\n\npub use governance_voting::GovernanceVoting;\n", "file_path": "dao-contracts/src/voting/mod.rs", "rank": 8, "score": 5.043795876099588 }, { "content": "extern crate alloc;\n\n\n\n// Reexport of casper-contract crate.\n\npub use casper_contract;\n\n\n\npub mod casper_env;\n\nmod events;\n\npub mod instance;\n\nmod parts;\n\npub use casper_dao_macros;\n\npub mod conversions;\n\npub mod math;\n\n\n\npub use parts::address::Address;\n\npub use parts::collection::List;\n\npub use parts::collection::OrderedCollection;\n\npub use parts::collection::Set;\n\npub use parts::consts;\n\npub use parts::error::Error;\n\npub use parts::mapping::Mapping;\n", "file_path": "dao-utils/src/lib.rs", "rank": 9, "score": 5.001734675770666 }, { "content": "use proc_macro2::TokenStream;\n\nuse quote::quote;\n\n\n\nuse crate::contract::{caller, contract_bin, contract_struct, contract_test};\n\n\n\nuse super::parser::CasperContractItem;\n\n\n", "file_path": "dao-macros/src/contract/generator.rs", "rank": 10, "score": 4.963044315662536 }, { "content": "use casper_types::bytesrepr::{Bytes, FromBytes, ToBytes};\n\n\n\nuse casper_types::{U256, U512};\n\n\n\nuse crate::Error;\n\n\n", "file_path": "dao-utils/src/conversions.rs", "rank": 12, "score": 4.952275167830491 }, { "content": "use proc_macro2::{Ident, Span, TokenStream};\n\nuse quote::{quote, TokenStreamExt};\n\nuse syn::TraitItemMethod;\n\n\n\nuse super::{parser::CasperContractItem, utils};\n\n\n", "file_path": "dao-macros/src/contract/contract_struct.rs", "rank": 13, "score": 4.940196090081035 }, { "content": "use self::{\n\n events::{BallotCast, VotingContractCreated, VotingCreated},\n\n voting::{Voting, VotingConfiguration, VotingResult, VotingType},\n\n};\n\n\n\nuse casper_dao_utils::VecMapping;\n\n\n\nuse super::ballot::Choice;\n\nuse super::VotingEnded;\n\nuse super::{ballot::VotingId, Ballot};\n\n\n", "file_path": "dao-contracts/src/voting/governance_voting.rs", "rank": 14, "score": 4.896959209670334 }, { "content": "use crate::conversions::BytesConversion;\n\nuse crate::Error;\n\nuse casper_types::{U256, U512};\n\n\n\npub const RATIO_DIVISOR: u32 = 1000;\n\n\n", "file_path": "dao-utils/src/math.rs", "rank": 15, "score": 4.89207102314651 }, { "content": "use casper_types::{bytesrepr::FromBytes, ContractPackageHash};\n\nuse std::fmt::Debug;\n\n\n\nuse crate::{Address, TestEnv};\n\n\n", "file_path": "dao-utils/src/test_contract.rs", "rank": 16, "score": 4.89207102314651 }, { "content": "use casper_dao_contracts::{\n\n DaoOwnedNftContractTest, OnboardingVoterContractTest, ReputationContractTest,\n\n VariableRepositoryContractTest,\n\n};\n\nuse casper_dao_utils::{Address, TestContract, TestEnv};\n\nuse casper_types::U256;\n\nuse speculate::speculate;\n\n\n\nspeculate! {\n\n use casper_types::U256;\n\n use casper_dao_contracts::voting::{Choice, onboarding_info::OnboardingAction, VotingId};\n\n use casper_dao_utils::Error;\n\n\n\n use std::time::Duration;\n\n\n\n before {\n\n #[allow(unused_variables, unused_mut)]\n\n let (\n\n user,\n\n va,\n", "file_path": "dao-contracts/tests/test_onboarding_voter.rs", "rank": 17, "score": 4.877442967715053 }, { "content": "use proc_macro2::TokenStream;\n\nuse quote::{quote, TokenStreamExt};\n\n\n\nuse super::{parser::CasperContractItem, utils};\n\n\n", "file_path": "dao-macros/src/contract/caller.rs", "rank": 18, "score": 4.8625145546692625 }, { "content": "use casper_dao_utils::{casper_contract::contract_api::runtime, Address};\n\nuse casper_types::bytesrepr::Bytes;\n\n\n\nuse crate::TokenId;\n\n\n", "file_path": "dao-erc721/src/receiver.rs", "rank": 19, "score": 4.833313084545846 }, { "content": "use proc_macro2::TokenStream;\n\nuse quote::{quote, TokenStreamExt};\n\nuse syn::{Data, DataStruct, DeriveInput, Fields};\n\n\n", "file_path": "dao-macros/src/event.rs", "rank": 20, "score": 4.833313084545846 }, { "content": "use proc_macro::TokenStream;\n\nuse proc_macro2::{Ident as Ident2, TokenStream as TokenStream2};\n\nuse quote::{quote, TokenStreamExt};\n\nuse syn::{Data, DataEnum, DataStruct, DeriveInput, Fields};\n\n\n", "file_path": "dao-macros/src/serialization.rs", "rank": 21, "score": 4.829039532174716 }, { "content": "use proc_macro2::TokenStream;\n\nuse quote::{quote, TokenStreamExt};\n\nuse syn::{spanned::Spanned, DataStruct, DeriveInput, Ident};\n\n\n", "file_path": "dao-macros/src/instance.rs", "rank": 22, "score": 4.804460255207401 }, { "content": "mod burnable;\n\nmod metadata;\n\nmod mintable;\n\n\n\npub use burnable::BurnableERC721;\n\npub use metadata::MetadataERC721;\n\npub use mintable::MintableERC721;\n", "file_path": "dao-erc721/src/extensions/mod.rs", "rank": 23, "score": 4.775949859992174 }, { "content": "use std::borrow::BorrowMut;\n\n\n\nuse casper_dao_utils::{\n\n casper_dao_macros::{casper_contract_interface, Instance},\n\n Address,\n\n};\n\nuse casper_types::{bytesrepr::Bytes, U256};\n\n\n\nuse crate::{\n\n core::ERC721Token,\n\n extensions::{BurnableERC721, MetadataERC721, MintableERC721},\n\n};\n\n\n\nuse delegate::delegate;\n\n\n\npub type TokenId = U256;\n\npub type TokenUri = String;\n\n\n\n#[casper_contract_interface]\n", "file_path": "dao-erc721/src/erc721.rs", "rank": 24, "score": 4.691434740012777 }, { "content": "pub mod core;\n\nmod erc721;\n\npub mod events;\n\nmod extensions;\n\nmod receiver;\n\npub use erc721::*;\n\npub use extensions::{BurnableERC721, MetadataERC721, MintableERC721};\n\npub use receiver::tests::*;\n\n\n\n#[cfg(feature = \"test-support\")]\n\npub use erc721::ERC721Test;\n\n#[cfg(feature = \"test-support\")]\n\npub use receiver::tests::MockERC721NonReceiverTest;\n\n#[cfg(feature = \"test-support\")]\n\npub use receiver::tests::MockERC721ReceiverTest;\n", "file_path": "dao-erc721/src/lib.rs", "rank": 25, "score": 4.684364044269124 }, { "content": "pub use parts::mapping::VecMapping;\n\npub use parts::sequence::SequenceGenerator;\n\npub use parts::variable::Variable;\n\n\n\n#[cfg(feature = \"test-support\")]\n\npub use conversions::BytesConversion;\n\n\n\n#[cfg(feature = \"test-support\")]\n\nmod test_env;\n\n\n\n#[cfg(feature = \"test-support\")]\n\npub use test_env::{ExecutionError, TestEnv};\n\n\n\n#[cfg(feature = \"test-support\")]\n\nmod test_contract;\n\n\n\n#[cfg(feature = \"test-support\")]\n\npub use test_contract::TestContract;\n", "file_path": "dao-utils/src/lib.rs", "rank": 26, "score": 4.684364044269124 }, { "content": "use proc_macro2::{Ident, Span, TokenStream};\n\nuse quote::{format_ident, quote, TokenStreamExt};\n\nuse syn::{punctuated::Punctuated, token, FnArg, Pat, Token, TraitItemMethod, Type, TypePath};\n\n\n\nuse crate::contract::parser::CasperContractItem;\n\n\n", "file_path": "dao-macros/src/contract/utils.rs", "rank": 27, "score": 4.681567314804374 }, { "content": "use pretty_assertions::assert_eq;\n\nuse std::{\n\n fs,\n\n process::{Command, Stdio},\n\n};\n\n\n\n#[test]\n", "file_path": "dao-macros/tests/expand_tests.rs", "rank": 28, "score": 4.673197127531799 }, { "content": "use casper_dao_contracts::ReputationContractTest;\n\nuse casper_dao_modules::events::{\n\n AddedToWhitelist, Burn, Mint, OwnerChanged, RemovedFromWhitelist, TokensStaked, TokensUnstaked,\n\n Transfer,\n\n};\n\nuse casper_dao_utils::{Error, TestContract, TestEnv};\n\nuse casper_types::U256;\n\n\n\n#[test]\n", "file_path": "dao-contracts/tests/test_reputation.rs", "rank": 29, "score": 4.641072468492958 }, { "content": "extern crate proc_macro;\n\n\n\nuse contract::CasperContractItem;\n\nuse proc_macro::TokenStream;\n\nuse quote::quote;\n\nuse syn::{parse_macro_input, DeriveInput};\n\n\n\nmod contract;\n\nmod event;\n\nmod instance;\n\nmod serialization;\n\n\n\n/// Derive events on top of any struct.\n\n#[proc_macro_derive(Event)]\n", "file_path": "dao-macros/src/lib.rs", "rank": 30, "score": 4.641072468492958 }, { "content": "mod erc20;\n\npub use erc20::*;\n\n\n\n#[cfg(feature = \"test-support\")]\n\npub use erc20::ERC20Test;\n", "file_path": "dao-erc20/src/lib.rs", "rank": 31, "score": 4.593186385434826 }, { "content": "\n\npub mod tests {\n\n use casper_dao_utils::{\n\n casper_dao_macros::{casper_contract_interface, Event, Instance},\n\n casper_env::emit,\n\n Address,\n\n };\n\n use casper_types::bytesrepr::Bytes;\n\n\n\n use crate::TokenId;\n\n\n", "file_path": "dao-erc721/src/receiver.rs", "rank": 32, "score": 4.585473593724667 }, { "content": "use casper_dao_utils::{\n\n casper_dao_macros::{casper_contract_interface, Instance},\n\n casper_env::caller,\n\n Address,\n\n};\n\nuse casper_types::{bytesrepr::Bytes, runtime_args, RuntimeArgs, U256};\n\n\n\nuse crate::voting::{voting::Voting, Ballot, Choice, GovernanceVoting, VotingId};\n\n\n\nuse delegate::delegate;\n\n\n\n#[casper_contract_interface]\n", "file_path": "dao-contracts/src/repo_voter.rs", "rank": 33, "score": 4.581626903101646 }, { "content": "use casper_dao_utils::{\n\n casper_dao_macros::{casper_contract_interface, Instance},\n\n casper_env::caller,\n\n Address,\n\n};\n\nuse casper_types::{runtime_args, RuntimeArgs, U256};\n\n\n\nuse crate::{\n\n action::Action,\n\n voting::{voting::Voting, Ballot, Choice, GovernanceVoting, VotingId},\n\n};\n\n\n\nuse delegate::delegate;\n\n\n\n#[casper_contract_interface]\n", "file_path": "dao-contracts/src/admin.rs", "rank": 34, "score": 4.581626903101646 }, { "content": "use casper_dao_utils::{\n\n casper_dao_macros::{casper_contract_interface, Instance},\n\n casper_env::{caller, self_address},\n\n Address, Variable,\n\n};\n\nuse casper_types::{runtime_args, RuntimeArgs, U256};\n\n\n\nuse crate::voting::{voting::Voting, Ballot, Choice, GovernanceVoting, VotingId};\n\n\n\nuse delegate::delegate;\n\n\n\n#[casper_contract_interface]\n", "file_path": "dao-contracts/src/mocks/mock_voter.rs", "rank": 35, "score": 4.581626903101646 }, { "content": "use casper_dao_erc721::{\n\n core::ERC721Token, BurnableERC721, MetadataERC721, MintableERC721, TokenId, TokenUri,\n\n};\n\nuse casper_dao_modules::AccessControl;\n\nuse casper_dao_utils::{\n\n casper_contract::unwrap_or_revert::UnwrapOrRevert,\n\n casper_dao_macros::{casper_contract_interface, Instance},\n\n casper_env::{self, caller},\n\n Address, Error, Mapping,\n\n};\n\nuse casper_types::U256;\n\nuse delegate::delegate;\n\n\n\n#[casper_contract_interface]\n", "file_path": "dao-contracts/src/dao_nft.rs", "rank": 36, "score": 4.579321985027704 }, { "content": "use casper_dao_utils::{\n\n casper_dao_macros::{casper_contract_interface, Instance},\n\n casper_env::{self, emit},\n\n Address, Error, Mapping, Variable,\n\n};\n\nuse casper_types::U256;\n\n\n\nuse self::events::{Approval, Transfer};\n\n\n\n#[casper_contract_interface]\n", "file_path": "dao-erc20/src/erc20.rs", "rank": 37, "score": 4.559495941159109 }, { "content": "use convert_case::{Case, Casing};\n\nuse proc_macro2::{Ident, Span};\n\nuse quote::format_ident;\n\nuse syn::parse::{Parse, ParseStream};\n\nuse syn::{braced, Token, TraitItemMethod};\n\n\n\nuse super::utils;\n\n\n\n#[derive(Debug)]\n\npub struct CasperContractItem {\n\n pub trait_token: Token![trait],\n\n pub trait_methods: Vec<TraitItemMethod>,\n\n pub ident: Ident,\n\n pub contract_ident: Ident,\n\n pub caller_ident: Ident,\n\n pub contract_test_ident: Ident,\n\n pub package_hash: String,\n\n pub wasm_file_name: String,\n\n}\n\n\n", "file_path": "dao-macros/src/contract/parser.rs", "rank": 38, "score": 4.551895785603611 }, { "content": "#[cfg(feature = \"test-support\")]\n\npub use repo_voter::RepoVoterContractTest;\n\n\n\n#[doc(hidden)]\n\n#[cfg(feature = \"test-support\")]\n\npub use admin::AdminContractTest;\n\n\n\n#[cfg(feature = \"test-support\")]\n\npub use mocks::mock_voter::MockVoterContractTest;\n\n\n\n#[cfg(feature = \"test-support\")]\n\npub use onboarding_voter::OnboardingVoterContractTest;\n\n\n\n#[cfg(feature = \"test-support\")]\n\npub use dao_nft::DaoOwnedNftContractTest;\n\n\n\n#[cfg(feature = \"test-support\")]\n\npub use kyc_voter::KycVoterContractTest;\n", "file_path": "dao-contracts/src/lib.rs", "rank": 39, "score": 4.539059862726747 }, { "content": "use std::marker::PhantomData;\n\n\n\nuse casper_contract::unwrap_or_revert::UnwrapOrRevert;\n\nuse casper_types::{\n\n bytesrepr::{FromBytes, ToBytes},\n\n CLTyped,\n\n};\n\n\n\nuse crate::{\n\n casper_env::{get_key, set_key},\n\n instance::Instanced,\n\n Error,\n\n};\n\n\n\n/// Data structure for storing a single value.\n\npub struct Variable<T> {\n\n name: String,\n\n ty: PhantomData<T>,\n\n}\n\n\n", "file_path": "dao-utils/src/parts/variable.rs", "rank": 40, "score": 4.523684906133738 }, { "content": "use std::{\n\n collections::{hash_map::DefaultHasher, BTreeMap},\n\n hash::{Hash, Hasher},\n\n marker::PhantomData,\n\n sync::Mutex,\n\n};\n\n\n\nuse casper_contract::{\n\n contract_api::{runtime, storage},\n\n unwrap_or_revert::UnwrapOrRevert,\n\n};\n\nuse casper_types::{\n\n bytesrepr::{FromBytes, ToBytes},\n\n CLTyped, Key, URef,\n\n};\n\nuse lazy_static::lazy_static;\n\n\n\nuse crate::{casper_env::to_dictionary_key, instance::Instanced, Error};\n\n\n\n/// Data structure for storing key-value pairs.\n", "file_path": "dao-utils/src/parts/mapping.rs", "rank": 41, "score": 4.517630951408681 }, { "content": "use casper_dao_modules::{AccessControl, TokenWithStaking};\n\nuse casper_dao_utils::{\n\n casper_dao_macros::{casper_contract_interface, Instance},\n\n casper_env::caller,\n\n Address, Variable,\n\n};\n\nuse casper_types::U256;\n\nuse delegate::delegate;\n\n\n\n// Interface of the Reputation Contract.\n\n//\n\n// It should be implemented by [`ReputationContract`], [`ReputationContractCaller`]\n\n// and [`ReputationContractTest`].\n\n#[casper_contract_interface]\n", "file_path": "dao-contracts/src/reputation.rs", "rank": 42, "score": 4.504695215206544 }, { "content": "mod governance_voting_common;\n\n\n\nuse casper_dao_contracts::voting::{\n\n consts as gv_consts, Ballot, BallotCast, Choice, VotingContractCreated, VotingCreated,\n\n VotingEnded, VotingId,\n\n};\n\nuse casper_dao_utils::Error;\n\nuse casper_dao_utils::TestContract;\n\nuse casper_types::U256;\n\nuse speculate::speculate;\n\n\n\nspeculate! {\n\n context \"governance voting\" {\n\n before {\n\n let informal_quorum = U256::from(500);\n\n let formal_quorum = U256::from(750);\n\n let total_onboarded = 4;\n\n #[allow(unused_variables)]\n\n let minimum_reputation = U256::from(500);\n\n #[allow(unused_variables)]\n", "file_path": "dao-contracts/tests/test_governance_voting.rs", "rank": 43, "score": 4.472442558054244 }, { "content": "use std::{fmt::Debug, hash::Hash};\n\n\n\nuse casper_contract::unwrap_or_revert::UnwrapOrRevert;\n\nuse casper_types::{\n\n bytesrepr::{FromBytes, ToBytes},\n\n CLTyped,\n\n};\n\n\n\nuse crate::{consts, instance::Instanced, Variable};\n\n\n\nuse super::mapping::IndexedMapping;\n\n\n\npub struct OrderedCollection<T> {\n\n pub values: IndexedMapping<T>,\n\n pub length: Variable<u32>,\n\n}\n\n\n\nimpl<T: ToBytes + FromBytes + CLTyped + PartialEq + Debug + Hash> OrderedCollection<T> {\n\n pub fn new(name: &str) -> Self {\n\n Self {\n", "file_path": "dao-utils/src/parts/collection.rs", "rank": 44, "score": 4.472442558054244 }, { "content": "#[doc(hidden)]\n\npub use mocks::mock_voter::{\n\n MockVoterContract, MockVoterContractCaller, MockVoterContractInterface,\n\n};\n\npub use onboarding_voter::{\n\n OnboardingVoterContract, OnboardingVoterContractCaller, OnboardingVoterContractInterface,\n\n};\n\npub use repo_voter::{RepoVoterContract, RepoVoterContractCaller, RepoVoterContractInterface};\n\npub use reputation::{ReputationContract, ReputationContractCaller, ReputationContractInterface};\n\npub use variable_repository::{\n\n VariableRepositoryContract, VariableRepositoryContractCaller,\n\n VariableRepositoryContractInterface,\n\n};\n\n\n\n#[cfg(feature = \"test-support\")]\n\npub use reputation::ReputationContractTest;\n\n\n\n#[cfg(feature = \"test-support\")]\n\npub use variable_repository::VariableRepositoryContractTest;\n\n\n", "file_path": "dao-contracts/src/lib.rs", "rank": 45, "score": 4.457201447629903 }, { "content": "use casper_dao_utils::{\n\n casper_contract::unwrap_or_revert::UnwrapOrRevert,\n\n casper_dao_macros::{casper_contract_interface, Instance},\n\n casper_env::{self, caller},\n\n consts, Address, Error,\n\n};\n\nuse casper_types::{runtime_args, RuntimeArgs, U256};\n\n\n\nuse crate::voting::{\n\n kyc_info::KycInfo, voting::Voting, Ballot, Choice, GovernanceVoting, VotingId,\n\n};\n\nuse delegate::delegate;\n\n\n\n#[casper_contract_interface]\n", "file_path": "dao-contracts/src/kyc_voter.rs", "rank": 46, "score": 4.412089066183572 }, { "content": "use std::{collections::BTreeSet, convert::TryInto};\n\n\n\nuse casper_contract::{\n\n contract_api::{runtime, storage},\n\n unwrap_or_revert::UnwrapOrRevert,\n\n};\n\nuse casper_types::{\n\n bytesrepr::{FromBytes, ToBytes},\n\n contracts::NamedKeys,\n\n system::CallStackElement,\n\n ApiError, CLTyped, ContractPackageHash, EntryPoints, RuntimeArgs, URef,\n\n};\n\n\n\nuse crate::{events::Events, Address};\n\n\n\n/// Read value from the storage.\n", "file_path": "dao-utils/src/casper_env.rs", "rank": 47, "score": 4.37610402197186 }, { "content": "use casper_dao_erc20::{\n\n events::{Approval, Transfer},\n\n ERC20Test,\n\n};\n\nuse casper_dao_utils::{Error, TestContract, TestEnv};\n\nuse casper_types::U256;\n\n\n\nstatic NAME: &str = \"Plascoin\";\n\nstatic SYMBOL: &str = \"PLS\";\n\nstatic DECIMALS: u8 = 2;\n\nstatic INITIAL_SUPPLY: u32 = 1000;\n\n\n", "file_path": "dao-erc20/tests/test_erc20.rs", "rank": 48, "score": 4.3618114572731574 }, { "content": "//! Governance Voting module.\n\npub mod consts;\n\npub mod events;\n\npub mod voting;\n\n\n\nuse casper_dao_utils::conversions::{u256_to_512, u512_to_u256};\n\nuse casper_dao_utils::{\n\n casper_contract::unwrap_or_revert::UnwrapOrRevert,\n\n casper_dao_macros::Instance,\n\n casper_env::{call_contract, emit, get_block_time, revert, self_address},\n\n Address, Error, Mapping, Variable,\n\n};\n\n\n\nuse casper_types::{runtime_args, RuntimeArgs, U256, U512};\n\n\n\nuse crate::{\n\n ReputationContractCaller, ReputationContractInterface, VariableRepositoryContractCaller,\n\n};\n\n\n\nuse self::voting::VotingSummary;\n", "file_path": "dao-contracts/src/voting/governance_voting.rs", "rank": 49, "score": 4.356244953527673 }, { "content": "//! Token with staking powers.\n\n\n\nuse self::events::{TokensStaked, TokensUnstaked};\n\nuse crate::Token;\n\nuse casper_dao_utils::{\n\n casper_dao_macros::Instance,\n\n casper_env::{self, emit},\n\n Address, Error, Mapping,\n\n};\n\nuse casper_types::U256;\n\n\n\n/// The TokenWithStaking module.\n\n#[derive(Instance)]\n\npub struct TokenWithStaking {\n\n pub stakes: Mapping<Address, U256>,\n\n pub token: Token,\n\n}\n\n\n\nimpl TokenWithStaking {\n\n /// Mint new tokens. See [`Token::mint`](Token::mint).\n", "file_path": "dao-modules/src/staking.rs", "rank": 50, "score": 4.323213757563448 }, { "content": " #sig {\n\n casper_dao_utils::casper_contract::contract_api::runtime::call_versioned_contract(\n\n self.contract_package_hash,\n\n std::option::Option::None,\n\n stringify!(#ident),\n\n #args,\n\n )\n\n }\n\n }\n\n }\n\n }));\n\n stream\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use pretty_assertions::assert_eq;\n\n use quote::quote;\n\n\n\n use crate::contract::utils;\n", "file_path": "dao-macros/src/contract/caller.rs", "rank": 51, "score": 4.315040033795845 }, { "content": "use casper_dao_utils::casper_contract::unwrap_or_revert::UnwrapOrRevert;\n\nuse casper_dao_utils::{casper_dao_macros::Instance, Address};\n\nuse casper_dao_utils::{consts as dao_consts, math};\n\nuse casper_types::bytesrepr::FromBytes;\n\nuse casper_types::U256;\n\n\n\nuse crate::VariableRepositoryContractCaller;\n\n\n\n#[derive(Instance)]\n\npub struct VariableRepoContractProxy {}\n\n\n\nimpl VariableRepoContractProxy {\n\n pub fn informal_voting_time(contract_address: Address) -> u64 {\n\n VariableRepoContractProxy::get_variable(contract_address, dao_consts::INFORMAL_VOTING_TIME)\n\n }\n\n\n\n pub fn formal_voting_time(contract_address: Address) -> u64 {\n\n VariableRepoContractProxy::get_variable(contract_address, dao_consts::FORMAL_VOTING_TIME)\n\n }\n\n\n", "file_path": "dao-contracts/src/proxy/variable_repo_proxy.rs", "rank": 52, "score": 4.273914923490322 }, { "content": " use quote::quote;\n\n\n\n use crate::contract::utils::tests::mock_valid_item;\n\n\n\n use super::generate_code;\n\n\n\n #[test]\n\n fn generating_no_mangles_works() {\n\n let item = mock_valid_item();\n\n let generated = generate_code(&item);\n\n\n\n let expected = quote! {\n\n #[doc = \"Generates a \"]\n\n #[doc = stringify!(Contract)]\n\n #[doc = \" binary with all the required no_mangle functions.\"]\n\n #[macro_export]\n\n macro_rules! contract {\n\n () => {\n\n #[no_mangle]\n\n fn call() {\n", "file_path": "dao-macros/src/contract/contract_bin.rs", "rank": 53, "score": 4.224443169456366 }, { "content": "//! Single-owner-based access control system.\n\n\n\n// use casper_contract::contract_api::runtime;\n\n\n\nuse casper_dao_utils::{\n\n casper_dao_macros::Instance,\n\n casper_env::{self, caller, emit},\n\n Address, Error, Variable,\n\n};\n\n\n\nuse self::events::OwnerChanged;\n\n\n\n/// The Owner module.\n\n#[derive(Instance)]\n\npub struct Owner {\n\n pub owner: Variable<Address>,\n\n}\n\n\n\nimpl Owner {\n\n /// Initialize the module.\n", "file_path": "dao-modules/src/owner.rs", "rank": 54, "score": 4.224443169456366 }, { "content": "use casper_dao_utils::{\n\n casper_contract::unwrap_or_revert::UnwrapOrRevert,\n\n casper_dao_macros::{casper_contract_interface, Instance},\n\n casper_env::{self, caller},\n\n consts, Address, Error, SequenceGenerator,\n\n};\n\nuse casper_types::{runtime_args, RuntimeArgs, U256};\n\n\n\nuse crate::{\n\n voting::{\n\n kyc_info::KycInfo,\n\n onboarding_info::{OnboardingAction, OnboardingInfo},\n\n voting::Voting,\n\n Ballot, Choice, GovernanceVoting, VotingId,\n\n },\n\n ReputationContractCaller,\n\n};\n\nuse delegate::delegate;\n\n\n\n#[casper_contract_interface]\n", "file_path": "dao-contracts/src/onboarding_voter.rs", "rank": 55, "score": 4.2211781445794525 }, { "content": "use casper_dao_modules::{AccessControl, Record, Repository};\n\nuse casper_dao_utils::{\n\n casper_contract::unwrap_or_revert::UnwrapOrRevert,\n\n casper_dao_macros::{casper_contract_interface, Instance},\n\n casper_env::{caller, revert},\n\n consts as dao_consts, math, Address, Error,\n\n};\n\nuse casper_types::{\n\n bytesrepr::{Bytes, FromBytes},\n\n U256,\n\n};\n\nuse delegate::delegate;\n\n\n\n// Interface of the Variable Repository Contract.\n\n//\n\n// It should be implemented by [`VariableRepositoryContract`], [`VariableRepositoryContractCaller`]\n\n// and [`VariableRepositoryContractTest`].\n\n#[casper_contract_interface]\n", "file_path": "dao-contracts/src/variable_repository.rs", "rank": 56, "score": 4.2046386400552365 }, { "content": " public createDeployRemoveFromWhitelist(\n\n address: CLPublicKey,\n\n paymentAmount: string,\n\n keys: Keys.AsymmetricKey = undefined\n\n ) {\n\n const runtimeArgs = RuntimeArgs.fromMap({\n\n address: createRecipientAddress(address),\n\n });\n\n\n\n const deployHash = this.contractClient.callEntrypoint(\n\n \"remove_from_whitelist\",\n\n runtimeArgs,\n\n keys.publicKey,\n\n this.chainName,\n\n paymentAmount,\n\n keys && [keys]\n\n );\n\n\n\n return deployHash;\n", "file_path": "client/src/reputation/client.ts", "rank": 57, "score": 4.19788575909373 }, { "content": " public createDeployAddToWhitelist(\n\n address: CLPublicKey,\n\n paymentAmount: string,\n\n keys: Keys.AsymmetricKey = undefined\n\n ) {\n\n const runtimeArgs = RuntimeArgs.fromMap({\n\n address: createRecipientAddress(address),\n\n });\n\n\n\n const deployHash = this.contractClient.callEntrypoint(\n\n \"add_to_whitelist\",\n\n runtimeArgs,\n\n keys.publicKey,\n\n this.chainName,\n\n paymentAmount,\n\n keys && [keys]\n\n );\n\n\n\n return deployHash;\n", "file_path": "client/src/reputation/client.ts", "rank": 58, "score": 4.19788575909373 }, { "content": " }\n\n }\n\n }\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use quote::quote;\n\n use syn::{\n\n punctuated::Punctuated, token, DataStruct, Field, Fields, FieldsNamed, Token, Type,\n\n VisPublic, Visibility,\n\n };\n\n\n\n use super::parse_data;\n\n\n\n #[test]\n\n fn parsing_struct_data_works() {\n\n let mut fields: Punctuated<Field, Token![,]> = Punctuated::new();\n\n fields.push(create_field(\"b\", syn::parse_quote! { B }));\n", "file_path": "dao-macros/src/instance.rs", "rank": 59, "score": 4.1375723461038865 }, { "content": " public createDeployChangeOwnership(\n\n owner: CLPublicKey,\n\n paymentAmount: string,\n\n keys: Keys.AsymmetricKey = undefined\n\n ) {\n\n const runtimeArgs = RuntimeArgs.fromMap({\n\n owner: createRecipientAddress(owner),\n\n });\n\n\n\n const deployHash = this.contractClient.callEntrypoint(\n\n \"change_ownership\",\n\n runtimeArgs,\n\n keys.publicKey,\n\n this.chainName,\n\n paymentAmount,\n\n keys && [keys]\n\n );\n\n\n\n return deployHash;\n", "file_path": "client/src/reputation/client.ts", "rank": 60, "score": 4.133210486672342 }, { "content": "#![allow(dead_code)]\n\n#![allow(unused_variables)]\n\n\n\nuse casper_dao_utils::casper_dao_macros::casper_contract_interface;\n\nuse casper_dao_utils::casper_dao_macros::Instance;\n\n\n\n#[casper_contract_interface]\n", "file_path": "dao-macros/sample-contract/src/contract.rs", "rank": 61, "score": 4.133210486672342 }, { "content": "//! Token module with balances and total supply.\n\n\n\nuse casper_types::U256;\n\n\n\nuse self::events::{Burn, Mint, Transfer};\n\nuse casper_dao_utils::{\n\n casper_dao_macros::Instance,\n\n casper_env::{self, emit},\n\n Address, Error, Mapping, Variable,\n\n};\n\n\n\n/// The Token module.\n\n#[derive(Instance)]\n\npub struct Token {\n\n pub total_supply: Variable<U256>,\n\n pub balances: Mapping<Address, U256>,\n\n}\n\n\n\nimpl Token {\n\n /// Mint new tokens.\n", "file_path": "dao-modules/src/token.rs", "rank": 62, "score": 4.116410034609885 }, { "content": "use casper_dao_utils::{\n\n casper_dao_macros::{CLTyped, FromBytes, ToBytes},\n\n Address,\n\n};\n\nuse casper_types::U256;\n\n\n\n/// Id of a Voting\n\npub type VotingId = U256;\n\n\n\n/// Choice enum, can be converted to bool using `is_in_favor()`\n\n#[derive(Debug, FromBytes, ToBytes, CLTyped, PartialEq, Clone, Copy)]\n\npub enum Choice {\n\n Against,\n\n InFavor,\n\n}\n\n\n\nimpl Default for Choice {\n\n fn default() -> Self {\n\n Self::InFavor\n\n }\n", "file_path": "dao-contracts/src/voting/ballot.rs", "rank": 63, "score": 4.116410034609885 }, { "content": "use std::{\n\n path::PathBuf,\n\n sync::{Arc, Mutex},\n\n time::Duration,\n\n};\n\n\n\nuse crate::{Address, Error};\n\nuse casper_engine_test_support::{\n\n DeployItemBuilder, ExecuteRequestBuilder, InMemoryWasmTestBuilder, ARG_AMOUNT,\n\n DEFAULT_ACCOUNT_INITIAL_BALANCE, DEFAULT_GENESIS_CONFIG, DEFAULT_GENESIS_CONFIG_HASH,\n\n DEFAULT_PAYMENT,\n\n};\n\nuse casper_execution_engine::core::engine_state::{\n\n self, run_genesis_request::RunGenesisRequest, GenesisAccount,\n\n};\n\nuse casper_types::{\n\n account::AccountHash,\n\n bytesrepr::{self, Bytes, FromBytes, ToBytes},\n\n runtime_args, ApiError, CLTyped, ContractPackageHash, Key, Motes, PublicKey, RuntimeArgs,\n\n SecretKey, URef, U512,\n", "file_path": "dao-utils/src/test_env.rs", "rank": 64, "score": 4.115656886413235 }, { "content": "mod caller;\n\nmod contract_bin;\n\nmod contract_struct;\n\nmod contract_test;\n\nmod generator;\n\nmod parser;\n\nmod utils;\n\npub use generator::generate_code;\n\npub use parser::CasperContractItem;\n", "file_path": "dao-macros/src/contract.rs", "rank": 65, "score": 4.101614458611838 }, { "content": "//! Voting struct with logic for governance voting\n\nuse crate::voting::ballot::{Choice, VotingId};\n\nuse casper_dao_utils::{\n\n casper_dao_macros::{CLTyped, FromBytes, ToBytes},\n\n Address,\n\n};\n\nuse casper_types::{RuntimeArgs, U256};\n\n\n\n/// Result of a Voting\n\n#[derive(PartialEq)]\n\npub enum VotingResult {\n\n InFavor,\n\n Against,\n\n QuorumNotReached,\n\n}\n\n\n\n/// Type of Voting (Formal or Informal)\n\npub enum VotingType {\n\n Informal,\n\n Formal,\n", "file_path": "dao-contracts/src/voting/governance_voting/voting.rs", "rank": 66, "score": 4.095463097966476 }, { "content": "use casper_dao_contracts::{\n\n action::Action,\n\n voting::{voting::Voting, Choice, VotingId},\n\n AdminContractTest, MockVoterContractTest, RepoVoterContractTest, ReputationContractTest,\n\n VariableRepositoryContractTest,\n\n};\n\n\n\nuse casper_dao_utils::{consts, Error, TestContract, TestEnv};\n\nuse casper_types::{\n\n bytesrepr::{Bytes, ToBytes},\n\n U256,\n\n};\n\n\n\n#[allow(dead_code)]\n", "file_path": "dao-contracts/tests/governance_voting_common.rs", "rank": 67, "score": 4.095463097966476 }, { "content": "use std::time::Duration;\n\n\n\nuse casper_dao_contracts::VariableRepositoryContractTest;\n\nuse casper_dao_modules::{events::ValueUpdated, RepositoryDefaults};\n\nuse casper_dao_utils::{consts, BytesConversion, Error, TestContract, TestEnv};\n\nuse casper_types::{bytesrepr::Bytes, U256};\n\n\n\nstatic KEY: &str = \"key\";\n\nstatic KEY_2: &str = \"key_2\";\n\nstatic KEY_3: &str = \"key_3\";\n\nstatic VALUE: u32 = 1;\n\nstatic VALUE_2: u32 = 2;\n\nstatic VALUE_3: u32 = 3;\n\n\n\n// Moments in time for interaction with activision_time param.\n\nstatic AT_DAY_ONE: u64 = 60 * 60 * 24;\n\nstatic AT_DAY_TWO: u64 = 2 * AT_DAY_ONE;\n\nstatic AT_DAY_THREE: u64 = 3 * AT_DAY_ONE;\n\n\n\n// Durations for moving time.\n\nstatic TWO_DAYS: Duration = Duration::from_secs(AT_DAY_TWO);\n\n\n", "file_path": "dao-contracts/tests/test_variable_repository.rs", "rank": 68, "score": 4.078118946995712 }, { "content": " }\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::contract::{\n\n contract_struct::{generate_entry_points, generate_install},\n\n utils,\n\n };\n\n use pretty_assertions::assert_eq;\n\n use quote::quote;\n\n\n\n #[test]\n\n fn generating_install_without_init_method_fails() {\n\n let valid_item = utils::tests::mock_item_without_init();\n\n let result = generate_install(&valid_item)\n\n .map_err(|err| err.to_string())\n\n .unwrap_err();\n", "file_path": "dao-macros/src/contract/contract_struct.rs", "rank": 69, "score": 4.074728264923407 }, { "content": "}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use quote::quote;\n\n use syn::parse_quote;\n\n\n\n use crate::contract::{contract_test::build_constructor, utils, CasperContractItem};\n\n\n\n #[test]\n\n fn generating_test_contract_constructor_works() {\n\n let item = CasperContractItem {\n\n trait_methods: vec![\n\n parse_quote! { fn do_something(&mut self, amount: U256); },\n\n parse_quote! { fn init(&mut self); },\n\n ],\n\n ..utils::tests::mock_valid_item()\n\n };\n\n\n\n let expected = quote! {\n", "file_path": "dao-macros/src/contract/contract_test.rs", "rank": 70, "score": 4.0338821525557025 }, { "content": "use casper_dao_utils::{\n\n casper_dao_macros::Instance,\n\n casper_env::{self, emit, get_block_time},\n\n consts, Error, Mapping, OrderedCollection, Set,\n\n};\n\n\n\nuse casper_types::{\n\n bytesrepr::{Bytes, ToBytes},\n\n U256,\n\n};\n\n\n\nuse self::events::ValueUpdated;\n\n\n\n/// A data struct stored in the repository.\n\n///\n\n/// The first value represents the current value.\n\n///\n\n/// The second value is an optional tuple consisting of the future value and its activation time.\n\npub type Record = (Bytes, Option<(Bytes, u64)>);\n\n\n", "file_path": "dao-modules/src/repository.rs", "rank": 71, "score": 4.013764653742885 }, { "content": "}\n\n\n\npub mod interface {\n\n use super::CasperContractItem;\n\n use proc_macro2::TokenStream;\n\n use quote::{quote, TokenStreamExt};\n\n\n\n pub fn generate_code(model: &CasperContractItem) -> TokenStream {\n\n let id = &model.ident;\n\n let contract_name = &model.contract_name();\n\n\n\n let mut methods = TokenStream::new();\n\n methods.append_all(&model.trait_methods);\n\n\n\n quote! {\n\n #[doc = \"Defines the \"]\n\n #[doc = #contract_name]\n\n #[doc = \" contract's public interface.\"]\n\n pub trait #id {\n\n #methods\n", "file_path": "dao-macros/src/contract/contract_struct.rs", "rank": 72, "score": 3.993846816396909 }, { "content": " public createDeployMint(\n\n recipient: CLPublicKey,\n\n amount: string,\n\n paymentAmount: string,\n\n keys: Keys.AsymmetricKey = undefined\n\n ) {\n\n const runtimeArgs = RuntimeArgs.fromMap({\n\n recipient: createRecipientAddress(recipient),\n\n amount: CLValueBuilder.u256(amount),\n\n });\n\n\n\n const deployHash = this.contractClient.callEntrypoint(\n\n \"mint\",\n\n runtimeArgs,\n\n keys.publicKey,\n\n this.chainName,\n\n paymentAmount,\n\n [keys]\n\n );\n\n\n\n return deployHash;\n", "file_path": "client/src/reputation/client.ts", "rank": 73, "score": 3.97991768910171 }, { "content": " public createDeployUnstake(\n\n address: CLPublicKey,\n\n amount: string,\n\n paymentAmount: string,\n\n keys: Keys.AsymmetricKey = undefined\n\n ) {\n\n const runtimeArgs = RuntimeArgs.fromMap({\n\n address: createRecipientAddress(address),\n\n amount: CLValueBuilder.u256(amount),\n\n });\n\n\n\n const deploy = this.contractClient.callEntrypoint(\n\n \"unstake\",\n\n runtimeArgs,\n\n keys.publicKey,\n\n this.chainName,\n\n paymentAmount,\n\n keys && [keys]\n\n );\n\n\n\n return deploy;\n", "file_path": "client/src/reputation/client.ts", "rank": 74, "score": 3.97991768910171 }, { "content": " public createDeployStake(\n\n address: CLPublicKey,\n\n amount: string,\n\n paymentAmount: string,\n\n keys: Keys.AsymmetricKey = undefined\n\n ) {\n\n const runtimeArgs = RuntimeArgs.fromMap({\n\n address: createRecipientAddress(address),\n\n amount: CLValueBuilder.u256(amount),\n\n });\n\n\n\n const deployHash = this.contractClient.callEntrypoint(\n\n \"stake\",\n\n runtimeArgs,\n\n keys.publicKey,\n\n this.chainName,\n\n paymentAmount,\n\n keys && [keys]\n\n );\n\n\n\n return deployHash;\n", "file_path": "client/src/reputation/client.ts", "rank": 75, "score": 3.97991768910171 }, { "content": " public createDeployBurn(\n\n owner: CLPublicKey,\n\n amount: string,\n\n paymentAmount: string,\n\n keys: Keys.AsymmetricKey = undefined\n\n ) {\n\n const runtimeArgs = RuntimeArgs.fromMap({\n\n owner: createRecipientAddress(owner),\n\n amount: CLValueBuilder.u256(amount),\n\n });\n\n\n\n const deployHash = this.contractClient.callEntrypoint(\n\n \"burn\",\n\n runtimeArgs,\n\n keys.publicKey,\n\n this.chainName,\n\n paymentAmount,\n\n keys && [keys]\n\n );\n\n\n\n return deployHash;\n", "file_path": "client/src/reputation/client.ts", "rank": 76, "score": 3.97991768910171 }, { "content": "use casper_contract::unwrap_or_revert::UnwrapOrRevert;\n\nuse casper_types::bytesrepr::{Bytes, ToBytes};\n\n\n\nuse crate::{consts, List, OrderedCollection};\n\n\n\npub struct Events {\n\n pub events: OrderedCollection<Bytes>,\n\n}\n\n\n\nimpl Default for Events {\n\n fn default() -> Self {\n\n Self {\n\n events: OrderedCollection::new(consts::NAME_EVENTS),\n\n }\n\n }\n\n}\n\n\n\nimpl Events {\n\n pub fn emit<T: ToBytes>(&mut self, event: T) {\n\n let bytes: Bytes = event.to_bytes().unwrap_or_revert().into();\n\n self.events.add(bytes);\n\n }\n\n}\n", "file_path": "dao-utils/src/events.rs", "rank": 77, "score": 3.974125682805092 }, { "content": "mod governance_voting_common;\n\n\n\nuse speculate::speculate;\n\n\n\nuse casper_dao_contracts::{voting::Choice, voting::VotingId};\n\n\n\nuse casper_dao_utils::{BytesConversion, TestContract};\n\nuse casper_types::{bytesrepr::FromBytes, U256};\n\n\n\nspeculate! {\n\n context \"repo_voter\" {\n\n before {\n\n let (mut repo_voter_contract, variable_repo_contract) = governance_voting_common::setup_repo_voter(\"variable_name\".into(), U256::from(123).convert_to_bytes().unwrap());\n\n let voting_id = VotingId::one();\n\n let voting = repo_voter_contract.get_voting(voting_id).unwrap();\n\n repo_voter_contract\n\n .as_nth_account(1)\n\n .vote(voting.voting_id(), Choice::InFavor, 1000.into())\n\n .unwrap();\n\n }\n", "file_path": "dao-contracts/tests/test_repo_voter.rs", "rank": 78, "score": 3.956593764516451 }, { "content": "mod contract;\n\n\n\npub use contract::{ImportantContract, ImportantContractInterface};\n", "file_path": "dao-macros/sample-contract/src/lib.rs", "rank": 79, "score": 3.938707229437521 }, { "content": "mod governance_voting_common;\n\n\n\nuse speculate::speculate;\n\n\n\nuse casper_dao_contracts::voting::{Choice, VotingId};\n\nuse casper_dao_utils::{Error, TestContract};\n\nuse casper_types::U256;\n\n\n\nspeculate! {\n\n describe \"admin with voting set up for adding an address to a whitelist\" {\n\n before {\n\n #[allow(unused_mut)]\n\n let (mut admin_contract, mut reputation_token_contract) = governance_voting_common::setup_admin();\n\n #[allow(unused_variables)]\n\n let voting = admin_contract.get_voting(VotingId::from(1)).unwrap();\n\n }\n\n\n\n test \"address cannot perform action before voting finishes\" {\n\n assert_eq!(\n\n reputation_token_contract.as_nth_account(1).mint(admin_contract.get_env().get_account(1), U256::from(500)),\n", "file_path": "dao-contracts/tests/test_admin.rs", "rank": 80, "score": 3.92763085031534 }, { "content": "\n\npub mod events {\n\n use casper_dao_utils::casper_dao_macros::Event;\n\n use casper_types::bytesrepr::Bytes;\n\n\n\n #[derive(Debug, PartialEq, Event)]\n\n pub struct ValueUpdated {\n\n pub key: String,\n\n pub value: Bytes,\n\n pub activation_time: Option<u64>,\n\n }\n\n}\n", "file_path": "dao-modules/src/repository.rs", "rank": 81, "score": 3.8932811207507987 }, { "content": "use casper_dao_utils::{\n\n casper_contract::unwrap_or_revert::UnwrapOrRevert,\n\n casper_dao_macros::Instance,\n\n casper_env::{self, emit},\n\n Address, Error, Mapping, Variable,\n\n};\n\nuse casper_types::{bytesrepr::Bytes, U256};\n\n\n\nuse crate::{\n\n events::{Approval, ApprovalForAll, Transfer},\n\n receiver::{ERC721ReceiverCaller, IERC721Receiver},\n\n TokenId,\n\n};\n\n\n\n#[derive(Instance)]\n\npub struct ERC721Token {\n\n total_supply: Variable<U256>,\n\n // Mapping owner address to token count\n\n balances: Mapping<Address, U256>,\n\n // Mapping from token ID to owner address\n", "file_path": "dao-erc721/src/core.rs", "rank": 82, "score": 3.8050268139423373 }, { "content": " public createDeployTransferFrom(\n\n owner: CLPublicKey,\n\n recipient: CLPublicKey,\n\n transferAmount: string,\n\n paymentAmount: string,\n\n keys: Keys.AsymmetricKey = undefined\n\n ) {\n\n const runtimeArgs = RuntimeArgs.fromMap({\n\n owner: createRecipientAddress(owner),\n\n recipient: createRecipientAddress(recipient),\n\n amount: CLValueBuilder.u256(transferAmount),\n\n });\n\n\n\n const deployHash = this.contractClient.callEntrypoint(\n\n \"transfer_from\",\n\n runtimeArgs,\n\n keys.publicKey,\n\n this.chainName,\n\n paymentAmount,\n\n keys && [keys]\n\n );\n\n\n\n return deployHash;\n", "file_path": "client/src/reputation/client.ts", "rank": 83, "score": 3.783467577527204 }, { "content": "#![no_main]\n\n\n\nuse sample_contract::{ImportantContract, ImportantContractInterface};\n\n\n\nsample_contract::important_contract!();\n", "file_path": "dao-macros/sample-contract/src/casper_contract.rs", "rank": 84, "score": 3.772546025456798 }, { "content": "#[allow(unused_variables)]\n\nmod test {\n\n extern crate speculate;\n\n use speculate::speculate;\n\n\n\n use casper_dao_erc721::{\n\n events::{Approval, ApprovalForAll, Transfer},\n\n ERC721Test, MockERC721NonReceiverTest, MockERC721ReceiverTest, Received, TokenId,\n\n };\n\n use casper_dao_utils::{Address, BytesConversion, Error, TestContract, TestEnv};\n\n\n\n speculate! {\n\n static NAME: &str = \"Plascoin\";\n\n static SYMBOL: &str = \"PLS\";\n\n static BASE_URI: &str = \"some://base/uri\";\n\n\n\n context \"erc721\" {\n\n\n\n before {\n\n let env = TestEnv::new();\n", "file_path": "dao-erc721/tests/test_erc721_spec.rs", "rank": 85, "score": 3.7693852202974965 }, { "content": "mod governance_voting_common;\n\nuse casper_dao_contracts::voting::{consts, VotingEnded};\n\nuse casper_dao_utils::TestContract;\n\nuse casper_types::U256;\n\nuse test_case::test_case;\n\n\n\n#[test_case(0, 0, 4, U256::from(500), consts::INFORMAL_VOTING_QUORUM_NOT_REACHED, &[9500, 0, 0]; \"Nobody votes\")]\n\n#[test_case(1, 1, 4, U256::from(500), consts::INFORMAL_VOTING_PASSED, &[9500, 10000, 10000, 500, 0]; \"Exact number of votes, tie\")]\n\n#[test_case(2, 0, 4, U256::from(500), consts::INFORMAL_VOTING_PASSED, &[9500, 10000, 500, 0]; \"Exact number of votes in favor\")]\n\n#[test_case(0, 2, 4, U256::from(500), consts::INFORMAL_VOTING_REJECTED, &[9500, 10000, 10000, 0, 0]; \"Exact number of votes againts\")]\n\n#[test_case(2, 2, 10, U256::from(500), consts::INFORMAL_VOTING_QUORUM_NOT_REACHED, &[9500, 10000, 10000, 10000, 0, 0]; \"One vote less than quorum\")]\n\n#[test_case(2, 3, 10, U256::from(500), consts::INFORMAL_VOTING_REJECTED, &[9500, 10000, 10000, 10000, 10000, 0, 0]; \"Exact number of votes - 10 onboarded\")]\n\n#[test_case(10, 0, 10, U256::from(500), consts::INFORMAL_VOTING_PASSED, &[9500, 10000, 500, 0]; \"Everybody votes in favor - 10 onboarded\")]\n", "file_path": "dao-contracts/tests/test_governance_results.rs", "rank": 86, "score": 3.723221422000579 }, { "content": "use casper_dao_utils::{casper_dao_macros::Event, Address};\n\nuse casper_types::U256;\n\n\n\nuse crate::voting::ballot::{Choice, VotingId};\n\n\n\n/// Event thrown after voting contract is created\n\n#[derive(Debug, PartialEq, Event)]\n\npub struct VotingContractCreated {\n\n pub voter_contract: Address,\n\n pub variable_repo: Address,\n\n pub reputation_token: Address,\n\n}\n\n\n\n/// Event thrown after ballot is cast\n\n#[derive(Debug, PartialEq, Event)]\n\npub struct BallotCast {\n\n pub voter: Address,\n\n pub voting_id: VotingId,\n\n pub choice: Choice,\n\n pub stake: U256,\n", "file_path": "dao-contracts/src/voting/governance_voting/events.rs", "rank": 87, "score": 3.70006832032303 }, { "content": "use casper_dao_utils::{casper_dao_macros::Instance, Address};\n\n\n\nuse crate::{Owner, Whitelist};\n\n\n\n/// The Access control module.\n\n///\n\n/// Aggregates the typical applications of [`Owner`] and [`Whitelist`] modules.\n\n#[derive(Instance)]\n\npub struct AccessControl {\n\n pub owner: Owner,\n\n pub whitelist: Whitelist,\n\n}\n\n\n\nimpl AccessControl {\n\n /// Module constructor.\n\n ///\n\n /// Initializes submodules.\n\n ///\n\n /// See [`Owner`] and [`Whitelist`].\n\n pub fn init(&mut self, address: Address) {\n", "file_path": "dao-modules/src/access_control.rs", "rank": 88, "score": 3.605498906371518 }, { "content": "#[cfg(test)]\n\npub mod tests {\n\n use quote::format_ident;\n\n use syn::parse_quote;\n\n\n\n use crate::contract::parser::CasperContractItem;\n\n\n\n pub fn mock_valid_item() -> CasperContractItem {\n\n CasperContractItem {\n\n trait_token: Default::default(),\n\n ident: format_ident!(\"{}\", \"ContractTrait\"),\n\n trait_methods: vec![\n\n parse_quote! { fn init(&mut self); },\n\n parse_quote! { fn do_something(&mut self, amount: U256); },\n\n ],\n\n caller_ident: format_ident!(\"{}\", \"ContractCaller\"),\n\n contract_ident: format_ident!(\"{}\", \"Contract\"),\n\n contract_test_ident: format_ident!(\"{}\", \"ContractTest\"),\n\n package_hash: \"contract\".to_string(),\n\n wasm_file_name: \"contract_wasm\".to_string(),\n", "file_path": "dao-macros/src/contract/utils.rs", "rank": 89, "score": 3.553056179825317 }, { "content": "use crate::{DaoOwnedNftContractCaller, DaoOwnedNftContractInterface};\n\nuse casper_dao_erc721::TokenId;\n\nuse casper_dao_utils::{\n\n casper_contract::unwrap_or_revert::UnwrapOrRevert,\n\n casper_dao_macros::{CLTyped, FromBytes, Instance, ToBytes},\n\n Address, Error, Mapping, Variable,\n\n};\n\n\n\n/// A utility module that provides information about the current status of the onboarding process.\n\n#[derive(Instance)]\n\npub struct OnboardingInfo {\n\n va_token: Variable<Address>,\n\n votings: Mapping<Address, bool>,\n\n}\n\n\n\nimpl OnboardingInfo {\n\n /// Initializes `va_token` contract address.\n\n pub fn init(&mut self, va_token: Address) {\n\n self.va_token.set(va_token);\n\n }\n", "file_path": "dao-contracts/src/voting/onboarding_info.rs", "rank": 90, "score": 3.553056179825317 }, { "content": "pub mod events {\n\n //! Events definitions.\n\n use casper_dao_utils::{casper_dao_macros::Event, Address};\n\n use casper_types::U256;\n\n\n\n /// Informs tokens have been staked.\n\n #[derive(Debug, PartialEq, Event)]\n\n pub struct TokensStaked {\n\n pub address: Address,\n\n pub amount: U256,\n\n }\n\n\n\n /// Informs tokens have been unstaked.\n\n #[derive(Debug, PartialEq, Event)]\n\n pub struct TokensUnstaked {\n\n pub address: Address,\n\n pub amount: U256,\n\n }\n\n}\n", "file_path": "dao-modules/src/staking.rs", "rank": 91, "score": 3.465763743475777 }, { "content": "//! Whitelist-based access control system.\n\n\n\nuse casper_dao_utils::{\n\n casper_dao_macros::Instance,\n\n casper_env::{self, caller, emit},\n\n Address, Error, Mapping,\n\n};\n\n\n\nuse self::events::{AddedToWhitelist, RemovedFromWhitelist};\n\n\n\n/// The Whitelist module.\n\n#[derive(Instance)]\n\npub struct Whitelist {\n\n pub whitelist: Mapping<Address, bool>,\n\n}\n\n\n\nimpl Whitelist {\n\n /// Add new `address` to the whitelist.\n\n pub fn add_to_whitelist(&mut self, address: Address) {\n\n self.whitelist.set(&address, true);\n", "file_path": "dao-modules/src/whitelist.rs", "rank": 92, "score": 3.465763743475777 }, { "content": "//! A selection of contracts implemented for usage in DAO\n\n\n\n#[doc(hidden)]\n\npub mod action;\n\nmod admin;\n\nmod dao_nft;\n\nmod kyc_voter;\n\n#[doc(hidden)]\n\npub mod mocks;\n\nmod onboarding_voter;\n\nmod repo_voter;\n\nmod reputation;\n\n/// Variable Repo\n\nmod variable_repository;\n\n/// Utilities to manage the voting process\n\npub mod voting;\n\n\n\npub use admin::{AdminContract, AdminContractCaller, AdminContractInterface};\n\npub use dao_nft::{DaoOwnedNftContract, DaoOwnedNftContractCaller, DaoOwnedNftContractInterface};\n\npub use kyc_voter::{KycVoterContract, KycVoterContractCaller, KycVoterContractInterface};\n", "file_path": "dao-contracts/src/lib.rs", "rank": 93, "score": 3.461370751489194 }, { "content": "};\n\n\n\nuse blake2::{\n\n digest::{Update, VariableOutput},\n\n VarBlake2b,\n\n};\n\n\n\npub use casper_execution_engine::core::execution::Error as ExecutionError;\n\n\n\n/// CasperVM based testing environment.\n\n#[derive(Clone)]\n\npub struct TestEnv {\n\n state: Arc<Mutex<TestEnvState>>,\n\n}\n\n\n\nimpl TestEnv {\n\n /// Create new TestEnv.\n\n pub fn new() -> TestEnv {\n\n TestEnv {\n\n state: Arc::new(Mutex::new(TestEnvState::new())),\n", "file_path": "dao-utils/src/test_env.rs", "rank": 94, "score": 3.3784727377810415 }, { "content": "use casper_dao_utils::{casper_dao_macros::Instance, Address};\n\nuse casper_types::U256;\n\n\n\nuse crate::{ReputationContractCaller, ReputationContractInterface};\n\n\n\n#[derive(Instance)]\n\npub struct ReputationContractProxy {}\n\n\n\nimpl ReputationContractProxy {\n\n pub fn balance_of(contract_address: Address, address: &Address) -> U256 {\n\n ReputationContractProxy::caller(contract_address).balance_of(*address)\n\n }\n\n\n\n pub fn has_reputation(contract_address: Address, address: &Address) -> bool {\n\n ReputationContractProxy::balance_of(contract_address, address) > U256::zero()\n\n }\n\n\n\n pub fn total_onboarded(contract_address: Address) -> U256 {\n\n ReputationContractProxy::caller(contract_address).total_onboarded()\n\n }\n\n\n\n fn caller(contract_address: Address) -> ReputationContractCaller {\n\n ReputationContractCaller::at(contract_address)\n\n }\n\n}\n", "file_path": "dao-contracts/src/proxy/reputation_proxy.rs", "rank": 95, "score": 3.3742981153193825 }, { "content": "/// Returns address based on a [`CallStackElement`].\n\n///\n\n/// For `Session` and `StoredSession` variants it will return account hash, and for `StoredContract`\n\n/// case it will use contract hash as the address.\n\nfn call_stack_element_to_address(call_stack_element: CallStackElement) -> Address {\n\n match call_stack_element {\n\n CallStackElement::Session { account_hash } => Address::from(account_hash),\n\n CallStackElement::StoredSession { account_hash, .. } => {\n\n // Stored session code acts in account's context, so if stored session\n\n // wants to interact, caller's address will be used.\n\n Address::from(account_hash)\n\n }\n\n CallStackElement::StoredContract {\n\n contract_package_hash,\n\n ..\n\n } => Address::from(contract_package_hash),\n\n }\n\n}\n\n\n", "file_path": "dao-utils/src/casper_env.rs", "rank": 96, "score": 3.3487300490398266 }, { "content": "use casper_types::U256;\n\n\n\nuse crate::{instance::Instanced, Variable};\n\n\n\npub struct SequenceGenerator {\n\n value: Variable<U256>,\n\n}\n\n\n\nimpl SequenceGenerator {\n\n pub fn get_current_value(&self) -> U256 {\n\n self.value.get().unwrap_or_default()\n\n }\n\n\n\n pub fn next_value(&mut self) -> U256 {\n\n let next = self.get_current_value() + U256::one();\n\n self.value.set(next);\n\n next\n\n }\n\n}\n\n\n\nimpl Instanced for SequenceGenerator {\n\n fn instance(namespace: &str) -> Self {\n\n Self {\n\n value: Instanced::instance(format!(\"{}_{}\", \"value\", namespace).as_str()),\n\n }\n\n }\n\n}\n", "file_path": "dao-utils/src/parts/sequence.rs", "rank": 97, "score": 3.3364556542359782 }, { "content": " self.balances.get(address).unwrap_or_default()\n\n }\n\n}\n\n\n\npub mod events {\n\n use casper_dao_utils::{casper_dao_macros::Event, Address};\n\n use casper_types::U256;\n\n\n\n #[derive(Debug, PartialEq, Event)]\n\n pub struct Transfer {\n\n pub from: Address,\n\n pub to: Address,\n\n pub value: U256,\n\n }\n\n\n\n #[derive(Debug, PartialEq, Event)]\n\n pub struct Mint {\n\n pub recipient: Address,\n\n pub value: U256,\n\n }\n\n\n\n #[derive(Debug, PartialEq, Event)]\n\n pub struct Burn {\n\n pub owner: Address,\n\n pub value: U256,\n\n }\n\n}\n", "file_path": "dao-modules/src/token.rs", "rank": 98, "score": 3.2753537207853074 }, { "content": "use casper_dao_utils::{\n\n casper_env::{self, emit},\n\n Address, Error,\n\n};\n\n\n\nuse crate::{core::ERC721Token, events::Transfer, TokenId};\n\n\n\npub struct MintableERC721 {}\n\n\n\nimpl MintableERC721 {\n\n pub fn mint(erc721: &mut ERC721Token, to: Address, token_id: TokenId) {\n\n if erc721.exists(&token_id) {\n\n casper_env::revert(Error::TokenAlreadyExists)\n\n }\n\n\n\n erc721.increment_balance(to);\n\n erc721.increment_total_supply();\n\n erc721.set_owner_of(token_id, Some(to));\n\n\n\n emit(Transfer {\n\n from: None,\n\n to: Some(to),\n\n token_id,\n\n });\n\n }\n\n}\n", "file_path": "dao-erc721/src/extensions/mintable.rs", "rank": 99, "score": 3.235847419454431 } ]
Rust
rusoto/credential/src/container.rs
svenwb/rusoto
e7a7f7c123266d82ff5a97b757d328523ff8a3e2
use std::time::Duration; use async_trait::async_trait; use hyper::{Body, Request}; use crate::request::HttpClient; use crate::{ non_empty_env_var, parse_credentials_from_aws_service, AwsCredentials, CredentialsError, ProvideAwsCredentials, }; const AWS_CREDENTIALS_PROVIDER_IP: &str = "169.254.170.2"; const AWS_CONTAINER_CREDENTIALS_RELATIVE_URI: &str = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; const AWS_CONTAINER_CREDENTIALS_FULL_URI: &str = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; const AWS_CONTAINER_AUTHORIZATION_TOKEN: &str = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; #[derive(Clone, Debug)] pub struct ContainerProvider { client: HttpClient, timeout: Duration, } impl ContainerProvider { pub fn new() -> Self { ContainerProvider { client: HttpClient::new(), timeout: Duration::from_secs(30), } } pub fn set_timeout(&mut self, timeout: Duration) { self.timeout = timeout; } } impl Default for ContainerProvider { fn default() -> Self { Self::new() } } #[async_trait] impl ProvideAwsCredentials for ContainerProvider { async fn credentials(&self) -> Result<AwsCredentials, CredentialsError> { let req = request_from_env_vars().map_err(|err| CredentialsError { message: format!( "Could not get request from environment: {}", err.to_string() ), })?; let resp = self .client .request(req, self.timeout) .await .map_err(|err| CredentialsError { message: format!( "Could not get credentials from container: {}", err.to_string() ), })?; parse_credentials_from_aws_service(&resp) } } fn request_from_env_vars() -> Result<Request<Body>, CredentialsError> { let relative_uri = non_empty_env_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) .map(|path| format!("http://{}{}", AWS_CREDENTIALS_PROVIDER_IP, path)); match relative_uri { Some(ref uri) => new_request(uri, AWS_CONTAINER_CREDENTIALS_RELATIVE_URI), None => match non_empty_env_var(AWS_CONTAINER_CREDENTIALS_FULL_URI) { Some(ref uri) => { let mut request = new_request(uri, AWS_CONTAINER_CREDENTIALS_FULL_URI)?; if let Some(token) = non_empty_env_var(AWS_CONTAINER_AUTHORIZATION_TOKEN) { match token.parse() { Ok(parsed_token) => { request.headers_mut().insert("authorization", parsed_token); } Err(err) => { return Err(CredentialsError::new(format!( "failed to parse token: {}", err ))); } } } Ok(request) } None => Err(CredentialsError::new(format!( "Neither environment variable '{}' nor '{}' is set", AWS_CONTAINER_CREDENTIALS_FULL_URI, AWS_CONTAINER_CREDENTIALS_RELATIVE_URI ))), }, } } fn new_request(uri: &str, env_var_name: &str) -> Result<Request<Body>, CredentialsError> { Request::get(uri).body(Body::empty()).map_err(|error| { CredentialsError::new(format!( "Error while parsing URI '{}' derived from environment variable '{}': {}", uri, env_var_name, error )) }) } #[cfg(test)] mod tests { use super::*; use crate::test_utils::lock_env; use std::env; #[test] fn request_from_relative_uri() { let path = "/xxx"; let _guard = lock_env(); env::set_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, path); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, "dummy"); env::set_var(AWS_CONTAINER_AUTHORIZATION_TOKEN, "dummy"); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); assert!(result.is_ok()); let request = result.ok().unwrap(); assert_eq!(request.uri().path(), path); assert_eq!(request.headers().contains_key("authorization"), false); } #[test] fn error_from_missing_env_vars() { let _guard = lock_env(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); let result = request_from_env_vars(); assert!(result.is_err()); } #[test] fn error_from_empty_env_vars() { let _guard = lock_env(); env::set_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, ""); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, ""); env::set_var(AWS_CONTAINER_AUTHORIZATION_TOKEN, ""); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); assert!(result.is_err()); } #[test] fn request_from_full_uri_with_token() { let url = "http://localhost/xxx"; let _guard = lock_env(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, url); env::set_var(AWS_CONTAINER_AUTHORIZATION_TOKEN, "dummy"); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); assert!(result.is_ok()); let request = result.ok().unwrap(); assert_eq!(request.uri().to_string(), url); assert_eq!(request.headers().contains_key("authorization"), true); } #[test] fn request_from_full_uri_without_token() { let url = "http://localhost/xxx"; let _guard = lock_env(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, url); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); assert!(result.is_ok()); let request = result.ok().unwrap(); assert_eq!(request.uri().to_string(), url); assert_eq!(request.headers().contains_key("authorization"), false); } #[test] fn request_from_full_uri_with_empty_token() { let url = "http://localhost/xxx"; let _guard = lock_env(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, url); env::set_var(AWS_CONTAINER_AUTHORIZATION_TOKEN, ""); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); assert!(result.is_ok()); let request = result.ok().unwrap(); assert_eq!(request.uri().to_string(), url); assert_eq!(request.headers().contains_key("authorization"), false); } }
use std::time::Duration; use async_trait::async_trait; use hyper::{Body, Request}; use crate::request::HttpClient; use crate::{ non_empty_env_var, parse_credentials_from_aws_service, AwsCredentials, CredentialsError, ProvideAwsCredentials, }; const AWS_CREDENTIALS_PROVIDER_IP: &str = "169.254.170.2"; const AWS_CONTAINER_CREDENTIALS_RELATIVE_URI: &str = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; const AWS_CONTAINER_CREDENTIALS_FULL_URI: &str = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; const AWS_CONTAINER_AUTHORIZATION_TOKEN: &str = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; #[derive(Clone, Debug)] pub struct ContainerProvider { client: HttpClient, timeout: Duration, } impl ContainerProvider { pub fn new() -> Self { ContainerProvider { client: HttpClient::new(), timeout: Duration::from_secs(30), } } pub fn set_timeout(&mut self, timeout: Duration) { self.timeout = timeout; } } impl Default for ContainerProvider { fn default() -> Self { Self::new() } } #[async_trait] impl ProvideAwsCredentials for ContainerProvider { async fn credentials(&self) -> Result<AwsCredentials, CredentialsError> { let req = request_from_env_vars().map_err(|err| CredentialsError { message: format!( "Could not get request from environment: {}", err.to_string() ), })?; let resp = self .client .request(req, self.timeout) .await .map_err(|err| CredentialsError { message: format!( "Could not get credentials from container: {}", err.to_string() ), })?; parse_credentials_from_aws_service(&resp) } } fn request_from_env_vars() -> Result<Request<Body>, CredentialsError> { let relative_uri = non_empty_env_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) .map(|path| format!("http://{}{}", AWS_CREDENTIALS_PROVIDER_IP, path)); match relative_uri { Some(ref uri) => new_request(uri, AWS_CONTAINER_CREDENTIALS_RELATIVE_URI), None => match non_empty_env_var(AWS_CONTAINER_CREDENTIALS_FULL_URI) { Some(ref uri) => { let mut request = new_request(uri, AWS_CONTAINER_CREDENTIALS_FULL_URI)?; if let Some(token) = non_empty_env_var(AWS_CONTAINER_AUTHORIZATION_TOKEN) { match token.pars
fn new_request(uri: &str, env_var_name: &str) -> Result<Request<Body>, CredentialsError> { Request::get(uri).body(Body::empty()).map_err(|error| { CredentialsError::new(format!( "Error while parsing URI '{}' derived from environment variable '{}': {}", uri, env_var_name, error )) }) } #[cfg(test)] mod tests { use super::*; use crate::test_utils::lock_env; use std::env; #[test] fn request_from_relative_uri() { let path = "/xxx"; let _guard = lock_env(); env::set_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, path); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, "dummy"); env::set_var(AWS_CONTAINER_AUTHORIZATION_TOKEN, "dummy"); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); assert!(result.is_ok()); let request = result.ok().unwrap(); assert_eq!(request.uri().path(), path); assert_eq!(request.headers().contains_key("authorization"), false); } #[test] fn error_from_missing_env_vars() { let _guard = lock_env(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); let result = request_from_env_vars(); assert!(result.is_err()); } #[test] fn error_from_empty_env_vars() { let _guard = lock_env(); env::set_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, ""); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, ""); env::set_var(AWS_CONTAINER_AUTHORIZATION_TOKEN, ""); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); assert!(result.is_err()); } #[test] fn request_from_full_uri_with_token() { let url = "http://localhost/xxx"; let _guard = lock_env(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, url); env::set_var(AWS_CONTAINER_AUTHORIZATION_TOKEN, "dummy"); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); assert!(result.is_ok()); let request = result.ok().unwrap(); assert_eq!(request.uri().to_string(), url); assert_eq!(request.headers().contains_key("authorization"), true); } #[test] fn request_from_full_uri_without_token() { let url = "http://localhost/xxx"; let _guard = lock_env(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, url); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); assert!(result.is_ok()); let request = result.ok().unwrap(); assert_eq!(request.uri().to_string(), url); assert_eq!(request.headers().contains_key("authorization"), false); } #[test] fn request_from_full_uri_with_empty_token() { let url = "http://localhost/xxx"; let _guard = lock_env(); env::remove_var(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); env::set_var(AWS_CONTAINER_CREDENTIALS_FULL_URI, url); env::set_var(AWS_CONTAINER_AUTHORIZATION_TOKEN, ""); let result = request_from_env_vars(); env::remove_var(AWS_CONTAINER_CREDENTIALS_FULL_URI); env::remove_var(AWS_CONTAINER_AUTHORIZATION_TOKEN); assert!(result.is_ok()); let request = result.ok().unwrap(); assert_eq!(request.uri().to_string(), url); assert_eq!(request.headers().contains_key("authorization"), false); } }
e() { Ok(parsed_token) => { request.headers_mut().insert("authorization", parsed_token); } Err(err) => { return Err(CredentialsError::new(format!( "failed to parse token: {}", err ))); } } } Ok(request) } None => Err(CredentialsError::new(format!( "Neither environment variable '{}' nor '{}' is set", AWS_CONTAINER_CREDENTIALS_FULL_URI, AWS_CONTAINER_CREDENTIALS_RELATIVE_URI ))), }, } }
function_block-function_prefixed
[ { "content": "#[inline]\n\n#[doc(hidden)]\n\npub fn encode_uri_path(uri: &str) -> String {\n\n utf8_percent_encode(uri, &STRICT_PATH_ENCODE_SET).collect::<String>()\n\n}\n\n\n", "file_path": "rusoto/signature/src/signature.rs", "rank": 1, "score": 339822.9463685929 }, { "content": "#[inline]\n\n#[doc(hidden)]\n\npub fn decode_uri(uri: &str) -> String {\n\n let decoder = percent_decode(uri.as_bytes());\n\n if let Ok(decoded) = decoder.decode_utf8() {\n\n decoded.to_string()\n\n } else {\n\n uri.to_owned()\n\n }\n\n}\n\n\n", "file_path": "rusoto/signature/src/signature.rs", "rank": 2, "score": 292386.26464057557 }, { "content": "pub fn parse_query_string(uri: &str) -> (String, Option<String>) {\n\n // botocore query strings for S3 are variations on \"/{Bucket}/{Key+}?foobar\"\n\n // the query string needs to be split out and put in the params hash,\n\n // and the + isn't useful information for us\n\n let base_uri = uri.replace(\"+\", \"\");\n\n let parts: Vec<&str> = base_uri.split('?').collect();\n\n\n\n match parts.len() {\n\n 1 => (parts[0].to_owned(), None),\n\n 2 => (parts[0].to_owned(), Some(parts[1].to_owned())),\n\n _ => panic!(\"Unknown uri structure {}\", uri),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn uri_snakeification_works() {\n", "file_path": "service_crategen/src/commands/generate/codegen/rest_request_generator.rs", "rank": 4, "score": 265490.857967708 }, { "content": "// TODO: make a macro from this?\n\npub fn get_str_from_attribute(attr: &AttributeValue) -> Option<&str> {\n\n match attr.b {\n\n None => (),\n\n Some(ref blob_attribute) => return Some(str::from_utf8(blob_attribute).unwrap()),\n\n }\n\n\n\n match attr.s {\n\n None => (),\n\n Some(ref string_attribute) => return Some(string_attribute),\n\n }\n\n\n\n match attr.n {\n\n None => (),\n\n Some(ref number_attribute) => return Some(number_attribute),\n\n }\n\n\n\n return None;\n\n}\n", "file_path": "helpers/src/dynamodb.rs", "rank": 5, "score": 262205.52710025886 }, { "content": "// This is a bit messy and could use refactoring.\n\nfn generate_snake_case_uri(request_uri: &str) -> String {\n\n lazy_static! {\n\n static ref URI_ARGS_SNAKE_REGEX: Regex = Regex::new(r\"\\{([\\w\\d]+)\\}\").unwrap();\n\n static ref URI_ARGS_DASH_TO_UNDERSCORE_REGEX: Regex = Regex::new(r\"\\{\\w+\\-\\w+\\}\").unwrap();\n\n }\n\n let mut snake: String = request_uri.to_string().clone();\n\n // convert fooBar to foo_bar\n\n for caps in URI_ARGS_SNAKE_REGEX.captures_iter(request_uri) {\n\n let to_find = caps.get(0).expect(\"nothing captured\").as_str();\n\n // Wrap with curly braces again:\n\n let replacement = format!(\n\n \"{{{}}}\",\n\n Inflector::to_snake_case(caps.get(0).unwrap().as_str())\n\n );\n\n snake = snake.replace(to_find, &replacement);\n\n }\n\n\n\n // convert foo-bar to foo_bar\n\n let temp_snake = snake.clone();\n\n for caps in URI_ARGS_DASH_TO_UNDERSCORE_REGEX.captures_iter(&temp_snake) {\n\n let to_find = caps.get(0).unwrap().as_str();\n\n let replacement = caps.get(0).unwrap().as_str().replace(\"-\", \"_\");\n\n snake = snake.replace(to_find, &replacement);\n\n }\n\n\n\n snake\n\n}\n\n\n", "file_path": "service_crategen/src/commands/generate/codegen/rest_request_generator.rs", "rank": 6, "score": 251827.76472311153 }, { "content": "/// Returns standardised URI\n\nfn canonical_uri(path: &str, region: &Region) -> String {\n\n let endpoint_path = match region {\n\n Region::Custom { ref endpoint, .. } => extract_endpoint_path(endpoint),\n\n _ => None,\n\n };\n\n match (endpoint_path, path) {\n\n (Some(prefix), \"\") => prefix.to_string(),\n\n (None, \"\") => \"/\".to_string(),\n\n (Some(prefix), _) => encode_uri_path(&(prefix.to_owned() + path)),\n\n _ => encode_uri_path(path),\n\n }\n\n}\n\n\n", "file_path": "rusoto/signature/src/signature.rs", "rank": 7, "score": 249538.99502914742 }, { "content": "/// Serialize `GetClusterCredentialsMessage` contents to a `SignedRequest`.\n\nstruct GetClusterCredentialsMessageSerializer;\n\nimpl GetClusterCredentialsMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetClusterCredentialsMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.auto_create {\n\n params.put(&format!(\"{}{}\", prefix, \"AutoCreate\"), &field_value);\n\n }\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"ClusterIdentifier\"),\n\n &obj.cluster_identifier,\n\n );\n\n if let Some(ref field_value) = obj.db_groups {\n\n DbGroupListSerializer::serialize(\n\n params,\n\n &format!(\"{}{}\", prefix, \"DbGroup\"),\n\n field_value,\n", "file_path": "rusoto/services/redshift/src/generated.rs", "rank": 8, "score": 248209.48919151886 }, { "content": "pub fn generate_uri_formatter(\n\n request_uri: &str,\n\n service: &Service<'_>,\n\n operation: &Operation,\n\n) -> Option<String> {\n\n if operation.input.is_some() {\n\n let input_shape = &service.get_shape(operation.input_shape()).unwrap();\n\n let uri_strings = generate_shape_member_uri_strings(input_shape);\n\n\n\n if !uri_strings.is_empty() {\n\n // massage for Route53.\n\n // See https://github.com/rusoto/rusoto/issues/997 .\n\n let replace_em = match service.name().to_ascii_lowercase().as_ref() {\n\n \"route 53\" => {\n\n \".replace(\\\"/hostedzone/hostedzone/\\\", \\\"/hostedzone/\\\").replace(\\\"/hostedzone//hostedzone/\\\", \\\"/hostedzone/\\\").replace(\\\"/change/change/\\\", \\\"/change/\\\")\"\n\n }\n\n _ => \"\"\n\n };\n\n return Some(format!(\n\n \"let request_uri = format!(\\\"{request_uri}\\\", {uri_strings}){replace_if_needed};\",\n", "file_path": "service_crategen/src/commands/generate/codegen/rest_request_generator.rs", "rank": 9, "score": 248165.6754428536 }, { "content": "/// Serialize `RequestEnvironmentInfoMessage` contents to a `SignedRequest`.\n\nstruct RequestEnvironmentInfoMessageSerializer;\n\nimpl RequestEnvironmentInfoMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &RequestEnvironmentInfoMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.environment_id {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentId\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.environment_name {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentName\"), &field_value);\n\n }\n\n params.put(&format!(\"{}{}\", prefix, \"InfoType\"), &obj.info_type);\n\n }\n\n}\n\n\n", "file_path": "rusoto/services/elasticbeanstalk/src/generated.rs", "rank": 10, "score": 248156.5918228408 }, { "content": "/// Serialize `GetDefaultCreditSpecificationRequest` contents to a `SignedRequest`.\n\nstruct GetDefaultCreditSpecificationRequestSerializer;\n\nimpl GetDefaultCreditSpecificationRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetDefaultCreditSpecificationRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.dry_run {\n\n params.put(&format!(\"{}{}\", prefix, \"DryRun\"), &field_value);\n\n }\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"InstanceFamily\"),\n\n &obj.instance_family,\n\n );\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetDefaultCreditSpecificationResult {\n\n /// <p>The default credit option for CPU usage of the instance family.</p>\n\n pub instance_family_credit_specification: Option<InstanceFamilyCreditSpecification>,\n\n}\n\n\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 11, "score": 241978.234515363 }, { "content": "/// Serialize `GetEbsEncryptionByDefaultRequest` contents to a `SignedRequest`.\n\nstruct GetEbsEncryptionByDefaultRequestSerializer;\n\nimpl GetEbsEncryptionByDefaultRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetEbsEncryptionByDefaultRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.dry_run {\n\n params.put(&format!(\"{}{}\", prefix, \"DryRun\"), &field_value);\n\n }\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetEbsEncryptionByDefaultResult {\n\n /// <p>Indicates whether encryption by default is enabled.</p>\n\n pub ebs_encryption_by_default: Option<bool>,\n\n}\n\n\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 12, "score": 241978.234515363 }, { "content": "/// Force an error if we do not see the particular variable name in the env.\n\nfn get_critical_variable(var_name: String) -> Result<String, CredentialsError> {\n\n non_empty_env_var(&var_name)\n\n .ok_or_else(|| CredentialsError::new(format!(\"No (or empty) {} in environment\", var_name)))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::test_utils::lock_env;\n\n use chrono::Utc;\n\n use std::env;\n\n\n\n static AWS_ACCESS_KEY_ID: &str = \"AWS_ACCESS_KEY_ID\";\n\n static AWS_SECRET_ACCESS_KEY: &str = \"AWS_SECRET_ACCESS_KEY\";\n\n static AWS_SESSION_TOKEN: &str = \"AWS_SESSION_TOKEN\";\n\n static AWS_CREDENTIAL_EXPIRATION: &str = \"AWS_CREDENTIAL_EXPIRATION\";\n\n\n\n static E_NO_ACCESS_KEY_ID: &str = \"No (or empty) AWS_ACCESS_KEY_ID in environment\";\n\n static E_NO_SECRET_ACCESS_KEY: &str = \"No (or empty) AWS_SECRET_ACCESS_KEY in environment\";\n\n static E_INVALID_EXPIRATION: &str = \"Invalid AWS_CREDENTIAL_EXPIRATION in environment\";\n", "file_path": "rusoto/credential/src/environment.rs", "rank": 13, "score": 239698.39681616987 }, { "content": "/// Serialize `GetAccessKeyLastUsedRequest` contents to a `SignedRequest`.\n\nstruct GetAccessKeyLastUsedRequestSerializer;\n\nimpl GetAccessKeyLastUsedRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetAccessKeyLastUsedRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(&format!(\"{}{}\", prefix, \"AccessKeyId\"), &obj.access_key_id);\n\n }\n\n}\n\n\n\n/// <p>Contains the response to a successful <a>GetAccessKeyLastUsed</a> request. It is also returned as a member of the <a>AccessKeyMetaData</a> structure returned by the <a>ListAccessKeys</a> action.</p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetAccessKeyLastUsedResponse {\n\n /// <p>Contains information about the last time the access key was used.</p>\n\n pub access_key_last_used: Option<AccessKeyLastUsed>,\n\n /// <p><p>The name of the AWS IAM user that owns this access key.</p> <p/></p>\n\n pub user_name: Option<String>,\n\n}\n\n\n", "file_path": "rusoto/services/iam/src/generated.rs", "rank": 14, "score": 236113.74631900602 }, { "content": "/// Serialize `GetEbsDefaultKmsKeyIdRequest` contents to a `SignedRequest`.\n\nstruct GetEbsDefaultKmsKeyIdRequestSerializer;\n\nimpl GetEbsDefaultKmsKeyIdRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetEbsDefaultKmsKeyIdRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.dry_run {\n\n params.put(&format!(\"{}{}\", prefix, \"DryRun\"), &field_value);\n\n }\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetEbsDefaultKmsKeyIdResult {\n\n /// <p>The Amazon Resource Name (ARN) of the default CMK for encryption by default.</p>\n\n pub kms_key_id: Option<String>,\n\n}\n\n\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 15, "score": 230555.62381384528 }, { "content": "#[inline]\n\nfn encode_uri_strict(uri: &str) -> String {\n\n utf8_percent_encode(uri, &STRICT_ENCODE_SET).collect::<String>()\n\n}\n\n\n", "file_path": "rusoto/signature/src/signature.rs", "rank": 16, "score": 230310.73879910406 }, { "content": "fn parse_command_str(s: &str) -> Result<Command, CredentialsError> {\n\n let args = shlex::split(s)\n\n .ok_or_else(|| CredentialsError::new(\"Unable to parse credential_process value.\"))?;\n\n let mut iter = args.iter();\n\n let mut command = Command::new(\n\n iter.next()\n\n .ok_or_else(|| CredentialsError::new(\"credential_process value is empty.\"))?,\n\n );\n\n command.args(iter);\n\n Ok(command)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::env;\n\n use std::path::Path;\n\n\n\n use super::*;\n\n use crate::test_utils::lock_env;\n\n use crate::{CredentialsError, ProvideAwsCredentials};\n", "file_path": "rusoto/credential/src/profile.rs", "rank": 17, "score": 228820.002182539 }, { "content": "fn dynamo_get_item_test <P: ProvideAwsCredentials> (dynamodb: &mut DynamoDbHelper<P>, table_name: &str, item_key: Key)\n\n -> AwsResult<GetItemOutput> {\n\n\n\n let mut item_request = GetItemInput::default();\n\n item_request.key = item_key;\n\n item_request.table_name = table_name.to_string();\n\n\n\n match dynamodb.get_item(&item_request) {\n\n Err(why) => Err(why),\n\n Ok(output) => Ok(output),\n\n }\n\n}\n\n\n", "file_path": "helpers/tests/dynamodb.rs", "rank": 18, "score": 221871.05234047686 }, { "content": "fn extract_endpoint_path(endpoint: &str) -> Option<&str> {\n\n extract_endpoint_components(endpoint).1\n\n}\n\n\n", "file_path": "rusoto/signature/src/signature.rs", "rank": 19, "score": 216140.20230430405 }, { "content": "/// Parses the response from an AWS Metadata Service, either from an IAM Role, or a Container.\n\nfn parse_credentials_from_aws_service(response: &str) -> Result<AwsCredentials, CredentialsError> {\n\n Ok(serde_json::from_str::<AwsCredentials>(response)?)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::fs::{self, File};\n\n use std::io::Read;\n\n use std::path::Path;\n\n\n\n use crate::test_utils::{is_secret_hidden_behind_asterisks, lock_env, SECRET};\n\n use quickcheck::quickcheck;\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn default_empty_credentials_are_considered_anonymous() {\n\n assert!(AwsCredentials::default().is_anonymous())\n\n }\n\n\n", "file_path": "rusoto/credential/src/lib.rs", "rank": 20, "score": 214832.51988043333 }, { "content": "#[pin_project]\n\nstruct ImplAsyncRead {\n\n buffer: BytesMut,\n\n #[pin]\n\n stream: futures::stream::Fuse<Pin<Box<dyn Stream<Item = Result<Bytes, io::Error>> + Send>>>,\n\n}\n\n\n\nimpl ImplAsyncRead {\n\n fn new(stream: Pin<Box<dyn Stream<Item = Result<Bytes, io::Error>> + Send>>) -> Self {\n\n ImplAsyncRead {\n\n buffer: BytesMut::new(),\n\n stream: stream.fuse(),\n\n }\n\n }\n\n}\n\n\n\nimpl AsyncRead for ImplAsyncRead {\n\n fn poll_read(\n\n self: Pin<&mut Self>,\n\n cx: &mut Context<'_>,\n\n buf: &mut [u8],\n", "file_path": "rusoto/signature/src/stream.rs", "rank": 21, "score": 208944.25484131317 }, { "content": "pub fn get_rust_type(\n\n service: &Service<'_>,\n\n shape_name: &str,\n\n shape: &Shape,\n\n streaming: bool,\n\n for_timestamps: &str,\n\n) -> String {\n\n if !streaming {\n\n match shape.shape_type {\n\n ShapeType::Blob => \"bytes::Bytes\".into(),\n\n ShapeType::Boolean => \"bool\".into(),\n\n ShapeType::Double => \"f64\".into(),\n\n ShapeType::Float => \"f32\".into(),\n\n ShapeType::Integer | ShapeType::Long => \"i64\".into(),\n\n ShapeType::String => \"String\".into(),\n\n ShapeType::Timestamp => for_timestamps.into(),\n\n ShapeType::List => format!(\n\n \"Vec<{}>\",\n\n get_rust_type(\n\n service,\n", "file_path": "service_crategen/src/commands/generate/codegen/mod.rs", "rank": 22, "score": 206168.2285757971 }, { "content": "#[allow(dead_code)]\n\nstruct ContainerFormatDeserializer;\n\nimpl ContainerFormatDeserializer {\n\n #[allow(dead_code, unused_variables)]\n\n fn deserialize<T: Peek + Next>(tag_name: &str, stack: &mut T) -> Result<String, XmlParseError> {\n\n start_element(tag_name, stack)?;\n\n let obj = characters(stack)?;\n\n end_element(tag_name, stack)?;\n\n\n\n Ok(obj)\n\n }\n\n}\n\n\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 23, "score": 203367.31967711577 }, { "content": "/// Serialize `ExportClientVpnClientConfigurationRequest` contents to a `SignedRequest`.\n\nstruct ExportClientVpnClientConfigurationRequestSerializer;\n\nimpl ExportClientVpnClientConfigurationRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &ExportClientVpnClientConfigurationRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"ClientVpnEndpointId\"),\n\n &obj.client_vpn_endpoint_id,\n\n );\n\n if let Some(ref field_value) = obj.dry_run {\n\n params.put(&format!(\"{}{}\", prefix, \"DryRun\"), &field_value);\n\n }\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct ExportClientVpnClientConfigurationResult {\n\n /// <p>The contents of the Client VPN endpoint configuration file.</p>\n\n pub client_configuration: Option<String>,\n\n}\n\n\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 24, "score": 202694.14343473822 }, { "content": "#[async_trait]\n\npub trait StsSessionCredentialsClient {\n\n async fn assume_role(\n\n &self,\n\n input: AssumeRoleRequest,\n\n ) -> Result<AssumeRoleResponse, RusotoError<AssumeRoleError>>;\n\n\n\n async fn assume_role_with_saml(\n\n &self,\n\n input: AssumeRoleWithSAMLRequest,\n\n ) -> Result<AssumeRoleWithSAMLResponse, RusotoError<AssumeRoleWithSAMLError>>;\n\n\n\n async fn assume_role_with_web_identity(\n\n &self,\n\n input: AssumeRoleWithWebIdentityRequest,\n\n ) -> Result<AssumeRoleWithWebIdentityResponse, RusotoError<AssumeRoleWithWebIdentityError>>;\n\n\n\n async fn decode_authorization_message(\n\n &self,\n\n input: DecodeAuthorizationMessageRequest,\n\n ) -> Result<DecodeAuthorizationMessageResponse, RusotoError<DecodeAuthorizationMessageError>>;\n", "file_path": "rusoto/services/sts/src/custom/credential.rs", "rank": 25, "score": 201806.4179792699 }, { "content": "// should probably constantize with lazy_static!\n\nfn new_profile_regex() -> Regex {\n\n Regex::new(r\"^\\[(profile )?([^\\]]+)\\]$\").expect(\"Failed to compile regex\")\n\n}\n\n\n", "file_path": "rusoto/credential/src/profile.rs", "rank": 26, "score": 198220.3940951263 }, { "content": "/// Serialize `UpdateEnvironmentMessage` contents to a `SignedRequest`.\n\nstruct UpdateEnvironmentMessageSerializer;\n\nimpl UpdateEnvironmentMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &UpdateEnvironmentMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.application_name {\n\n params.put(&format!(\"{}{}\", prefix, \"ApplicationName\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.description {\n\n params.put(&format!(\"{}{}\", prefix, \"Description\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.environment_id {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentId\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.environment_name {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentName\"), &field_value);\n\n }\n", "file_path": "rusoto/services/elasticbeanstalk/src/generated.rs", "rank": 27, "score": 198100.249904719 }, { "content": "/// Serialize `DescribeEnvironmentsMessage` contents to a `SignedRequest`.\n\nstruct DescribeEnvironmentsMessageSerializer;\n\nimpl DescribeEnvironmentsMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &DescribeEnvironmentsMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.application_name {\n\n params.put(&format!(\"{}{}\", prefix, \"ApplicationName\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.environment_ids {\n\n EnvironmentIdListSerializer::serialize(\n\n params,\n\n &format!(\"{}{}\", prefix, \"EnvironmentIds\"),\n\n field_value,\n\n );\n\n }\n\n if let Some(ref field_value) = obj.environment_names {\n\n EnvironmentNamesListSerializer::serialize(\n", "file_path": "rusoto/services/elasticbeanstalk/src/generated.rs", "rank": 28, "score": 198100.249904719 }, { "content": "/// Serialize `CreateEnvironmentMessage` contents to a `SignedRequest`.\n\nstruct CreateEnvironmentMessageSerializer;\n\nimpl CreateEnvironmentMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &CreateEnvironmentMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"ApplicationName\"),\n\n &obj.application_name,\n\n );\n\n if let Some(ref field_value) = obj.cname_prefix {\n\n params.put(&format!(\"{}{}\", prefix, \"CNAMEPrefix\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.description {\n\n params.put(&format!(\"{}{}\", prefix, \"Description\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.environment_name {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentName\"), &field_value);\n", "file_path": "rusoto/services/elasticbeanstalk/src/generated.rs", "rank": 29, "score": 198100.249904719 }, { "content": "/// Serialize `TerminateEnvironmentMessage` contents to a `SignedRequest`.\n\nstruct TerminateEnvironmentMessageSerializer;\n\nimpl TerminateEnvironmentMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &TerminateEnvironmentMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.environment_id {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentId\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.environment_name {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentName\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.force_terminate {\n\n params.put(&format!(\"{}{}\", prefix, \"ForceTerminate\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.terminate_resources {\n\n params.put(&format!(\"{}{}\", prefix, \"TerminateResources\"), &field_value);\n\n }\n\n }\n\n}\n\n\n", "file_path": "rusoto/services/elasticbeanstalk/src/generated.rs", "rank": 30, "score": 198100.249904719 }, { "content": "/// Serialize `RebuildEnvironmentMessage` contents to a `SignedRequest`.\n\nstruct RebuildEnvironmentMessageSerializer;\n\nimpl RebuildEnvironmentMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &RebuildEnvironmentMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.environment_id {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentId\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.environment_name {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentName\"), &field_value);\n\n }\n\n }\n\n}\n\n\n", "file_path": "rusoto/services/elasticbeanstalk/src/generated.rs", "rank": 31, "score": 198100.249904719 }, { "content": "/// Serialize `ComposeEnvironmentsMessage` contents to a `SignedRequest`.\n\nstruct ComposeEnvironmentsMessageSerializer;\n\nimpl ComposeEnvironmentsMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &ComposeEnvironmentsMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.application_name {\n\n params.put(&format!(\"{}{}\", prefix, \"ApplicationName\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.group_name {\n\n params.put(&format!(\"{}{}\", prefix, \"GroupName\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.version_labels {\n\n VersionLabelsSerializer::serialize(\n\n params,\n\n &format!(\"{}{}\", prefix, \"VersionLabels\"),\n\n field_value,\n\n );\n\n }\n\n }\n\n}\n\n\n", "file_path": "rusoto/services/elasticbeanstalk/src/generated.rs", "rank": 32, "score": 198100.249904719 }, { "content": "#[allow(dead_code)]\n\nstruct EnvironmentDescriptionsMessageDeserializer;\n\nimpl EnvironmentDescriptionsMessageDeserializer {\n\n #[allow(dead_code, unused_variables)]\n\n fn deserialize<T: Peek + Next>(\n\n tag_name: &str,\n\n stack: &mut T,\n\n ) -> Result<EnvironmentDescriptionsMessage, XmlParseError> {\n\n deserialize_elements::<_, EnvironmentDescriptionsMessage, _>(\n\n tag_name,\n\n stack,\n\n |name, stack, obj| {\n\n match name {\n\n \"Environments\" => {\n\n obj.environments.get_or_insert(vec![]).extend(\n\n EnvironmentDescriptionsListDeserializer::deserialize(\n\n \"Environments\",\n\n stack,\n\n )?,\n\n );\n\n }\n\n \"NextToken\" => {\n\n obj.next_token = Some(TokenDeserializer::deserialize(\"NextToken\", stack)?);\n\n }\n\n _ => skip_tree(stack),\n\n }\n\n Ok(())\n\n },\n\n )\n\n }\n\n}\n", "file_path": "rusoto/services/elasticbeanstalk/src/generated.rs", "rank": 33, "score": 198076.79275095713 }, { "content": "/// Serialize `GetUserRequest` contents to a `SignedRequest`.\n\nstruct GetUserRequestSerializer;\n\nimpl GetUserRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetUserRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.user_name {\n\n params.put(&format!(\"{}{}\", prefix, \"UserName\"), &field_value);\n\n }\n\n }\n\n}\n\n\n\n/// <p>Contains the response to a successful <a>GetUser</a> request. </p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetUserResponse {\n\n /// <p><p>A structure containing details about the IAM user.</p> <important> <p>Due to a service issue, password last used data does not include password use from May 3, 2018 22:50 PDT to May 23, 2018 14:08 PDT. This affects <a href=\"https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_finding-unused.html\">last sign-in</a> dates shown in the IAM console and password last used dates in the <a href=\"https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_getting-report.html\">IAM credential report</a>, and returned by this GetUser API. If users signed in during the affected time, the password last used date that is returned is the date the user last signed in before May 3, 2018. For users that signed in after May 23, 2018 14:08 PDT, the returned password last used date is accurate.</p> <p>You can use password last used information to identify unused credentials for deletion. For example, you might delete users who did not sign in to AWS in the last 90 days. In cases like this, we recommend that you adjust your evaluation window to include dates after May 23, 2018. Alternatively, if your users use access keys to access AWS programmatically you can refer to access key last used information because it is accurate for all dates. </p> </important></p>\n\n pub user: User,\n\n}\n\n\n", "file_path": "rusoto/services/iam/src/generated.rs", "rank": 34, "score": 198054.9988888299 }, { "content": "/// Serialize `GetGroupRequest` contents to a `SignedRequest`.\n\nstruct GetGroupRequestSerializer;\n\nimpl GetGroupRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetGroupRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(&format!(\"{}{}\", prefix, \"GroupName\"), &obj.group_name);\n\n if let Some(ref field_value) = obj.marker {\n\n params.put(&format!(\"{}{}\", prefix, \"Marker\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.max_items {\n\n params.put(&format!(\"{}{}\", prefix, \"MaxItems\"), &field_value);\n\n }\n\n }\n\n}\n\n\n\n/// <p>Contains the response to a successful <a>GetGroup</a> request. </p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n", "file_path": "rusoto/services/iam/src/generated.rs", "rank": 35, "score": 198054.9988888299 }, { "content": "/// Serialize `GetTemplateRequest` contents to a `SignedRequest`.\n\nstruct GetTemplateRequestSerializer;\n\nimpl GetTemplateRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetTemplateRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(&format!(\"{}{}\", prefix, \"TemplateName\"), &obj.template_name);\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetTemplateResponse {\n\n pub template: Option<Template>,\n\n}\n\n\n", "file_path": "rusoto/services/ses/src/generated.rs", "rank": 36, "score": 198054.9988888299 }, { "content": "/// Serialize `GetAttributesRequest` contents to a `SignedRequest`.\n\nstruct GetAttributesRequestSerializer;\n\nimpl GetAttributesRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetAttributesRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.attribute_names {\n\n AttributeNameListSerializer::serialize(\n\n params,\n\n &format!(\"{}{}\", prefix, \"AttributeName\"),\n\n field_value,\n\n );\n\n }\n\n if let Some(ref field_value) = obj.consistent_read {\n\n params.put(&format!(\"{}{}\", prefix, \"ConsistentRead\"), &field_value);\n\n }\n\n params.put(&format!(\"{}{}\", prefix, \"DomainName\"), &obj.domain_name);\n\n params.put(&format!(\"{}{}\", prefix, \"ItemName\"), &obj.item_name);\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetAttributesResult {\n\n /// <p>The list of attributes returned by the operation.</p>\n\n pub attributes: Option<Vec<Attribute>>,\n\n}\n\n\n", "file_path": "rusoto/services/sdb/src/generated.rs", "rank": 37, "score": 198054.9988888299 }, { "content": "/// Serialize `GetPolicyRequest` contents to a `SignedRequest`.\n\nstruct GetPolicyRequestSerializer;\n\nimpl GetPolicyRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetPolicyRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(&format!(\"{}{}\", prefix, \"PolicyArn\"), &obj.policy_arn);\n\n }\n\n}\n\n\n\n/// <p>Contains the response to a successful <a>GetPolicy</a> request. </p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetPolicyResponse {\n\n /// <p>A structure containing details about the policy.</p>\n\n pub policy: Option<Policy>,\n\n}\n\n\n", "file_path": "rusoto/services/iam/src/generated.rs", "rank": 38, "score": 198054.9988888299 }, { "content": "/// Serialize `GetRoleRequest` contents to a `SignedRequest`.\n\nstruct GetRoleRequestSerializer;\n\nimpl GetRoleRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetRoleRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(&format!(\"{}{}\", prefix, \"RoleName\"), &obj.role_name);\n\n }\n\n}\n\n\n\n/// <p>Contains the response to a successful <a>GetRole</a> request. </p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetRoleResponse {\n\n /// <p>A structure containing details about the IAM role.</p>\n\n pub role: Role,\n\n}\n\n\n", "file_path": "rusoto/services/iam/src/generated.rs", "rank": 39, "score": 198054.9988888299 }, { "content": "#[allow(dead_code)]\n\nstruct ClientRequestTokenDeserializer;\n\nimpl ClientRequestTokenDeserializer {\n\n #[allow(dead_code, unused_variables)]\n\n fn deserialize<T: Peek + Next>(tag_name: &str, stack: &mut T) -> Result<String, XmlParseError> {\n\n start_element(tag_name, stack)?;\n\n let obj = characters(stack)?;\n\n end_element(tag_name, stack)?;\n\n\n\n Ok(obj)\n\n }\n\n}\n\n/// <p>The input for the <a>ContinueUpdateRollback</a> action.</p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"deserialize_structs\", derive(Deserialize))]\n\npub struct ContinueUpdateRollbackInput {\n\n /// <p>A unique identifier for this <code>ContinueUpdateRollback</code> request. Specify this token if you plan to retry requests so that AWS CloudFormation knows that you're not attempting to continue the rollback to a stack with the same name. You might retry <code>ContinueUpdateRollback</code> requests to ensure that AWS CloudFormation successfully received them.</p>\n\n pub client_request_token: Option<String>,\n\n /// <p><p>A list of the logical IDs of the resources that AWS CloudFormation skips during the continue update rollback operation. You can specify only resources that are in the <code>UPDATE<em>FAILED</code> state because a rollback failed. You can&#39;t specify resources that are in the <code>UPDATE</em>FAILED</code> state for other reasons, for example, because an update was cancelled. To check why a resource update failed, use the <a>DescribeStackResources</a> action, and view the resource status reason. </p> <important> <p>Specify this property to skip rolling back resources that AWS CloudFormation can&#39;t successfully roll back. We recommend that you <a href=\"https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html#troubleshooting-errors-update-rollback-failed\"> troubleshoot</a> resources before skipping them. AWS CloudFormation sets the status of the specified resources to <code>UPDATE<em>COMPLETE</code> and continues to roll back the stack. After the rollback is complete, the state of the skipped resources will be inconsistent with the state of the resources in the stack template. Before performing another stack update, you must update the stack or resources to be consistent with each other. If you don&#39;t, subsequent stack updates might fail, and the stack will become unrecoverable. </p> </important> <p>Specify the minimum number of resources required to successfully roll back your stack. For example, a failed resource update might cause dependent resources to fail. In this case, it might not be necessary to skip the dependent resources. </p> <p>To skip resources that are part of nested stacks, use the following format: <code>NestedStackName.ResourceLogicalID</code>. If you want to specify the logical ID of a stack resource (<code>Type: AWS::CloudFormation::Stack</code>) in the <code>ResourcesToSkip</code> list, then its corresponding embedded stack must be in one of the following states: <code>DELETE</em>IN<em>PROGRESS</code>, <code>DELETE</em>COMPLETE</code>, or <code>DELETE_FAILED</code>. </p> <note> <p>Don&#39;t confuse a child stack&#39;s name with its corresponding logical ID defined in the parent stack. For an example of a continue update rollback operation with nested stacks, see <a href=\"https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-continueupdaterollback.html#nested-stacks\">Using ResourcesToSkip to recover a nested stacks hierarchy</a>. </p> </note></p>\n\n pub resources_to_skip: Option<Vec<String>>,\n\n /// <p>The Amazon Resource Name (ARN) of an AWS Identity and Access Management (IAM) role that AWS CloudFormation assumes to roll back the stack. AWS CloudFormation uses the role's credentials to make calls on your behalf. AWS CloudFormation always uses this role for all future operations on the stack. As long as users have permission to operate on the stack, AWS CloudFormation uses this role even if the users don't have permission to pass it. Ensure that the role grants least privilege.</p> <p>If you don't specify a value, AWS CloudFormation uses the role that was previously associated with the stack. If no role is available, AWS CloudFormation uses a temporary session that is generated from your user credentials.</p>\n\n pub role_arn: Option<String>,\n\n /// <p><p>The name or the unique ID of the stack that you want to continue rolling back.</p> <note> <p>Don&#39;t specify the name of a nested stack (a stack that was created by using the <code>AWS::CloudFormation::Stack</code> resource). Instead, use this operation on the parent stack (the stack that contains the <code>AWS::CloudFormation::Stack</code> resource).</p> </note></p>\n\n pub stack_name: String,\n\n}\n\n\n", "file_path": "rusoto/services/cloudformation/src/generated.rs", "rank": 40, "score": 198047.69419497577 }, { "content": "/// Serialize `SendMessageRequest` contents to a `SignedRequest`.\n\nstruct SendMessageRequestSerializer;\n\nimpl SendMessageRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &SendMessageRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.delay_seconds {\n\n params.put(&format!(\"{}{}\", prefix, \"DelaySeconds\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.message_attributes {\n\n MessageBodyAttributeMapSerializer::serialize(\n\n params,\n\n &format!(\"{}{}\", prefix, \"MessageAttribute\"),\n\n field_value,\n\n );\n\n }\n\n params.put(&format!(\"{}{}\", prefix, \"MessageBody\"), &obj.message_body);\n\n if let Some(ref field_value) = obj.message_deduplication_id {\n", "file_path": "rusoto/services/sqs/src/generated.rs", "rank": 41, "score": 198022.70878486626 }, { "content": "/// Serialize `DeleteMessageRequest` contents to a `SignedRequest`.\n\nstruct DeleteMessageRequestSerializer;\n\nimpl DeleteMessageRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &DeleteMessageRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(&format!(\"{}{}\", prefix, \"QueueUrl\"), &obj.queue_url);\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"ReceiptHandle\"),\n\n &obj.receipt_handle,\n\n );\n\n }\n\n}\n\n\n\n/// <p><p/></p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"deserialize_structs\", derive(Deserialize))]\n\npub struct DeleteQueueRequest {\n\n /// <p>The URL of the Amazon SQS queue to delete.</p> <p>Queue URLs and names are case-sensitive.</p>\n\n pub queue_url: String,\n\n}\n\n\n", "file_path": "rusoto/services/sqs/src/generated.rs", "rank": 42, "score": 198022.70878486626 }, { "content": "/// Serialize `ReceiveMessageRequest` contents to a `SignedRequest`.\n\nstruct ReceiveMessageRequestSerializer;\n\nimpl ReceiveMessageRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &ReceiveMessageRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.attribute_names {\n\n AttributeNameListSerializer::serialize(\n\n params,\n\n &format!(\"{}{}\", prefix, \"AttributeName\"),\n\n field_value,\n\n );\n\n }\n\n if let Some(ref field_value) = obj.max_number_of_messages {\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"MaxNumberOfMessages\"),\n\n &field_value,\n\n );\n", "file_path": "rusoto/services/sqs/src/generated.rs", "rank": 43, "score": 198022.70878486626 }, { "content": "fn preprocess(input: &str, pre: &str, fmt: &mut Formatter<'_>) -> FmtResult {\n\n // fix up problems in AWS docs\n\n let escaped_1 = input.replace(\"<code>\\\\</code>\", \"<code>&bsol;</code>\");\n\n let escaped_2 = escaped_1.replace(\"\\\"</p>\\\"\", \"</p>\");\n\n\n\n // parse and render markdown\n\n let markdown = Markdown::new(&escaped_2);\n\n let mut html_renderer = Html::new(Flags::empty(), 0);\n\n let buffer = html_renderer.render(&markdown);\n\n let rendered = buffer.to_str().unwrap();\n\n\n\n // prefix and write to formatter\n\n prefix(&rendered, pre, fmt)\n\n}\n\n\n", "file_path": "service_crategen/src/doco.rs", "rank": 44, "score": 197491.57917275623 }, { "content": "fn prefix(input: &str, pre: &str, fmt: &mut Formatter<'_>) -> FmtResult {\n\n for (i, line) in input.lines().enumerate() {\n\n if i > 0 {\n\n fmt.write_char('\\n')?;\n\n }\n\n if line.is_empty() {\n\n write!(fmt, \"{}\", pre)?;\n\n } else {\n\n write!(fmt, \"{} {}\", pre, line.trim())?;\n\n }\n\n }\n\n Ok(())\n\n}\n", "file_path": "service_crategen/src/doco.rs", "rank": 45, "score": 197491.57917275623 }, { "content": "/// This is a helper function as Option<T>::filter is not yet stable (see issue #45860).\n\n/// <https://github.com/rust-lang/rfcs/issues/2036> also affects the implementation of this.\n\nfn non_empty_env_var(name: &str) -> Option<String> {\n\n match env_var(name) {\n\n Ok(value) => {\n\n if value.is_empty() {\n\n None\n\n } else {\n\n Some(value)\n\n }\n\n }\n\n Err(_) => None,\n\n }\n\n}\n\n\n", "file_path": "rusoto/credential/src/lib.rs", "rank": 46, "score": 196469.81589509358 }, { "content": "#[inline]\n\npub fn case_insensitive_btreemap_get<'a, V>(\n\n map: &'a BTreeMap<String, V>,\n\n key: &str,\n\n) -> Option<&'a V> {\n\n map.iter()\n\n .filter(|&(k, _)| k.to_lowercase() == key.to_lowercase())\n\n .map(|(_, v)| v)\n\n .next()\n\n}\n\n\n", "file_path": "service_crategen/src/util.rs", "rank": 47, "score": 196318.9323672006 }, { "content": "pub fn find_responses_in_dir(dir_path: &Path) -> Vec<Response> {\n\n let dir = fs::read_dir(dir_path).expect(\"read_dir\");\n\n\n\n let mut responses = dir\n\n .filter_map(std::result::Result::ok)\n\n .filter(|d| d.path().extension().map(|ex| ex == \"xml\").unwrap_or(false))\n\n .filter_map(|d| Response::from_response_path(&d.path()))\n\n .collect::<Vec<_>>();\n\n\n\n responses.sort_by_key(|e| e.full_path.clone());\n\n\n\n responses\n\n}\n\n\n", "file_path": "service_crategen/src/commands/generate/codegen/tests.rs", "rank": 48, "score": 194974.21269874534 }, { "content": "/// Serialize `ExportClientVpnClientCertificateRevocationListRequest` contents to a `SignedRequest`.\n\nstruct ExportClientVpnClientCertificateRevocationListRequestSerializer;\n\nimpl ExportClientVpnClientCertificateRevocationListRequestSerializer {\n\n fn serialize(\n\n params: &mut Params,\n\n name: &str,\n\n obj: &ExportClientVpnClientCertificateRevocationListRequest,\n\n ) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"ClientVpnEndpointId\"),\n\n &obj.client_vpn_endpoint_id,\n\n );\n\n if let Some(ref field_value) = obj.dry_run {\n\n params.put(&format!(\"{}{}\", prefix, \"DryRun\"), &field_value);\n\n }\n\n }\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 49, "score": 194757.36432426196 }, { "content": "/// Serialize `ImportClientVpnClientCertificateRevocationListRequest` contents to a `SignedRequest`.\n\nstruct ImportClientVpnClientCertificateRevocationListRequestSerializer;\n\nimpl ImportClientVpnClientCertificateRevocationListRequestSerializer {\n\n fn serialize(\n\n params: &mut Params,\n\n name: &str,\n\n obj: &ImportClientVpnClientCertificateRevocationListRequest,\n\n ) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"CertificateRevocationList\"),\n\n &obj.certificate_revocation_list,\n\n );\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"ClientVpnEndpointId\"),\n\n &obj.client_vpn_endpoint_id,\n\n );\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 50, "score": 194757.36432426196 }, { "content": "#[test]\n\nfn structs_should_impl_clone() {\n\n fn assert_clone<T: Clone>() {}\n\n\n\n // GetObjectRequest is common but simple. It must impl Clone.\n\n // (But note GetObjectOutput cannot impl Clone because it uses streaming.)\n\n assert_clone::<GetObjectRequest>();\n\n // RestoreObjectRequest has several layers of structs, all of which must impl Clone.\n\n assert_clone::<RestoreObjectRequest>();\n\n}\n\n\n", "file_path": "rusoto/services/s3/src/custom/custom_tests.rs", "rank": 51, "score": 194393.32313746747 }, { "content": "fn generate_examples(crate_dir_path: &Path) -> Option<String> {\n\n let examples_dir_path = crate_dir_path.join(\"examples\");\n\n\n\n if !examples_dir_path.exists() {\n\n return None;\n\n }\n\n\n\n let mut output = \"//!\\n//! # Examples\\n\".to_string();\n\n\n\n for dir_entry_result in fs::read_dir(&examples_dir_path).expect(\"failed to read examples dir\") {\n\n let dir_entry = dir_entry_result.expect(\"failed to read examples dir\");\n\n let mut contents = Vec::new();\n\n let mut file = fs::File::open(dir_entry.path()).expect(\"failed to open example\");\n\n file.read_to_end(&mut contents)\n\n .expect(\"failed to read from example file\");\n\n let string_contents =\n\n String::from_utf8(contents).expect(\"example file has invalid encoding\");\n\n\n\n output.push_str(\"//!\\n\");\n\n\n", "file_path": "service_crategen/src/commands/generate/mod.rs", "rank": 52, "score": 193661.69916290912 }, { "content": "pub fn generate_params_loading_string(\n\n service: &Service<'_>,\n\n operation: &Operation,\n\n) -> Option<String> {\n\n operation.input.as_ref()?;\n\n\n\n let input_type = operation.input_shape();\n\n let input_shape = service.get_shape(input_type).unwrap();\n\n\n\n // Construct a list of strings which will be used to load request\n\n // parameters from the input struct into a `Params` vec, which will\n\n // then be added to the request.\n\n let mut param_strings = generate_shape_member_param_strings(service, input_shape);\n\n param_strings.append(&mut generate_static_param_strings(operation));\n\n\n\n let load_params = match param_strings.len() {\n\n 0 => \"\".to_owned(),\n\n _ => format!(\n\n \"let mut params = Params::new();\n\n {param_strings}\n\n request.set_params(params);\",\n\n param_strings = param_strings.join(\"\\n\")\n\n ),\n\n };\n\n\n\n Some(load_params)\n\n}\n\n\n", "file_path": "service_crategen/src/commands/generate/codegen/rest_request_generator.rs", "rank": 53, "score": 193568.27682634906 }, { "content": "/// Serialize `AbortEnvironmentUpdateMessage` contents to a `SignedRequest`.\n\nstruct AbortEnvironmentUpdateMessageSerializer;\n\nimpl AbortEnvironmentUpdateMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &AbortEnvironmentUpdateMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.environment_id {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentId\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.environment_name {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentName\"), &field_value);\n\n }\n\n }\n\n}\n\n\n", "file_path": "rusoto/services/elasticbeanstalk/src/generated.rs", "rank": 54, "score": 193167.25346347375 }, { "content": "/// Serialize `RetrieveEnvironmentInfoMessage` contents to a `SignedRequest`.\n\nstruct RetrieveEnvironmentInfoMessageSerializer;\n\nimpl RetrieveEnvironmentInfoMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &RetrieveEnvironmentInfoMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.environment_id {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentId\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.environment_name {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentName\"), &field_value);\n\n }\n\n params.put(&format!(\"{}{}\", prefix, \"InfoType\"), &obj.info_type);\n\n }\n\n}\n\n\n\n/// <p>Result message containing a description of the requested environment info.</p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct RetrieveEnvironmentInfoResultMessage {\n\n /// <p> The <a>EnvironmentInfoDescription</a> of the environment. </p>\n\n pub environment_info: Option<Vec<EnvironmentInfoDescription>>,\n\n}\n\n\n", "file_path": "rusoto/services/elasticbeanstalk/src/generated.rs", "rank": 55, "score": 193167.25346347375 }, { "content": "/// Serialize `DeleteEnvironmentConfigurationMessage` contents to a `SignedRequest`.\n\nstruct DeleteEnvironmentConfigurationMessageSerializer;\n\nimpl DeleteEnvironmentConfigurationMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &DeleteEnvironmentConfigurationMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"ApplicationName\"),\n\n &obj.application_name,\n\n );\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"EnvironmentName\"),\n\n &obj.environment_name,\n\n );\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"deserialize_structs\", derive(Deserialize))]\n\npub struct DeletePlatformVersionRequest {\n\n /// <p>The ARN of the version of the custom platform.</p>\n\n pub platform_arn: Option<String>,\n\n}\n\n\n", "file_path": "rusoto/services/elasticbeanstalk/src/generated.rs", "rank": 56, "score": 193167.25346347375 }, { "content": "/// Serialize `DescribeEnvironmentResourcesMessage` contents to a `SignedRequest`.\n\nstruct DescribeEnvironmentResourcesMessageSerializer;\n\nimpl DescribeEnvironmentResourcesMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &DescribeEnvironmentResourcesMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.environment_id {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentId\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.environment_name {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentName\"), &field_value);\n\n }\n\n }\n\n}\n\n\n\n/// <p>Request to describe one or more environments.</p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"deserialize_structs\", derive(Deserialize))]\n", "file_path": "rusoto/services/elasticbeanstalk/src/generated.rs", "rank": 57, "score": 193167.25346347375 }, { "content": "#[allow(dead_code)]\n\nstruct GetCredentialReportResponseDeserializer;\n\nimpl GetCredentialReportResponseDeserializer {\n\n #[allow(dead_code, unused_variables)]\n\n fn deserialize<T: Peek + Next>(\n\n tag_name: &str,\n\n stack: &mut T,\n\n ) -> Result<GetCredentialReportResponse, XmlParseError> {\n\n deserialize_elements::<_, GetCredentialReportResponse, _>(\n\n tag_name,\n\n stack,\n\n |name, stack, obj| {\n\n match name {\n\n \"Content\" => {\n\n obj.content = Some(ReportContentTypeDeserializer::deserialize(\n\n \"Content\", stack,\n\n )?);\n\n }\n\n \"GeneratedTime\" => {\n\n obj.generated_time =\n\n Some(DateTypeDeserializer::deserialize(\"GeneratedTime\", stack)?);\n", "file_path": "rusoto/services/iam/src/generated.rs", "rank": 58, "score": 193164.63873531157 }, { "content": "#[allow(dead_code)]\n\nstruct EnvironmentResourceDescriptionsMessageDeserializer;\n\nimpl EnvironmentResourceDescriptionsMessageDeserializer {\n\n #[allow(dead_code, unused_variables)]\n\n fn deserialize<T: Peek + Next>(\n\n tag_name: &str,\n\n stack: &mut T,\n\n ) -> Result<EnvironmentResourceDescriptionsMessage, XmlParseError> {\n\n deserialize_elements::<_, EnvironmentResourceDescriptionsMessage, _>(\n\n tag_name,\n\n stack,\n\n |name, stack, obj| {\n\n match name {\n\n \"EnvironmentResources\" => {\n\n obj.environment_resources =\n\n Some(EnvironmentResourceDescriptionDeserializer::deserialize(\n\n \"EnvironmentResources\",\n\n stack,\n\n )?);\n\n }\n\n _ => skip_tree(stack),\n", "file_path": "rusoto/services/elasticbeanstalk/src/generated.rs", "rank": 59, "score": 193143.9646918428 }, { "content": "#[allow(dead_code)]\n\nstruct HsmClientCertificateMessageDeserializer;\n\nimpl HsmClientCertificateMessageDeserializer {\n\n #[allow(dead_code, unused_variables)]\n\n fn deserialize<T: Peek + Next>(\n\n tag_name: &str,\n\n stack: &mut T,\n\n ) -> Result<HsmClientCertificateMessage, XmlParseError> {\n\n deserialize_elements::<_, HsmClientCertificateMessage, _>(\n\n tag_name,\n\n stack,\n\n |name, stack, obj| {\n\n match name {\n\n \"HsmClientCertificates\" => {\n\n obj.hsm_client_certificates.get_or_insert(vec![]).extend(\n\n HsmClientCertificateListDeserializer::deserialize(\n\n \"HsmClientCertificates\",\n\n stack,\n\n )?,\n\n );\n\n }\n", "file_path": "rusoto/services/redshift/src/generated.rs", "rank": 60, "score": 193141.28426139877 }, { "content": "/// Serialize `ModifyIdFormatRequest` contents to a `SignedRequest`.\n\nstruct ModifyIdFormatRequestSerializer;\n\nimpl ModifyIdFormatRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &ModifyIdFormatRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(&format!(\"{}{}\", prefix, \"Resource\"), &obj.resource);\n\n params.put(&format!(\"{}{}\", prefix, \"UseLongIds\"), &obj.use_long_ids);\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"deserialize_structs\", derive(Deserialize))]\n\npub struct ModifyIdentityIdFormatRequest {\n\n /// <p>The ARN of the principal, which can be an IAM user, IAM role, or the root user. Specify <code>all</code> to modify the ID format for all IAM users, IAM roles, and the root user of the account.</p>\n\n pub principal_arn: String,\n\n /// <p>The type of resource: <code>bundle</code> | <code>conversion-task</code> | <code>customer-gateway</code> | <code>dhcp-options</code> | <code>elastic-ip-allocation</code> | <code>elastic-ip-association</code> | <code>export-task</code> | <code>flow-log</code> | <code>image</code> | <code>import-task</code> | <code>internet-gateway</code> | <code>network-acl</code> | <code>network-acl-association</code> | <code>network-interface</code> | <code>network-interface-attachment</code> | <code>prefix-list</code> | <code>route-table</code> | <code>route-table-association</code> | <code>security-group</code> | <code>subnet</code> | <code>subnet-cidr-block-association</code> | <code>vpc</code> | <code>vpc-cidr-block-association</code> | <code>vpc-endpoint</code> | <code>vpc-peering-connection</code> | <code>vpn-connection</code> | <code>vpn-gateway</code>.</p> <p>Alternatively, use the <code>all-current</code> option to include all resource types that are currently within their opt-in period for longer IDs.</p>\n\n pub resource: String,\n\n /// <p>Indicates whether the resource should use longer IDs (17-character IDs)</p>\n\n pub use_long_ids: bool,\n\n}\n\n\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 61, "score": 193138.05791149085 }, { "content": "/// Serialize `DescribeIdFormatRequest` contents to a `SignedRequest`.\n\nstruct DescribeIdFormatRequestSerializer;\n\nimpl DescribeIdFormatRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &DescribeIdFormatRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.resource {\n\n params.put(&format!(\"{}{}\", prefix, \"Resource\"), &field_value);\n\n }\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct DescribeIdFormatResult {\n\n /// <p>Information about the ID format for the resource.</p>\n\n pub statuses: Option<Vec<IdFormat>>,\n\n}\n\n\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 62, "score": 193138.05791149085 }, { "content": "/// Serialize `CreateDefaultSubnetRequest` contents to a `SignedRequest`.\n\nstruct CreateDefaultSubnetRequestSerializer;\n\nimpl CreateDefaultSubnetRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &CreateDefaultSubnetRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"AvailabilityZone\"),\n\n &obj.availability_zone,\n\n );\n\n if let Some(ref field_value) = obj.dry_run {\n\n params.put(&format!(\"{}{}\", prefix, \"DryRun\"), &field_value);\n\n }\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct CreateDefaultSubnetResult {\n\n /// <p>Information about the subnet.</p>\n\n pub subnet: Option<Subnet>,\n\n}\n\n\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 63, "score": 193135.20065762172 }, { "content": "/// Serialize `CreateDefaultVpcRequest` contents to a `SignedRequest`.\n\nstruct CreateDefaultVpcRequestSerializer;\n\nimpl CreateDefaultVpcRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &CreateDefaultVpcRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.dry_run {\n\n params.put(&format!(\"{}{}\", prefix, \"DryRun\"), &field_value);\n\n }\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct CreateDefaultVpcResult {\n\n /// <p>Information about the VPC.</p>\n\n pub vpc: Option<Vpc>,\n\n}\n\n\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 64, "score": 193135.20065762172 }, { "content": "/// Serialize `DescribeEnvironmentHealthRequest` contents to a `SignedRequest`.\n\nstruct DescribeEnvironmentHealthRequestSerializer;\n\nimpl DescribeEnvironmentHealthRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &DescribeEnvironmentHealthRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.attribute_names {\n\n EnvironmentHealthAttributesSerializer::serialize(\n\n params,\n\n &format!(\"{}{}\", prefix, \"AttributeNames\"),\n\n field_value,\n\n );\n\n }\n\n if let Some(ref field_value) = obj.environment_id {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentId\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.environment_name {\n\n params.put(&format!(\"{}{}\", prefix, \"EnvironmentName\"), &field_value);\n", "file_path": "rusoto/services/elasticbeanstalk/src/generated.rs", "rank": 65, "score": 193134.95921332913 }, { "content": "/// Serialize `ClientVpnAuthenticationRequest` contents to a `SignedRequest`.\n\nstruct ClientVpnAuthenticationRequestSerializer;\n\nimpl ClientVpnAuthenticationRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &ClientVpnAuthenticationRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.active_directory {\n\n DirectoryServiceAuthenticationRequestSerializer::serialize(\n\n params,\n\n &format!(\"{}{}\", prefix, \"ActiveDirectory\"),\n\n field_value,\n\n );\n\n }\n\n if let Some(ref field_value) = obj.mutual_authentication {\n\n CertificateAuthenticationRequestSerializer::serialize(\n\n params,\n\n &format!(\"{}{}\", prefix, \"MutualAuthentication\"),\n\n field_value,\n\n );\n\n }\n\n if let Some(ref field_value) = obj.type_ {\n\n params.put(&format!(\"{}{}\", prefix, \"Type\"), &field_value);\n\n }\n\n }\n\n}\n\n\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 66, "score": 193132.13658785215 }, { "content": "/// Serialize `GetSAMLProviderRequest` contents to a `SignedRequest`.\n\nstruct GetSAMLProviderRequestSerializer;\n\nimpl GetSAMLProviderRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetSAMLProviderRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"SAMLProviderArn\"),\n\n &obj.saml_provider_arn,\n\n );\n\n }\n\n}\n\n\n\n/// <p>Contains the response to a successful <a>GetSAMLProvider</a> request. </p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetSAMLProviderResponse {\n\n /// <p>The date and time when the SAML provider was created.</p>\n\n pub create_date: Option<String>,\n\n /// <p>The XML metadata document that includes information about an identity provider.</p>\n\n pub saml_metadata_document: Option<String>,\n\n /// <p>The expiration date and time for the SAML provider.</p>\n\n pub valid_until: Option<String>,\n\n}\n\n\n", "file_path": "rusoto/services/iam/src/generated.rs", "rank": 67, "score": 193123.1939405792 }, { "content": "/// Serialize `GetInstanceProfileRequest` contents to a `SignedRequest`.\n\nstruct GetInstanceProfileRequestSerializer;\n\nimpl GetInstanceProfileRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetInstanceProfileRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"InstanceProfileName\"),\n\n &obj.instance_profile_name,\n\n );\n\n }\n\n}\n\n\n\n/// <p>Contains the response to a successful <a>GetInstanceProfile</a> request. </p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetInstanceProfileResponse {\n\n /// <p>A structure containing details about the instance profile.</p>\n\n pub instance_profile: InstanceProfile,\n\n}\n\n\n", "file_path": "rusoto/services/iam/src/generated.rs", "rank": 68, "score": 193123.1939405792 }, { "content": "/// Serialize `GetGroupPolicyRequest` contents to a `SignedRequest`.\n\nstruct GetGroupPolicyRequestSerializer;\n\nimpl GetGroupPolicyRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetGroupPolicyRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(&format!(\"{}{}\", prefix, \"GroupName\"), &obj.group_name);\n\n params.put(&format!(\"{}{}\", prefix, \"PolicyName\"), &obj.policy_name);\n\n }\n\n}\n\n\n\n/// <p>Contains the response to a successful <a>GetGroupPolicy</a> request. </p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetGroupPolicyResponse {\n\n /// <p>The group the policy is associated with.</p>\n\n pub group_name: String,\n\n /// <p>The policy document.</p> <p>IAM stores policies in JSON format. However, resources that were created using AWS CloudFormation templates can be formatted in YAML. AWS CloudFormation always converts a YAML policy to JSON format before submitting it to IAM.</p>\n\n pub policy_document: String,\n\n /// <p>The name of the policy.</p>\n\n pub policy_name: String,\n\n}\n\n\n", "file_path": "rusoto/services/iam/src/generated.rs", "rank": 69, "score": 193123.1939405792 }, { "content": "/// Serialize `GetPolicyVersionRequest` contents to a `SignedRequest`.\n\nstruct GetPolicyVersionRequestSerializer;\n\nimpl GetPolicyVersionRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetPolicyVersionRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(&format!(\"{}{}\", prefix, \"PolicyArn\"), &obj.policy_arn);\n\n params.put(&format!(\"{}{}\", prefix, \"VersionId\"), &obj.version_id);\n\n }\n\n}\n\n\n\n/// <p>Contains the response to a successful <a>GetPolicyVersion</a> request. </p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetPolicyVersionResponse {\n\n /// <p>A structure containing details about the policy version.</p>\n\n pub policy_version: Option<PolicyVersion>,\n\n}\n\n\n", "file_path": "rusoto/services/iam/src/generated.rs", "rank": 70, "score": 193123.1939405792 }, { "content": "/// Serialize `GetSessionTokenRequest` contents to a `SignedRequest`.\n\nstruct GetSessionTokenRequestSerializer;\n\nimpl GetSessionTokenRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetSessionTokenRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.duration_seconds {\n\n params.put(&format!(\"{}{}\", prefix, \"DurationSeconds\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.serial_number {\n\n params.put(&format!(\"{}{}\", prefix, \"SerialNumber\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.token_code {\n\n params.put(&format!(\"{}{}\", prefix, \"TokenCode\"), &field_value);\n\n }\n\n }\n\n}\n\n\n\n/// <p>Contains the response to a successful <a>GetSessionToken</a> request, including temporary AWS credentials that can be used to make AWS requests. </p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetSessionTokenResponse {\n\n /// <p><p>The temporary security credentials, which include an access key ID, a secret access key, and a security (or session) token.</p> <note> <p>The size of the security token that STS API operations return is not fixed. We strongly recommend that you make no assumptions about the maximum size.</p> </note></p>\n\n pub credentials: Option<Credentials>,\n\n}\n\n\n", "file_path": "rusoto/services/sts/src/generated.rs", "rank": 71, "score": 193123.1939405792 }, { "content": "/// Serialize `GetServerCertificateRequest` contents to a `SignedRequest`.\n\nstruct GetServerCertificateRequestSerializer;\n\nimpl GetServerCertificateRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetServerCertificateRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"ServerCertificateName\"),\n\n &obj.server_certificate_name,\n\n );\n\n }\n\n}\n\n\n\n/// <p>Contains the response to a successful <a>GetServerCertificate</a> request. </p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetServerCertificateResponse {\n\n /// <p>A structure containing details about the server certificate.</p>\n\n pub server_certificate: ServerCertificate,\n\n}\n\n\n", "file_path": "rusoto/services/iam/src/generated.rs", "rank": 72, "score": 193123.1939405792 }, { "content": "/// Serialize `GetQueueAttributesRequest` contents to a `SignedRequest`.\n\nstruct GetQueueAttributesRequestSerializer;\n\nimpl GetQueueAttributesRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetQueueAttributesRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.attribute_names {\n\n AttributeNameListSerializer::serialize(\n\n params,\n\n &format!(\"{}{}\", prefix, \"AttributeName\"),\n\n field_value,\n\n );\n\n }\n\n params.put(&format!(\"{}{}\", prefix, \"QueueUrl\"), &obj.queue_url);\n\n }\n\n}\n\n\n\n/// <p>A list of returned queue attributes.</p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetQueueAttributesResult {\n\n /// <p>A map of attributes to their respective values.</p>\n\n pub attributes: Option<::std::collections::HashMap<String, String>>,\n\n}\n\n\n", "file_path": "rusoto/services/sqs/src/generated.rs", "rank": 73, "score": 193123.1939405792 }, { "content": "/// Serialize `GetLoginProfileRequest` contents to a `SignedRequest`.\n\nstruct GetLoginProfileRequestSerializer;\n\nimpl GetLoginProfileRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetLoginProfileRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(&format!(\"{}{}\", prefix, \"UserName\"), &obj.user_name);\n\n }\n\n}\n\n\n\n/// <p>Contains the response to a successful <a>GetLoginProfile</a> request. </p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetLoginProfileResponse {\n\n /// <p>A structure containing the user name and password create date for the user.</p>\n\n pub login_profile: LoginProfile,\n\n}\n\n\n", "file_path": "rusoto/services/iam/src/generated.rs", "rank": 74, "score": 193123.1939405792 }, { "content": "/// Serialize `GetQueueUrlRequest` contents to a `SignedRequest`.\n\nstruct GetQueueUrlRequestSerializer;\n\nimpl GetQueueUrlRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetQueueUrlRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(&format!(\"{}{}\", prefix, \"QueueName\"), &obj.queue_name);\n\n if let Some(ref field_value) = obj.queue_owner_aws_account_id {\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"QueueOwnerAWSAccountId\"),\n\n &field_value,\n\n );\n\n }\n\n }\n\n}\n\n\n\n/// <p>For more information, see <a href=\"https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-api-responses.html\">Interpreting Responses</a> in the <i>Amazon Simple Queue Service Developer Guide</i>.</p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetQueueUrlResult {\n\n /// <p>The URL of the queue.</p>\n\n pub queue_url: Option<String>,\n\n}\n\n\n", "file_path": "rusoto/services/sqs/src/generated.rs", "rank": 75, "score": 193123.1939405792 }, { "content": "/// Serialize `GetPasswordDataRequest` contents to a `SignedRequest`.\n\nstruct GetPasswordDataRequestSerializer;\n\nimpl GetPasswordDataRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetPasswordDataRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.dry_run {\n\n params.put(&format!(\"{}{}\", prefix, \"DryRun\"), &field_value);\n\n }\n\n params.put(&format!(\"{}{}\", prefix, \"InstanceId\"), &obj.instance_id);\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetPasswordDataResult {\n\n /// <p>The ID of the Windows instance.</p>\n\n pub instance_id: Option<String>,\n\n /// <p>The password of the instance. Returns an empty string if the password is not available.</p>\n\n pub password_data: Option<String>,\n\n /// <p>The time the data was last updated.</p>\n\n pub timestamp: Option<String>,\n\n}\n\n\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 76, "score": 193123.1939405792 }, { "content": "/// Serialize `GetConsoleScreenshotRequest` contents to a `SignedRequest`.\n\nstruct GetConsoleScreenshotRequestSerializer;\n\nimpl GetConsoleScreenshotRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetConsoleScreenshotRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.dry_run {\n\n params.put(&format!(\"{}{}\", prefix, \"DryRun\"), &field_value);\n\n }\n\n params.put(&format!(\"{}{}\", prefix, \"InstanceId\"), &obj.instance_id);\n\n if let Some(ref field_value) = obj.wake_up {\n\n params.put(&format!(\"{}{}\", prefix, \"WakeUp\"), &field_value);\n\n }\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetConsoleScreenshotResult {\n\n /// <p>The data that comprises the image.</p>\n\n pub image_data: Option<String>,\n\n /// <p>The ID of the instance.</p>\n\n pub instance_id: Option<String>,\n\n}\n\n\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 77, "score": 193123.1939405792 }, { "content": "/// Serialize `GetConsoleOutputRequest` contents to a `SignedRequest`.\n\nstruct GetConsoleOutputRequestSerializer;\n\nimpl GetConsoleOutputRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetConsoleOutputRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.dry_run {\n\n params.put(&format!(\"{}{}\", prefix, \"DryRun\"), &field_value);\n\n }\n\n params.put(&format!(\"{}{}\", prefix, \"InstanceId\"), &obj.instance_id);\n\n if let Some(ref field_value) = obj.latest {\n\n params.put(&format!(\"{}{}\", prefix, \"Latest\"), &field_value);\n\n }\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetConsoleOutputResult {\n\n /// <p>The ID of the instance.</p>\n\n pub instance_id: Option<String>,\n\n /// <p>The console output, base64-encoded. If you are using a command line tool, the tool decodes the output for you.</p>\n\n pub output: Option<String>,\n\n /// <p>The time at which the output was last updated.</p>\n\n pub timestamp: Option<String>,\n\n}\n\n\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 78, "score": 193123.1939405792 }, { "content": "/// Serialize `GetFederationTokenRequest` contents to a `SignedRequest`.\n\nstruct GetFederationTokenRequestSerializer;\n\nimpl GetFederationTokenRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetFederationTokenRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.duration_seconds {\n\n params.put(&format!(\"{}{}\", prefix, \"DurationSeconds\"), &field_value);\n\n }\n\n params.put(&format!(\"{}{}\", prefix, \"Name\"), &obj.name);\n\n if let Some(ref field_value) = obj.policy {\n\n params.put(&format!(\"{}{}\", prefix, \"Policy\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.policy_arns {\n\n PolicyDescriptorListTypeSerializer::serialize(\n\n params,\n\n &format!(\"{}{}\", prefix, \"PolicyArns\"),\n\n field_value,\n", "file_path": "rusoto/services/sts/src/generated.rs", "rank": 79, "score": 193123.1939405792 }, { "content": "/// Serialize `GetIdentityPoliciesRequest` contents to a `SignedRequest`.\n\nstruct GetIdentityPoliciesRequestSerializer;\n\nimpl GetIdentityPoliciesRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetIdentityPoliciesRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(&format!(\"{}{}\", prefix, \"Identity\"), &obj.identity);\n\n PolicyNameListSerializer::serialize(\n\n params,\n\n &format!(\"{}{}\", prefix, \"PolicyNames\"),\n\n &obj.policy_names,\n\n );\n\n }\n\n}\n\n\n\n/// <p>Represents the requested sending authorization policies.</p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetIdentityPoliciesResponse {\n\n /// <p>A map of policy names to policies.</p>\n\n pub policies: ::std::collections::HashMap<String, String>,\n\n}\n\n\n", "file_path": "rusoto/services/ses/src/generated.rs", "rank": 80, "score": 193123.1939405792 }, { "content": "/// Serialize `GetRolePolicyRequest` contents to a `SignedRequest`.\n\nstruct GetRolePolicyRequestSerializer;\n\nimpl GetRolePolicyRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetRolePolicyRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(&format!(\"{}{}\", prefix, \"PolicyName\"), &obj.policy_name);\n\n params.put(&format!(\"{}{}\", prefix, \"RoleName\"), &obj.role_name);\n\n }\n\n}\n\n\n\n/// <p>Contains the response to a successful <a>GetRolePolicy</a> request. </p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetRolePolicyResponse {\n\n /// <p>The policy document.</p> <p>IAM stores policies in JSON format. However, resources that were created using AWS CloudFormation templates can be formatted in YAML. AWS CloudFormation always converts a YAML policy to JSON format before submitting it to IAM.</p>\n\n pub policy_document: String,\n\n /// <p>The name of the policy.</p>\n\n pub policy_name: String,\n\n /// <p>The role the policy is associated with.</p>\n\n pub role_name: String,\n\n}\n\n\n", "file_path": "rusoto/services/iam/src/generated.rs", "rank": 81, "score": 193123.1939405792 }, { "content": "/// Serialize `GetCallerIdentityRequest` contents to a `SignedRequest`.\n\nstruct GetCallerIdentityRequestSerializer;\n\nimpl GetCallerIdentityRequestSerializer {\n\n fn serialize(_params: &mut Params, name: &str, _obj: &GetCallerIdentityRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n }\n\n}\n\n\n\n/// <p>Contains the response to a successful <a>GetCallerIdentity</a> request, including information about the entity making the request.</p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetCallerIdentityResponse {\n\n /// <p>The AWS account ID number of the account that owns or contains the calling entity.</p>\n\n pub account: Option<String>,\n\n /// <p>The AWS ARN associated with the calling entity.</p>\n\n pub arn: Option<String>,\n\n /// <p>The unique identifier of the calling entity. The exact value depends on the type of entity that is making the call. The values returned are those listed in the <b>aws:userid</b> column in the <a href=\"https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html#principaltable\">Principal table</a> found on the <b>Policy Variables</b> reference page in the <i>IAM User Guide</i>.</p>\n\n pub user_id: Option<String>,\n\n}\n\n\n", "file_path": "rusoto/services/sts/src/generated.rs", "rank": 82, "score": 193123.1939405792 }, { "content": "/// Serialize `GetUserPolicyRequest` contents to a `SignedRequest`.\n\nstruct GetUserPolicyRequestSerializer;\n\nimpl GetUserPolicyRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &GetUserPolicyRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(&format!(\"{}{}\", prefix, \"PolicyName\"), &obj.policy_name);\n\n params.put(&format!(\"{}{}\", prefix, \"UserName\"), &obj.user_name);\n\n }\n\n}\n\n\n\n/// <p>Contains the response to a successful <a>GetUserPolicy</a> request. </p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct GetUserPolicyResponse {\n\n /// <p>The policy document.</p> <p>IAM stores policies in JSON format. However, resources that were created using AWS CloudFormation templates can be formatted in YAML. AWS CloudFormation always converts a YAML policy to JSON format before submitting it to IAM.</p>\n\n pub policy_document: String,\n\n /// <p>The name of the policy.</p>\n\n pub policy_name: String,\n\n /// <p>The user the policy is associated with.</p>\n\n pub user_name: String,\n\n}\n\n\n", "file_path": "rusoto/services/iam/src/generated.rs", "rank": 83, "score": 193123.1939405792 }, { "content": "/// Serialize `SendMessageBatchRequest` contents to a `SignedRequest`.\n\nstruct SendMessageBatchRequestSerializer;\n\nimpl SendMessageBatchRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &SendMessageBatchRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n SendMessageBatchRequestEntryListSerializer::serialize(\n\n params,\n\n &format!(\"{}{}\", prefix, \"SendMessageBatchRequestEntry\"),\n\n &obj.entries,\n\n );\n\n params.put(&format!(\"{}{}\", prefix, \"QueueUrl\"), &obj.queue_url);\n\n }\n\n}\n\n\n\n/// <p>Contains the details of a single Amazon SQS message along with an <code>Id</code>.</p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"deserialize_structs\", derive(Deserialize))]\n", "file_path": "rusoto/services/sqs/src/generated.rs", "rank": 84, "score": 193091.84479248163 }, { "content": "/// Serialize `DecodeAuthorizationMessageRequest` contents to a `SignedRequest`.\n\nstruct DecodeAuthorizationMessageRequestSerializer;\n\nimpl DecodeAuthorizationMessageRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &DecodeAuthorizationMessageRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"EncodedMessage\"),\n\n &obj.encoded_message,\n\n );\n\n }\n\n}\n\n\n\n/// <p>A document that contains additional information about the authorization status of a request from an encoded message that is returned in response to an AWS request.</p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct DecodeAuthorizationMessageResponse {\n\n /// <p>An XML document that contains the decoded message.</p>\n\n pub decoded_message: Option<String>,\n\n}\n\n\n", "file_path": "rusoto/services/sts/src/generated.rs", "rank": 85, "score": 193091.84479248163 }, { "content": "/// Serialize `DeleteMessageBatchRequest` contents to a `SignedRequest`.\n\nstruct DeleteMessageBatchRequestSerializer;\n\nimpl DeleteMessageBatchRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &DeleteMessageBatchRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n DeleteMessageBatchRequestEntryListSerializer::serialize(\n\n params,\n\n &format!(\"{}{}\", prefix, \"DeleteMessageBatchRequestEntry\"),\n\n &obj.entries,\n\n );\n\n params.put(&format!(\"{}{}\", prefix, \"QueueUrl\"), &obj.queue_url);\n\n }\n\n}\n\n\n\n/// <p>Encloses a receipt handle and an identifier for it.</p>\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"deserialize_structs\", derive(Deserialize))]\n\npub struct DeleteMessageBatchRequestEntry {\n\n /// <p><p>An identifier for this particular receipt handle. This is used to communicate the result.</p> <note> <p>The <code>Id</code>s of a batch request need to be unique within a request</p> </note></p>\n\n pub id: String,\n\n /// <p>A receipt handle.</p>\n\n pub receipt_handle: String,\n\n}\n\n\n", "file_path": "rusoto/services/sqs/src/generated.rs", "rank": 86, "score": 193091.84479248163 }, { "content": "/// Serialize `ChangeMessageVisibilityRequest` contents to a `SignedRequest`.\n\nstruct ChangeMessageVisibilityRequestSerializer;\n\nimpl ChangeMessageVisibilityRequestSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &ChangeMessageVisibilityRequest) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(&format!(\"{}{}\", prefix, \"QueueUrl\"), &obj.queue_url);\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"ReceiptHandle\"),\n\n &obj.receipt_handle,\n\n );\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"VisibilityTimeout\"),\n\n &obj.visibility_timeout,\n\n );\n\n }\n\n}\n\n\n", "file_path": "rusoto/services/sqs/src/generated.rs", "rank": 87, "score": 193091.84479248163 }, { "content": "// cargo runs tests in parallel, which leads to race conditions when changing environment\n\n// variables. Therefore we use a global mutex for all tests which rely on environment variables.\n\n//\n\n// As failed (panic) tests will poison the global mutex, we use a helper which recovers from\n\n// poisoned mutex.\n\n//\n\n// The first time the helper is called it stores the original environment. If the lock is poisoned,\n\n// the environment is reset to the original state.\n\npub fn lock_env() -> MutexGuard<'static, ()> {\n\n lazy_static! {\n\n static ref ENV_MUTEX: Mutex<()> = Mutex::new(());\n\n static ref ORIGINAL_ENVIRONMENT: HashMap<OsString, OsString> =\n\n std::env::vars_os().collect();\n\n }\n\n\n\n let guard = ENV_MUTEX.lock();\n\n lazy_static::initialize(&ORIGINAL_ENVIRONMENT);\n\n match guard {\n\n Ok(guard) => guard,\n\n Err(poisoned) => {\n\n for (name, _) in std::env::vars_os() {\n\n if !ORIGINAL_ENVIRONMENT.contains_key(&name) {\n\n std::env::remove_var(name);\n\n }\n\n }\n\n for (name, value) in ORIGINAL_ENVIRONMENT.iter() {\n\n std::env::set_var(name, value);\n\n }\n\n poisoned.into_inner()\n\n }\n\n }\n\n}\n", "file_path": "rusoto/credential/src/test_utils.rs", "rank": 88, "score": 191667.08922580152 }, { "content": "fn generate_member_format_string(member_name: &str, member: &Member) -> Option<String> {\n\n match member.location {\n\n Some(ref x) if x == \"uri\" => match member.location_name {\n\n Some(ref loc_name) => Some(format!(\n\n \"{member_name} = input.{field_name}\",\n\n field_name = member_name,\n\n member_name = loc_name.to_snake_case(),\n\n )),\n\n None => Some(format!(\n\n \"{member_name} = input.{field_name}\",\n\n field_name = member_name,\n\n member_name = member_name.to_snake_case(),\n\n )),\n\n },\n\n Some(_) | None => None,\n\n }\n\n}\n\n\n", "file_path": "service_crategen/src/commands/generate/codegen/rest_request_generator.rs", "rank": 89, "score": 191660.71559430673 }, { "content": "/// consume an `EndElement` with a specific name or throw an `XmlParseError`\n\npub fn end_element<T: Peek + Next>(element_name: &str, stack: &mut T) -> Result<(), XmlParseError> {\n\n let next = stack.next();\n\n if let Some(Ok(XmlEvent::EndElement { name, .. })) = next {\n\n if name.local_name == element_name {\n\n Ok(())\n\n } else {\n\n Err(XmlParseError::new(&format!(\n\n \"END Expected {} got {}\",\n\n element_name, name.local_name\n\n )))\n\n }\n\n } else {\n\n Err(XmlParseError::new(&format!(\n\n \"Expected EndElement {} got {:?}\",\n\n element_name, next\n\n )))\n\n }\n\n}\n\n\n", "file_path": "rusoto/core/src/proto/xml/util.rs", "rank": 90, "score": 190691.594196751 }, { "content": "/// return a string field with the right name or throw a parse error\n\npub fn string_field<T: Peek + Next>(name: &str, stack: &mut T) -> Result<String, XmlParseError> {\n\n start_element(name, stack)?;\n\n let value = characters(stack)?;\n\n end_element(name, stack)?;\n\n Ok(value)\n\n}\n\n\n", "file_path": "rusoto/core/src/proto/xml/util.rs", "rank": 91, "score": 188894.69462953496 }, { "content": "#[allow(dead_code)]\n\nstruct GetEbsEncryptionByDefaultResultDeserializer;\n\nimpl GetEbsEncryptionByDefaultResultDeserializer {\n\n #[allow(dead_code, unused_variables)]\n\n fn deserialize<T: Peek + Next>(\n\n tag_name: &str,\n\n stack: &mut T,\n\n ) -> Result<GetEbsEncryptionByDefaultResult, XmlParseError> {\n\n deserialize_elements::<_, GetEbsEncryptionByDefaultResult, _>(\n\n tag_name,\n\n stack,\n\n |name, stack, obj| {\n\n match name {\n\n \"ebsEncryptionByDefault\" => {\n\n obj.ebs_encryption_by_default = Some(BooleanDeserializer::deserialize(\n\n \"ebsEncryptionByDefault\",\n\n stack,\n\n )?);\n\n }\n\n _ => skip_tree(stack),\n\n }\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 92, "score": 188521.06192404736 }, { "content": "#[allow(dead_code)]\n\nstruct GetDefaultCreditSpecificationResultDeserializer;\n\nimpl GetDefaultCreditSpecificationResultDeserializer {\n\n #[allow(dead_code, unused_variables)]\n\n fn deserialize<T: Peek + Next>(\n\n tag_name: &str,\n\n stack: &mut T,\n\n ) -> Result<GetDefaultCreditSpecificationResult, XmlParseError> {\n\n deserialize_elements::<_, GetDefaultCreditSpecificationResult, _>(\n\n tag_name,\n\n stack,\n\n |name, stack, obj| {\n\n match name {\n\n \"instanceFamilyCreditSpecification\" => {\n\n obj.instance_family_credit_specification =\n\n Some(InstanceFamilyCreditSpecificationDeserializer::deserialize(\n\n \"instanceFamilyCreditSpecification\",\n\n stack,\n\n )?);\n\n }\n\n _ => skip_tree(stack),\n", "file_path": "rusoto/services/ec2/src/generated.rs", "rank": 93, "score": 188521.06192404736 }, { "content": "/// Serialize `DescribeEngineDefaultParametersMessage` contents to a `SignedRequest`.\n\nstruct DescribeEngineDefaultParametersMessageSerializer;\n\nimpl DescribeEngineDefaultParametersMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &DescribeEngineDefaultParametersMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"DBParameterGroupFamily\"),\n\n &obj.db_parameter_group_family,\n\n );\n\n if let Some(ref field_value) = obj.filters {\n\n FilterListSerializer::serialize(\n\n params,\n\n &format!(\"{}{}\", prefix, \"Filter\"),\n\n field_value,\n\n );\n\n }\n\n if let Some(ref field_value) = obj.marker {\n", "file_path": "rusoto/services/neptune/src/generated.rs", "rank": 94, "score": 188513.49290410616 }, { "content": "/// Serialize `DescribeDefaultClusterParametersMessage` contents to a `SignedRequest`.\n\nstruct DescribeDefaultClusterParametersMessageSerializer;\n\nimpl DescribeDefaultClusterParametersMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &DescribeDefaultClusterParametersMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.marker {\n\n params.put(&format!(\"{}{}\", prefix, \"Marker\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.max_records {\n\n params.put(&format!(\"{}{}\", prefix, \"MaxRecords\"), &field_value);\n\n }\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"ParameterGroupFamily\"),\n\n &obj.parameter_group_family,\n\n );\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct DescribeDefaultClusterParametersResult {\n\n pub default_cluster_parameters: Option<DefaultClusterParameters>,\n\n}\n\n\n", "file_path": "rusoto/services/redshift/src/generated.rs", "rank": 95, "score": 188513.49290410616 }, { "content": "/// Serialize `DescribeEngineDefaultParametersMessage` contents to a `SignedRequest`.\n\nstruct DescribeEngineDefaultParametersMessageSerializer;\n\nimpl DescribeEngineDefaultParametersMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &DescribeEngineDefaultParametersMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"CacheParameterGroupFamily\"),\n\n &obj.cache_parameter_group_family,\n\n );\n\n if let Some(ref field_value) = obj.marker {\n\n params.put(&format!(\"{}{}\", prefix, \"Marker\"), &field_value);\n\n }\n\n if let Some(ref field_value) = obj.max_records {\n\n params.put(&format!(\"{}{}\", prefix, \"MaxRecords\"), &field_value);\n\n }\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct DescribeEngineDefaultParametersResult {\n\n pub engine_defaults: Option<EngineDefaults>,\n\n}\n\n\n", "file_path": "rusoto/services/elasticache/src/generated.rs", "rank": 96, "score": 188513.49290410616 }, { "content": "/// Serialize `DescribeEngineDefaultParametersMessage` contents to a `SignedRequest`.\n\nstruct DescribeEngineDefaultParametersMessageSerializer;\n\nimpl DescribeEngineDefaultParametersMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &DescribeEngineDefaultParametersMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"DBParameterGroupFamily\"),\n\n &obj.db_parameter_group_family,\n\n );\n\n if let Some(ref field_value) = obj.filters {\n\n FilterListSerializer::serialize(\n\n params,\n\n &format!(\"{}{}\", prefix, \"Filter\"),\n\n field_value,\n\n );\n\n }\n\n if let Some(ref field_value) = obj.marker {\n", "file_path": "rusoto/services/rds/src/generated.rs", "rank": 97, "score": 188513.49290410616 }, { "content": "/// Serialize `SwapEnvironmentCNAMEsMessage` contents to a `SignedRequest`.\n\nstruct SwapEnvironmentCNAMEsMessageSerializer;\n\nimpl SwapEnvironmentCNAMEsMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &SwapEnvironmentCNAMEsMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n if let Some(ref field_value) = obj.destination_environment_id {\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"DestinationEnvironmentId\"),\n\n &field_value,\n\n );\n\n }\n\n if let Some(ref field_value) = obj.destination_environment_name {\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"DestinationEnvironmentName\"),\n\n &field_value,\n\n );\n\n }\n", "file_path": "rusoto/services/elasticbeanstalk/src/generated.rs", "rank": 98, "score": 188513.2620376477 }, { "content": "/// Serialize `CreateHsmClientCertificateMessage` contents to a `SignedRequest`.\n\nstruct CreateHsmClientCertificateMessageSerializer;\n\nimpl CreateHsmClientCertificateMessageSerializer {\n\n fn serialize(params: &mut Params, name: &str, obj: &CreateHsmClientCertificateMessage) {\n\n let mut prefix = name.to_string();\n\n if prefix != \"\" {\n\n prefix.push_str(\".\");\n\n }\n\n\n\n params.put(\n\n &format!(\"{}{}\", prefix, \"HsmClientCertificateIdentifier\"),\n\n &obj.hsm_client_certificate_identifier,\n\n );\n\n if let Some(ref field_value) = obj.tags {\n\n TagListSerializer::serialize(params, &format!(\"{}{}\", prefix, \"Tag\"), field_value);\n\n }\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize_structs\", derive(Serialize))]\n\npub struct CreateHsmClientCertificateResult {\n\n pub hsm_client_certificate: Option<HsmClientCertificate>,\n\n}\n\n\n", "file_path": "rusoto/services/redshift/src/generated.rs", "rank": 99, "score": 188510.5162286908 } ]
Rust
prost-derive/src/lib.rs
Max-Meldrum/prost
6f3c60f136be096194a3c6e0e77e25a9e1356669
#![doc(html_root_url = "https://docs.rs/prost-derive/0.6.1")] #![recursion_limit = "4096"] extern crate proc_macro; use anyhow::bail; use quote::quote; use anyhow::Error; use itertools::Itertools; use proc_macro::TokenStream; use proc_macro2::Span; use syn::{ punctuated::Punctuated, Data, DataEnum, DataStruct, DeriveInput, Expr, Fields, FieldsNamed, FieldsUnnamed, Ident, Variant, }; mod field; use crate::field::Field; fn try_message(input: TokenStream) -> Result<TokenStream, Error> { let input: DeriveInput = syn::parse(input)?; let ident = input.ident; let variant_data = match input.data { Data::Struct(variant_data) => variant_data, Data::Enum(..) => bail!("Message can not be derived for an enum"), Data::Union(..) => bail!("Message can not be derived for a union"), }; if !input.generics.params.is_empty() || input.generics.where_clause.is_some() { bail!("Message may not be derived for generic type"); } let fields = match variant_data { DataStruct { fields: Fields::Named(FieldsNamed { named: fields, .. }), .. } | DataStruct { fields: Fields::Unnamed(FieldsUnnamed { unnamed: fields, .. }), .. } => fields.into_iter().collect(), DataStruct { fields: Fields::Unit, .. } => Vec::new(), }; let mut next_tag: u32 = 1; let mut fields = fields .into_iter() .enumerate() .flat_map(|(idx, field)| { let field_ident = field .ident .unwrap_or_else(|| Ident::new(&idx.to_string(), Span::call_site())); match Field::new(field.attrs, Some(next_tag)) { Ok(Some(field)) => { next_tag = field.tags().iter().max().map(|t| t + 1).unwrap_or(next_tag); Some(Ok((field_ident, field))) } Ok(None) => None, Err(err) => Some(Err( err.context(format!("invalid message field {}.{}", ident, field_ident)) )), } }) .collect::<Result<Vec<_>, _>>()?; let unsorted_fields = fields.clone(); fields.sort_by_key(|&(_, ref field)| field.tags().into_iter().min().unwrap()); let fields = fields; let mut tags = fields .iter() .flat_map(|&(_, ref field)| field.tags()) .collect::<Vec<_>>(); let num_tags = tags.len(); tags.sort(); tags.dedup(); if tags.len() != num_tags { bail!("message {} has fields with duplicate tags", ident); } let encoded_len = fields .iter() .map(|&(ref field_ident, ref field)| field.encoded_len(quote!(self.#field_ident))); let encode = fields .iter() .map(|&(ref field_ident, ref field)| field.encode(quote!(self.#field_ident))); let merge = fields.iter().map(|&(ref field_ident, ref field)| { let merge = field.merge(quote!(value)); let tags = field .tags() .into_iter() .map(|tag| quote!(#tag)) .intersperse(quote!(|)); quote! { #(#tags)* => { let mut value = &mut self.#field_ident; #merge.map_err(|mut error| { error.push(STRUCT_NAME, stringify!(#field_ident)); error }) }, } }); let struct_name = if fields.is_empty() { quote!() } else { quote!( const STRUCT_NAME: &'static str = stringify!(#ident); ) }; let is_struct = true; let clear = fields .iter() .map(|&(ref field_ident, ref field)| field.clear(quote!(self.#field_ident))); let default = fields.iter().map(|&(ref field_ident, ref field)| { let value = field.default(); quote!(#field_ident: #value,) }); let methods = fields .iter() .flat_map(|&(ref field_ident, ref field)| field.methods(field_ident)) .collect::<Vec<_>>(); let methods = if methods.is_empty() { quote!() } else { quote! { #[allow(dead_code)] impl #ident { #(#methods)* } } }; let debugs = unsorted_fields.iter().map(|&(ref field_ident, ref field)| { let wrapper = field.debug(quote!(self.#field_ident)); let call = if is_struct { quote!(builder.field(stringify!(#field_ident), &wrapper)) } else { quote!(builder.field(&wrapper)) }; quote! { let builder = { let wrapper = #wrapper; #call }; } }); let debug_builder = if is_struct { quote!(f.debug_struct(stringify!(#ident))) } else { quote!(f.debug_tuple(stringify!(#ident))) }; let expanded = quote! { impl ::prost::Message for #ident { #[allow(unused_variables)] fn encode_raw<B>(&self, buf: &mut B) where B: ::prost::bytes::BufMut { #(#encode)* } #[allow(unused_variables)] fn merge_field<B>( &mut self, tag: u32, wire_type: ::prost::encoding::WireType, buf: &mut B, ctx: ::prost::encoding::DecodeContext, ) -> ::std::result::Result<(), ::prost::DecodeError> where B: ::prost::bytes::Buf { #struct_name match tag { #(#merge)* _ => ::prost::encoding::skip_field(wire_type, tag, buf, ctx), } } #[inline] fn encoded_len(&self) -> usize { 0 #(+ #encoded_len)* } fn clear(&mut self) { #(#clear;)* } } impl Default for #ident { fn default() -> #ident { #ident { #(#default)* } } } impl ::std::fmt::Debug for #ident { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let mut builder = #debug_builder; #(#debugs;)* builder.finish() } } #methods }; Ok(expanded.into()) } #[proc_macro_derive(Message, attributes(prost))] pub fn message(input: TokenStream) -> TokenStream { try_message(input).unwrap() } fn try_enumeration(input: TokenStream) -> Result<TokenStream, Error> { let input: DeriveInput = syn::parse(input)?; let ident = input.ident; if !input.generics.params.is_empty() || input.generics.where_clause.is_some() { bail!("Message may not be derived for generic type"); } let punctuated_variants = match input.data { Data::Enum(DataEnum { variants, .. }) => variants, Data::Struct(_) => bail!("Enumeration can not be derived for a struct"), Data::Union(..) => bail!("Enumeration can not be derived for a union"), }; let mut variants: Vec<(Ident, Expr)> = Vec::new(); for Variant { ident, fields, discriminant, .. } in punctuated_variants { match fields { Fields::Unit => (), Fields::Named(_) | Fields::Unnamed(_) => { bail!("Enumeration variants may not have fields") } } match discriminant { Some((_, expr)) => variants.push((ident, expr)), None => bail!("Enumeration variants must have a disriminant"), } } if variants.is_empty() { panic!("Enumeration must have at least one variant"); } let default = variants[0].0.clone(); let is_valid = variants .iter() .map(|&(_, ref value)| quote!(#value => true)); let from = variants.iter().map( |&(ref variant, ref value)| quote!(#value => ::std::option::Option::Some(#ident::#variant)), ); let is_valid_doc = format!("Returns `true` if `value` is a variant of `{}`.", ident); let from_i32_doc = format!( "Converts an `i32` to a `{}`, or `None` if `value` is not a valid variant.", ident ); let expanded = quote! { impl #ident { #[doc=#is_valid_doc] pub fn is_valid(value: i32) -> bool { match value { #(#is_valid,)* _ => false, } } #[doc=#from_i32_doc] pub fn from_i32(value: i32) -> ::std::option::Option<#ident> { match value { #(#from,)* _ => ::std::option::Option::None, } } } impl ::std::default::Default for #ident { fn default() -> #ident { #ident::#default } } impl ::std::convert::From<#ident> for i32 { fn from(value: #ident) -> i32 { value as i32 } } }; Ok(expanded.into()) } #[proc_macro_derive(Enumeration, attributes(prost))] pub fn enumeration(input: TokenStream) -> TokenStream { try_enumeration(input).unwrap() } fn try_oneof(input: TokenStream) -> Result<TokenStream, Error> { let input: DeriveInput = syn::parse(input)?; let ident = input.ident; let variants = match input.data { Data::Enum(DataEnum { variants, .. }) => variants, Data::Struct(..) => bail!("Oneof can not be derived for a struct"), Data::Union(..) => bail!("Oneof can not be derived for a union"), }; if !input.generics.params.is_empty() || input.generics.where_clause.is_some() { bail!("Message may not be derived for generic type"); } let mut fields: Vec<(Ident, Field)> = Vec::new(); for Variant { attrs, ident: variant_ident, fields: variant_fields, .. } in variants { let variant_fields = match variant_fields { Fields::Unit => Punctuated::new(), Fields::Named(FieldsNamed { named: fields, .. }) | Fields::Unnamed(FieldsUnnamed { unnamed: fields, .. }) => fields, }; if variant_fields.len() != 1 { bail!("Oneof enum variants must have a single field"); } match Field::new_oneof(attrs)? { Some(field) => fields.push((variant_ident, field)), None => bail!("invalid oneof variant: oneof variants may not be ignored"), } } let mut tags = fields .iter() .flat_map(|&(ref variant_ident, ref field)| -> Result<u32, Error> { if field.tags().len() > 1 { bail!( "invalid oneof variant {}::{}: oneof variants may only have a single tag", ident, variant_ident ); } Ok(field.tags()[0]) }) .collect::<Vec<_>>(); tags.sort(); tags.dedup(); if tags.len() != fields.len() { panic!("invalid oneof {}: variants have duplicate tags", ident); } let encode = fields.iter().map(|&(ref variant_ident, ref field)| { let encode = field.encode(quote!(*value)); quote!(#ident::#variant_ident(ref value) => { #encode }) }); let merge = fields.iter().map(|&(ref variant_ident, ref field)| { let tag = field.tags()[0]; let merge = field.merge(quote!(value)); quote! { #tag => { match field { ::std::option::Option::Some(#ident::#variant_ident(ref mut value)) => { #merge }, _ => { let mut owned_value = ::std::default::Default::default(); let value = &mut owned_value; #merge.map(|_| *field = ::std::option::Option::Some(#ident::#variant_ident(owned_value))) }, } } } }); let encoded_len = fields.iter().map(|&(ref variant_ident, ref field)| { let encoded_len = field.encoded_len(quote!(*value)); quote!(#ident::#variant_ident(ref value) => #encoded_len) }); let debug = fields.iter().map(|&(ref variant_ident, ref field)| { let wrapper = field.debug(quote!(*value)); quote!(#ident::#variant_ident(ref value) => { let wrapper = #wrapper; f.debug_tuple(stringify!(#variant_ident)) .field(&wrapper) .finish() }) }); let expanded = quote! { impl #ident { pub fn encode<B>(&self, buf: &mut B) where B: ::prost::bytes::BufMut { match *self { #(#encode,)* } } pub fn merge<B>( field: &mut ::std::option::Option<#ident>, tag: u32, wire_type: ::prost::encoding::WireType, buf: &mut B, ctx: ::prost::encoding::DecodeContext, ) -> ::std::result::Result<(), ::prost::DecodeError> where B: ::prost::bytes::Buf { match tag { #(#merge,)* _ => unreachable!(concat!("invalid ", stringify!(#ident), " tag: {}"), tag), } } #[inline] pub fn encoded_len(&self) -> usize { match *self { #(#encoded_len,)* } } } impl ::std::fmt::Debug for #ident { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { #(#debug,)* } } } }; Ok(expanded.into()) } #[proc_macro_derive(Oneof, attributes(prost))] pub fn oneof(input: TokenStream) -> TokenStream { try_oneof(input).unwrap() }
#![doc(html_root_url = "https://docs.rs/prost-derive/0.6.1")] #![recursion_limit = "4096"] extern crate proc_macro; use anyhow::bail; use quote::quote; use anyhow::Error; use itertools::Itertools; use proc_macro::TokenStream; use proc_macro2::Span; use syn::{ punctuated::Punctuated, Data, DataEnum, DataStruct, DeriveInput, Expr, Fields, FieldsNamed, FieldsUnnamed, Ident, Variant, }; mod field; use crate::field::Field; fn try_message(input: TokenStream) -> Result<TokenStream, Error> { let input: DeriveInput = syn::parse(input)?; let ident = input.ident; let variant_data = match input.data { Data::Struct(variant_data) => variant_data, Data::Enum(..) => bail!("Message can not be derived for an enum"), Data::Union(..) => bail!("Message can not be derived for a union"), }; if !input.generics.params.is_empty() || input.generics.where_clause.is_some() { bail!("Message may not be derived for generic type"); } let fields = match variant_data { DataStruct { fields: Fields::Named(FieldsNamed { named: fields, .. }), .. } | DataStruct { fields: Fields::Unnamed(FieldsUnnamed { unnamed: fields, .. }), .. } => fields.into_iter().collect(), DataStruct { fields: Fields::Unit, .. } => Vec::new(), }; let mut next_tag: u32 = 1; let mut fields = fields .into_iter() .enumerate() .flat_map(|(idx, field)| { let field_ident = field .ident .unwrap_or_else(|| Ident::new(&idx.to_string(), Span::call_site())); match Field::new(field.attrs, Some(next_tag)) { Ok(Some(field)) => { next_tag = field.tags().iter().max().map(|t| t + 1).unwrap_or(next_tag); Some(Ok((field_ident, field))) } Ok(None) => None, Err(err) => Some(Err( err.context(format!("invalid message field {}.{}", ident, field_ident)) )), } }) .collect::<Result<Vec<_>, _>>()?; let unsorted_fields = fields.clone(); fields.sort_by_key(|&(_, ref field)| field.tags().into_iter().min().unwrap()); let fields = fields; let mut tags = fields .iter() .flat_map(|&(_, ref field)| field.tags()) .collect::<Vec<_>>(); let num_tags = tags.len(); tags.sort(); tags.dedup(); if tags.len() != num_tags { bail!("message {} has fields with duplicate tags", ident); } let encoded_len = fields .iter() .map(|&(ref field_ident, ref field)| field.encoded_len(quote!(self.#field_ident))); let encode = fields .iter() .map(|&(ref field_ident, ref field)| field.encode(quote!(self.#field_ident))); let merge = fields.iter().map(|&(ref field_ident, ref field)| { let merge = field.merge(quote!(value)); let tags = field .tags() .into_iter() .map(|tag| quote!(#tag)) .intersperse(quote!(|)); quote! { #(#tags)* => { let mut value = &mut self.#field_ident; #merge.map_err(|mut error| { error.push(STRUCT_NAME, stringify!(#field_ident)); error }) }, } }); let struct_name = if fields.is_empty() { quote!() } else { quote!( const STRUCT_NAME: &'static str = stringify!(#ident); ) }; let is_struct = true; let clear = fields .iter() .map(|&(ref field_ident, ref field)| field.clear(quote!(self.#field_ident))); let default = fields.iter().map(|&(ref field_ident, ref field)| { let value = field.default(); quote!(#field_ident: #value,) }); let methods = fields .iter() .flat_map(|&(ref field_ident, ref field)| field.methods(field_ident)) .collect::<Vec<_>>(); let methods = if methods.is_empty() { quote!() } else { quote! { #[allow(dead_code)] impl #ident { #(#methods)* } } }; let debugs = unsorted_fields.iter().map(|&(ref field_ident, ref field)| { let wrapper = field.debug(quote!(self.#field_ident)); let call = if is_struct { quote!(builder.field(stringify!(#field_ident), &wrapper)) } else { quote!(builder.field(&wrapper)) }; quote! { let builder = { let wrapper = #wrapper; #call }; } }); let debug_builder = if is_struct { quote!(f.debug_struct(stringify!(#ident))) } else { quote!(f.debug_tuple(stringify!(#ident))) }; let expanded = quote! { impl ::prost::Message for #ident { #[allow(unused_variables)] fn encode_raw<B>(&self, buf: &mut B) where B: ::prost::bytes::BufMut { #(#encode)* } #[allow(unused_variables)] fn merge_field<B>( &mut self, tag: u32, wire_type: ::prost::encoding::WireType, buf: &mut B, ctx: ::prost::encoding::DecodeContext, ) -> ::std::result::Result<(), ::prost::DecodeError> where B: ::prost::bytes::Buf { #struct_name match tag { #(#merge)* _ => ::prost::encoding::skip_field(wire_type, tag, buf, ctx), } } #[inline] fn encoded_len(&self) -> usize { 0 #(+ #encoded_len)* } fn clear(&mut self) { #(#clear;)* } } impl Default for #ident { fn default() -> #ident { #ident { #(#default)* } } } impl ::std::fmt::Debug for #ident { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let mut builder = #debug_builder; #(#debugs;)* builder.finish() } } #methods }; Ok(expanded.into()) } #[proc_macro_derive(Message, attributes(prost))] pub fn message(input: TokenStream) -> TokenStream { try_message(input).unwrap() } fn try_enumeration(input: TokenStream) -> Result<TokenStream, Error> { let input: DeriveInput = syn::parse(input)?; let ident = input.ident; if !input.generics.params.is_empty() || input.generics.where_clause.is_some() { bail!("Message may not be derived for generic type"); } let punctuated_variants = match input.data { Data::Enum(DataEnum { variants, .. }) => variants, Data::Struct(_) => bail!("Enumeration can not be derived for a struct"), Data::Union(..) => bail!("Enumeration can not be derived for a union"), }; let mut variants: Vec<(Ident, Expr)> = Vec::new(); for Variant { ident, fields, discriminant, .. } in punctuated_var
_doc = format!("Returns `true` if `value` is a variant of `{}`.", ident); let from_i32_doc = format!( "Converts an `i32` to a `{}`, or `None` if `value` is not a valid variant.", ident ); let expanded = quote! { impl #ident { #[doc=#is_valid_doc] pub fn is_valid(value: i32) -> bool { match value { #(#is_valid,)* _ => false, } } #[doc=#from_i32_doc] pub fn from_i32(value: i32) -> ::std::option::Option<#ident> { match value { #(#from,)* _ => ::std::option::Option::None, } } } impl ::std::default::Default for #ident { fn default() -> #ident { #ident::#default } } impl ::std::convert::From<#ident> for i32 { fn from(value: #ident) -> i32 { value as i32 } } }; Ok(expanded.into()) } #[proc_macro_derive(Enumeration, attributes(prost))] pub fn enumeration(input: TokenStream) -> TokenStream { try_enumeration(input).unwrap() } fn try_oneof(input: TokenStream) -> Result<TokenStream, Error> { let input: DeriveInput = syn::parse(input)?; let ident = input.ident; let variants = match input.data { Data::Enum(DataEnum { variants, .. }) => variants, Data::Struct(..) => bail!("Oneof can not be derived for a struct"), Data::Union(..) => bail!("Oneof can not be derived for a union"), }; if !input.generics.params.is_empty() || input.generics.where_clause.is_some() { bail!("Message may not be derived for generic type"); } let mut fields: Vec<(Ident, Field)> = Vec::new(); for Variant { attrs, ident: variant_ident, fields: variant_fields, .. } in variants { let variant_fields = match variant_fields { Fields::Unit => Punctuated::new(), Fields::Named(FieldsNamed { named: fields, .. }) | Fields::Unnamed(FieldsUnnamed { unnamed: fields, .. }) => fields, }; if variant_fields.len() != 1 { bail!("Oneof enum variants must have a single field"); } match Field::new_oneof(attrs)? { Some(field) => fields.push((variant_ident, field)), None => bail!("invalid oneof variant: oneof variants may not be ignored"), } } let mut tags = fields .iter() .flat_map(|&(ref variant_ident, ref field)| -> Result<u32, Error> { if field.tags().len() > 1 { bail!( "invalid oneof variant {}::{}: oneof variants may only have a single tag", ident, variant_ident ); } Ok(field.tags()[0]) }) .collect::<Vec<_>>(); tags.sort(); tags.dedup(); if tags.len() != fields.len() { panic!("invalid oneof {}: variants have duplicate tags", ident); } let encode = fields.iter().map(|&(ref variant_ident, ref field)| { let encode = field.encode(quote!(*value)); quote!(#ident::#variant_ident(ref value) => { #encode }) }); let merge = fields.iter().map(|&(ref variant_ident, ref field)| { let tag = field.tags()[0]; let merge = field.merge(quote!(value)); quote! { #tag => { match field { ::std::option::Option::Some(#ident::#variant_ident(ref mut value)) => { #merge }, _ => { let mut owned_value = ::std::default::Default::default(); let value = &mut owned_value; #merge.map(|_| *field = ::std::option::Option::Some(#ident::#variant_ident(owned_value))) }, } } } }); let encoded_len = fields.iter().map(|&(ref variant_ident, ref field)| { let encoded_len = field.encoded_len(quote!(*value)); quote!(#ident::#variant_ident(ref value) => #encoded_len) }); let debug = fields.iter().map(|&(ref variant_ident, ref field)| { let wrapper = field.debug(quote!(*value)); quote!(#ident::#variant_ident(ref value) => { let wrapper = #wrapper; f.debug_tuple(stringify!(#variant_ident)) .field(&wrapper) .finish() }) }); let expanded = quote! { impl #ident { pub fn encode<B>(&self, buf: &mut B) where B: ::prost::bytes::BufMut { match *self { #(#encode,)* } } pub fn merge<B>( field: &mut ::std::option::Option<#ident>, tag: u32, wire_type: ::prost::encoding::WireType, buf: &mut B, ctx: ::prost::encoding::DecodeContext, ) -> ::std::result::Result<(), ::prost::DecodeError> where B: ::prost::bytes::Buf { match tag { #(#merge,)* _ => unreachable!(concat!("invalid ", stringify!(#ident), " tag: {}"), tag), } } #[inline] pub fn encoded_len(&self) -> usize { match *self { #(#encoded_len,)* } } } impl ::std::fmt::Debug for #ident { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { #(#debug,)* } } } }; Ok(expanded.into()) } #[proc_macro_derive(Oneof, attributes(prost))] pub fn oneof(input: TokenStream) -> TokenStream { try_oneof(input).unwrap() }
iants { match fields { Fields::Unit => (), Fields::Named(_) | Fields::Unnamed(_) => { bail!("Enumeration variants may not have fields") } } match discriminant { Some((_, expr)) => variants.push((ident, expr)), None => bail!("Enumeration variants must have a disriminant"), } } if variants.is_empty() { panic!("Enumeration must have at least one variant"); } let default = variants[0].0.clone(); let is_valid = variants .iter() .map(|&(_, ref value)| quote!(#value => true)); let from = variants.iter().map( |&(ref variant, ref value)| quote!(#value => ::std::option::Option::Some(#ident::#variant)), ); let is_valid
function_block-random_span
[ { "content": "pub fn skip_field<B>(wire_type: WireType, tag: u32, buf: &mut B, ctx: DecodeContext) -> Result<(), DecodeError>\n\nwhere\n\n B: Buf,\n\n{\n\n ctx.limit_reached()?;\n\n let len = match wire_type {\n\n WireType::Varint => decode_varint(buf).map(|_| 0)?,\n\n WireType::ThirtyTwoBit => 4,\n\n WireType::SixtyFourBit => 8,\n\n WireType::LengthDelimited => decode_varint(buf)?,\n\n WireType::StartGroup => loop {\n\n let (inner_tag, inner_wire_type) = decode_key(buf)?;\n\n match inner_wire_type {\n\n WireType::EndGroup => {\n\n if inner_tag != tag {\n\n return Err(DecodeError::new(\"unexpected end group tag\"));\n\n }\n\n break 0;\n\n }\n\n _ => skip_field(inner_wire_type, inner_tag, buf, ctx.enter_recursion())?,\n", "file_path": "src/encoding.rs", "rank": 0, "score": 379188.32664539886 }, { "content": "#[inline]\n\npub fn encode_key<B>(tag: u32, wire_type: WireType, buf: &mut B)\n\nwhere\n\n B: BufMut,\n\n{\n\n debug_assert!(tag >= MIN_TAG && tag <= MAX_TAG);\n\n let key = (tag << 3) | wire_type as u32;\n\n encode_varint(u64::from(key), buf);\n\n}\n\n\n\n/// Decodes a Protobuf field key, which consists of a wire type designator and\n\n/// the field tag.\n", "file_path": "src/encoding.rs", "rank": 1, "score": 364352.97339812096 }, { "content": "#[inline(always)]\n\npub fn decode_key<B>(buf: &mut B) -> Result<(u32, WireType), DecodeError>\n\nwhere\n\n B: Buf,\n\n{\n\n let key = decode_varint(buf)?;\n\n if key > u64::from(u32::MAX) {\n\n return Err(DecodeError::new(format!(\"invalid key value: {}\", key)));\n\n }\n\n let wire_type = WireType::try_from(key & 0x07)?;\n\n let tag = key as u32 >> 3;\n\n\n\n if tag < MIN_TAG {\n\n return Err(DecodeError::new(\"invalid tag value: 0\"));\n\n }\n\n\n\n Ok((tag, wire_type))\n\n}\n\n\n\n/// Returns the width of an encoded Protobuf field key with the given tag.\n\n/// The returned width will be between 1 and 5 bytes (inclusive).\n", "file_path": "src/encoding.rs", "rank": 2, "score": 327855.90712031664 }, { "content": "pub fn set_bool(b: &mut bool, message: &str) -> Result<(), Error> {\n\n if *b {\n\n bail!(\"{}\", message);\n\n } else {\n\n *b = true;\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 3, "score": 319960.3583924554 }, { "content": "#[inline]\n\npub fn encode_varint<B>(mut value: u64, buf: &mut B)\n\nwhere\n\n B: BufMut,\n\n{\n\n // Safety notes:\n\n //\n\n // - advance_mut is unsafe because it could cause uninitialized memory to be\n\n // advanced over. The use here is safe since each byte which is advanced over\n\n // has been written to in the previous loop iteration.\n\n let mut i;\n\n 'outer: loop {\n\n i = 0;\n\n\n\n for byte in buf.bytes_mut() {\n\n i += 1;\n\n if value < 0x80 {\n\n *byte = mem::MaybeUninit::new(value as u8);\n\n break 'outer;\n\n } else {\n\n *byte = mem::MaybeUninit::new(((value & 0x7F) | 0x80) as u8);\n", "file_path": "src/encoding.rs", "rank": 4, "score": 312854.7753121229 }, { "content": "/// Encodes a length delimiter to the buffer.\n\n///\n\n/// See [Message.encode_length_delimited] for more info.\n\n///\n\n/// An error will be returned if the buffer does not have sufficient capacity to encode the\n\n/// delimiter.\n\npub fn encode_length_delimiter<B>(length: usize, buf: &mut B) -> Result<(), EncodeError>\n\nwhere\n\n B: BufMut,\n\n{\n\n let length = length as u64;\n\n let required = encoded_len_varint(length);\n\n let remaining = buf.remaining_mut();\n\n if required > remaining {\n\n return Err(EncodeError::new(required, remaining));\n\n }\n\n encode_varint(length, buf);\n\n Ok(())\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 5, "score": 299137.1314844731 }, { "content": "pub fn set_option<T>(option: &mut Option<T>, value: T, message: &str) -> Result<(), Error>\n\nwhere\n\n T: fmt::Debug,\n\n{\n\n if let Some(ref existing) = *option {\n\n bail!(\"{}: {:?} and {:?}\", message, existing, value);\n\n }\n\n *option = Some(value);\n\n Ok(())\n\n}\n\n\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 6, "score": 284127.321144854 }, { "content": "/// Decodes a LEB128-encoded variable length integer from the buffer.\n\npub fn decode_varint<B>(buf: &mut B) -> Result<u64, DecodeError>\n\nwhere\n\n B: Buf,\n\n{\n\n let bytes = buf.bytes();\n\n let len = bytes.len();\n\n if len == 0 {\n\n return Err(DecodeError::new(\"invalid varint\"));\n\n }\n\n\n\n let byte = unsafe { *bytes.get_unchecked(0) };\n\n if byte < 0x80 {\n\n buf.advance(1);\n\n Ok(u64::from(byte))\n\n } else if len > 10 || bytes[len - 1] < 0x80 {\n\n let (value, advance) = unsafe { decode_varint_slice(bytes) }?;\n\n buf.advance(advance);\n\n Ok(value)\n\n } else {\n\n decode_varint_slow(buf)\n", "file_path": "src/encoding.rs", "rank": 7, "score": 277731.5480710742 }, { "content": "/// Decodes a length delimiter from the buffer.\n\n///\n\n/// This method allows the length delimiter to be decoded independently of the message, when the\n\n/// message is encoded with [Message.encode_length_delimited].\n\n///\n\n/// An error may be returned in two cases:\n\n///\n\n/// * If the supplied buffer contains fewer than 10 bytes, then an error indicates that more\n\n/// input is required to decode the full delimiter.\n\n/// * If the supplied buffer contains more than 10 bytes, then the buffer contains an invalid\n\n/// delimiter, and typically the buffer should be considered corrupt.\n\npub fn decode_length_delimiter<B>(mut buf: B) -> Result<usize, DecodeError>\n\nwhere\n\n B: Buf,\n\n{\n\n let length = decode_varint(&mut buf)?;\n\n if length > usize::max_value() as u64 {\n\n return Err(DecodeError::new(\n\n \"length delimiter exceeds maximum usize value\",\n\n ));\n\n }\n\n Ok(length as usize)\n\n}\n\n\n\n// Re-export #[derive(Message, Enumeration, Oneof)].\n\n// Based on serde's equivalent re-export [1], but enabled by default.\n\n//\n\n// [1]: https://github.com/serde-rs/serde/blob/v1.0.89/serde/src/lib.rs#L245-L256\n\n#[cfg(feature = \"prost-derive\")]\n\n#[allow(unused_imports)]\n\n#[macro_use]\n\nextern crate prost_derive;\n\n#[cfg(feature = \"prost-derive\")]\n\n#[doc(hidden)]\n\npub use bytes;\n\n#[cfg(feature = \"prost-derive\")]\n\n#[doc(hidden)]\n\npub use prost_derive::*;\n", "file_path": "src/lib.rs", "rank": 8, "score": 272970.7137492554 }, { "content": "#[inline]\n\npub fn key_len(tag: u32) -> usize {\n\n encoded_len_varint(u64::from(tag << 3))\n\n}\n\n\n\n/// Checks that the expected wire type matches the actual wire type,\n\n/// or returns an error result.\n", "file_path": "src/encoding.rs", "rank": 9, "score": 262204.1033475414 }, { "content": "/// Matches a 'matcher' against a fully qualified identifier.\n\npub fn match_ident(matcher: &str, msg: &str, field: Option<&str>) -> bool {\n\n assert_eq!(b'.', msg.as_bytes()[0]);\n\n\n\n if matcher.is_empty() {\n\n return false;\n\n } else if matcher == \".\" {\n\n return true;\n\n }\n\n\n\n let match_paths = matcher.split('.').collect::<Vec<_>>();\n\n let field_paths = {\n\n let mut paths = msg.split('.').collect::<Vec<_>>();\n\n if let Some(field) = field {\n\n paths.push(field);\n\n }\n\n paths\n\n };\n\n\n\n if &matcher[..1] == \".\" {\n\n // Prefix match.\n", "file_path": "prost-build/src/ident.rs", "rank": 10, "score": 244740.9256547966 }, { "content": "#[inline(never)]\n\nfn decode_varint_slow<B>(buf: &mut B) -> Result<u64, DecodeError>\n\nwhere\n\n B: Buf,\n\n{\n\n let mut value = 0;\n\n for count in 0..min(10, buf.remaining()) {\n\n let byte = buf.get_u8();\n\n value |= u64::from(byte & 0x7F) << (count * 7);\n\n if byte <= 0x7F {\n\n return Ok(value);\n\n }\n\n }\n\n\n\n Err(DecodeError::new(\"invalid varint\"))\n\n}\n\n\n\n/// Additional information passed to every decode/merge function.\n\n///\n\n/// The context should be passed by value and can be freely cloned. When passing\n\n/// to a function which is decoding a nested object, then use `enter_recursion`.\n", "file_path": "src/encoding.rs", "rank": 11, "score": 239683.37364909909 }, { "content": "fn tags_attr(attr: &Meta) -> Result<Option<Vec<u32>>, Error> {\n\n if !attr.path().is_ident(\"tags\") {\n\n return Ok(None);\n\n }\n\n match *attr {\n\n Meta::List(ref meta_list) => {\n\n let mut tags = Vec::with_capacity(meta_list.nested.len());\n\n for item in &meta_list.nested {\n\n if let NestedMeta::Lit(Lit::Int(ref lit)) = *item {\n\n tags.push(lit.base10_parse()?);\n\n } else {\n\n bail!(\"invalid tag attribute: {:?}\", attr);\n\n }\n\n }\n\n return Ok(Some(tags));\n\n }\n\n Meta::NameValue(MetaNameValue {\n\n lit: Lit::Str(ref lit),\n\n ..\n\n }) => lit\n\n .value()\n\n .split(',')\n\n .map(|s| s.trim().parse::<u32>().map_err(Error::from))\n\n .collect::<Result<Vec<u32>, _>>()\n\n .map(|tags| Some(tags)),\n\n _ => bail!(\"invalid tag attribute: {:?}\", attr),\n\n }\n\n}\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 12, "score": 225175.43400574708 }, { "content": "/// Helper function which abstracts reading a length delimiter prefix followed\n\n/// by decoding values until the length of bytes is exhausted.\n\npub fn merge_loop<T, M, B>(\n\n value: &mut T,\n\n buf: &mut B,\n\n ctx: DecodeContext,\n\n mut merge: M,\n\n) -> Result<(), DecodeError>\n\nwhere\n\n M: FnMut(&mut T, &mut B, DecodeContext) -> Result<(), DecodeError>,\n\n B: Buf,\n\n{\n\n let len = decode_varint(buf)?;\n\n let remaining = buf.remaining();\n\n if len > remaining as u64 {\n\n return Err(DecodeError::new(\"buffer underflow\"));\n\n }\n\n\n\n let limit = remaining - len as usize;\n\n while buf.remaining() > limit {\n\n merge(value, buf, ctx.clone())?;\n\n }\n\n\n\n if buf.remaining() != limit {\n\n return Err(DecodeError::new(\"delimited length exceeded\"));\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/encoding.rs", "rank": 15, "score": 209926.48644226856 }, { "content": "fn benchmark_varint(criterion: &mut Criterion, name: &str, mut values: Vec<u64>) {\n\n // Shuffle the values in a stable order.\n\n values.shuffle(&mut StdRng::seed_from_u64(0));\n\n\n\n let encoded_len = values\n\n .iter()\n\n .cloned()\n\n .map(encoded_len_varint)\n\n .sum::<usize>() as u64;\n\n let decoded_len = (values.len() * mem::size_of::<u64>()) as u64;\n\n\n\n let encode_values = values.clone();\n\n let encode = Benchmark::new(\"encode\", move |b| {\n\n let mut buf = Vec::<u8>::with_capacity(encode_values.len() * 10);\n\n b.iter(|| {\n\n buf.clear();\n\n for &value in &encode_values {\n\n encode_varint(value, &mut buf);\n\n }\n\n criterion::black_box(&buf);\n", "file_path": "benches/varint.rs", "rank": 16, "score": 207190.36015760107 }, { "content": "/// Strip an enum's type name from the prefix of an enum value.\n\n///\n\n/// This function assumes that both have been formatted to Rust's\n\n/// upper camel case naming conventions.\n\n///\n\n/// It also tries to handle cases where the stripped name would be\n\n/// invalid - for example, if it were to begin with a number.\n\nfn strip_enum_prefix<'a>(prefix: &str, name: &'a str) -> &'a str {\n\n let stripped = if name.starts_with(prefix) {\n\n &name[prefix.len()..]\n\n } else {\n\n name\n\n };\n\n // If the next character after the stripped prefix is not\n\n // uppercase, then it means that we didn't have a true prefix -\n\n // for example, \"Foo\" should not be stripped from \"Foobar\".\n\n if stripped\n\n .chars()\n\n .next()\n\n .map(char::is_uppercase)\n\n .unwrap_or(false)\n\n {\n\n stripped\n\n } else {\n\n name\n\n }\n\n}\n", "file_path": "prost-build/src/code_generator.rs", "rank": 17, "score": 205148.1326511334 }, { "content": "fn benchmark_dataset<M>(criterion: &mut Criterion, name: &str, dataset: &'static Path)\n\nwhere\n\n M: prost::Message + Default + 'static,\n\n{\n\n criterion.bench_function(&format!(\"dataset/{}/merge\", name), move |b| {\n\n let dataset = load_dataset(dataset).unwrap();\n\n let mut message = M::default();\n\n b.iter(|| {\n\n for buf in &dataset.payload {\n\n message.clear();\n\n message.merge(buf.as_slice()).unwrap();\n\n criterion::black_box(&message);\n\n }\n\n });\n\n });\n\n\n\n criterion.bench_function(&format!(\"dataset/{}/encode\", name), move |b| {\n\n let messages = load_dataset(dataset)\n\n .unwrap()\n\n .payload\n", "file_path": "protobuf/benches/dataset.rs", "rank": 18, "score": 199972.0983306625 }, { "content": "#[inline]\n\npub fn encoded_len_varint(value: u64) -> usize {\n\n // Based on [VarintSize64][1].\n\n // [1]: https://github.com/google/protobuf/blob/3.3.x/src/google/protobuf/io/coded_stream.h#L1301-L1309\n\n ((((value | 1).leading_zeros() ^ 63) * 9 + 73) / 64) as usize\n\n}\n\n\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum WireType {\n\n Varint = 0,\n\n SixtyFourBit = 1,\n\n LengthDelimited = 2,\n\n StartGroup = 3,\n\n EndGroup = 4,\n\n ThirtyTwoBit = 5,\n\n}\n\n\n\npub const MIN_TAG: u32 = 1;\n\npub const MAX_TAG: u32 = (1 << 29) - 1;\n\n\n", "file_path": "src/encoding.rs", "rank": 19, "score": 194978.90819767857 }, { "content": "/// Unpacks an attribute into a (key, boolean) pair, returning the boolean value.\n\n/// If the key doesn't match the attribute, `None` is returned.\n\nfn bool_attr(key: &str, attr: &Meta) -> Result<Option<bool>, Error> {\n\n if !attr.path().is_ident(key) {\n\n return Ok(None);\n\n }\n\n match *attr {\n\n Meta::Path(..) => Ok(Some(true)),\n\n Meta::List(ref meta_list) => {\n\n // TODO(rustlang/rust#23121): slice pattern matching would make this much nicer.\n\n if meta_list.nested.len() == 1 {\n\n if let NestedMeta::Lit(Lit::Bool(LitBool { value, .. })) = meta_list.nested[0] {\n\n return Ok(Some(value));\n\n }\n\n }\n\n bail!(\"invalid {} attribute\", key);\n\n }\n\n Meta::NameValue(MetaNameValue {\n\n lit: Lit::Str(ref lit),\n\n ..\n\n }) => lit\n\n .value()\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 22, "score": 191859.72087778378 }, { "content": "fn key_ty_from_str(s: &str) -> Result<scalar::Ty, Error> {\n\n let ty = scalar::Ty::from_str(s)?;\n\n match ty {\n\n scalar::Ty::Int32\n\n | scalar::Ty::Int64\n\n | scalar::Ty::Uint32\n\n | scalar::Ty::Uint64\n\n | scalar::Ty::Sint32\n\n | scalar::Ty::Sint64\n\n | scalar::Ty::Fixed32\n\n | scalar::Ty::Fixed64\n\n | scalar::Ty::Sfixed32\n\n | scalar::Ty::Sfixed64\n\n | scalar::Ty::Bool\n\n | scalar::Ty::String => Ok(ty),\n\n _ => bail!(\"invalid map key type: {}\", s),\n\n }\n\n}\n\n\n\n/// A map value type.\n", "file_path": "prost-derive/src/field/map.rs", "rank": 23, "score": 190418.98610784076 }, { "content": "#[test]\n\nfn check_default_values() {\n\n let default = DefaultValues::default();\n\n assert_eq!(default.int32, 42);\n\n assert_eq!(default.optional_int32, None);\n\n assert_eq!(&default.string, \"fourty two\");\n\n assert_eq!(default.enumeration, BasicEnumeration::ONE as i32);\n\n assert_eq!(default.optional_enumeration, None);\n\n assert_eq!(&default.repeated_enumeration, &[]);\n\n assert_eq!(0, default.encoded_len());\n\n}\n\n\n\n/// A protobuf enum.\n\n#[derive(Clone, Copy, Debug, PartialEq, Enumeration)]\n\npub enum BasicEnumeration {\n\n ZERO = 0,\n\n ONE = 1,\n\n TWO = 2,\n\n THREE = 3,\n\n}\n\n\n", "file_path": "tests/src/message_encoding.rs", "rank": 26, "score": 182152.58461219197 }, { "content": "/// Converts a `camelCase` or `SCREAMING_SNAKE_CASE` identifier to a `lower_snake` case Rust field\n\n/// identifier.\n\npub fn to_snake(s: &str) -> String {\n\n let mut ident = s.to_snake_case();\n\n\n\n // Use a raw identifier if the identifier matches a Rust keyword:\n\n // https://doc.rust-lang.org/reference/keywords.html.\n\n match ident.as_str() {\n\n // 2015 strict keywords.\n\n | \"as\" | \"break\" | \"const\" | \"continue\" | \"else\" | \"enum\" | \"false\"\n\n | \"fn\" | \"for\" | \"if\" | \"impl\" | \"in\" | \"let\" | \"loop\" | \"match\" | \"mod\" | \"move\" | \"mut\"\n\n | \"pub\" | \"ref\" | \"return\" | \"static\" | \"struct\" | \"trait\" | \"true\"\n\n | \"type\" | \"unsafe\" | \"use\" | \"where\" | \"while\"\n\n // 2018 strict keywords.\n\n | \"dyn\"\n\n // 2015 reserved keywords.\n\n | \"abstract\" | \"become\" | \"box\" | \"do\" | \"final\" | \"macro\" | \"override\" | \"priv\" | \"typeof\"\n\n | \"unsized\" | \"virtual\" | \"yield\"\n\n // 2018 reserved keywords.\n\n | \"async\" | \"await\" | \"try\" => ident.insert_str(0, \"r#\"),\n\n // the following keywords are not supported as raw identifiers and are therefore suffixed with an underscore.\n\n \"self\" | \"super\" | \"extern\" | \"crate\" => ident += \"_\",\n\n _ => (),\n\n }\n\n ident\n\n}\n\n\n", "file_path": "prost-build/src/ident.rs", "rank": 27, "score": 178820.696185432 }, { "content": "/// Converts a `snake_case` identifier to an `UpperCamel` case Rust type identifier.\n\npub fn to_upper_camel(s: &str) -> String {\n\n let mut ident = s.to_camel_case();\n\n\n\n // Suffix an underscore for the `Self` Rust keyword as it is not allowed as raw identifier.\n\n if ident == \"Self\" {\n\n ident += \"_\";\n\n }\n\n ident\n\n}\n\n\n", "file_path": "prost-build/src/ident.rs", "rank": 28, "score": 174470.11106060125 }, { "content": "#[inline]\n\npub fn check_wire_type(expected: WireType, actual: WireType) -> Result<(), DecodeError> {\n\n if expected != actual {\n\n return Err(DecodeError::new(format!(\n\n \"invalid wire type: {:?} (expected {:?})\",\n\n actual, expected\n\n )));\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/encoding.rs", "rank": 29, "score": 168143.093827429 }, { "content": "/// Checks if an attribute matches a word.\n\nfn word_attr(key: &str, attr: &Meta) -> bool {\n\n if let Meta::Path(ref path) = *attr {\n\n path.is_ident(key)\n\n } else {\n\n false\n\n }\n\n}\n\n\n\npub(super) fn tag_attr(attr: &Meta) -> Result<Option<u32>, Error> {\n\n if !attr.path().is_ident(\"tag\") {\n\n return Ok(None);\n\n }\n\n match *attr {\n\n Meta::List(ref meta_list) => {\n\n // TODO(rustlang/rust#23121): slice pattern matching would make this much nicer.\n\n if meta_list.nested.len() == 1 {\n\n if let NestedMeta::Lit(Lit::Int(ref lit)) = meta_list.nested[0] {\n\n return Ok(Some(lit.base10_parse()?));\n\n }\n\n }\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 30, "score": 167900.49317507795 }, { "content": "#[test]\n\nfn oneof_with_enum() {\n\n let msg = MessageWithOneof {\n\n of: Some(OneofWithEnum::Enumeration(BasicEnumeration::TWO as i32)),\n\n };\n\n assert_eq!(\n\n format!(\"{:?}\", msg),\n\n \"MessageWithOneof { of: Some(Enumeration(TWO)) }\"\n\n );\n\n}\n", "file_path": "tests/src/debug.rs", "rank": 31, "score": 161111.50343684756 }, { "content": "/// Returns the path to the `protoc` binary.\n\npub fn protoc() -> &'static Path {\n\n Path::new(env!(\"PROTOC\"))\n\n}\n\n\n", "file_path": "prost-build/src/lib.rs", "rank": 32, "score": 151926.2628156553 }, { "content": "#[test]\n\nfn check_tags_inferred() {\n\n check_message(&TagsInferred::default());\n\n check_serialize_equivalent(&TagsInferred::default(), &TagsQualified::default());\n\n\n\n let tags_inferred = TagsInferred {\n\n one: true,\n\n two: Some(42),\n\n three: vec![0.0, 1.0, 1.0],\n\n skip_to_nine: \"nine\".to_owned(),\n\n ten: 0,\n\n eleven: ::std::collections::HashMap::new(),\n\n back_to_five: vec![1, 0, 1],\n\n six: Basic::default(),\n\n };\n\n check_message(&tags_inferred);\n\n\n\n let tags_qualified = TagsQualified {\n\n one: true,\n\n two: Some(42),\n\n three: vec![0.0, 1.0, 1.0],\n", "file_path": "tests/src/message_encoding.rs", "rank": 33, "score": 149324.53628859564 }, { "content": "/// Returns the path to the Protobuf include directory.\n\npub fn protoc_include() -> &'static Path {\n\n Path::new(env!(\"PROTOC_INCLUDE\"))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use env_logger;\n\n use std::cell::RefCell;\n\n use std::rc::Rc;\n\n\n\n /// An example service generator that generates a trait with methods corresponding to the\n\n /// service methods.\n\n struct ServiceTraitGenerator;\n\n impl ServiceGenerator for ServiceTraitGenerator {\n\n fn generate(&mut self, service: Service, buf: &mut String) {\n\n // Generate a trait for the service.\n\n service.comments.append_with_indent(0, buf);\n\n buf.push_str(&format!(\"trait {} {{\\n\", &service.name));\n\n\n", "file_path": "prost-build/src/lib.rs", "rank": 34, "score": 148665.92252752394 }, { "content": "#[test]\n\nfn check_scalar_types() {\n\n check_message(&ScalarTypes::default());\n\n}\n\n\n\n/// A protobuf message which contains all scalar types.\n\n#[derive(Clone, PartialEq, Message)]\n\npub struct ScalarTypes {\n\n #[prost(int32, tag = \"001\")]\n\n pub int32: i32,\n\n #[prost(int64, tag = \"002\")]\n\n pub int64: i64,\n\n #[prost(uint32, tag = \"003\")]\n\n pub uint32: u32,\n\n #[prost(uint64, tag = \"004\")]\n\n pub uint64: u64,\n\n #[prost(sint32, tag = \"005\")]\n\n pub sint32: i32,\n\n #[prost(sint64, tag = \"006\")]\n\n pub sint64: i64,\n\n #[prost(fixed32, tag = \"007\")]\n", "file_path": "tests/src/message_encoding.rs", "rank": 35, "score": 148129.57639511072 }, { "content": "/// A Protocol Buffers message.\n\npub trait Message: Debug + Send + Sync {\n\n /// Encodes the message to a buffer.\n\n ///\n\n /// This method will panic if the buffer has insufficient capacity.\n\n ///\n\n /// Meant to be used only by `Message` implementations.\n\n #[doc(hidden)]\n\n fn encode_raw<B>(&self, buf: &mut B)\n\n where\n\n B: BufMut,\n\n Self: Sized;\n\n\n\n /// Decodes a field from a buffer, and merges it into `self`.\n\n ///\n\n /// Meant to be used only by `Message` implementations.\n\n #[doc(hidden)]\n\n fn merge_field<B>(\n\n &mut self,\n\n tag: u32,\n\n wire_type: WireType,\n", "file_path": "src/message.rs", "rank": 36, "score": 147824.3578646485 }, { "content": "/// Tests round-tripping a message type. The message should be compiled with `BTreeMap` fields,\n\n/// otherwise the comparison may fail due to inconsistent `HashMap` entry encoding ordering.\n\npub fn roundtrip<M>(data: &[u8]) -> RoundtripResult\n\nwhere\n\n M: Message + Default,\n\n{\n\n // Try to decode a message from the data. If decoding fails, continue.\n\n let all_types = match M::decode(data) {\n\n Ok(all_types) => all_types,\n\n Err(error) => return RoundtripResult::DecodeError(error),\n\n };\n\n\n\n let encoded_len = all_types.encoded_len();\n\n\n\n // TODO: Reenable this once sign-extension in negative int32s is figured out.\n\n // assert!(encoded_len <= data.len(), \"encoded_len: {}, len: {}, all_types: {:?}\",\n\n // encoded_len, data.len(), all_types);\n\n\n\n let mut buf1 = Vec::new();\n\n if let Err(error) = all_types.encode(&mut buf1) {\n\n return RoundtripResult::Error(error.into());\n\n }\n", "file_path": "tests/src/lib.rs", "rank": 37, "score": 138207.13370130784 }, { "content": "/// Returns the encoded length of a length delimiter.\n\n///\n\n/// Applications may use this method to ensure sufficient buffer capacity before calling\n\n/// `encode_length_delimiter`. The returned size will be between 1 and 10, inclusive.\n\npub fn length_delimiter_len(length: usize) -> usize {\n\n encoded_len_varint(length as u64)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 38, "score": 135069.31197272486 }, { "content": "#[derive(Clone, PartialEq, prost::Message)]\n\nstruct MessageWithOneof {\n\n #[prost(oneof = \"OneofWithEnum\", tags = \"8, 9, 10\")]\n\n of: Option<OneofWithEnum>,\n\n}\n\n\n\n/// Enumerations inside oneofs\n", "file_path": "tests/src/debug.rs", "rank": 39, "score": 134430.71900250076 }, { "content": "#[test]\n\nfn tuple_struct() {\n\n #[derive(Clone, PartialEq, Message)]\n\n struct NewType(\n\n #[prost(enumeration=\"BasicEnumeration\", tag=\"5\")]\n\n i32,\n\n );\n\n assert_eq!(format!(\"{:?}\", NewType(BasicEnumeration::TWO as i32)), \"NewType(TWO)\");\n\n assert_eq!(format!(\"{:?}\", NewType(42)), \"NewType(42)\");\n\n}\n\n*/\n\n\n\n#[derive(Clone, PartialEq, prost::Oneof)]\n\npub enum OneofWithEnum {\n\n #[prost(int32, tag = \"8\")]\n\n Int(i32),\n\n #[prost(string, tag = \"9\")]\n\n String(String),\n\n #[prost(enumeration = \"BasicEnumeration\", tag = \"10\")]\n\n Enumeration(i32),\n\n}\n\n\n", "file_path": "tests/src/debug.rs", "rank": 40, "score": 125653.33223114737 }, { "content": "fn fake_scalar(ty: scalar::Ty) -> scalar::Field {\n\n let kind = scalar::Kind::Plain(scalar::DefaultValue::new(&ty));\n\n scalar::Field {\n\n ty,\n\n kind,\n\n tag: 0, // Not used here\n\n }\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct Field {\n\n pub map_ty: MapTy,\n\n pub key_ty: scalar::Ty,\n\n pub value_ty: ValueTy,\n\n pub tag: u32,\n\n}\n\n\n\nimpl Field {\n\n pub fn new(attrs: &[Meta], inferred_tag: Option<u32>) -> Result<Option<Field>, Error> {\n\n let mut types = None;\n", "file_path": "prost-derive/src/field/map.rs", "rank": 41, "score": 123960.28290404892 }, { "content": "/// Generic rountrip serialization check for messages.\n\npub fn check_message<M>(msg: &M)\n\nwhere\n\n M: Message + Default + PartialEq,\n\n{\n\n let expected_len = msg.encoded_len();\n\n\n\n let mut buf = Vec::with_capacity(18);\n\n msg.encode(&mut buf).unwrap();\n\n assert_eq!(expected_len, buf.len());\n\n\n\n let mut buf = &*buf;\n\n let roundtrip = M::decode(&mut buf).unwrap();\n\n\n\n if buf.has_remaining() {\n\n panic!(format!(\"expected buffer to be empty: {}\", buf.remaining()));\n\n }\n\n\n\n assert_eq!(msg, &roundtrip);\n\n}\n\n\n", "file_path": "tests/src/lib.rs", "rank": 42, "score": 123885.18384057093 }, { "content": "#[test]\n\nfn test_warns_when_using_fields_with_deprecated_field() {\n\n #[allow(deprecated)]\n\n deprecated_field::Test {\n\n not_outdated: \".ogg\".to_string(),\n\n outdated: \".wav\".to_string(),\n\n };\n\n // This test relies on the `#[allow(deprecated)]` attribute to ignore the warning that should\n\n // be raised by the compiler.\n\n // This test has a shortcoming since it doesn't explicitly check for the presence of the\n\n // `deprecated` attribute since it doesn't exist at runtime. If complied without the `allow`\n\n // attribute the following warning would be raised:\n\n //\n\n // warning: use of deprecated item 'deprecated_field::deprecated_field::Test::outdated'\n\n // --> tests/src/deprecated_field.rs:11:9\n\n // |\n\n // 11 | outdated: \".wav\".to_string(),\n\n // | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n // |\n\n // = note: `#[warn(deprecated)]` on by default\n\n\n\n assert!(true);\n\n}\n", "file_path": "tests/src/deprecated_field.rs", "rank": 43, "score": 123317.59796673994 }, { "content": "#[test]\n\nfn extreme_default_values() {\n\n use protobuf::test_messages::protobuf_unittest;\n\n use std::{f32, f64};\n\n\n\n let pb = protobuf_unittest::TestExtremeDefaultValues::default();\n\n\n\n assert_eq!(\n\n b\"\\0\\x01\\x07\\x08\\x0C\\n\\r\\t\\x0B\\\\\\'\\\"\\xFE\",\n\n pb.escaped_bytes()\n\n );\n\n\n\n assert_eq!(0xFFFFFFFF, pb.large_uint32());\n\n assert_eq!(0xFFFFFFFFFFFFFFFF, pb.large_uint64());\n\n assert_eq!(-0x7FFFFFFF, pb.small_int32());\n\n assert_eq!(-0x7FFFFFFFFFFFFFFF, pb.small_int64());\n\n assert_eq!(-0x80000000, pb.really_small_int32());\n\n assert_eq!(-0x8000000000000000, pb.really_small_int64());\n\n\n\n assert_eq!(pb.utf8_string(), \"\\u{1234}\");\n\n\n", "file_path": "tests/src/unittest.rs", "rank": 44, "score": 121576.56587306119 }, { "content": "fn validate_proto_path(path: &str) -> Result<(), String> {\n\n if path.chars().next().map(|c| c != '.').unwrap_or(true) {\n\n return Err(format!(\n\n \"Protobuf paths must be fully qualified (begin with a leading '.'): {}\",\n\n path\n\n ));\n\n }\n\n if path.split('.').skip(1).any(str::is_empty) {\n\n return Err(format!(\"invalid fully-qualified Protobuf path: {}\", path));\n\n }\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct ExternPaths {\n\n extern_paths: HashMap<String, String>,\n\n}\n\n\n\nimpl ExternPaths {\n\n pub fn new(paths: &[(String, String)], prost_types: bool) -> Result<ExternPaths, String> {\n", "file_path": "prost-build/src/extern_paths.rs", "rank": 45, "score": 116588.11860042505 }, { "content": "#[test]\n\nfn check_repeated_floats() {\n\n check_message(&RepeatedFloats {\n\n single_float: 0.0,\n\n repeated_float: vec![\n\n 0.1,\n\n 340282300000000000000000000000000000000.0,\n\n 0.000000000000000000000000000000000000011754944,\n\n ],\n\n });\n\n}\n\n\n", "file_path": "tests/src/message_encoding.rs", "rank": 46, "score": 116513.9826888155 }, { "content": "mod group;\n\nmod map;\n\nmod message;\n\nmod oneof;\n\nmod scalar;\n\n\n\nuse std::fmt;\n\nuse std::slice;\n\n\n\nuse anyhow::{bail, Error};\n\nuse proc_macro2::TokenStream;\n\nuse quote::quote;\n\nuse syn::{Attribute, Ident, Lit, LitBool, Meta, MetaList, MetaNameValue, NestedMeta};\n\n\n\n#[derive(Clone)]\n\npub enum Field {\n\n /// A scalar field.\n\n Scalar(scalar::Field),\n\n /// A message field.\n\n Message(message::Field),\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 47, "score": 104038.585537654 }, { "content": " }\n\n }\n\n\n\n /// Returns a statement which clears the field.\n\n pub fn clear(&self, ident: TokenStream) -> TokenStream {\n\n match *self {\n\n Field::Scalar(ref scalar) => scalar.clear(ident),\n\n Field::Message(ref message) => message.clear(ident),\n\n Field::Map(ref map) => map.clear(ident),\n\n Field::Oneof(ref oneof) => oneof.clear(ident),\n\n Field::Group(ref group) => group.clear(ident),\n\n }\n\n }\n\n\n\n pub fn default(&self) -> TokenStream {\n\n match *self {\n\n Field::Scalar(ref scalar) => scalar.default(),\n\n _ => quote!(::std::default::Default::default()),\n\n }\n\n }\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 48, "score": 104034.52263982582 }, { "content": " /// Returns an expression which evaluates to the result of merging a decoded\n\n /// value into the field.\n\n pub fn merge(&self, ident: TokenStream) -> TokenStream {\n\n match *self {\n\n Field::Scalar(ref scalar) => scalar.merge(ident),\n\n Field::Message(ref message) => message.merge(ident),\n\n Field::Map(ref map) => map.merge(ident),\n\n Field::Oneof(ref oneof) => oneof.merge(ident),\n\n Field::Group(ref group) => group.merge(ident),\n\n }\n\n }\n\n\n\n /// Returns an expression which evaluates to the encoded length of the field.\n\n pub fn encoded_len(&self, ident: TokenStream) -> TokenStream {\n\n match *self {\n\n Field::Scalar(ref scalar) => scalar.encoded_len(ident),\n\n Field::Map(ref map) => map.encoded_len(ident),\n\n Field::Message(ref msg) => msg.encoded_len(ident),\n\n Field::Oneof(ref oneof) => oneof.encoded_len(ident),\n\n Field::Group(ref group) => group.encoded_len(ident),\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 49, "score": 104034.21642650756 }, { "content": " }\n\n }\n\n _ => quote!(&#ident),\n\n }\n\n }\n\n\n\n pub fn methods(&self, ident: &Ident) -> Option<TokenStream> {\n\n match *self {\n\n Field::Scalar(ref scalar) => scalar.methods(ident),\n\n Field::Map(ref map) => map.methods(ident),\n\n _ => None,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Clone, Copy, PartialEq, Eq)]\n\npub enum Label {\n\n /// An optional field.\n\n Optional,\n\n /// A required field.\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 50, "score": 104032.83527830588 }, { "content": " match *self {\n\n Field::Scalar(ref scalar) => vec![scalar.tag],\n\n Field::Message(ref message) => vec![message.tag],\n\n Field::Map(ref map) => vec![map.tag],\n\n Field::Oneof(ref oneof) => oneof.tags.clone(),\n\n Field::Group(ref group) => vec![group.tag],\n\n }\n\n }\n\n\n\n /// Returns a statement which encodes the field.\n\n pub fn encode(&self, ident: TokenStream) -> TokenStream {\n\n match *self {\n\n Field::Scalar(ref scalar) => scalar.encode(ident),\n\n Field::Message(ref message) => message.encode(ident),\n\n Field::Map(ref map) => map.encode(ident),\n\n Field::Oneof(ref oneof) => oneof.encode(ident),\n\n Field::Group(ref group) => group.encode(ident),\n\n }\n\n }\n\n\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 51, "score": 104032.66215331115 }, { "content": "\n\n /// Produces the fragment implementing debug for the given field.\n\n pub fn debug(&self, ident: TokenStream) -> TokenStream {\n\n match *self {\n\n Field::Scalar(ref scalar) => {\n\n let wrapper = scalar.debug(quote!(ScalarWrapper));\n\n quote! {\n\n {\n\n #wrapper\n\n ScalarWrapper(&#ident)\n\n }\n\n }\n\n }\n\n Field::Map(ref map) => {\n\n let wrapper = map.debug(quote!(MapWrapper));\n\n quote! {\n\n {\n\n #wrapper\n\n MapWrapper(&#ident)\n\n }\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 52, "score": 104032.01590391633 }, { "content": " bail!(\"invalid tag attribute: {:?}\", attr);\n\n }\n\n Meta::NameValue(ref meta_name_value) => match meta_name_value.lit {\n\n Lit::Str(ref lit) => lit\n\n .value()\n\n .parse::<u32>()\n\n .map_err(Error::from)\n\n .map(Option::Some),\n\n Lit::Int(ref lit) => Ok(Some(lit.base10_parse()?)),\n\n _ => bail!(\"invalid tag attribute: {:?}\", attr),\n\n },\n\n _ => bail!(\"invalid tag attribute: {:?}\", attr),\n\n }\n\n}\n\n\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 53, "score": 104027.4592964421 }, { "content": " /// If the string doesn't match a field label, `None` is returned.\n\n fn from_attr(attr: &Meta) -> Option<Label> {\n\n if let Meta::Path(ref path) = *attr {\n\n for &label in Label::variants() {\n\n if path.is_ident(label.as_str()) {\n\n return Some(label);\n\n }\n\n }\n\n }\n\n None\n\n }\n\n}\n\n\n\nimpl fmt::Debug for Label {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.write_str(self.as_str())\n\n }\n\n}\n\n\n\nimpl fmt::Display for Label {\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 54, "score": 104025.74815504377 }, { "content": " /// A map field.\n\n Map(map::Field),\n\n /// A oneof field.\n\n Oneof(oneof::Field),\n\n /// A group field.\n\n Group(group::Field),\n\n}\n\n\n\nimpl Field {\n\n /// Creates a new `Field` from an iterator of field attributes.\n\n ///\n\n /// If the meta items are invalid, an error will be returned.\n\n /// If the field should be ignored, `None` is returned.\n\n pub fn new(attrs: Vec<Attribute>, inferred_tag: Option<u32>) -> Result<Option<Field>, Error> {\n\n let attrs = prost_attrs(attrs)?;\n\n\n\n // TODO: check for ignore attribute.\n\n\n\n let field = if let Some(field) = scalar::Field::new(&attrs, inferred_tag)? {\n\n Field::Scalar(field)\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 55, "score": 104022.79004926978 }, { "content": " Required,\n\n /// A repeated field.\n\n Repeated,\n\n}\n\n\n\nimpl Label {\n\n fn as_str(&self) -> &'static str {\n\n match *self {\n\n Label::Optional => \"optional\",\n\n Label::Required => \"required\",\n\n Label::Repeated => \"repeated\",\n\n }\n\n }\n\n\n\n fn variants() -> slice::Iter<'static, Label> {\n\n const VARIANTS: &'static [Label] = &[Label::Optional, Label::Required, Label::Repeated];\n\n VARIANTS.iter()\n\n }\n\n\n\n /// Parses a string into a field label.\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 56, "score": 104021.94164408527 }, { "content": " } else if let Some(field) = message::Field::new(&attrs, inferred_tag)? {\n\n Field::Message(field)\n\n } else if let Some(field) = map::Field::new(&attrs, inferred_tag)? {\n\n Field::Map(field)\n\n } else if let Some(field) = oneof::Field::new(&attrs)? {\n\n Field::Oneof(field)\n\n } else if let Some(field) = group::Field::new(&attrs, inferred_tag)? {\n\n Field::Group(field)\n\n } else {\n\n bail!(\"no type attribute\");\n\n };\n\n\n\n Ok(Some(field))\n\n }\n\n\n\n /// Creates a new oneof `Field` from an iterator of field attributes.\n\n ///\n\n /// If the meta items are invalid, an error will be returned.\n\n /// If the field should be ignored, `None` is returned.\n\n pub fn new_oneof(attrs: Vec<Attribute>) -> Result<Option<Field>, Error> {\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 57, "score": 104021.58215320525 }, { "content": " fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.write_str(self.as_str())\n\n }\n\n}\n\n\n\n/// Get the items belonging to the 'prost' list attribute, e.g. `#[prost(foo, bar=\"baz\")]`.\n\npub(super) fn prost_attrs(attrs: Vec<Attribute>) -> Result<Vec<Meta>, Error> {\n\n Ok(attrs\n\n .iter()\n\n .flat_map(Attribute::parse_meta)\n\n .flat_map(|meta| match meta {\n\n Meta::List(MetaList { path, nested, .. }) => {\n\n if path.is_ident(\"prost\") {\n\n nested.into_iter().collect()\n\n } else {\n\n Vec::new()\n\n }\n\n }\n\n _ => Vec::new(),\n\n })\n\n .flat_map(|attr| -> Result<_, _> {\n\n match attr {\n\n NestedMeta::Meta(attr) => Ok(attr),\n\n NestedMeta::Lit(lit) => bail!(\"invalid prost attribute: {:?}\", lit),\n\n }\n\n })\n\n .collect())\n\n}\n\n\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 58, "score": 104016.83903098878 }, { "content": " let attrs = prost_attrs(attrs)?;\n\n\n\n // TODO: check for ignore attribute.\n\n\n\n let field = if let Some(field) = scalar::Field::new_oneof(&attrs)? {\n\n Field::Scalar(field)\n\n } else if let Some(field) = message::Field::new_oneof(&attrs)? {\n\n Field::Message(field)\n\n } else if let Some(field) = map::Field::new_oneof(&attrs)? {\n\n Field::Map(field)\n\n } else if let Some(field) = group::Field::new_oneof(&attrs)? {\n\n Field::Group(field)\n\n } else {\n\n bail!(\"no type attribute for oneof field\");\n\n };\n\n\n\n Ok(Some(field))\n\n }\n\n\n\n pub fn tags(&self) -> Vec<u32> {\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 59, "score": 104015.28625180565 }, { "content": " .parse::<bool>()\n\n .map_err(Error::from)\n\n .map(Option::Some),\n\n Meta::NameValue(MetaNameValue {\n\n lit: Lit::Bool(LitBool { value, .. }),\n\n ..\n\n }) => Ok(Some(value)),\n\n _ => bail!(\"invalid {} attribute\", key),\n\n }\n\n}\n\n\n", "file_path": "prost-derive/src/field/mod.rs", "rank": 60, "score": 104011.83082788797 }, { "content": "use anyhow::{bail, Error};\n\nuse proc_macro2::TokenStream;\n\nuse quote::{quote, ToTokens};\n\nuse syn::Meta;\n\n\n\nuse crate::field::{set_bool, set_option, tag_attr, word_attr, Label};\n\n\n\n#[derive(Clone)]\n\npub struct Field {\n\n pub label: Label,\n\n pub tag: u32,\n\n}\n\n\n\nimpl Field {\n\n pub fn new(attrs: &[Meta], inferred_tag: Option<u32>) -> Result<Option<Field>, Error> {\n\n let mut message = false;\n\n let mut label = None;\n\n let mut tag = None;\n\n let mut boxed = false;\n\n\n", "file_path": "prost-derive/src/field/message.rs", "rank": 61, "score": 103818.01501689832 }, { "content": " ctx)\n\n },\n\n Label::Required => quote! {\n\n ::prost::encoding::message::merge(wire_type, #ident, buf, ctx)\n\n },\n\n Label::Repeated => quote! {\n\n ::prost::encoding::message::merge_repeated(wire_type, #ident, buf, ctx)\n\n },\n\n }\n\n }\n\n\n\n pub fn encoded_len(&self, ident: TokenStream) -> TokenStream {\n\n let tag = self.tag;\n\n match self.label {\n\n Label::Optional => quote! {\n\n #ident.as_ref().map_or(0, |msg| ::prost::encoding::message::encoded_len(#tag, msg))\n\n },\n\n Label::Required => quote! {\n\n ::prost::encoding::message::encoded_len(#tag, &#ident)\n\n },\n", "file_path": "prost-derive/src/field/message.rs", "rank": 62, "score": 103815.14748215489 }, { "content": " ::prost::encoding::message::encode(#tag, msg, buf);\n\n }\n\n },\n\n Label::Required => quote! {\n\n ::prost::encoding::message::encode(#tag, &#ident, buf);\n\n },\n\n Label::Repeated => quote! {\n\n for msg in &#ident {\n\n ::prost::encoding::message::encode(#tag, msg, buf);\n\n }\n\n },\n\n }\n\n }\n\n\n\n pub fn merge(&self, ident: TokenStream) -> TokenStream {\n\n match self.label {\n\n Label::Optional => quote! {\n\n ::prost::encoding::message::merge(wire_type,\n\n #ident.get_or_insert_with(Default::default),\n\n buf,\n", "file_path": "prost-derive/src/field/message.rs", "rank": 63, "score": 103811.7172934594 }, { "content": " pub fn new_oneof(attrs: &[Meta]) -> Result<Option<Field>, Error> {\n\n if let Some(mut field) = Field::new(attrs, None)? {\n\n if let Some(attr) = attrs.iter().find(|attr| Label::from_attr(attr).is_some()) {\n\n bail!(\n\n \"invalid attribute for oneof field: {}\",\n\n attr.path().into_token_stream()\n\n );\n\n }\n\n field.label = Label::Required;\n\n Ok(Some(field))\n\n } else {\n\n Ok(None)\n\n }\n\n }\n\n\n\n pub fn encode(&self, ident: TokenStream) -> TokenStream {\n\n let tag = self.tag;\n\n match self.label {\n\n Label::Optional => quote! {\n\n if let Some(ref msg) = #ident {\n", "file_path": "prost-derive/src/field/message.rs", "rank": 64, "score": 103805.98140997875 }, { "content": " Label::Repeated => quote! {\n\n ::prost::encoding::message::encoded_len_repeated(#tag, &#ident)\n\n },\n\n }\n\n }\n\n\n\n pub fn clear(&self, ident: TokenStream) -> TokenStream {\n\n match self.label {\n\n Label::Optional => quote!(#ident = ::std::option::Option::None),\n\n Label::Required => quote!(#ident.clear()),\n\n Label::Repeated => quote!(#ident.clear()),\n\n }\n\n }\n\n}\n", "file_path": "prost-derive/src/field/message.rs", "rank": 65, "score": 103803.9433435138 }, { "content": " let mut unknown_attrs = Vec::new();\n\n\n\n for attr in attrs {\n\n if word_attr(\"message\", attr) {\n\n set_bool(&mut message, \"duplicate message attribute\")?;\n\n } else if word_attr(\"boxed\", attr) {\n\n set_bool(&mut boxed, \"duplicate boxed attribute\")?;\n\n } else if let Some(t) = tag_attr(attr)? {\n\n set_option(&mut tag, t, \"duplicate tag attributes\")?;\n\n } else if let Some(l) = Label::from_attr(attr) {\n\n set_option(&mut label, l, \"duplicate label attributes\")?;\n\n } else {\n\n unknown_attrs.push(attr);\n\n }\n\n }\n\n\n\n if !message {\n\n return Ok(None);\n\n }\n\n\n", "file_path": "prost-derive/src/field/message.rs", "rank": 66, "score": 103790.98348453552 }, { "content": " match unknown_attrs.len() {\n\n 0 => (),\n\n 1 => bail!(\n\n \"unknown attribute for message field: {:?}\",\n\n unknown_attrs[0]\n\n ),\n\n _ => bail!(\"unknown attributes for message field: {:?}\", unknown_attrs),\n\n }\n\n\n\n let tag = match tag.or(inferred_tag) {\n\n Some(tag) => tag,\n\n None => bail!(\"message field is missing a tag attribute\"),\n\n };\n\n\n\n Ok(Some(Field {\n\n label: label.unwrap_or(Label::Optional),\n\n tag: tag,\n\n }))\n\n }\n\n\n", "file_path": "prost-derive/src/field/message.rs", "rank": 67, "score": 103789.95721495856 }, { "content": "/// Returns `true` if the repeated field type can be packed.\n\nfn can_pack(field: &FieldDescriptorProto) -> bool {\n\n match field.r#type() {\n\n Type::Float\n\n | Type::Double\n\n | Type::Int32\n\n | Type::Int64\n\n | Type::Uint32\n\n | Type::Uint64\n\n | Type::Sint32\n\n | Type::Sint64\n\n | Type::Fixed32\n\n | Type::Fixed64\n\n | Type::Sfixed32\n\n | Type::Sfixed64\n\n | Type::Bool\n\n | Type::Enum => true,\n\n _ => false,\n\n }\n\n}\n\n\n", "file_path": "prost-build/src/code_generator.rs", "rank": 68, "score": 102148.3668546853 }, { "content": "fn download_tarball(url: &str, out_dir: &Path) {\n\n let mut data = Vec::new();\n\n let mut handle = Easy::new();\n\n\n\n // Download the tarball.\n\n handle.url(url).expect(\"failed to configure tarball URL\");\n\n handle\n\n .follow_location(true)\n\n .expect(\"failed to configure follow location\");\n\n {\n\n let mut transfer = handle.transfer();\n\n transfer\n\n .write_function(|new_data| {\n\n data.extend_from_slice(new_data);\n\n Ok(new_data.len())\n\n })\n\n .expect(\"failed to write download data\");\n\n transfer.perform().expect(\"failed to download tarball\");\n\n }\n\n\n\n // Unpack the tarball.\n\n Archive::new(GzDecoder::new(Cursor::new(data)))\n\n .unpack(out_dir)\n\n .expect(\"failed to unpack tarball\");\n\n}\n\n\n", "file_path": "protobuf/build.rs", "rank": 69, "score": 96832.30753117759 }, { "content": "#[derive(PartialEq)]\n\nenum Syntax {\n\n Proto2,\n\n Proto3,\n\n}\n\n\n\npub struct CodeGenerator<'a> {\n\n config: &'a mut Config,\n\n package: String,\n\n source_info: SourceCodeInfo,\n\n syntax: Syntax,\n\n message_graph: &'a MessageGraph,\n\n extern_paths: &'a ExternPaths,\n\n depth: u8,\n\n path: Vec<i32>,\n\n buf: &'a mut String,\n\n}\n\n\n\nimpl<'a> CodeGenerator<'a> {\n\n pub fn generate(\n\n config: &mut Config,\n", "file_path": "prost-build/src/code_generator.rs", "rank": 70, "score": 96648.23844004146 }, { "content": "// Trait used in extern_paths.rs.\n\npub trait DoIt {\n\n fn do_it(&self);\n\n}\n\n\n\nimpl DoIt for gizmo::Gizmo {\n\n fn do_it(&self) {}\n\n}\n\n\n", "file_path": "tests/src/packages/mod.rs", "rank": 71, "score": 94543.54307326522 }, { "content": "#[test]\n\nfn basic() {\n\n let mut basic = Basic::default();\n\n assert_eq!(\n\n format!(\"{:?}\", basic),\n\n \"Basic { \\\n\n int32: 0, \\\n\n bools: [], \\\n\n string: \\\"\\\", \\\n\n optional_string: None, \\\n\n enumeration: ZERO, \\\n\n enumeration_map: {}, \\\n\n string_map: {}, \\\n\n enumeration_btree_map: {}, \\\n\n string_btree_map: {}, \\\n\n oneof: None \\\n\n }\"\n\n );\n\n basic\n\n .enumeration_map\n\n .insert(0, BasicEnumeration::TWO as i32);\n", "file_path": "tests/src/debug.rs", "rank": 72, "score": 93117.71076785064 }, { "content": "/// Based on [`google::protobuf::UnescapeCEscapeString`][1]\n\n/// [1]: https://github.com/google/protobuf/blob/3.3.x/src/google/protobuf/stubs/strutil.cc#L312-L322\n\nfn unescape_c_escape_string(s: &str) -> Vec<u8> {\n\n let src = s.as_bytes();\n\n let len = src.len();\n\n let mut dst = Vec::new();\n\n\n\n let mut p = 0;\n\n\n\n while p < len {\n\n if src[p] != b'\\\\' {\n\n dst.push(src[p]);\n\n p += 1;\n\n } else {\n\n p += 1;\n\n if p == len {\n\n panic!(\n\n \"invalid c-escaped default binary value ({}): ends with '\\'\",\n\n s\n\n )\n\n }\n\n match src[p] {\n", "file_path": "prost-build/src/code_generator.rs", "rank": 73, "score": 90748.66955680458 }, { "content": "#[test]\n\nfn test() {\n\n use crate::packages::gizmo;\n\n use crate::packages::DoIt;\n\n use prost::Message;\n\n\n\n let mut widget_factory = widget::factory::WidgetFactory::default();\n\n assert_eq!(0, widget_factory.encoded_len());\n\n\n\n widget_factory.inner = Some(widget::factory::widget_factory::Inner {});\n\n assert_eq!(2, widget_factory.encoded_len());\n\n\n\n widget_factory.root = Some(Root {});\n\n assert_eq!(4, widget_factory.encoded_len());\n\n\n\n widget_factory.root_inner = Some(root::Inner {});\n\n assert_eq!(6, widget_factory.encoded_len());\n\n\n\n widget_factory.widget = Some(widget::Widget {});\n\n assert_eq!(8, widget_factory.encoded_len());\n\n\n", "file_path": "tests/src/extern_paths.rs", "rank": 74, "score": 90130.20604700905 }, { "content": "#[test]\n\nfn test() {\n\n use prost::Message;\n\n\n\n let mut widget_factory = widget::factory::WidgetFactory::default();\n\n assert_eq!(0, widget_factory.encoded_len());\n\n\n\n widget_factory.inner = Some(widget::factory::widget_factory::Inner {});\n\n assert_eq!(2, widget_factory.encoded_len());\n\n\n\n widget_factory.root = Some(Root {});\n\n assert_eq!(4, widget_factory.encoded_len());\n\n\n\n widget_factory.root_inner = Some(root::Inner {});\n\n assert_eq!(6, widget_factory.encoded_len());\n\n\n\n widget_factory.widget = Some(widget::Widget {});\n\n assert_eq!(8, widget_factory.encoded_len());\n\n\n\n widget_factory.widget_inner = Some(widget::widget::Inner {});\n\n assert_eq!(10, widget_factory.encoded_len());\n\n\n\n widget_factory.gizmo = Some(gizmo::Gizmo {});\n\n assert_eq!(12, widget_factory.encoded_len());\n\n\n\n widget_factory.gizmo_inner = Some(gizmo::gizmo::Inner {});\n\n assert_eq!(14, widget_factory.encoded_len());\n\n}\n", "file_path": "tests/src/packages/mod.rs", "rank": 75, "score": 90037.61666589024 }, { "content": "#[test]\n\nfn test_well_known_types() {\n\n let msg = Foo {\n\n null: ::prost_types::NullValue::NullValue.into(),\n\n timestamp: Some(::prost_types::Timestamp {\n\n seconds: 99,\n\n nanos: 42,\n\n }),\n\n };\n\n\n\n crate::check_message(&msg);\n\n}\n", "file_path": "tests/src/well_known_types.rs", "rank": 76, "score": 89793.8120918009 }, { "content": "/// Returns the path to the location of the bundled Protobuf artifacts.\n\nfn bundle_path() -> PathBuf {\n\n env::current_dir()\n\n .unwrap()\n\n .join(\"third-party\")\n\n .join(\"protobuf\")\n\n}\n\n\n", "file_path": "prost-build/build.rs", "rank": 77, "score": 83117.27003231696 }, { "content": "fn load_dataset(dataset: &Path) -> Result<BenchmarkDataset, Box<dyn Error>> {\n\n let mut f = File::open(dataset)?;\n\n let mut buf = Vec::new();\n\n f.read_to_end(&mut buf)?;\n\n Ok(BenchmarkDataset::decode(&*buf)?)\n\n}\n\n\n", "file_path": "protobuf/benches/dataset.rs", "rank": 78, "score": 81533.70938858198 }, { "content": "/// Returns the path to the bundled Protobuf include directory.\n\nfn bundled_protoc_include() -> PathBuf {\n\n bundle_path().join(\"include\")\n\n}\n\n\n", "file_path": "prost-build/build.rs", "rank": 79, "score": 80787.81369283539 }, { "content": "/// Compile `.proto` files into Rust files during a Cargo build.\n\n///\n\n/// The generated `.rs` files are written to the Cargo `OUT_DIR` directory, suitable for use with\n\n/// the [include!][1] macro. See the [Cargo `build.rs` code generation][2] example for more info.\n\n///\n\n/// This function should be called in a project's `build.rs`.\n\n///\n\n/// # Arguments\n\n///\n\n/// **`protos`** - Paths to `.proto` files to compile. Any transitively [imported][3] `.proto`\n\n/// files are automatically be included.\n\n///\n\n/// **`includes`** - Paths to directories in which to search for imports. Directories are searched\n\n/// in order. The `.proto` files passed in **`protos`** must be found in one of the provided\n\n/// include directories.\n\n///\n\n/// # Errors\n\n///\n\n/// This function can fail for a number of reasons:\n\n///\n\n/// - Failure to locate or download `protoc`.\n\n/// - Failure to parse the `.proto`s.\n\n/// - Failure to locate an imported `.proto`.\n\n/// - Failure to compile a `.proto` without a [package specifier][4].\n\n///\n\n/// It's expected that this function call be `unwrap`ed in a `build.rs`; there is typically no\n\n/// reason to gracefully recover from errors during a build.\n\n///\n\n/// # Example `build.rs`\n\n///\n\n/// ```rust,no_run\n\n/// fn main() {\n\n/// prost_build::compile_protos(&[\"src/frontend.proto\", \"src/backend.proto\"],\n\n/// &[\"src\"]).unwrap();\n\n/// }\n\n/// ```\n\n///\n\n/// [1]: https://doc.rust-lang.org/std/macro.include.html\n\n/// [2]: http://doc.crates.io/build-script.html#case-study-code-generation\n\n/// [3]: https://developers.google.com/protocol-buffers/docs/proto3#importing-definitions\n\n/// [4]: https://developers.google.com/protocol-buffers/docs/proto#packages\n\npub fn compile_protos<P>(protos: &[P], includes: &[P]) -> Result<()>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n Config::new().compile_protos(protos, includes)\n\n}\n\n\n", "file_path": "prost-build/src/lib.rs", "rank": 80, "score": 80563.38854011155 }, { "content": "/// Serialize from A should equal Serialize from B\n\npub fn check_serialize_equivalent<M, N>(msg_a: &M, msg_b: &N)\n\nwhere\n\n M: Message + Default + PartialEq,\n\n N: Message + Default + PartialEq,\n\n{\n\n let mut buf_a = Vec::new();\n\n msg_a.encode(&mut buf_a).unwrap();\n\n let mut buf_b = Vec::new();\n\n msg_b.encode(&mut buf_b).unwrap();\n\n assert_eq!(buf_a, buf_b);\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\n\n use std::collections::{BTreeMap, BTreeSet};\n\n\n\n use super::*;\n\n use protobuf::test_messages::proto3::TestAllTypesProto3;\n\n\n", "file_path": "tests/src/lib.rs", "rank": 81, "score": 80559.0350307034 }, { "content": "/// Returns the path to the `protoc` pointed to by the `PROTOC` environment variable, if it is set.\n\nfn env_protoc() -> Option<PathBuf> {\n\n let protoc = match env::var_os(\"PROTOC\") {\n\n Some(path) => PathBuf::from(path),\n\n None => return None,\n\n };\n\n\n\n if !protoc.exists() {\n\n panic!(\n\n \"PROTOC environment variable points to non-existent file ({:?})\",\n\n protoc\n\n );\n\n }\n\n\n\n Some(protoc)\n\n}\n\n\n", "file_path": "prost-build/build.rs", "rank": 82, "score": 79310.01662169672 }, { "content": "/// Returns the path to the bundled `protoc`, if it is available for the host platform.\n\nfn bundled_protoc() -> Option<PathBuf> {\n\n let protoc_bin_name = match (env::consts::OS, env::consts::ARCH) {\n\n (\"linux\", \"x86\") => \"protoc-linux-x86_32\",\n\n (\"linux\", \"x86_64\") => \"protoc-linux-x86_64\",\n\n (\"linux\", \"aarch64\") => \"protoc-linux-aarch_64\",\n\n (\"macos\", \"x86_64\") => \"protoc-osx-x86_64\",\n\n (\"windows\", _) => \"protoc-win32.exe\",\n\n _ => return None,\n\n };\n\n\n\n Some(bundle_path().join(protoc_bin_name))\n\n}\n\n\n", "file_path": "prost-build/build.rs", "rank": 83, "score": 79310.01662169672 }, { "content": "/// Returns the path to the `protoc` included on the `PATH`, if it exists.\n\nfn path_protoc() -> Option<PathBuf> {\n\n which::which(\"protoc\").ok()\n\n}\n\n\n", "file_path": "prost-build/build.rs", "rank": 84, "score": 79310.01662169672 }, { "content": "/// Downloads and unpacks a Protobuf release tarball to the provided directory.\n\nfn download_protobuf(out_dir: &Path) -> PathBuf {\n\n download_tarball(\n\n &format!(\n\n \"https://github.com/google/protobuf/archive/v{}.tar.gz\",\n\n VERSION\n\n ),\n\n out_dir,\n\n );\n\n let src_dir = out_dir.join(format!(\"protobuf-{}\", VERSION));\n\n\n\n // Apply patches.\n\n let mut patch_src = env::current_dir().expect(\"failed to get current working directory\");\n\n patch_src.push(\"src\");\n\n patch_src.push(\"fix-conformance_test_runner-cmake-build.patch\");\n\n\n\n let rc = Command::new(\"patch\")\n\n .arg(\"-p1\")\n\n .arg(\"-i\")\n\n .arg(patch_src)\n\n .current_dir(&src_dir)\n\n .status()\n\n .expect(\"failed to apply patch\");\n\n assert!(rc.success(), \"protobuf patch failed\");\n\n\n\n src_dir\n\n}\n\n\n", "file_path": "protobuf/build.rs", "rank": 85, "score": 78054.22892149046 }, { "content": "/// Returns the path to the Protobuf include directory pointed to by the `PROTOC_INCLUDE`\n\n/// environment variable, if it is set.\n\nfn env_protoc_include() -> Option<PathBuf> {\n\n let protoc_include = match env::var_os(\"PROTOC_INCLUDE\") {\n\n Some(path) => PathBuf::from(path),\n\n None => return None,\n\n };\n\n\n\n if !protoc_include.exists() {\n\n panic!(\n\n \"PROTOC_INCLUDE environment variable points to non-existent directory ({:?})\",\n\n protoc_include\n\n );\n\n }\n\n if !protoc_include.is_dir() {\n\n panic!(\n\n \"PROTOC_INCLUDE environment variable points to a non-directory file ({:?})\",\n\n protoc_include\n\n );\n\n }\n\n\n\n Some(protoc_include)\n\n}\n\n\n", "file_path": "prost-build/build.rs", "rank": 86, "score": 77141.93748998249 }, { "content": "use prost::{Enumeration, Message, Oneof};\n\n\n\nuse crate::check_message;\n\nuse crate::check_serialize_equivalent;\n\n\n\n#[derive(Clone, PartialEq, Message)]\n\npub struct RepeatedFloats {\n\n #[prost(float, tag = \"11\")]\n\n pub single_float: f32,\n\n #[prost(float, repeated, packed = \"true\", tag = \"41\")]\n\n pub repeated_float: Vec<f32>,\n\n}\n\n\n\n#[test]\n", "file_path": "tests/src/message_encoding.rs", "rank": 87, "score": 72473.2923510222 }, { "content": " #[prost(tag = \"5\", bytes)]\n\n pub five: Vec<u8>,\n\n #[prost(tag = \"6\", message, required)]\n\n pub six: Basic,\n\n\n\n #[prost(tag = \"9\", string, required)]\n\n pub nine: String,\n\n #[prost(tag = \"10\", enumeration = \"BasicEnumeration\", default = \"ONE\")]\n\n pub ten: i32,\n\n #[prost(tag = \"11\", map = \"string, string\")]\n\n pub eleven: ::std::collections::HashMap<String, String>,\n\n}\n\n\n\n/// A prost message with default value.\n\n#[derive(Clone, PartialEq, Message)]\n\npub struct DefaultValues {\n\n #[prost(int32, tag = \"1\", default = \"42\")]\n\n pub int32: i32,\n\n\n\n #[prost(int32, optional, tag = \"2\", default = \"88\")]\n", "file_path": "tests/src/message_encoding.rs", "rank": 88, "score": 72467.84863619761 }, { "content": "\n\n #[prost(message, repeated, tag = \"3\")]\n\n pub repeated_message: Vec<Basic>,\n\n\n\n #[prost(map = \"sint32, message\", tag = \"4\")]\n\n pub message_map: ::std::collections::HashMap<i32, Basic>,\n\n\n\n #[prost(btree_map = \"sint32, message\", tag = \"5\")]\n\n pub message_btree_map: ::std::collections::BTreeMap<i32, Basic>,\n\n}\n\n\n\n#[derive(Clone, PartialEq, Oneof)]\n\npub enum BasicOneof {\n\n #[prost(int32, tag = \"8\")]\n\n Int(i32),\n\n #[prost(string, tag = \"9\")]\n\n String(String),\n\n}\n", "file_path": "tests/src/message_encoding.rs", "rank": 89, "score": 72465.23193631496 }, { "content": " #[prost(hash_map = \"string, string\", tag = \"7\")]\n\n pub string_map: ::std::collections::HashMap<String, String>,\n\n\n\n #[prost(btree_map = \"int32, enumeration(BasicEnumeration)\", tag = \"10\")]\n\n pub enumeration_btree_map: ::std::collections::BTreeMap<i32, i32>,\n\n\n\n #[prost(btree_map = \"string, string\", tag = \"11\")]\n\n pub string_btree_map: ::std::collections::BTreeMap<String, String>,\n\n\n\n #[prost(oneof = \"BasicOneof\", tags = \"8, 9\")]\n\n pub oneof: Option<BasicOneof>,\n\n}\n\n\n\n#[derive(Clone, PartialEq, Message)]\n\npub struct Compound {\n\n #[prost(message, optional, tag = \"1\")]\n\n pub optional_message: Option<Basic>,\n\n\n\n #[prost(message, required, tag = \"2\")]\n\n pub required_message: Basic,\n", "file_path": "tests/src/message_encoding.rs", "rank": 90, "score": 72464.94528178817 }, { "content": " #[prost(enumeration = \"BasicEnumeration\", default = \"ONE\")]\n\n pub ten: i32,\n\n #[prost(map = \"string, string\")]\n\n pub eleven: ::std::collections::HashMap<String, String>,\n\n\n\n #[prost(tag = \"5\", bytes)]\n\n pub back_to_five: Vec<u8>,\n\n #[prost(message, required)]\n\n pub six: Basic,\n\n}\n\n\n\n#[derive(Clone, PartialEq, Message)]\n\npub struct TagsQualified {\n\n #[prost(tag = \"1\", bool)]\n\n pub one: bool,\n\n #[prost(tag = \"2\", int32, optional)]\n\n pub two: Option<i32>,\n\n #[prost(tag = \"3\", float, repeated)]\n\n pub three: Vec<f32>,\n\n\n", "file_path": "tests/src/message_encoding.rs", "rank": 91, "score": 72461.57978630441 }, { "content": "#[derive(Clone, PartialEq, Message)]\n\npub struct Basic {\n\n #[prost(int32, tag = \"1\")]\n\n pub int32: i32,\n\n\n\n #[prost(bool, repeated, packed = \"false\", tag = \"2\")]\n\n pub bools: Vec<bool>,\n\n\n\n #[prost(string, tag = \"3\")]\n\n pub string: String,\n\n\n\n #[prost(string, optional, tag = \"4\")]\n\n pub optional_string: Option<String>,\n\n\n\n #[prost(enumeration = \"BasicEnumeration\", tag = \"5\")]\n\n pub enumeration: i32,\n\n\n\n #[prost(map = \"int32, enumeration(BasicEnumeration)\", tag = \"6\")]\n\n pub enumeration_map: ::std::collections::HashMap<i32, i32>,\n\n\n", "file_path": "tests/src/message_encoding.rs", "rank": 92, "score": 72460.82345574895 }, { "content": " five: vec![1, 0, 1],\n\n six: Basic::default(),\n\n nine: \"nine\".to_owned(),\n\n ten: 0,\n\n eleven: ::std::collections::HashMap::new(),\n\n };\n\n check_serialize_equivalent(&tags_inferred, &tags_qualified);\n\n}\n\n\n\n#[derive(Clone, PartialEq, Message)]\n\npub struct TagsInferred {\n\n #[prost(bool)]\n\n pub one: bool,\n\n #[prost(int32, optional)]\n\n pub two: Option<i32>,\n\n #[prost(float, repeated)]\n\n pub three: Vec<f32>,\n\n\n\n #[prost(tag = \"9\", string, required)]\n\n pub skip_to_nine: String,\n", "file_path": "tests/src/message_encoding.rs", "rank": 93, "score": 72460.40279898039 }, { "content": " #[prost(int64, required, tag = \"102\")]\n\n pub required_int64: i64,\n\n #[prost(uint32, required, tag = \"103\")]\n\n pub required_uint32: u32,\n\n #[prost(uint64, required, tag = \"104\")]\n\n pub required_uint64: u64,\n\n #[prost(sint32, required, tag = \"105\")]\n\n pub required_sint32: i32,\n\n #[prost(sint64, required, tag = \"106\")]\n\n pub required_sint64: i64,\n\n #[prost(fixed32, required, tag = \"107\")]\n\n pub required_fixed32: u32,\n\n #[prost(fixed64, required, tag = \"108\")]\n\n pub required_fixed64: u64,\n\n #[prost(sfixed32, required, tag = \"109\")]\n\n pub required_sfixed32: i32,\n\n #[prost(sfixed64, required, tag = \"110\")]\n\n pub required_sfixed64: i64,\n\n #[prost(float, required, tag = \"111\")]\n\n pub required_float: f32,\n", "file_path": "tests/src/message_encoding.rs", "rank": 94, "score": 72459.61591076103 }, { "content": " pub fixed32: u32,\n\n #[prost(fixed64, tag = \"008\")]\n\n pub fixed64: u64,\n\n #[prost(sfixed32, tag = \"009\")]\n\n pub sfixed32: i32,\n\n #[prost(sfixed64, tag = \"010\")]\n\n pub sfixed64: i64,\n\n #[prost(float, tag = \"011\")]\n\n pub float: f32,\n\n #[prost(double, tag = \"012\")]\n\n pub double: f64,\n\n #[prost(bool, tag = \"013\")]\n\n pub _bool: bool,\n\n #[prost(string, tag = \"014\")]\n\n pub string: String,\n\n #[prost(bytes, tag = \"015\")]\n\n pub bytes: Vec<u8>,\n\n\n\n #[prost(int32, required, tag = \"101\")]\n\n pub required_int32: i32,\n", "file_path": "tests/src/message_encoding.rs", "rank": 95, "score": 72459.1879655836 }, { "content": "\n\n #[prost(int32, repeated, packed = \"false\", tag = \"301\")]\n\n pub repeated_int32: Vec<i32>,\n\n #[prost(int64, repeated, packed = \"false\", tag = \"302\")]\n\n pub repeated_int64: Vec<i64>,\n\n #[prost(uint32, repeated, packed = \"false\", tag = \"303\")]\n\n pub repeated_uint32: Vec<u32>,\n\n #[prost(uint64, repeated, packed = \"false\", tag = \"304\")]\n\n pub repeated_uint64: Vec<u64>,\n\n #[prost(sint32, repeated, packed = \"false\", tag = \"305\")]\n\n pub repeated_sint32: Vec<i32>,\n\n #[prost(sint64, repeated, packed = \"false\", tag = \"306\")]\n\n pub repeated_sint64: Vec<i64>,\n\n #[prost(fixed32, repeated, packed = \"false\", tag = \"307\")]\n\n pub repeated_fixed32: Vec<u32>,\n\n #[prost(fixed64, repeated, packed = \"false\", tag = \"308\")]\n\n pub repeated_fixed64: Vec<u64>,\n\n #[prost(sfixed32, repeated, packed = \"false\", tag = \"309\")]\n\n pub repeated_sfixed32: Vec<i32>,\n\n #[prost(sfixed64, repeated, packed = \"false\", tag = \"310\")]\n", "file_path": "tests/src/message_encoding.rs", "rank": 96, "score": 72458.75043022893 }, { "content": " #[prost(double, required, tag = \"112\")]\n\n pub required_double: f64,\n\n #[prost(bool, required, tag = \"113\")]\n\n pub required_bool: bool,\n\n #[prost(string, required, tag = \"114\")]\n\n pub required_string: String,\n\n #[prost(bytes, required, tag = \"115\")]\n\n pub required_bytes: Vec<u8>,\n\n\n\n #[prost(int32, optional, tag = \"201\")]\n\n pub optional_int32: Option<i32>,\n\n #[prost(int64, optional, tag = \"202\")]\n\n pub optional_int64: Option<i64>,\n\n #[prost(uint32, optional, tag = \"203\")]\n\n pub optional_uint32: Option<u32>,\n\n #[prost(uint64, optional, tag = \"204\")]\n\n pub optional_uint64: Option<u64>,\n\n #[prost(sint32, optional, tag = \"205\")]\n\n pub optional_sint32: Option<i32>,\n\n #[prost(sint64, optional, tag = \"206\")]\n", "file_path": "tests/src/message_encoding.rs", "rank": 97, "score": 72458.42159149463 }, { "content": " pub optional_sint64: Option<i64>,\n\n\n\n #[prost(fixed32, optional, tag = \"207\")]\n\n pub optional_fixed32: Option<u32>,\n\n #[prost(fixed64, optional, tag = \"208\")]\n\n pub optional_fixed64: Option<u64>,\n\n #[prost(sfixed32, optional, tag = \"209\")]\n\n pub optional_sfixed32: Option<i32>,\n\n #[prost(sfixed64, optional, tag = \"210\")]\n\n pub optional_sfixed64: Option<i64>,\n\n #[prost(float, optional, tag = \"211\")]\n\n pub optional_float: Option<f32>,\n\n #[prost(double, optional, tag = \"212\")]\n\n pub optional_double: Option<f64>,\n\n #[prost(bool, optional, tag = \"213\")]\n\n pub optional_bool: Option<bool>,\n\n #[prost(string, optional, tag = \"214\")]\n\n pub optional_string: Option<String>,\n\n #[prost(bytes, optional, tag = \"215\")]\n\n pub optional_bytes: Option<Vec<u8>>,\n", "file_path": "tests/src/message_encoding.rs", "rank": 98, "score": 72458.26481186235 }, { "content": " #[prost(sint32, repeated, tag = \"405\")]\n\n pub packed_sint32: Vec<i32>,\n\n #[prost(sint64, repeated, tag = \"406\")]\n\n pub packed_sint64: Vec<i64>,\n\n #[prost(fixed32, repeated, tag = \"407\")]\n\n pub packed_fixed32: Vec<u32>,\n\n\n\n #[prost(fixed64, repeated, tag = \"408\")]\n\n pub packed_fixed64: Vec<u64>,\n\n #[prost(sfixed32, repeated, tag = \"409\")]\n\n pub packed_sfixed32: Vec<i32>,\n\n #[prost(sfixed64, repeated, tag = \"410\")]\n\n pub packed_sfixed64: Vec<i64>,\n\n #[prost(float, repeated, tag = \"411\")]\n\n pub packed_float: Vec<f32>,\n\n #[prost(double, repeated, tag = \"412\")]\n\n pub packed_double: Vec<f64>,\n\n #[prost(bool, repeated, tag = \"413\")]\n\n pub packed_bool: Vec<bool>,\n\n #[prost(string, repeated, tag = \"415\")]\n\n pub packed_string: Vec<String>,\n\n #[prost(bytes, repeated, tag = \"416\")]\n\n pub packed_bytes: Vec<Vec<u8>>,\n\n}\n\n\n", "file_path": "tests/src/message_encoding.rs", "rank": 99, "score": 72458.15407958189 } ]
Rust
src/page.rs
matthiasbeyer/elefren
04dbf66451e9d93be971f3409a05d2f8a14a6e04
use super::{deserialise_blocking, Mastodon, Result}; use crate::entities::itemsiter::ItemsIter; use hyper_old_types::header::{parsing, Link, RelationType}; use reqwest::{header::LINK, Response}; use serde::Deserialize; use url::Url; macro_rules! pages { ($($direction:ident: $fun:ident),*) => { $( doc_comment::doc_comment!(concat!( "Method to retrieve the ", stringify!($direction), " page of results"), pub fn $fun(&mut self) -> Result<Option<Vec<T>>> { let url = match self.$direction.take() { Some(s) => s, None => return Ok(None), }; let response = self.mastodon.send_blocking( self.mastodon.client.get(url) )?; let (prev, next) = get_links(&response)?; self.next = next; self.prev = prev; deserialise_blocking(response) }); )* } } #[derive(Debug, Clone)] pub struct OwnedPage<T: for<'de> Deserialize<'de>> { mastodon: Mastodon, next: Option<Url>, prev: Option<Url>, pub initial_items: Vec<T>, } impl<T: for<'de> Deserialize<'de>> OwnedPage<T> { pages! { next: next_page, prev: prev_page } } impl<'a, T: for<'de> Deserialize<'de>> From<Page<'a, T>> for OwnedPage<T> { fn from(page: Page<'a, T>) -> OwnedPage<T> { OwnedPage { mastodon: page.mastodon.clone(), next: page.next, prev: page.prev, initial_items: page.initial_items, } } } #[derive(Debug, Clone)] pub struct Page<'a, T: for<'de> Deserialize<'de>> { mastodon: &'a Mastodon, next: Option<Url>, prev: Option<Url>, pub initial_items: Vec<T>, } impl<'a, T: for<'de> Deserialize<'de>> Page<'a, T> { pages! { next: next_page, prev: prev_page } pub(crate) fn new(mastodon: &'a Mastodon, response: Response) -> Result<Self> { let (prev, next) = get_links(&response)?; Ok(Page { initial_items: deserialise_blocking(response)?, next, prev, mastodon, }) } } impl<'a, T: Clone + for<'de> Deserialize<'de>> Page<'a, T> { pub fn into_owned(self) -> OwnedPage<T> { OwnedPage::from(self) } pub fn items_iter(self) -> impl Iterator<Item = T> + 'a where T: 'a, { ItemsIter::new(self) } } fn get_links(response: &Response) -> Result<(Option<Url>, Option<Url>)> { let mut prev = None; let mut next = None; if let Some(link_header) = response.headers().get(LINK) { let link_header = link_header.to_str()?; let link_header = link_header.as_bytes(); let link_header: Link = parsing::from_raw_str(&link_header)?; for value in link_header.values() { if let Some(relations) = value.rel() { if relations.contains(&RelationType::Next) { next = Some(Url::parse(value.link())?); } if relations.contains(&RelationType::Prev) { prev = Some(Url::parse(value.link())?); } } } } Ok((prev, next)) }
use super::{deserialise_blocking, Mastodon, Result}; use crate::entities::itemsiter::ItemsIter; use hyper_old_types::header::{parsing, Link, RelationType}; use reqwest::{header::LINK, Response}; use serde::Deserialize; use url::Url; macro_rules! pages { ($($direction:ident: $fun:ident),*) => { $( doc_comment::doc_comment!(concat!( "Method to retrieve the ", stringify!($direction), " page of results"), pub fn $fun(&mut self) -> Result<Option<Vec<T>>> { let url = match self.$direction.take() { Some(s) => s, None => return Ok(None), }; let response = self.mastodon.send_blocking( self.mastodon.client.get(url) )?; let (prev, next) = get_links(&response)?; self.next = next; self.prev = prev; deserialise_blocking(response) }); )* } } #[derive(Debug, Clone)] pub struct OwnedPage<T: for<'de> Deserialize<'de>> { mastodon: Mastodon, next: Option<Url>, prev: Option<Url>, pub initial_items: Vec<T>, } impl<T: for<'de> Deserialize<'de>> OwnedPage<T> { pages! { next: next_page, prev: prev_page } } impl<'a, T: for<'de> Deserialize<'de>> From<Page<'a, T>> for OwnedPage<T> { fn from(page: Page<'a, T>) -> OwnedPage<T> { OwnedPage { mastodon: page.mastodon.clone(), next: page.next, prev: page.prev, initial_items: page.initial_items, } } } #[derive(Debug, Clone)] pub struct Page<'a, T: for<'de> Deserialize<'de>> { mastodon: &'a Mastodon, next: Option<Url>, prev: Option<Url>, pub initial_items: Vec<T>, } impl<'a, T: for<'de> Deserialize<'de>> Page<'a, T> { pages! { next: next_page, prev: prev_page } pub(crate) fn new(mastodon: &'a Mastodon, response: Response) -> Result<Self> { let (prev, next) = get_links(&response)?; Ok(Page { initial_items: deserialise_blocking(response)?, next, prev, mastodon, }) } } impl<'a, T: Clone + for<'de> Deserialize<'de>> Page<'a, T> { pub fn into_owned(self) -> OwnedPage<T> { OwnedPage::from(self) } pub fn items_iter(self) -> impl Iterator<Item = T> + 'a where T: 'a, { ItemsIter::new(self) } } fn get_links(response: &Response) -> Result<(Option<Url>, Option<Url>)> { let mut prev = None; let mut next = None; if let Some(link_header) = response.headers().get(LINK) { let link_header = link_header.to_str()?; let link_header = link_header.as_bytes(); let link_header: Link = parsing::from_raw_str(&link_header)?; for value in link_header.values() { if let Some(relations) = value.rel() {
if relations.contains(&RelationType::Prev) { prev = Some(Url::parse(value.link())?); } } } } Ok((prev, next)) }
if relations.contains(&RelationType::Next) { next = Some(Url::parse(value.link())?); }
if_condition
[ { "content": "fn get_links(response: &Response) -> Result<(Option<Url>, Option<Url>)> {\n\n let mut prev = None;\n\n let mut next = None;\n\n\n\n if let Some(link_header) = response.header(LINK) {\n\n let link_header = link_header.as_str();\n\n let link_header = link_header.as_bytes();\n\n let link_header: Link = parsing::from_raw_str(&link_header)?;\n\n for value in link_header.values() {\n\n if let Some(relations) = value.rel() {\n\n if relations.contains(&RelationType::Next) {\n\n next = Some(Url::parse(value.link())?);\n\n }\n\n\n\n if relations.contains(&RelationType::Prev) {\n\n prev = Some(Url::parse(value.link())?);\n\n }\n\n }\n\n }\n\n }\n\n\n\n Ok((prev, next))\n\n}\n", "file_path": "src/async/page.rs", "rank": 1, "score": 180936.2951532458 }, { "content": "/// Finishes the authentication process for the given `Registered` object,\n\n/// using the command-line\n\npub fn authenticate(registration: Registered) -> Result<Mastodon> {\n\n let url = registration.authorize_url()?;\n\n\n\n let stdout = io::stdout();\n\n let stdin = io::stdin();\n\n\n\n let mut stdout = stdout.lock();\n\n let mut stdin = stdin.lock();\n\n\n\n writeln!(&mut stdout, \"Click this link to authorize: {}\", url)?;\n\n write!(&mut stdout, \"Paste the returned authorization code: \")?;\n\n stdout.flush()?;\n\n\n\n let mut input = String::new();\n\n stdin.read_line(&mut input)?;\n\n let code = input.trim();\n\n Ok(registration.complete(code)?)\n\n}\n", "file_path": "src/helpers/cli.rs", "rank": 2, "score": 170907.865955243 }, { "content": "#[allow(dead_code)]\n\n#[cfg(feature = \"toml\")]\n\npub fn get_mastodon_data() -> Result<Mastodon, Box<dyn Error>> {\n\n if let Ok(data) = toml::from_file(\"mastodon-data.toml\") {\n\n Ok(Mastodon::from(data))\n\n } else {\n\n register()\n\n }\n\n}\n\n\n", "file_path": "examples/register/mod.rs", "rank": 3, "score": 166216.12448432925 }, { "content": "#[cfg(feature = \"toml\")]\n\npub fn register() -> Result<Mastodon, Box<dyn Error>> {\n\n let website = read_line(\"Please enter your mastodon instance url:\")?;\n\n let registration = Registration::new(website.trim())\n\n .client_name(\"elefren-examples\")\n\n .scopes(Scopes::all())\n\n .website(\"https://github.com/pwoolcoc/elefren\")\n\n .build()?;\n\n let mastodon = cli::authenticate(registration)?;\n\n\n\n // Save app data for using on the next run.\n\n toml::to_file(&*mastodon, \"mastodon-data.toml\")?;\n\n\n\n Ok(mastodon)\n\n}\n\n\n", "file_path": "examples/register/mod.rs", "rank": 4, "score": 162944.2578171208 }, { "content": "/// Attempts to deserialize a Data struct from something that implements\n\n/// the std::io::Read trait\n\npub fn from_reader<R: Read>(mut r: R) -> Result<Data> {\n\n let mut buffer = Vec::new();\n\n r.read_to_end(&mut buffer)?;\n\n from_slice(&buffer)\n\n}\n\n\n", "file_path": "src/helpers/json.rs", "rank": 5, "score": 152878.23892298865 }, { "content": "/// Attempts to deserialize a Data struct from something that implements\n\n/// the std::io::Read trait\n\npub fn from_reader<R: Read>(mut r: R) -> Result<Data> {\n\n let mut buffer = Vec::new();\n\n r.read_to_end(&mut buffer)?;\n\n from_slice(&buffer)\n\n}\n\n\n", "file_path": "src/helpers/toml.rs", "rank": 6, "score": 152878.23892298865 }, { "content": "/// Attempts to deserialize a Data struct from the environment\n\npub fn from_env() -> Result<Data> {\n\n Ok(envy::from_env()?)\n\n}\n\n\n", "file_path": "src/helpers/env.rs", "rank": 7, "score": 140197.55460770027 }, { "content": "/// Attempts to deserialize a Data struct from a string\n\npub fn from_str(s: &str) -> Result<Data> {\n\n Ok(serde_json::from_str(s)?)\n\n}\n\n\n", "file_path": "src/helpers/json.rs", "rank": 8, "score": 129590.36932499602 }, { "content": "/// Attempts to deserialize a Data struct from a string\n\npub fn from_str(s: &str) -> Result<Data> {\n\n Ok(toml::from_str(s)?)\n\n}\n\n\n", "file_path": "src/helpers/toml.rs", "rank": 9, "score": 129590.36932499602 }, { "content": "/// Attempts to deserialize a Data struct from a slice of bytes\n\npub fn from_slice(s: &[u8]) -> Result<Data> {\n\n Ok(serde_json::from_slice(s)?)\n\n}\n\n\n", "file_path": "src/helpers/json.rs", "rank": 10, "score": 129590.24468556402 }, { "content": "/// Attempts to deserialize a Data struct from a slice of bytes\n\npub fn from_slice(s: &[u8]) -> Result<Data> {\n\n Ok(toml::from_slice(s)?)\n\n}\n\n\n", "file_path": "src/helpers/toml.rs", "rank": 11, "score": 129590.24468556404 }, { "content": "/// Attempts to serialize a Data struct to a String\n\npub fn to_string(data: &Data) -> Result<String> {\n\n Ok(serde_json::to_string_pretty(data)?)\n\n}\n\n\n", "file_path": "src/helpers/json.rs", "rank": 12, "score": 126385.23804050959 }, { "content": "/// Attempts to serialize a Data struct to a String\n\npub fn to_string(data: &Data) -> Result<String> {\n\n Ok(toml::to_string_pretty(data)?)\n\n}\n\n\n", "file_path": "src/helpers/toml.rs", "rank": 13, "score": 126385.23804050959 }, { "content": "/// Attempts to deserialize a Data struct from the environment. All keys are\n\n/// prefixed with the given prefix\n\npub fn from_env_prefixed(prefix: &str) -> Result<Data> {\n\n Ok(envy::prefixed(prefix).from_env()?)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::{\n\n env,\n\n ops::FnOnce,\n\n panic::{catch_unwind, UnwindSafe},\n\n };\n\n\n\n fn withenv<F: FnOnce() -> R + UnwindSafe, R>(prefix: Option<&'static str>, test: F) -> R {\n\n env::set_var(makekey(prefix, \"BASE\"), \"https://example.com\");\n\n env::set_var(makekey(prefix, \"CLIENT_ID\"), \"adbc01234\");\n\n env::set_var(makekey(prefix, \"CLIENT_SECRET\"), \"0987dcba\");\n\n env::set_var(makekey(prefix, \"REDIRECT\"), \"urn:ietf:wg:oauth:2.0:oob\");\n\n env::set_var(makekey(prefix, \"TOKEN\"), \"fedc5678\");\n\n\n", "file_path": "src/helpers/env.rs", "rank": 14, "score": 123423.33011701619 }, { "content": "/// Attempts to serialize a Data struct to a Vec of bytes\n\npub fn to_vec(data: &Data) -> Result<Vec<u8>> {\n\n Ok(serde_json::to_vec(data)?)\n\n}\n\n\n", "file_path": "src/helpers/json.rs", "rank": 15, "score": 120526.59506461295 }, { "content": "/// Attempts to serialize a Data struct to a Vec of bytes\n\npub fn to_vec(data: &Data) -> Result<Vec<u8>> {\n\n Ok(toml::to_vec(data)?)\n\n}\n\n\n", "file_path": "src/helpers/toml.rs", "rank": 16, "score": 120526.59506461295 }, { "content": "/// Attempts to deserialize a Data struct from a file\n\npub fn from_file<P: AsRef<Path>>(path: P) -> Result<Data> {\n\n let path = path.as_ref();\n\n let file = File::open(path)?;\n\n Ok(from_reader(file)?)\n\n}\n\n\n", "file_path": "src/helpers/json.rs", "rank": 17, "score": 110398.01171435442 }, { "content": "/// Attempts to deserialize a Data struct from a file\n\npub fn from_file<P: AsRef<Path>>(path: P) -> Result<Data> {\n\n let path = path.as_ref();\n\n let file = File::open(path)?;\n\n Ok(from_reader(file)?)\n\n}\n\n\n", "file_path": "src/helpers/toml.rs", "rank": 18, "score": 110398.01171435442 }, { "content": "/// Attempts to serialize a Data struct to something that implements the\n\n/// std::io::Write trait\n\npub fn to_writer<W: Write>(data: &Data, writer: W) -> Result<()> {\n\n let mut buf_writer = BufWriter::new(writer);\n\n let vec = to_vec(data)?;\n\n buf_writer.write_all(&vec)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/helpers/json.rs", "rank": 19, "score": 110393.54982138009 }, { "content": "/// Attempts to serialize a Data struct to something that implements the\n\n/// std::io::Write trait\n\npub fn to_writer<W: Write>(data: &Data, writer: W) -> Result<()> {\n\n let mut buf_writer = BufWriter::new(writer);\n\n let vec = to_vec(data)?;\n\n buf_writer.write_all(&vec)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/helpers/toml.rs", "rank": 20, "score": 110393.54982138009 }, { "content": "#[cfg(feature = \"toml\")]\n\npub fn read_line(message: &str) -> Result<String, Box<dyn Error>> {\n\n println!(\"{}\", message);\n\n\n\n let mut input = String::new();\n\n io::stdin().read_line(&mut input)?;\n\n\n\n Ok(input.trim().to_string())\n\n}\n\n\n", "file_path": "examples/register/mod.rs", "rank": 21, "score": 107992.99244526603 }, { "content": "/// Attempts to serialize a Data struct to a file\n\n///\n\n/// When opening the file, this will set the `.write(true)` and\n\n/// `.truncate(true)` options, use the next method for more\n\n/// fine-grained control\n\npub fn to_file<P: AsRef<Path>>(data: &Data, path: P) -> Result<()> {\n\n let mut options = OpenOptions::new();\n\n options.create(true).write(true).truncate(true);\n\n to_file_with_options(data, path, options)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/helpers/json.rs", "rank": 22, "score": 105984.99657290158 }, { "content": "/// Attempts to serialize a Data struct to a file\n\n///\n\n/// When opening the file, this will set the `.write(true)` and\n\n/// `.truncate(true)` options, use the next method for more\n\n/// fine-grained control\n\npub fn to_file<P: AsRef<Path>>(data: &Data, path: P) -> Result<()> {\n\n let mut options = OpenOptions::new();\n\n options.create(true).write(true).truncate(true);\n\n to_file_with_options(data, path, options)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/helpers/toml.rs", "rank": 23, "score": 105984.99657290158 }, { "content": "fn string_or_bool<'de, D: de::Deserializer<'de>>(val: D) -> ::std::result::Result<bool, D::Error> {\n\n #[derive(Clone, Debug, Deserialize, PartialEq)]\n\n #[serde(untagged)]\n\n pub enum BoolOrString {\n\n Bool(bool),\n\n Str(String),\n\n }\n\n\n\n Ok(match BoolOrString::deserialize(val)? {\n\n BoolOrString::Bool(b) => b,\n\n BoolOrString::Str(ref s) => {\n\n if s == \"true\" {\n\n true\n\n } else if s == \"false\" {\n\n false\n\n } else {\n\n return Err(de::Error::invalid_value(\n\n Unexpected::Str(s),\n\n &\"true or false\",\n\n ));\n", "file_path": "src/entities/account.rs", "rank": 24, "score": 95489.93945769928 }, { "content": "struct MastodonBuilder {\n\n client: Option<Client>,\n\n data: Option<Data>,\n\n}\n\n\n\nimpl MastodonBuilder {\n\n pub fn new() -> Self {\n\n MastodonBuilder {\n\n client: None,\n\n data: None,\n\n }\n\n }\n\n\n\n pub fn client(&mut self, client: Client) -> &mut Self {\n\n self.client = Some(client);\n\n self\n\n }\n\n\n\n pub fn data(&mut self, data: Data) -> &mut Self {\n\n self.data = Some(data);\n", "file_path": "src/lib.rs", "rank": 25, "score": 93374.53273001185 }, { "content": "#[allow(unused)]\n\n#[async_trait::async_trait]\n\npub trait MastodonClient {\n\n /// Type that wraps streaming API streams\n\n type Stream: Iterator<Item = Event>;\n\n\n\n /// GET /api/v1/favourites\n\n fn favourites(&self) -> Result<Page<Status>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/blocks\n\n fn blocks(&self) -> Result<Page<Account>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/domain_blocks\n\n fn domain_blocks(&self) -> Result<Page<String>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/follow_requests\n\n fn follow_requests(&self) -> Result<Page<Account>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n", "file_path": "src/mastodon_client.rs", "rank": 26, "score": 92751.74928622787 }, { "content": "#[allow(unused)]\n\npub trait MastodonUnauthenticated {\n\n /// GET /api/v1/statuses/:id\n\n fn get_status(&self, id: &str) -> Result<Status> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/statuses/:id/context\n\n fn get_context(&self, id: &str) -> Result<Context> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/statuses/:id/card\n\n fn get_card(&self, id: &str) -> Result<Card> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/statuses/:id/reblogged_by\n\n fn reblogged_by(&self, id: &str) -> Result<Page<Account>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/statuses/:id/favourited_by\n\n fn favourited_by(&self, id: &str) -> Result<Page<Account>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n}\n", "file_path": "src/mastodon_client.rs", "rank": 27, "score": 92751.74928622787 }, { "content": "// Convert the HTTP response body from JSON. Pass up deserialization errors\n\n// transparently.\n\nfn deserialise_blocking<T: for<'de> serde::Deserialize<'de>>(response: Response) -> Result<T> {\n\n let handle = tokio::runtime::Handle::current();\n\n\n\n let bytes = handle.block_on(response.bytes())?;\n\n\n\n match serde_json::from_slice(&bytes) {\n\n Ok(t) => {\n\n log::debug!(\"{}\", String::from_utf8_lossy(&bytes));\n\n Ok(t)\n\n },\n\n // If deserializing into the desired type fails try again to\n\n // see if this is an error response.\n\n Err(e) => {\n\n log::error!(\"{}\", String::from_utf8_lossy(&bytes));\n\n if let Ok(error) = serde_json::from_slice(&bytes) {\n\n return Err(Error::Api(error));\n\n }\n\n Err(e.into())\n\n },\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 28, "score": 92522.9202890832 }, { "content": "struct DeserializeScopesVisitor;\n\n\n\nimpl<'de> Visitor<'de> for DeserializeScopesVisitor {\n\n type Value = Scopes;\n\n\n\n fn expecting(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {\n\n write!(formatter, \"space separated scopes\")\n\n }\n\n\n\n fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>\n\n where\n\n E: de::Error,\n\n {\n\n Scopes::from_str(v).map_err(de::Error::custom)\n\n }\n\n}\n\n\n\nimpl<'de> Deserialize<'de> for Scopes {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>\n\n where\n", "file_path": "src/scopes.rs", "rank": 29, "score": 90611.30037954832 }, { "content": "#[allow(dead_code)]\n\n#[cfg(feature = \"toml\")]\n\nfn main() -> Result<(), Box<dyn Error>> {\n\n register()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "examples/register/mod.rs", "rank": 30, "score": 87844.14855312528 }, { "content": "/// Attempts to serialize a Data struct to a file\n\npub fn to_file_with_options<P: AsRef<Path>>(\n\n data: &Data,\n\n path: P,\n\n options: OpenOptions,\n\n) -> Result<()> {\n\n let path = path.as_ref();\n\n let file = options.open(path)?;\n\n to_writer(data, file)?;\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::{fs::OpenOptions, io::Cursor};\n\n use tempfile::{tempdir, NamedTempFile};\n\n\n\n const DOC: &'static str = indoc::indoc!(\n\n r#\"\n\n base = \"https://example.com\"\n", "file_path": "src/helpers/toml.rs", "rank": 31, "score": 86250.72392872641 }, { "content": "/// Attempts to serialize a Data struct to a file\n\npub fn to_file_with_options<P: AsRef<Path>>(\n\n data: &Data,\n\n path: P,\n\n options: OpenOptions,\n\n) -> Result<()> {\n\n let path = path.as_ref();\n\n let file = options.open(path)?;\n\n to_writer(data, file)?;\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::{fs::OpenOptions, io::Cursor};\n\n use tempfile::{tempdir, NamedTempFile};\n\n\n\n const DOC: &'static str = indoc::indoc!(\n\n r#\"\n\n {\n", "file_path": "src/helpers/json.rs", "rank": 32, "score": 86250.72392872641 }, { "content": "#[cfg(feature = \"toml\")]\n\nfn main() -> Result<(), Box<dyn error::Error>> {\n\n let mastodon = register::get_mastodon_data()?;\n\n for account in mastodon.follows_me()?.items_iter() {\n\n println!(\"{}\", account.acct);\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "examples/follows_me.rs", "rank": 33, "score": 85681.2979332315 }, { "content": "#[cfg(feature = \"toml\")]\n\nfn main() -> Result<(), Box<dyn error::Error>> {\n\n let mastodon = register::get_mastodon_data()?;\n\n let input = register::read_line(\"Enter the term you'd like to search: \")?;\n\n let result = mastodon.search(&input, false)?;\n\n\n\n println!(\"{:#?}\", result);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "examples/search.rs", "rank": 34, "score": 85681.2979332315 }, { "content": "#[cfg(feature = \"toml\")]\n\nfn main() -> Result<(), Box<dyn error::Error>> {\n\n let mastodon = register::get_mastodon_data()?;\n\n let input = register::read_line(\"Enter the path to the photo you'd like to post: \")?;\n\n\n\n mastodon.media(input.into())?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "examples/upload_photo.rs", "rank": 35, "score": 83550.45174560526 }, { "content": "#[cfg(feature = \"toml\")]\n\nfn main() -> Result<(), Box<dyn error::Error>> {\n\n let mastodon = register::get_mastodon_data()?;\n\n let tl = mastodon.get_home_timeline()?;\n\n\n\n println!(\"{:#?}\", tl);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "examples/home_timeline.rs", "rank": 36, "score": 83550.45174560526 }, { "content": "#[cfg(feature = \"toml\")]\n\nfn main() -> Result<(), Box<dyn error::Error>> {\n\n let mastodon = register::get_mastodon_data()?;\n\n let input = register::read_line(\"Enter the account id you'd like to follow: \")?;\n\n let new_follow = mastodon.follow(input.trim())?;\n\n\n\n println!(\"{:#?}\", new_follow);\n\n Ok(())\n\n}\n\n\n", "file_path": "examples/follow_profile.rs", "rank": 37, "score": 83550.45174560526 }, { "content": "#[cfg(feature = \"toml\")]\n\nfn main() -> Result<(), Box<dyn error::Error>> {\n\n let mastodon = register::get_mastodon_data()?;\n\n let you = mastodon.verify_credentials()?;\n\n\n\n println!(\"{:#?}\", you);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "examples/print_your_profile.rs", "rank": 38, "score": 83550.45174560526 }, { "content": "#[derive(Deserialize)]\n\nstruct AccessToken {\n\n access_token: String,\n\n}\n\n\n\nimpl<'a> Registration<'a> {\n\n /// Construct a new registration process to the instance of the `base` url.\n\n /// ```\n\n /// use elefren::prelude::*;\n\n ///\n\n /// let registration = Registration::new(\"https://mastodon.social\");\n\n /// ```\n\n pub fn new<I: Into<String>>(base: I) -> Self {\n\n Registration {\n\n base: base.into(),\n\n client: Client::new(),\n\n app_builder: AppBuilder::new(),\n\n force_login: false,\n\n }\n\n }\n\n}\n", "file_path": "src/registration.rs", "rank": 39, "score": 60000.58364281237 }, { "content": "#[derive(Deserialize)]\n\nstruct OAuth {\n\n client_id: String,\n\n client_secret: String,\n\n #[serde(default = \"default_redirect_uri\")]\n\n redirect_uri: String,\n\n}\n\n\n", "file_path": "src/registration.rs", "rank": 40, "score": 60000.58364281237 }, { "content": "#[cfg(not(feature = \"toml\"))]\n\nfn main() {\n\n println!(\n\n \"examples require the `toml` feature, run this command for this example:\\n\\ncargo run \\\n\n --example print_your_profile --features toml\\n\"\n\n );\n\n}\n", "file_path": "examples/follows_me.rs", "rank": 41, "score": 56537.53020699243 }, { "content": "#[cfg(not(feature = \"toml\"))]\n\nfn main() {\n\n println!(\n\n \"examples require the `toml` feature, run this command for this example:\\n\\ncargo run \\\n\n --example search --features toml\\n\"\n\n );\n\n}\n", "file_path": "examples/search.rs", "rank": 42, "score": 56537.53020699243 }, { "content": "#[cfg(not(feature = \"toml\"))]\n\nfn main() {\n\n println!(\n\n \"examples require the `toml` feature, run this command for this example:\\n\\ncargo run \\\n\n --example print_your_profile --features toml\\n\"\n\n );\n\n}\n", "file_path": "examples/home_timeline.rs", "rank": 43, "score": 54897.54264595386 }, { "content": "#[cfg(not(feature = \"toml\"))]\n\nfn main() {}\n", "file_path": "examples/register/mod.rs", "rank": 44, "score": 54897.54264595386 }, { "content": "#[cfg(not(feature = \"toml\"))]\n\nfn main() {\n\n println!(\n\n \"examples require the `toml` feature, run this command for this example:\\n\\ncargo run \\\n\n --example print_your_profile --features toml\\n\"\n\n );\n\n}\n", "file_path": "examples/print_your_profile.rs", "rank": 45, "score": 54897.54264595386 }, { "content": "#[cfg(not(feature = \"toml\"))]\n\nfn main() {\n\n println!(\n\n \"examples require the `toml` feature, run this command for this example:\\n\\ncargo run \\\n\n --example upload_photo --features toml\\n\"\n\n );\n\n}\n", "file_path": "examples/upload_photo.rs", "rank": 46, "score": 54897.54264595386 }, { "content": "#[cfg(not(feature = \"toml\"))]\n\nfn main() {\n\n println!(\n\n \"examples require the `toml` feature, run this command for this example:\\n\\ncargo run \\\n\n --example follow_profile --features toml\\n\"\n\n );\n\n}\n", "file_path": "examples/follow_profile.rs", "rank": 47, "score": 54897.54264595386 }, { "content": "#[async_trait::async_trait]\n\npub trait Authenticate {\n\n async fn authenticate(&self, request: &mut Request) -> Result<()>;\n\n}\n\n\n\n/// The null-strategy, will only allow the client to call public API endpoints\n\n#[derive(Debug, Clone, Copy, PartialEq)]\n\npub struct Unauthenticated;\n\n#[async_trait::async_trait]\n\nimpl Authenticate for Unauthenticated {\n\n async fn authenticate(&self, _: &mut Request) -> Result<()> {\n\n Ok(())\n\n }\n\n}\n\n\n\n/// Authenticates to the server via oauth\n\n#[derive(Debug, Clone, PartialEq)]\n\npub struct OAuth {\n\n client_id: String,\n\n client_secret: String,\n\n redirect: String,\n\n token: String,\n\n}\n\n#[async_trait::async_trait]\n\nimpl Authenticate for Mutex<RefCell<Option<OAuth>>> {\n\n async fn authenticate(&self, _: &mut Request) -> Result<()> {\n\n unimplemented!()\n\n }\n\n}\n", "file_path": "src/async/auth.rs", "rank": 48, "score": 53563.182614909376 }, { "content": "/// A type that streaming events can be read from\n\npub trait EventStream {\n\n /// Read a message from this stream\n\n fn read_message(&mut self) -> Result<String>;\n\n}\n\n\n\nimpl<R: BufRead> EventStream for R {\n\n fn read_message(&mut self) -> Result<String> {\n\n let mut buf = String::new();\n\n self.read_line(&mut buf)?;\n\n Ok(buf)\n\n }\n\n}\n\n\n\nimpl EventStream for WebSocket {\n\n fn read_message(&mut self) -> Result<String> {\n\n Ok(self.0.read_message()?.into_text()?)\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n", "file_path": "src/lib.rs", "rank": 49, "score": 53563.182614909376 }, { "content": "fn default_redirect_uri() -> String {\n\n DEFAULT_REDIRECT_URI.to_string()\n\n}\n\n\n", "file_path": "src/registration.rs", "rank": 50, "score": 50026.534874794495 }, { "content": " let items = deserialize(response).await?;\n\n Ok(items)\n\n }\n\n\n\n fn fill_links_from_resp(&mut self, response: &Response) -> Result<()> {\n\n let (prev, next) = get_links(&response)?;\n\n self.prev = prev.map(|url| Request::new(Method::Get, url));\n\n self.next = next.map(|url| Request::new(Method::Get, url));\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "src/async/page.rs", "rank": 61, "score": 35168.52214050354 }, { "content": " prev: Option<Request>,\n\n auth: &'client A,\n\n _marker: std::marker::PhantomData<T>,\n\n}\n\nimpl<'client, T: serde::de::DeserializeOwned, A: Authenticate + Debug + 'client>\n\n Page<'client, T, A>\n\n{\n\n pub fn new(next: Request, auth: &'client A) -> Page<'client, T, A> {\n\n Page {\n\n next: Some(next),\n\n prev: None,\n\n auth,\n\n _marker: std::marker::PhantomData,\n\n }\n\n }\n\n\n\n pub async fn next_page(&mut self) -> Result<Option<Vec<T>>> {\n\n let mut req = if let Some(next) = self.next.take() {\n\n next\n\n } else {\n", "file_path": "src/async/page.rs", "rank": 62, "score": 35167.206264831475 }, { "content": "use super::{client, deserialize, Authenticate};\n\nuse crate::{\n\n entities::{account::Account, card::Card, context::Context, status::Status},\n\n errors::{Error, Result},\n\n};\n\nuse http_types::{Method, Request, Response};\n\nuse hyper_old_types::header::{parsing, Link, RelationType};\n\nuse smol::{prelude::*, Async};\n\nuse std::{\n\n fmt::Debug,\n\n net::{TcpStream, ToSocketAddrs},\n\n};\n\nuse url::Url;\n\n\n\n// link header name\n\nconst LINK: &str = \"link\";\n\n\n\n#[derive(Debug)]\n\npub struct Page<'client, T, A: Authenticate + Debug + 'client> {\n\n next: Option<Request>,\n", "file_path": "src/async/page.rs", "rank": 63, "score": 35163.57072403404 }, { "content": " return Ok(None);\n\n };\n\n Ok(self.send(req).await?)\n\n }\n\n\n\n pub async fn prev_page(&mut self) -> Result<Option<Vec<T>>> {\n\n let req = if let Some(prev) = self.prev.take() {\n\n prev\n\n } else {\n\n return Ok(None);\n\n };\n\n Ok(self.send(req).await?)\n\n }\n\n\n\n async fn send(&mut self, mut req: Request) -> Result<Option<Vec<T>>> {\n\n self.auth.authenticate(&mut req).await?;\n\n log::trace!(\"Request: {:?}\", req);\n\n let response = client::fetch(req).await?;\n\n log::trace!(\"Response: {:?}\", response);\n\n self.fill_links_from_resp(&response)?;\n", "file_path": "src/async/page.rs", "rank": 64, "score": 35161.0548117176 }, { "content": " /// # client_secret: \"\".into(),\n\n /// # redirect: \"\".into(),\n\n /// # token: \"\".into(),\n\n /// # };\n\n /// # let client = Mastodon::from(data);\n\n /// let follows_me = client.followed_by_me()?;\n\n /// # Ok(())\n\n /// # }\n\n fn followed_by_me(&self) -> Result<Page<Account>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n\n\n /// Returns events that are relevant to the authorized user, i.e. home\n\n /// timeline and notifications\n\n fn streaming_user(&self) -> Result<Self::Stream> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n\n\n /// Returns all public statuses\n\n fn streaming_public(&self) -> Result<Self::Stream> {\n", "file_path": "src/mastodon_client.rs", "rank": 65, "score": 35051.686924578025 }, { "content": " unimplemented!(\"This method was not implemented\");\n\n }\n\n\n\n /// Returns all direct messages\n\n fn streaming_direct(&self) -> Result<Self::Stream> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n}\n\n\n\n/// Trait that represents clients that can make unauthenticated calls to a\n\n/// mastodon instance\n", "file_path": "src/mastodon_client.rs", "rank": 66, "score": 35048.44598483279 }, { "content": " unimplemented!(\"This method was not implemented\");\n\n }\n\n\n\n /// Returns all local statuses\n\n fn streaming_local(&self) -> Result<Self::Stream> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n\n\n /// Returns all public statuses for a particular hashtag\n\n fn streaming_public_hashtag(&self, hashtag: &str) -> Result<Self::Stream> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n\n\n /// Returns all local statuses for a particular hashtag\n\n fn streaming_local_hashtag(&self, hashtag: &str) -> Result<Self::Stream> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n\n\n /// Returns statuses for a list\n\n fn streaming_list(&self, list_id: &str) -> Result<Self::Stream> {\n", "file_path": "src/mastodon_client.rs", "rank": 67, "score": 35048.0082868656 }, { "content": " /// # token: \"\".into(),\n\n /// # };\n\n /// # let client = Mastodon::from(data);\n\n /// let follows_me = client.follows_me()?;\n\n /// # Ok(())\n\n /// # }\n\n fn follows_me(&self) -> Result<Page<Account>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// Shortcut for\n\n /// `let me = client.verify_credentials(); client.following(&me.id)`\n\n ///\n\n /// ```no_run\n\n /// # extern crate elefren;\n\n /// # use std::error::Error;\n\n /// # use elefren::prelude::*;\n\n /// # fn main() -> Result<(), Box<dyn Error>> {\n\n /// # let data = Data {\n\n /// # base: \"\".into(),\n\n /// # client_id: \"\".into(),\n", "file_path": "src/mastodon_client.rs", "rank": 68, "score": 35045.8884529557 }, { "content": "use std::borrow::Cow;\n\n\n\nuse crate::{\n\n entities::prelude::*,\n\n errors::Result,\n\n media_builder::MediaBuilder,\n\n page::Page,\n\n requests::{\n\n AddFilterRequest,\n\n AddPushRequest,\n\n StatusesRequest,\n\n UpdateCredsRequest,\n\n UpdatePushRequest,\n\n },\n\n status_builder::NewStatus,\n\n};\n\n\n\n/// Represents the set of methods that a Mastodon Client can do, so that\n\n/// implementations might be swapped out for testing\n\n#[allow(unused)]\n\n#[async_trait::async_trait]\n", "file_path": "src/mastodon_client.rs", "rank": 69, "score": 35045.01839318056 }, { "content": " /// GET /api/v1/timelines/home\n\n fn get_home_timeline(&self) -> Result<Page<Status>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/custom_emojis\n\n fn get_emojis(&self) -> Result<Page<Emoji>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/mutes\n\n fn mutes(&self) -> Result<Page<Account>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/notifications\n\n fn notifications(&self) -> Result<Page<Notification>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/reports\n\n fn reports(&self) -> Result<Page<Report>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n", "file_path": "src/mastodon_client.rs", "rank": 70, "score": 35044.16347961026 }, { "content": " /// PUT /api/v1/filters/:id\n\n fn update_filter(&self, id: &str, request: &mut AddFilterRequest) -> Result<Filter> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// DELETE /api/v1/filters/:id\n\n fn delete_filter(&self, id: &str) -> Result<Empty> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/suggestions\n\n fn get_follow_suggestions(&self) -> Result<Vec<Account>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// DELETE /api/v1/suggestions/:account_id\n\n fn delete_from_suggestions(&self, id: &str) -> Result<Empty> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/endorsements\n\n fn get_endorsements(&self) -> Result<Page<Account>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n", "file_path": "src/mastodon_client.rs", "rank": 71, "score": 35043.425503331455 }, { "content": " /// GET /api/v1/accounts/:id/followers\n\n fn followers(&self, id: &str) -> Result<Page<Account>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/accounts/:id/following\n\n fn following(&self, id: &str) -> Result<Page<Account>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/statuses/:id/reblogged_by\n\n fn reblogged_by(&self, id: &str) -> Result<Page<Account>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/statuses/:id/favourited_by\n\n fn favourited_by(&self, id: &str) -> Result<Page<Account>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// DELETE /api/v1/domain_blocks\n\n fn unblock_domain(&self, domain: String) -> Result<Empty> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n", "file_path": "src/mastodon_client.rs", "rank": 72, "score": 35043.31420291251 }, { "content": " /// GET /api/v1/timelines/public?local=true\n\n fn get_local_timeline(&self) -> Result<Page<Status>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/timelines/public?local=false\n\n fn get_federated_timeline(&self) -> Result<Page<Status>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/timelines/tag/:hashtag\n\n fn get_hashtag_timeline(&self, hashtag: &str, local: bool) -> Result<Page<Status>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/accounts/:id/statuses\n\n fn statuses<'a, 'b: 'a, S>(&'b self, id: &'b str, request: S) -> Result<Page<Status>>\n\n where\n\n S: Into<Option<StatusesRequest<'a>>>,\n\n {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/accounts/relationships\n", "file_path": "src/mastodon_client.rs", "rank": 73, "score": 35042.692881181785 }, { "content": " fn relationships(&self, ids: &[&str]) -> Result<Page<Relationship>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/accounts/search?q=:query&limit=:limit&following=:following\n\n fn search_accounts(\n\n &self,\n\n query: &str,\n\n limit: Option<u64>,\n\n following: bool,\n\n ) -> Result<Page<Account>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// POST /api/v1/push/subscription\n\n fn add_push_subscription(&self, request: &AddPushRequest) -> Result<Subscription> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// PUT /api/v1/push/subscription\n\n fn update_push_data(&self, request: &UpdatePushRequest) -> Result<Subscription> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n", "file_path": "src/mastodon_client.rs", "rank": 74, "score": 35042.078167256244 }, { "content": " /// GET /api/v1/push/subscription\n\n fn get_push_subscription(&self) -> Result<Subscription> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// DELETE /api/v1/push/subscription\n\n fn delete_push_subscription(&self) -> Result<Empty> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/filters\n\n fn get_filters(&self) -> Result<Vec<Filter>> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// POST /api/v1/filters\n\n fn add_filter(&self, request: &mut AddFilterRequest) -> Result<Filter> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/filters/:id\n\n fn get_filter(&self, id: &str) -> Result<Filter> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n", "file_path": "src/mastodon_client.rs", "rank": 75, "score": 35041.53541561557 }, { "content": " /// POST /api/v1/accounts/:id/pin\n\n fn endorse_user(&self, id: &str) -> Result<Relationship> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// POST /api/v1/accounts/:id/unpin\n\n fn unendorse_user(&self, id: &str) -> Result<Relationship> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// Shortcut for: `let me = client.verify_credentials(); client.followers()`\n\n ///\n\n /// ```no_run\n\n /// # extern crate elefren;\n\n /// # use std::error::Error;\n\n /// # use elefren::prelude::*;\n\n /// # fn main() -> Result<(), Box<dyn Error>> {\n\n /// # let data = Data {\n\n /// # base: \"\".into(),\n\n /// # client_id: \"\".into(),\n\n /// # client_secret: \"\".into(),\n\n /// # redirect: \"\".into(),\n", "file_path": "src/mastodon_client.rs", "rank": 76, "score": 35040.988004039544 }, { "content": " /// POST /api/v1/accounts/follow_requests/reject\n\n fn reject_follow_request(&self, id: &str) -> Result<Empty> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/search\n\n fn search(&self, q: &str, resolve: bool) -> Result<SearchResult> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v2/search\n\n fn search_v2(&self, q: &str, resolve: bool) -> Result<SearchResultV2> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// POST /api/v1/follows\n\n fn follows(&self, uri: Cow<'static, str>) -> Result<Account> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// POST /api/v1/media\n\n fn media(&self, media_builder: MediaBuilder) -> Result<Attachment> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n", "file_path": "src/mastodon_client.rs", "rank": 77, "score": 35039.56674573253 }, { "content": " /// POST /api/v1/notifications/clear\n\n fn clear_notifications(&self) -> Result<Empty> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// POST /api/v1/notifications/dismiss\n\n fn dismiss_notification(&self, id: &str) -> Result<Empty> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/accounts/:id\n\n fn get_account(&self, id: &str) -> Result<Account> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// POST /api/v1/accounts/:id/follow\n\n fn follow(&self, id: &str) -> Result<Relationship> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// POST /api/v1/accounts/:id/unfollow\n\n fn unfollow(&self, id: &str) -> Result<Relationship> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n", "file_path": "src/mastodon_client.rs", "rank": 78, "score": 35039.403767384036 }, { "content": " /// GET /api/v1/accounts/:id/block\n\n fn block(&self, id: &str) -> Result<Relationship> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/accounts/:id/unblock\n\n fn unblock(&self, id: &str) -> Result<Relationship> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/accounts/:id/mute\n\n fn mute(&self, id: &str) -> Result<Relationship> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/accounts/:id/unmute\n\n fn unmute(&self, id: &str) -> Result<Relationship> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/notifications/:id\n\n fn get_notification(&self, id: &str) -> Result<Notification> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n", "file_path": "src/mastodon_client.rs", "rank": 79, "score": 35039.350291763316 }, { "content": " /// GET /api/v1/statuses/:id\n\n fn get_status(&self, id: &str) -> Result<Status> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/statuses/:id/context\n\n fn get_context(&self, id: &str) -> Result<Context> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/statuses/:id/card\n\n fn get_card(&self, id: &str) -> Result<Card> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// POST /api/v1/statuses/:id/reblog\n\n fn reblog(&self, id: &str) -> Result<Status> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// POST /api/v1/statuses/:id/unreblog\n\n fn unreblog(&self, id: &str) -> Result<Status> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n", "file_path": "src/mastodon_client.rs", "rank": 80, "score": 35039.297475895306 }, { "content": " /// POST /api/v1/statuses/:id/favourite\n\n fn favourite(&self, id: &str) -> Result<Status> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// POST /api/v1/statuses/:id/unfavourite\n\n fn unfavourite(&self, id: &str) -> Result<Status> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// DELETE /api/v1/statuses/:id\n\n fn delete_status(&self, id: &str) -> Result<Empty> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// PATCH /api/v1/accounts/update_credentials\n\n fn update_credentials(&self, builder: UpdateCredsRequest) -> Result<Account> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// POST /api/v1/statuses\n\n fn new_status(&self, status: NewStatus) -> Result<Status> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n", "file_path": "src/mastodon_client.rs", "rank": 81, "score": 35039.27131156483 }, { "content": " /// GET /api/v1/instance\n\n fn instance(&self) -> Result<Instance> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// GET /api/v1/accounts/verify_credentials\n\n fn verify_credentials(&self) -> Result<Account> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// POST /api/v1/reports\n\n fn report(&self, account_id: &str, status_ids: Vec<&str>, comment: String) -> Result<Report> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// POST /api/v1/domain_blocks\n\n fn block_domain(&self, domain: String) -> Result<Empty> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n\n /// POST /api/v1/accounts/follow_requests/authorize\n\n fn authorize_follow_request(&self, id: &str) -> Result<Empty> {\n\n unimplemented!(\"This method was not implemented\");\n\n }\n", "file_path": "src/mastodon_client.rs", "rank": 82, "score": 35039.27131156483 }, { "content": "//! A module containing info relating to a search result.\n\nuse serde::Deserialize;\n\n\n\nuse super::{\n\n prelude::{Account, Status},\n\n status::Tag,\n\n};\n\n\n\n/// A struct containing results of a search.\n\n#[derive(Debug, Clone, Deserialize, PartialEq)]\n\npub struct SearchResult {\n\n /// An array of matched Accounts.\n\n pub accounts: Vec<Account>,\n\n /// An array of matched Statuses.\n\n pub statuses: Vec<Status>,\n\n /// An array of matched hashtags, as strings.\n\n pub hashtags: Vec<String>,\n\n}\n\n\n\n/// A struct containing results of a search, with `Tag` objects in the\n", "file_path": "src/entities/search_result.rs", "rank": 83, "score": 33255.18129981546 }, { "content": "/// `hashtags` field\n\n#[derive(Debug, Clone, Deserialize, PartialEq)]\n\npub struct SearchResultV2 {\n\n /// An array of matched Accounts.\n\n pub accounts: Vec<Account>,\n\n /// An array of matched Statuses.\n\n pub statuses: Vec<Status>,\n\n /// An array of matched hashtags, as `Tag` objects.\n\n pub hashtags: Vec<Tag>,\n\n}\n", "file_path": "src/entities/search_result.rs", "rank": 84, "score": 33251.2308861351 }, { "content": " } else {\n\n None\n\n }\n\n }\n\n}\n\n\n\nimpl<'a, T: Clone + for<'de> Deserialize<'de>> Iterator for ItemsIter<'a, T> {\n\n type Item = T;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n if self.use_initial {\n\n if self.page.initial_items.is_empty() || self.cur_idx == self.page.initial_items.len() {\n\n return None;\n\n }\n\n let idx = self.cur_idx;\n\n if self.cur_idx == self.page.initial_items.len() - 1 {\n\n self.cur_idx = 0;\n\n self.use_initial = false;\n\n } else {\n\n self.cur_idx += 1;\n", "file_path": "src/entities/itemsiter.rs", "rank": 85, "score": 26.693939696555145 }, { "content": "//! Async Mastodon Client\n\n//!\n\n//! # Example\n\n//!\n\n//! ```rust,no_run\n\n//! use elefren::r#async::Client;\n\n//! use url::Url;\n\n//!\n\n//! # fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n//! # smol::block_on(async {\n\n//! let client = Client::new(\"https://mastodon.social\")?;\n\n//!\n\n//! // iterate page-by-page\n\n//! // this API isn't ideal, but one day we'll get better\n\n//! // syntax support for iterating over streams and we can\n\n//! // do better\n\n//! let mut pages = client.public_timeline(None).await?;\n\n//! while let Some(statuses) = pages.next_page().await? {\n\n//! for status in statuses {\n\n//! println!(\"{:?}\", status);\n", "file_path": "src/async/mod.rs", "rank": 86, "score": 23.29254748288923 }, { "content": "};\n\nuse http_types::{Method, Request, Response};\n\nuse std::fmt::Debug;\n\nuse url::Url;\n\n\n\npub use auth::Authenticate;\n\nuse auth::{OAuth, Unauthenticated};\n\npub use page::Page;\n\n\n\nmod auth;\n\nmod client;\n\nmod page;\n\n\n\n/// Async unauthenticated client\n\n#[derive(Debug)]\n\npub struct Client<A: Debug + Authenticate> {\n\n base_url: Url,\n\n auth: A,\n\n}\n\nimpl Client<Unauthenticated> {\n", "file_path": "src/async/mod.rs", "rank": 87, "score": 22.228739266879707 }, { "content": "/// // do something with `status`\n\n/// }\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n\n#[derive(Debug, Clone)]\n\npub(crate) struct ItemsIter<'a, T: Clone + for<'de> Deserialize<'de>> {\n\n page: Page<'a, T>,\n\n buffer: Vec<T>,\n\n cur_idx: usize,\n\n use_initial: bool,\n\n}\n\n\n\nimpl<'a, T: Clone + for<'de> Deserialize<'de>> ItemsIter<'a, T> {\n\n pub(crate) fn new(page: Page<'a, T>) -> ItemsIter<'a, T> {\n\n ItemsIter {\n\n page,\n\n buffer: vec![],\n\n cur_idx: 0,\n\n use_initial: true,\n", "file_path": "src/entities/itemsiter.rs", "rank": 88, "score": 20.887744593858642 }, { "content": " focus: None,\n\n }\n\n }\n\n\n\n /// Set an alt text description for the attachment.\n\n pub fn description(mut self, description: Cow<'static, str>) -> Self {\n\n self.description = Some(description);\n\n self\n\n }\n\n\n\n /// Set a focus point for an image attachment.\n\n pub fn focus(mut self, f1: f32, f2: f32) -> Self {\n\n self.focus = Some((f1, f2));\n\n self\n\n }\n\n}\n\n\n\n// Convenience helper so that the mastodon.media() method can be called with a\n\n// file name only (owned string).\n\nimpl From<String> for MediaBuilder {\n", "file_path": "src/media_builder.rs", "rank": 89, "score": 20.78220303651276 }, { "content": "/// Your mastodon application client, handles all requests to and from Mastodon.\n\n#[derive(Clone, Debug)]\n\npub struct Mastodon {\n\n client: Client,\n\n /// Raw data about your mastodon instance.\n\n pub data: Data,\n\n}\n\n\n\nimpl Mastodon {\n\n methods![get, post, delete,];\n\n\n\n fn route(&self, url: &str) -> String {\n\n format!(\"{}{}\", self.base, url)\n\n }\n\n\n\n pub(crate) fn send_blocking(&self, req: RequestBuilder) -> Result<Response> {\n\n let request = req.bearer_auth(&self.token).build()?;\n\n let handle = tokio::runtime::Handle::current();\n\n Ok(handle.block_on(self.client.execute(request))?)\n\n }\n", "file_path": "src/lib.rs", "rank": 90, "score": 20.769564719373893 }, { "content": "use crate::page::Page;\n\nuse serde::Deserialize;\n\n\n\n/// Abstracts away the `next_page` logic into a single stream of items\n\n///\n\n/// ```no_run\n\n/// # extern crate elefren;\n\n/// # use elefren::prelude::*;\n\n/// # use std::error::Error;\n\n/// # fn main() -> Result<(), Box<dyn Error>> {\n\n/// # let data = Data {\n\n/// # base: \"\".into(),\n\n/// # client_id: \"\".into(),\n\n/// # client_secret: \"\".into(),\n\n/// # redirect: \"\".into(),\n\n/// # token: \"\".into(),\n\n/// # };\n\n/// let client = Mastodon::from(data);\n\n/// let statuses = client.statuses(\"user-id\", None)?;\n\n/// for status in statuses.items_iter() {\n", "file_path": "src/entities/itemsiter.rs", "rank": 91, "score": 20.3495895216939 }, { "content": " id: &str,\n\n request: I,\n\n ) -> Result<Page<'client, Status, A>> {\n\n let mut url = self\n\n .base_url\n\n .join(&format!(\"api/v1/accounts/{}/statuses\", id))?;\n\n if let Some(request) = request.into() {\n\n let qs = request.to_querystring()?;\n\n url.set_query(Some(&qs[..]));\n\n }\n\n Ok(Page::new(Request::new(Method::Get, url), &self.auth))\n\n }\n\n\n\n /// GET /api/v1/polls/:id\n\n pub async fn poll(&self, id: &str) -> Result<Poll> {\n\n let url = self.base_url.join(&format!(\"api/v1/polls/{}\", id))?;\n\n let response = self.send(Request::new(Method::Get, url)).await?;\n\n Ok(deserialize(response).await?)\n\n }\n\n\n", "file_path": "src/async/mod.rs", "rank": 92, "score": 20.33653144131029 }, { "content": "/// Error returned from the Mastodon API.\n\n#[derive(Clone, Debug, Deserialize)]\n\npub struct ApiError {\n\n /// The type of error.\n\n pub error: Option<String>,\n\n /// The description of the error.\n\n pub error_description: Option<String>,\n\n}\n\n\n\nimpl fmt::Display for ApiError {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{:?}\", self)\n\n }\n\n}\n\n\n\nimpl error::Error for ApiError {}\n\n\n\nmacro_rules! from {\n\n ($($(#[$met:meta])* $typ:ident, $variant:ident,)*) => {\n\n $(\n", "file_path": "src/errors.rs", "rank": 93, "score": 20.124606847880393 }, { "content": "\n\n /// Permission scope of the application.\n\n ///\n\n /// IF none is specified, the default is Scopes::read_all()\n\n pub fn scopes(&mut self, scopes: Scopes) -> &mut Self {\n\n self.scopes = Some(scopes);\n\n self\n\n }\n\n\n\n /// URL to the homepage of your application.\n\n pub fn website<I: Into<Cow<'a, str>>>(&mut self, website: I) -> &mut Self {\n\n self.website = Some(website.into());\n\n self\n\n }\n\n\n\n /// Attempts to convert this build into an `App`\n\n ///\n\n /// Will fail if no `client_name` was provided\n\n pub fn build(self) -> Result<App> {\n\n Ok(App {\n", "file_path": "src/apps.rs", "rank": 94, "score": 19.833832639724836 }, { "content": "use serde::{Deserialize, Serialize};\n\n\n\n/// Custom emoji fields for AnnouncementReaction\n\n#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]\n\npub struct AnnouncementReactionCustomEmoji {\n\n /// A link to the custom emoji.\n\n pub url: String,\n\n /// A link to a non-animated version of the custom emoji.\n\n pub static_url: String,\n\n}\n\n\n\n/// Represents an emoji reaction to an Announcement.\n\n#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]\n\npub struct AnnouncementReaction {\n\n /// The emoji used for the reaction. Either a unicode emoji, or a custom emoji's shortcode.\n\n pub name: String,\n\n /// The total number of users who have added this reaction.\n\n pub count: u64,\n\n /// Whether the authorized user has added this reaction to the announcement.\n\n pub me: bool,\n", "file_path": "src/entities/announcement.rs", "rank": 95, "score": 19.758582625270073 }, { "content": "## Example\n\n\n\nIn your `Cargo.toml`, make sure you enable the `toml` feature:\n\n\n\n```toml\n\n[dependencies]\n\nelefren = { version = \"0.22\", features = [\"toml\"] }\n\n```\n\n\n\n```rust,no_run\n\n// src/main.rs\n\nextern crate elefren;\n\n\n\nuse std::error::Error;\n\n\n\nuse elefren::prelude::*;\n\nuse elefren::helpers::toml; // requires `features = [\"toml\"]`\n\nuse elefren::helpers::cli;\n\n\n\nfn main() -> Result<(), Box<dyn Error>> {\n\n let mastodon = if let Ok(data) = toml::from_file(\"mastodon-data.toml\") {\n\n Mastodon::from(data)\n\n } else {\n\n register()?\n\n };\n\n\n\n let you = mastodon.verify_credentials()?;\n\n\n\n println!(\"{:#?}\", you);\n\n\n\n Ok(())\n\n}\n\n\n\nfn register() -> Result<Mastodon, Box<dyn Error>> {\n\n let registration = Registration::new(\"https://mastodon.social\")\n\n .client_name(\"elefren-examples\")\n\n .build()?;\n\n let mastodon = cli::authenticate(registration)?;\n\n\n\n // Save app data for using on the next run.\n\n toml::to_file(&*mastodon, \"mastodon-data.toml\")?;\n\n\n\n Ok(mastodon)\n\n}\n\n```\n\n\n\nIt also supports the [Streaming API](https://docs.joinmastodon.org/api/streaming):\n\n\n\n```no_run\n\nuse elefren::prelude::*;\n\nuse elefren::entities::event::Event;\n\n\n\nuse std::error::Error;\n\n\n\nfn main() -> Result<(), Box<dyn Error>> {\n\n let data = Data {\n\n base: \"\".into(),\n\n client_id: \"\".into(),\n\n client_secret: \"\".into(),\n\n redirect: \"\".into(),\n\n token: \"\".into(),\n\n };\n\n\n\n let client = Mastodon::from(data);\n\n\n\n for event in client.streaming_user()? {\n\n match event {\n\n Event::Update(ref status) => { /* .. */ },\n\n Event::Notification(ref notification) => { /* .. */ },\n\n Event::Delete(ref id) => { /* .. */ },\n\n Event::FiltersChanged => { /* .. */ },\n\n }\n\n }\n\n Ok(())\n\n}\n\n```\n", "file_path": "README.md", "rank": 96, "score": 19.69816184235286 }, { "content": "//! Module containing everything related to an instance.\n\nuse super::account::Account;\n\nuse serde::Deserialize;\n\n\n\n/// A struct containing info of an instance.\n\n#[derive(Debug, Clone, Deserialize, PartialEq)]\n\npub struct Instance {\n\n /// URI of the current instance\n\n pub uri: String,\n\n /// The instance's title.\n\n pub title: String,\n\n /// A description for the instance.\n\n pub description: String,\n\n /// An email address which can be used to contact the\n\n /// instance administrator.\n\n pub email: String,\n\n /// The Mastodon version used by instance.\n\n pub version: String,\n\n /// Urls to the streaming api.\n\n pub urls: Option<StreamingApi>,\n", "file_path": "src/entities/instance.rs", "rank": 97, "score": 19.406906583341588 }, { "content": " pub fn new<S: AsRef<str>>(base_url: S) -> Result<Client<Unauthenticated>> {\n\n let base_url = Url::parse(base_url.as_ref())?;\n\n Ok(Client {\n\n base_url,\n\n auth: Unauthenticated,\n\n })\n\n }\n\n}\n\nimpl<A: Debug + Authenticate> Client<A> {\n\n async fn send(&self, mut req: Request) -> Result<Response> {\n\n self.auth.authenticate(&mut req).await?;\n\n Ok(client::fetch(req).await?)\n\n }\n\n\n\n /// GET /api/v1/timelines/public\n\n pub async fn public_timeline<'a, 'client: 'a, I: Into<Option<StatusesRequest<'a>>>>(\n\n &'client self,\n\n opts: I,\n\n ) -> Result<Page<'client, Status, A>> {\n\n let mut url = self.base_url.join(\"api/v1/timelines/public\")?;\n", "file_path": "src/async/mod.rs", "rank": 98, "score": 19.168018942537074 }, { "content": " /// builder.field_attribute(\"some key\", \"some value\");\n\n /// ```\n\n pub fn field_attribute(mut self, name: &str, value: &str) -> Self {\n\n self.field_attributes.push(MetadataField::new(name, value));\n\n self\n\n }\n\n\n\n pub(crate) fn build(self) -> Result<Credentials> {\n\n Ok(Credentials {\n\n display_name: self.display_name.clone(),\n\n note: self.note.clone(),\n\n avatar: self.avatar.clone(),\n\n header: self.avatar.clone(),\n\n source: Some(UpdateSource {\n\n privacy: self.privacy,\n\n sensitive: self.sensitive,\n\n }),\n\n fields_attributes: self.field_attributes,\n\n })\n\n }\n", "file_path": "src/requests/update_credentials.rs", "rank": 99, "score": 18.86161544772751 } ]
Rust
src/writers/syslog_writer.rs
ijackson/flexi_logger
674d0b8c9f8f8291b4a2a14f53fd84b40e71e788
use crate::deferred_now::DeferredNow; use crate::writers::log_writer::LogWriter; use std::cell::RefCell; use std::ffi::OsString; use std::io::Error as IoError; use std::io::Result as IoResult; use std::io::{BufWriter, ErrorKind, Write}; use std::net::{TcpStream, ToSocketAddrs, UdpSocket}; #[cfg(target_os = "linux")] use std::path::Path; use std::sync::Mutex; #[derive(Copy, Clone, Debug)] pub enum SyslogFacility { Kernel = 0 << 3, UserLevel = 1 << 3, MailSystem = 2 << 3, SystemDaemons = 3 << 3, Authorization = 4 << 3, SyslogD = 5 << 3, LinePrinter = 6 << 3, News = 7 << 3, Uucp = 8 << 3, Clock = 9 << 3, Authorization2 = 10 << 3, Ftp = 11 << 3, Ntp = 12 << 3, LogAudit = 13 << 3, LogAlert = 14 << 3, Clock2 = 15 << 3, LocalUse0 = 16 << 3, LocalUse1 = 17 << 3, LocalUse2 = 18 << 3, LocalUse3 = 19 << 3, LocalUse4 = 20 << 3, LocalUse5 = 21 << 3, LocalUse6 = 22 << 3, LocalUse7 = 23 << 3, } #[derive(Debug)] pub enum SyslogSeverity { Emergency = 0, Alert = 1, Critical = 2, Error = 3, Warning = 4, Notice = 5, Info = 6, Debug = 7, } pub type LevelToSyslogSeverity = fn(level: log::Level) -> SyslogSeverity; fn default_mapping(level: log::Level) -> SyslogSeverity { match level { log::Level::Error => SyslogSeverity::Error, log::Level::Warn => SyslogSeverity::Warning, log::Level::Info => SyslogSeverity::Info, log::Level::Debug | log::Level::Trace => SyslogSeverity::Debug, } } pub struct SyslogWriter { hostname: OsString, process: String, pid: u32, facility: SyslogFacility, message_id: String, determine_severity: LevelToSyslogSeverity, syslog: Mutex<RefCell<SyslogConnector>>, max_log_level: log::LevelFilter, } impl SyslogWriter { pub fn try_new( facility: SyslogFacility, determine_severity: Option<LevelToSyslogSeverity>, max_log_level: log::LevelFilter, message_id: String, syslog: SyslogConnector, ) -> IoResult<Box<Self>> { Ok(Box::new(Self { hostname: hostname::get().unwrap_or_else(|_| OsString::from("<unknown_hostname>")), process: std::env::args() .next() .ok_or_else(|| IoError::new(ErrorKind::Other, "<no progname>".to_owned()))?, pid: std::process::id(), facility, max_log_level, message_id, determine_severity: determine_severity.unwrap_or_else(|| default_mapping), syslog: Mutex::new(RefCell::new(syslog)), })) } } impl LogWriter for SyslogWriter { fn write(&self, now: &mut DeferredNow, record: &log::Record) -> IoResult<()> { let mr_syslog = self.syslog.lock().unwrap(); let mut syslog = mr_syslog.borrow_mut(); let severity = (self.determine_severity)(record.level()); write!( syslog, "{}", format!( "<{}>1 {} {:?} {} {} {} - {}\n", self.facility as u8 | severity as u8, now.now() .to_rfc3339_opts(chrono::SecondsFormat::Micros, false), self.hostname, self.process, self.pid, self.message_id, &record.args() ) ) } fn flush(&self) -> IoResult<()> { let mr_syslog = self.syslog.lock().unwrap(); let mut syslog = mr_syslog.borrow_mut(); syslog.flush()?; Ok(()) } fn max_log_level(&self) -> log::LevelFilter { self.max_log_level } } #[derive(Debug)] pub enum SyslogConnector { #[cfg(target_os = "linux")] Stream(BufWriter<std::os::unix::net::UnixStream>), #[cfg(target_os = "linux")] Datagram(std::os::unix::net::UnixDatagram), Udp(UdpSocket), Tcp(BufWriter<TcpStream>), } impl SyslogConnector { #[cfg(target_os = "linux")] pub fn try_datagram<P: AsRef<Path>>(path: P) -> IoResult<SyslogConnector> { let ud = std::os::unix::net::UnixDatagram::unbound()?; ud.connect(&path)?; Ok(SyslogConnector::Datagram(ud)) } #[cfg(target_os = "linux")] pub fn try_stream<P: AsRef<Path>>(path: P) -> IoResult<SyslogConnector> { Ok(SyslogConnector::Stream(BufWriter::new( std::os::unix::net::UnixStream::connect(path)?, ))) } pub fn try_tcp<T: ToSocketAddrs>(server: T) -> IoResult<Self> { Ok(Self::Tcp(BufWriter::new(TcpStream::connect(server)?))) } pub fn try_udp<T: ToSocketAddrs>(local: T, server: T) -> IoResult<Self> { let socket = UdpSocket::bind(local)?; socket.connect(server)?; Ok(Self::Udp(socket)) } } impl Write for SyslogConnector { fn write(&mut self, message: &[u8]) -> IoResult<usize> { match *self { #[cfg(target_os = "linux")] Self::Datagram(ref ud) => { ud.send(&message[..]) } #[cfg(target_os = "linux")] Self::Stream(ref mut w) => { w.write(&message[..]) .and_then(|sz| w.write_all(&[0; 1]).map(|_| sz)) } Self::Tcp(ref mut w) => { w.write(&message[..]) } Self::Udp(ref socket) => { socket.send(&message[..]) } } } fn flush(&mut self) -> IoResult<()> { match *self { #[cfg(target_os = "linux")] Self::Datagram(_) => Ok(()), #[cfg(target_os = "linux")] Self::Stream(ref mut w) => w.flush(), Self::Udp(_) => Ok(()), Self::Tcp(ref mut w) => w.flush(), } } }
use crate::deferred_now::DeferredNow; use crate::writers::log_writer::LogWriter; use std::cell::RefCell; use std::ffi::OsString; use std::io::Error as IoError; use std::io::Result as IoResult; use std::io::{BufWriter, ErrorKind, Write}; use std::net::{TcpStream, ToSocketAddrs, UdpSocket}; #[cfg(target_os = "linux")] use std::path::Path; use std::sync::Mutex; #[derive(Copy, Clone, Debug)] pub enum SyslogFacility { Kernel = 0 << 3, UserLevel = 1 << 3, MailSystem = 2 << 3, SystemDaemons = 3 << 3, Authorization = 4 << 3, SyslogD = 5 << 3, LinePrinter = 6 << 3, News = 7 << 3, Uucp = 8 << 3, Clock = 9 << 3, Authorization2 = 10 << 3, Ftp = 11 << 3, Ntp = 12 << 3, LogAudit = 13 << 3, LogAlert = 14 << 3, Clock2 = 15 << 3, LocalUse0 = 16 << 3, LocalUse1 = 17 << 3, LocalUse2 = 18 << 3, LocalUse3 = 19 << 3, LocalUse4 = 20 << 3, LocalUse5 = 21 << 3, LocalUse6 = 22 << 3, LocalUse7 = 23 << 3, } #[derive(Debug)] pub enum SyslogSeverity { Emergency = 0, Alert = 1, Critical = 2, Error = 3, Warning = 4, Notice = 5, Info = 6, Debug = 7, } pub type LevelToSyslogSeverity = fn(level: log::Level) -> SyslogSeverity; fn default_mapping(level: log::Level) -> SyslogSeverity { match level { log::Level::Error => SyslogSeverity::Error, log::Level::Warn => SyslogSeverity::Warning, log::Level::Info => SyslogSeverity::Info, log::Level::Debug | log::Level::Trace => SyslogSeverity::Debug, } } pub struct SyslogWriter { hostname: OsString, process: String, pid: u32, facility: SyslogFacility, message_id: String, determine_severity: LevelToSyslogSeverity, syslog: Mutex<RefCell<SyslogConnec
et) => { socket.send(&message[..]) } } } fn flush(&mut self) -> IoResult<()> { match *self { #[cfg(target_os = "linux")] Self::Datagram(_) => Ok(()), #[cfg(target_os = "linux")] Self::Stream(ref mut w) => w.flush(), Self::Udp(_) => Ok(()), Self::Tcp(ref mut w) => w.flush(), } } }
tor>>, max_log_level: log::LevelFilter, } impl SyslogWriter { pub fn try_new( facility: SyslogFacility, determine_severity: Option<LevelToSyslogSeverity>, max_log_level: log::LevelFilter, message_id: String, syslog: SyslogConnector, ) -> IoResult<Box<Self>> { Ok(Box::new(Self { hostname: hostname::get().unwrap_or_else(|_| OsString::from("<unknown_hostname>")), process: std::env::args() .next() .ok_or_else(|| IoError::new(ErrorKind::Other, "<no progname>".to_owned()))?, pid: std::process::id(), facility, max_log_level, message_id, determine_severity: determine_severity.unwrap_or_else(|| default_mapping), syslog: Mutex::new(RefCell::new(syslog)), })) } } impl LogWriter for SyslogWriter { fn write(&self, now: &mut DeferredNow, record: &log::Record) -> IoResult<()> { let mr_syslog = self.syslog.lock().unwrap(); let mut syslog = mr_syslog.borrow_mut(); let severity = (self.determine_severity)(record.level()); write!( syslog, "{}", format!( "<{}>1 {} {:?} {} {} {} - {}\n", self.facility as u8 | severity as u8, now.now() .to_rfc3339_opts(chrono::SecondsFormat::Micros, false), self.hostname, self.process, self.pid, self.message_id, &record.args() ) ) } fn flush(&self) -> IoResult<()> { let mr_syslog = self.syslog.lock().unwrap(); let mut syslog = mr_syslog.borrow_mut(); syslog.flush()?; Ok(()) } fn max_log_level(&self) -> log::LevelFilter { self.max_log_level } } #[derive(Debug)] pub enum SyslogConnector { #[cfg(target_os = "linux")] Stream(BufWriter<std::os::unix::net::UnixStream>), #[cfg(target_os = "linux")] Datagram(std::os::unix::net::UnixDatagram), Udp(UdpSocket), Tcp(BufWriter<TcpStream>), } impl SyslogConnector { #[cfg(target_os = "linux")] pub fn try_datagram<P: AsRef<Path>>(path: P) -> IoResult<SyslogConnector> { let ud = std::os::unix::net::UnixDatagram::unbound()?; ud.connect(&path)?; Ok(SyslogConnector::Datagram(ud)) } #[cfg(target_os = "linux")] pub fn try_stream<P: AsRef<Path>>(path: P) -> IoResult<SyslogConnector> { Ok(SyslogConnector::Stream(BufWriter::new( std::os::unix::net::UnixStream::connect(path)?, ))) } pub fn try_tcp<T: ToSocketAddrs>(server: T) -> IoResult<Self> { Ok(Self::Tcp(BufWriter::new(TcpStream::connect(server)?))) } pub fn try_udp<T: ToSocketAddrs>(local: T, server: T) -> IoResult<Self> { let socket = UdpSocket::bind(local)?; socket.connect(server)?; Ok(Self::Udp(socket)) } } impl Write for SyslogConnector { fn write(&mut self, message: &[u8]) -> IoResult<usize> { match *self { #[cfg(target_os = "linux")] Self::Datagram(ref ud) => { ud.send(&message[..]) } #[cfg(target_os = "linux")] Self::Stream(ref mut w) => { w.write(&message[..]) .and_then(|sz| w.write_all(&[0; 1]).map(|_| sz)) } Self::Tcp(ref mut w) => { w.write(&message[..]) } Self::Udp(ref sock
random
[ { "content": "fn number_infix(idx: u32) -> String {\n\n format!(\"_r{:0>5}\", idx)\n\n}\n\n\n", "file_path": "src/writers/file_log_writer.rs", "rank": 0, "score": 146125.11405953576 }, { "content": "#[cfg(feature = \"colors\")]\n\npub fn style<T>(level: log::Level, item: T) -> Paint<T> {\n\n match level {\n\n log::Level::Error => Paint::new(item).with_style(PALETTE.error),\n\n log::Level::Warn => Paint::new(item).with_style(PALETTE.warn),\n\n log::Level::Info => Paint::new(item).with_style(PALETTE.info),\n\n log::Level::Debug => Paint::new(item).with_style(PALETTE.debug),\n\n log::Level::Trace => Paint::new(item).with_style(PALETTE.trace),\n\n }\n\n}\n\n\n\n#[cfg(feature = \"colors\")]\n\nlazy_static::lazy_static! {\n\n static ref PALETTE: Palette = {\n\n match std::env::var(\"FLEXI_LOGGER_PALETTE\") {\n\n Ok(palette) => Palette::parse(&palette).unwrap_or_else(|_| Palette::default()),\n\n Err(..) => Palette::default(),\n\n }\n\n\n\n };\n\n}\n\n\n", "file_path": "src/formats.rs", "rank": 2, "score": 140382.72765938332 }, { "content": "pub fn alert_logger() -> Box<FileLogWriter> {\n\n Box::new(\n\n FileLogWriter::builder()\n\n .discriminant(\"Alert\")\n\n .suffix(\"alerts\")\n\n .print_message()\n\n .try_build()\n\n .unwrap(),\n\n )\n\n}\n", "file_path": "tests/test_multi_logger.rs", "rank": 3, "score": 119468.99267669336 }, { "content": "fn use_error() {\n\n for _ in 1..100 {\n\n error!(\"This is an error message\");\n\n }\n\n}\n", "file_path": "benches/bench_standard.rs", "rank": 4, "score": 118977.08950341464 }, { "content": "fn use_error() {\n\n for _ in 1..100 {\n\n error!(\"This is an error message\");\n\n }\n\n}\n", "file_path": "benches/bench_reconfigurable.rs", "rank": 5, "score": 118977.08950341464 }, { "content": "/// A logline-formatter that produces log lines like\n\n/// <br>\n\n/// ```[2016-01-13 15:25:01.640870 +01:00] T[taskreader] INFO [src/foo/bar:26] Task successfully read from conf.json```\n\n/// <br>\n\n/// i.e. with timestamp, thread name and file location.\n\n///\n\n/// # Errors\n\n///\n\n/// See `std::write`\n\npub fn with_thread(\n\n w: &mut dyn std::io::Write,\n\n now: &mut DeferredNow,\n\n record: &Record,\n\n) -> Result<(), std::io::Error> {\n\n write!(\n\n w,\n\n \"[{}] T[{:?}] {} [{}:{}] {}\",\n\n now.now().format(\"%Y-%m-%d %H:%M:%S%.6f %:z\"),\n\n thread::current().name().unwrap_or(\"<unnamed>\"),\n\n record.level(),\n\n record.file().unwrap_or(\"<unnamed>\"),\n\n record.line().unwrap_or(0),\n\n &record.args()\n\n )\n\n}\n\n\n\n/// A colored version of the logline-formatter `with_thread`.\n\n///\n\n/// See method [style](fn.style.html) if you want to influence coloring.\n\n///\n\n/// Only available with feature `colors`.\n\n///\n\n/// # Errors\n\n///\n\n/// See `std::write`\n", "file_path": "src/formats.rs", "rank": 6, "score": 113190.76078101507 }, { "content": "fn write_err(msg: &str, err: &std::io::Error) {\n\n eprintln!(\"[flexi_logger] {} with {}\", msg, err);\n\n}\n", "file_path": "src/primary_writer.rs", "rank": 7, "score": 113079.78404138098 }, { "content": "/// A logline-formatter that produces log lines like <br>\n\n/// ```INFO [my_prog::some_submodule] Task successfully read from conf.json```\n\n///\n\n/// # Errors\n\n///\n\n/// See `std::write`\n\npub fn default_format(\n\n w: &mut dyn std::io::Write,\n\n _now: &mut DeferredNow,\n\n record: &Record,\n\n) -> Result<(), std::io::Error> {\n\n write!(\n\n w,\n\n \"{} [{}] {}\",\n\n record.level(),\n\n record.module_path().unwrap_or(\"<unnamed>\"),\n\n record.args()\n\n )\n\n}\n\n\n\n#[allow(clippy::doc_markdown)]\n\n/// A colored version of the logline-formatter `default_format`\n\n/// that produces log lines like <br>\n\n/// <code><span style=\"color:red\">ERROR</span> &#91;my_prog::some_submodule&#93; <span\n\n/// style=\"color:red\">File not found</span></code>\n\n///\n\n/// See method [style](fn.style.html) if you want to influence coloring.\n\n///\n\n/// Only available with feature `colors`.\n\n///\n\n/// # Errors\n\n///\n\n/// See `std::write`\n", "file_path": "src/formats.rs", "rank": 8, "score": 110568.27297245138 }, { "content": "/// A logline-formatter that produces log lines with timestamp and file location, like\n\n/// <br>\n\n/// ```[2016-01-13 15:25:01.640870 +01:00] INFO [src/foo/bar:26] Task successfully read from conf.json```\n\n/// <br>\n\n///\n\n/// # Errors\n\n///\n\n/// See `std::write`\n\npub fn opt_format(\n\n w: &mut dyn std::io::Write,\n\n now: &mut DeferredNow,\n\n record: &Record,\n\n) -> Result<(), std::io::Error> {\n\n write!(\n\n w,\n\n \"[{}] {} [{}:{}] {}\",\n\n now.now().format(\"%Y-%m-%d %H:%M:%S%.6f %:z\"),\n\n record.level(),\n\n record.file().unwrap_or(\"<unnamed>\"),\n\n record.line().unwrap_or(0),\n\n &record.args()\n\n )\n\n}\n\n\n\n/// A colored version of the logline-formatter `opt_format`.\n\n///\n\n/// See method [style](fn.style.html) if you want to influence coloring.\n\n///\n\n/// Only available with feature `colors`.\n\n///\n\n/// # Errors\n\n///\n\n/// See `std::write`\n", "file_path": "src/formats.rs", "rank": 9, "score": 110567.77920250801 }, { "content": "/// A logline-formatter that produces log lines like\n\n/// <br>\n\n/// ```[2016-01-13 15:25:01.640870 +01:00] INFO [foo::bar] src/foo/bar.rs:26: Task successfully read from conf.json```\n\n/// <br>\n\n/// i.e. with timestamp, module path and file location.\n\n///\n\n/// # Errors\n\n///\n\n/// See `std::write`\n\npub fn detailed_format(\n\n w: &mut dyn std::io::Write,\n\n now: &mut DeferredNow,\n\n record: &Record,\n\n) -> Result<(), std::io::Error> {\n\n write!(\n\n w,\n\n \"[{}] {} [{}] {}:{}: {}\",\n\n now.now().format(\"%Y-%m-%d %H:%M:%S%.6f %:z\"),\n\n record.level(),\n\n record.module_path().unwrap_or(\"<unnamed>\"),\n\n record.file().unwrap_or(\"<unnamed>\"),\n\n record.line().unwrap_or(0),\n\n &record.args()\n\n )\n\n}\n\n\n\n/// A colored version of the logline-formatter `detailed_format`.\n\n///\n\n/// See method [style](fn.style.html) if you want to influence coloring.\n\n///\n\n/// Only available with feature `colors`.\n\n///\n\n/// # Errors\n\n///\n\n/// See `std::write`\n", "file_path": "src/formats.rs", "rank": 10, "score": 110567.32956702096 }, { "content": "#[cfg(feature = \"colors\")]\n\npub fn colored_with_thread(\n\n w: &mut dyn std::io::Write,\n\n now: &mut DeferredNow,\n\n record: &Record,\n\n) -> Result<(), std::io::Error> {\n\n let level = record.level();\n\n write!(\n\n w,\n\n \"[{}] T[{:?}] {} [{}:{}] {}\",\n\n style(level, now.now().format(\"%Y-%m-%d %H:%M:%S%.6f %:z\")),\n\n style(level, thread::current().name().unwrap_or(\"<unnamed>\")),\n\n style(level, level),\n\n record.file().unwrap_or(\"<unnamed>\"),\n\n record.line().unwrap_or(0),\n\n style(level, &record.args())\n\n )\n\n}\n\n\n\n/// Helper function that is used in the provided colored format functions.\n\n///\n", "file_path": "src/formats.rs", "rank": 11, "score": 110557.71828832262 }, { "content": "fn write_err(msg: &str, err: &std::io::Error) {\n\n eprintln!(\"[flexi_logger] {} with {}\", msg, err);\n\n}\n\n\n\nmod platform {\n\n use std::path::{Path, PathBuf};\n\n\n\n pub fn create_symlink_if_possible(link: &PathBuf, path: &Path) {\n\n linux_create_symlink(link, path);\n\n }\n\n\n\n #[cfg(target_os = \"linux\")]\n\n fn linux_create_symlink(link: &PathBuf, logfile: &Path) {\n\n if std::fs::symlink_metadata(link).is_ok() {\n\n // remove old symlink before creating a new one\n\n if let Err(e) = std::fs::remove_file(link) {\n\n eprintln!(\n\n \"[flexi_logger] deleting old symlink to log file failed with {:?}\",\n\n e\n\n );\n", "file_path": "src/writers/file_log_writer.rs", "rank": 12, "score": 108328.95784406592 }, { "content": "#[cfg(feature = \"colors\")]\n\npub fn colored_default_format(\n\n w: &mut dyn std::io::Write,\n\n _now: &mut DeferredNow,\n\n record: &Record,\n\n) -> Result<(), std::io::Error> {\n\n let level = record.level();\n\n write!(\n\n w,\n\n \"{} [{}] {}\",\n\n style(level, level),\n\n record.module_path().unwrap_or(\"<unnamed>\"),\n\n style(level, record.args())\n\n )\n\n}\n\n\n", "file_path": "src/formats.rs", "rank": 13, "score": 108127.46751828291 }, { "content": "#[cfg(feature = \"colors\")]\n\npub fn colored_detailed_format(\n\n w: &mut dyn std::io::Write,\n\n now: &mut DeferredNow,\n\n record: &Record,\n\n) -> Result<(), std::io::Error> {\n\n let level = record.level();\n\n write!(\n\n w,\n\n \"[{}] {} [{}] {}:{}: {}\",\n\n style(level, now.now().format(\"%Y-%m-%d %H:%M:%S%.6f %:z\")),\n\n style(level, record.level()),\n\n record.module_path().unwrap_or(\"<unnamed>\"),\n\n record.file().unwrap_or(\"<unnamed>\"),\n\n record.line().unwrap_or(0),\n\n style(level, &record.args())\n\n )\n\n}\n\n\n", "file_path": "src/formats.rs", "rank": 14, "score": 108127.46751828291 }, { "content": "#[cfg(feature = \"colors\")]\n\npub fn colored_opt_format(\n\n w: &mut dyn std::io::Write,\n\n now: &mut DeferredNow,\n\n record: &Record,\n\n) -> Result<(), std::io::Error> {\n\n let level = record.level();\n\n write!(\n\n w,\n\n \"[{}] {} [{}:{}] {}\",\n\n style(level, now.now().format(\"%Y-%m-%d %H:%M:%S%.6f %:z\")),\n\n style(level, level),\n\n record.file().unwrap_or(\"<unnamed>\"),\n\n record.line().unwrap_or(0),\n\n style(level, &record.args())\n\n )\n\n}\n\n\n", "file_path": "src/formats.rs", "rank": 15, "score": 108127.46751828291 }, { "content": "fn define_directory() -> String {\n\n format!(\n\n \"./log_files/age_or_size/{}\",\n\n Local::now().format(\"%Y-%m-%d_%H-%M-%S\")\n\n )\n\n}\n\n\n", "file_path": "tests/test_age_or_size.rs", "rank": 16, "score": 106337.371881984 }, { "content": "fn define_directory() -> String {\n\n format!(\n\n \"./log_files/mt_logs/{}\",\n\n Local::now().format(\"%Y-%m-%d_%H-%M-%S\")\n\n )\n\n}\n\n\n", "file_path": "tests/test_multi_threaded_dates.rs", "rank": 17, "score": 104231.27083231084 }, { "content": "fn define_directory() -> String {\n\n format!(\n\n \"./log_files/mt_logs/{}\",\n\n Local::now().format(\"%Y-%m-%d_%H-%M-%S\")\n\n )\n\n}\n\n\n", "file_path": "tests/test_multi_threaded_numbers.rs", "rank": 18, "score": 104231.27083231084 }, { "content": "pub fn test_format(\n\n w: &mut dyn std::io::Write,\n\n now: &mut DeferredNow,\n\n record: &Record,\n\n) -> std::io::Result<()> {\n\n write!(\n\n w,\n\n \"XXXXX [{}] T[{:?}] {} [{}:{}] {}\",\n\n now.now().format(\"%Y-%m-%d %H:%M:%S%.6f %:z\"),\n\n std::thread::current().name().unwrap_or(\"<unnamed>\"),\n\n record.level(),\n\n record.file().unwrap_or(\"<unnamed>\"),\n\n record.line().unwrap_or(0),\n\n &record.args()\n\n )\n\n}\n\n\n", "file_path": "tests/test_multi_threaded_dates.rs", "rank": 19, "score": 103766.81672522692 }, { "content": "pub fn test_format(\n\n w: &mut dyn std::io::Write,\n\n now: &mut DeferredNow,\n\n record: &Record,\n\n) -> std::io::Result<()> {\n\n write!(\n\n w,\n\n \"XXXXX [{}] T[{:?}] {} [{}:{}] {}\",\n\n now.now().format(\"%Y-%m-%d %H:%M:%S%.6f %:z\"),\n\n std::thread::current().name().unwrap_or(\"<unnamed>\"),\n\n record.level(),\n\n record.file().unwrap_or(\"<unnamed>\"),\n\n record.line().unwrap_or(0),\n\n &record.args()\n\n )\n\n}\n\n\n", "file_path": "tests/test_multi_threaded_numbers.rs", "rank": 20, "score": 103766.81672522692 }, { "content": "#[test]\n\nfn you_must_see_exactly_three_messages_above_1_err_1_warn_1_info() {\n\n flexi_logger::Logger::with_str(\"info\").start().unwrap();\n\n\n\n error!(\"This is an error message\");\n\n warn!(\"This is a warning\");\n\n info!(\"This is an info message\");\n\n debug!(\"This is a debug message - you must not see it!\");\n\n trace!(\"This is a trace message - you must not see it!\");\n\n}\n", "file_path": "tests/test_env_logger_style.rs", "rank": 21, "score": 95838.82455965181 }, { "content": "fn parse_level_filter<S: AsRef<str>>(s: S) -> Result<LevelFilter, FlexiLoggerError> {\n\n match s.as_ref().to_lowercase().as_ref() {\n\n \"off\" => Ok(LevelFilter::Off),\n\n \"error\" => Ok(LevelFilter::Error),\n\n \"warn\" => Ok(LevelFilter::Warn),\n\n \"info\" => Ok(LevelFilter::Info),\n\n \"debug\" => Ok(LevelFilter::Debug),\n\n \"trace\" => Ok(LevelFilter::Trace),\n\n _ => Err(FlexiLoggerError::LevelFilter(format!(\n\n \"unknown level filter: {}\",\n\n s.as_ref()\n\n ))),\n\n }\n\n}\n\n\n", "file_path": "src/log_specification.rs", "rank": 22, "score": 91687.69227190375 }, { "content": "#[test]\n\nfn parse_errors_logger() {\n\n let result = Logger::with_str(\"info, foo=baz\").check_parser_error();\n\n assert!(result.is_err());\n\n let error = result.err().unwrap();\n\n println!(\"err: {}\", error);\n\n\n\n Logger::with_str(\"info, foo=debug\")\n\n .check_parser_error()\n\n .unwrap()\n\n .start()\n\n .unwrap();\n\n info!(\"logging works\");\n\n info!(\"logging works\");\n\n}\n", "file_path": "tests/test_parse_errors.rs", "rank": 23, "score": 90244.17069466863 }, { "content": "#[test]\n\nfn parse_errors_logspec() {\n\n match LogSpecification::parse(\"info, foo=bar, fuzz=debug\")\n\n .err()\n\n .unwrap()\n\n {\n\n FlexiLoggerError::Parse(_, logspec) => {\n\n assert_eq!(\n\n logspec.module_filters(),\n\n LogSpecification::parse(\"info, fuzz=debug\")\n\n .unwrap()\n\n .module_filters()\n\n );\n\n #[cfg(feature = \"textfilter\")]\n\n assert!(logspec.text_filter().is_none());\n\n }\n\n _ => panic!(\"Wrong error from parsing (1)\"),\n\n }\n\n\n\n match LogSpecification::parse(\"info, ene mene dubbedene\")\n\n .err()\n", "file_path": "tests/test_parse_errors.rs", "rank": 24, "score": 90244.17069466863 }, { "content": "fn push_err(s: &str, parse_errs: &mut String) {\n\n if !parse_errs.is_empty() {\n\n parse_errs.push_str(\"; \");\n\n }\n\n parse_errs.push_str(s);\n\n}\n\n\n", "file_path": "src/log_specification.rs", "rank": 25, "score": 89260.06023617007 }, { "content": "fn contains_whitespace(s: &str, parse_errs: &mut String) -> bool {\n\n let result = s.chars().any(char::is_whitespace);\n\n if result {\n\n push_err(\n\n &format!(\n\n \"ignoring invalid part in log spec '{}' (contains a whitespace)\",\n\n s\n\n ),\n\n parse_errs,\n\n );\n\n }\n\n result\n\n}\n\n\n\n#[allow(clippy::needless_doctest_main)]\n\n/// Builder for `LogSpecification`.\n\n///\n\n/// # Example\n\n///\n\n/// Use the reconfigurability feature and build the log spec programmatically.\n", "file_path": "src/log_specification.rs", "rank": 26, "score": 85559.80522101367 }, { "content": "// Use a thread-local buffer for writing to stderr or stdout\n\nfn write_buffered(\n\n format_function: FormatFunction,\n\n now: &mut DeferredNow,\n\n record: &Record,\n\n w: &mut dyn Write,\n\n) -> Result<(), std::io::Error> {\n\n let mut result: Result<(), std::io::Error> = Ok(());\n\n\n\n buffer_with(|tl_buf| match tl_buf.try_borrow_mut() {\n\n Ok(mut buffer) => {\n\n (format_function)(&mut *buffer, now, record)\n\n .unwrap_or_else(|e| write_err(ERR_FORMATTING, &e));\n\n buffer\n\n .write_all(b\"\\n\")\n\n .unwrap_or_else(|e| write_err(ERR_FORMATTING, &e));\n\n\n\n result = w.write_all(&*buffer).map_err(|e| {\n\n write_err(ERR_WRITING, &e);\n\n e\n\n });\n", "file_path": "src/primary_writer.rs", "rank": 27, "score": 85365.93062504177 }, { "content": "fn use_trace() {\n\n for _ in 1..100 {\n\n trace!(\"This is a trace message\");\n\n }\n\n}\n", "file_path": "benches/bench_reconfigurable.rs", "rank": 28, "score": 85358.1183968299 }, { "content": "fn use_trace() {\n\n for _ in 1..100 {\n\n trace!(\"This is a trace message\");\n\n }\n\n}\n", "file_path": "benches/bench_standard.rs", "rank": 29, "score": 85358.1183968299 }, { "content": "struct Struct {\n\n data: [u8; 32],\n\n}\n\n\n\nimpl fmt::Display for Struct {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{:?}\", self.data)\n\n }\n\n}\n\n\n", "file_path": "examples/performance.rs", "rank": 30, "score": 81582.10351475992 }, { "content": "fn write_log_lines() {\n\n // Fill first three files by size\n\n trace!(\"{}\", 'a');\n\n trace!(\"{}\", 'b');\n\n trace!(\"{}\", 'c');\n\n\n\n trace!(\"{}\", 'd');\n\n trace!(\"{}\", 'e');\n\n trace!(\"{}\", 'f');\n\n\n\n trace!(\"{}\", 'g');\n\n trace!(\"{}\", 'h');\n\n trace!(\"{}\", 'i');\n\n\n\n trace!(\"{}\", 'j');\n\n\n\n // now wait to enforce a rotation with a smaller file\n\n std::thread::sleep(std::time::Duration::from_secs(2));\n\n trace!(\"{}\", 'k');\n\n\n", "file_path": "tests/test_age_or_size.rs", "rank": 31, "score": 80661.06308717371 }, { "content": "#[cfg(feature = \"colors\")]\n\nstruct Palette {\n\n pub error: Style,\n\n pub warn: Style,\n\n pub info: Style,\n\n pub debug: Style,\n\n pub trace: Style,\n\n}\n\n#[cfg(feature = \"colors\")]\n\nimpl Palette {\n\n fn default() -> Palette {\n\n Palette {\n\n error: Style::new(Color::Fixed(196)).bold(),\n\n warn: Style::new(Color::Fixed(208)).bold(),\n\n info: Style::new(Color::Unset),\n\n debug: Style::new(Color::Fixed(7)),\n\n trace: Style::new(Color::Fixed(8)),\n\n }\n\n }\n\n\n\n fn parse(palette: &str) -> Result<Palette, std::num::ParseIntError> {\n", "file_path": "src/formats.rs", "rank": 32, "score": 66046.62530079715 }, { "content": "#[allow(clippy::cognitive_complexity)]\n\nfn test_push_new_spec(log_handle: &mut ReconfigurationHandle) {\n\n error!(\"2-error message\");\n\n warn!(\"2-warning\");\n\n info!(\"2-info message\");\n\n debug!(\"2-debug message - you must not see it!\");\n\n trace!(\"2-trace message - you must not see it!\");\n\n\n\n log_handle.parse_and_push_temp_spec(\"error\");\n\n error!(\"2-error message\");\n\n warn!(\"2-warning - you must not see it!\");\n\n info!(\"2-info message - you must not see it!\");\n\n debug!(\"2-debug message - you must not see it!\");\n\n trace!(\"2-trace message - you must not see it!\");\n\n\n\n log_handle.parse_and_push_temp_spec(\"trace\");\n\n error!(\"2-error message\");\n\n warn!(\"2-warning\");\n\n info!(\"2-info message\");\n\n debug!(\"2-debug message\");\n\n trace!(\"2-trace message\");\n", "file_path": "tests/test_reconfigure_methods.rs", "rank": 33, "score": 65802.84933179713 }, { "content": "fn test_parse_new_spec(log_handle: &mut ReconfigurationHandle) {\n\n error!(\"1-error message\");\n\n warn!(\"1-warning\");\n\n info!(\"1-info message\");\n\n debug!(\"1-debug message - you must not see it!\");\n\n trace!(\"1-trace message - you must not see it!\");\n\n\n\n log_handle.parse_new_spec(\"error\");\n\n error!(\"1-error message\");\n\n warn!(\"1-warning - you must not see it!\");\n\n info!(\"1-info message - you must not see it!\");\n\n debug!(\"1-debug message - you must not see it!\");\n\n trace!(\"1-trace message - you must not see it!\");\n\n\n\n log_handle.parse_new_spec(\"trace\");\n\n error!(\"1-error message\");\n\n warn!(\"1-warning\");\n\n info!(\"1-info message\");\n\n debug!(\"1-debug message\");\n\n trace!(\"1-trace message\");\n\n\n\n log_handle.parse_new_spec(\"info\");\n\n}\n\n\n", "file_path": "tests/test_reconfigure_methods.rs", "rank": 34, "score": 65802.84933179713 }, { "content": "struct Dummy();\n\nimpl std::fmt::Display for Dummy {\n\n fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {\n\n info!(\"Here comes the inner message :-| \");\n\n f.write_str(\"Dummy!!\")?;\n\n Ok(())\n\n }\n\n}\n", "file_path": "tests/test_recursion.rs", "rank": 35, "score": 64595.59828610903 }, { "content": "#[cfg(feature = \"colors\")]\n\nfn parse_style(input: &str) -> Result<Style, std::num::ParseIntError> {\n\n Ok(if input == \"-\" {\n\n Style::new(Color::Unset)\n\n } else {\n\n Style::new(Color::Fixed(input.parse()?))\n\n })\n\n}\n", "file_path": "src/formats.rs", "rank": 36, "score": 62286.24473541592 }, { "content": "#[derive(Clone, Copy)]\n\nenum IdxState {\n\n // We rotate to numbered files, and no rotated numbered file exists yet\n\n Start,\n\n // highest index of rotated numbered files\n\n Idx(u32),\n\n}\n\n\n", "file_path": "src/writers/file_log_writer.rs", "rank": 37, "score": 61288.28418394235 }, { "content": "// Created_at is needed both for\n\n// is_rotation_necessary() -> if Criterion::Age -> NamingState::CreatedAt\n\n// and rotate_to_date() -> if Naming::Timestamps -> RollState::Age\n\nenum NamingState {\n\n CreatedAt,\n\n IdxState(IdxState),\n\n}\n\n\n", "file_path": "src/writers/file_log_writer.rs", "rank": 38, "score": 61283.97240854209 }, { "content": "enum RollState {\n\n Size(u64, u64), // max_size, current_size\n\n Age(Age),\n\n AgeOrSize(Age, u64, u64), // age, max_size, current_size\n\n}\n\n\n", "file_path": "src/writers/file_log_writer.rs", "rank": 39, "score": 61283.97240854209 }, { "content": "#[derive(Clone)]\n\nstruct FilenameConfig {\n\n directory: PathBuf,\n\n file_basename: String,\n\n suffix: String,\n\n use_timestamp: bool,\n\n}\n\n\n", "file_path": "src/writers/file_log_writer.rs", "rank": 40, "score": 60864.958014514516 }, { "content": "// Describes how rotation should work\n\nstruct RotationConfig {\n\n // Defines if rotation should be based on size or date\n\n criterion: Criterion,\n\n // Defines if rotated files should be numbered or get a date-based name\n\n naming: Naming,\n\n // Defines the cleanup strategy\n\n cleanup: Cleanup,\n\n}\n", "file_path": "src/writers/file_log_writer.rs", "rank": 41, "score": 60860.59543976767 }, { "content": "struct RotationState {\n\n naming_state: NamingState,\n\n roll_state: RollState,\n\n created_at: DateTime<Local>,\n\n cleanup: Cleanup,\n\n o_cleanup_thread_handle: Option<CleanupThreadHandle>,\n\n}\n\n\n", "file_path": "src/writers/file_log_writer.rs", "rank": 42, "score": 60860.59543976767 }, { "content": "fn get_fake_creation_date() -> Result<DateTime<Local>, FlexiLoggerError> {\n\n Ok(Local::now())\n\n}\n\n\n", "file_path": "src/writers/file_log_writer.rs", "rank": 43, "score": 60548.818277224986 }, { "content": "enum MessageToCleanupThread {\n\n Act,\n\n Die,\n\n}\n", "file_path": "src/writers/file_log_writer.rs", "rank": 44, "score": 60206.97192798601 }, { "content": "struct CleanupThreadHandle {\n\n sender: std::sync::mpsc::Sender<MessageToCleanupThread>,\n\n join_handle: std::thread::JoinHandle<()>,\n\n}\n", "file_path": "src/writers/file_log_writer.rs", "rank": 45, "score": 59786.30791748204 }, { "content": "// The immutable configuration of a FileLogWriter.\n\nstruct FileLogWriterConfig {\n\n format: FormatFunction,\n\n print_message: bool,\n\n append: bool,\n\n filename_config: FilenameConfig,\n\n o_create_symlink: Option<PathBuf>,\n\n use_windows_line_ending: bool,\n\n}\n\nimpl FileLogWriterConfig {\n\n // Factory method; uses the same defaults as Logger.\n\n pub fn default() -> Self {\n\n Self {\n\n format: default_format,\n\n print_message: false,\n\n filename_config: FilenameConfig {\n\n directory: PathBuf::from(\".\"),\n\n file_basename: String::new(),\n\n suffix: \"log\".to_string(),\n\n use_timestamp: true,\n\n },\n", "file_path": "src/writers/file_log_writer.rs", "rank": 46, "score": 58783.23195509349 }, { "content": "// The mutable state of a FileLogWriter.\n\nstruct FileLogWriterState {\n\n o_log_file: Option<File>,\n\n o_rotation_state: Option<RotationState>,\n\n line_ending: &'static [u8],\n\n}\n\nimpl FileLogWriterState {\n\n // If rotate, the logger writes into a file with infix `_rCURRENT`.\n\n fn try_new(\n\n config: &FileLogWriterConfig,\n\n o_rotation_config: &Option<RotationConfig>,\n\n cleanup_in_background_thread: bool,\n\n ) -> Result<Self, FlexiLoggerError> {\n\n let (log_file, o_rotation_state) = match o_rotation_config {\n\n None => {\n\n let (log_file, _created_at, _p_path) = open_log_file(config, false)?;\n\n (log_file, None)\n\n }\n\n Some(rotate_config) => {\n\n // first rotate, then open the log file\n\n let naming_state = match rotate_config.naming {\n", "file_path": "src/writers/file_log_writer.rs", "rank": 47, "score": 58783.23195509349 }, { "content": "#[allow(unused_variables)]\n\nfn get_creation_date(path: &PathBuf) -> Result<DateTime<Local>, FlexiLoggerError> {\n\n // On windows, we know that try_get_creation_date() returns a result, but it is wrong.\n\n // On linux, we know that try_get_creation_date() returns an error.\n\n #[cfg(any(target_os = \"windows\", target_os = \"linux\"))]\n\n return get_fake_creation_date();\n\n\n\n // On all others of the many platforms, we give the real creation date a try,\n\n // and fall back to the fake if it is not available.\n\n #[cfg(not(any(target_os = \"windows\", target_os = \"linux\")))]\n\n match try_get_creation_date(path) {\n\n Ok(d) => Ok(d),\n\n Err(e) => get_fake_creation_date(),\n\n }\n\n}\n\n\n", "file_path": "src/writers/file_log_writer.rs", "rank": 48, "score": 56526.41135031314 }, { "content": "#[cfg(not(any(target_os = \"windows\", target_os = \"linux\")))]\n\nfn try_get_creation_date(path: &PathBuf) -> Result<DateTime<Local>, FlexiLoggerError> {\n\n Ok(std::fs::metadata(path)?.created()?.into())\n\n}\n\n\n\n/// A configurable `LogWriter` implementation that writes to a file or a sequence of files.\n\n///\n\n/// See the [module description](index.html) for usage guidance.\n\npub struct FileLogWriter {\n\n config: FileLogWriterConfig,\n\n // the state needs to be mutable; since `Log.log()` requires an unmutable self,\n\n // which translates into a non-mutating `LogWriter::write()`,\n\n // we need internal mutability and thread-safety.\n\n state: Mutex<FileLogWriterState>,\n\n max_log_level: log::LevelFilter,\n\n}\n\nimpl FileLogWriter {\n\n /// Instantiates a builder for `FileLogWriter`.\n\n #[must_use]\n\n pub fn builder() -> FileLogWriterBuilder {\n\n FileLogWriterBuilder {\n", "file_path": "src/writers/file_log_writer.rs", "rank": 49, "score": 55433.47656457631 }, { "content": "fn list_of_files(pattern: &str) -> Result<std::vec::IntoIter<PathBuf>, FlexiLoggerError> {\n\n let mut log_files: Vec<PathBuf> = glob::glob(pattern)\n\n .unwrap(/* failure should be impossible */)\n\n .filter_map(Result::ok)\n\n .collect();\n\n log_files.reverse();\n\n Ok(log_files.into_iter())\n\n}\n\n\n", "file_path": "src/writers/file_log_writer.rs", "rank": 50, "score": 55221.26893174932 }, { "content": "fn main() {\n\n #[cfg(feature = \"colors\")]\n\n for i in 0..=255 {\n\n println!(\"{}: {}\", i, yansi::Paint::fixed(i, i));\n\n }\n\n}\n", "file_path": "examples/colors.rs", "rank": 51, "score": 54215.37505831333 }, { "content": "fn main() {\n\n for pattern in &[\n\n \"./*.log\",\n\n \"./*.alerts\",\n\n \"./*.seclog\",\n\n \"./*logspec.toml\",\n\n \"./log_files/**/*.log\",\n\n \"./log_files/**/*.zip\",\n\n \"./test_spec/*.toml\",\n\n ] {\n\n for globresult in glob::glob(pattern).unwrap() {\n\n match globresult {\n\n Err(e) => eprintln!(\"Evaluating pattern {:?} produced error {}\", pattern, e),\n\n Ok(pathbuf) => {\n\n std::fs::remove_file(&pathbuf).unwrap();\n\n }\n\n }\n\n }\n\n }\n\n\n", "file_path": "scripts/cleanup.rs", "rank": 52, "score": 54215.37505831333 }, { "content": "fn main() {\n\n // --------------------------------\n\n println!(\"flexi_logger\");\n\n flexi_logger::Logger::with_str(\"off\")\n\n .format(flexi_logger::detailed_format)\n\n .start()\n\n .unwrap();\n\n // --------------------------------\n\n // $> Set-Item -Path Env:RUST_LOG -Value \"trace\"\n\n // println!(\"env_logger\");\n\n // env_logger::init();\n\n // $> Set-Item -Path Env:RUST_LOG\n\n // --------------------------------\n\n let mut structs = Vec::new();\n\n for i in 0..100 {\n\n structs.push(Struct {\n\n data: [i as u8; 32],\n\n });\n\n }\n\n\n", "file_path": "examples/performance.rs", "rank": 53, "score": 54215.37505831333 }, { "content": "fn main() {\n\n // format\n\n run_command!(\"cargo\", \"fmt\");\n\n\n\n // Build in important variants\n\n run_command!(\"cargo\", \"build\");\n\n run_command!(\"cargo\", \"build\", \"--no-default-features\");\n\n run_command!(\"cargo\", \"build\", \"--all-features\");\n\n run_command!(\"cargo\", \"+1.37.0\", \"build\", \"--no-default-features\");\n\n run_command!(\"cargo\", \"+1.37.0\", \"build\", \"--all-features\");\n\n run_command!(\"cargo\", \"build\", \"--release\");\n\n run_command!(\"cargo\", \"build\", \"--release\", \"--all-features\");\n\n\n\n // Clippy in important variants\n\n run_command!(\"cargo\", \"clippy\", \"--\", \"-D\", \"warnings\");\n\n run_command!(\"cargo\", \"clippy\", \"--all-features\", \"--\", \"-D\", \"warnings\");\n\n\n\n // Run tests in important variants\n\n run_command!(\"cargo\", \"test\", \"--release\", \"--all-features\");\n\n run_command!(\"cargo\", \"test\", \"--no-default-features\");\n", "file_path": "scripts/qualify.rs", "rank": 54, "score": 54215.37505831333 }, { "content": "struct SecWriter(Arc<FileLogWriter>);\n\n\n\nimpl SecWriter {\n\n pub fn new() -> (Box<SecWriter>, Arc<FileLogWriter>) {\n\n let a_flw = Arc::new(\n\n FileLogWriter::builder()\n\n .discriminant(\"Security\")\n\n .suffix(\"seclog\")\n\n .print_message()\n\n .try_build()\n\n .unwrap(),\n\n );\n\n (Box::new(SecWriter(Arc::clone(&a_flw))), a_flw)\n\n }\n\n}\n\nimpl LogWriter for SecWriter {\n\n fn write(&self, now: &mut DeferredNow, record: &Record) -> std::io::Result<()> {\n\n self.0.write(now, record)\n\n }\n\n fn flush(&self) -> std::io::Result<()> {\n\n self.0.flush()\n\n }\n\n fn max_log_level(&self) -> log::LevelFilter {\n\n log::LevelFilter::Error\n\n }\n\n}\n\n\n", "file_path": "tests/test_multi_logger.rs", "rank": 55, "score": 53332.69430480308 }, { "content": "fn main() {\n\n // Build in important variants\n\n run_command!(\"cargo\", \"build\", \"--release\", \"--all-features\");\n\n\n\n // Clippy in important variants\n\n run_command!(\"cargo\", \"clippy\", \"--all-features\", \"--\", \"-D\", \"warnings\");\n\n\n\n // Run tests in important variants\n\n run_command!(\"cargo\", \"test\", \"--release\", \"--all-features\");\n\n run_script(\"cleanup\");\n\n\n\n // doc\n\n run_command!(\"cargo\", \"doc\", \"--all-features\", \"--no-deps\", \"--open\");\n\n\n\n // say goodbye\n\n println!(\"\\n> fast qualification is done :-) Looks like you're ready to do the full qualification?\");\n\n}\n", "file_path": "scripts/qualify_fast.rs", "rank": 56, "score": 52824.158349323596 }, { "content": "/// Writes to a single log output stream.\n\n///\n\n/// Boxed instances of `LogWriter` can be used as additional log targets\n\n/// (see [module description](index.html) for more details).\n\npub trait LogWriter: Sync + Send {\n\n /// Writes out a log line.\n\n ///\n\n /// # Errors\n\n ///\n\n /// `std::io::Error`\n\n fn write(&self, now: &mut DeferredNow, record: &Record) -> std::io::Result<()>;\n\n\n\n /// Flushes any buffered records.\n\n ///\n\n /// # Errors\n\n ///\n\n /// `std::io::Error`\n\n fn flush(&self) -> std::io::Result<()>;\n\n\n\n /// Provides the maximum log level that is to be written.\n\n fn max_log_level(&self) -> log::LevelFilter;\n\n\n\n /// Sets the format function.\n\n /// Defaults to ([`formats::default_format`](fn.default_format.html)),\n", "file_path": "src/writers/log_writer.rs", "rank": 57, "score": 52325.44307794377 }, { "content": "#[test]\n\n#[cfg(feature = \"textfilter\")]\n\nfn test_textfilter() {\n\n use flexi_logger::{default_format, LogSpecification, Logger};\n\n use log::*;\n\n\n\n use std::env;\n\n use std::fs::File;\n\n use std::io::{BufRead, BufReader};\n\n use std::path::Path;\n\n\n\n let logspec = LogSpecification::parse(\"info/Hello\").unwrap();\n\n Logger::with(logspec)\n\n .format(default_format)\n\n .print_message()\n\n .log_to_file()\n\n .suppress_timestamp()\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n\n\n error!(\"This is an error message\");\n\n warn!(\"This is a warning\");\n", "file_path": "tests/test_textfilter.rs", "rank": 58, "score": 51539.256155339644 }, { "content": "#[test]\n\nfn test() {\n\n // more complex just to support validation:\n\n let (sec_writer, sec_handle) = SecWriter::new();\n\n let mut log_handle = Logger::with_str(\"info, fantasy = trace\")\n\n .format(detailed_format)\n\n .print_message()\n\n .log_to_file()\n\n .add_writer(\"Sec\", sec_writer)\n\n .add_writer(\"Alert\", alert_logger())\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n\n\n // Explicitly send logs to different loggers\n\n error!(target : \"{Sec}\", \"This is a security-relevant error message\");\n\n error!(target : \"{Sec,Alert}\", \"This is a security-relevant alert message\");\n\n error!(target : \"{Sec,Alert,_Default}\", \"This is a security-relevant alert and log message\");\n\n error!(target : \"{Alert}\", \"This is an alert\");\n\n\n\n // Nicer: use explicit macros\n\n sec_alert_error!(\"This is another security-relevant alert and log message\");\n", "file_path": "tests/test_multi_logger.rs", "rank": 59, "score": 51539.256155339644 }, { "content": "#[test]\n\nfn test_mods_off() {\n\n let handle: ReconfigurationHandle = Logger::with_env_or_str(\"info, test_mods_off::mymod1=off\")\n\n .format(detailed_format)\n\n .log_to_file()\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n\n\n error!(\"This is an error message\");\n\n warn!(\"This is a warning\");\n\n mymod1::test_traces();\n\n info!(\"This is an info message\");\n\n debug!(\"This is a debug message - you must not see it!\");\n\n trace!(\"This is a trace message - you must not see it!\");\n\n\n\n handle.validate_logs(&[\n\n (\"ERROR\", \"test_mods\", \"error\"),\n\n (\"WARN\", \"test_mods\", \"warning\"),\n\n (\"INFO\", \"test_mods\", \"info\"),\n\n ]);\n\n}\n", "file_path": "tests/test_mods_off.rs", "rank": 60, "score": 51539.256155339644 }, { "content": "fn parse_err(\n\n errors: String,\n\n logspec: LogSpecification,\n\n) -> Result<LogSpecification, FlexiLoggerError> {\n\n Err(FlexiLoggerError::Parse(errors, logspec))\n\n}\n\n\n", "file_path": "src/log_specification.rs", "rank": 61, "score": 51539.256155339644 }, { "content": "#[test]\n\nfn test_recursion() {\n\n Logger::with_str(\"info\")\n\n .format(detailed_format)\n\n .log_to_file()\n\n .duplicate_to_stderr(Duplicate::All)\n\n .duplicate_to_stdout(Duplicate::All)\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed because: {}\", e));\n\n\n\n let dummy = Dummy();\n\n\n\n for _ in 0..10 {\n\n error!(\"This is an error message for {}\", dummy);\n\n warn!(\"This is a warning for {}\", dummy);\n\n info!(\"This is an info message for {}\", dummy);\n\n debug!(\"This is a debug message for {}\", dummy);\n\n trace!(\"This is a trace message for {}\", dummy);\n\n }\n\n}\n\n\n", "file_path": "tests/test_recursion.rs", "rank": 62, "score": 51539.256155339644 }, { "content": "#[test]\n\nfn test_mods() {\n\n let handle: ReconfigurationHandle = Logger::with_env_or_str(\n\n \"info, test_mods::mymod1=debug, test_mods::mymod2=error, test_mods::mymod1::mysubmod = off\",\n\n )\n\n .format(detailed_format)\n\n .log_to_file()\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n\n\n error!(\"This is an error message\");\n\n warn!(\"This is a warning\");\n\n info!(\"This is an info message\");\n\n debug!(\"This is a debug message - you must not see it!\");\n\n trace!(\"This is a trace message - you must not see it!\");\n\n\n\n mymod1::test_traces();\n\n mymod2::test_traces();\n\n\n\n handle.validate_logs(&[\n\n (\"ERROR\", \"test_mods\", \"error\"),\n", "file_path": "tests/test_mods.rs", "rank": 63, "score": 51539.256155339644 }, { "content": "#[test]\n\nfn test_mods() {\n\n Logger::with_str(\"trace\")\n\n .log_target(LogTarget::StdOut)\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n\n\n error!(\"This is an error message\");\n\n warn!(\"This is a warning\");\n\n info!(\"This is an info message\");\n\n debug!(\"This is a debug message\");\n\n trace!(\"This is a trace message\");\n\n}\n", "file_path": "tests/test_colors.rs", "rank": 64, "score": 51539.256155339644 }, { "content": "#[test]\n\nfn you_must_not_see_anything() {\n\n Logger::with_str(\"info\")\n\n .log_target(LogTarget::DevNull)\n\n .start()\n\n .unwrap();\n\n\n\n error!(\"This is an error message - you must not see it!\");\n\n warn!(\"This is a warning - you must not see it!\");\n\n info!(\"This is an info message - you must not see it!\");\n\n debug!(\"This is a debug message - you must not see it!\");\n\n trace!(\"This is a trace message - you must not see it!\");\n\n}\n", "file_path": "tests/test_no_logger.rs", "rank": 65, "score": 50348.930405373845 }, { "content": "#[test]\n\nfn test_readme_deps() {\n\n assert_markdown_deps_updated!(\"README.md\");\n\n}\n", "file_path": "tests/version_numbers.rs", "rank": 66, "score": 50348.930405373845 }, { "content": "#[test]\n\nfn test_age_or_size() {\n\n let directory = define_directory();\n\n Logger::with_str(\"trace\")\n\n .log_to_file()\n\n .duplicate_to_stderr(Duplicate::Info)\n\n .directory(directory.clone())\n\n .rotate(\n\n Criterion::AgeOrSize(Age::Second, 80),\n\n Naming::Numbers,\n\n Cleanup::Never,\n\n )\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n // info!(\"test correct rotation by age or size\");\n\n\n\n write_log_lines();\n\n\n\n verify_logs(&directory);\n\n}\n\n\n", "file_path": "tests/test_age_or_size.rs", "rank": 67, "score": 49243.10967458811 }, { "content": "#[test]\n\nfn test_mods() {\n\n let handle: ReconfigurationHandle = Logger::with_env_or_str(\n\n \"info, test_windows_line_ending::mymod1=debug, test_windows_line_ending::mymod2=error\",\n\n )\n\n .format(detailed_format)\n\n .log_to_file()\n\n .use_windows_line_ending()\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n\n\n error!(\"This is an error message\");\n\n warn!(\"This is a warning\");\n\n info!(\"This is an info message\");\n\n debug!(\"This is a debug message - you must not see it!\");\n\n trace!(\"This is a trace message - you must not see it!\");\n\n\n\n mymod1::test_traces();\n\n mymod2::test_traces();\n\n\n\n handle.validate_logs(&[\n", "file_path": "tests/test_windows_line_ending.rs", "rank": 68, "score": 49243.10967458811 }, { "content": "#[test]\n\nfn multi_threaded() {\n\n // we use a special log line format that starts with a special string so that it is easier to\n\n // verify that all log lines are written correctly\n\n\n\n let start = Local::now();\n\n let directory = define_directory();\n\n let mut reconf_handle = Logger::with_str(\"debug\")\n\n .log_to_file()\n\n .format(test_format)\n\n .duplicate_to_stderr(Duplicate::Info)\n\n .directory(directory.clone())\n\n .rotate(\n\n Criterion::Size(ROTATE_OVER_SIZE),\n\n Naming::Numbers,\n\n Cleanup::Never,\n\n )\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n info!(\n\n \"create a huge number of log lines with a considerable number of threads, verify the log\"\n", "file_path": "tests/test_multi_threaded_numbers.rs", "rank": 69, "score": 49243.10967458811 }, { "content": "#[test]\n\nfn test_reconfigure_methods() {\n\n let mut log_handle = Logger::with_str(\"info\")\n\n .log_to_file()\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n\n\n test_parse_new_spec(&mut log_handle);\n\n test_push_new_spec(&mut log_handle);\n\n validate_logs(&mut log_handle);\n\n}\n\n\n", "file_path": "tests/test_reconfigure_methods.rs", "rank": 70, "score": 49243.10967458811 }, { "content": "#[test]\n\nfn multi_threaded() {\n\n // we use a special log line format that starts with a special string so that it is easier to\n\n // verify that all log lines are written correctly\n\n\n\n let start = Local::now();\n\n let directory = define_directory();\n\n let mut reconf_handle = Logger::with_str(\"debug\")\n\n .log_to_file()\n\n .format(test_format)\n\n .create_symlink(\"link_to_mt_log\")\n\n .duplicate_to_stderr(Duplicate::Info)\n\n .directory(directory.clone())\n\n .rotate(\n\n Criterion::Age(Age::Minute),\n\n Naming::Timestamps,\n\n Cleanup::Never,\n\n )\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n info!(\n", "file_path": "tests/test_multi_threaded_dates.rs", "rank": 71, "score": 49243.10967458811 }, { "content": "fn run_script(s: &str) {\n\n let mut path = std::path::PathBuf::from(std::env::var(\"CARGO_SCRIPT_BASE_PATH\").unwrap());\n\n path.push(s);\n\n let script = path.to_string_lossy().to_owned().to_string();\n\n run_command!(\"cargo\", \"script\", script);\n\n}\n\n\n", "file_path": "scripts/qualify.rs", "rank": 72, "score": 48605.51844903853 }, { "content": "fn custom_format(\n\n writer: &mut dyn std::io::Write,\n\n _now: &mut DeferredNow,\n\n record: &Record,\n\n) -> Result<(), std::io::Error> {\n\n // Only write the message and the level, without the module\n\n write!(writer, \"{}: {}\", record.level(), &record.args())\n\n}\n\n\n", "file_path": "tests/test_custom_log_writer_format.rs", "rank": 73, "score": 48213.1035229906 }, { "content": "fn open_log_file(\n\n config: &FileLogWriterConfig,\n\n with_rotation: bool,\n\n) -> Result<(File, DateTime<Local>, PathBuf), FlexiLoggerError> {\n\n let o_infix = if with_rotation {\n\n Some(CURRENT_INFIX)\n\n } else {\n\n None\n\n };\n\n let p_path = get_filepath(o_infix, &config.filename_config);\n\n if config.print_message {\n\n println!(\"Log is written to {}\", &p_path.display());\n\n }\n\n if let Some(ref link) = config.o_create_symlink {\n\n self::platform::create_symlink_if_possible(link, &p_path);\n\n }\n\n\n\n let log_file = OpenOptions::new()\n\n .write(true)\n\n .create(true)\n\n .append(config.append)\n\n .truncate(!config.append)\n\n .open(&p_path)?;\n\n\n\n Ok((log_file, get_creation_date(&p_path)?, p_path))\n\n}\n\n\n", "file_path": "src/writers/file_log_writer.rs", "rank": 74, "score": 48213.1035229906 }, { "content": "fn run_script(s: &str) {\n\n let mut path = std::path::PathBuf::from(std::env::var(\"CARGO_SCRIPT_BASE_PATH\").unwrap());\n\n path.push(s);\n\n let script = path.to_string_lossy().to_owned().to_string();\n\n run_command!(\"cargo\", \"script\", script);\n\n}\n\n\n", "file_path": "scripts/qualify_fast.rs", "rank": 75, "score": 47415.19269907272 }, { "content": "// Moves the current file to the timestamp of the CURRENT file's creation date.\n\n// If the rotation comes very fast, the new timestamp would be equal to the old one.\n\n// To avoid file collisions, we insert an additional string to the filename (\".restart-<number>\").\n\n// The number is incremented in case of repeated collisions.\n\n// Cleaning up can leave some restart-files with higher numbers; if we still are in the same\n\n// second, we need to continue with the restart-incrementing.\n\nfn rotate_output_file_to_date(\n\n creation_date: &DateTime<Local>,\n\n config: &FileLogWriterConfig,\n\n) -> Result<(), FlexiLoggerError> {\n\n let current_path = get_filepath(Some(CURRENT_INFIX), &config.filename_config);\n\n\n\n let mut rotated_path = get_filepath(\n\n Some(&creation_date.format(\"_r%Y-%m-%d_%H-%M-%S\").to_string()),\n\n &config.filename_config,\n\n );\n\n\n\n // Search for rotated_path as is and for restart-siblings;\n\n // if any exists, find highest restart and add 1, else continue without restart\n\n let mut pattern = rotated_path.clone();\n\n pattern.set_extension(\"\");\n\n let mut pattern = pattern.to_string_lossy().to_string();\n\n pattern.push_str(\".restart-*\");\n\n\n\n let file_list = glob::glob(&pattern).unwrap(/*ok*/);\n\n let mut vec: Vec<PathBuf> = file_list.map(Result::unwrap).collect();\n", "file_path": "src/writers/file_log_writer.rs", "rank": 76, "score": 47257.07219453137 }, { "content": "#[test]\n\nfn test_detailed_files_rot() {\n\n let handle = Logger::with_str(\"info\")\n\n .format(detailed_format)\n\n .log_to_file()\n\n .rotate(Criterion::Size(2000), Naming::Numbers, Cleanup::Never)\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n\n\n error!(\"This is an error message\");\n\n warn!(\"This is a warning\");\n\n info!(\"This is an info message\");\n\n debug!(\"This is a debug message - you must not see it!\");\n\n trace!(\"This is a trace message - you must not see it!\");\n\n handle.validate_logs(&[\n\n (\"ERROR\", \"test_detailed_files_rot\", \"error\"),\n\n (\"WARN\", \"test_detailed_files_rot\", \"warning\"),\n\n (\"INFO\", \"test_detailed_files_rot\", \"info\"),\n\n ]);\n\n}\n", "file_path": "tests/test_detailed_files_rot.rs", "rank": 77, "score": 47251.3736412345 }, { "content": "#[test]\n\nfn test_default_file_and_writer() {\n\n let w = FileLogWriter::builder()\n\n .format(detailed_format)\n\n .discriminant(\"bar\")\n\n .try_build()\n\n .unwrap();\n\n\n\n let handle = Logger::with_str(\"info\")\n\n .log_target(LogTarget::FileAndWriter(Box::new(w)))\n\n .format(detailed_format)\n\n .discriminant(\"foo\")\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n\n\n error!(\"This is an error message\");\n\n warn!(\"This is a warning\");\n\n info!(\"This is an info message\");\n\n debug!(\"This is a debug message - you must not see it!\");\n\n trace!(\"This is a trace message - you must not see it!\");\n\n\n", "file_path": "tests/test_default_file_and_writer.rs", "rank": 78, "score": 47251.3736412345 }, { "content": "fn list_of_log_and_zip_files(\n\n filename_config: &FilenameConfig,\n\n) -> Result<\n\n std::iter::Chain<std::vec::IntoIter<PathBuf>, std::vec::IntoIter<PathBuf>>,\n\n FlexiLoggerError,\n\n> {\n\n let fn_pattern = String::with_capacity(180)\n\n .add(&filename_config.file_basename)\n\n .add(\"_r[0-9]*\")\n\n .add(\".\");\n\n\n\n let mut log_pattern = filename_config.directory.clone();\n\n log_pattern.push(fn_pattern.clone().add(&filename_config.suffix));\n\n let log_pattern = log_pattern.as_os_str().to_string_lossy();\n\n\n\n let mut zip_pattern = filename_config.directory.clone();\n\n zip_pattern.push(fn_pattern.add(\"zip\"));\n\n let zip_pattern = zip_pattern.as_os_str().to_string_lossy();\n\n\n\n Ok(list_of_files(&log_pattern)?.chain(list_of_files(&zip_pattern)?))\n\n}\n\n\n", "file_path": "src/writers/file_log_writer.rs", "rank": 79, "score": 47251.3736412345 }, { "content": "fn remove_or_zip_too_old_logfiles(\n\n o_cleanup_thread_handle: &Option<CleanupThreadHandle>,\n\n cleanup_config: &Cleanup,\n\n filename_config: &FilenameConfig,\n\n) -> Result<(), FlexiLoggerError> {\n\n if let Some(ref cleanup_thread_handle) = o_cleanup_thread_handle {\n\n cleanup_thread_handle\n\n .sender\n\n .send(MessageToCleanupThread::Act)\n\n .ok();\n\n Ok(())\n\n } else {\n\n remove_or_zip_too_old_logfiles_impl(cleanup_config, filename_config)\n\n }\n\n}\n\n\n", "file_path": "src/writers/file_log_writer.rs", "rank": 80, "score": 47251.3736412345 }, { "content": "#[test]\n\nfn test_default_files_dir() {\n\n let handle = flexi_logger::Logger::with_str(\"info\")\n\n .log_to_file()\n\n .directory(\"log_files\")\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n\n\n error!(\"This is an error message\");\n\n warn!(\"This is a warning\");\n\n info!(\"This is an info message\");\n\n debug!(\"This is a debug message - you must not see it!\");\n\n trace!(\"This is a trace message - you must not see it!\");\n\n handle.validate_logs(&[\n\n (\"ERROR\", \"test_default_files_dir\", \"error\"),\n\n (\"WARN\", \"test_default_files_dir\", \"warning\"),\n\n (\"INFO\", \"test_default_files_dir\", \"info\"),\n\n ]);\n\n}\n", "file_path": "tests/test_default_files_dir.rs", "rank": 81, "score": 47251.3736412345 }, { "content": "// Could not implement `std::convert::From` because other parameters are required.\n\nfn try_roll_state_from_criterion(\n\n criterion: Criterion,\n\n config: &FileLogWriterConfig,\n\n p_path: &Path,\n\n) -> Result<RollState, FlexiLoggerError> {\n\n Ok(match criterion {\n\n Criterion::Age(age) => RollState::Age(age),\n\n Criterion::Size(size) => {\n\n let written_bytes = if config.append {\n\n std::fs::metadata(p_path)?.len()\n\n } else {\n\n 0\n\n };\n\n RollState::Size(size, written_bytes)\n\n } // max_size, current_size\n\n Criterion::AgeOrSize(age, size) => {\n\n let written_bytes = if config.append {\n\n std::fs::metadata(&p_path)?.len()\n\n } else {\n\n 0\n", "file_path": "src/writers/file_log_writer.rs", "rank": 82, "score": 47251.3736412345 }, { "content": "// Moves the current file to the name with the next rotate_idx and returns the next rotate_idx.\n\n// The current file must be closed already.\n\nfn rotate_output_file_to_idx(\n\n idx_state: IdxState,\n\n config: &FileLogWriterConfig,\n\n) -> Result<IdxState, FlexiLoggerError> {\n\n let new_idx = match idx_state {\n\n IdxState::Start => 0,\n\n IdxState::Idx(idx) => idx + 1,\n\n };\n\n\n\n match std::fs::rename(\n\n get_filepath(Some(CURRENT_INFIX), &config.filename_config),\n\n get_filepath(Some(&number_infix(new_idx)), &config.filename_config),\n\n ) {\n\n Ok(()) => Ok(IdxState::Idx(new_idx)),\n\n Err(e) => {\n\n if e.kind() == std::io::ErrorKind::NotFound {\n\n // current did not exist, so we had nothing to do\n\n Ok(idx_state)\n\n } else {\n\n Err(FlexiLoggerError::OutputIo(e))\n\n }\n\n }\n\n }\n\n}\n\n\n\n// See documentation of Criterion::Age.\n", "file_path": "src/writers/file_log_writer.rs", "rank": 83, "score": 47251.3736412345 }, { "content": "#[test]\n\nfn test_custom_log_writer() {\n\n let handle = Logger::with_str(\"info\")\n\n .log_target(LogTarget::Writer(Box::new(CustomWriter {\n\n data: Mutex::new(Vec::new()),\n\n })))\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n\n\n error!(\"This is an error message\");\n\n warn!(\"This is a warning\");\n\n info!(\"This is an info message\");\n\n debug!(\"This is a debug message - you must not see it!\");\n\n trace!(\"This is a trace message - you must not see it!\");\n\n\n\n handle.validate_logs(&[\n\n (\n\n \"ERROR\",\n\n \"test_custom_log_writer\",\n\n \"This is an error message\",\n\n ),\n\n (\"WARN\", \"test_custom_log_writer\", \"This is a warning\"),\n\n (\"INFO\", \"test_custom_log_writer\", \"This is an info message\"),\n\n ]);\n\n}\n", "file_path": "tests/test_custom_log_writer.rs", "rank": 84, "score": 47251.3736412345 }, { "content": "fn remove_or_zip_too_old_logfiles_impl(\n\n cleanup_config: &Cleanup,\n\n filename_config: &FilenameConfig,\n\n) -> Result<(), FlexiLoggerError> {\n\n let (log_limit, zip_limit) = match *cleanup_config {\n\n Cleanup::Never => {\n\n return Ok(());\n\n }\n\n Cleanup::KeepLogFiles(log_limit) => (log_limit, 0),\n\n #[cfg(feature = \"ziplogs\")]\n\n Cleanup::KeepZipFiles(zip_limit) => (0, zip_limit),\n\n #[cfg(feature = \"ziplogs\")]\n\n Cleanup::KeepLogAndZipFiles(log_limit, zip_limit) => (log_limit, zip_limit),\n\n };\n\n\n\n for (index, file) in list_of_log_and_zip_files(&filename_config)?.enumerate() {\n\n if index >= log_limit + zip_limit {\n\n // delete (zip or log)\n\n std::fs::remove_file(&file)?;\n\n } else if index >= log_limit {\n", "file_path": "src/writers/file_log_writer.rs", "rank": 85, "score": 46351.3490467719 }, { "content": "#[test]\n\nfn test_default_files_dir_rot() {\n\n Logger::with_str(\"info\")\n\n .log_target(LogTarget::File)\n\n .directory(\"log_files\")\n\n .rotate(Criterion::Size(2000), Naming::Numbers, Cleanup::Never)\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n\n\n error!(\"This is an error message\");\n\n warn!(\"This is a warning\");\n\n info!(\"This is an info message\");\n\n debug!(\"This is a debug message - you must not see it!\");\n\n trace!(\"This is a trace message - you must not see it!\");\n\n}\n", "file_path": "tests/test_default_files_dir_rot.rs", "rank": 86, "score": 45507.275745779814 }, { "content": "#[test]\n\nfn test_opt_files_dir_dscr() {\n\n let handle = Logger::with_str(\"info\")\n\n .format(opt_format)\n\n .log_to_file()\n\n .directory(\"log_files\")\n\n .discriminant(\"foo\")\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n\n\n error!(\"This is an error message\");\n\n warn!(\"This is a warning\");\n\n info!(\"This is an info message\");\n\n debug!(\"This is a debug message - you must not see it!\");\n\n trace!(\"This is a trace message - you must not see it!\");\n\n handle.validate_logs(&[\n\n (\"ERROR\", \"test_opt_files_dir_dscr\", \"error\"),\n\n (\"WARN\", \"test_opt_files_dir_dscr\", \"warning\"),\n\n (\"INFO\", \"test_opt_files_dir_dscr\", \"info\"),\n\n ]);\n\n}\n", "file_path": "tests/test_opt_files_dir_dscr.rs", "rank": 87, "score": 45507.275745779814 }, { "content": "#[test]\n\nfn test_detailed_files_rot_timestamp() {\n\n let handle = Logger::with_str(\"info\")\n\n .format(detailed_format)\n\n .log_to_file()\n\n .rotate(Criterion::Size(2000), Naming::Numbers, Cleanup::Never)\n\n .o_timestamp(true)\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n\n\n error!(\"This is an error message\");\n\n warn!(\"This is a warning\");\n\n info!(\"This is an info message\");\n\n debug!(\"This is a debug message - you must not see it!\");\n\n trace!(\"This is a trace message - you must not see it!\");\n\n handle.validate_logs(&[\n\n (\"ERROR\", \"test_detailed_files_rot\", \"error\"),\n\n (\"WARN\", \"test_detailed_files_rot\", \"warning\"),\n\n (\"INFO\", \"test_detailed_files_rot\", \"info\"),\n\n ]);\n\n}\n", "file_path": "tests/test_detailed_files_rot_timestamp.rs", "rank": 88, "score": 45507.275745779814 }, { "content": "fn verify_logs(directory: &str) {\n\n let expected_line_counts = [3, 3, 3, 1, 1, 3, 1];\n\n // read all files\n\n let pattern = String::from(directory).add(\"/*\");\n\n let globresults = match glob(&pattern) {\n\n Err(e) => panic!(\n\n \"Is this ({}) really a directory? Listing failed with {}\",\n\n pattern, e\n\n ),\n\n Ok(globresults) => globresults,\n\n };\n\n let mut no_of_log_files = 0;\n\n let mut total_line_count = 0_usize;\n\n for (index, globresult) in globresults.into_iter().enumerate() {\n\n let mut line_count = 0_usize;\n\n let pathbuf = globresult.unwrap_or_else(|e| panic!(\"Ups - error occured: {}\", e));\n\n let f = File::open(&pathbuf)\n\n .unwrap_or_else(|e| panic!(\"Cannot open file {:?} due to {}\", pathbuf, e));\n\n no_of_log_files += 1;\n\n let mut reader = BufReader::new(f);\n", "file_path": "tests/test_age_or_size.rs", "rank": 89, "score": 45279.365816689475 }, { "content": "#[test]\n\nfn test_custom_log_writer_custom_format() {\n\n let handle = Logger::with_str(\"info\")\n\n .log_target(LogTarget::Writer(Box::new(CustomWriter {\n\n data: Mutex::new(Vec::new()),\n\n format: default_format,\n\n })))\n\n .format(custom_format)\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n\n\n error!(\"This is an error message\");\n\n warn!(\"This is a warning\");\n\n info!(\"This is an info message\");\n\n debug!(\"This is a debug message - you must not see it!\");\n\n trace!(\"This is a trace message - you must not see it!\");\n\n\n\n handle.validate_logs(&[\n\n (\n\n \"ERROR\",\n\n \"test_custom_log_writer\",\n\n \"This is an error message\",\n\n ),\n\n (\"WARN\", \"test_custom_log_writer\", \"This is a warning\"),\n\n (\"INFO\", \"test_custom_log_writer\", \"This is an info message\"),\n\n ]);\n\n}\n", "file_path": "tests/test_custom_log_writer_format.rs", "rank": 90, "score": 44714.093587782976 }, { "content": "fn do_work(thread_number: usize) {\n\n trace!(\"({}) Thread started working\", thread_number);\n\n trace!(\"ERROR_IF_PRINTED\");\n\n for idx in 0..NO_OF_LOGLINES_PER_THREAD {\n\n debug!(\"({}) writing out line number {}\", thread_number, idx);\n\n }\n\n trace!(\"MUST_BE_PRINTED\");\n\n}\n\n\n", "file_path": "tests/test_multi_threaded_numbers.rs", "rank": 91, "score": 44317.63593493339 }, { "content": "fn verify_logs(directory: &str) {\n\n // read all files\n\n let pattern = String::from(directory).add(\"/*\");\n\n let globresults = match glob(&pattern) {\n\n Err(e) => panic!(\n\n \"Is this ({}) really a directory? Listing failed with {}\",\n\n pattern, e\n\n ),\n\n Ok(globresults) => globresults,\n\n };\n\n let mut no_of_log_files = 0;\n\n let mut line_count = 0_usize;\n\n for globresult in globresults {\n\n let pathbuf = globresult.unwrap_or_else(|e| panic!(\"Ups - error occured: {}\", e));\n\n let f = File::open(&pathbuf)\n\n .unwrap_or_else(|e| panic!(\"Cannot open file {:?} due to {}\", pathbuf, e));\n\n no_of_log_files += 1;\n\n let mut reader = BufReader::new(f);\n\n let mut buffer = String::new();\n\n while reader.read_line(&mut buffer).unwrap() > 0 {\n", "file_path": "tests/test_multi_threaded_dates.rs", "rank": 92, "score": 44317.63593493339 }, { "content": "fn verify_logs(directory: &str) {\n\n // read all files\n\n let pattern = String::from(directory).add(\"/*\");\n\n let globresults = match glob(&pattern) {\n\n Err(e) => panic!(\n\n \"Is this ({}) really a directory? Listing failed with {}\",\n\n pattern, e\n\n ),\n\n Ok(globresults) => globresults,\n\n };\n\n let mut no_of_log_files = 0;\n\n let mut line_count = 0_usize;\n\n for globresult in globresults {\n\n let pathbuf = globresult.unwrap_or_else(|e| panic!(\"Ups - error occured: {}\", e));\n\n let f = File::open(&pathbuf)\n\n .unwrap_or_else(|e| panic!(\"Cannot open file {:?} due to {}\", pathbuf, e));\n\n no_of_log_files += 1;\n\n let mut reader = BufReader::new(f);\n\n let mut buffer = String::new();\n\n while reader.read_line(&mut buffer).unwrap() > 0 {\n", "file_path": "tests/test_multi_threaded_numbers.rs", "rank": 93, "score": 44317.63593493339 }, { "content": "fn do_work(thread_number: usize) {\n\n trace!(\"({}) Thread started working\", thread_number);\n\n trace!(\"ERROR_IF_PRINTED\");\n\n for idx in 0..NO_OF_LOGLINES_PER_THREAD {\n\n debug!(\"({}) writing out line number {}\", thread_number, idx);\n\n }\n\n trace!(\"MUST_BE_PRINTED\");\n\n}\n\n\n", "file_path": "tests/test_multi_threaded_dates.rs", "rank": 94, "score": 44317.63593493339 }, { "content": "#[bench]\n\nfn b10_no_logger_active(b: &mut Bencher) {\n\n b.iter(use_error);\n\n}\n\n\n", "file_path": "benches/bench_reconfigurable.rs", "rank": 95, "score": 44124.897604481586 }, { "content": "#[bench]\n\nfn b20_initialize_logger(_: &mut Bencher) {\n\n Logger::with_str(\"info\")\n\n .log_to_file()\n\n .directory(\"log_files\")\n\n .start()\n\n .unwrap_or_else(|e| panic!(\"Logger initialization failed with {}\", e));\n\n}\n\n\n", "file_path": "benches/bench_reconfigurable.rs", "rank": 96, "score": 44124.897604481586 }, { "content": "#[bench]\n\nfn b10_no_logger_active(b: &mut Bencher) {\n\n b.iter(use_error);\n\n}\n\n\n", "file_path": "benches/bench_standard.rs", "rank": 97, "score": 44124.897604481586 }, { "content": "#[bench]\n\nfn b40_suppressed_logs(b: &mut Bencher) {\n\n b.iter(use_trace);\n\n}\n\n\n", "file_path": "benches/bench_reconfigurable.rs", "rank": 98, "score": 44124.897604481586 }, { "content": "#[bench]\n\nfn b30_relevant_logs(b: &mut Bencher) {\n\n b.iter(use_error);\n\n}\n\n\n", "file_path": "benches/bench_reconfigurable.rs", "rank": 99, "score": 44124.897604481586 } ]
Rust
zircon-loader/src/lib.rs
Lincyaw/zCore
152733a670e5bec222349279de238e2f37bc4a97
#![no_std] #![feature(asm)] #![feature(global_asm)] #![deny(warnings, unused_must_use)] #[macro_use] extern crate alloc; #[macro_use] extern crate log; use { alloc::{boxed::Box, sync::Arc, vec::Vec}, kernel_hal::GeneralRegs, xmas_elf::ElfFile, zircon_object::{dev::*, ipc::*, object::*, task::*, util::elf_loader::*, vm::*}, zircon_syscall::Syscall, }; mod kcounter; const K_PROC_SELF: usize = 0; const K_VMARROOT_SELF: usize = 1; const K_ROOTJOB: usize = 2; const K_ROOTRESOURCE: usize = 3; const K_ZBI: usize = 4; const K_FIRSTVDSO: usize = 5; const K_CRASHLOG: usize = 8; const K_COUNTERNAMES: usize = 9; const K_COUNTERS: usize = 10; const K_FISTINSTRUMENTATIONDATA: usize = 11; const K_HANDLECOUNT: usize = 15; pub struct Images<T: AsRef<[u8]>> { pub userboot: T, pub vdso: T, pub zbi: T, } pub fn run_userboot(images: &Images<impl AsRef<[u8]>>, cmdline: &str) -> Arc<Process> { let job = Job::root(); let proc = Process::create(&job, "userboot", 0).unwrap(); let thread = Thread::create(&proc, "userboot", 0).unwrap(); let resource = Resource::create( "root", ResourceKind::ROOT, 0, 0x1_0000_0000, ResourceFlags::empty(), ); let vmar = proc.vmar(); let (entry, userboot_size) = { let elf = ElfFile::new(images.userboot.as_ref()).unwrap(); let size = elf.load_segment_size(); let vmar = vmar .allocate(None, size, VmarFlags::CAN_MAP_RXW, PAGE_SIZE) .unwrap(); vmar.load_from_elf(&elf).unwrap(); (vmar.addr() + elf.header.pt2.entry_point() as usize, size) }; let vdso_vmo = { let elf = ElfFile::new(images.vdso.as_ref()).unwrap(); let vdso_vmo = VmObject::new_paged(images.vdso.as_ref().len() / PAGE_SIZE + 1); vdso_vmo.write(0, images.vdso.as_ref()).unwrap(); let size = elf.load_segment_size(); let vmar = vmar .allocate_at( userboot_size, size, VmarFlags::CAN_MAP_RXW | VmarFlags::SPECIFIC, PAGE_SIZE, ) .unwrap(); vmar.map_from_elf(&elf, vdso_vmo.clone()).unwrap(); #[cfg(feature = "std")] { let offset = elf .get_symbol_address("zcore_syscall_entry") .expect("failed to locate syscall entry") as usize; let syscall_entry = &(kernel_hal_unix::syscall_entry as usize).to_ne_bytes(); vdso_vmo.write(offset, syscall_entry).unwrap(); vdso_vmo.write(offset + 8, syscall_entry).unwrap(); vdso_vmo.write(offset + 16, syscall_entry).unwrap(); } vdso_vmo }; let zbi_vmo = { let vmo = VmObject::new_paged(images.zbi.as_ref().len() / PAGE_SIZE + 1); vmo.write(0, images.zbi.as_ref()).unwrap(); vmo.set_name("zbi"); vmo }; const STACK_PAGES: usize = 8; let stack_vmo = VmObject::new_paged(STACK_PAGES); let flags = MMUFlags::READ | MMUFlags::WRITE | MMUFlags::USER; let stack_bottom = vmar .map(None, stack_vmo.clone(), 0, stack_vmo.len(), flags) .unwrap(); #[cfg(target_arch = "x86_64")] let sp = stack_bottom + stack_vmo.len() - 8; #[cfg(target_arch = "aarch64")] let sp = stack_bottom + stack_vmo.len(); let (user_channel, kernel_channel) = Channel::create(); let handle = Handle::new(user_channel, Rights::DEFAULT_CHANNEL); let mut handles = vec![Handle::new(proc.clone(), Rights::empty()); K_HANDLECOUNT]; handles[K_PROC_SELF] = Handle::new(proc.clone(), Rights::DEFAULT_PROCESS); handles[K_VMARROOT_SELF] = Handle::new(proc.vmar(), Rights::DEFAULT_VMAR | Rights::IO); handles[K_ROOTJOB] = Handle::new(job, Rights::DEFAULT_JOB); handles[K_ROOTRESOURCE] = Handle::new(resource, Rights::DEFAULT_RESOURCE); handles[K_ZBI] = Handle::new(zbi_vmo, Rights::DEFAULT_VMO); const VDSO_DATA_CONSTANTS: usize = 0x4a50; const VDSO_DATA_CONSTANTS_SIZE: usize = 0x78; let constants: [u8; VDSO_DATA_CONSTANTS_SIZE] = unsafe { core::mem::transmute(kernel_hal::vdso_constants()) }; vdso_vmo.write(VDSO_DATA_CONSTANTS, &constants).unwrap(); vdso_vmo.set_name("vdso/full"); let vdso_test1 = vdso_vmo.create_child(false, 0, vdso_vmo.len()).unwrap(); vdso_test1.set_name("vdso/test1"); let vdso_test2 = vdso_vmo.create_child(false, 0, vdso_vmo.len()).unwrap(); vdso_test2.set_name("vdso/test2"); handles[K_FIRSTVDSO] = Handle::new(vdso_vmo, Rights::DEFAULT_VMO | Rights::EXECUTE); handles[K_FIRSTVDSO + 1] = Handle::new(vdso_test1, Rights::DEFAULT_VMO | Rights::EXECUTE); handles[K_FIRSTVDSO + 2] = Handle::new(vdso_test2, Rights::DEFAULT_VMO | Rights::EXECUTE); let crash_log_vmo = VmObject::new_paged(1); crash_log_vmo.set_name("crashlog"); handles[K_CRASHLOG] = Handle::new(crash_log_vmo, Rights::DEFAULT_VMO); let (counter_name_vmo, kcounters_vmo) = kcounter::create_kcounter_vmo(); handles[K_COUNTERNAMES] = Handle::new(counter_name_vmo, Rights::DEFAULT_VMO); handles[K_COUNTERS] = Handle::new(kcounters_vmo, Rights::DEFAULT_VMO); let instrumentation_data_vmo = VmObject::new_paged(0); instrumentation_data_vmo.set_name("UNIMPLEMENTED_VMO"); handles[K_FISTINSTRUMENTATIONDATA] = Handle::new(instrumentation_data_vmo.clone(), Rights::DEFAULT_VMO); handles[K_FISTINSTRUMENTATIONDATA + 1] = Handle::new(instrumentation_data_vmo.clone(), Rights::DEFAULT_VMO); handles[K_FISTINSTRUMENTATIONDATA + 2] = Handle::new(instrumentation_data_vmo.clone(), Rights::DEFAULT_VMO); handles[K_FISTINSTRUMENTATIONDATA + 3] = Handle::new(instrumentation_data_vmo, Rights::DEFAULT_VMO); let data = Vec::from(cmdline.replace(':', "\0") + "\0"); let msg = MessagePacket { data, handles }; kernel_channel.write(msg).unwrap(); proc.start(&thread, entry, sp, Some(handle), 0, spawn) .expect("failed to start main thread"); proc } kcounter!(EXCEPTIONS_USER, "exceptions.user"); kcounter!(EXCEPTIONS_TIMER, "exceptions.timer"); kcounter!(EXCEPTIONS_PGFAULT, "exceptions.pgfault"); fn spawn(thread: Arc<Thread>) { let vmtoken = thread.proc().vmar().table_phys(); let future = async move { kernel_hal::Thread::set_tid(thread.id(), thread.proc().id()); let mut exit = false; if thread.get_first_thread() { let proc_start_exception = Exception::create(thread.clone(), ExceptionType::ProcessStarting, None); if !proc_start_exception .handle_with_exceptionates( false, JobDebuggerIterator::new(thread.proc().job()), true, ) .await { exit = true; } }; let start_exception = Exception::create(thread.clone(), ExceptionType::ThreadStarting, None); if !start_exception .handle_with_exceptionates(false, Some(thread.proc().get_debug_exceptionate()), false) .await { exit = true; } while !exit { let mut cx = thread.wait_for_run().await; if thread.state() == ThreadState::Dying { info!( "proc={:?} thread={:?} was killed", thread.proc().name(), thread.name() ); break; } trace!("go to user: {:#x?}", cx); debug!("switch to {}|{}", thread.proc().name(), thread.name()); let tmp_time = kernel_hal::timer_now().as_nanos(); kernel_hal::context_run(&mut cx); let time = kernel_hal::timer_now().as_nanos() - tmp_time; thread.time_add(time); trace!("back from user: {:#x?}", cx); EXCEPTIONS_USER.add(1); #[cfg(target_arch = "aarch64")] match cx.trap_num { 0 => exit = handle_syscall(&thread, &mut cx.general).await, _ => unimplemented!(), } #[cfg(target_arch = "x86_64")] match cx.trap_num { 0x100 => exit = handle_syscall(&thread, &mut cx.general).await, 0x20..=0x3f => { kernel_hal::InterruptManager::handle(cx.trap_num as u8); if cx.trap_num == 0x20 { EXCEPTIONS_TIMER.add(1); kernel_hal::yield_now().await; } } 0xe => { EXCEPTIONS_PGFAULT.add(1); #[cfg(target_arch = "x86_64")] let flags = if cx.error_code & 0x2 == 0 { MMUFlags::READ } else { MMUFlags::WRITE }; #[cfg(target_arch = "aarch64")] let flags = MMUFlags::WRITE; error!( "page fualt from user mode {:#x} {:#x?}", kernel_hal::fetch_fault_vaddr(), flags ); match thread .proc() .vmar() .handle_page_fault(kernel_hal::fetch_fault_vaddr(), flags) { Ok(()) => {} Err(e) => { error!( "proc={:?} thread={:?} err={:?}", thread.proc().name(), thread.name(), e ); error!("Page Fault from user mode {:#x?}", cx); let exception = Exception::create( thread.clone(), ExceptionType::FatalPageFault, Some(&cx), ); if !exception.handle(true).await { exit = true; } } } } 0x8 => { panic!("Double fault from user mode! {:#x?}", cx); } num => { let type_ = match num { 0x1 => ExceptionType::HardwareBreakpoint, 0x3 => ExceptionType::SoftwareBreakpoint, 0x6 => ExceptionType::UndefinedInstruction, 0x17 => ExceptionType::UnalignedAccess, _ => ExceptionType::General, }; error!("User mode exception:{:?} {:#x?}", type_, cx); let exception = Exception::create(thread.clone(), type_, Some(&cx)); if !exception.handle(true).await { exit = true; } } } thread.end_running(cx); if exit { info!( "proc={:?} thread={:?} exited", thread.proc().name(), thread.name() ); break; } } let end_exception = Exception::create(thread.clone(), ExceptionType::ThreadExiting, None); let handled = thread .proc() .get_debug_exceptionate() .send_exception(&end_exception); if let Ok(future) = handled { thread.dying_run(future).await.ok(); } else { handled.ok(); } thread.terminate(); }; kernel_hal::Thread::spawn(Box::pin(future), vmtoken); } async fn handle_syscall(thread: &Arc<Thread>, regs: &mut GeneralRegs) -> bool { #[cfg(target_arch = "x86_64")] let num = regs.rax as u32; #[cfg(target_arch = "aarch64")] let num = regs.x16 as u32; #[cfg(feature = "std")] #[cfg(target_arch = "x86_64")] let args = unsafe { let a6 = (regs.rsp as *const usize).read(); let a7 = (regs.rsp as *const usize).add(1).read(); [ regs.rdi, regs.rsi, regs.rdx, regs.rcx, regs.r8, regs.r9, a6, a7, ] }; #[cfg(not(feature = "std"))] #[cfg(target_arch = "x86_64")] let args = [ regs.rdi, regs.rsi, regs.rdx, regs.r10, regs.r8, regs.r9, regs.r12, regs.r13, ]; #[cfg(target_arch = "aarch64")] let args = [ regs.x0, regs.x1, regs.x2, regs.x3, regs.x4, regs.x5, regs.x6, regs.x7, ]; let mut syscall = Syscall { regs, thread: thread.clone(), spawn_fn: spawn, exit: false, }; let ret = syscall.syscall(num, args).await as usize; #[cfg(target_arch = "x86_64")] { syscall.regs.rax = ret; } #[cfg(target_arch = "aarch64")] { syscall.regs.x0 = ret; } syscall.exit }
#![no_std] #![feature(asm)] #![feature(global_asm)] #![deny(warnings, unused_must_use)] #[macro_use] extern crate alloc; #[macro_use] extern crate log; use { alloc::{boxed::Box, sync::Arc, vec::Vec}, kernel_hal::GeneralRegs, xmas_elf::ElfFile, zircon_object::{dev::*, ipc::*, object::*, task::*, util::elf_loader::*, vm::*}, zircon_syscall::Syscall, }; mod kcounter; const K_PROC_SELF: usize = 0; const K_VMARROOT_SELF: usize = 1; const K_ROOTJOB: usize = 2; const K_ROOTRESOURCE: usize = 3; const K_ZBI: usize = 4; const K_FIRSTVDSO: usize = 5; const K_CRASHLOG: usize = 8; const K_COUNTERNAMES: usize = 9; const K_COUNTERS: usize = 10; const K_FISTINSTRUMENTATIONDATA: usize = 11; const K_HANDLECOUNT: usize = 15; pub struct Images<T: AsRef<[u8]>> { pub userboot: T, pub vdso: T, pub zbi: T, } pub fn run_userboot(images: &Images<impl AsRef<[u8]>>, cmdline: &str) -> Arc<Process> { let job = Job::root(); let proc = Process::create(&job, "userboot", 0).unwrap(); let thread = Thread::create(&proc, "userboot", 0).unwrap(); let resource = Resource::create( "root", ResourceKind::ROOT, 0, 0x1_0000_0000, ResourceFlags::empty(), ); let vmar = proc.vmar(); let (entry, userboot_size) = { let elf = ElfFile::new(images.userboot.as_ref()).unwrap(); let size = elf.load_segment_size(); let vmar = vmar .allocate(None, size, VmarFlags::CAN_MAP_RXW, PAGE_SIZE) .unwrap(); vmar.load_from_elf(&elf).unwrap(); (vmar.addr() + elf.header.pt2.entry_point() as usize, size) }; let vdso_vmo = { let elf = ElfFile::new(images.vdso.as_ref()).unwrap(); let vdso_vmo = VmObject::new_paged(images.vdso.as_ref().len() / PAGE_SIZE + 1); vdso_vmo.write(0, images.vdso.as_ref()).unwrap(); let size = elf.load_segment_size(); let vmar = vmar .allocate_at( userboot_size, size, VmarFlags::CAN_MAP_RXW | VmarFlags::SPECIFIC, PAGE_SIZE, ) .unwrap(); vmar.map_from_elf(&elf, vdso_vmo.clone()).unwrap(); #[cfg(feature = "std")] { let offset = elf .get_symbol_address("zcore_syscall_entry") .expect("failed to locate syscall entry") as usize; let syscall_entry = &(kernel_hal_unix::syscall_entry as usize).to_ne_bytes(); vdso_vmo.write(offset, syscall_entry).unwrap(); vdso_vmo.write(offset + 8, syscall_entry).unwrap(); vdso_vmo.write(offset + 16, syscall_entry).unwrap(); } vdso_vmo }; let zbi_vmo = { let vmo = VmObject::new_paged(images.zbi.as_ref().len() / PAGE_SIZE + 1); vmo.write(0, images.zbi.as_ref()).unwrap(); vmo.set_name("zbi"); vmo }; const STACK_PAGES: usize = 8; let stack_vmo = VmObject::new_paged(STACK_PAGES); let flags = MMUFlags::READ | MMUFlags::WRITE | MMUFlags::USER; let stack_bottom = vmar .map(None, stack_vmo.clone(), 0, stack_vmo.len(), flags) .unwrap(); #[cfg(target_arch = "x86_64")] let sp = stack_bottom + stack_vmo.len() - 8; #[cfg(target_arch = "aarch64")] let sp = stack_bottom + stack_vmo.len(); let (user_channel, kernel_channel) = Channel::create(); let handle = Handle::new(user_channel, Rights::DEFAULT_CHANNEL); let mut handles = vec![Handle::new(proc.clone(), Rights::empty()); K_HANDLECOUNT]; handles[K_PROC_SELF] = Handle::new(proc.clone(), Rights::DEFAULT_PROCESS); handles[K_VMARROOT_SELF] = Handle::new(proc.vmar(), Rights::DEFAULT_VMAR | Rights::IO); handles[K_ROOTJOB] = Handle::new(job, Rights::DEFAULT_JOB); handles[K_ROOTRESOURCE] = Handle::new(resource, Rights::DEFAULT_RESOURCE); handles[K_ZBI] = Handle::new(zbi_vmo, Rights::DEFAULT_VMO); const VDSO_DATA_CONSTANTS: usize = 0x4a50; const VDSO_DATA_CONSTANTS_SIZE: usize = 0x78; let constants: [u8; VDSO_DATA_CONSTANTS_SIZE] = unsafe { core::mem::transmute(kernel_hal::vdso_constants()) }; vdso_vmo.write(VDSO_DATA_CONSTANTS, &constants).unwrap(); vdso_vmo.set_name("vdso/full"); let vdso_test1 = vdso_vmo.create_child(false, 0, vdso_vmo.len()).unwrap(); vdso_test1.set_name("vdso/test1"); let vdso_test2 = vdso_vmo.create_child(false, 0, vdso_vmo.len()).unwrap(); vdso_test2.set_name("vdso/test2"); handles[K_FIRSTVDSO] = Handle::new(vdso_vmo, Rights::DEFAULT_VMO | Rights::EXECUTE); handles[K_FIRSTVDSO + 1] = Handle::new(vdso_test1, Rights::DEFAULT_VMO | Rights::EXECUTE); handles[K_FIRSTVDSO + 2] = Handle::new(vdso_test2, Rights::DEFAULT_VMO | Rights::EXECUTE); let crash_log_vmo = VmObject::new_paged(1); crash_log_vmo.set_name("crashlog"); handles[K_CRASHLOG] = Handle::new(crash_log_vmo, Rights::DEFAULT_VMO); let (counter_name_vmo, kcounters_vmo) = kcounter::create_kcounter_vmo(); handles[K_COUNTERNAMES] = Handle::new(counter_name_vmo, Rights::DEFAULT_VMO); handles[K_COUNTERS] = Handle::new(kcounters_vmo, Rights::DEFAULT_VMO); let instrumentation_data_vmo = VmObject::new_paged(0); instrumentation_data_vmo.set_name("UNIMPLEMENTED_VMO"); handles[K_FISTINSTRUMENTATIONDATA] = Handle::new(instrumentation_data_vmo.clone(), Rights::DEFAULT_VMO); handles[K_FISTINSTRUMENTATIONDATA + 1] = Handle::new(instrumentation_data_vmo.clone(), Rights::DEFAULT_VMO); handles[K_FISTINSTRUMENTATIONDATA + 2] = Handle::new(instrumentation_data_vmo.clone(), Rights::DEFAULT_VMO); handles[K_FISTINSTRUMENTATIONDATA + 3] = Handle::new(instrumentation_data_vmo, Rights::DEFAULT_VMO); let data = Vec::from(cmdline.replace(':', "\0") + "\0"); let msg = MessagePacket { data, handles }; kernel_channel.write(msg).unwrap(); proc.start(&thread, entry, sp, Some(handle), 0, spawn) .expect("failed to start main thread"); proc } kcounter!(EXCEPTIONS_USER, "exceptions.user"); kcounter!(EXCEPTIONS_TIMER, "exceptions.timer"); kcounter!(EXCEPTIONS_PGFAULT, "exceptions.pgfault"); fn spawn(thread: Arc<Thread>) { let vmtoken = thread.proc().vmar().table_phys(); let future = async move { kernel_hal::Thread::set_tid(thread.id(), thread.proc().id()); let mut exit = false; if thread.get_first_thread() { let proc_start_exception = Exception::create(thread.clone(), ExceptionType::ProcessStarting, None); if !proc_start_exception .handle_with_exceptionates( false, JobDebuggerIterator::new(thread.proc().job()), true, ) .await { exit = true; } }; let start_exception = Exception::create(thread.clone(), ExceptionType::ThreadStarting, None); if !start_exception .handle_with_exceptionates(false, Some(thread.proc().get_debug_exceptionate()), false) .await { exit = true; } while !exit { let mut cx = thread.wait_for_run().await; if thread.state() == ThreadState::Dying { info!( "proc={:?} thread={:?} was killed", thread.proc().name(), thread.name() ); break; } trace!("go to user: {:#x?}", cx); debug!("switch to {}|{}", thread.proc().name(), thread.name()); let tmp_time = kernel_hal::timer_now().as_nanos(); kernel_hal::context_run
flags ); match thread .proc() .vmar() .handle_page_fault(kernel_hal::fetch_fault_vaddr(), flags) { Ok(()) => {} Err(e) => { error!( "proc={:?} thread={:?} err={:?}", thread.proc().name(), thread.name(), e ); error!("Page Fault from user mode {:#x?}", cx); let exception = Exception::create( thread.clone(), ExceptionType::FatalPageFault, Some(&cx), ); if !exception.handle(true).await { exit = true; } } } } 0x8 => { panic!("Double fault from user mode! {:#x?}", cx); } num => { let type_ = match num { 0x1 => ExceptionType::HardwareBreakpoint, 0x3 => ExceptionType::SoftwareBreakpoint, 0x6 => ExceptionType::UndefinedInstruction, 0x17 => ExceptionType::UnalignedAccess, _ => ExceptionType::General, }; error!("User mode exception:{:?} {:#x?}", type_, cx); let exception = Exception::create(thread.clone(), type_, Some(&cx)); if !exception.handle(true).await { exit = true; } } } thread.end_running(cx); if exit { info!( "proc={:?} thread={:?} exited", thread.proc().name(), thread.name() ); break; } } let end_exception = Exception::create(thread.clone(), ExceptionType::ThreadExiting, None); let handled = thread .proc() .get_debug_exceptionate() .send_exception(&end_exception); if let Ok(future) = handled { thread.dying_run(future).await.ok(); } else { handled.ok(); } thread.terminate(); }; kernel_hal::Thread::spawn(Box::pin(future), vmtoken); } async fn handle_syscall(thread: &Arc<Thread>, regs: &mut GeneralRegs) -> bool { #[cfg(target_arch = "x86_64")] let num = regs.rax as u32; #[cfg(target_arch = "aarch64")] let num = regs.x16 as u32; #[cfg(feature = "std")] #[cfg(target_arch = "x86_64")] let args = unsafe { let a6 = (regs.rsp as *const usize).read(); let a7 = (regs.rsp as *const usize).add(1).read(); [ regs.rdi, regs.rsi, regs.rdx, regs.rcx, regs.r8, regs.r9, a6, a7, ] }; #[cfg(not(feature = "std"))] #[cfg(target_arch = "x86_64")] let args = [ regs.rdi, regs.rsi, regs.rdx, regs.r10, regs.r8, regs.r9, regs.r12, regs.r13, ]; #[cfg(target_arch = "aarch64")] let args = [ regs.x0, regs.x1, regs.x2, regs.x3, regs.x4, regs.x5, regs.x6, regs.x7, ]; let mut syscall = Syscall { regs, thread: thread.clone(), spawn_fn: spawn, exit: false, }; let ret = syscall.syscall(num, args).await as usize; #[cfg(target_arch = "x86_64")] { syscall.regs.rax = ret; } #[cfg(target_arch = "aarch64")] { syscall.regs.x0 = ret; } syscall.exit }
(&mut cx); let time = kernel_hal::timer_now().as_nanos() - tmp_time; thread.time_add(time); trace!("back from user: {:#x?}", cx); EXCEPTIONS_USER.add(1); #[cfg(target_arch = "aarch64")] match cx.trap_num { 0 => exit = handle_syscall(&thread, &mut cx.general).await, _ => unimplemented!(), } #[cfg(target_arch = "x86_64")] match cx.trap_num { 0x100 => exit = handle_syscall(&thread, &mut cx.general).await, 0x20..=0x3f => { kernel_hal::InterruptManager::handle(cx.trap_num as u8); if cx.trap_num == 0x20 { EXCEPTIONS_TIMER.add(1); kernel_hal::yield_now().await; } } 0xe => { EXCEPTIONS_PGFAULT.add(1); #[cfg(target_arch = "x86_64")] let flags = if cx.error_code & 0x2 == 0 { MMUFlags::READ } else { MMUFlags::WRITE }; #[cfg(target_arch = "aarch64")] let flags = MMUFlags::WRITE; error!( "page fualt from user mode {:#x} {:#x?}", kernel_hal::fetch_fault_vaddr(),
function_block-random_span
[]
Rust
src/cargo/sources/registry/local.rs
quark-zju/cargo
62180bf27d83e1d8785b32bbe4d6f6fb07fff4bc
use crate::core::{InternedString, PackageId}; use crate::sources::registry::{MaybeLock, RegistryConfig, RegistryData}; use crate::util::errors::CargoResult; use crate::util::paths; use crate::util::{Config, Filesystem, Sha256}; use std::fs::File; use std::io::prelude::*; use std::io::SeekFrom; use std::path::Path; pub struct LocalRegistry<'cfg> { index_path: Filesystem, root: Filesystem, src_path: Filesystem, config: &'cfg Config, } impl<'cfg> LocalRegistry<'cfg> { pub fn new(root: &Path, config: &'cfg Config, name: &str) -> LocalRegistry<'cfg> { LocalRegistry { src_path: config.registry_source_path().join(name), index_path: Filesystem::new(root.join("index")), root: Filesystem::new(root.to_path_buf()), config, } } } impl<'cfg> RegistryData for LocalRegistry<'cfg> { fn prepare(&self) -> CargoResult<()> { Ok(()) } fn index_path(&self) -> &Filesystem { &self.index_path } fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path { path.as_path_unlocked() } fn current_version(&self) -> Option<InternedString> { None } fn load( &self, root: &Path, path: &Path, data: &mut dyn FnMut(&[u8]) -> CargoResult<()>, ) -> CargoResult<()> { data(&paths::read_bytes(&root.join(path))?) } fn config(&mut self) -> CargoResult<Option<RegistryConfig>> { Ok(None) } fn update_index(&mut self) -> CargoResult<()> { let root = self.root.clone().into_path_unlocked(); if !root.is_dir() { anyhow::bail!("local registry path is not a directory: {}", root.display()) } let index_path = self.index_path.clone().into_path_unlocked(); if !index_path.is_dir() { anyhow::bail!( "local registry index path is not a directory: {}", index_path.display() ) } Ok(()) } fn download(&mut self, pkg: PackageId, checksum: &str) -> CargoResult<MaybeLock> { let crate_file = format!("{}-{}.crate", pkg.name(), pkg.version()); let path = self.root.join(&crate_file).into_path_unlocked(); let mut crate_file = File::open(&path)?; let dst = format!("{}-{}", pkg.name(), pkg.version()); if self.src_path.join(dst).into_path_unlocked().exists() { return Ok(MaybeLock::Ready(crate_file)); } self.config.shell().status("Unpacking", pkg)?; let actual = Sha256::new().update_file(&crate_file)?.finish_hex(); if actual != checksum { anyhow::bail!("failed to verify the checksum of `{}`", pkg) } crate_file.seek(SeekFrom::Start(0))?; Ok(MaybeLock::Ready(crate_file)) } fn finish_download( &mut self, _pkg: PackageId, _checksum: &str, _data: &[u8], ) -> CargoResult<File> { panic!("this source doesn't download") } }
use crate::core::{InternedString, PackageId}; use crate::sources::registry::{MaybeLock, RegistryConfig, RegistryData}; use crate::util::errors::CargoResult; use crate::util::paths; use crate::util::{Config, Filesystem, Sha256}; use std::fs::File; use std::io::prelude::*; use std::io::SeekFrom; use std::path::Path; pub struct LocalRegistry<'cfg> { index_path: Filesystem, root: Filesystem, src_path: Filesystem, config: &'cfg Config, } impl<'cfg> LocalRegistry<'cfg> { pub fn new(root: &Path, config: &'cfg Config, name: &str) -> LocalRegistry<'cfg> { LocalRegistry { src_path: config.registry_source_path().join(name), index_path: Filesystem::new(root.join("index")), root: Filesystem::new(root.to_path_buf()), config, } } } impl<'cfg> RegistryData for LocalRegistry<'cfg> { fn prepare(&self) -> CargoResult<()> { Ok(()) } fn index_path(&self) -> &Filesystem { &self.index_path } fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path { path.as_path_unlocked() } fn current_version(&self) -> Option<InternedString> { None } fn load( &self, root: &Path, path: &Path, data: &mut dyn FnMut(&[u8]) -> CargoResult<()>, ) -> CargoResult<()> { data(&paths::read_bytes(&root.join(path))?) } fn config(&mut self) -> CargoResult<Option<RegistryConfig>> { Ok(None) }
fn download(&mut self, pkg: PackageId, checksum: &str) -> CargoResult<MaybeLock> { let crate_file = format!("{}-{}.crate", pkg.name(), pkg.version()); let path = self.root.join(&crate_file).into_path_unlocked(); let mut crate_file = File::open(&path)?; let dst = format!("{}-{}", pkg.name(), pkg.version()); if self.src_path.join(dst).into_path_unlocked().exists() { return Ok(MaybeLock::Ready(crate_file)); } self.config.shell().status("Unpacking", pkg)?; let actual = Sha256::new().update_file(&crate_file)?.finish_hex(); if actual != checksum { anyhow::bail!("failed to verify the checksum of `{}`", pkg) } crate_file.seek(SeekFrom::Start(0))?; Ok(MaybeLock::Ready(crate_file)) } fn finish_download( &mut self, _pkg: PackageId, _checksum: &str, _data: &[u8], ) -> CargoResult<File> { panic!("this source doesn't download") } }
fn update_index(&mut self) -> CargoResult<()> { let root = self.root.clone().into_path_unlocked(); if !root.is_dir() { anyhow::bail!("local registry path is not a directory: {}", root.display()) } let index_path = self.index_path.clone().into_path_unlocked(); if !index_path.is_dir() { anyhow::bail!( "local registry index path is not a directory: {}", index_path.display() ) } Ok(()) }
function_block-full_function
[ { "content": "/// Determines the root directory where installation is done.\n\npub fn resolve_root(flag: Option<&str>, config: &Config) -> CargoResult<Filesystem> {\n\n let config_root = config.get_path(\"install.root\")?;\n\n Ok(flag\n\n .map(PathBuf::from)\n\n .or_else(|| env::var_os(\"CARGO_INSTALL_ROOT\").map(PathBuf::from))\n\n .or_else(move || config_root.map(|v| v.val))\n\n .map(Filesystem::new)\n\n .unwrap_or_else(|| config.home().clone()))\n\n}\n\n\n", "file_path": "src/cargo/ops/common_for_install_and_uninstall.rs", "rank": 0, "score": 374424.7481196213 }, { "content": "pub fn write_config_at(path: impl AsRef<Path>, contents: &str) {\n\n let path = paths::root().join(path.as_ref());\n\n fs::create_dir_all(path.parent().unwrap()).unwrap();\n\n fs::write(path, contents).unwrap();\n\n}\n\n\n", "file_path": "tests/testsuite/config.rs", "rank": 1, "score": 337394.3088373097 }, { "content": "pub fn write_config(config: &str) {\n\n write_config_at(paths::root().join(\".cargo/config\"), config);\n\n}\n\n\n", "file_path": "tests/testsuite/config.rs", "rank": 2, "score": 328150.93885104894 }, { "content": "pub fn generate_path(name: &str) -> PathBuf {\n\n paths::root().join(name)\n\n}\n", "file_path": "crates/cargo-test-support/src/registry.rs", "rank": 3, "score": 326820.0305827412 }, { "content": "pub fn parse(toml: &str, file: &Path, config: &Config) -> CargoResult<toml::Value> {\n\n let first_error = match toml.parse() {\n\n Ok(ret) => return Ok(ret),\n\n Err(e) => e,\n\n };\n\n\n\n let mut second_parser = toml::de::Deserializer::new(toml);\n\n second_parser.set_require_newline_after_table(false);\n\n if let Ok(ret) = toml::Value::deserialize(&mut second_parser) {\n\n let msg = format!(\n\n \"\\\n\nTOML file found which contains invalid syntax and will soon not parse\n\nat `{}`.\n\n\n\nThe TOML spec requires newlines after table definitions (e.g., `[a] b = 1` is\n\ninvalid), but this file has a table header which does not have a newline after\n\nit. A newline needs to be added and this warning will soon become a hard error\n\nin the future.\",\n\n file.display()\n\n );\n", "file_path": "src/cargo/util/toml/mod.rs", "rank": 4, "score": 322844.88918834797 }, { "content": "/// Check the base requirements for a package name.\n\n///\n\n/// This can be used for other things than package names, to enforce some\n\n/// level of sanity. Note that package names have other restrictions\n\n/// elsewhere. `cargo new` has a few restrictions, such as checking for\n\n/// reserved names. crates.io has even more restrictions.\n\npub fn validate_package_name(name: &str, what: &str, help: &str) -> CargoResult<()> {\n\n if let Some(ch) = name\n\n .chars()\n\n .find(|ch| !ch.is_alphanumeric() && *ch != '_' && *ch != '-')\n\n {\n\n anyhow::bail!(\"Invalid character `{}` in {}: `{}`{}\", ch, what, name, help);\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/cargo/util/mod.rs", "rank": 5, "score": 317565.37555191055 }, { "content": "fn walk(path: &Path, callback: &mut dyn FnMut(&Path) -> CargoResult<bool>) -> CargoResult<()> {\n\n if !callback(path)? {\n\n trace!(\"not processing {}\", path.display());\n\n return Ok(());\n\n }\n\n\n\n // Ignore any permission denied errors because temporary directories\n\n // can often have some weird permissions on them.\n\n let dirs = match fs::read_dir(path) {\n\n Ok(dirs) => dirs,\n\n Err(ref e) if e.kind() == io::ErrorKind::PermissionDenied => return Ok(()),\n\n Err(e) => {\n\n let cx = format!(\"failed to read directory `{}`\", path.display());\n\n let e = anyhow::Error::from(e);\n\n return Err(e.context(cx).into());\n\n }\n\n };\n\n for dir in dirs {\n\n let dir = dir?;\n\n if dir.file_type()?.is_dir() {\n\n walk(&dir.path(), callback)?;\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/cargo/ops/cargo_read_manifest.rs", "rank": 6, "score": 314831.0478967155 }, { "content": "/// Get the filename for a library.\n\n///\n\n/// `kind` should be one of: \"lib\", \"rlib\", \"staticlib\", \"dylib\", \"proc-macro\"\n\n///\n\n/// For example, dynamic library named \"foo\" would return:\n\n/// - macOS: \"libfoo.dylib\"\n\n/// - Windows: \"foo.dll\"\n\n/// - Unix: \"libfoo.so\"\n\npub fn get_lib_filename(name: &str, kind: &str) -> String {\n\n let prefix = get_lib_prefix(kind);\n\n let extension = get_lib_extension(kind);\n\n format!(\"{}{}.{}\", prefix, name, extension)\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/paths.rs", "rank": 7, "score": 313800.85655490856 }, { "content": "pub fn pkg_id(name: &str) -> PackageId {\n\n PackageId::new(name, \"1.0.0\", registry_loc()).unwrap()\n\n}\n\n\n", "file_path": "crates/resolver-tests/src/lib.rs", "rank": 8, "score": 307090.6545622115 }, { "content": "/// Used by `cargo install` tests to assert an executable binary\n\n/// has been installed. Example usage:\n\n///\n\n/// assert_has_installed_exe(cargo_home(), \"foo\");\n\npub fn assert_has_installed_exe<P: AsRef<Path>>(path: P, name: &'static str) {\n\n assert!(check_has_installed_exe(path, name));\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/install.rs", "rank": 9, "score": 304135.3393279123 }, { "content": "pub fn assert_has_not_installed_exe<P: AsRef<Path>>(path: P, name: &'static str) {\n\n assert!(!check_has_installed_exe(path, name));\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/install.rs", "rank": 10, "score": 304130.2422293424 }, { "content": "fn uninstall_cwd(root: &Filesystem, bins: &[String], config: &Config) -> CargoResult<()> {\n\n let tracker = InstallTracker::load(config, root)?;\n\n let source_id = SourceId::for_path(config.cwd())?;\n\n let src = path_source(source_id, config)?;\n\n let pkg = select_pkg(src, None, None, config, true, &mut |path| {\n\n path.read_packages()\n\n })?;\n\n let pkgid = pkg.package_id();\n\n uninstall_pkgid(root, tracker, pkgid, bins, config)\n\n}\n\n\n", "file_path": "src/cargo/ops/cargo_uninstall.rs", "rank": 11, "score": 294258.4875443042 }, { "content": "/// Display a list of installed binaries.\n\npub fn install_list(dst: Option<&str>, config: &Config) -> CargoResult<()> {\n\n let root = resolve_root(dst, config)?;\n\n let tracker = InstallTracker::load(config, &root)?;\n\n for (k, v) in tracker.all_installed_bins() {\n\n println!(\"{}:\", k);\n\n for bin in v {\n\n println!(\" {}\", bin);\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/cargo/ops/cargo_install.rs", "rank": 12, "score": 293578.2165167818 }, { "content": "pub fn is_bad_artifact_name(name: &str) -> bool {\n\n [\"deps\", \"examples\", \"build\", \"incremental\"]\n\n .iter()\n\n .any(|&reserved| reserved == name)\n\n}\n\n\n\nimpl Layout {\n\n /// Calculate the paths for build output, lock the build directory, and return as a Layout.\n\n ///\n\n /// This function will block if the directory is already locked.\n\n ///\n\n /// `dest` should be the final artifact directory name. Currently either\n\n /// \"debug\" or \"release\".\n\n pub fn new(\n\n ws: &Workspace<'_>,\n\n target: Option<CompileTarget>,\n\n dest: &str,\n\n ) -> CargoResult<Layout> {\n\n let mut root = ws.target_dir();\n\n if let Some(target) = target {\n", "file_path": "src/cargo/core/compiler/layout.rs", "rank": 13, "score": 291312.1521691724 }, { "content": "pub fn root() -> PathBuf {\n\n let id = TEST_ID.with(|n| {\n\n n.borrow().expect(\n\n \"Tests must use the `#[cargo_test]` attribute in \\\n\n order to be able to use the crate root.\",\n\n )\n\n });\n\n GLOBAL_ROOT.join(&format!(\"t{}\", id))\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/paths.rs", "rank": 14, "score": 286341.18267030787 }, { "content": "pub fn dep(name: &str) -> Dependency {\n\n dep_req(name, \"*\")\n\n}\n", "file_path": "crates/resolver-tests/src/lib.rs", "rank": 15, "score": 286021.9937346485 }, { "content": "pub fn dep_loc(name: &str, location: &str) -> Dependency {\n\n let url = location.into_url().unwrap();\n\n let master = GitReference::Branch(\"master\".to_string());\n\n let source_id = SourceId::for_git(&url, master).unwrap();\n\n Dependency::parse_no_deprecated(name, Some(\"1.0.0\"), source_id).unwrap()\n\n}\n", "file_path": "crates/resolver-tests/src/lib.rs", "rank": 16, "score": 284032.4164878652 }, { "content": "pub fn dep_req(name: &str, req: &str) -> Dependency {\n\n Dependency::parse_no_deprecated(name, Some(req), registry_loc()).unwrap()\n\n}\n", "file_path": "crates/resolver-tests/src/lib.rs", "rank": 17, "score": 284032.4164878652 }, { "content": "pub fn pkg_loc(name: &str, loc: &str) -> Summary {\n\n let link = if name.ends_with(\"-sys\") {\n\n Some(name)\n\n } else {\n\n None\n\n };\n\n Summary::new(\n\n pkg_id_loc(name, loc),\n\n Vec::new(),\n\n &BTreeMap::<String, Vec<String>>::new(),\n\n link,\n\n false,\n\n )\n\n .unwrap()\n\n}\n\n\n", "file_path": "crates/resolver-tests/src/lib.rs", "rank": 18, "score": 284032.4164878652 }, { "content": "pub fn exe(name: &str) -> String {\n\n format!(\"{}{}\", name, EXE_SUFFIX)\n\n}\n", "file_path": "crates/cargo-test-support/src/install.rs", "rank": 19, "score": 281044.89143948344 }, { "content": "/// Prepare the authentication callbacks for cloning a git repository.\n\n///\n\n/// The main purpose of this function is to construct the \"authentication\n\n/// callback\" which is used to clone a repository. This callback will attempt to\n\n/// find the right authentication on the system (without user input) and will\n\n/// guide libgit2 in doing so.\n\n///\n\n/// The callback is provided `allowed` types of credentials, and we try to do as\n\n/// much as possible based on that:\n\n///\n\n/// * Prioritize SSH keys from the local ssh agent as they're likely the most\n\n/// reliable. The username here is prioritized from the credential\n\n/// callback, then from whatever is configured in git itself, and finally\n\n/// we fall back to the generic user of `git`.\n\n///\n\n/// * If a username/password is allowed, then we fallback to git2-rs's\n\n/// implementation of the credential helper. This is what is configured\n\n/// with `credential.helper` in git, and is the interface for the macOS\n\n/// keychain, for example.\n\n///\n\n/// * After the above two have failed, we just kinda grapple attempting to\n\n/// return *something*.\n\n///\n\n/// If any form of authentication fails, libgit2 will repeatedly ask us for\n\n/// credentials until we give it a reason to not do so. To ensure we don't\n\n/// just sit here looping forever we keep track of authentications we've\n\n/// attempted and we don't try the same ones again.\n\nfn with_authentication<T, F>(url: &str, cfg: &git2::Config, mut f: F) -> CargoResult<T>\n\nwhere\n\n F: FnMut(&mut git2::Credentials<'_>) -> CargoResult<T>,\n\n{\n\n let mut cred_helper = git2::CredentialHelper::new(url);\n\n cred_helper.config(cfg);\n\n\n\n let mut ssh_username_requested = false;\n\n let mut cred_helper_bad = None;\n\n let mut ssh_agent_attempts = Vec::new();\n\n let mut any_attempts = false;\n\n let mut tried_sshkey = false;\n\n\n\n let mut res = f(&mut |url, username, allowed| {\n\n any_attempts = true;\n\n // libgit2's \"USERNAME\" authentication actually means that it's just\n\n // asking us for a username to keep going. This is currently only really\n\n // used for SSH authentication and isn't really an authentication type.\n\n // The logic currently looks like:\n\n //\n", "file_path": "src/cargo/sources/git/utils.rs", "rank": 20, "score": 280380.40093428607 }, { "content": "pub fn basic_manifest(name: &str, version: &str) -> String {\n\n format!(\n\n r#\"\n\n [package]\n\n name = \"{}\"\n\n version = \"{}\"\n\n authors = []\n\n \"#,\n\n name, version\n\n )\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/lib.rs", "rank": 21, "score": 279876.17667930224 }, { "content": "fn rm_rf(path: &Path, config: &Config) -> CargoResult<()> {\n\n let m = fs::metadata(path);\n\n if m.as_ref().map(|s| s.is_dir()).unwrap_or(false) {\n\n config\n\n .shell()\n\n .verbose(|shell| shell.status(\"Removing\", path.display()))?;\n\n paths::remove_dir_all(path)\n\n .chain_err(|| anyhow::format_err!(\"could not remove build directory\"))?;\n\n } else if m.is_ok() {\n\n config\n\n .shell()\n\n .verbose(|shell| shell.status(\"Removing\", path.display()))?;\n\n paths::remove_file(path)\n\n .chain_err(|| anyhow::format_err!(\"failed to remove build artifact\"))?;\n\n }\n\n Ok(())\n\n}\n", "file_path": "src/cargo/ops/cargo_clean.rs", "rank": 22, "score": 279786.6033290898 }, { "content": "/// Configure a libcurl http handle with the defaults options for Cargo\n\npub fn configure_http_handle(config: &Config, handle: &mut Easy) -> CargoResult<HttpTimeout> {\n\n let http = config.http_config()?;\n\n if let Some(proxy) = http_proxy(config)? {\n\n handle.proxy(&proxy)?;\n\n }\n\n if let Some(cainfo) = &http.cainfo {\n\n let cainfo = cainfo.resolve_path(config);\n\n handle.cainfo(&cainfo)?;\n\n }\n\n if let Some(check) = http.check_revoke {\n\n handle.ssl_options(SslOpt::new().no_revoke(!check))?;\n\n }\n\n\n\n if let Some(user_agent) = &http.user_agent {\n\n handle.useragent(user_agent)?;\n\n } else {\n\n handle.useragent(&version().to_string())?;\n\n }\n\n\n\n fn to_ssl_version(s: &str) -> CargoResult<SslVersion> {\n", "file_path": "src/cargo/ops/registry.rs", "rank": 23, "score": 278908.69626562664 }, { "content": "/// Returns the path to the `file` in `pwd`, if it exists.\n\npub fn find_project_manifest_exact(pwd: &Path, file: &str) -> CargoResult<PathBuf> {\n\n let manifest = pwd.join(file);\n\n\n\n if manifest.exists() {\n\n Ok(manifest)\n\n } else {\n\n anyhow::bail!(\"Could not find `{}` in `{}`\", file, pwd.display())\n\n }\n\n}\n", "file_path": "src/cargo/util/important_paths.rs", "rank": 24, "score": 278271.444123406 }, { "content": "pub fn dylib_path_envvar() -> &'static str {\n\n if cfg!(windows) {\n\n \"PATH\"\n\n } else if cfg!(target_os = \"macos\") {\n\n // When loading and linking a dynamic library or bundle, dlopen\n\n // searches in LD_LIBRARY_PATH, DYLD_LIBRARY_PATH, PWD, and\n\n // DYLD_FALLBACK_LIBRARY_PATH.\n\n // In the Mach-O format, a dynamic library has an \"install path.\"\n\n // Clients linking against the library record this path, and the\n\n // dynamic linker, dyld, uses it to locate the library.\n\n // dyld searches DYLD_LIBRARY_PATH *before* the install path.\n\n // dyld searches DYLD_FALLBACK_LIBRARY_PATH only if it cannot\n\n // find the library in the install path.\n\n // Setting DYLD_LIBRARY_PATH can easily have unintended\n\n // consequences.\n\n //\n\n // Also, DYLD_LIBRARY_PATH appears to have significant performance\n\n // penalty starting in 10.13. Cargo's testsuite ran more than twice as\n\n // slow with it on CI.\n\n \"DYLD_FALLBACK_LIBRARY_PATH\"\n\n } else {\n\n \"LD_LIBRARY_PATH\"\n\n }\n\n}\n\n\n", "file_path": "src/cargo/util/paths.rs", "rank": 25, "score": 277235.1218218339 }, { "content": "pub fn assert_match(expected: &str, actual: &str) {\n\n if !normalized_lines_match(expected, actual, None) {\n\n panic!(\n\n \"Did not find expected:\\n{}\\nActual:\\n{}\\n\",\n\n expected, actual\n\n );\n\n }\n\n}\n\n\n", "file_path": "tests/testsuite/config.rs", "rank": 26, "score": 276862.38410515746 }, { "content": "/// Compute all the dependencies of the given root units.\n\n/// The result is stored in state.unit_dependencies.\n\nfn deps_of_roots<'a, 'cfg>(roots: &[Unit<'a>], mut state: &mut State<'a, 'cfg>) -> CargoResult<()> {\n\n // Loop because we are downloading while building the dependency graph.\n\n // The partially-built unit graph is discarded through each pass of the\n\n // loop because it is incomplete because not all required Packages have\n\n // been downloaded.\n\n loop {\n\n for unit in roots.iter() {\n\n state.get(unit.pkg.package_id())?;\n\n\n\n // Dependencies of tests/benches should not have `panic` set.\n\n // We check the global test mode to see if we are running in `cargo\n\n // test` in which case we ensure all dependencies have `panic`\n\n // cleared, and avoid building the lib thrice (once with `panic`, once\n\n // without, once for `--test`). In particular, the lib included for\n\n // Doc tests and examples are `Build` mode here.\n\n let unit_for = if unit.mode.is_any_test() || state.bcx.build_config.test() {\n\n UnitFor::new_test(state.bcx.config)\n\n } else if unit.target.is_custom_build() {\n\n // This normally doesn't happen, except `clean` aggressively\n\n // generates all units.\n", "file_path": "src/cargo/core/compiler/unit_dependencies.rs", "rank": 27, "score": 276674.7992988818 }, { "content": "pub fn generate_url(name: &str) -> Url {\n\n Url::from_file_path(generate_path(name)).ok().unwrap()\n\n}\n", "file_path": "crates/cargo-test-support/src/registry.rs", "rank": 28, "score": 276346.743216791 }, { "content": "fn do_op<F>(path: &Path, desc: &str, mut f: F)\n\nwhere\n\n F: FnMut(&Path) -> io::Result<()>,\n\n{\n\n match f(path) {\n\n Ok(()) => {}\n\n Err(ref e) if e.kind() == ErrorKind::PermissionDenied => {\n\n let mut p = t!(path.metadata()).permissions();\n\n p.set_readonly(false);\n\n t!(fs::set_permissions(path, p));\n\n\n\n // Unix also requires the parent to not be readonly for example when\n\n // removing files\n\n let parent = path.parent().unwrap();\n\n let mut p = t!(parent.metadata()).permissions();\n\n p.set_readonly(false);\n\n t!(fs::set_permissions(parent, p));\n\n\n\n f(path).unwrap_or_else(|e| {\n\n panic!(\"failed to {} {}: {}\", desc, path.display(), e);\n\n })\n\n }\n\n Err(e) => {\n\n panic!(\"failed to {} {}: {}\", desc, path.display(), e);\n\n }\n\n }\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/paths.rs", "rank": 29, "score": 275461.65210381313 }, { "content": "pub fn loc_names(names: &[(&'static str, &'static str)]) -> Vec<PackageId> {\n\n names\n\n .iter()\n\n .map(|&(name, loc)| pkg_id_loc(name, loc))\n\n .collect()\n\n}\n\n\n\n/// By default `Summary` and `Dependency` have a very verbose `Debug` representation.\n\n/// This replaces with a representation that uses constructors from this file.\n\n///\n\n/// If `registry_strategy` is improved to modify more fields\n\n/// then this needs to update to display the corresponding constructor.\n\npub struct PrettyPrintRegistry(pub Vec<Summary>);\n\n\n\nimpl fmt::Debug for PrettyPrintRegistry {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"vec![\")?;\n\n for s in &self.0 {\n\n if s.dependencies().is_empty() {\n\n write!(f, \"pkg!((\\\"{}\\\", \\\"{}\\\")),\", s.name(), s.version())?;\n", "file_path": "crates/resolver-tests/src/lib.rs", "rank": 30, "score": 274760.2174527373 }, { "content": "/// Finds the root `Cargo.toml`.\n\npub fn find_root_manifest_for_wd(cwd: &Path) -> CargoResult<PathBuf> {\n\n let file = \"Cargo.toml\";\n\n for current in paths::ancestors(cwd) {\n\n let manifest = current.join(file);\n\n if fs::metadata(&manifest).is_ok() {\n\n return Ok(manifest);\n\n }\n\n }\n\n\n\n anyhow::bail!(\n\n \"could not find `{}` in `{}` or any parent directory\",\n\n file,\n\n cwd.display()\n\n )\n\n}\n\n\n", "file_path": "src/cargo/util/important_paths.rs", "rank": 31, "score": 274442.710237811 }, { "content": "pub fn subcommand(name: &'static str) -> App {\n\n SubCommand::with_name(name).settings(&[\n\n AppSettings::UnifiedHelpMessage,\n\n AppSettings::DeriveDisplayOrder,\n\n AppSettings::DontCollapseArgsInUsage,\n\n ])\n\n}\n\n\n\n// Determines whether or not to gate `--profile` as unstable when resolving it.\n\npub enum ProfileChecking {\n\n Checked,\n\n Unchecked,\n\n}\n\n\n", "file_path": "src/cargo/util/command_prelude.rs", "rank": 32, "score": 272435.706656549 }, { "content": "pub fn basic_lib_manifest(name: &str) -> String {\n\n format!(\n\n r#\"\n\n [package]\n\n\n\n name = \"{}\"\n\n version = \"0.5.0\"\n\n authors = [\"wycats@example.com\"]\n\n\n\n [lib]\n\n\n\n name = \"{}\"\n\n \"#,\n\n name, name\n\n )\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/lib.rs", "rank": 33, "score": 271904.7363523996 }, { "content": "pub fn basic_bin_manifest(name: &str) -> String {\n\n format!(\n\n r#\"\n\n [package]\n\n\n\n name = \"{}\"\n\n version = \"0.5.0\"\n\n authors = [\"wycats@example.com\"]\n\n\n\n [[bin]]\n\n\n\n name = \"{}\"\n\n \"#,\n\n name, name\n\n )\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/lib.rs", "rank": 34, "score": 271904.7363523996 }, { "content": "// Generates a project layout inside our fake home dir\n\npub fn project_in_home(name: &str) -> ProjectBuilder {\n\n ProjectBuilder::new(paths::home().join(name))\n\n}\n\n\n\n// === Helpers ===\n\n\n", "file_path": "crates/cargo-test-support/src/lib.rs", "rank": 35, "score": 271904.7363523996 }, { "content": "/// Wrapper method for network call retry logic.\n\n///\n\n/// Retry counts provided by Config object `net.retry`. Config shell outputs\n\n/// a warning on per retry.\n\n///\n\n/// Closure must return a `CargoResult`.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// # use crate::cargo::util::{CargoResult, Config};\n\n/// # let download_something = || return Ok(());\n\n/// # let config = Config::default().unwrap();\n\n/// use cargo::util::network;\n\n/// let cargo_result = network::with_retry(&config, || download_something());\n\n/// ```\n\npub fn with_retry<T, F>(config: &Config, mut callback: F) -> CargoResult<T>\n\nwhere\n\n F: FnMut() -> CargoResult<T>,\n\n{\n\n let mut retry = Retry::new(config)?;\n\n loop {\n\n if let Some(ret) = retry.r#try(&mut callback)? {\n\n return Ok(ret);\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/cargo/util/network.rs", "rank": 36, "score": 270007.82202798675 }, { "content": "/// Returns the location that the dep-info file will show up at for the `unit`\n\n/// specified.\n\npub fn dep_info_loc<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> PathBuf {\n\n cx.files()\n\n .fingerprint_dir(unit)\n\n .join(&format!(\"dep-{}\", filename(cx, unit)))\n\n}\n\n\n", "file_path": "src/cargo/core/compiler/fingerprint.rs", "rank": 37, "score": 269760.5018823125 }, { "content": "pub fn get_lib_extension(kind: &str) -> &str {\n\n match kind {\n\n \"lib\" | \"rlib\" => \"rlib\",\n\n \"staticlib\" => {\n\n if cfg!(windows) {\n\n \"lib\"\n\n } else {\n\n \"a\"\n\n }\n\n }\n\n \"dylib\" | \"proc-macro\" => {\n\n if cfg!(windows) {\n\n \"dll\"\n\n } else if cfg!(target_os = \"macos\") {\n\n \"dylib\"\n\n } else {\n\n \"so\"\n\n }\n\n }\n\n _ => unreachable!(),\n\n }\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/paths.rs", "rank": 38, "score": 269510.19177930563 }, { "content": "pub fn get_lib_prefix(kind: &str) -> &str {\n\n match kind {\n\n \"lib\" | \"rlib\" => \"lib\",\n\n \"staticlib\" | \"dylib\" | \"proc-macro\" => {\n\n if cfg!(windows) {\n\n \"\"\n\n } else {\n\n \"lib\"\n\n }\n\n }\n\n _ => unreachable!(),\n\n }\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/paths.rs", "rank": 39, "score": 269510.19177930563 }, { "content": "/// Compares a line with an expected pattern.\n\n/// - Use `[..]` as a wildcard to match 0 or more characters on the same line\n\n/// (similar to `.*` in a regex).\n\n/// - Use `[EXE]` to optionally add `.exe` on Windows (empty string on other\n\n/// platforms).\n\n/// - There is a wide range of macros (such as `[COMPILING]` or `[WARNING]`)\n\n/// to match cargo's \"status\" output and allows you to ignore the alignment.\n\n/// See `substitute_macros` for a complete list of macros.\n\n/// - `[ROOT]` the path to the test directory's root\n\n/// - `[CWD]` is the working directory of the process that was run.\n\npub fn lines_match(expected: &str, mut actual: &str) -> bool {\n\n let expected = substitute_macros(expected);\n\n for (i, part) in expected.split(\"[..]\").enumerate() {\n\n match actual.find(part) {\n\n Some(j) => {\n\n if i == 0 && j != 0 {\n\n return false;\n\n }\n\n actual = &actual[j + part.len()..];\n\n }\n\n None => return false,\n\n }\n\n }\n\n actual.is_empty() || expected.ends_with(\"[..]\")\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/lib.rs", "rank": 40, "score": 269318.1033853671 }, { "content": "pub fn generate_alt_dl_url(name: &str) -> String {\n\n let base = Url::from_file_path(generate_path(name)).ok().unwrap();\n\n format!(\"{}/{{crate}}/{{version}}/{{crate}}-{{version}}.crate\", base)\n\n}\n\n\n\n/// A builder for creating a new package in a registry.\n\n///\n\n/// This uses \"source replacement\" using an automatically generated\n\n/// `.cargo/config` file to ensure that dependencies will use these packages\n\n/// instead of contacting crates.io. See `source-replacement.md` for more\n\n/// details on how source replacement works.\n\n///\n\n/// Call `publish` to finalize and create the package.\n\n///\n\n/// If no files are specified, an empty `lib.rs` file is automatically created.\n\n///\n\n/// The `Cargo.toml` file is automatically generated based on the methods\n\n/// called on `Package` (for example, calling `dep()` will add to the\n\n/// `[dependencies]` automatically). You may also specify a `Cargo.toml` file\n\n/// to override the generated one.\n", "file_path": "crates/cargo-test-support/src/registry.rs", "rank": 41, "score": 267698.47960522585 }, { "content": "#[cfg(windows)]\n\npub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {\n\n match path.as_os_str().to_str() {\n\n Some(s) => Ok(s.as_bytes()),\n\n None => Err(anyhow::format_err!(\n\n \"invalid non-unicode path: {}\",\n\n path.display()\n\n )),\n\n }\n\n}\n\n\n", "file_path": "src/cargo/util/paths.rs", "rank": 42, "score": 265470.9791216385 }, { "content": "pub fn read(path: &Path) -> CargoResult<String> {\n\n match String::from_utf8(read_bytes(path)?) {\n\n Ok(s) => Ok(s),\n\n Err(_) => anyhow::bail!(\"path at `{}` was not valid utf-8\", path.display()),\n\n }\n\n}\n\n\n", "file_path": "src/cargo/util/paths.rs", "rank": 43, "score": 265464.5235053321 }, { "content": "/// Determines the `PathSource` from a `SourceId`.\n\npub fn path_source(source_id: SourceId, config: &Config) -> CargoResult<PathSource<'_>> {\n\n let path = source_id\n\n .url()\n\n .to_file_path()\n\n .map_err(|()| format_err!(\"path sources must have a valid path\"))?;\n\n Ok(PathSource::new(&path, source_id, config))\n\n}\n\n\n", "file_path": "src/cargo/ops/common_for_install_and_uninstall.rs", "rank": 44, "score": 263937.9458685628 }, { "content": "fn installed_exe(name: &str) -> PathBuf {\n\n cargo_home().join(\"bin\").join(exe(name))\n\n}\n\n\n", "file_path": "tests/testsuite/install_upgrade.rs", "rank": 45, "score": 263038.18613132846 }, { "content": "pub fn mtime(path: &Path) -> CargoResult<FileTime> {\n\n let meta = fs::metadata(path).chain_err(|| format!(\"failed to stat `{}`\", path.display()))?;\n\n Ok(FileTime::from_last_modification_time(&meta))\n\n}\n\n\n", "file_path": "src/cargo/util/paths.rs", "rank": 46, "score": 262208.8655600106 }, { "content": "fn inferred_bins(package_root: &Path, package_name: &str) -> Vec<(String, PathBuf)> {\n\n let main = package_root.join(\"src\").join(\"main.rs\");\n\n let mut result = Vec::new();\n\n if main.exists() {\n\n result.push((package_name.to_string(), main));\n\n }\n\n result.extend(infer_from_directory(&package_root.join(\"src\").join(\"bin\")));\n\n\n\n result\n\n}\n\n\n", "file_path": "src/cargo/util/toml/targets.rs", "rank": 47, "score": 260764.2454737104 }, { "content": "pub fn save_credentials(cfg: &Config, token: String, registry: Option<String>) -> CargoResult<()> {\n\n // If 'credentials.toml' exists, we should write to that, otherwise\n\n // use the legacy 'credentials'. There's no need to print the warning\n\n // here, because it would already be printed at load time.\n\n let home_path = cfg.home_path.clone().into_path_unlocked();\n\n let filename = match cfg.get_file_path(&home_path, \"credentials\", false)? {\n\n Some(path) => match path.file_name() {\n\n Some(filename) => Path::new(filename).to_owned(),\n\n None => Path::new(\"credentials\").to_owned(),\n\n },\n\n None => Path::new(\"credentials\").to_owned(),\n\n };\n\n\n\n let mut file = {\n\n cfg.home_path.create_dir()?;\n\n cfg.home_path\n\n .open_rw(filename, cfg, \"credentials' config file\")?\n\n };\n\n\n\n let (key, mut value) = {\n", "file_path": "src/cargo/util/config/mod.rs", "rank": 48, "score": 259929.42755978456 }, { "content": "fn write_config_toml(config: &str) {\n\n write_config_at(paths::root().join(\".cargo/config.toml\"), config);\n\n}\n\n\n", "file_path": "tests/testsuite/config.rs", "rank": 49, "score": 257664.20800397883 }, { "content": "/// Prepare for work when a package starts to build\n\npub fn prepare_init<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> CargoResult<()> {\n\n let new1 = cx.files().fingerprint_dir(unit);\n\n\n\n // Doc tests have no output, thus no fingerprint.\n\n if !new1.exists() && !unit.mode.is_doc_test() {\n\n paths::create_dir_all(&new1)?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/cargo/core/compiler/fingerprint.rs", "rank": 50, "score": 256515.26463428023 }, { "content": "/// Initializes the correct VCS system based on the provided config.\n\nfn init_vcs(path: &Path, vcs: VersionControl, config: &Config) -> CargoResult<()> {\n\n match vcs {\n\n VersionControl::Git => {\n\n if !path.join(\".git\").exists() {\n\n // Temporary fix to work around bug in libgit2 when creating a\n\n // directory in the root of a posix filesystem.\n\n // See: https://github.com/libgit2/libgit2/issues/5130\n\n paths::create_dir_all(path)?;\n\n GitRepo::init(path, config.cwd())?;\n\n }\n\n }\n\n VersionControl::Hg => {\n\n if !path.join(\".hg\").exists() {\n\n HgRepo::init(path, config.cwd())?;\n\n }\n\n }\n\n VersionControl::Pijul => {\n\n if !path.join(\".pijul\").exists() {\n\n PijulRepo::init(path, config.cwd())?;\n\n }\n", "file_path": "src/cargo/ops/cargo_new.rs", "rank": 51, "score": 256307.93717745732 }, { "content": "/// Record the current time on the filesystem (using the filesystem's clock)\n\n/// using a file at the given directory. Returns the current time.\n\npub fn set_invocation_time(path: &Path) -> CargoResult<FileTime> {\n\n // note that if `FileTime::from_system_time(SystemTime::now());` is determined to be sufficient,\n\n // then this can be removed.\n\n let timestamp = path.join(\"invoked.timestamp\");\n\n write(\n\n &timestamp,\n\n b\"This file has an mtime of when this was started.\",\n\n )?;\n\n mtime(&timestamp)\n\n}\n\n\n", "file_path": "src/cargo/util/paths.rs", "rank": 52, "score": 256159.12177344965 }, { "content": "/// Create a new tag in the git repository.\n\npub fn tag(repo: &git2::Repository, name: &str) {\n\n let head = repo.head().unwrap().target().unwrap();\n\n t!(repo.tag(\n\n name,\n\n &t!(repo.find_object(head, None)),\n\n &t!(repo.signature()),\n\n \"make a new tag\",\n\n false\n\n ));\n\n}\n", "file_path": "crates/cargo-test-support/src/git.rs", "rank": 53, "score": 255901.36491527973 }, { "content": "pub fn write(path: &Path, contents: &[u8]) -> CargoResult<()> {\n\n (|| -> CargoResult<()> {\n\n let mut f = File::create(path)?;\n\n f.write_all(contents)?;\n\n Ok(())\n\n })()\n\n .chain_err(|| format!(\"failed to write `{}`\", path.display()))?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/cargo/util/paths.rs", "rank": 54, "score": 254614.37010462096 }, { "content": "pub fn append(path: &Path, contents: &[u8]) -> CargoResult<()> {\n\n (|| -> CargoResult<()> {\n\n let mut f = OpenOptions::new()\n\n .write(true)\n\n .append(true)\n\n .create(true)\n\n .open(path)?;\n\n\n\n f.write_all(contents)?;\n\n Ok(())\n\n })()\n\n .chain_err(|| format!(\"failed to write `{}`\", path.display()))?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/cargo/util/paths.rs", "rank": 55, "score": 254614.37010462096 }, { "content": "/// Creates a new HTTP handle with appropriate global configuration for cargo.\n\npub fn http_handle(config: &Config) -> CargoResult<Easy> {\n\n let (mut handle, timeout) = http_handle_and_timeout(config)?;\n\n timeout.configure(&mut handle)?;\n\n Ok(handle)\n\n}\n\n\n", "file_path": "src/cargo/ops/registry.rs", "rank": 56, "score": 254516.38806475874 }, { "content": "pub fn homedir(cwd: &Path) -> Option<PathBuf> {\n\n ::home::cargo_home_with_cwd(cwd).ok()\n\n}\n\n\n", "file_path": "src/cargo/util/config/mod.rs", "rank": 57, "score": 253925.7945902692 }, { "content": "fn get_name<'a>(path: &'a Path, opts: &'a NewOptions) -> CargoResult<&'a str> {\n\n if let Some(ref name) = opts.name {\n\n return Ok(name);\n\n }\n\n\n\n let file_name = path.file_name().ok_or_else(|| {\n\n anyhow::format_err!(\n\n \"cannot auto-detect package name from path {:?} ; use --name to override\",\n\n path.as_os_str()\n\n )\n\n })?;\n\n\n\n file_name.to_str().ok_or_else(|| {\n\n anyhow::format_err!(\n\n \"cannot create package with a non-unicode name: {:?}\",\n\n file_name\n\n )\n\n })\n\n}\n\n\n", "file_path": "src/cargo/ops/cargo_new.rs", "rank": 58, "score": 253432.99992813193 }, { "content": "/// Computes several maps in `Context`:\n\n/// - `build_scripts`: A map that tracks which build scripts each package\n\n/// depends on.\n\n/// - `build_explicit_deps`: Dependency statements emitted by build scripts\n\n/// from a previous run.\n\n/// - `build_script_outputs`: Pre-populates this with any overridden build\n\n/// scripts.\n\n///\n\n/// The important one here is `build_scripts`, which for each `(package,\n\n/// metadata)` stores a `BuildScripts` object which contains a list of\n\n/// dependencies with build scripts that the unit should consider when\n\n/// linking. For example this lists all dependencies' `-L` flags which need to\n\n/// be propagated transitively.\n\n///\n\n/// The given set of units to this function is the initial set of\n\n/// targets/profiles which are being built.\n\npub fn build_map<'b, 'cfg>(cx: &mut Context<'b, 'cfg>, units: &[Unit<'b>]) -> CargoResult<()> {\n\n let mut ret = HashMap::new();\n\n for unit in units {\n\n build(&mut ret, cx, unit)?;\n\n }\n\n cx.build_scripts\n\n .extend(ret.into_iter().map(|(k, v)| (k, Arc::new(v))));\n\n return Ok(());\n\n\n\n // Recursive function to build up the map we're constructing. This function\n\n // memoizes all of its return values as it goes along.\n\n fn build<'a, 'b, 'cfg>(\n\n out: &'a mut HashMap<Unit<'b>, BuildScripts>,\n\n cx: &mut Context<'b, 'cfg>,\n\n unit: &Unit<'b>,\n\n ) -> CargoResult<&'a BuildScripts> {\n\n // Do a quick pre-flight check to see if we've already calculated the\n\n // set of dependencies.\n\n if out.contains_key(unit) {\n\n return Ok(&out[unit]);\n", "file_path": "src/cargo/core/compiler/custom_build.rs", "rank": 59, "score": 253074.05857858784 }, { "content": "pub fn dep_kind(name: &str, kind: DepKind) -> Dependency {\n\n dep(name).set_kind(kind).clone()\n\n}\n\n\n", "file_path": "crates/resolver-tests/src/lib.rs", "rank": 60, "score": 251695.10816810606 }, { "content": "pub fn read_bytes(path: &Path) -> CargoResult<Vec<u8>> {\n\n let res = (|| -> CargoResult<_> {\n\n let mut ret = Vec::new();\n\n let mut f = File::open(path)?;\n\n if let Ok(m) = f.metadata() {\n\n ret.reserve(m.len() as usize + 1);\n\n }\n\n f.read_to_end(&mut ret)?;\n\n Ok(ret)\n\n })()\n\n .chain_err(|| format!(\"failed to read `{}`\", path.display()))?;\n\n Ok(res)\n\n}\n\n\n", "file_path": "src/cargo/util/paths.rs", "rank": 61, "score": 251511.91401671758 }, { "content": "pub fn normalize_path(path: &Path) -> PathBuf {\n\n let mut components = path.components().peekable();\n\n let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {\n\n components.next();\n\n PathBuf::from(c.as_os_str())\n\n } else {\n\n PathBuf::new()\n\n };\n\n\n\n for component in components {\n\n match component {\n\n Component::Prefix(..) => unreachable!(),\n\n Component::RootDir => {\n\n ret.push(component.as_os_str());\n\n }\n\n Component::CurDir => {}\n\n Component::ParentDir => {\n\n ret.pop();\n\n }\n\n Component::Normal(c) => {\n\n ret.push(c);\n\n }\n\n }\n\n }\n\n ret\n\n}\n\n\n", "file_path": "src/cargo/util/paths.rs", "rank": 62, "score": 251250.55428902933 }, { "content": "/// Read the output from Config.\n\npub fn read_output(config: Config) -> String {\n\n drop(config); // Paranoid about flushing the file.\n\n let path = paths::root().join(\"shell.out\");\n\n fs::read_to_string(path).unwrap()\n\n}\n\n\n", "file_path": "tests/testsuite/config.rs", "rank": 63, "score": 250634.21155742486 }, { "content": "pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CargoResult<OsString> {\n\n env::join_paths(paths.iter())\n\n .chain_err(|| {\n\n let paths = paths.iter().map(Path::new).collect::<Vec<_>>();\n\n format!(\"failed to join path array: {:?}\", paths)\n\n })\n\n .chain_err(|| {\n\n format!(\n\n \"failed to join search paths together\\n\\\n\n Does ${} have an unterminated quote character?\",\n\n env\n\n )\n\n })\n\n}\n\n\n", "file_path": "src/cargo/util/paths.rs", "rank": 64, "score": 250557.98562782773 }, { "content": "pub fn opt(name: &'static str, help: &'static str) -> Arg<'static, 'static> {\n\n Arg::with_name(name).long(name).help(help)\n\n}\n\n\n", "file_path": "src/cargo/util/command_prelude.rs", "rank": 65, "score": 249621.70208532523 }, { "content": "fn pkg_id_loc(name: &str, loc: &str) -> PackageId {\n\n let remote = loc.into_url();\n\n let master = GitReference::Branch(\"master\".to_string());\n\n let source_id = SourceId::for_git(&remote.unwrap(), master).unwrap();\n\n\n\n PackageId::new(name, \"1.0.0\", source_id).unwrap()\n\n}\n\n\n", "file_path": "crates/resolver-tests/src/lib.rs", "rank": 66, "score": 248893.1286924092 }, { "content": "/// Prepares a `Work` that executes the target as a custom build script.\n\npub fn prepare<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> CargoResult<Job> {\n\n let _p = profile::start(format!(\n\n \"build script prepare: {}/{}\",\n\n unit.pkg,\n\n unit.target.name()\n\n ));\n\n\n\n let metadata = cx.get_run_build_script_metadata(unit);\n\n if cx\n\n .build_script_outputs\n\n .lock()\n\n .unwrap()\n\n .contains_key(unit.pkg.package_id(), metadata)\n\n {\n\n // The output is already set, thus the build script is overridden.\n\n fingerprint::prepare_target(cx, unit, false)\n\n } else {\n\n build_work(cx, unit)\n\n }\n\n}\n\n\n", "file_path": "src/cargo/core/compiler/custom_build.rs", "rank": 67, "score": 248685.36226170236 }, { "content": "pub fn needs_custom_http_transport(config: &Config) -> CargoResult<bool> {\n\n Ok(http_proxy_exists(config)?\n\n || *config.http_config()? != Default::default()\n\n || env::var_os(\"HTTP_TIMEOUT\").is_some())\n\n}\n\n\n", "file_path": "src/cargo/ops/registry.rs", "rank": 68, "score": 248189.25638746825 }, { "content": "fn pkg(name: &str, vers: &str) {\n\n Package::new(name, vers)\n\n .file(\"src/main.rs\", \"fn main() {{}}\")\n\n .publish();\n\n}\n\n\n", "file_path": "tests/testsuite/concurrent.rs", "rank": 69, "score": 248088.33904003812 }, { "content": "fn pkg(name: &str, vers: &str) {\n\n Package::new(name, vers)\n\n .file(\"src/lib.rs\", \"\")\n\n .file(\n\n \"src/main.rs\",\n\n &format!(\"extern crate {}; fn main() {{}}\", name),\n\n )\n\n .publish();\n\n}\n\n\n", "file_path": "tests/testsuite/install.rs", "rank": 70, "score": 248088.3390400381 }, { "content": "fn setup(name: &str, version: &str) {\n\n let dir = api_path().join(format!(\"api/v1/crates/{}/{}\", name, version));\n\n dir.mkdir_p();\n\n fs::write(dir.join(\"yank\"), r#\"{\"ok\": true}\"#).unwrap();\n\n}\n\n\n", "file_path": "tests/testsuite/yank.rs", "rank": 71, "score": 248088.3390400381 }, { "content": "fn check_has_installed_exe<P: AsRef<Path>>(path: P, name: &'static str) -> bool {\n\n path.as_ref().join(\"bin\").join(exe(name)).is_file()\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/install.rs", "rank": 72, "score": 247410.61494510528 }, { "content": "/// Variant of `lines_match` that applies normalization to the strings.\n\npub fn normalized_lines_match(expected: &str, actual: &str, cwd: Option<&Path>) -> bool {\n\n let expected = normalize_matcher(expected, cwd);\n\n let actual = normalize_matcher(actual, cwd);\n\n lines_match(&expected, &actual)\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/lib.rs", "rank": 73, "score": 247119.06214271672 }, { "content": "/// Checks the result of a crate publish.\n\npub fn validate_upload(expected_json: &str, expected_crate_name: &str, expected_files: &[&str]) {\n\n let new_path = registry::api_path().join(\"api/v1/crates/new\");\n\n _validate_upload(\n\n &new_path,\n\n expected_json,\n\n expected_crate_name,\n\n expected_files,\n\n &[],\n\n );\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/publish.rs", "rank": 74, "score": 246908.88713549508 }, { "content": "pub fn resolve_executable(exec: &Path) -> CargoResult<PathBuf> {\n\n if exec.components().count() == 1 {\n\n let paths = env::var_os(\"PATH\").ok_or_else(|| anyhow::format_err!(\"no PATH\"))?;\n\n let candidates = env::split_paths(&paths).flat_map(|path| {\n\n let candidate = path.join(&exec);\n\n let with_exe = if env::consts::EXE_EXTENSION == \"\" {\n\n None\n\n } else {\n\n Some(candidate.with_extension(env::consts::EXE_EXTENSION))\n\n };\n\n iter::once(candidate).chain(with_exe)\n\n });\n\n for candidate in candidates {\n\n if candidate.is_file() {\n\n // PATH may have a component like \".\" in it, so we still need to\n\n // canonicalize.\n\n return Ok(candidate.canonicalize()?);\n\n }\n\n }\n\n\n\n anyhow::bail!(\"no executable for `{}` found in PATH\", exec.display())\n\n } else {\n\n Ok(exec.canonicalize()?)\n\n }\n\n}\n\n\n", "file_path": "src/cargo/util/paths.rs", "rank": 75, "score": 245788.28580237576 }, { "content": "/// Create a new git repository with a project.\n\npub fn new<F>(name: &str, callback: F) -> Project\n\nwhere\n\n F: FnOnce(ProjectBuilder) -> ProjectBuilder,\n\n{\n\n new_repo(name, callback).0\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/git.rs", "rank": 76, "score": 245275.66721392423 }, { "content": "pub fn ancestors(path: &Path) -> PathAncestors<'_> {\n\n PathAncestors::new(path)\n\n}\n\n\n\npub struct PathAncestors<'a> {\n\n current: Option<&'a Path>,\n\n stop_at: Option<PathBuf>,\n\n}\n\n\n\nimpl<'a> PathAncestors<'a> {\n\n fn new(path: &Path) -> PathAncestors<'_> {\n\n PathAncestors {\n\n current: Some(path),\n\n //HACK: avoid reading `~/.cargo/config` when testing Cargo itself.\n\n stop_at: env::var(\"__CARGO_TEST_ROOT\").ok().map(PathBuf::from),\n\n }\n\n }\n\n}\n\n\n\nimpl<'a> Iterator for PathAncestors<'a> {\n", "file_path": "src/cargo/util/paths.rs", "rank": 77, "score": 245046.384814688 }, { "content": "// Helper for publishing a package.\n\nfn pkg(name: &str, vers: &str) {\n\n Package::new(name, vers)\n\n .file(\n\n \"src/main.rs\",\n\n r#\"fn main() { println!(\"{}\", env!(\"CARGO_PKG_VERSION\")) }\"#,\n\n )\n\n .publish();\n\n}\n\n\n", "file_path": "tests/testsuite/install_upgrade.rs", "rank": 78, "score": 244078.93361386546 }, { "content": "fn open_docs(path: &Path, shell: &mut Shell) -> CargoResult<()> {\n\n match std::env::var_os(\"BROWSER\") {\n\n Some(browser) => {\n\n if let Err(e) = Command::new(&browser).arg(path).status() {\n\n shell.warn(format!(\n\n \"Couldn't open docs with {}: {}\",\n\n browser.to_string_lossy(),\n\n e\n\n ))?;\n\n }\n\n }\n\n None => {\n\n if let Err(e) = opener::open(&path) {\n\n shell.warn(format!(\"Couldn't open docs: {}\", e))?;\n\n for cause in anyhow::Error::new(e).chain().skip(1) {\n\n shell.warn(format!(\"Caused by:\\n {}\", cause))?;\n\n }\n\n }\n\n }\n\n };\n\n\n\n Ok(())\n\n}\n", "file_path": "src/cargo/ops/cargo_doc.rs", "rank": 79, "score": 241031.2822442443 }, { "content": "pub fn new(opts: &NewOptions, config: &Config) -> CargoResult<()> {\n\n let path = &opts.path;\n\n if fs::metadata(path).is_ok() {\n\n anyhow::bail!(\n\n \"destination `{}` already exists\\n\\n\\\n\n Use `cargo init` to initialize the directory\",\n\n path.display()\n\n )\n\n }\n\n\n\n let name = get_name(path, opts)?;\n\n check_name(name, opts)?;\n\n\n\n let mkopts = MkOptions {\n\n version_control: opts.version_control,\n\n path,\n\n name,\n\n source_files: vec![plan_new_source_file(opts.kind.is_bin(), name.to_string())],\n\n bin: opts.kind.is_bin(),\n\n edition: opts.edition.as_ref().map(|s| &**s),\n", "file_path": "src/cargo/ops/cargo_new.rs", "rank": 80, "score": 240590.89535244496 }, { "content": "pub fn init(opts: &NewOptions, config: &Config) -> CargoResult<()> {\n\n // This is here just as a random location to exercise the internal error handling.\n\n if std::env::var_os(\"__CARGO_TEST_INTERNAL_ERROR\").is_some() {\n\n return Err(crate::util::internal(\"internal error test\"));\n\n }\n\n\n\n let path = &opts.path;\n\n\n\n if fs::metadata(&path.join(\"Cargo.toml\")).is_ok() {\n\n anyhow::bail!(\"`cargo init` cannot be run on existing Cargo packages\")\n\n }\n\n\n\n let name = get_name(path, opts)?;\n\n check_name(name, opts)?;\n\n\n\n let mut src_paths_types = vec![];\n\n\n\n detect_source_paths_and_types(path, name, &mut src_paths_types)?;\n\n\n\n if src_paths_types.is_empty() {\n", "file_path": "src/cargo/ops/cargo_new.rs", "rank": 81, "score": 240590.89535244502 }, { "content": "pub fn modify_owners(config: &Config, opts: &OwnersOptions) -> CargoResult<()> {\n\n let name = match opts.krate {\n\n Some(ref name) => name.clone(),\n\n None => {\n\n let manifest_path = find_root_manifest_for_wd(config.cwd())?;\n\n let ws = Workspace::new(&manifest_path, config)?;\n\n ws.current()?.package_id().name().to_string()\n\n }\n\n };\n\n\n\n let (mut registry, _) = registry(\n\n config,\n\n opts.token.clone(),\n\n opts.index.clone(),\n\n opts.registry.clone(),\n\n true,\n\n true,\n\n )?;\n\n\n\n if let Some(ref v) = opts.to_add {\n", "file_path": "src/cargo/ops/registry.rs", "rank": 82, "score": 240590.895352445 }, { "content": "pub fn values(args: &ArgMatches<'_>, name: &str) -> Vec<String> {\n\n args._values_of(name)\n\n}\n\n\n", "file_path": "src/cargo/util/command_prelude.rs", "rank": 83, "score": 239650.1455929901 }, { "content": "pub fn dep_req_kind(name: &str, req: &str, kind: DepKind, public: bool) -> Dependency {\n\n let mut dep = dep_req(name, req);\n\n dep.set_kind(kind);\n\n dep.set_public(public);\n\n dep\n\n}\n\n\n", "file_path": "crates/resolver-tests/src/lib.rs", "rank": 84, "score": 239290.76390616194 }, { "content": "pub fn http_handle_and_timeout(config: &Config) -> CargoResult<(Easy, HttpTimeout)> {\n\n if config.frozen() {\n\n bail!(\n\n \"attempting to make an HTTP request, but --frozen was \\\n\n specified\"\n\n )\n\n }\n\n if !config.network_allowed() {\n\n bail!(\"can't make HTTP request in the offline mode\")\n\n }\n\n\n\n // The timeout option for libcurl by default times out the entire transfer,\n\n // but we probably don't want this. Instead we only set timeouts for the\n\n // connect phase as well as a \"low speed\" timeout so if we don't receive\n\n // many bytes in a large-ish period of time then we time out.\n\n let mut handle = Easy::new();\n\n let timeout = configure_http_handle(config, &mut handle)?;\n\n Ok((handle, timeout))\n\n}\n\n\n", "file_path": "src/cargo/ops/registry.rs", "rank": 85, "score": 237648.64358710177 }, { "content": "fn setup(name: &str, content: Option<&str>) {\n\n let dir = api_path().join(format!(\"api/v1/crates/{}\", name));\n\n dir.mkdir_p();\n\n if let Some(body) = content {\n\n fs::write(dir.join(\"owners\"), body).unwrap();\n\n }\n\n}\n\n\n", "file_path": "tests/testsuite/owner.rs", "rank": 86, "score": 237639.67928225518 }, { "content": "/// Check that the given package name/version has the following bins listed in\n\n/// the trackers. Also verifies that both trackers are in sync and valid.\n\n/// Pass in an empty `bins` list to assert that the package is *not* installed.\n\nfn validate_trackers(name: &str, version: &str, bins: &[&str]) {\n\n let v1 = load_crates1();\n\n let v1_table = v1.get(\"v1\").unwrap().as_table().unwrap();\n\n let v2 = load_crates2();\n\n let v2_table = v2[\"installs\"].as_object().unwrap();\n\n assert_eq!(v1_table.len(), v2_table.len());\n\n // Convert `bins` to a BTreeSet.\n\n let bins: BTreeSet<String> = bins\n\n .iter()\n\n .map(|b| format!(\"{}{}\", b, env::consts::EXE_SUFFIX))\n\n .collect();\n\n // Check every entry matches between v1 and v2.\n\n for (pkg_id_str, v1_bins) in v1_table {\n\n let pkg_id: PackageId = toml::Value::from(pkg_id_str.to_string())\n\n .try_into()\n\n .unwrap();\n\n let v1_bins: BTreeSet<String> = v1_bins\n\n .as_array()\n\n .unwrap()\n\n .iter()\n", "file_path": "tests/testsuite/install_upgrade.rs", "rank": 87, "score": 236790.3568890472 }, { "content": "/// Resolves all dependencies for a package using an optional previous instance.\n\n/// of resolve to guide the resolution process.\n\n///\n\n/// This also takes an optional hash set, `to_avoid`, which is a list of package\n\n/// IDs that should be avoided when consulting the previous instance of resolve\n\n/// (often used in pairings with updates).\n\n///\n\n/// The previous resolve normally comes from a lock file. This function does not\n\n/// read or write lock files from the filesystem.\n\n///\n\n/// `specs` may be empty, which indicates it should resolve all workspace\n\n/// members. In this case, `opts.all_features` must be `true`.\n\n///\n\n/// If `register_patches` is true, then entries from the `[patch]` table in\n\n/// the manifest will be added to the given `PackageRegistry`.\n\npub fn resolve_with_previous<'cfg>(\n\n registry: &mut PackageRegistry<'cfg>,\n\n ws: &Workspace<'cfg>,\n\n opts: &ResolveOpts,\n\n previous: Option<&Resolve>,\n\n to_avoid: Option<&HashSet<PackageId>>,\n\n specs: &[PackageIdSpec],\n\n register_patches: bool,\n\n) -> CargoResult<Resolve> {\n\n // We only want one Cargo at a time resolving a crate graph since this can\n\n // involve a lot of frobbing of the global caches.\n\n let _lock = ws.config().acquire_package_cache_lock()?;\n\n\n\n // Here we place an artificial limitation that all non-registry sources\n\n // cannot be locked at more than one revision. This means that if a Git\n\n // repository provides more than one package, they must all be updated in\n\n // step when any of them are updated.\n\n //\n\n // TODO: this seems like a hokey reason to single out the registry as being\n\n // different.\n", "file_path": "src/cargo/ops/resolve.rs", "rank": 88, "score": 236164.1581752369 }, { "content": "fn check_name(name: &str, opts: &NewOptions) -> CargoResult<()> {\n\n // If --name is already used to override, no point in suggesting it\n\n // again as a fix.\n\n let name_help = match opts.name {\n\n Some(_) => \"\",\n\n None => \"\\nuse --name to override crate name\",\n\n };\n\n\n\n // Ban keywords + test list found at\n\n // https://doc.rust-lang.org/reference/keywords.html\n\n let blacklist = [\n\n \"abstract\", \"alignof\", \"as\", \"become\", \"box\", \"break\", \"const\", \"continue\", \"crate\", \"do\",\n\n \"else\", \"enum\", \"extern\", \"false\", \"final\", \"fn\", \"for\", \"if\", \"impl\", \"in\", \"let\", \"loop\",\n\n \"macro\", \"match\", \"mod\", \"move\", \"mut\", \"offsetof\", \"override\", \"priv\", \"proc\", \"pub\",\n\n \"pure\", \"ref\", \"return\", \"self\", \"sizeof\", \"static\", \"struct\", \"super\", \"test\", \"trait\",\n\n \"true\", \"type\", \"typeof\", \"unsafe\", \"unsized\", \"use\", \"virtual\", \"where\", \"while\", \"yield\",\n\n ];\n\n if blacklist.contains(&name) || (opts.kind.is_bin() && compiler::is_bad_artifact_name(name)) {\n\n anyhow::bail!(\n\n \"The name `{}` cannot be used as a crate name{}\",\n", "file_path": "src/cargo/ops/cargo_new.rs", "rank": 89, "score": 235464.75813573645 }, { "content": "/// returns path to clippy-driver binary\n\n///\n\n/// Allows override of the path via `CARGO_CLIPPY_DRIVER` env variable\n\npub fn clippy_driver() -> PathBuf {\n\n env::var(\"CARGO_CLIPPY_DRIVER\")\n\n .unwrap_or_else(|_| \"clippy-driver\".into())\n\n .into()\n\n}\n\n\n\n#[derive(Debug, Default, Deserialize, PartialEq)]\n\n#[serde(rename_all = \"kebab-case\")]\n\npub struct CargoHttpConfig {\n\n pub proxy: Option<String>,\n\n pub low_speed_limit: Option<u32>,\n\n pub timeout: Option<u64>,\n\n pub cainfo: Option<ConfigRelativePath>,\n\n pub check_revoke: Option<bool>,\n\n pub user_agent: Option<String>,\n\n pub debug: Option<bool>,\n\n pub multiplexing: Option<bool>,\n\n pub ssl_version: Option<SslVersionConfig>,\n\n}\n\n\n", "file_path": "src/cargo/util/config/mod.rs", "rank": 90, "score": 234554.3950508095 }, { "content": "pub fn create_dir_all(p: impl AsRef<Path>) -> CargoResult<()> {\n\n _create_dir_all(p.as_ref())\n\n}\n\n\n", "file_path": "src/cargo/util/paths.rs", "rank": 91, "score": 233796.70553316938 }, { "content": "// Check if we are in an existing repo. We define that to be true if either:\n\n//\n\n// 1. We are in a git repo and the path to the new package is not an ignored\n\n// path in that repo.\n\n// 2. We are in an HG repo.\n\npub fn existing_vcs_repo(path: &Path, cwd: &Path) -> bool {\n\n fn in_git_repo(path: &Path, cwd: &Path) -> bool {\n\n if let Ok(repo) = GitRepo::discover(path, cwd) {\n\n // Don't check if the working directory itself is ignored.\n\n if repo.workdir().map_or(false, |workdir| workdir == path) {\n\n true\n\n } else {\n\n !repo.is_path_ignored(path).unwrap_or(false)\n\n }\n\n } else {\n\n false\n\n }\n\n }\n\n\n\n in_git_repo(path, cwd) || HgRepo::discover(path, cwd).is_ok()\n\n}\n\n\n\npub struct HgRepo;\n\npub struct GitRepo;\n\npub struct PijulRepo;\n", "file_path": "src/cargo/util/vcs.rs", "rank": 92, "score": 233089.42763654905 }, { "content": "pub fn values_os(args: &ArgMatches<'_>, name: &str) -> Vec<OsString> {\n\n args._values_of_os(name)\n\n}\n\n\n\n#[derive(PartialEq, PartialOrd, Eq, Ord)]\n\npub enum CommandInfo {\n\n BuiltIn { name: String, about: Option<String> },\n\n External { name: String, path: PathBuf },\n\n}\n\n\n\nimpl CommandInfo {\n\n pub fn name(&self) -> &str {\n\n match self {\n\n CommandInfo::BuiltIn { name, .. } => name,\n\n CommandInfo::External { name, .. } => name,\n\n }\n\n }\n\n}\n", "file_path": "src/cargo/util/command_prelude.rs", "rank": 93, "score": 231873.59428634867 }, { "content": "fn pl_manifest(name: &str, version: &str, extra: &str) -> String {\n\n format!(\n\n r#\"\n\n [package]\n\n name = \"{}\"\n\n version = \"{}\"\n\n authors = []\n\n license = \"MIT\"\n\n description = \"foo\"\n\n documentation = \"foo\"\n\n homepage = \"foo\"\n\n repository = \"foo\"\n\n\n\n {}\n\n \"#,\n\n name, version, extra\n\n )\n\n}\n\n\n", "file_path": "tests/testsuite/publish_lockfile.rs", "rank": 94, "score": 228792.82907760402 }, { "content": "/// Resolve the standard library dependencies.\n\npub fn resolve_std<'cfg>(\n\n ws: &Workspace<'cfg>,\n\n target_data: &RustcTargetData,\n\n requested_target: CompileKind,\n\n crates: &[String],\n\n) -> CargoResult<(PackageSet<'cfg>, Resolve, ResolvedFeatures)> {\n\n let src_path = detect_sysroot_src_path(target_data)?;\n\n let to_patch = [\n\n \"rustc-std-workspace-core\",\n\n \"rustc-std-workspace-alloc\",\n\n \"rustc-std-workspace-std\",\n\n ];\n\n let patches = to_patch\n\n .iter()\n\n .map(|&name| {\n\n let source_path = SourceId::for_path(&src_path.join(\"src\").join(\"tools\").join(name))?;\n\n let dep = Dependency::parse_no_deprecated(name, None, source_path)?;\n\n Ok(dep)\n\n })\n\n .collect::<CargoResult<Vec<_>>>()?;\n", "file_path": "src/cargo/core/compiler/standard_lib.rs", "rank": 95, "score": 228017.68793380063 }, { "content": "/// Initialize a new repository at the given path.\n\npub fn init(path: &Path) -> git2::Repository {\n\n let repo = t!(git2::Repository::init(path));\n\n default_repo_cfg(&repo);\n\n repo\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/git.rs", "rank": 96, "score": 226234.87317276397 }, { "content": "fn find_files(path: &Path, dst: &mut Vec<PathBuf>) {\n\n for e in path.read_dir().unwrap() {\n\n let e = e.unwrap();\n\n let path = e.path();\n\n if e.file_type().unwrap().is_dir() {\n\n find_files(&path, dst);\n\n } else {\n\n dst.push(path);\n\n }\n\n }\n\n}\n", "file_path": "tests/testsuite/corrupt_git.rs", "rank": 97, "score": 225681.64170790196 }, { "content": "pub fn init_root() -> TestIdGuard {\n\n static NEXT_ID: AtomicUsize = AtomicUsize::new(0);\n\n\n\n let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);\n\n TEST_ID.with(|n| *n.borrow_mut() = Some(id));\n\n\n\n let guard = TestIdGuard { _private: () };\n\n\n\n let r = root();\n\n r.rm_rf();\n\n r.mkdir_p();\n\n\n\n guard\n\n}\n\n\n\nimpl Drop for TestIdGuard {\n\n fn drop(&mut self) {\n\n TEST_ID.with(|n| *n.borrow_mut() = None);\n\n }\n\n}\n\n\n", "file_path": "crates/cargo-test-support/src/paths.rs", "rank": 98, "score": 225188.23039327766 } ]
Rust
src/power/battery-manager/battery-cli/src/commands.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use { rustyline::{ completion::Completer, error::ReadlineError, highlight::Highlighter, hint::Hinter, Helper, }, std::{ borrow::Cow::{self, Borrowed, Owned}, fmt, str::FromStr, }, }; macro_rules! gen_commands { ($name:ident { $($variant:ident = ($val:expr, [$($arg:expr),*], $help:expr)),*, }) => { #[derive(PartialEq)] pub enum $name { $($variant),* } impl $name { pub fn variants() -> Vec<String> { let mut variants = Vec::new(); $(variants.push($val.to_string());)* variants } pub fn arguments(&self) -> &'static str { match self { $( $name::$variant => concat!($("<", $arg, "> ",)*) ),* } } #[allow(unused)] pub fn cmd_help(&self) -> &'static str { match self { $( $name::$variant => concat!($val, " ", $("<", $arg, "> ",)* "-- ", $help) ),* } } pub fn help_msg() -> &'static str { concat!("Commands:\n", $( "\t", $val, " ", $("<", $arg, "> ",)* "-- ", $help, "\n" ),*) } } impl fmt::Display for $name { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { $($name::$variant => write!(f, $val)),* , } } } impl FromStr for $name { type Err = (); fn from_str(s: &str) -> Result<$name, ()> { match s { $($val => Ok($name::$variant)),* , _ => Err(()), } } } } } gen_commands! { Command { Get = ("get", [], "Get all information of the battery state"), Set = ("set", ["<attribute1 value1> ... [attributeN valueN]", "--help"], "Set state of battery in one line | Print help message"), Reconnect = ("reconnect", [], "Connect the real battery and disconnect the simulator"), Disconnect = ("disconnect", [], "Disconnect the real battery and connect to the simulator"), Help = ("help", [], "Help message"), Exit = ("exit", [], "Exit/Close REPL"), Quit = ("quit", [], "Quit/Close REPL"), } } pub struct CmdHelper; impl CmdHelper { pub fn new() -> CmdHelper { CmdHelper {} } } impl Completer for CmdHelper { type Candidate = String; fn complete(&self, line: &str, _pos: usize) -> Result<(usize, Vec<String>), ReadlineError> { let mut variants = Vec::new(); for variant in Command::variants() { if variant.starts_with(line) { variants.push(variant) } } Ok((0, variants)) } } impl Hinter for CmdHelper { fn hint(&self, line: &str, _pos: usize) -> Option<String> { let needs_space = !line.ends_with(" "); line.trim() .parse::<Command>() .map(|cmd| { format!("{}{}", if needs_space { " " } else { "" }, cmd.arguments().to_string(),) }) .ok() } } impl Highlighter for CmdHelper { fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> { if hint.trim().is_empty() { Borrowed(hint) } else { Owned(format!("\x1b[90m{}\x1b[0m", hint)) } } } impl Helper for CmdHelper {} pub enum ReplControl { Break, Continue, }
use { rustyline::{ completion::Completer, error::ReadlineError, highlight::Highlighter, hint::Hinter, Helper, }, std::{ borrow::Cow::{self, Borrowed, Owned}, fmt, str::FromStr, }, }; macro_rules! gen_commands { ($name:ident { $($variant:ident = ($val:expr, [$($arg:expr),*], $help:expr)),*, }) => { #[derive(PartialEq)] pub enum $name { $($variant),* } impl $name { pub fn variants() -> Vec<String> { let mut variants = Vec::new(); $(variants.push($val.to_string());)* variants } pub fn arguments(&self) -> &'static str { match self { $( $name::$variant => concat!($("<", $arg, "> ",)*) ),* } } #[allow(unused)] pub fn cmd_help(&self) -> &'static str { match self { $( $name::$variant => concat!($val, " ", $("<", $arg, "> ",)* "-- ", $help) ),* } } pub fn help_msg() -> &'static str { concat!("Commands:\n", $( "\t", $val, " ", $("<", $arg, "> ",)* "-- ", $help, "\n" ),*) } } impl fmt::Display for $name { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { $($name::$variant => write!(f, $val)),* , } } } impl FromStr for $name { type Err = (); fn from_str(s: &str) -> Result<$name, ()> { match s { $($val => Ok($name::$variant)),* , _ => Err(()), } } } } } gen_commands! { Command { Get = ("get", [], "Get all information of the battery state"), Set = ("set", ["<attribute1 value1> ... [attributeN valueN]", "--help"], "Set state of battery in one line | Print help message"), Reconnect = ("reconnect", [], "Connect the real battery and disconnect the simulator"), Disconnect = ("disconnect", [], "Disconnect the real battery and connect to the simulator"), Help = ("help", [], "Help message"), Exit = ("exit", [], "Exit/Close REPL"), Quit = ("quit", [], "Quit/Close REPL"), } } pub struct CmdHelper; impl CmdHelper { pub fn new() -> CmdHelper { CmdHelper {} } } impl Completer for CmdHelper { type Candidate = String;
} impl Hinter for CmdHelper { fn hint(&self, line: &str, _pos: usize) -> Option<String> { let needs_space = !line.ends_with(" "); line.trim() .parse::<Command>() .map(|cmd| { format!("{}{}", if needs_space { " " } else { "" }, cmd.arguments().to_string(),) }) .ok() } } impl Highlighter for CmdHelper { fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> { if hint.trim().is_empty() { Borrowed(hint) } else { Owned(format!("\x1b[90m{}\x1b[0m", hint)) } } } impl Helper for CmdHelper {} pub enum ReplControl { Break, Continue, }
fn complete(&self, line: &str, _pos: usize) -> Result<(usize, Vec<String>), ReadlineError> { let mut variants = Vec::new(); for variant in Command::variants() { if variant.starts_with(line) { variants.push(variant) } } Ok((0, variants)) }
function_block-full_function
[]
Rust
bot/src/module/promotions.rs
Abendstolz/OxidizeBot
9c217e2c68bef0ff6e5ed9fb68aded6576d27186
use crate::auth; use crate::command; use crate::db; use crate::irc; use crate::module; use crate::prelude::*; use crate::utils; use chrono::Utc; pub struct Handler { enabled: settings::Var<bool>, promotions: injector::Ref<db::Promotions>, } #[async_trait] impl command::Handler for Handler { async fn handle(&self, ctx: &mut command::Context) -> Result<(), anyhow::Error> { if !self.enabled.load().await { return Ok(()); } let promotions = match self.promotions.load().await { Some(promotions) => promotions, None => return Ok(()), }; let next = command_base!(ctx, promotions, "promotion", PromoEdit); match next.as_deref() { Some("edit") => { ctx.check_scope(auth::Scope::PromoEdit).await?; let name = ctx.next_str("<name> <frequency> <template..>")?; let frequency = ctx.next_parse("<name> <frequency> <template..>")?; let template = ctx.rest_parse("<name> <frequency> <template..>")?; promotions .edit(ctx.channel(), &name, frequency, template) .await?; respond!(ctx, "Edited promo."); } None | Some(..) => { respond!( ctx, "Expected: show, list, edit, delete, enable, disable, or group." ); } } Ok(()) } } pub struct Module; #[async_trait] impl super::Module for Module { fn ty(&self) -> &'static str { "promotions" } async fn hook( &self, module::HookContext { injector, handlers, futures, sender, settings, idle, .. }: module::HookContext<'_>, ) -> Result<(), anyhow::Error> { let settings = settings.scoped("promotions"); let enabled = settings.var("enabled", false).await?; let (mut setting, frequency) = settings .stream("frequency") .or_with_else(|| utils::Duration::seconds(5 * 60)) .await?; handlers.insert( "promo", Handler { enabled: enabled.clone(), promotions: injector.var().await, }, ); let (mut promotions_stream, mut promotions) = injector.stream::<db::Promotions>().await; let sender = sender.clone(); let mut interval = tokio::time::interval(frequency.as_std()); let idle = idle.clone(); let future = async move { loop { tokio::select! { update = promotions_stream.recv() => { promotions = update; } duration = setting.recv() => { interval = tokio::time::interval(duration.as_std()); } _ = interval.tick() => { if !enabled.load().await { continue; } let promotions = match promotions.as_ref() { Some(promotions) => promotions, None => continue, }; if idle.is_idle().await { log::trace!("channel is too idle to send a promotion"); } else { let promotions = promotions.clone(); let sender = sender.clone(); if let Err(e) = promote(promotions, sender).await { log::error!("failed to send promotion: {}", e); } } } } } }; futures.push(Box::pin(future)); Ok(()) } } async fn promote(promotions: db::Promotions, sender: irc::Sender) -> Result<(), anyhow::Error> { let channel = sender.channel(); if let Some(p) = pick(promotions.list(channel).await) { let text = p.render(&PromoData { channel })?; promotions.bump_promoted_at(&*p).await?; sender.privmsg(text).await; } Ok(()) } #[derive(Debug, serde::Serialize)] struct PromoData<'a> { channel: &'a str, } fn pick(mut promotions: Vec<Arc<db::Promotion>>) -> Option<Arc<db::Promotion>> { promotions.sort_by(|a, b| a.promoted_at.cmp(&b.promoted_at)); let now = Utc::now(); for p in promotions { let promoted_at = match p.promoted_at.as_ref() { None => return Some(p), Some(promoted_at) => promoted_at, }; if now.clone().signed_duration_since(promoted_at.clone()) < p.frequency.as_chrono() { continue; } return Some(p); } None }
use crate::auth; use crate::command; use crate::db; use crate::irc; use crate::module; use crate::prelude::*; use crate::utils; use chrono::Utc; pub struct Handler { enabled: settings::Var<bool>, promotions: injector::Ref<db::Promotions>, } #[async_trait] impl command::Handler for Handler { async fn handle(&self, ctx: &mut command::Context) -> Result<(), anyhow::Error> { if !self.enabled.
>")?; let template = ctx.rest_parse("<name> <frequency> <template..>")?; promotions .edit(ctx.channel(), &name, frequency, template) .await?; respond!(ctx, "Edited promo."); } None | Some(..) => { respond!( ctx, "Expected: show, list, edit, delete, enable, disable, or group." ); } } Ok(()) } } pub struct Module; #[async_trait] impl super::Module for Module { fn ty(&self) -> &'static str { "promotions" } async fn hook( &self, module::HookContext { injector, handlers, futures, sender, settings, idle, .. }: module::HookContext<'_>, ) -> Result<(), anyhow::Error> { let settings = settings.scoped("promotions"); let enabled = settings.var("enabled", false).await?; let (mut setting, frequency) = settings .stream("frequency") .or_with_else(|| utils::Duration::seconds(5 * 60)) .await?; handlers.insert( "promo", Handler { enabled: enabled.clone(), promotions: injector.var().await, }, ); let (mut promotions_stream, mut promotions) = injector.stream::<db::Promotions>().await; let sender = sender.clone(); let mut interval = tokio::time::interval(frequency.as_std()); let idle = idle.clone(); let future = async move { loop { tokio::select! { update = promotions_stream.recv() => { promotions = update; } duration = setting.recv() => { interval = tokio::time::interval(duration.as_std()); } _ = interval.tick() => { if !enabled.load().await { continue; } let promotions = match promotions.as_ref() { Some(promotions) => promotions, None => continue, }; if idle.is_idle().await { log::trace!("channel is too idle to send a promotion"); } else { let promotions = promotions.clone(); let sender = sender.clone(); if let Err(e) = promote(promotions, sender).await { log::error!("failed to send promotion: {}", e); } } } } } }; futures.push(Box::pin(future)); Ok(()) } } async fn promote(promotions: db::Promotions, sender: irc::Sender) -> Result<(), anyhow::Error> { let channel = sender.channel(); if let Some(p) = pick(promotions.list(channel).await) { let text = p.render(&PromoData { channel })?; promotions.bump_promoted_at(&*p).await?; sender.privmsg(text).await; } Ok(()) } #[derive(Debug, serde::Serialize)] struct PromoData<'a> { channel: &'a str, } fn pick(mut promotions: Vec<Arc<db::Promotion>>) -> Option<Arc<db::Promotion>> { promotions.sort_by(|a, b| a.promoted_at.cmp(&b.promoted_at)); let now = Utc::now(); for p in promotions { let promoted_at = match p.promoted_at.as_ref() { None => return Some(p), Some(promoted_at) => promoted_at, }; if now.clone().signed_duration_since(promoted_at.clone()) < p.frequency.as_chrono() { continue; } return Some(p); } None }
load().await { return Ok(()); } let promotions = match self.promotions.load().await { Some(promotions) => promotions, None => return Ok(()), }; let next = command_base!(ctx, promotions, "promotion", PromoEdit); match next.as_deref() { Some("edit") => { ctx.check_scope(auth::Scope::PromoEdit).await?; let name = ctx.next_str("<name> <frequency> <template..>")?; let frequency = ctx.next_parse("<name> <frequency> <template..
function_block-random_span
[ { "content": "/// Extract a settings key from the context.\n\nfn key(ctx: &mut command::Context) -> Result<String> {\n\n let key = ctx.next().ok_or_else(|| respond_err!(\"Expected <key>\"))?;\n\n\n\n if key.starts_with(\"secrets/\") {\n\n respond_bail!(\"Cannot access secrets through chat!\");\n\n }\n\n\n\n Ok(key)\n\n}\n\n\n\npub struct Module;\n\n\n\n#[async_trait]\n\nimpl super::Module for Module {\n\n fn ty(&self) -> &'static str {\n\n \"admin\"\n\n }\n\n\n\n async fn hook(\n\n &self,\n", "file_path": "bot/src/module/admin.rs", "rank": 0, "score": 247666.16494181345 }, { "content": "/// Construct a JSON OK response.\n\npub fn json_ok(body: impl Serialize) -> Result<Response<Body>, Error> {\n\n let body = serde_json::to_string(&body).map_err(anyhow::Error::from)?;\n\n\n\n let mut r = Response::new(Body::from(body));\n\n\n\n r.headers_mut().insert(\n\n header::CONTENT_TYPE,\n\n \"application/json\".parse().map_err(anyhow::Error::from)?,\n\n );\n\n\n\n Ok(r)\n\n}\n\n\n", "file_path": "web/src/web.rs", "rank": 1, "score": 230451.92180427603 }, { "content": "fn dbg_impl(stack: &mut Stack, args: usize) -> Result<(), VmError> {\n\n let mut string = String::new();\n\n\n\n let mut it = stack.drain_stack_top(args)?;\n\n let last = it.next_back();\n\n\n\n for value in it {\n\n write!(string, \"{:?}\", value).map_err(VmError::panic)?;\n\n string.push_str(\"\\n\");\n\n }\n\n\n\n if let Some(value) = last {\n\n write!(string, \"{:?}\", value).map_err(VmError::panic)?;\n\n }\n\n\n\n log::info!(\"[dbg]: {}\", string);\n\n stack.push(Value::Unit);\n\n Ok(())\n\n}\n\n\n", "file_path": "bot/src/script/io.rs", "rank": 2, "score": 215013.20047628888 }, { "content": "/// Construct a HTML response.\n\npub fn html(body: String) -> Result<Response<Body>, Error> {\n\n let mut r = Response::new(Body::from(body));\n\n\n\n r.headers_mut().insert(\n\n header::CONTENT_TYPE,\n\n \"text/html; charset=utf-8\"\n\n .parse()\n\n .map_err(anyhow::Error::from)?,\n\n );\n\n\n\n Ok(r)\n\n}\n\n\n", "file_path": "web/src/web.rs", "rank": 3, "score": 181370.78165880384 }, { "content": "/// Copy a wide string from a source to a destination.\n\npub fn copy_wstring(dest: &mut [u16], source: &str) {\n\n let source = source.to_wide_null();\n\n let len = usize::min(source.len(), dest.len());\n\n dest[..len].copy_from_slice(&source[..len]);\n\n}\n\n\n", "file_path": "bot/src/sys/windows/window.rs", "rank": 4, "score": 180309.89395884657 }, { "content": "/// Load the settings schema to use.\n\npub fn load_schema() -> Result<crate::Schema, crate::settings::Error> {\n\n crate::settings::Schema::load_bytes(SCHEMA)\n\n}\n", "file_path": "bot/src/lib.rs", "rank": 5, "score": 178698.7489837545 }, { "content": "fn create_zip(file: &Path, it: impl IntoIterator<Item = PathBuf>) -> Result<()> {\n\n let options =\n\n zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored);\n\n\n\n let mut zip = zip::ZipWriter::new(fs::File::create(file)?);\n\n\n\n for p in it {\n\n println!(\"Adding to zip: {}\", p.display());\n\n\n\n let file_name = p\n\n .file_name()\n\n .and_then(OsStr::to_str)\n\n .ok_or_else(|| anyhow!(\"file name is not a string\"))?;\n\n\n\n zip.start_file(file_name, options)?;\n\n let mut from = fs::File::open(&p)?;\n\n io::copy(&mut from, &mut zip)?;\n\n }\n\n\n\n zip.finish()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "tools/builder/src/main.rs", "rank": 7, "score": 170363.8847349951 }, { "content": "pub fn setup(_root: &Path, _log_file: &Path) -> Result<System, Error> {\n\n Ok(System)\n\n}\n", "file_path": "bot/src/sys/noop.rs", "rank": 8, "score": 170186.4391282036 }, { "content": "/// Setup all required flows.\n\npub fn setup_flows(base_url: &Url, config: &Config) -> Result<Flows, Error> {\n\n let mut out = HashMap::new();\n\n\n\n let login_flow = Arc::new(config.login.as_flow(base_url, config)?);\n\n\n\n for client_config in &config.flows {\n\n let flow = client_config.as_flow(base_url, config)?;\n\n out.insert(client_config.id.clone(), Arc::new(flow));\n\n }\n\n\n\n Ok((login_flow, out))\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct TokenQuery {\n\n pub code: AuthorizationCode,\n\n pub state: State,\n\n}\n\n\n\n#[derive(Debug)]\n", "file_path": "web/src/oauth2.rs", "rank": 9, "score": 170186.4391282036 }, { "content": "#[derive(Clone, Any)]\n\nstruct Ctx {\n\n ctx: command::Context,\n\n db: ScopedDb,\n\n}\n\n\n\nimpl Ctx {\n\n /// Access the db associated with the context.\n\n fn db(&self) -> ScopedDb {\n\n self.db.clone()\n\n }\n\n\n\n /// Get the user name, if present.\n\n fn user(&self) -> Option<String> {\n\n self.ctx.user.name().map(|s| s.to_owned())\n\n }\n\n\n\n /// Respond with the given message.\n\n async fn respond(&self, message: &str) {\n\n self.ctx.respond(message).await;\n\n }\n\n\n\n /// Send a privmsg, without prefixing it with the user we are responding to.\n\n async fn privmsg(&self, message: &str) {\n\n self.ctx.privmsg(message).await;\n\n }\n\n}\n", "file_path": "bot/src/script/mod.rs", "rank": 10, "score": 169564.11216557986 }, { "content": "pub fn setup(root: &Path, log_file: &Path) -> Result<System, Error> {\n\n let root = root.to_owned();\n\n let log_file = log_file.to_owned();\n\n\n\n // all senders to notify when we are requesting a restart.\n\n let (restart, _) = broadcast::channel(1);\n\n let restart1 = restart.clone();\n\n\n\n // all senders to notify when we are shutting down.\n\n let (shutdown, mut shutdown_rx) = broadcast::channel(1);\n\n let shutdown1 = shutdown.clone();\n\n\n\n let (events, mut events_rx) = mpsc::unbounded_channel::<Event>();\n\n\n\n let window_loop = async move {\n\n let mut window = window::Window::new(String::from(\"OxidizeBot\")).await?;\n\n\n\n window.set_icon_from_buffer(ICON, 128, 128)?;\n\n\n\n window.add_menu_entry(0, &format!(\"OxidizeBot {}\", crate::VERSION), true)?;\n", "file_path": "bot/src/sys/windows/mod.rs", "rank": 11, "score": 167812.27643655517 }, { "content": "/// Construct a JSON OK response.\n\npub fn http_error(status: StatusCode, message: &str) -> Result<Response<Body>, Error> {\n\n let body = serde_json::to_string(&Error {\n\n status: status.as_u16(),\n\n message,\n\n })\n\n .map_err(anyhow::Error::from)?;\n\n\n\n let mut r = Response::new(Body::from(body));\n\n\n\n *r.status_mut() = status;\n\n\n\n r.headers_mut().insert(\n\n header::CONTENT_TYPE,\n\n \"application/json\".parse().expect(\"valid header value\"),\n\n );\n\n\n\n return Ok(r);\n\n\n\n #[derive(Debug, Default, Serialize)]\n\n struct Error<'a> {\n", "file_path": "web/src/web.rs", "rank": 12, "score": 164791.44782985502 }, { "content": "fn main() -> Result<()> {\n\n if cfg!(target_os = \"windows\") {\n\n use winres::VersionInfo::*;\n\n\n\n let mut res = winres::WindowsResource::new();\n\n res.set_icon(\"res/icon.ico\");\n\n\n\n if let Some((version, info)) = file_version() {\n\n res.set(\"FileVersion\", &version);\n\n res.set(\"ProductVersion\", &version);\n\n res.set_version_info(FILEVERSION, info);\n\n res.set_version_info(PRODUCTVERSION, info);\n\n }\n\n\n\n res.compile().context(\"compiling resorces\")?;\n\n }\n\n\n\n let out_dir = PathBuf::from(env::var_os(\"OUT_DIR\").ok_or_else(|| anyhow!(\"missing: OUT_DIR\"))?);\n\n\n\n let version;\n", "file_path": "bot/build.rs", "rank": 13, "score": 162505.1436164567 }, { "content": "/// The handler trait for a given command.\n\npub trait Handler\n\nwhere\n\n Self: 'static + Send + Sync,\n\n{\n\n /// Scope required to run command.\n\n fn scope(&self) -> Option<Scope> {\n\n None\n\n }\n\n\n\n /// Handle the command.\n\n async fn handle(&self, ctx: &mut Context) -> Result<()>;\n\n}\n\n\n\n#[async_trait]\n", "file_path": "bot/src/command.rs", "rank": 14, "score": 160704.38302247503 }, { "content": "/// Handler for incoming messages.\n\nstruct Handler<'a> {\n\n /// Current Streamer.\n\n streamer: api::TwitchAndUser,\n\n /// The channel data associated with the streamer.\n\n streamer_channel: Arc<twitch::v5::Channel>,\n\n /// Queue for sending messages.\n\n sender: Sender,\n\n /// Moderators.\n\n moderators: Arc<RwLock<HashSet<String>>>,\n\n /// VIPs.\n\n vips: Arc<RwLock<HashSet<String>>>,\n\n /// Whitelisted hosts for links.\n\n whitelisted_hosts: HashSet<String>,\n\n /// All registered commands.\n\n commands: Option<db::Commands>,\n\n /// Bad words.\n\n bad_words: &'a db::Words,\n\n /// For sending notifications.\n\n global_bus: &'a bus::Bus<bus::Global>,\n\n /// Aliases.\n", "file_path": "bot/src/irc/mod.rs", "rank": 15, "score": 160311.65479792256 }, { "content": "fn main() -> Result<()> {\n\n let args = Args::args()?;\n\n\n\n if args.help {\n\n return Ok(());\n\n }\n\n\n\n if let Some(size) = args.stack_size {\n\n let thread = std::thread::Builder::new()\n\n .name(format!(\"main-with-stack-{}\", size))\n\n .spawn(move || inner_main(args))?;\n\n\n\n thread.join().expect(\"thread shouldn't panic\")\n\n } else {\n\n inner_main(args)\n\n }\n\n}\n\n\n", "file_path": "bot/src/main.rs", "rank": 16, "score": 160066.53536487618 }, { "content": "pub fn run(\n\n injector: &Injector,\n\n) -> (\n\n settings::Var<Option<api::github::Release>>,\n\n impl Future<Output = Result<()>>,\n\n) {\n\n let latest = settings::Var::new(None);\n\n let returned_latest = latest.clone();\n\n let injector = injector.clone();\n\n\n\n let future = async move {\n\n let github = api::GitHub::new()?;\n\n let mut interval = tokio::time::interval(Duration::hours(6).as_std());\n\n\n\n let (mut cache_stream, mut cache) = injector.stream::<Cache>().await;\n\n\n\n loop {\n\n tokio::select! {\n\n update = cache_stream.recv() => {\n\n cache = update;\n", "file_path": "bot/src/updater.rs", "rank": 17, "score": 160031.85155130588 }, { "content": "pub fn setup(\n\n db: db::Database,\n\n host: String,\n\n port: u32,\n\n config: Config,\n\n) -> Result<impl Future<Output = Result<(), hyper::Error>>, anyhow::Error> {\n\n let fallback =\n\n assets::Asset::get(\"index.html\").ok_or_else(|| anyhow!(\"missing index.html in assets\"))?;\n\n\n\n let pending_tokens = Arc::new(Mutex::new(HashMap::new()));\n\n\n\n let handler = Arc::new(Handler::new(fallback, db, config, pending_tokens.clone())?);\n\n\n\n let bind = format!(\"{}:{}\", host, port);\n\n log::info!(\"Listening on: http://{}\", bind);\n\n\n\n let addr: SocketAddr = str::parse(&bind)?;\n\n\n\n // TODO: add graceful shutdown.\n\n let mut server_future =\n", "file_path": "web/src/web.rs", "rank": 18, "score": 160031.85155130588 }, { "content": "fn main() -> Result<()> {\n\n let root = env::current_dir()?;\n\n println!(\"root: {}\", root.display());\n\n\n\n if cfg!(target_os = \"windows\") {\n\n windows_build(&root)?;\n\n } else if cfg!(target_os = \"linux\") {\n\n linux_build(&root)?;\n\n } else if cfg!(target_os = \"macos\") {\n\n macos_build(&root)?;\n\n } else {\n\n bail!(\"unsupported operating system: {}\", consts::OS);\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "tools/builder/src/main.rs", "rank": 19, "score": 157741.55691718162 }, { "content": "/// Setup tracing.\n\nfn tracing_config() -> Result<()> {\n\n tracing::subscriber::set_global_default(tracing_utils::Subscriber::new())?;\n\n Ok(())\n\n}\n\n\n", "file_path": "bot/src/main.rs", "rank": 20, "score": 157741.55691718162 }, { "content": "/// Set up a stream information loop.\n\npub fn setup(\n\n streamer: Arc<twitch::v5::User>,\n\n twitch: api::Twitch,\n\n) -> (\n\n StreamInfo,\n\n mpsc::Receiver<StreamState>,\n\n impl Future<Output = Result<()>>,\n\n) {\n\n let (mut stream_state_tx, stream_state_rx) = mpsc::channel(64);\n\n\n\n let stream_info = StreamInfo {\n\n user: streamer.clone(),\n\n data: Default::default(),\n\n };\n\n\n\n let mut stream_interval = tokio::time::interval(time::Duration::from_secs(30));\n\n let mut subs_interval = tokio::time::interval(time::Duration::from_secs(60 * 10));\n\n\n\n let future_info = stream_info.clone();\n\n\n", "file_path": "bot/src/stream_info.rs", "rank": 21, "score": 157707.05767781907 }, { "content": "/// Connect to the pub/sub websocket once available.\n\npub fn connect(\n\n settings: &crate::Settings,\n\n injector: &Injector,\n\n) -> impl Future<Output = Result<()>> {\n\n task(settings.clone(), injector.clone())\n\n}\n\n\n", "file_path": "bot/src/api/twitch/pubsub.rs", "rank": 22, "score": 155493.2841958874 }, { "content": "/// Install a panic handler which logs panics on errors.\n\n/// Adapted from: https://github.com/sfackler/rust-log-panics/blob/master/src/lib.rs\n\npub fn panic_logger() {\n\n panic::set_hook(Box::new(|info| {\n\n let bt = Backtrace::new();\n\n\n\n let thread = thread::current();\n\n let thread = thread.name().unwrap_or(\"unnamed\");\n\n\n\n let msg = match info.payload().downcast_ref::<&'static str>() {\n\n Some(s) => *s,\n\n None => match info.payload().downcast_ref::<String>() {\n\n Some(s) => &**s,\n\n None => \"?\",\n\n },\n\n };\n\n\n\n match info.location() {\n\n Some(location) => {\n\n log::error!(\n\n target: \"panic\", \"thread '{}' panicked at '{}': {}:{}\\n{:?}\",\n\n thread,\n", "file_path": "bot/src/panic_logger.rs", "rank": 23, "score": 155492.95243598 }, { "content": "/// Discards a result and log a warning on errors.\n\nfn warn_on_error<T, E>(result: Result<T, E>)\n\nwhere\n\n Error: From<E>,\n\n{\n\n if let Err(e) = result {\n\n log_warn!(e, \"failed to issue connect command\");\n\n }\n\n}\n", "file_path": "bot/src/player/connect.rs", "rank": 24, "score": 144478.29626114856 }, { "content": "/// Get the version from GITHUB_REF.\n\nfn github_ref_version() -> Result<Version> {\n\n let version = match env::var(\"GITHUB_REF\") {\n\n Ok(version) => version,\n\n _ => bail!(\"missing: GITHUB_REF\"),\n\n };\n\n\n\n let mut it = version.split('/');\n\n\n\n let version = match (it.next(), it.next(), it.next()) {\n\n (Some(\"refs\"), Some(\"tags\"), Some(version)) => {\n\n Version::open(version)?.ok_or_else(|| anyhow!(\"Expected valid version\"))?\n\n }\n\n _ => bail!(\"expected GITHUB_REF: refs/tags/*\"),\n\n };\n\n\n\n Ok(version)\n\n}\n\n\n", "file_path": "tools/builder/src/main.rs", "rank": 25, "score": 144308.5421476148 }, { "content": "type Callback = Box<dyn FnMut() -> Result<(), Error> + Send + 'static>;\n\n\n\n/// A single notification.\n\npub struct Notification {\n\n pub message: String,\n\n pub title: Option<String>,\n\n pub icon: NotificationIcon,\n\n pub timeout: Option<Duration>,\n\n pub on_click: Option<Callback>,\n\n}\n\n\n\nimpl fmt::Debug for Notification {\n\n fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n fmt.debug_struct(\"Notification\")\n\n .field(\"message\", &self.message)\n\n .field(\"title\", &self.title)\n\n .field(\"icon\", &self.icon)\n\n .field(\"timeout\", &self.timeout)\n\n .finish()\n\n }\n", "file_path": "bot/src/sys/mod.rs", "rank": 26, "score": 142658.2251158587 }, { "content": "fn cargo(args: &[&str]) -> Result<()> {\n\n println!(\"cargo {}\", args.join(\" \"));\n\n let status = Command::new(\"cargo\").args(args).status()?;\n\n\n\n if !status.success() {\n\n bail!(\"failed to run cargo\");\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "tools/builder/src/main.rs", "rank": 27, "score": 140753.61181743303 }, { "content": "fn inner_main(args: Args) -> Result<()> {\n\n let (old_root, root) = match args.root {\n\n Some(root) => (None, root),\n\n None => {\n\n let base = dirs::config_dir()\n\n .ok_or_else(|| anyhow!(\"no standard configuration directory available\"))?;\n\n let old = base.join(OLD_CONFIG_DIR);\n\n let new = base.join(CONFIG_DIR);\n\n (Some(old), new)\n\n }\n\n };\n\n\n\n let default_log_file = root.join(\"oxidize.log\");\n\n\n\n setup_logs(\n\n &root,\n\n args.log_config,\n\n &default_log_file,\n\n args.trace,\n\n &args.log,\n", "file_path": "bot/src/main.rs", "rank": 28, "score": 140753.61181743303 }, { "content": "/// Perform a MacOS build.\n\nfn macos_build(root: &Path) -> Result<()> {\n\n let version = github_ref_version()?;\n\n env::set_var(\"OXIDIZE_VERSION\", &version);\n\n println!(\"version: {}\", version);\n\n\n\n let exe = root.join(\"target/release/oxidize\");\n\n let upload = root.join(\"target/upload\");\n\n\n\n if !exe.is_file() {\n\n println!(\"building: {}\", exe.display());\n\n cargo(&[\n\n \"build\",\n\n \"--manifest-path=bot/Cargo.toml\",\n\n \"--release\",\n\n \"--bin\",\n\n \"oxidize\",\n\n ])?;\n\n }\n\n\n\n create_zip_dist(&upload, &version, vec![root.join(\"README.md\"), exe])?;\n\n Ok(())\n\n}\n\n\n", "file_path": "tools/builder/src/main.rs", "rank": 29, "score": 138725.64439385224 }, { "content": "/// Perform a Windows build.\n\nfn windows_build(root: &Path) -> Result<()> {\n\n let version = github_ref_version()?;\n\n let file_version = version.as_windows_file_version()?;\n\n\n\n env::set_var(\"OXIDIZE_VERSION\", &version);\n\n env::set_var(\"OXIDIZE_FILE_VERSION\", &file_version);\n\n\n\n println!(\"version: {}\", version);\n\n\n\n let signer = match (env::var(\"SIGNTOOL\"), env::var(\"CERTIFICATE_PASSWORD\")) {\n\n (Ok(signtool), Ok(password)) => {\n\n SignTool::open(root.to_owned(), PathBuf::from(signtool), password)\n\n }\n\n _ => None,\n\n };\n\n\n\n let exe = root.join(\"target\").join(\"release\").join(\"oxidize.exe\");\n\n let wix_dir = root.join(\"target\").join(\"wix\");\n\n let upload = root.join(\"target\").join(\"upload\");\n\n\n", "file_path": "tools/builder/src/main.rs", "rank": 30, "score": 138725.64439385224 }, { "content": "/// Perform a Linux build.\n\nfn linux_build(root: &Path) -> Result<()> {\n\n let version = github_ref_version()?;\n\n env::set_var(\"OXIDIZE_VERSION\", &version);\n\n println!(\"version: {}\", version);\n\n\n\n // Install cargo-deb for building the package below.\n\n cargo(&[\"install\", \"cargo-deb\"])?;\n\n\n\n let exe = root.join(\"target/release/oxidize\");\n\n let debian_dir = root.join(\"target/debian\");\n\n let upload = root.join(\"target/upload\");\n\n\n\n if !debian_dir.is_dir() {\n\n cargo(&[\n\n \"deb\",\n\n \"-p\",\n\n \"oxidize\",\n\n \"--deb-version\",\n\n &version.to_string(),\n\n ])?;\n", "file_path": "tools/builder/src/main.rs", "rank": 31, "score": 138725.64439385224 }, { "content": "/// Construct an empty json response.\n\nfn json_empty() -> Result<Response<Body>, Error> {\n\n return json_ok(&Empty {});\n\n\n\n #[derive(Debug, Serialize, Deserialize)]\n\n struct Empty {}\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct ReceivedToken {\n\n pub code: String,\n\n pub state: String,\n\n}\n", "file_path": "web/src/web.rs", "rank": 32, "score": 134203.06820963506 }, { "content": "/// Tokenize the given word.\n\npub fn tokenize(word: &str) -> String {\n\n let word = word.to_lowercase();\n\n inflector::string::singularize::to_singular(&word)\n\n}\n\n\n", "file_path": "bot/src/db/words.rs", "rank": 33, "score": 134176.69841060205 }, { "content": "/// Function to abbreviate texts.\n\n///\n\n/// Numeric components are left as is and require a space after it.\n\n/// For example: `100%` stays `100%`.\n\n///\n\n/// Non-numeric ascii text components are abbreviated with their first letter in uppercase.\n\n/// For example: `No Mission Skips` becomes `NMS`.\n\nfn abbreviate_text(mut text: &str) -> String {\n\n if text\n\n .chars()\n\n .all(|c| !c.is_whitespace() && (c.is_uppercase() || c.is_numeric()))\n\n {\n\n return text.to_string();\n\n }\n\n\n\n let mut out = String::new();\n\n\n\n // If the last added element requires spacing.\n\n let mut last_spacing = false;\n\n\n\n while !text.is_empty() {\n\n let c = match text.chars().next() {\n\n Some(c) => c,\n\n None => break,\n\n };\n\n\n\n match c {\n", "file_path": "bot/src/module/speedrun.rs", "rank": 34, "score": 132451.62848902208 }, { "content": "/// Convert a user display name into a user id.\n\npub fn user_id(user: &str) -> String {\n\n user.trim_start_matches('@').to_lowercase()\n\n}\n\n\n\n#[derive(Debug, Error)]\n\npub enum RenameError {\n\n /// Trying to rename something to a conflicting name.\n\n #[error(\"conflict\")]\n\n Conflict,\n\n /// Trying to rename something which doesn't exist.\n\n #[error(\"missing\")]\n\n Missing,\n\n}\n\n\n\n#[cfg(tests)]\n\nmod tests {\n\n use super::user_id;\n\n\n\n #[test]\n\n fn test_user_id() {\n\n assert_eq!(\"oxidizebot\", user_id(\"@OxidizeBot\"));\n\n }\n\n}\n", "file_path": "bot/src/db/mod.rs", "rank": 35, "score": 132235.3250910824 }, { "content": "struct InternalHandler {\n\n name: String,\n\n function: SyncFunction,\n\n path: PathBuf,\n\n sources: Arc<rune::Sources>,\n\n}\n\n\n", "file_path": "bot/src/script/mod.rs", "rank": 36, "score": 132093.34969197502 }, { "content": "/// Parse a CookieJar from a header.\n\nfn cookiejar_from_header(header: &[u8]) -> Result<CookieJar, Error> {\n\n let mut jar = CookieJar::new();\n\n\n\n for p in header.split(|b| *b == b';') {\n\n let p = std::str::from_utf8(p)?;\n\n jar.add_original(Cookie::parse_encoded(p.trim().to_owned())?);\n\n }\n\n\n\n Ok(jar)\n\n}\n", "file_path": "web/src/session.rs", "rank": 38, "score": 126662.91519394987 }, { "content": "/// Format the given number of seconds as a compact human time.\n\npub fn compact_duration(duration: time::Duration) -> String {\n\n let mut parts = Vec::new();\n\n\n\n let p = partition(duration);\n\n\n\n parts.extend(match p.days {\n\n 0 => None,\n\n n => Some(format!(\"{}d\", n)),\n\n });\n\n\n\n parts.extend(match p.hours {\n\n 0 => None,\n\n n => Some(format!(\"{}h\", n)),\n\n });\n\n\n\n parts.extend(match p.minutes {\n\n 0 => None,\n\n n => Some(format!(\"{}m\", n)),\n\n });\n\n\n", "file_path": "bot/src/utils/mod.rs", "rank": 39, "score": 126638.50695238983 }, { "content": "/// Formats the given list of strings as a comma-separated set of values.\n\npub fn human_list(list: &[String]) -> Option<String> {\n\n if list.is_empty() {\n\n return None;\n\n }\n\n\n\n let mut it = list.iter();\n\n let mut list = String::new();\n\n\n\n if let Some(el) = it.next() {\n\n list.push_str(el);\n\n }\n\n\n\n let back = it.next_back();\n\n\n\n for el in it {\n\n list.push_str(\", \");\n\n list.push_str(el);\n\n }\n\n\n\n if let Some(el) = back {\n\n list.push_str(\", & \");\n\n list.push_str(el);\n\n }\n\n\n\n Some(list)\n\n}\n\n\n", "file_path": "bot/src/utils/mod.rs", "rank": 40, "score": 126638.50695238983 }, { "content": "/// Format the given number of seconds as a long human time.\n\npub fn long_duration(duration: time::Duration) -> String {\n\n let mut parts = Vec::new();\n\n\n\n let p = partition(duration);\n\n\n\n parts.extend(match p.hours {\n\n 0 => None,\n\n 1 => Some(\"one hour\".to_string()),\n\n n => Some(format!(\"{} hours\", english_num(n))),\n\n });\n\n\n\n parts.extend(match p.minutes {\n\n 0 => None,\n\n 1 => Some(\"one minute\".to_string()),\n\n n => Some(format!(\"{} minutes\", english_num(n))),\n\n });\n\n\n\n parts.extend(match p.seconds {\n\n 0 => None,\n\n 1 => Some(\"one second\".to_string()),\n\n n => Some(format!(\"{} seconds\", english_num(n))),\n\n });\n\n\n\n if parts.is_empty() {\n\n return String::from(\"0 seconds\");\n\n }\n\n\n\n parts.join(\", \")\n\n}\n\n\n", "file_path": "bot/src/utils/mod.rs", "rank": 41, "score": 126638.50695238983 }, { "content": "/// Format the given number of seconds as a digital duration.\n\npub fn digital_duration(duration: time::Duration) -> String {\n\n let mut parts = Vec::new();\n\n\n\n let p = partition(duration);\n\n\n\n parts.extend(match p.hours {\n\n 0 => None,\n\n n => Some(format!(\"{:02}\", n)),\n\n });\n\n\n\n parts.push(format!(\"{:02}\", p.minutes));\n\n parts.push(format!(\"{:02}\", p.seconds));\n\n\n\n parts.join(\":\")\n\n}\n\n\n", "file_path": "bot/src/utils/mod.rs", "rank": 42, "score": 126638.50695238983 }, { "content": "/// Decode a query string.\n\npub fn query_pairs(query: &str) -> QueryPairs<'_> {\n\n QueryPairs { query }\n\n}\n\n\n\npub struct QueryPairs<'a> {\n\n query: &'a str,\n\n}\n\n\n\nimpl<'a> Iterator for QueryPairs<'a> {\n\n type Item = (PercentDecode<'a>, Option<PercentDecode<'a>>);\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n use percent_encoding::percent_decode;\n\n\n\n if self.query.is_empty() {\n\n return None;\n\n }\n\n\n\n let s = match self.query.find('&') {\n\n Some(index) => {\n", "file_path": "bot/src/utils/mod.rs", "rank": 43, "score": 126638.50695238983 }, { "content": "/// Open the given directory.\n\nfn open_dir(path: &Path) -> io::Result<bool> {\n\n use self::convert::ToWide as _;\n\n\n\n let path = path.to_wide_null();\n\n let operation = \"open\".to_wide_null();\n\n\n\n let result = unsafe {\n\n ShellExecuteW(\n\n ptr::null_mut(),\n\n operation.as_ptr(),\n\n path.as_ptr(),\n\n ptr::null(),\n\n ptr::null(),\n\n SW_SHOW,\n\n )\n\n };\n\n\n\n Ok(result as usize > 32)\n\n}\n\n\n", "file_path": "bot/src/sys/windows/mod.rs", "rank": 44, "score": 124878.476245858 }, { "content": "pub fn for_uri(uri: String) -> Option<Offset> {\n\n Some(Offset {\n\n position: None,\n\n uri: Some(uri),\n\n })\n\n}\n", "file_path": "bot/src/api/spotify/model/offset.rs", "rank": 45, "score": 124854.20966643054 }, { "content": "pub fn for_position(position: u32) -> Option<Offset> {\n\n Some(Offset {\n\n position: Some(position),\n\n uri: None,\n\n })\n\n}\n\n\n", "file_path": "bot/src/api/spotify/model/offset.rs", "rank": 46, "score": 124854.20966643054 }, { "content": "#[derive(Clone)]\n\nstruct Promotions(injector::Ref<db::Promotions>);\n\n\n\nimpl Promotions {\n\n fn route(\n\n promotions: injector::Ref<db::Promotions>,\n\n ) -> filters::BoxedFilter<(impl warp::Reply,)> {\n\n let api = Promotions(promotions);\n\n\n\n let list = warp::get()\n\n .and(path!(\"promotions\" / Fragment).and(path::end()))\n\n .and_then({\n\n let api = api.clone();\n\n move |channel: Fragment| {\n\n let api = api.clone();\n\n async move { api.list(channel.as_str()).await.map_err(custom_reject) }\n\n }\n\n });\n\n\n\n let delete = warp::delete()\n\n .and(path!(\"promotions\" / Fragment / Fragment).and(path::end()))\n", "file_path": "bot/src/web/mod.rs", "rank": 47, "score": 124424.0407078125 }, { "content": "/// Format the given number as a string according to english conventions.\n\npub fn english_num(n: u64) -> Cow<'static, str> {\n\n let n = match n {\n\n 1 => \"one\",\n\n 2 => \"two\",\n\n 3 => \"three\",\n\n 4 => \"four\",\n\n 5 => \"five\",\n\n 6 => \"six\",\n\n 7 => \"seven\",\n\n 8 => \"eight\",\n\n 9 => \"nine\",\n\n n => return Cow::from(n.to_string()),\n\n };\n\n\n\n Cow::Borrowed(n)\n\n}\n\n\n", "file_path": "bot/src/utils/mod.rs", "rank": 48, "score": 123498.4158965326 }, { "content": "/// Format the given part and whole as a percentage.\n\npub fn percentage(part: u32, total: u32) -> Percentage {\n\n Percentage(part, total)\n\n}\n\n\n\nimpl fmt::Display for Percentage {\n\n fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n let Percentage(part, total) = *self;\n\n\n\n let total = match total {\n\n 0 => return write!(fmt, \"0%\"),\n\n total => total,\n\n };\n\n\n\n let p = (part * 10_000) / total;\n\n write!(fmt, \"{}\", p / 100)?;\n\n\n\n match p % 100 {\n\n 0 => (),\n\n n => write!(fmt, \".{}\", n)?,\n\n };\n\n\n\n fmt.write_str(\"%\")\n\n }\n\n}\n\n\n", "file_path": "bot/src/utils/mod.rs", "rank": 49, "score": 123498.4158965326 }, { "content": "fn print_impl(m: &str) {\n\n log::info!(\"[out]: {}\", m);\n\n}\n\n\n", "file_path": "bot/src/script/io.rs", "rank": 50, "score": 121796.05935296614 }, { "content": "fn println_impl(m: &str) {\n\n log::info!(\"[out]: {}\", m);\n\n}\n", "file_path": "bot/src/script/io.rs", "rank": 51, "score": 121796.05935296614 }, { "content": "#[derive(Clone)]\n\nstruct Database(db::Database);\n\n\n\nimpl Database {\n\n private_database_group_fns!(promotions, Promotion, Key);\n\n\n\n async fn edit(\n\n &self,\n\n key: &Key,\n\n frequency: utils::Duration,\n\n text: &str,\n\n ) -> Result<Option<db::models::Promotion>, anyhow::Error> {\n\n use db::schema::promotions::dsl;\n\n\n\n let key = key.clone();\n\n let text = text.to_string();\n\n\n\n self.0\n\n .asyncify(move |c| {\n\n let filter = dsl::promotions\n\n .filter(dsl::channel.eq(&key.channel).and(dsl::name.eq(&key.name)));\n", "file_path": "bot/src/db/promotions.rs", "rank": 52, "score": 121662.67125248892 }, { "content": "/// Spawn the given task in the background.\n\npub fn spawn<F>(future: F) -> Handle<F::Output>\n\nwhere\n\n F: Future + Send + 'static,\n\n F::Output: Send + 'static,\n\n{\n\n let handle = tokio::spawn(future);\n\n Handle { handle }\n\n}\n", "file_path": "bot/src/task.rs", "rank": 53, "score": 120822.47231741529 }, { "content": "/// Extract referer.\n\nfn referer<B>(req: &Request<B>) -> Result<Option<Url>, Error> {\n\n let referer = match req.headers().get(header::REFERER) {\n\n Some(referer) => referer,\n\n None => return Ok(None),\n\n };\n\n\n\n let referer = match std::str::from_utf8(referer.as_ref()) {\n\n Ok(referer) => referer,\n\n Err(_) => return Ok(None),\n\n };\n\n\n\n let referer = match referer.parse() {\n\n Ok(referer) => referer,\n\n Err(_) => return Ok(None),\n\n };\n\n\n\n Ok(Some(referer))\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n", "file_path": "web/src/web.rs", "rank": 54, "score": 116751.20856219289 }, { "content": "/// Render artists in a human readable form INCLUDING an oxford comma.\n\npub fn human_artists(artists: &[api::spotify::SimplifiedArtist]) -> Option<String> {\n\n if artists.is_empty() {\n\n return None;\n\n }\n\n\n\n let mut it = artists.iter();\n\n let mut artists = String::new();\n\n\n\n if let Some(artist) = it.next() {\n\n artists.push_str(artist.name.as_str());\n\n }\n\n\n\n let back = it.next_back();\n\n\n\n for artist in it {\n\n artists.push_str(\", \");\n\n artists.push_str(artist.name.as_str());\n\n }\n\n\n\n if let Some(artist) = back {\n\n artists.push_str(\", and \");\n\n artists.push_str(artist.name.as_str());\n\n }\n\n\n\n Some(artists)\n\n}\n\n\n", "file_path": "bot/src/utils/mod.rs", "rank": 55, "score": 115679.81939955828 }, { "content": "/// Handle device control requests.\n\nfn device_control<C>(status: StatusCode, _: &C) -> Result<Option<bool>> {\n\n match status {\n\n StatusCode::NO_CONTENT => Ok(Some(true)),\n\n StatusCode::NOT_FOUND => Ok(Some(false)),\n\n _ => Ok(None),\n\n }\n\n}\n\n\n\n/// A page converted into a stream which will perform pagination under the hood.\n\npub struct PageStream<T> {\n\n client: Client,\n\n token: oauth2::SyncToken,\n\n next: Option<BoxFuture<'static, Result<Page<T>>>>,\n\n}\n\n\n\nimpl<T> PageStream<T>\n\nwhere\n\n T: serde::de::DeserializeOwned,\n\n{\n\n /// Get the next page for a type.\n", "file_path": "bot/src/api/spotify/mod.rs", "rank": 56, "score": 111810.3040752114 }, { "content": "/// Create a zip distribution.\n\nfn create_zip_dist(dest: &Path, version: &Version, files: Vec<PathBuf>) -> Result<()> {\n\n if !dest.is_dir() {\n\n fs::create_dir_all(dest)?;\n\n }\n\n\n\n let zip_file = dest.join(format!(\n\n \"oxidize-{version}-{os}-{arch}.zip\",\n\n version = version,\n\n os = consts::OS,\n\n arch = consts::ARCH\n\n ));\n\n\n\n println!(\"Creating Zip File: {}\", zip_file.display());\n\n create_zip(&zip_file, files)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "tools/builder/src/main.rs", "rank": 57, "score": 110287.81863790899 }, { "content": "/// Common function to modify the balance for the given user.\n\nfn modify_balance(c: &SqliteConnection, channel: &str, user: &str, amount: i64) -> Result<()> {\n\n use self::schema::balances::dsl;\n\n\n\n let filter = dsl::balances.filter(dsl::channel.eq(channel).and(dsl::user.eq(user)));\n\n\n\n match filter.clone().first::<models::Balance>(&*c).optional()? {\n\n None => {\n\n let balance = models::Balance {\n\n channel: channel.to_string(),\n\n user: user.to_string(),\n\n amount,\n\n watch_time: 0,\n\n };\n\n\n\n diesel::insert_into(dsl::balances)\n\n .values(&balance)\n\n .execute(c)?;\n\n }\n\n Some(b) => {\n\n let amount = b.amount.saturating_add(amount);\n\n\n\n diesel::update(filter)\n\n .set(dsl::amount.eq(amount))\n\n .execute(c)?;\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "bot/src/currency/builtin.rs", "rank": 58, "score": 109798.95830576256 }, { "content": "/// Copy a bunch of files with the matching file extension from one directory to another.\n\nfn copy_files<F>(from: &Path, target: &Path, ext: &str, visitor: F) -> Result<()>\n\nwhere\n\n F: Fn(&Path) -> Result<()>,\n\n{\n\n if !target.is_dir() {\n\n fs::create_dir_all(target)?;\n\n }\n\n\n\n for e in WalkDir::new(from) {\n\n let e = e?;\n\n\n\n let source = e.path();\n\n\n\n if source.extension() != Some(OsStr::new(ext)) {\n\n continue;\n\n }\n\n\n\n let name = source.file_name().ok_or_else(|| anyhow!(\"no file name\"))?;\n\n let target = target.join(name);\n\n println!(\"{} -> {}\", source.display(), target.display());\n\n fs::copy(source, &target)?;\n\n visitor(&target)?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "tools/builder/src/main.rs", "rank": 59, "score": 108030.9610955033 }, { "content": "/// Connecting a bus to a websocket connection.\n\nfn send_bus<T>(bus: bus::Bus<T>) -> filters::BoxedFilter<(impl warp::Reply,)>\n\nwhere\n\n T: bus::Message,\n\n{\n\n warp::ws()\n\n .map({\n\n move |ws: warp::ws::Ws| {\n\n let bus = bus.clone();\n\n\n\n ws.on_upgrade(move |websocket: warp::filters::ws::WebSocket| async {\n\n if let Err(e) = send_bus_forward(bus, websocket).await {\n\n log_error!(e, \"websocket error\");\n\n }\n\n })\n\n }\n\n })\n\n .boxed()\n\n}\n\n\n\n/// Forward the bus message to the websocket.\n", "file_path": "bot/src/web/mod.rs", "rank": 60, "score": 105184.33236855223 }, { "content": "/// Serialize a regular expression.\n\nfn serialize_regex<S>(regex: &regex::Regex, s: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: serde::Serializer,\n\n{\n\n s.collect_str(regex)\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum Captures<'a> {\n\n Prefix { rest: &'a str },\n\n Regex { captures: regex::Captures<'a> },\n\n}\n\n\n\nimpl<'a> Captures<'a> {\n\n /// Get the number of captures.\n\n fn len(&self) -> usize {\n\n match self {\n\n Self::Prefix { .. } => 1,\n\n Self::Regex { captures, .. } => captures.len(),\n\n }\n", "file_path": "bot/src/db/matcher.rs", "rank": 61, "score": 104942.18286884508 }, { "content": "/// Serialize the atomic count.\n\nfn serialize_count<S>(value: &Arc<AtomicUsize>, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: serde::Serializer,\n\n{\n\n use serde::Serialize as _;\n\n\n\n value\n\n .load(std::sync::atomic::Ordering::SeqCst)\n\n .serialize(serializer)\n\n}\n\n\n\nimpl Command {\n\n pub const NAME: &'static str = \"command\";\n\n\n\n /// Load a command from the database.\n\n pub fn from_db(command: &db::models::Command) -> Result<Command, Error> {\n\n let template = template::Template::compile(&command.text)\n\n .with_context(|| anyhow!(\"failed to compile command `{:?}` from db\", command))?;\n\n\n\n let key = db::Key::new(&command.channel, &command.name);\n", "file_path": "bot/src/db/commands.rs", "rank": 62, "score": 102063.53724573074 }, { "content": "/// The future that drives a synchronized variable.\n\nstruct Driver {\n\n future: Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>>,\n\n}\n\n\n\nimpl Future for Driver {\n\n type Output = ();\n\n\n\n fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {\n\n self.future.as_mut().poll(cx)\n\n }\n\n}\n\n\n\npub struct Inner<S>\n\nwhere\n\n S: Scope,\n\n{\n\n db: db::Database,\n\n /// Maps setting prefixes to subscriptions.\n\n subscriptions: HashMap<Box<str>, broadcast::Sender<Update>>,\n\n /// Schema for every corresponding type.\n", "file_path": "bot/src/settings.rs", "rank": 63, "score": 85607.86937649589 }, { "content": "#[derive(Default)]\n\nstruct Prefix {\n\n /// All keys that belongs to the given prefix.\n\n keys: Vec<String>,\n\n}\n\n\n", "file_path": "bot/src/settings.rs", "rank": 64, "score": 85607.86937649589 }, { "content": "struct Inner {\n\n db: db::Database,\n\n /// Schema for every corresponding scope.\n\n schema: Schema,\n\n /// Assignments.\n\n grants: RwLock<HashSet<(Scope, Role)>>,\n\n /// Temporary grants.\n\n temporary_grants: RwLock<Vec<TemporaryGrant>>,\n\n}\n\n\n\n/// A container for scopes and their grants.\n\n#[derive(Clone)]\n\npub struct Auth {\n\n inner: Arc<Inner>,\n\n}\n\n\n\nimpl Auth {\n\n pub async fn new(db: db::Database, schema: Schema) -> Result<Self, Error> {\n\n use db::schema::grants::dsl;\n\n\n", "file_path": "bot/src/auth.rs", "rank": 65, "score": 85607.86937649589 }, { "content": "struct Inner {\n\n cache: Cache,\n\n ffz: FrankerFaceZ,\n\n bttv: BetterTTV,\n\n tduva: Tduva,\n\n tduva_data: RwLock<Option<TduvaData>>,\n\n twitch: Twitch,\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct Emotes {\n\n inner: Arc<Inner>,\n\n}\n\n\n\nimpl Emotes {\n\n /// Construct a new emoticon handler.\n\n pub fn new(cache: Cache, twitch: Twitch) -> Result<Self, Error> {\n\n Ok(Self {\n\n inner: Arc::new(Inner {\n\n cache: cache.namespaced(&\"emotes\")?,\n", "file_path": "bot/src/emotes.rs", "rank": 66, "score": 85607.86937649589 }, { "content": "/// Configure logging.\n\nfn setup_logs(\n\n root: &Path,\n\n log_config: Option<PathBuf>,\n\n default_log_file: &Path,\n\n trace: bool,\n\n modules: &[String],\n\n) -> Result<()> {\n\n let file = log_config.unwrap_or_else(|| root.join(\"log4rs.yaml\"));\n\n\n\n if !file.is_file() {\n\n let config = default_log_config(default_log_file, trace, modules)?;\n\n log4rs::init_config(config)?;\n\n } else {\n\n log4rs::init_file(file, Default::default())?;\n\n }\n\n\n\n tracing_config()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "bot/src/main.rs", "rank": 67, "score": 84430.9433798214 }, { "content": "#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]\n\nstruct Status {\n\n status: u32,\n\n}\n", "file_path": "bot/src/api/nightbot.rs", "rank": 68, "score": 84390.09519985973 }, { "content": "struct Timer {\n\n duration: utils::Duration,\n\n elapsed: utils::Duration,\n\n interval: tokio::time::Interval,\n\n}\n\n\n\nimpl stream::Stream for Timer {\n\n type Item = ();\n\n\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {\n\n match Pin::new(&mut self.as_mut().interval).poll_tick(cx) {\n\n Poll::Pending => return Poll::Pending,\n\n Poll::Ready(..) => (),\n\n }\n\n\n\n self.as_mut().elapsed += utils::Duration::seconds(1);\n\n\n\n if self.as_ref().elapsed >= self.as_ref().duration {\n\n return Poll::Ready(None);\n\n }\n\n\n\n Poll::Ready(Some(()))\n\n }\n\n}\n", "file_path": "bot/src/module/countdown.rs", "rank": 69, "score": 84390.09519985973 }, { "content": "#[derive(Provider)]\n\nstruct Setup {\n\n #[dependency]\n\n db: db::Database,\n\n #[dependency(tag = \"tags::Twitch::Bot\")]\n\n bot: api::TwitchAndUser,\n\n #[dependency(tag = \"tags::Twitch::Streamer\")]\n\n streamer: api::TwitchAndUser,\n\n #[dependency]\n\n auth: Auth,\n\n #[dependency]\n\n bad_words: db::Words,\n\n #[dependency]\n\n message_log: MessageLog,\n\n #[dependency]\n\n command_bus: bus::Bus<bus::Command>,\n\n #[dependency]\n\n global_bus: bus::Bus<bus::Global>,\n\n #[dependency]\n\n settings: crate::Settings,\n\n #[dependency]\n\n restart: utils::Restart,\n\n}\n\n\n", "file_path": "bot/src/irc/mod.rs", "rank": 70, "score": 84390.09519985973 }, { "content": "#[derive(Any)]\n\nstruct Registry {\n\n handlers: HashMap<String, SyncFunction>,\n\n}\n\n\n\nimpl Registry {\n\n /// Construct a new registry.\n\n fn new() -> Self {\n\n Self {\n\n handlers: Default::default(),\n\n }\n\n }\n\n\n\n /// Register the given handler.\n\n fn register(&mut self, name: &str, handler: SyncFunction) {\n\n self.handlers.insert(name.to_owned(), handler);\n\n }\n\n}\n\n\n", "file_path": "bot/src/script/mod.rs", "rank": 71, "score": 84390.09519985973 }, { "content": "struct Queries {\n\n schema: Schema,\n\n}\n\n\n\nimpl Queries {\n\n /// Select all balances.\n\n async fn select_balances<Tx>(&self, tx: &mut Tx) -> Result<Vec<(String, i32)>>\n\n where\n\n Tx: Queryable,\n\n {\n\n let query = format!(\n\n \"SELECT (`{user_column}`, `{balance_column}`) FROM `{table}`\",\n\n table = self.schema.table,\n\n balance_column = self.schema.balance_column,\n\n user_column = self.schema.user_column,\n\n );\n\n\n\n log::trace!(\"select_balances: {}\", query);\n\n let results = tx\n\n .exec_map(query.as_str(), (), mysql::from_row::<(String, i32)>)\n", "file_path": "bot/src/currency/mysql.rs", "rank": 72, "score": 84390.09519985973 }, { "content": "#[derive(Clone)]\n\nstruct Api {\n\n player: injector::Ref<player::Player>,\n\n after_streams: injector::Ref<db::AfterStreams>,\n\n currency: injector::Ref<Currency>,\n\n latest: crate::settings::Var<Option<api::github::Release>>,\n\n}\n\n\n\n#[derive(Clone, serde::Serialize, serde::Deserialize)]\n\npub struct Balance {\n\n name: String,\n\n #[serde(default)]\n\n balance: i64,\n\n #[serde(default)]\n\n watch_time: i64,\n\n}\n\n\n\nimpl Api {\n\n /// Handle request to set device.\n\n async fn set_device(self, id: String) -> Result<impl warp::Reply, Error> {\n\n let player = self.player.read().await;\n", "file_path": "bot/src/web/mod.rs", "rank": 73, "score": 84390.09519985973 }, { "content": "#[derive(Default)]\n\nstruct Remote {\n\n rx: Option<bus::Reader<bus::Global>>,\n\n player: Option<player::Player>,\n\n setbac: Option<Setbac>,\n\n}\n\n\n\n/// Run update loop shipping information to the remote server.\n\npub async fn run(\n\n settings: &crate::Settings,\n\n injector: &Injector,\n\n global_bus: bus::Bus<bus::Global>,\n\n) -> Result<impl Future<Output = Result<()>>> {\n\n let settings = settings.scoped(\"remote\");\n\n\n\n let (mut api_url_stream, api_url) = settings\n\n .stream(\"api-url\")\n\n .or(Some(String::from(DEFAULT_API_URL)))\n\n .optional()\n\n .await?;\n\n\n", "file_path": "bot/src/api/setbac.rs", "rank": 74, "score": 84390.09519985973 }, { "content": "struct RequestBuilder {\n\n client: Client,\n\n method: Method,\n\n url: Url,\n\n headers: Vec<(header::HeaderName, String)>,\n\n body: Option<Bytes>,\n\n}\n\n\n\nimpl RequestBuilder {\n\n /// Create a new request.\n\n pub fn new(client: Client, method: Method, url: Url) -> Self {\n\n RequestBuilder {\n\n client,\n\n method,\n\n url,\n\n headers: Vec::new(),\n\n body: None,\n\n }\n\n }\n\n\n", "file_path": "web/src/api.rs", "rank": 75, "score": 84390.09519985973 }, { "content": "struct ConnectionFactory {\n\n setbac: Option<Setbac>,\n\n flow_id: &'static str,\n\n what: &'static str,\n\n expires: time::Duration,\n\n force_refresh: bool,\n\n connection: Option<Connection>,\n\n sync_token: SyncToken,\n\n settings: crate::Settings,\n\n injector: Injector,\n\n key: Key<SyncToken>,\n\n server: web::Server,\n\n current_hash: Option<String>,\n\n}\n\n\n", "file_path": "bot/src/oauth2.rs", "rank": 76, "score": 84390.09519985973 }, { "content": "#[derive(Debug, Error)]\n\n#[error(\"failed to commit\")]\n\nstruct CommitError;\n\n\n\n#[derive(Serialize, Deserialize)]\n\npub struct Connection {\n\n pub id: String,\n\n #[serde(default = \"meta_default\", skip_serializing_if = \"meta_is_null\")]\n\n pub meta: serde_cbor::Value,\n\n pub token: oauth2::SavedToken,\n\n}\n\n\n", "file_path": "web/src/db.rs", "rank": 77, "score": 84390.09519985973 }, { "content": "#[derive(Clone)]\n\nstruct Db {\n\n db: db::ScriptStorage,\n\n}\n\n\n\nimpl Db {\n\n async fn open(channel: String, db: db::Database) -> Result<Self> {\n\n Ok(Self {\n\n db: db::ScriptStorage::load(channel, db).await?,\n\n })\n\n }\n\n\n\n /// Scope the db.\n\n fn scoped(&self, command: &str) -> ScopedDb {\n\n ScopedDb {\n\n command: command.to_owned(),\n\n db: self.db.clone(),\n\n }\n\n }\n\n}\n\n\n\n/// A database scoped into a single command.\n", "file_path": "bot/src/script/mod.rs", "rank": 78, "score": 84390.09519985973 }, { "content": "#[derive(Clone)]\n\nstruct Auth {\n\n active_connections: Arc<RwLock<HashMap<String, ConnectionMeta>>>,\n\n auth: auth::Auth,\n\n settings: injector::Ref<crate::Settings>,\n\n}\n\n\n\n#[derive(serde::Deserialize)]\n\npub struct AuthKeyQuery {\n\n #[serde(default)]\n\n key: Option<Fragment>,\n\n}\n\n\n\nimpl Auth {\n\n fn route(\n\n auth: auth::Auth,\n\n active_connections: Arc<RwLock<HashMap<String, ConnectionMeta>>>,\n\n settings: injector::Ref<crate::Settings>,\n\n ) -> filters::BoxedFilter<(impl warp::Reply,)> {\n\n let api = Auth {\n\n auth,\n", "file_path": "bot/src/web/mod.rs", "rank": 79, "score": 84390.09519985973 }, { "content": "struct Inner {\n\n target: String,\n\n sender: client::Sender,\n\n limiter: LeakyBucket,\n\n nightbot_limiter: LeakyBucket,\n\n nightbot: injector::Ref<api::NightBot>,\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct Sender {\n\n ty: settings::Var<Type>,\n\n inner: Arc<Inner>,\n\n}\n\n\n\nimpl Sender {\n\n /// Create a new sender.\n\n pub fn new(\n\n ty: settings::Var<Type>,\n\n target: String,\n\n sender: client::Sender,\n", "file_path": "bot/src/irc/sender.rs", "rank": 80, "score": 84390.09519985973 }, { "content": "#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]\n\nstruct TduvaBadge {\n\n id: String,\n\n version: String,\n\n image_url: String,\n\n color: Option<String>,\n\n title: String,\n\n usernames: HashSet<String>,\n\n}\n\n\n", "file_path": "bot/src/emotes.rs", "rank": 81, "score": 84390.09519985973 }, { "content": "#[derive(Debug, Clone, Default, Serialize, Deserialize)]\n\nstruct TokenMeta {\n\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n\n login: Option<String>,\n\n}\n\n\n", "file_path": "web/src/web.rs", "rank": 82, "score": 84390.09519985973 }, { "content": "#[derive(Debug, Default)]\n\nstruct Inner {\n\n hashed: HashMap<eudex::Hash, Arc<Word>>,\n\n exact: HashMap<String, Arc<Word>>,\n\n}\n\n\n\nimpl Inner {\n\n /// Insert a bad word.\n\n fn insert(&mut self, word: &str, why: Option<&str>) -> Result<(), anyhow::Error> {\n\n let word = Word {\n\n word: tokenize(word),\n\n why: why.map(template::Template::compile).transpose()?,\n\n };\n\n\n\n let word = Arc::new(word);\n\n self.hashed\n\n .insert(eudex::Hash::new(&word.word), Arc::clone(&word));\n\n self.exact.insert(word.word.to_string(), Arc::clone(&word));\n\n Ok(())\n\n }\n\n\n\n /// Insert a bad word.\n\n fn remove(&mut self, word: &str) {\n\n let word = tokenize(word);\n\n\n\n // TODO: there might be hash conflicts. Deal with them.\n\n self.hashed.remove(&eudex::Hash::new(&word));\n\n self.exact.remove(&word);\n\n }\n\n}\n\n\n", "file_path": "bot/src/db/words.rs", "rank": 83, "score": 84390.09519985973 }, { "content": "struct Inner {\n\n voted: HashSet<String>,\n\n votes: HashMap<String, u32>,\n\n}\n\n\n", "file_path": "bot/src/module/poll.rs", "rank": 84, "score": 84390.09519985973 }, { "content": "/// A grant that has been temporarily given.\n\nstruct TemporaryGrant {\n\n pub scope: Scope,\n\n pub principal: RoleOrUser,\n\n pub expires_at: DateTime<Utc>,\n\n}\n\n\n\nimpl TemporaryGrant {\n\n /// Test if the grant is expired.\n\n pub fn is_expired(&self, now: &DateTime<Utc>) -> bool {\n\n *now >= self.expires_at\n\n }\n\n}\n\n\n", "file_path": "bot/src/auth.rs", "rank": 85, "score": 84390.09519985973 }, { "content": "#[derive(Default, serde::Serialize)]\n\nstruct Empty {}\n\n\n\nconst EMPTY: Empty = Empty {};\n\n\n", "file_path": "bot/src/web/mod.rs", "rank": 86, "score": 84390.09519985973 }, { "content": "#[derive(Default)]\n\nstruct TduvaData {\n\n chatty: Vec<TduvaBadge>,\n\n}\n\n\n", "file_path": "bot/src/emotes.rs", "rank": 87, "score": 84390.09519985973 }, { "content": "struct Inner {\n\n backend: Backend,\n\n twitch: api::Twitch,\n\n}\n\n\n\n/// The currency being used.\n\n#[derive(Clone)]\n\npub struct Currency {\n\n pub name: Arc<String>,\n\n pub command_enabled: bool,\n\n inner: Arc<Inner>,\n\n}\n\n\n\nimpl Currency {\n\n /// Reward all users.\n\n pub async fn add_channel_all(\n\n &self,\n\n channel: &str,\n\n reward: i64,\n\n watch_time: i64,\n", "file_path": "bot/src/currency/mod.rs", "rank": 88, "score": 84390.09519985973 }, { "content": "#[derive(Debug, Clone)]\n\nstruct Version {\n\n base: String,\n\n major: u32,\n\n minor: u32,\n\n patch: u32,\n\n pre: Option<u32>,\n\n}\n\n\n\nimpl Version {\n\n /// Open a version by matching it against the given string.\n\n pub fn open(version: impl AsRef<str>) -> Result<Option<Version>> {\n\n let version_re = Regex::new(r\"^(\\d+)\\.(\\d+)\\.(\\d+)(-.+\\.(\\d+))?$\")?;\n\n let version = version.as_ref();\n\n\n\n let m = match version_re.captures(version) {\n\n Some(m) => m,\n\n None => return Ok(None),\n\n };\n\n\n\n let major: u32 = str::parse(&m[1])?;\n", "file_path": "tools/builder/src/main.rs", "rank": 89, "score": 84390.09519985973 }, { "content": "#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]\n\nstruct Message {\n\n message: String,\n\n}\n\n\n", "file_path": "bot/src/api/nightbot.rs", "rank": 90, "score": 84390.09519985973 }, { "content": "/// Setup a default logging configuration if none is specified.\n\nfn default_log_config(\n\n log_path: &Path,\n\n trace: bool,\n\n modules: &[String],\n\n) -> Result<log4rs::config::Config> {\n\n use self::internal::{config_builder, logger_builder, root_builder};\n\n use log::LevelFilter;\n\n use log4rs::{append::file::FileAppender, config::Appender, encode::pattern::PatternEncoder};\n\n\n\n let pattern = PatternEncoder::new(\"{d(%Y-%m-%dT%H:%M:%S%.3f%Z)} {l:5.5} {t} - {m}{n}\");\n\n\n\n let mut config = config_builder().appender(\n\n Appender::builder().build(\n\n FILE,\n\n Box::new(\n\n FileAppender::builder()\n\n .encoder(Box::new(pattern))\n\n .build(log_path)?,\n\n ),\n\n ),\n", "file_path": "bot/src/main.rs", "rank": 91, "score": 83269.7251300693 }, { "content": "/// Inner struct for User to make it cheaper to clone.\n\nstruct UserInner {\n\n tags: Tags,\n\n sender: Sender,\n\n principal: Principal,\n\n streamer: Arc<twitch::v5::User>,\n\n moderators: Arc<RwLock<HashSet<String>>>,\n\n vips: Arc<RwLock<HashSet<String>>>,\n\n stream_info: stream_info::StreamInfo,\n\n auth: Auth,\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct User {\n\n inner: Arc<UserInner>,\n\n}\n\n\n\nimpl User {\n\n /// Access the user as a real user.\n\n pub fn real(&self) -> Option<RealUser<'_>> {\n\n match self.inner.principal {\n", "file_path": "bot/src/irc/mod.rs", "rank": 92, "score": 83234.54264579949 }, { "content": "struct RemoteBuilder {\n\n streamer_token: Option<oauth2::SyncToken>,\n\n injector: Injector,\n\n global_bus: bus::Bus<bus::Global>,\n\n player: Option<Player>,\n\n enabled: bool,\n\n api_url: Option<Url>,\n\n secret_key: Option<String>,\n\n}\n\n\n\nimpl RemoteBuilder {\n\n async fn init(&self, remote: &mut Remote) {\n\n if self.enabled {\n\n remote.rx = Some(self.global_bus.subscribe());\n\n\n\n remote.player = match self.player.as_ref() {\n\n Some(player) => Some(player.clone()),\n\n None => None,\n\n };\n\n } else {\n", "file_path": "bot/src/api/setbac.rs", "rank": 93, "score": 83229.06463539616 }, { "content": "struct Client {\n\n stream: WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>,\n\n}\n\n\n\nimpl Client {\n\n /// Send a message.\n\n async fn send(&mut self, frame: self::transport::Frame) -> Result<()> {\n\n use futures_util::SinkExt as _;\n\n\n\n let text = serde_json::to_string(&frame)?;\n\n log::trace!(\">> {:?}\", frame);\n\n let message = tungstenite::Message::Text(text);\n\n self.stream.send(message).await?;\n\n Ok(())\n\n }\n\n\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Result<String>>> {\n\n use crate::stream::Stream as _;\n\n\n\n loop {\n", "file_path": "bot/src/api/twitch/pubsub.rs", "rank": 94, "score": 83229.06463539616 }, { "content": "#[derive(Debug)]\n\nstruct CommandSetting {\n\n enabled: bool,\n\n cooldown: Option<settings::Var<Cooldown>>,\n\n cost: Option<u32>,\n\n}\n\n\n\nimpl Default for CommandSetting {\n\n fn default() -> Self {\n\n CommandSetting {\n\n enabled: true,\n\n cooldown: None,\n\n cost: None,\n\n }\n\n }\n\n}\n\n\n\nimpl CommandsConfig {\n\n fn into_map(self) -> HashMap<String, CommandSetting> {\n\n let mut m = HashMap::new();\n\n\n", "file_path": "bot/src/module/gtav.rs", "rank": 95, "score": 83229.06463539616 }, { "content": "struct Inner {\n\n redemptions: broadcast::Sender<Redemption>,\n\n}\n\n\n\npub(crate) mod transport {\n\n use serde::{Deserialize, Serialize};\n\n use std::fmt;\n\n\n\n #[derive(Debug, Clone, Serialize, Deserialize)]\n\n #[serde(tag = \"type\")]\n\n pub(crate) enum Frame {\n\n #[serde(rename = \"PING\")]\n\n Ping,\n\n #[serde(rename = \"PONG\")]\n\n Pong,\n\n #[serde(rename = \"LISTEN\")]\n\n Listen(Data<Listen>),\n\n #[serde(rename = \"RESPONSE\")]\n\n Response(Response),\n\n #[serde(rename = \"MESSAGE\")]\n", "file_path": "bot/src/api/twitch/pubsub.rs", "rank": 96, "score": 83229.06463539616 }, { "content": "#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]\n\nstruct CommandConfig {\n\n name: String,\n\n #[serde(default)]\n\n enabled: Option<bool>,\n\n #[serde(default)]\n\n cooldown: Option<Duration>,\n\n #[serde(default)]\n\n cost: Option<u32>,\n\n}\n\n\n", "file_path": "bot/src/module/gtav.rs", "rank": 97, "score": 83229.06463539616 }, { "content": "#[derive(Default)]\n\nstruct FileWriter {\n\n path: Option<PathBuf>,\n\n template: Option<template::Template>,\n\n}\n\n\n\nimpl FileWriter {\n\n fn write(&self, timer: &Timer) -> Result<(), anyhow::Error> {\n\n let path = match &self.path {\n\n Some(path) => path,\n\n None => return Ok(()),\n\n };\n\n\n\n let template = match &self.template {\n\n Some(template) => template,\n\n None => return Ok(()),\n\n };\n\n\n\n log::trace!(\"Writing to log: {}\", path.display());\n\n\n\n let mut f = fs::File::create(path)?;\n", "file_path": "bot/src/module/countdown.rs", "rank": 98, "score": 83229.06463539616 }, { "content": "struct State {\n\n enabled: bool,\n\n ws: TwitchPubSub,\n\n client: Fuse<Client>,\n\n streamer: Option<api::TwitchAndUser>,\n\n ping_interval: Fuse<Interval>,\n\n pong_deadline: Fuse<Pin<Box<Sleep>>>,\n\n reconnect: Fuse<Pin<Box<Sleep>>>,\n\n reconnect_backoff: backoff::ExponentialBackoff,\n\n}\n\n\n\nimpl State {\n\n /// Disconnect and clear client (if connected).\n\n async fn disconnect(&mut self) {\n\n if let Some(client) = self.client.as_inner_mut() {\n\n if let Err(e) = client.stream.close(None).await {\n\n log_error!(e, \"error when closing stream\");\n\n }\n\n\n\n log::info!(\"Disconnected from Twitch Pub/Sub!\");\n", "file_path": "bot/src/api/twitch/pubsub.rs", "rank": 99, "score": 83229.06463539616 } ]
Rust
system/kernel/src/mem/mm.rs
meg-os/maystorm
e1709de563f0d356898ad9681d29c630efea97e4
use super::slab::*; use crate::{ arch::cpu::Cpu, arch::page::*, sync::{fifo::EventQueue, semaphore::Semaphore}, system::System, task::scheduler::*, }; use alloc::{boxed::Box, sync::Arc}; use bitflags::*; use bootprot::*; use core::{ alloc::Layout, ffi::c_void, fmt::Write, mem::MaybeUninit, mem::{size_of, transmute}, num::*, slice, sync::atomic::*, }; use megstd::string::*; pub use crate::arch::page::{NonNullPhysicalAddress, PhysicalAddress}; static mut MM: MemoryManager = MemoryManager::new(); pub struct MemoryManager { reserved_memory_size: usize, page_size_min: usize, dummy_size: AtomicUsize, n_free: AtomicUsize, pairs: [MemFreePair; Self::MAX_FREE_PAIRS], slab: Option<Box<SlabAllocator>>, real_bitmap: [u32; 8], fifo: MaybeUninit<EventQueue<Arc<AsyncMmapRequest>>>, } impl MemoryManager { const MAX_FREE_PAIRS: usize = 1024; pub const PAGE_SIZE_MIN: usize = 0x1000; const fn new() -> Self { Self { reserved_memory_size: 0, page_size_min: 0x1000, dummy_size: AtomicUsize::new(0), n_free: AtomicUsize::new(0), pairs: [MemFreePair::empty(); Self::MAX_FREE_PAIRS], slab: None, real_bitmap: [0; 8], fifo: MaybeUninit::uninit(), } } pub unsafe fn init_first(info: &BootInfo) { let shared = Self::shared_mut(); let mm: &[BootMemoryMapDescriptor] = slice::from_raw_parts(info.mmap_base as usize as *const _, info.mmap_len as usize); let mut free_count = 0; let mut n_free = 0; for mem_desc in mm { if mem_desc.mem_type == BootMemoryType::Available { let size = mem_desc.page_count as usize * Self::PAGE_SIZE_MIN; shared.pairs[n_free] = MemFreePair::new(mem_desc.base as usize, size); free_count += size; } n_free += 1; } shared.n_free.store(n_free, Ordering::SeqCst); shared.reserved_memory_size = info.total_memory_size as usize - free_count; if cfg!(any(target_arch = "x86_64")) { shared.real_bitmap = info.real_bitmap; } PageManager::init(info); shared.slab = Some(Box::new(SlabAllocator::new())); shared.fifo.write(EventQueue::new(100)); } pub unsafe fn late_init() { PageManager::init_late(); SpawnOption::with_priority(Priority::Realtime).start(Self::page_thread, 0, "Page Manager"); } #[allow(dead_code)] fn page_thread(_args: usize) { let shared = Self::shared(); let fifo = unsafe { &*shared.fifo.as_ptr() }; while let Some(event) = fifo.wait_event() { let result = unsafe { PageManager::mmap(event.request) }; PageManager::broadcast_invalidate_tlb().unwrap(); event.result.store(result, Ordering::SeqCst); event.sem.signal(); } } #[inline] fn shared_mut() -> &'static mut Self { unsafe { &mut MM } } #[inline] pub fn shared() -> &'static Self { unsafe { &MM } } #[inline] pub unsafe fn mmap(request: MemoryMapRequest) -> Option<NonZeroUsize> { if Scheduler::is_enabled() { let fifo = &*Self::shared().fifo.as_ptr(); let event = Arc::new(AsyncMmapRequest { request, result: AtomicUsize::new(0), sem: Semaphore::new(0), }); let _ = fifo.post(event.clone()); event.sem.wait(); NonZeroUsize::new(event.result.load(Ordering::SeqCst)) } else { NonZeroUsize::new(PageManager::mmap(request)) } } #[inline] pub fn direct_map(pa: PhysicalAddress) -> usize { PageManager::direct_map(pa) } #[inline] pub unsafe fn invalidate_cache(p: usize) { PageManager::invalidate_cache(p); } #[inline] pub fn page_size_min(&self) -> usize { self.page_size_min } #[inline] pub fn reserved_memory_size() -> usize { let shared = Self::shared_mut(); shared.reserved_memory_size } #[inline] pub fn free_memory_size() -> usize { let shared = Self::shared_mut(); let mut total = shared.dummy_size.load(Ordering::Relaxed); total += shared .slab .as_ref() .map(|v| v.free_memory_size()) .unwrap_or(0); total += shared.pairs[..shared.n_free.load(Ordering::Relaxed)] .iter() .fold(0, |v, i| v + i.size()); total } pub unsafe fn pg_alloc(layout: Layout) -> Option<NonZeroUsize> { let shared = Self::shared_mut(); let align_m1 = Self::PAGE_SIZE_MIN - 1; let size = (layout.size() + align_m1) & !(align_m1); let n_free = shared.n_free.load(Ordering::SeqCst); for i in 0..n_free { let free_pair = &shared.pairs[i]; match free_pair.alloc(size) { Ok(v) => return Some(NonZeroUsize::new_unchecked(v)), Err(_) => (), } } None } #[inline] pub unsafe fn alloc_pages(size: usize) -> Option<NonZeroUsize> { let result = Self::pg_alloc(Layout::from_size_align_unchecked(size, Self::PAGE_SIZE_MIN)); if let Some(p) = result { let p = PageManager::direct_map(p.get() as PhysicalAddress) as *const c_void as *mut c_void; p.write_bytes(0, size); } result } pub unsafe fn zalloc(layout: Layout) -> Option<NonZeroUsize> { let shared = Self::shared_mut(); if let Some(slab) = &shared.slab { match slab.alloc(layout) { Ok(result) => return Some(result), Err(AllocationError::Unsupported) => (), Err(_err) => return None, } } Self::pg_alloc(layout) .and_then(|v| NonZeroUsize::new(PageManager::direct_map(v.get() as PhysicalAddress))) } pub unsafe fn zfree( base: Option<NonZeroUsize>, layout: Layout, ) -> Result<(), DeallocationError> { if let Some(base) = base { let ptr = base.get() as *mut u8; ptr.write_bytes(0xCC, layout.size()); let shared = Self::shared_mut(); if let Some(slab) = &shared.slab { match slab.free(base, layout) { Ok(_) => Ok(()), Err(_) => { shared.dummy_size.fetch_add(layout.size(), Ordering::SeqCst); Ok(()) } } } else { shared.dummy_size.fetch_add(layout.size(), Ordering::SeqCst); Ok(()) } } else { Ok(()) } } pub unsafe fn static_alloc_real() -> Option<NonZeroU8> { let max_real = 0xA0; let shared = Self::shared_mut(); for i in 1..max_real { let result = Cpu::interlocked_test_and_clear( &*(&shared.real_bitmap[0] as *const _ as *const AtomicUsize), i, ); if result { return NonZeroU8::new(i as u8); } } None } pub fn statistics(sb: &mut StringBuffer) { let shared = Self::shared_mut(); sb.clear(); let dummy = shared.dummy_size.load(Ordering::Relaxed); let free = shared.pairs[..shared.n_free.load(Ordering::Relaxed)] .iter() .fold(0, |v, i| v + i.size()); let total = free + dummy; writeln!( sb, "Memory {} MB Pages {} ({} + {})", System::current_device().total_memory_size() >> 20, total / Self::PAGE_SIZE_MIN, free / Self::PAGE_SIZE_MIN, dummy / Self::PAGE_SIZE_MIN, ) .unwrap(); for chunk in shared.slab.as_ref().unwrap().statistics().chunks(4) { write!(sb, "Slab").unwrap(); for item in chunk { write!(sb, " {:4}: {:4}/{:4}", item.0, item.1, item.2,).unwrap(); } writeln!(sb, "").unwrap(); } } } struct AsyncMmapRequest { request: MemoryMapRequest, result: AtomicUsize, sem: Semaphore, } #[derive(Debug, Clone, Copy)] struct MemFreePair { inner: u64, } impl MemFreePair { const PAGE_SIZE: usize = 0x1000; #[inline] pub const fn empty() -> Self { Self { inner: 0 } } #[inline] pub const fn new(base: usize, size: usize) -> Self { let base = (base / Self::PAGE_SIZE) as u64; let size = (size / Self::PAGE_SIZE) as u64; Self { inner: base | (size << 32), } } #[inline] pub fn alloc(&self, size: usize) -> Result<usize, ()> { let size = (size + Self::PAGE_SIZE - 1) / Self::PAGE_SIZE; let p: &AtomicU64 = unsafe { transmute(&self.inner) }; let mut data = p.load(Ordering::SeqCst); loop { let (base, limit) = ((data & 0xFFFF_FFFF) as usize, (data >> 32) as usize); if limit < size { return Err(()); } let new_size = limit - size; let new_data = (base as u64) | ((new_size as u64) << 32); data = match p.compare_exchange(data, new_data, Ordering::SeqCst, Ordering::Relaxed) { Ok(_) => return Ok((base + new_size) * Self::PAGE_SIZE), Err(v) => v, }; } } #[inline] fn split(&self) -> (usize, usize) { let p: &AtomicU64 = unsafe { transmute(&self.inner) }; let data = p.load(Ordering::SeqCst); ((data & 0xFFFF_FFFF) as usize, (data >> 32) as usize) } #[inline] #[allow(dead_code)] pub fn base(&self) -> usize { self.split().0 * Self::PAGE_SIZE } #[inline] pub fn size(&self) -> usize { self.split().1 * Self::PAGE_SIZE } } bitflags! { pub struct MProtect: usize { const READ = 0x4; const WRITE = 0x2; const EXEC = 0x1; const NONE = 0x0; const READ_WRITE = Self::READ.bits | Self::WRITE.bits; const READ_EXEC = Self::READ.bits | Self::WRITE.bits; } } #[derive(Debug, Copy, Clone)] pub enum AllocationError { Unexpected, OutOfMemory, InvalidArgument, Unsupported, } #[derive(Debug, Copy, Clone)] pub enum DeallocationError { Unexpected, InvalidArgument, Unsupported, } #[derive(Debug, Clone, Copy)] pub enum MemoryMapRequest { Mmio(PhysicalAddress, usize), Vram(PhysicalAddress, usize), Kernel(usize, usize, MProtect), User(usize, usize, MProtect), } impl MemoryMapRequest { #[allow(dead_code)] fn to_slice(&self) -> &[u8] { unsafe { slice::from_raw_parts(&self as *const _ as *const u8, size_of::<Self>()) } } }
use super::slab::*; use crate::{ arch::cpu::Cpu, arch::page::*, sync::{fifo::EventQueue, semaphore::Semaphore}, system::System, task::scheduler::*, }; use alloc::{boxed::Box, sync::Arc}; use bitflags::*; use bootprot::*; use core::{ alloc::Layout, ffi::c_void, fmt::Write, mem::MaybeUninit, mem::{size_of, transmute}, num::*, slice, sync::atomic::*, }; use megstd::string::*; pub use crate::arch::page::{NonNullPhysicalAddress, PhysicalAddress}; static mut MM: MemoryManager = MemoryManager::new(); pub struct MemoryManager { reserved_memory_size: usize, page_size_min: usize, dummy_size: AtomicUsize, n_free: AtomicUsize, pairs: [MemFreePair; Self::MAX_FREE_PAIRS], slab: Option<Box<SlabAllocator>>, real_bitmap: [u32; 8], fifo: MaybeUninit<EventQueue<Arc<AsyncMmapRequest>>>, } impl MemoryManager { const MAX_FREE_PAIRS: usize = 1024; pub const PAGE_SIZE_MIN: usize = 0x1000; const fn new() -> Self { Self { reserved_memory_size: 0, page_size_min: 0x1000, dummy_size: AtomicUsize::new(0), n_free: AtomicUsize::new(0), pairs: [MemFreePair::empty(); Self::MAX_FREE_PAIRS], slab: None, real_bitmap: [0; 8], fifo: MaybeUninit::uninit(), } } pub unsafe fn init_first(info: &BootInfo) { let shared = Self::shared_mut(); let mm: &[BootMemoryMapDescriptor] = slice::from_raw_parts(info.mmap_base as usize as *const _, info.mmap_len as usize); let mut free_count = 0; let mut n_free = 0; for mem_desc in mm { if mem_desc.mem_type == BootMemoryType::Available { let size = mem_desc.page_count as usize * Self::PAGE_SIZE_MIN; shared.pairs[n_free] = MemFreePair::new(mem_desc.base as usize, size); free_count += size; } n_free += 1; } shared.n_free.store(n_free, Ordering::SeqCst); shared.reserved_memory_size = info.total_memory_size as usize - free_count; if cfg!(any(target_arch = "x86_64")) { shared.real_bitmap = info.real_bitmap; } PageManager::init(info); shared.slab = Some(Box::new(SlabAllocator::new())); shared.fifo.write(EventQueue::new(100)); } pub unsafe fn late_init() { PageManager::init_late(); SpawnOption::with_priority(Priority::Realtime).start(Self::page_thread, 0, "Page Manager"); } #[allow(dead_code)] fn page_thread(_args: usize) { let shared = Self::shared(); let fifo = unsafe { &*shared.fifo.as_ptr() }; while let Some(event) = fifo.wait_event() { let result = unsafe { PageManager::mmap(event.request) }; PageManager::broadcast_invalidate_tlb().unwrap(); event.result.store(result, Ordering::SeqCst); event.sem.signal(); } } #[inline] fn shared_mut() -> &'static mut Self { unsafe { &mut MM } } #[inline] pub fn shared() -> &'static Self { unsafe { &MM } } #[inline] pub unsafe fn mmap(request: MemoryMapRequest) -> Option<NonZeroUsize> { if Scheduler::is_enabled() { let fifo = &*Self::shared().fifo.as_ptr(); let event = Arc::new(AsyncMmapRequest { request, result: AtomicUsize::new(0), sem: Semaphore::new(0), }); let _ = fifo.post(event.clone()); event.sem.wait(); NonZeroUsize::new(event.result.load(Ordering::SeqCst)) } else { NonZeroUsize::new(PageManager::mmap(request)) } } #[inline] pub fn direct_map(pa: PhysicalAddress) -> usize { PageManager::direct_map(pa) } #[inline] pub unsafe fn invalidate_cache(p: usize) { PageManager::invalidate_cache(p); } #[inline] pub fn page_size_min(&self) -> usize { self.page_size_min } #[inline] pub fn reserved_memory_size() -> usize { let shared = Self::shared_mut(); shared.reserved_memory_size } #[inline] pub fn free_memory_size() -> usize { let shared = Self::shared_mut(); let mut total = shared.dummy_size.load(Ordering::Relaxed); total += shared .slab .as_ref() .map(|v| v.free_memory_size()) .unwrap_or(0); total += shared.pairs[..shared.n_free.load(Ordering::Relaxed)] .iter() .fold(0, |v, i| v + i.size()); total } pub unsafe fn pg_alloc(layout: Layout) -> Option<NonZeroUsize> { let shared = Self::shared_mut(); let align_m1 = Self::PAGE_SIZE_MIN - 1; let size = (layout.size() + align_m1) & !(align_m1); let n_free = shared.n_free.load(Ordering::SeqCst); for i in 0..n_free { let free_pair = &shared.pairs[i]; match free_pair.alloc(size) { Ok(v) => return Some(NonZeroUsize::new_unchecked(v)), Err(_) => (), } } None } #[inline] pub unsafe fn alloc_pages(size: usize) -> Option<NonZeroUsize> { let result = Self::pg_alloc(Layout::from_size_align_unchecked(size, Self::PAGE_SIZE_MIN)); if let Some(p) = result { let p = PageManager::direct_map(p.get() as PhysicalAddress) as *const c_void as *mut c_void; p.write_bytes(0, size); } result } pub unsafe fn zalloc(layout: Layout) -> Option<NonZeroUsize> { let shared = Self::shared_mut(); if let Some(slab) = &shared.slab { match slab.alloc(layout) { Ok(result) => return Some(result), Err(AllocationError::Unsupported) => (), Err(_err) => return None, } } Self::pg_alloc(layout) .and_then(|v| NonZeroUsize::new(PageManager::direct_map(v.get() as PhysicalAddress))) } pub unsafe fn zfree( base: Option<NonZeroUsize>, layout: Layout, ) -> Result<(), DeallocationError> { if let Some(base) = base { let ptr = base.get() as *mut u8; ptr.write_bytes(0xCC, layout.size()); let shared = Self::shared_mut(); if let Some(slab) = &shared.slab { match slab.free(base, layout) { Ok(_) => Ok(()), Err(_) => { shared.dummy_size.fetch_add(layout.size(), Ordering::SeqCst); Ok(()) } } } else { shared.dummy_size.fetch_add(layout.size(), Ordering::SeqCst); Ok(()) } } else { Ok(()) } } pub unsafe fn static_alloc_real() -> Option<NonZeroU8> { let max_real = 0xA0; let shared = Self::shared_mut(); for i in 1..max_real { let result = Cpu::interlocked_test_and_clear( &*(&shared.real_bitmap[0] as *const _ as *const AtomicUsize), i, ); if result { return NonZeroU8::new(i as u8); } } None } pub fn statistics(sb: &mut StringBuffer) { let shared = Self::shared_mut(); sb.clear(); let dummy = shared.dummy_size.load(Ordering::Relaxed); let free = shared.pairs[..shared.n_free.load(Ordering::Relaxed)] .iter() .fold(0, |v, i| v + i.size()); let total = free + dummy; writeln!( sb, "Memory {} MB Pages {} ({} + {})", System::current_device().total_memory_size() >> 20, total / Self::PAGE_SIZE_MIN, free / Self::PAGE_SIZE_MIN, dummy / Self::PAGE_SIZE_MIN, ) .unwrap(); for chunk in shared.slab.as_ref().unwrap().statistics().chunks(4) { write!(sb, "Slab").unwrap(); for item in chunk { write!(sb, " {:4}: {:4}/{:4}", item.0, item.1, item.2,).unwrap(); } writeln!(sb, "").unwrap(); } } } struct AsyncMmapRequest { request: MemoryMapRequest, result: AtomicUsize, sem: Semaphore, } #[derive(Debug, Clone, Copy)] struct MemFreePair { inner: u64, } impl MemFreePair { const PAGE_SIZE: usize = 0x1000; #[inline] pub const fn empty() -> Self { Self { inner: 0 } } #[inline] pub const fn new(bas
r: base | (size << 32), } } #[inline] pub fn alloc(&self, size: usize) -> Result<usize, ()> { let size = (size + Self::PAGE_SIZE - 1) / Self::PAGE_SIZE; let p: &AtomicU64 = unsafe { transmute(&self.inner) }; let mut data = p.load(Ordering::SeqCst); loop { let (base, limit) = ((data & 0xFFFF_FFFF) as usize, (data >> 32) as usize); if limit < size { return Err(()); } let new_size = limit - size; let new_data = (base as u64) | ((new_size as u64) << 32); data = match p.compare_exchange(data, new_data, Ordering::SeqCst, Ordering::Relaxed) { Ok(_) => return Ok((base + new_size) * Self::PAGE_SIZE), Err(v) => v, }; } } #[inline] fn split(&self) -> (usize, usize) { let p: &AtomicU64 = unsafe { transmute(&self.inner) }; let data = p.load(Ordering::SeqCst); ((data & 0xFFFF_FFFF) as usize, (data >> 32) as usize) } #[inline] #[allow(dead_code)] pub fn base(&self) -> usize { self.split().0 * Self::PAGE_SIZE } #[inline] pub fn size(&self) -> usize { self.split().1 * Self::PAGE_SIZE } } bitflags! { pub struct MProtect: usize { const READ = 0x4; const WRITE = 0x2; const EXEC = 0x1; const NONE = 0x0; const READ_WRITE = Self::READ.bits | Self::WRITE.bits; const READ_EXEC = Self::READ.bits | Self::WRITE.bits; } } #[derive(Debug, Copy, Clone)] pub enum AllocationError { Unexpected, OutOfMemory, InvalidArgument, Unsupported, } #[derive(Debug, Copy, Clone)] pub enum DeallocationError { Unexpected, InvalidArgument, Unsupported, } #[derive(Debug, Clone, Copy)] pub enum MemoryMapRequest { Mmio(PhysicalAddress, usize), Vram(PhysicalAddress, usize), Kernel(usize, usize, MProtect), User(usize, usize, MProtect), } impl MemoryMapRequest { #[allow(dead_code)] fn to_slice(&self) -> &[u8] { unsafe { slice::from_raw_parts(&self as *const _ as *const u8, size_of::<Self>()) } } }
e: usize, size: usize) -> Self { let base = (base / Self::PAGE_SIZE) as u64; let size = (size / Self::PAGE_SIZE) as u64; Self { inne
function_block-random_span
[ { "content": "fn format_bytes(sb: &mut dyn Write, val: usize) -> core::fmt::Result {\n\n let kb = (val >> 10) & 0x3FF;\n\n let mb = (val >> 20) & 0x3FF;\n\n let gb = val >> 30;\n\n\n\n if gb >= 10 {\n\n // > 10G\n\n write!(sb, \"{:4}G\", gb)\n\n } else if gb >= 1 {\n\n // 1G~10G\n\n let mb0 = (mb * 100) >> 10;\n\n write!(sb, \"{}.{:02}G\", gb, mb0)\n\n } else if mb >= 100 {\n\n // 100M~1G\n\n write!(sb, \"{:4}M\", mb)\n\n } else if mb >= 10 {\n\n // 10M~100M\n\n let kb00 = (kb * 10) >> 10;\n\n write!(sb, \"{:2}.{}M\", mb, kb00)\n\n } else if mb >= 1 {\n", "file_path": "system/kernel/src/user/userenv.rs", "rank": 0, "score": 261192.71744960968 }, { "content": "#[inline]\n\npub fn os_dealloc(ptr: usize, size: usize, align: usize) {\n\n unsafe { svc3(Function::Dealloc, ptr, size, align) };\n\n}\n\n\n\n#[inline]\n\npub unsafe fn game_v1_init(window: usize, screen: *const c_void) -> usize {\n\n svc2(Function::GameV1Init, window, screen as usize)\n\n}\n\n\n\n#[inline]\n\n#[rustfmt::skip]\n\npub unsafe fn game_v1_init_long(window: usize, screen: *const c_void, scale: usize, fps: usize) -> usize {\n\n svc4(Function::GameV1Init, window, screen as usize, scale, fps)\n\n}\n\n\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 1, "score": 255316.35821527726 }, { "content": "pub fn canonicalize<P: AsRef<Path>>(_path: P) -> Result<PathBuf> {\n\n todo!()\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct Metadata(fs_imp::Metadata);\n\n\n\nimpl Metadata {\n\n pub fn file_type(&self) -> FileType {\n\n FileType(self.0.file_type())\n\n }\n\n\n\n #[inline]\n\n pub fn is_dir(&self) -> bool {\n\n self.file_type().is_dir()\n\n }\n\n\n\n #[inline]\n\n pub fn is_file(&self) -> bool {\n\n self.file_type().is_file()\n", "file_path": "lib/megstd/src/fs.rs", "rank": 3, "score": 214003.94625528413 }, { "content": "#[inline]\n\npub fn os_alloc(size: usize, align: usize) -> usize {\n\n unsafe { svc2(Function::Alloc, size, align) }\n\n}\n\n\n\n/// Frees an allocated memory block\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 4, "score": 211884.4774715689 }, { "content": "pub fn read_dir<P: AsRef<Path>>(_path: P) -> Result<ReadDir> {\n\n todo!()\n\n}\n\n\n", "file_path": "lib/megstd/src/fs.rs", "rank": 5, "score": 210438.44832597655 }, { "content": "#[inline]\n\npub fn game_v1_button(handle: usize) -> u32 {\n\n unsafe { svc1(Function::GameV1Button, handle) as u32 }\n\n}\n\n\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 6, "score": 204341.72884427535 }, { "content": "#[inline]\n\npub fn os_wait_char(window: usize) -> u32 {\n\n unsafe { svc1(Function::WaitChar, window) as u32 }\n\n}\n\n\n\n/// Read a key event\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 7, "score": 204341.72884427535 }, { "content": "#[inline]\n\npub fn os_read_char(window: usize) -> u32 {\n\n unsafe { svc1(Function::ReadChar, window) as u32 }\n\n}\n\n\n\n/// Draw a bitmap in a window\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 8, "score": 204341.72884427535 }, { "content": "#[alloc_error_handler]\n\nfn alloc_error_handler(layout: Layout) -> ! {\n\n panic!(\"allocation error: {:?}\", layout)\n\n}\n", "file_path": "system/kernel/src/mem/alloc.rs", "rank": 9, "score": 196751.36207925313 }, { "content": "#[alloc_error_handler]\n\nfn alloc_error_handler(layout: Layout) -> ! {\n\n panic!(\n\n \"Allocation error: {{ size: {}, align: {} }}\",\n\n layout.size(),\n\n layout.align()\n\n )\n\n}\n", "file_path": "lib/megoslib/src/os_alloc.rs", "rank": 10, "score": 196751.36207925313 }, { "content": "#[inline]\n\npub fn os_srand(srand: u32) -> u32 {\n\n unsafe { svc1(Function::Srand, srand as usize) as u32 }\n\n}\n\n\n\n/// Allocates memory blocks with a simple allocator\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 11, "score": 193018.1498093945 }, { "content": "#[inline]\n\npub fn os_version() -> u32 {\n\n unsafe { svc1(Function::GetSystemInfo, 0) as u32 }\n\n}\n\n\n\n/// Create a new window.\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 12, "score": 190246.24099553612 }, { "content": "#[inline]\n\npub fn os_monotonic() -> u32 {\n\n unsafe { svc0(Function::Monotonic) as u32 }\n\n}\n\n\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 13, "score": 190246.24099553612 }, { "content": "#[inline]\n\npub fn os_rand() -> u32 {\n\n unsafe { svc0(Function::Rand) as u32 }\n\n}\n\n\n\n/// Set the seed of the random number.\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 14, "score": 190246.24099553612 }, { "content": "#[inline]\n\npub fn os_time_of_day() -> u32 {\n\n unsafe { svc1(Function::Time, 0) as u32 }\n\n}\n\n\n\n/// Blocks a thread for the specified microseconds.\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 15, "score": 186437.62742071284 }, { "content": "#[inline]\n\npub fn os_blt1(ctx: usize, x: usize, y: usize, bitmap: usize, color: u32, mode: usize) {\n\n unsafe { svc6(Function::Blt1, ctx, x, y, bitmap, color as usize, mode) };\n\n}\n\n\n\n/// TEST\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 16, "score": 185811.97926749373 }, { "content": "#[repr(transparent)]\n\n#[derive(Debug, Copy, Clone, PartialEq)]\n\nstruct Ps2Command(pub u8);\n\n\n\n#[allow(dead_code)]\n\nimpl Ps2Command {\n\n const WRITE_CONFIG: Ps2Command = Ps2Command(0x60);\n\n const DISABLE_SECOND_PORT: Ps2Command = Ps2Command(0xA7);\n\n const ENABLE_SECOND_PORT: Ps2Command = Ps2Command(0xA8);\n\n const DISABLE_FIRST_PORT: Ps2Command = Ps2Command(0xAD);\n\n const ENABLE_FIRST_PORT: Ps2Command = Ps2Command(0xAE);\n\n const WRITE_SECOND_PORT: Ps2Command = Ps2Command(0xD4);\n\n}\n\n\n\nbitflags! {\n\n struct Ps2Status: u8 {\n\n const OUTPUT_FULL = 0b0000_0001;\n\n const INPUT_FULL = 0b0000_0010;\n\n const SYSTEM_FLAG = 0b0000_0100;\n\n const COMMAND = 0b0000_1000;\n\n const TIMEOUT_ERROR = 0b0100_0000;\n\n const PARITY_ERROR = 0b1000_0000;\n", "file_path": "system/kernel/src/arch/x86_64/ps2.rs", "rank": 17, "score": 183578.20412097638 }, { "content": "#[repr(transparent)]\n\n#[derive(Debug, Copy, Clone, PartialEq)]\n\nstruct Ps2Data(pub u8);\n\n\n\n#[allow(dead_code)]\n\nimpl Ps2Data {\n\n const ACK: Ps2Data = Ps2Data(0xFA);\n\n const NAK: Ps2Data = Ps2Data(0xFE);\n\n const ECHO: Ps2Data = Ps2Data(0xEE);\n\n\n\n const RESET_COMMAND: Ps2Data = Ps2Data(0xFF);\n\n const ENABLE_SEND: Ps2Data = Ps2Data(0xF4);\n\n const DISABLE_SEND: Ps2Data = Ps2Data(0xF5);\n\n const SET_DEFAULT: Ps2Data = Ps2Data(0xF6);\n\n\n\n const SCAN_E0: Ps2Data = Ps2Data(0xE0);\n\n\n\n const fn is_break(self) -> bool {\n\n (self.0 & 0x80) != 0\n\n }\n\n\n\n const fn scancode(self) -> u8 {\n\n self.0 & 0x7F\n\n }\n\n}\n\n\n", "file_path": "system/kernel/src/arch/x86_64/ps2.rs", "rank": 18, "score": 183578.20412097638 }, { "content": "#[inline]\n\n#[rustfmt::skip]\n\npub fn os_blend_rect(bitmap: usize, x: usize, y: usize, width: usize, height: usize, color: u32) {\n\n unsafe { svc6(Function::BlendRect, bitmap, x, y, width, height, color as usize) };\n\n}\n\n\n\n/// Returns a simple pseudo-random number\n\n///\n\n/// # Safety\n\n///\n\n/// Since this system call returns a simple pseudo-random number,\n\n/// it should not be used in situations where random number safety is required.\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 19, "score": 182936.8271359494 }, { "content": "#[repr(transparent)]\n\n#[derive(Debug, Copy, Clone, Default)]\n\nstruct PackedTriggerMode(pub u8);\n\n\n\nimpl PackedTriggerMode {\n\n const fn new(trigger: ApicTriggerMode, polarity: ApicPolarity) -> Self {\n\n Self(trigger.as_packed() | polarity.as_packed())\n\n }\n\n\n\n const fn as_redir(self) -> u32 {\n\n (self.0 as u32) << 12\n\n }\n\n}\n\n\n", "file_path": "system/kernel/src/arch/x86_64/apic.rs", "rank": 21, "score": 180209.12179287948 }, { "content": "#[inline]\n\n#[rustfmt::skip]\n\npub fn os_new_window1(title: &str, width: usize, height: usize) -> usize {\n\n unsafe { svc4(Function::NewWindow, title.as_ptr() as usize, title.len(), width, height) }\n\n}\n\n\n\n/// Create a new window.\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 22, "score": 180186.51415816753 }, { "content": "#[inline]\n\npub fn os_usleep(us: u32) {\n\n unsafe { svc1(Function::Usleep, us as usize) };\n\n}\n\n\n\n/// Get the system version information.\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 23, "score": 179695.39174576206 }, { "content": "#[inline]\n\n#[rustfmt::skip]\n\npub fn os_new_window2(title: &str, width: usize, height: usize, bg_color: usize, flag: usize) -> usize {\n\n unsafe { svc6( Function::NewWindow, title.as_ptr() as usize, title.len(), width, height, bg_color, flag) }\n\n}\n\n\n\n/// Close a window.\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 24, "score": 167794.01158071475 }, { "content": "struct SlabChunkHeader {\n\n ptr: AtomicUsize,\n\n bitmap: AtomicUsize,\n\n}\n\n\n\nimpl SlabChunkHeader {\n\n #[inline]\n\n fn new(ptr: usize, bitmap: usize) -> Self {\n\n Self {\n\n ptr: AtomicUsize::new(ptr),\n\n bitmap: AtomicUsize::new(bitmap),\n\n }\n\n }\n\n\n\n #[inline]\n\n fn is_some(&self) -> bool {\n\n self.ptr.load(Ordering::Relaxed) != 0\n\n }\n\n\n\n #[inline]\n", "file_path": "system/kernel/src/mem/slab.rs", "rank": 25, "score": 164251.84443014377 }, { "content": "/// Common color trait\n\npub trait ColorTrait: Sized + Copy + Clone + PartialEq + Eq + Default {}\n\n\n\n#[repr(transparent)]\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]\n\npub struct IndexedColor(pub u8);\n\n\n\nimpl ColorTrait for IndexedColor {}\n\n\n\nimpl IndexedColor {\n\n pub const MIN: Self = Self(u8::MIN);\n\n pub const MAX: Self = Self(u8::MAX);\n\n pub const DEFAULT_KEY: Self = Self(u8::MAX);\n\n\n\n pub const BLACK: Self = Self(0);\n\n pub const BLUE: Self = Self(1);\n\n pub const GREEN: Self = Self(2);\n\n pub const CYAN: Self = Self(3);\n\n pub const RED: Self = Self(4);\n\n pub const MAGENTA: Self = Self(5);\n\n pub const BROWN: Self = Self(6);\n", "file_path": "lib/megstd/src/drawing/color.rs", "rank": 26, "score": 162757.40345176365 }, { "content": "#[inline]\n\npub fn os_begin_draw(window: usize) -> usize {\n\n unsafe { svc1(Function::BeginDraw, window) }\n\n}\n\n\n\n/// Discard the drawing context and reflect it to the screen\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 27, "score": 160837.8474082127 }, { "content": "#[inline]\n\npub fn game_v1_sync(handle: usize) -> usize {\n\n unsafe { svc1(Function::GameV1Sync, handle) }\n\n}\n\n\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 28, "score": 160837.8474082127 }, { "content": "#[inline]\n\npub fn os_blt32(ctx: usize, x: usize, y: usize, bitmap: usize) {\n\n unsafe { svc4(Function::Blt32, ctx, x, y, bitmap) };\n\n}\n\n\n\n/// Draw a bitmap in a window\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 29, "score": 154857.3601210563 }, { "content": "#[inline]\n\npub fn os_blt8(ctx: usize, x: usize, y: usize, bitmap: usize) {\n\n unsafe { svc4(Function::Blt8, ctx, x, y, bitmap) };\n\n}\n\n\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 30, "score": 154857.3601210563 }, { "content": "#[inline]\n\npub fn os_end_draw(ctx: usize) {\n\n unsafe { svc1(Function::EndDraw, ctx) };\n\n}\n\n\n\n/// Draw a string in a window.\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 31, "score": 154599.42515559535 }, { "content": "#[inline]\n\npub fn os_close_window(window: usize) {\n\n unsafe { svc1(Function::CloseWindow, window) };\n\n}\n\n\n\n/// Create a drawing context\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 32, "score": 154599.42515559535 }, { "content": "struct AsyncSemaphoreResultObserver<T> {\n\n sem: Pin<Arc<AsyncSemaphore>>,\n\n _phantom: PhantomData<T>,\n\n}\n\n\n\nimpl<T> Future for AsyncSemaphoreResultObserver<T> {\n\n type Output = Result<(), T>;\n\n\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {\n\n if self.sem.poll(cx) {\n\n Poll::Ready(Ok(()))\n\n } else {\n\n Poll::Pending\n\n }\n\n }\n\n}\n", "file_path": "system/kernel/src/sync/semaphore.rs", "rank": 33, "score": 153541.22440649598 }, { "content": "#[inline]\n\npub fn game_v1_move_sprite(handle: usize, index: usize, x: usize, y: usize) {\n\n unsafe { svc4(Function::GameV1MoveSprite, handle, index, x, y) };\n\n}\n\n\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 34, "score": 149797.54530974326 }, { "content": "type IntPtr = u64;\n\n\n\n#[repr(transparent)]\n\n#[derive(Debug, Copy, Clone, Default, PartialEq, PartialOrd)]\n\npub struct VirtualAddress(pub IntPtr);\n\n\n\nimpl VirtualAddress {\n\n pub const fn as_u64(&self) -> u64 {\n\n self.0 as u64\n\n }\n\n\n\n pub const fn index_of(&self, level: usize) -> usize {\n\n (self.0 >> (level * PageTableEntry::SHIFT_PER_LEVEL + PageTableEntry::SHIFT_PTE)) as usize\n\n & PageTableEntry::INDEX_MASK\n\n }\n\n}\n\n\n\nimpl Add<u32> for VirtualAddress {\n\n type Output = Self;\n\n fn add(self, rhs: u32) -> Self {\n", "file_path": "boot/boot-efi/src/page.rs", "rank": 35, "score": 149124.71355058165 }, { "content": "#[inline]\n\npub fn os_bench<F>(f: F) -> usize\n\nwhere\n\n F: FnOnce() -> (),\n\n{\n\n let time0 = unsafe { svc0(Function::Monotonic) };\n\n f();\n\n let time1 = unsafe { svc0(Function::Monotonic) };\n\n time1 - time0\n\n}\n\n\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 36, "score": 147990.40611721185 }, { "content": "#[inline]\n\npub fn game_v1_rect(handle: usize, x: usize, y: usize, width: usize, height: usize) {\n\n unsafe { svc5(Function::GameV1Rect, handle, x, y, width, height) };\n\n}\n\n\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 37, "score": 147835.73925099097 }, { "content": "#[derive(Clone, Copy)]\n\nstruct SimpleFreePair {\n\n base: u32,\n\n size: u32,\n\n}\n\n\n\nimpl SimpleFreePair {\n\n #[inline]\n\n pub const fn new(base: u32, size: u32) -> Self {\n\n Self { base, size }\n\n }\n\n\n\n #[inline]\n\n pub const fn next_base(&self) -> u32 {\n\n self.base + self.size\n\n }\n\n}\n\n\n", "file_path": "system/kernel/src/rt/megos/arle.rs", "rank": 38, "score": 147642.9266343287 }, { "content": "fn set_name_array(array: &mut [u8; CONTEXT_LABEL_LENGTH], name: &str) {\n\n let mut i = 1;\n\n for c in name.bytes() {\n\n if i >= CONTEXT_LABEL_LENGTH {\n\n break;\n\n }\n\n array[i] = c;\n\n i += 1;\n\n }\n\n array[0] = i as u8 - 1;\n\n}\n\n\n\nimpl ProcessContextData {\n\n fn new(parent: ProcessId, priority: Priority, name: &str) -> Box<ProcessContextData> {\n\n let pid = Self::next_pid();\n\n let mut child = Self {\n\n parent,\n\n pid,\n\n n_threads: AtomicUsize::new(0),\n\n priority,\n", "file_path": "system/kernel/src/task/scheduler.rs", "rank": 39, "score": 145863.50543756332 }, { "content": "#[inline]\n\npub fn os_win_draw_string(ctx: usize, x: usize, y: usize, s: &str, color: usize) {\n\n let ptr = s.as_ptr() as usize;\n\n unsafe { svc6(Function::DrawString, ctx, x, y, ptr, s.len(), color) };\n\n}\n\n\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 40, "score": 144655.05253290033 }, { "content": "pub trait MemoryTypeHelper {\n\n fn is_conventional_at_runtime(&self) -> bool;\n\n fn is_countable(&self) -> bool;\n\n fn as_boot_memory_type(&self) -> BootMemoryType;\n\n}\n\nimpl MemoryTypeHelper for MemoryType {\n\n #[inline]\n\n fn is_conventional_at_runtime(&self) -> bool {\n\n match *self {\n\n MemoryType::CONVENTIONAL\n\n | MemoryType::BOOT_SERVICES_CODE\n\n | MemoryType::BOOT_SERVICES_DATA => true,\n\n _ => false,\n\n }\n\n }\n\n\n\n #[inline]\n\n fn is_countable(&self) -> bool {\n\n match *self {\n\n MemoryType::CONVENTIONAL\n", "file_path": "boot/boot-efi/src/page.rs", "rank": 41, "score": 143144.05253579648 }, { "content": "#[inline]\n\n#[rustfmt::skip]\n\npub fn os_win_fill_rect(ctx: usize, x: usize, y: usize, width: usize, height: usize, color: usize) {\n\n unsafe { svc6(Function::FillRect, ctx, x, y, width, height, color) };\n\n}\n\n\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 42, "score": 141780.4657185729 }, { "content": "type Slice = [u8];\n\n\n\npub struct OsStr {\n\n inner: Slice,\n\n}\n\n\n\nimpl OsStr {\n\n #[inline]\n\n fn from_inner(inner: &Slice) -> &OsStr {\n\n unsafe { &*(inner as *const Slice as *const OsStr) }\n\n }\n\n\n\n #[inline]\n\n fn from_inner_mut(inner: &mut Slice) -> &mut OsStr {\n\n unsafe { &mut *(inner as *mut Slice as *mut OsStr) }\n\n }\n\n\n\n #[inline]\n\n pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {\n\n s.as_ref()\n", "file_path": "lib/megstd/src/osstr.rs", "rank": 43, "score": 140960.67594556673 }, { "content": "#[inline]\n\n#[rustfmt::skip]\n\npub fn game_v1_load_font(handle: usize, start_index: usize, start_char: usize, end_char: usize) {\n\n unsafe { svc4( Function::GameV1LoadFont, handle, start_index, start_char, end_char) };\n\n}\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 44, "score": 138908.5764635651 }, { "content": "#[inline]\n\npub fn os_win_draw_line(ctx: usize, x1: usize, y1: usize, x2: usize, y2: usize, color: usize) {\n\n unsafe { svc6(Function::DrawLine, ctx, x1, y1, x2, y2, color) };\n\n}\n\n\n\n/// Wait for key event\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 45, "score": 138069.61438541466 }, { "content": "#[inline]\n\n#[rustfmt::skip]\n\npub fn os_draw_shape(ctx: usize, x: usize, y: usize, width: usize, height: usize, params: &OsDrawShape) {\n\n unsafe { svc6(Function::DrawShape, ctx, x, y, width, height, params as *const _ as usize) };\n\n}\n\n\n\n#[allow(dead_code)]\n\n#[derive(Clone, Copy)]\n\npub struct OsDrawShape {\n\n pub radius: u32,\n\n pub bg_color: u32,\n\n pub border_color: u32,\n\n}\n\n\n\n/// Fill a rectangle in a window.\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 46, "score": 137346.35568553614 }, { "content": "#[repr(transparent)]\n\n#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]\n\nstruct TaskId(u64);\n\n\n\nimpl TaskId {\n\n fn new() -> Self {\n\n static NEXT_ID: AtomicU64 = AtomicU64::new(0);\n\n TaskId(NEXT_ID.fetch_add(1, Ordering::Relaxed))\n\n }\n\n}\n", "file_path": "system/kernel/src/task/mod.rs", "rank": 47, "score": 134017.71180180667 }, { "content": "#[inline]\n\npub fn os_exit() -> ! {\n\n unsafe {\n\n svc0(Function::Exit);\n\n loop {\n\n asm!(\"unreachable\");\n\n }\n\n }\n\n}\n\n\n\n/// Display a string.\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 48, "score": 133833.51393354178 }, { "content": "pub fn get_file(\n\n handle: Handle,\n\n bs: &BootServices,\n\n path: &str,\n\n) -> Result<&'static mut [u8], Status> {\n\n let li = unsafe {\n\n match bs.handle_protocol::<uefi::proto::loaded_image::LoadedImage>(handle) {\n\n Ok(val) => val.unwrap().get().as_ref().unwrap(),\n\n Err(_) => return Err(Status::LOAD_ERROR),\n\n }\n\n };\n\n let fs = unsafe {\n\n match bs.handle_protocol::<SimpleFileSystem>(li.device()) {\n\n Ok(val) => val.unwrap().get().as_mut().unwrap(),\n\n Err(_) => return Err(Status::LOAD_ERROR),\n\n }\n\n };\n\n let mut root = match fs.open_volume() {\n\n Ok(val) => val.unwrap(),\n\n Err(err) => return Err(err.status()),\n", "file_path": "boot/lib-efi/src/lib.rs", "rank": 49, "score": 131123.3227767604 }, { "content": "#[repr(transparent)]\n\n#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]\n\nstruct IoApicIndex(u8);\n\n\n\nimpl IoApicIndex {\n\n #[allow(dead_code)]\n\n const ID: IoApicIndex = IoApicIndex(0x00);\n\n const VER: IoApicIndex = IoApicIndex(0x01);\n\n const REDIR_BASE: IoApicIndex = IoApicIndex(0x10);\n\n\n\n const fn redir_table_low(index: u8) -> Self {\n\n Self(Self::REDIR_BASE.0 + index * 2)\n\n }\n\n\n\n const fn redir_table_high(index: u8) -> Self {\n\n Self(Self::REDIR_BASE.0 + index * 2 + 1)\n\n }\n\n}\n\n\n", "file_path": "system/kernel/src/arch/x86_64/apic.rs", "rank": 50, "score": 128999.9275436698 }, { "content": "struct SlabCache {\n\n block_size: UsizeSmall,\n\n count: UsizeSmall,\n\n chunks: [MaybeUninit<SlabChunkHeader>; Self::N_CHUNKS],\n\n}\n\n\n\nimpl SlabCache {\n\n const N_CHUNKS: usize = 63;\n\n const ITEMS_PER_CHUNK: usize = 8 * size_of::<usize>();\n\n\n\n fn new(block_size: usize) -> Self {\n\n let mut chunks = MaybeUninit::uninit_array();\n\n for chunk in chunks.iter_mut() {\n\n *chunk = MaybeUninit::zeroed();\n\n }\n\n\n\n let mut count = 0;\n\n let items_per_chunk = Self::ITEMS_PER_CHUNK;\n\n let preferred_page_size = items_per_chunk * block_size;\n\n let atomic_page_size = if MemoryManager::PAGE_SIZE_MIN < preferred_page_size {\n", "file_path": "system/kernel/src/mem/slab.rs", "rank": 51, "score": 125996.89673014318 }, { "content": "struct AsyncSemaphoreObserver {\n\n sem: Pin<Arc<AsyncSemaphore>>,\n\n}\n\n\n\nimpl Future for AsyncSemaphoreObserver {\n\n type Output = ();\n\n\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {\n\n if self.sem.poll(cx) {\n\n Poll::Ready(())\n\n } else {\n\n Poll::Pending\n\n }\n\n }\n\n}\n\n\n", "file_path": "system/kernel/src/sync/semaphore.rs", "rank": 52, "score": 123490.80806312652 }, { "content": "#[derive(Debug, Copy, Clone, Default, PartialEq, PartialOrd)]\n\nstruct PageTableEntry {\n\n repr: u64,\n\n}\n\n\n\n#[allow(dead_code)]\n\nimpl PageTableEntry {\n\n const ADDRESS_BIT: u64 = 0x0000_FFFF_FFFF_F000;\n\n const NATIVE_PAGE_SIZE: u64 = 0x0000_1000;\n\n const N_NATIVE_PAGE_ENTRIES: usize = 512;\n\n const LARGE_PAGE_SIZE: u64 = 0x0020_0000;\n\n const INDEX_MASK: usize = 0x1FF;\n\n const MAX_PAGE_LEVEL: usize = 4;\n\n const SHIFT_PER_LEVEL: usize = 9;\n\n const SHIFT_PTE: usize = 3;\n\n\n\n const fn empty() -> Self {\n\n Self { repr: 0 }\n\n }\n\n\n\n fn is_empty(&self) -> bool {\n", "file_path": "boot/boot-efi/src/page.rs", "rank": 53, "score": 123398.15524768585 }, { "content": "#[inline]\n\npub fn os_print(s: &str) {\n\n unsafe { svc2(Function::PrintString, s.as_ptr() as usize, s.len()) };\n\n}\n\n\n\n/// Get the value of the monotonic timer in microseconds.\n", "file_path": "lib/megoslib/src/syscall.rs", "rank": 54, "score": 121269.75438866887 }, { "content": "type PageTableRepr = u64;\n\n\n\npub struct PageManager {\n\n _phantom: (),\n\n}\n\n\n\nimpl PageManager {\n\n const PAGE_SIZE_MIN: usize = 0x1000;\n\n const PAGE_SIZE_2M: usize = 0x200000;\n\n const PAGE_KERNEL_PREFIX: usize = 0xFFFF_0000_0000_0000;\n\n const PAGE_RECURSIVE: usize = 0x1FE;\n\n // const PAGE_KERNEL_HEAP: usize = 0x1FC;\n\n const PAGE_DIRECT_MAP: usize = 0x180;\n\n const DIRECT_BASE: usize = Self::PAGE_KERNEL_PREFIX | (Self::PAGE_DIRECT_MAP << 39);\n\n // const HEAP_BASE: usize = Self::PAGE_KERNEL_PREFIX | (Self::PAGE_KERNEL_HEAP << 39);\n\n\n\n #[inline]\n\n pub unsafe fn init(_info: &BootInfo) {\n\n let base = Self::read_pdbr() as usize & !(Self::PAGE_SIZE_MIN - 1);\n\n let p = base as *const u64 as *mut PageTableEntry;\n", "file_path": "system/kernel/src/arch/x86_64/page.rs", "rank": 55, "score": 116516.97433832717 }, { "content": "#[panic_handler]\n\nfn panic(info: &core::panic::PanicInfo) -> ! {\n\n println!(\"{}\", info);\n\n os_exit();\n\n}\n\n\n\npub struct OsPrint {}\n\n\n\nimpl OsPrint {\n\n pub const fn new() -> Self {\n\n Self {}\n\n }\n\n}\n\n\n\nimpl Write for OsPrint {\n\n fn write_str(&mut self, s: &str) -> core::fmt::Result {\n\n os_print(s);\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "lib/megoslib/src/lib.rs", "rank": 56, "score": 114387.89116092464 }, { "content": "#[repr(C)]\n\n#[derive(Copy, Clone, Default)]\n\nstruct AccumulatorPair {\n\n eax: u32,\n\n edx: u32,\n\n}\n\n\n\nimpl Msr {\n\n #[inline]\n\n pub unsafe fn write(self, value: u64) {\n\n let value = MsrResult { qword: value };\n\n asm!(\"wrmsr\", in(\"eax\") value.tuple.eax, in(\"edx\") value.tuple.edx, in(\"ecx\") self as u32, options(nomem, nostack),);\n\n }\n\n\n\n #[inline]\n\n pub unsafe fn read(self) -> u64 {\n\n let mut eax: u32;\n\n let mut edx: u32;\n\n asm!(\"rdmsr\", lateout(\"eax\") eax, lateout(\"edx\") edx, in(\"ecx\") self as u32, options(nomem, nostack));\n\n MsrResult {\n\n tuple: AccumulatorPair { eax, edx },\n\n }\n", "file_path": "system/kernel/src/arch/x86_64/cpu.rs", "rank": 57, "score": 110692.11693252245 }, { "content": "struct RwLockInner {\n\n data: AtomicUsize,\n\n signal: SignallingObject,\n\n}\n\n\n\nimpl RwLockInner {\n\n const LOCK_WRITE: usize = 1;\n\n const LOCK_COUNT: usize = 2;\n\n\n\n #[inline]\n\n const fn new() -> Self {\n\n Self {\n\n data: AtomicUsize::new(0),\n\n signal: SignallingObject::new(None),\n\n }\n\n }\n\n\n\n #[inline]\n\n fn destroy(&self) {\n\n // TODO: ?\n", "file_path": "system/kernel/src/sync/rwlock.rs", "rank": 58, "score": 110686.02638954297 }, { "content": "struct Slot<T> {\n\n stamp: AtomicUsize,\n\n value: UnsafeCell<MaybeUninit<T>>,\n\n}\n\n\n\nimpl<T> Slot<T> {\n\n #[inline]\n\n fn new(stamp: usize) -> Self {\n\n Self {\n\n stamp: AtomicUsize::new(stamp),\n\n value: UnsafeCell::new(MaybeUninit::zeroed()),\n\n }\n\n }\n\n\n\n #[inline]\n\n fn stamp(&self) -> usize {\n\n self.stamp.load(Ordering::Acquire)\n\n }\n\n\n\n #[inline]\n", "file_path": "system/kernel/src/sync/fifo.rs", "rank": 59, "score": 109770.92398746374 }, { "content": "#[derive(Clone)]\n\nstruct ElfProgramHeaderIter {\n\n base: *const u8,\n\n entry_size: usize,\n\n n_entries: usize,\n\n index: usize,\n\n}\n\n\n\nimpl ElfProgramHeaderIter {\n\n #[inline]\n\n const fn new(base: *const u8, entry_size: usize, n_entries: usize) -> Self {\n\n Self {\n\n base,\n\n entry_size,\n\n n_entries,\n\n index: 0,\n\n }\n\n }\n\n}\n\n\n\nimpl Iterator for ElfProgramHeaderIter {\n", "file_path": "boot/boot-efi/src/loader/elfldr.rs", "rank": 60, "score": 105757.02735718219 }, { "content": "pub trait PciImpl {\n\n unsafe fn read_pci(&self, addr: PciConfigAddress) -> u32;\n\n\n\n unsafe fn write_pci(&self, addr: PciConfigAddress, value: u32);\n\n}\n\n\n", "file_path": "system/kernel/src/bus/pci/pci.rs", "rank": 61, "score": 103744.97621200501 }, { "content": "/// Wrapper object to spawn the closure\n\nstruct FnSpawner<F, T>\n\nwhere\n\n F: FnOnce() -> T,\n\n F: Send + 'static,\n\n T: Send + 'static,\n\n{\n\n start: F,\n\n mutex: Arc<Mutex<Option<T>>>,\n\n}\n\n\n\nimpl<F, T> FnSpawner<F, T>\n\nwhere\n\n F: FnOnce() -> T,\n\n F: Send + 'static,\n\n T: Send + 'static,\n\n{\n\n fn spawn(start: F, name: &str, options: SpawnOption) -> JoinHandle<T> {\n\n let mutex = Arc::new(Mutex::new(None));\n\n let boxed = Arc::new(Box::new(Self {\n\n start,\n", "file_path": "system/kernel/src/task/scheduler.rs", "rank": 62, "score": 101554.93586670974 }, { "content": "type ThreadStart = fn(usize) -> ();\n\n\n", "file_path": "system/kernel/src/task/scheduler.rs", "rank": 63, "score": 101041.32074733311 }, { "content": "struct UsbHidClassDescriptorIter<'a> {\n\n base: &'a UsbHidClassDescriptor,\n\n index: usize,\n\n}\n\n\n\nimpl Iterator for UsbHidClassDescriptorIter<'_> {\n\n type Item = (UsbDescriptorType, u16);\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n unsafe {\n\n if self.index < self.base.num_descriptors() {\n\n let p = self.base as *const _ as *const u8;\n\n let offset = self.index * 3 + 6;\n\n let p = p.add(offset);\n\n let ty = match FromPrimitive::from_u8(p.read()) {\n\n Some(v) => v,\n\n None => return None,\n\n };\n\n let len = (p.add(1).read() as u16) + (p.add(2).read() as u16 * 256);\n\n self.index += 1;\n", "file_path": "system/kernel/src/bus/usb/types.rs", "rank": 64, "score": 99903.6295719277 }, { "content": "#[repr(transparent)]\n\nstruct ThreadQueue(ConcurrentFifo<ThreadHandle>);\n\n\n\nimpl ThreadQueue {\n\n #[inline]\n\n fn with_capacity(capacity: usize) -> Self {\n\n Self(ConcurrentFifo::with_capacity(capacity))\n\n }\n\n\n\n #[inline]\n\n fn dequeue(&self) -> Option<ThreadHandle> {\n\n self.0.dequeue()\n\n }\n\n\n\n #[inline]\n\n fn enqueue(&self, data: ThreadHandle) -> Result<(), ()> {\n\n self.0.enqueue(data).map_err(|_| ())\n\n }\n\n}\n\n\n\n/// Interrupt Request Level\n", "file_path": "system/kernel/src/task/scheduler.rs", "rank": 65, "score": 97069.37633757063 }, { "content": "#[entry]\n\nfn efi_main(handle: Handle, mut st: SystemTable<Boot>) -> Status {\n\n let mut info = BootInfo::default();\n\n let bs = st.boot_services();\n\n info.platform = Platform::UEFI;\n\n info.color_mode = ColorMode::Argb32;\n\n\n\n // Find ACPI Table\n\n info.acpi_rsdptr = match st.find_config_table(::uefi::table::cfg::ACPI2_GUID) {\n\n Some(val) => val as u64,\n\n None => {\n\n writeln!(st.stdout(), \"Error: ACPI Table Not Found\").unwrap();\n\n return Status::UNSUPPORTED;\n\n }\n\n };\n\n\n\n // Find SMBIOS Table\n\n info.smbios = match st.find_config_table(::uefi::table::cfg::SMBIOS_GUID) {\n\n Some(val) => val as u64,\n\n None => 0,\n\n };\n", "file_path": "boot/boot-efi/src/main.rs", "rank": 66, "score": 96263.51501668933 }, { "content": "pub trait TrbPtr: TrbCommon {\n\n #[inline]\n\n fn ptr(&self) -> u64 {\n\n let low = self.raw_data()[0].load(Ordering::SeqCst) as u64;\n\n let high = self.raw_data()[1].load(Ordering::SeqCst) as u64;\n\n low | (high << 32)\n\n }\n\n\n\n #[inline]\n\n fn set_ptr(&self, val: u64) {\n\n let low = val as u32;\n\n let high = (val >> 32) as u32;\n\n self.raw_data()[0].store(low, Ordering::SeqCst);\n\n self.raw_data()[1].store(high, Ordering::SeqCst);\n\n }\n\n}\n\n\n", "file_path": "system/kernel/src/bus/usb/xhci/data.rs", "rank": 67, "score": 94257.85293829281 }, { "content": "type UsizeSmall = u16;\n\n\n\npub(super) struct SlabAllocator {\n\n vec: Vec<SlabCache>,\n\n}\n\n\n\nimpl SlabAllocator {\n\n pub unsafe fn new() -> Self {\n\n let sizes = [16, 32, 64, 128, 256, 512, 1024, 2048];\n\n\n\n let mut vec: Vec<SlabCache> = Vec::with_capacity(sizes.len());\n\n for block_size in &sizes {\n\n vec.push(SlabCache::new(*block_size));\n\n }\n\n\n\n Self { vec }\n\n }\n\n\n\n pub fn alloc(&self, layout: Layout) -> Result<NonZeroUsize, AllocationError> {\n\n if layout.size() > UsizeSmall::MAX as usize || layout.align() > UsizeSmall::MAX as usize {\n", "file_path": "system/kernel/src/mem/slab.rs", "rank": 68, "score": 81455.59965916134 }, { "content": "struct SmBiosStructWalker {\n\n base: usize,\n\n offset: usize,\n\n index: usize,\n\n limit: usize,\n\n}\n\n\n\nimpl Iterator for SmBiosStructWalker {\n\n type Item = &'static SmBiosHeader;\n\n\n\n #[inline]\n\n fn next(&mut self) -> Option<Self::Item> {\n\n if self.index >= self.limit {\n\n return None;\n\n }\n\n unsafe {\n\n let p = (self.base + self.offset) as *const SmBiosHeader;\n\n let r = &*p;\n\n self.offset += r.struct_size();\n\n self.index += 1;\n", "file_path": "system/kernel/src/fw/smbios/smbios.rs", "rank": 69, "score": 80536.27452543774 }, { "content": "fn main() {\n\n let out_dir = env::var(\"OUT_DIR\").unwrap();\n\n\n\n match env::var(\"PROFILE\").unwrap().as_str() {\n\n \"debug\" => {\n\n // TODO:\n\n }\n\n \"release\" => {\n\n let target_arch: String = env::var(\"CARGO_CFG_TARGET_ARCH\").unwrap();\n\n\n\n match &*target_arch {\n\n \"x86_64\" => {\n\n Command::new(\"nasm\")\n\n .args(&[\"-f\", \"elf64\", \"src/arch/x86_64/asm.asm\", \"-o\"])\n\n .arg(&format!(\"{}/asm.o\", out_dir))\n\n .status()\n\n .unwrap();\n\n\n\n Command::new(\"ar\")\n\n .args(&[\"crus\", \"libkernel.a\", \"asm.o\"])\n", "file_path": "system/kernel/build.rs", "rank": 70, "score": 75123.93505767893 }, { "content": "#[derive(Clone, Copy)]\n\nstruct Marble {\n\n x: isize,\n\n y: isize,\n\n dir_x: isize,\n\n dir_y: isize,\n\n speed: isize,\n\n}\n\n\n\nimpl Marble {\n\n #[inline]\n\n fn new(x: isize, y: isize, dir_x: isize, dir_y: isize, speed: isize) -> Self {\n\n Self {\n\n x,\n\n y,\n\n dir_x,\n\n dir_y,\n\n speed,\n\n }\n\n }\n\n\n", "file_path": "apps/gbench/src/main.rs", "rank": 71, "score": 74280.7439532187 }, { "content": "#[derive(Debug, Clone, Copy)]\n\nstruct Board {\n\n x: isize,\n\n y: isize,\n\n z: isize,\n\n width: isize,\n\n height: isize,\n\n color: TrueColor,\n\n}\n\n\n\nimpl Board {\n\n #[inline]\n\n const fn new(\n\n x: isize,\n\n y: isize,\n\n z: isize,\n\n width: isize,\n\n height: isize,\n\n color: TrueColor,\n\n ) -> Self {\n\n Self {\n\n x,\n\n y,\n\n z,\n\n width,\n\n height,\n\n color,\n\n }\n\n }\n\n}\n\n\n", "file_path": "apps/noiz2bg/src/main.rs", "rank": 72, "score": 74280.56400826937 }, { "content": "struct App {\n\n presenter: GamePresenterImpl,\n\n}\n\n\n\nimpl App {\n\n const WINDOW_WIDTH: isize = 240;\n\n const WINDOW_HEIGHT: isize = 160;\n\n\n\n fn new() -> Self {\n\n let presenter = GameWindow::with_options(\n\n \"GAME TEST\",\n\n Size::new(Self::WINDOW_WIDTH, Self::WINDOW_HEIGHT),\n\n ScaleMode::NearestNeighbor2X,\n\n 60,\n\n );\n\n Self { presenter }\n\n }\n\n\n\n #[inline]\n\n fn screen(&mut self) -> &mut v1::Screen {\n", "file_path": "apps/test/src/main.rs", "rank": 73, "score": 74269.55519612691 }, { "content": "struct Player {\n\n point: Point,\n\n speed: isize,\n\n dir: Direction,\n\n}\n\n\n\nimpl Player {\n\n #[inline]\n\n const fn new(point: Point, speed: isize, dir: Direction) -> Self {\n\n Self { point, speed, dir }\n\n }\n\n\n\n fn walk(&mut self) {\n\n let speed = self.speed * 2;\n\n match self.dir {\n\n Direction::Neutral => (),\n\n Direction::Up => {\n\n if self.point.y > 16 {\n\n self.point.y -= speed;\n\n }\n", "file_path": "apps/test/src/main.rs", "rank": 74, "score": 74269.55519612691 }, { "content": "struct Fatfs {\n\n sector_size: usize,\n\n total_sectors: usize,\n\n record_size: usize,\n\n total_records: usize,\n\n offset_fat: usize,\n\n offset_root: usize,\n\n offset_cluster: usize,\n\n last_record_allocated: usize,\n\n fattype: FatType,\n\n end_of_chain: FatEntry,\n\n bpb: DosBpb,\n\n fat: Vec<FatEntry>,\n\n root_dir: Vec<DosDirEnt>,\n\n}\n\n\n", "file_path": "tools/mkfdfs/src/main.rs", "rank": 75, "score": 74269.55519612691 }, { "content": "struct Missile {\n\n point: Point,\n\n dir: Direction,\n\n}\n\n\n\nimpl Missile {\n\n #[inline]\n\n fn new(point: Point, dir: Direction) -> Self {\n\n Self { point, dir }\n\n }\n\n\n\n #[inline]\n\n fn is_alive(&self) -> bool {\n\n self.point.y < v1::MAX_HEIGHT\n\n }\n\n\n\n fn step(&mut self) {\n\n let speed = 4;\n\n if self.point.y < v1::MAX_HEIGHT {\n\n match self.dir {\n", "file_path": "apps/test/src/main.rs", "rank": 76, "score": 74269.55519612691 }, { "content": "#[test]\n\nfn add() {\n\n let slice = [0, 0x20, 0, 0x20, 1, 0x6A, 0x0B];\n\n let param_types = [WasmValType::I32, WasmValType::I32];\n\n let result_types = [WasmValType::I32];\n\n let mut stream = Leb128Stream::from_slice(&slice);\n\n let module = WasmModule::new();\n\n let info =\n\n WasmCodeBlock::generate(0, 0, &mut stream, &param_types, &result_types, &module).unwrap();\n\n let mut interp = WasmInterpreter::new(&module);\n\n\n\n let mut locals = [1234.into(), 5678.into()];\n\n let result = interp\n\n .invoke(0, &info, &mut locals, &result_types)\n\n .unwrap()\n\n .unwrap()\n\n .get_i32()\n\n .unwrap();\n\n assert_eq!(result, 6912);\n\n\n\n let mut locals = [0xDEADBEEFu32.into(), 0x55555555.into()];\n\n let result = interp\n\n .invoke(0, &info, &mut locals, &result_types)\n\n .unwrap()\n\n .unwrap()\n\n .get_i32()\n\n .unwrap();\n\n assert_eq!(result, 0x34031444);\n\n}\n\n\n", "file_path": "lib/wasm/src/tests.rs", "rank": 77, "score": 73460.39955978666 }, { "content": "#[test]\n\nfn select() {\n\n let slice = [0, 0x20, 0, 0x20, 1, 0x20, 2, 0x1B, 0x0B];\n\n let param_types = [WasmValType::I32, WasmValType::I32, WasmValType::I32];\n\n let result_types = [WasmValType::I32];\n\n let mut stream = Leb128Stream::from_slice(&slice);\n\n let module = WasmModule::new();\n\n let info =\n\n WasmCodeBlock::generate(0, 0, &mut stream, &param_types, &result_types, &module).unwrap();\n\n let mut interp = WasmInterpreter::new(&module);\n\n\n\n let mut locals = [123.into(), 456.into(), 789.into()];\n\n let result = interp\n\n .invoke(0, &info, &mut locals, &result_types)\n\n .unwrap()\n\n .unwrap()\n\n .get_i32()\n\n .unwrap();\n\n assert_eq!(result, 123);\n\n\n\n let mut locals = [123.into(), 456.into(), 0.into()];\n\n let result = interp\n\n .invoke(0, &info, &mut locals, &result_types)\n\n .unwrap()\n\n .unwrap()\n\n .get_i32()\n\n .unwrap();\n\n assert_eq!(result, 456);\n\n}\n\n\n", "file_path": "lib/wasm/src/tests.rs", "rank": 78, "score": 73460.39955978666 }, { "content": "#[test]\n\nfn mul() {\n\n let slice = [0, 0x20, 0, 0x20, 1, 0x6C, 0x0B];\n\n let param_types = [WasmValType::I32, WasmValType::I32];\n\n let result_types = [WasmValType::I32];\n\n let mut stream = Leb128Stream::from_slice(&slice);\n\n let module = WasmModule::new();\n\n let info =\n\n WasmCodeBlock::generate(0, 0, &mut stream, &param_types, &result_types, &module).unwrap();\n\n let mut interp = WasmInterpreter::new(&module);\n\n\n\n let mut locals = [1234.into(), 5678.into()];\n\n let result = interp\n\n .invoke(0, &info, &mut locals, &result_types)\n\n .unwrap()\n\n .unwrap()\n\n .get_i32()\n\n .unwrap();\n\n assert_eq!(result, 7006652);\n\n\n\n let mut locals = [0x55555555.into(), 0xDEADBEEFu32.into()];\n\n let result = interp\n\n .invoke(0, &info, &mut locals, &result_types)\n\n .unwrap()\n\n .unwrap()\n\n .get_i32()\n\n .unwrap();\n\n assert_eq!(result, 0x6070c05b);\n\n}\n\n\n", "file_path": "lib/wasm/src/tests.rs", "rank": 79, "score": 73460.39955978666 }, { "content": "#[no_mangle]\n\nfn _start() {\n\n App::new().run();\n\n}\n\n\n", "file_path": "apps/noiz2bg/src/main.rs", "rank": 80, "score": 73460.39955978666 }, { "content": "#[test]\n\nfn sub() {\n\n let slice = [0, 0x20, 0, 0x20, 1, 0x6B, 0x0B];\n\n let param_types = [WasmValType::I32, WasmValType::I32];\n\n let result_types = [WasmValType::I32];\n\n let mut stream = Leb128Stream::from_slice(&slice);\n\n let module = WasmModule::new();\n\n let info =\n\n WasmCodeBlock::generate(0, 0, &mut stream, &param_types, &result_types, &module).unwrap();\n\n let mut interp = WasmInterpreter::new(&module);\n\n\n\n let mut locals = [1234.into(), 5678.into()];\n\n let result = interp\n\n .invoke(0, &info, &mut locals, &result_types)\n\n .unwrap()\n\n .unwrap()\n\n .get_i32()\n\n .unwrap();\n\n assert_eq!(result, -4444);\n\n\n\n let mut locals = [0x55555555.into(), 0xDEADBEEFu32.into()];\n\n let result = interp\n\n .invoke(0, &info, &mut locals, &result_types)\n\n .unwrap()\n\n .unwrap()\n\n .get_i32()\n\n .unwrap();\n\n assert_eq!(result, 0x76a79666);\n\n}\n\n\n", "file_path": "lib/wasm/src/tests.rs", "rank": 81, "score": 73460.39955978666 }, { "content": "#[no_mangle]\n\nfn _start() {\n\n let window = WindowBuilder::new()\n\n .size(Size::new(200, 200))\n\n .bg_color(WindowColor::BLACK)\n\n .build(\"bball\");\n\n window.draw(|ctx| {\n\n for (i, c1) in COORD_TABLE[..14].iter().enumerate() {\n\n for (j, c2) in COORD_TABLE[i..].iter().enumerate() {\n\n let dis = if j < 8 { j } else { 15 - j };\n\n ctx.draw_line(\n\n Point::new(c1.0 as isize, c1.1 as isize),\n\n Point::new(c2.0 as isize, c2.1 as isize),\n\n PackedColor(16 - dis as u32),\n\n );\n\n }\n\n }\n\n });\n\n window.wait_char();\n\n}\n\n\n", "file_path": "apps/bball/src/main.rs", "rank": 82, "score": 73460.39955978666 }, { "content": "#[test]\n\nfn lts() {\n\n let slice = [0, 0x20, 0, 0x20, 1, 0x48, 0x0B];\n\n let param_types = [WasmValType::I32, WasmValType::I32];\n\n let result_types = [WasmValType::I32];\n\n let mut stream = Leb128Stream::from_slice(&slice);\n\n let module = WasmModule::new();\n\n let info =\n\n WasmCodeBlock::generate(0, 0, &mut stream, &param_types, &result_types, &module).unwrap();\n\n let mut interp = WasmInterpreter::new(&module);\n\n\n\n let mut locals = [123.into(), 456.into()];\n\n let result = interp\n\n .invoke(0, &info, &mut locals, &result_types)\n\n .unwrap()\n\n .unwrap()\n\n .get_i32()\n\n .unwrap();\n\n assert_eq!(result, 1);\n\n\n\n let mut locals = [123.into(), 123.into()];\n", "file_path": "lib/wasm/src/tests.rs", "rank": 83, "score": 73460.39955978666 }, { "content": "#[no_mangle]\n\nfn _start() {\n\n os_srand(os_monotonic());\n\n\n\n let window = Window::new(\n\n \"LIFE\",\n\n Size::new(BITMAP_WIDTH * DRAW_SCALE, BITMAP_HEIGHT * DRAW_SCALE),\n\n );\n\n\n\n let mut curr_data = [0u8; SIZE_BITMAP];\n\n let mut next_data = [0u8; SIZE_BITMAP];\n\n for i in 1..(SIZE_BITMAP - 1) {\n\n curr_data[i] = os_rand() as u8;\n\n }\n\n\n\n let mut current =\n\n OsMutBitmap1::from_slice(&mut curr_data, Size::new(BITMAP_WIDTH, BITMAP_HEIGHT));\n\n let mut next = OsMutBitmap1::from_slice(&mut next_data, Size::new(BITMAP_WIDTH, BITMAP_HEIGHT));\n\n\n\n loop {\n\n window.draw(|ctx| {\n", "file_path": "apps/life/src/main.rs", "rank": 84, "score": 73460.39955978666 }, { "content": "fn usage() {\n\n let mut args = env::args_os();\n\n let arg = args.next().unwrap();\n\n let path = Path::new(&arg);\n\n let lpc = path.file_name().unwrap();\n\n eprintln!(\"{} INFILE OUTFILE\", lpc.to_str().unwrap());\n\n process::exit(1);\n\n}\n\n\n", "file_path": "tools/elf2ceef/src/main.rs", "rank": 85, "score": 73460.39955978666 }, { "content": "#[no_mangle]\n\nfn _start() {\n\n os_print(\"hello, world\\n\");\n\n}\n", "file_path": "apps/hello/src/main.rs", "rank": 86, "score": 73460.39955978666 }, { "content": "#[no_mangle]\n\nfn _start() {\n\n {\n\n println!(\"Benchmarking...\");\n\n\n\n let mut mips_temp: usize = 0;\n\n let time = os_bench(|| {\n\n for _ in 0..BENCH_COUNT1 {\n\n unsafe {\n\n asm!(\"\n\n local.get {0}\n\n i32.const 1\n\n i32.add\n\n local.set {0}\n\n \", inlateout(local) mips_temp);\n\n }\n\n }\n\n }) as u64;\n\n let steps: u64 = BENCH_STEPS * BENCH_COUNT1;\n\n let (bogomips, multi) = if steps < time {\n\n ((steps * 1_000_000).checked_div(time).unwrap_or(0), 1)\n", "file_path": "apps/bench/src/main.rs", "rank": 87, "score": 73460.39955978666 }, { "content": "#[no_mangle]\n\nfn _start() {\n\n let window = Window::new(\"Hello\", Size::new(200, 50));\n\n window.draw(|ctx| ctx.draw_string(\"Hello, World!\", Point::new(10, 10), WindowColor::BLACK));\n\n let _ = window.wait_char();\n\n}\n", "file_path": "apps/winhello/src/main.rs", "rank": 88, "score": 73460.39955978666 }, { "content": "#[test]\n\nfn div_s() {\n\n let slice = [0, 0x20, 0, 0x20, 1, 0x6D, 0x0B];\n\n let param_types = [WasmValType::I32, WasmValType::I32];\n\n let result_types = [WasmValType::I32];\n\n let mut stream = Leb128Stream::from_slice(&slice);\n\n let module = WasmModule::new();\n\n let info =\n\n WasmCodeBlock::generate(0, 0, &mut stream, &param_types, &result_types, &module).unwrap();\n\n let mut interp = WasmInterpreter::new(&module);\n\n\n\n let mut locals = [7006652.into(), 5678.into()];\n\n let result = interp\n\n .invoke(0, &info, &mut locals, &result_types)\n\n .unwrap()\n\n .unwrap()\n\n .get_i32()\n\n .unwrap();\n\n assert_eq!(result, 1234);\n\n\n\n let mut locals = [42.into(), (-6).into()];\n", "file_path": "lib/wasm/src/tests.rs", "rank": 89, "score": 73460.39955978666 }, { "content": "#[test]\n\nfn div_u() {\n\n let slice = [0, 0x20, 0, 0x20, 1, 0x6E, 0x0B];\n\n let param_types = [WasmValType::I32, WasmValType::I32];\n\n let result_types = [WasmValType::I32];\n\n let mut stream = Leb128Stream::from_slice(&slice);\n\n let module = WasmModule::new();\n\n let info =\n\n WasmCodeBlock::generate(0, 0, &mut stream, &param_types, &result_types, &module).unwrap();\n\n let mut interp = WasmInterpreter::new(&module);\n\n\n\n let mut locals = [7006652.into(), 5678.into()];\n\n let result = interp\n\n .invoke(0, &info, &mut locals, &result_types)\n\n .unwrap()\n\n .unwrap()\n\n .get_i32()\n\n .unwrap();\n\n assert_eq!(result, 1234);\n\n\n\n let mut locals = [42.into(), (-6).into()];\n", "file_path": "lib/wasm/src/tests.rs", "rank": 90, "score": 73460.39955978666 }, { "content": "#[test]\n\nfn instantiate() {\n\n let minimal = [0, 97, 115, 109, 1, 0, 0, 0];\n\n WasmLoader::instantiate(&minimal, |_, _, _| unreachable!()).unwrap();\n\n}\n\n\n", "file_path": "lib/wasm/src/tests.rs", "rank": 91, "score": 73460.39955978666 }, { "content": "#[test]\n\nfn ltu() {\n\n let slice = [0, 0x20, 0, 0x20, 1, 0x49, 0x0B];\n\n let param_types = [WasmValType::I32, WasmValType::I32];\n\n let result_types = [WasmValType::I32];\n\n let mut stream = Leb128Stream::from_slice(&slice);\n\n let module = WasmModule::new();\n\n let info =\n\n WasmCodeBlock::generate(0, 0, &mut stream, &param_types, &result_types, &module).unwrap();\n\n let mut interp = WasmInterpreter::new(&module);\n\n\n\n let mut locals = [123.into(), 456.into()];\n\n let result = interp\n\n .invoke(0, &info, &mut locals, &result_types)\n\n .unwrap()\n\n .unwrap()\n\n .get_i32()\n\n .unwrap();\n\n assert_eq!(result, 1);\n\n\n\n let mut locals = [123.into(), 123.into()];\n", "file_path": "lib/wasm/src/tests.rs", "rank": 92, "score": 73460.39955978666 }, { "content": "fn main() {\n\n let mut args = env::args();\n\n let _ = args.next().unwrap();\n\n\n\n let in_file = match args.next() {\n\n Some(v) => v,\n\n None => return usage(),\n\n };\n\n let out_file = match args.next() {\n\n Some(v) => v,\n\n None => return usage(),\n\n };\n\n\n\n let mut is = File::open(in_file).unwrap();\n\n let mut blob = Vec::new();\n\n let _ = is.read_to_end(&mut blob).unwrap();\n\n\n\n let mut data: Vec<u8> = Vec::with_capacity(blob.len());\n\n\n\n let header: &Elf32Hdr = unsafe { transmute(&blob[0]) };\n", "file_path": "tools/elf2ceef/src/main.rs", "rank": 93, "score": 73460.39955978666 }, { "content": "#[test]\n\nfn leb128() {\n\n let data = [\n\n 0x7F, 0xFF, 0x00, 0xEF, 0xFD, 0xB6, 0xF5, 0x0D, 0xEF, 0xFD, 0xB6, 0xF5, 0x7D,\n\n ];\n\n let mut stream = Leb128Stream::from_slice(&data);\n\n\n\n stream.reset();\n\n assert_eq!(stream.position(), 0);\n\n let test = stream.read_unsigned().unwrap();\n\n assert_eq!(test, 127);\n\n let test = stream.read_unsigned().unwrap();\n\n assert_eq!(test, 127);\n\n let test = stream.read_unsigned().unwrap();\n\n assert_eq!(test, 0xdeadbeef);\n\n let test = stream.read_unsigned().unwrap();\n\n assert_eq!(test, 0x7deadbeef);\n\n\n\n stream.reset();\n\n assert_eq!(stream.position(), 0);\n\n let test = stream.read_signed().unwrap();\n\n assert_eq!(test, -1);\n\n let test = stream.read_signed().unwrap();\n\n assert_eq!(test, 127);\n\n let test = stream.read_signed().unwrap();\n\n assert_eq!(test, 0xdeadbeef);\n\n let test = stream.read_signed().unwrap();\n\n assert_eq!(test, -559038737);\n\n}\n\n\n", "file_path": "lib/wasm/src/tests.rs", "rank": 94, "score": 73460.39955978666 }, { "content": "#[no_mangle]\n\nfn _start() {\n\n App::new().run();\n\n}\n\n\n\npub struct App {\n\n presenter: GamePresenterImpl,\n\n}\n\n\n\nimpl App {\n\n const WINDOW_WIDTH: isize = 256;\n\n const WINDOW_HEIGHT: isize = 240;\n\n\n\n #[inline]\n\n fn new() -> Self {\n\n let presenter = GameWindow::with_options(\n\n \"GAME BENCH\",\n\n Size::new(Self::WINDOW_WIDTH, Self::WINDOW_HEIGHT),\n\n ScaleMode::DotByDot,\n\n 500,\n\n );\n", "file_path": "apps/gbench/src/main.rs", "rank": 95, "score": 73460.39955978666 }, { "content": "#[no_mangle]\n\nfn _start() {\n\n App::new().run();\n\n}\n\n\n", "file_path": "apps/test/src/main.rs", "rank": 96, "score": 73460.39955978666 }, { "content": "#[no_mangle]\n\nfn _start() {\n\n let presenter = GameWindow::new(\"hello\", Size::new(128, 64));\n\n presenter\n\n .screen()\n\n .draw_string(Point::new(0, 3), 0, b\"Hello, world!\");\n\n loop {\n\n presenter.sync();\n\n\n\n presenter.screen().control_mut().scroll_x -= 1;\n\n presenter.set_needs_display();\n\n }\n\n}\n", "file_path": "apps/ghello/src/main.rs", "rank": 97, "score": 73460.39955978666 }, { "content": "#[no_mangle]\n\nfn _start() {\n\n println!(\"hello, world\");\n\n}\n", "file_path": "apps/hello2/src/main.rs", "rank": 98, "score": 73460.39955978666 }, { "content": "#[no_mangle]\n\nfn _start() {\n\n let presenter = GameWindow::new(\"hello2\", Size::new(128, 64));\n\n\n\n let chars = b\"Hello, world!\";\n\n for (index, char) in chars.iter().enumerate() {\n\n presenter.screen().set_sprite(index, *char, 0);\n\n }\n\n\n\n let mut phase = 0;\n\n loop {\n\n presenter.sync();\n\n\n\n for index in 0..chars.len() {\n\n let position = ((phase - index as isize) & 31) - 15;\n\n let value = position * position / 8 - 16;\n\n presenter.move_sprite(\n\n index as v1::SpriteIndex,\n\n Point::new(index as isize * 10, 28 + value),\n\n );\n\n }\n\n\n\n phase += 1;\n\n }\n\n}\n", "file_path": "apps/ghello2/src/main.rs", "rank": 99, "score": 73460.39955978666 } ]
Rust
src/str/ascii.rs
LaudateCorpus1/ari
b01265230dec54b1608e6277d7be4b1a1957a11b
#[rustfmt::skip] pub trait AsciiExt { type Owned; fn is_ascii(&self) -> bool; fn to_ascii_uppercase(&self) -> Self::Owned; fn to_ascii_lowercase(&self) -> Self::Owned; fn eq_ignore_ascii_case(&self, other: &Self) -> bool; fn make_ascii_uppercase(&mut self); fn make_ascii_lowercase(&mut self); fn is_ascii_alphabetic(&self) -> bool { unimplemented!(); } fn is_ascii_uppercase(&self) -> bool { unimplemented!(); } fn is_ascii_lowercase(&self) -> bool { unimplemented!(); } fn is_ascii_alphanumeric(&self) -> bool { unimplemented!(); } fn is_ascii_digit(&self) -> bool { unimplemented!(); } fn is_ascii_hexdigit(&self) -> bool { unimplemented!(); } fn is_ascii_punctuation(&self) -> bool { unimplemented!(); } fn is_ascii_graphic(&self) -> bool { unimplemented!(); } fn is_ascii_whitespace(&self) -> bool { unimplemented!(); } fn is_ascii_control(&self) -> bool { unimplemented!(); } } macro_rules! delegate_ascii_methods { () => { #[inline] fn is_ascii (&self) -> bool { self.is_ascii() } #[inline] fn to_ascii_uppercase (&self) -> Self::Owned { self.to_ascii_uppercase() } #[inline] fn to_ascii_lowercase (&self) -> Self::Owned { self.to_ascii_lowercase() } #[inline] fn eq_ignore_ascii_case (&self, other: &Self) -> bool { self.eq_ignore_ascii_case(other) } #[inline] fn make_ascii_uppercase (&mut self) { self.make_ascii_uppercase(); } #[inline] fn make_ascii_lowercase (&mut self) { self.make_ascii_lowercase(); } } } macro_rules! delegate_ascii_ctype_methods { () => { #[inline] fn is_ascii_alphabetic (&self) -> bool { self.is_ascii_alphabetic() } #[inline] fn is_ascii_uppercase (&self) -> bool { self.is_ascii_uppercase() } #[inline] fn is_ascii_lowercase (&self) -> bool { self.is_ascii_lowercase() } #[inline] fn is_ascii_alphanumeric(&self) -> bool { self.is_ascii_alphanumeric() } #[inline] fn is_ascii_digit (&self) -> bool { self.is_ascii_digit() } #[inline] fn is_ascii_hexdigit (&self) -> bool { self.is_ascii_hexdigit() } #[inline] fn is_ascii_punctuation (&self) -> bool { self.is_ascii_punctuation() } #[inline] fn is_ascii_graphic (&self) -> bool { self.is_ascii_graphic() } #[inline] fn is_ascii_whitespace (&self) -> bool { self.is_ascii_whitespace() } #[inline] fn is_ascii_control (&self) -> bool { self.is_ascii_control() } } } impl AsciiExt for u8 { type Owned = u8; delegate_ascii_methods!(); delegate_ascii_ctype_methods!(); } impl AsciiExt for char { type Owned = char; delegate_ascii_methods!(); delegate_ascii_ctype_methods!(); } impl AsciiExt for [u8] { type Owned = Vec<u8>; delegate_ascii_methods!(); #[inline] fn is_ascii_alphabetic(&self) -> bool { self.iter().all(|b| b.is_ascii_alphabetic()) } #[inline] fn is_ascii_uppercase(&self) -> bool { self.iter().all(|b| b.is_ascii_uppercase()) } #[inline] fn is_ascii_lowercase(&self) -> bool { self.iter().all(|b| b.is_ascii_lowercase()) } #[inline] fn is_ascii_alphanumeric(&self) -> bool { self.iter().all(|b| b.is_ascii_alphanumeric()) } #[inline] fn is_ascii_digit(&self) -> bool { self.iter().all(|b| b.is_ascii_digit()) } #[inline] fn is_ascii_hexdigit(&self) -> bool { self.iter().all(|b| b.is_ascii_hexdigit()) } #[inline] fn is_ascii_punctuation(&self) -> bool { self.iter().all(|b| b.is_ascii_punctuation()) } #[inline] fn is_ascii_graphic(&self) -> bool { self.iter().all(|b| b.is_ascii_graphic()) } #[inline] fn is_ascii_whitespace(&self) -> bool { self.iter().all(|b| b.is_ascii_whitespace()) } #[inline] fn is_ascii_control(&self) -> bool { self.iter().all(|b| b.is_ascii_control()) } } impl AsciiExt for str { type Owned = String; delegate_ascii_methods!(); #[inline] fn is_ascii_alphabetic(&self) -> bool { self.bytes().all(|b| b.is_ascii_alphabetic()) } #[inline] fn is_ascii_uppercase(&self) -> bool { self.bytes().all(|b| b.is_ascii_uppercase()) } #[inline] fn is_ascii_lowercase(&self) -> bool { self.bytes().all(|b| b.is_ascii_lowercase()) } #[inline] fn is_ascii_alphanumeric(&self) -> bool { self.bytes().all(|b| b.is_ascii_alphanumeric()) } #[inline] fn is_ascii_digit(&self) -> bool { self.bytes().all(|b| b.is_ascii_digit()) } #[inline] fn is_ascii_hexdigit(&self) -> bool { self.bytes().all(|b| b.is_ascii_hexdigit()) } #[inline] fn is_ascii_punctuation(&self) -> bool { self.bytes().all(|b| b.is_ascii_punctuation()) } #[inline] fn is_ascii_graphic(&self) -> bool { self.bytes().all(|b| b.is_ascii_graphic()) } #[inline] fn is_ascii_whitespace(&self) -> bool { self.bytes().all(|b| b.is_ascii_whitespace()) } #[inline] fn is_ascii_control(&self) -> bool { self.bytes().all(|b| b.is_ascii_control()) } }
#[rustfmt::skip] pub trait AsciiExt { type Owned; fn is_ascii(&self) -> bool; fn to_ascii_uppercase(&self) -> Self::Owned; fn to_ascii_lowercase(&self) -> Self::Owned; fn eq_ignore_ascii_case(&self, other: &Self) -> bool; fn make_ascii_uppercase(&mut self); fn make_ascii_lowercase(&mut self); fn is_ascii_alphabetic(&self) -> bool { unimplemented!(); } fn is_ascii_uppercase(&self) -> bool { unimplemented!(); } fn is_ascii_lowercase(&self) -> bool { unimplemented!(); } fn is_ascii_alphanumeric(&self) -> bool { unimplemented!(); } fn is_ascii_digit(&self) -> bool { unimplemented!(); } fn is_ascii_hexdigit(&self) -> bool { unimplemented!(); } fn is_ascii_punctuation(&self) -> bool { unimplemented!(); } fn is_ascii_graphic(&self) -> bool { unimplemented!(); } fn is_ascii_whitespace(&self) -> bool { unimplemented!(); } fn is_ascii_control(&self) -> bool { unimplemented!(); } } macro_rules! delegate_ascii_methods { () => { #[inline] fn is_ascii (&self) -> bool { self.is_ascii() } #[inline] fn to_ascii_uppercase (&self) -> Self::Owned { self.to_ascii_uppercase() } #[inline] fn to_ascii_lowercase (&self) -> Self::Owned { self.to_ascii_lowercase() } #[inline] fn eq_ignore_ascii_case (&self, other: &Self) -> bool { self.eq_ignore_ascii_case(other) } #[inline] fn make_ascii_uppercase (&mut self) { self.make_ascii_uppercase(); } #[inline] fn make_ascii_lowercase (&mut self) { self.make_ascii_lowercase(); } } } macro_rules! delegate_ascii_ctype_methods { () => { #[inline] fn is_ascii_alphabetic (&self) -> bool { self.is_ascii_alphabetic() } #[inline] fn is_ascii_uppercase (&self) -> bool { self.is_ascii_uppercase() } #[inline] fn is_ascii_lowercase (&self) -> bool { self.is_ascii_lowercase() } #[inline] fn is_ascii_alphanumeric(&self) -> bool { self.is_ascii_alphanu
alphanumeric(&self) -> bool { self.iter().all(|b| b.is_ascii_alphanumeric()) } #[inline] fn is_ascii_digit(&self) -> bool { self.iter().all(|b| b.is_ascii_digit()) } #[inline] fn is_ascii_hexdigit(&self) -> bool { self.iter().all(|b| b.is_ascii_hexdigit()) } #[inline] fn is_ascii_punctuation(&self) -> bool { self.iter().all(|b| b.is_ascii_punctuation()) } #[inline] fn is_ascii_graphic(&self) -> bool { self.iter().all(|b| b.is_ascii_graphic()) } #[inline] fn is_ascii_whitespace(&self) -> bool { self.iter().all(|b| b.is_ascii_whitespace()) } #[inline] fn is_ascii_control(&self) -> bool { self.iter().all(|b| b.is_ascii_control()) } } impl AsciiExt for str { type Owned = String; delegate_ascii_methods!(); #[inline] fn is_ascii_alphabetic(&self) -> bool { self.bytes().all(|b| b.is_ascii_alphabetic()) } #[inline] fn is_ascii_uppercase(&self) -> bool { self.bytes().all(|b| b.is_ascii_uppercase()) } #[inline] fn is_ascii_lowercase(&self) -> bool { self.bytes().all(|b| b.is_ascii_lowercase()) } #[inline] fn is_ascii_alphanumeric(&self) -> bool { self.bytes().all(|b| b.is_ascii_alphanumeric()) } #[inline] fn is_ascii_digit(&self) -> bool { self.bytes().all(|b| b.is_ascii_digit()) } #[inline] fn is_ascii_hexdigit(&self) -> bool { self.bytes().all(|b| b.is_ascii_hexdigit()) } #[inline] fn is_ascii_punctuation(&self) -> bool { self.bytes().all(|b| b.is_ascii_punctuation()) } #[inline] fn is_ascii_graphic(&self) -> bool { self.bytes().all(|b| b.is_ascii_graphic()) } #[inline] fn is_ascii_whitespace(&self) -> bool { self.bytes().all(|b| b.is_ascii_whitespace()) } #[inline] fn is_ascii_control(&self) -> bool { self.bytes().all(|b| b.is_ascii_control()) } }
meric() } #[inline] fn is_ascii_digit (&self) -> bool { self.is_ascii_digit() } #[inline] fn is_ascii_hexdigit (&self) -> bool { self.is_ascii_hexdigit() } #[inline] fn is_ascii_punctuation (&self) -> bool { self.is_ascii_punctuation() } #[inline] fn is_ascii_graphic (&self) -> bool { self.is_ascii_graphic() } #[inline] fn is_ascii_whitespace (&self) -> bool { self.is_ascii_whitespace() } #[inline] fn is_ascii_control (&self) -> bool { self.is_ascii_control() } } } impl AsciiExt for u8 { type Owned = u8; delegate_ascii_methods!(); delegate_ascii_ctype_methods!(); } impl AsciiExt for char { type Owned = char; delegate_ascii_methods!(); delegate_ascii_ctype_methods!(); } impl AsciiExt for [u8] { type Owned = Vec<u8>; delegate_ascii_methods!(); #[inline] fn is_ascii_alphabetic(&self) -> bool { self.iter().all(|b| b.is_ascii_alphabetic()) } #[inline] fn is_ascii_uppercase(&self) -> bool { self.iter().all(|b| b.is_ascii_uppercase()) } #[inline] fn is_ascii_lowercase(&self) -> bool { self.iter().all(|b| b.is_ascii_lowercase()) } #[inline] fn is_ascii_
random
[ { "content": "/// returns true if `ari` has been initialized.\n\npub fn initialized() -> bool {\n\n INITIALIZED.state() != OnceState::Done\n\n}\n\n\n\n/// keep `x`, preventing llvm from optimizing it away.\n", "file_path": "src/core/mod.rs", "rank": 0, "score": 147101.8094612884 }, { "content": "/// convert a singular `T` into a single element slice of `T`.\n\npub fn as_slice_mut<T>(item: &mut T) -> &mut [T] {\n\n // safe: the memory layout of a singular `T` is always the same as an array of one `T`.\n\n unsafe { std::slice::from_raw_parts_mut(item, 1) }\n\n}\n\n\n", "file_path": "src/core/mod.rs", "rank": 1, "score": 138906.01874258585 }, { "content": "/// convert an `Option<T>` into a zero or single element slice of `T`.\n\npub fn option_as_slice_mut<T>(value: &mut Option<T>) -> &mut [T] {\n\n match value {\n\n Some(x) => as_slice_mut(x),\n\n None => &mut [],\n\n }\n\n}\n\n\n\n/// a bitfield.\n\n///\n\n/// this is c ffi compatible, which means for example a `[u8; 4]` bitfield consumes 4 bytes of space. just like a\n\n/// u32-based c-style bitfield.\n\n///\n\n/// # examples.\n\n///\n\n/// ```\n\n/// # #![feature(type_ascription)]\n\n/// # use ari::BitField;\n\n///\n\n/// let mut x: BitField<[u8; 4], u32> = BitField::new([0u8; 4]);\n\n///\n", "file_path": "src/core/mod.rs", "rank": 2, "score": 132720.46718512455 }, { "content": "/// extensions to `bool`.\n\npub trait BoolExt {\n\n /// converts a true into `Some(())` and false into `None`.\n\n fn as_option(&self) -> Option<()>;\n\n}\n\n\n\nimpl BoolExt for bool {\n\n fn as_option(&self) -> Option<()> {\n\n match self {\n\n true => Some(()),\n\n false => None,\n\n }\n\n }\n\n}\n", "file_path": "src/core/mod.rs", "rank": 3, "score": 130983.83573087916 }, { "content": "// returns true if the file at `path` exists, and it is a file.\n\npub fn file_exists(path: impl AsRef<Path>) -> bool {\n\n match std::fs::metadata(path) {\n\n Ok(meta) => meta.is_file(),\n\n Err(_) => false,\n\n }\n\n}\n\n\n", "file_path": "src/fs/mod.rs", "rank": 5, "score": 120689.17559267647 }, { "content": "// returns true if the directory at `path` exists, and it is a directory.\n\npub fn directory_exists(path: impl AsRef<Path>) -> bool {\n\n match std::fs::metadata(path) {\n\n Ok(meta) => meta.is_dir(),\n\n Err(_) => false,\n\n }\n\n}\n\n\n\n\n", "file_path": "src/fs/mod.rs", "rank": 6, "score": 120689.17559267647 }, { "content": "pub fn aero_enabled() -> Result<bool, std::io::Error> {\n\n unsafe { crate::os::win::hr::call(|x| DwmIsCompositionEnabled(x)).map(|x| x != 0) }\n\n}\n\n\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\npub struct OsVersion {\n\n pub major: usize,\n\n pub minor: usize,\n\n pub build: usize,\n\n}\n\n\n\nimpl OsVersion {\n\n pub const fn new(major: usize, minor: usize, build: usize) -> OsVersion {\n\n OsVersion { major, minor, build }\n\n }\n\n\n\n pub const fn windows_7() -> OsVersion {\n\n OsVersion::new(6, 1, 0)\n\n }\n", "file_path": "src/os/win/mod.rs", "rank": 7, "score": 118349.35957688032 }, { "content": "/// clears a console `stream` by writing clear + reset ansi escapes into it.\n\npub fn clear_into(stream: &mut impl Write) -> Result<(), std::io::Error> {\n\n const CLEAR_CONSOLE: &[u8] = b\"\\x1b[2J\\x1b[1;1H\";\n\n\n\n stream.write_all(CLEAR_CONSOLE)\n\n}\n", "file_path": "src/console/mod.rs", "rank": 8, "score": 109834.21072467745 }, { "content": "pub fn _ari_path_append(destination: &mut PathBuf, path: impl AsRef<Path>) {\n\n let path = path.as_ref();\n\n let os = path.as_os_str();\n\n let bytes = os_str_as_u8_slice(os);\n\n\n\n if bytes.is_empty() {\n\n destination.push(os);\n\n } else {\n\n for bit in bytes.split(|x| *x == b'/' || *x == b'\\\\') {\n\n destination.push(unsafe { u8_slice_as_os_str(bit) });\n\n }\n\n }\n\n}\n\n\n\n\n", "file_path": "src/path/util.rs", "rank": 9, "score": 107768.78693093127 }, { "content": "/// a trait that encompasses all types.\n\npub trait Any {}\n\n\n\nimpl<T> Any for T {}\n\n\n\n/// an opaque error that be converted from any other error type.\n\n#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]\n\npub struct BlackHole;\n\n\n\nimpl<T> Into<Result<T, BlackHole>> for BlackHole {\n\n fn into(self) -> Result<T, BlackHole> {\n\n Err(BlackHole)\n\n }\n\n}\n\n\n\nimpl Display for BlackHole {\n\n fn fmt(&self, formatter: &mut Formatter) -> Result<(), std::fmt::Error> {\n\n writeln!(formatter, \"BlackHole\")\n\n }\n\n}\n\n\n", "file_path": "src/core/mod.rs", "rank": 10, "score": 107015.77504223227 }, { "content": "pub trait Float {\n\n fn is_nan(self) -> bool;\n\n}\n\n\n\nimpl Float for f32 {\n\n fn is_nan(self) -> bool {\n\n self.is_nan()\n\n }\n\n}\n\n\n\nimpl Float for f64 {\n\n fn is_nan(self) -> bool {\n\n self.is_nan()\n\n }\n\n}\n", "file_path": "src/cmp/mod.rs", "rank": 11, "score": 104309.0455922876 }, { "content": "// extension methods for `std::fs::File`\n\npub trait FileExt {\n\n // returns the number of bytes allocated for this file.\n\n fn allocation_size(&self) -> Result<u64, std::io::Error>;\n\n\n\n // allocates at least `size` bytes for this file. if the existing allocation is greater than `length`, then this\n\n // method has no effect.\n\n fn set_allocation_size(&self, length: u64) -> Result<(), std::io::Error>;\n\n}\n\n\n\nimpl FileExt for File {\n\n fn allocation_size(&self) -> Result<u64, std::io::Error> {\n\n crate::fs::sys::get_allocation_size(self)\n\n }\n\n\n\n fn set_allocation_size(&self, length: u64) -> Result<(), std::io::Error> {\n\n crate::fs::sys::set_allocation_size(self, length)\n\n }\n\n}\n\n\n\n\n\n#[derive(Clone, Debug)]\n\npub struct VolumeInformation {\n\n pub free_bytes: u64,\n\n pub available_bytes: u64,\n\n pub total_bytes: u64,\n\n pub allocation_granularity: u64,\n\n}\n\n\n", "file_path": "src/fs/mod.rs", "rank": 12, "score": 101836.26000429089 }, { "content": "pub trait PadString {\n\n fn pad_left(&self, width: usize) -> String {\n\n self.pad(width, ' ', TextAlignment::Right)\n\n }\n\n\n\n fn pad_right(&self, width: usize) -> String {\n\n self.pad(width, ' ', TextAlignment::Left)\n\n }\n\n\n\n fn pad_left_with(&self, width: usize, character: char) -> String {\n\n self.pad(width, character, TextAlignment::Right)\n\n }\n\n\n\n fn pad_right_with(&self, width: usize, character: char) -> String {\n\n self.pad(width, character, TextAlignment::Left)\n\n }\n\n\n\n fn pad_to_width_with_alignment(&self, width: usize, alignment: TextAlignment) -> String {\n\n self.pad(width, ' ', alignment)\n\n }\n", "file_path": "src/str/mod.rs", "rank": 13, "score": 101836.26000429089 }, { "content": "/// extensions to `std::vec::Vec`.\n\npub trait VecExt {\n\n /// clears this `Vec<t>`. if `T` is copy, this method optimizes the clear by truncating the vec's length to zero,\n\n /// unlike `Vec<T>::clear()`.\n\n fn clear_vec(&mut self);\n\n}\n\n\n\nimpl<T> VecExt for Vec<T> {\n\n default fn clear_vec(&mut self) {\n\n self.clear();\n\n }\n\n}\n\n\n\nimpl<T> VecExt for Vec<T>\n\nwhere\n\n T: Copy,\n\n{\n\n fn clear_vec(&mut self) {\n\n // safe: `T` is copy.\n\n unsafe {\n\n self.set_len(0);\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/core/mod.rs", "rank": 14, "score": 101836.26000429089 }, { "content": "pub trait ResetEvent {\n\n /// sets the state of the event to nonsignaled, causing threads to block.\n\n ///\n\n /// returns true if the operation succeeded.\n\n fn reset(&self);\n\n\n\n /// sets the state of the event to signaled, allowing one or more waiting threads to proceed.\n\n ///\n\n /// returns true if the operation succeeded.\n\n fn set(&self);\n\n\n\n /// wait for a signal.\n\n fn wait(&self);\n\n\n\n /// returns true if this wait received a signal, otherwise false.\n\n fn wait_until(&self, instant: Instant) -> bool;\n\n\n\n /// returns true if this wait received a signal, otherwise false.\n\n fn wait_duration(&self, duration: Duration) -> bool {\n\n self.wait_until(Instant::now() + duration)\n", "file_path": "src/sync/mod.rs", "rank": 15, "score": 101836.26000429089 }, { "content": "pub fn main() {\n\n if let Ok(profile) = std::env::var(\"PROFILE\") {\n\n println!(\"cargo:rustc-cfg={}\", profile);\n\n }\n\n}\n", "file_path": "build.rs", "rank": 16, "score": 101198.0896499283 }, { "content": "pub trait PathBufExt {\n\n /// appends a `path` to self. always treats `path` as a relative path.\n\n ///\n\n /// # examples\n\n ///\n\n /// ```\n\n /// # use ari::path::PathBufExt;\n\n /// # use std::path::PathBuf;\n\n ///\n\n /// let mut path = PathBuf::from(\"/var/bin\");\n\n /// path.append(\"/ari/hello.so\");\n\n ///\n\n /// let expected = PathBuf::from(\"/var/bin/ari/hello.so\");\n\n /// assert_eq!(path, expected);\n\n /// ```\n\n fn append(&mut self, path: impl AsRef<Path>);\n\n}\n\n\n\nimpl PathBufExt for PathBuf {\n\n fn append(&mut self, path: impl AsRef<Path>) {\n\n crate::path::util::_ari_path_append(self, path);\n\n }\n\n}\n", "file_path": "src/path/ext.rs", "rank": 17, "score": 99562.2568015586 }, { "content": "pub trait SeekExt: Seek {\n\n fn position(&mut self) -> Result<u64, std::io::Error> {\n\n self.seek(SeekFrom::Current(0))\n\n }\n\n}\n\n\n\nimpl<T> SeekExt for T where T: Seek + ?Sized\n\n{\n\n}\n", "file_path": "src/io/mod.rs", "rank": 18, "score": 96938.54014180167 }, { "content": "pub trait ReadExt: Read {\n\n #[inline]\n\n fn read_as_string(&mut self) -> Result<String, std::io::Error> {\n\n let mut string = String::new();\n\n\n\n self.read_to_string(&mut string)?;\n\n Ok(string)\n\n }\n\n\n\n #[inline]\n\n fn read_as_bytes(&mut self) -> Result<Vec<u8>, std::io::Error> {\n\n let mut data = vec![];\n\n\n\n self.read_to_end(&mut data)?;\n\n Ok(data)\n\n }\n\n\n\n #[inline]\n\n fn read_vec(&mut self, count: usize) -> Result<Vec<u8>, std::io::Error> {\n\n let mut data = Vec::with_capacity(count);\n", "file_path": "src/io/mod.rs", "rank": 19, "score": 96938.54014180167 }, { "content": "// todo: const-generics: make `BUFFER_LENGTH` a generic parameter with default value.\n\npub fn hash_read(source: &mut impl Read, algorithm: HashAlgorithm) -> Result<Hash, std::io::Error> {\n\n const BUFFER_LENGTH: usize = 1024 * 1024;\n\n\n\n let mut buffer = vec![0; BUFFER_LENGTH];\n\n let mut hash = IncrementalHash::new(algorithm);\n\n\n\n loop {\n\n match source.read(&mut buffer)? {\n\n 0 => return Ok(hash.finish()),\n\n read => hash.update(&buffer[0..read]),\n\n }\n\n }\n\n}\n", "file_path": "src/crypto/hash.rs", "rank": 20, "score": 95829.05576384222 }, { "content": "/// replaces `source` file with `destination` file, using `backup` as an intermediatary backup.\n\n///\n\n/// if `source`, `destination` or `backup` are on different volumes, this method will likely fail.\n\npub fn replace(\n\n source: impl AsRef<Path>,\n\n destination: impl AsRef<Path>,\n\n backup: impl AsRef<Path>,\n\n) -> Result<(), std::io::Error> {\n\n let source = source.as_ref();\n\n let destination = destination.as_ref();\n\n let backup = backup.as_ref();\n\n\n\n if crate::fs::file_exists(backup) {\n\n std::fs::remove_file(backup)?;\n\n }\n\n\n\n if crate::fs::file_exists(destination) {\n\n std::fs::rename(destination, backup)?;\n\n }\n\n\n\n match std::fs::rename(source, destination) {\n\n Ok(()) => {\n\n std::fs::remove_file(backup).ok();\n\n Ok(())\n\n },\n\n Err(e) => {\n\n std::fs::rename(backup, source).ok();\n\n Err(e)\n\n },\n\n }\n\n}\n\n\n\n\n", "file_path": "src/fs/mod.rs", "rank": 21, "score": 95658.74715148477 }, { "content": "pub fn entries(\n\n path: impl AsRef<Path>,\n\n option: SearchOption,\n\n) -> Result<impl Iterator<Item = Result<FsEntry, std::io::Error>> + Debug, std::io::Error> {\n\n Enumerator::new(path.as_ref(), option)\n\n}\n\n\n", "file_path": "src/fs/enumerate.rs", "rank": 22, "score": 95658.74715148477 }, { "content": "pub fn directories(\n\n path: impl AsRef<Path>,\n\n option: SearchOption,\n\n) -> Result<impl Iterator<Item = Result<FsEntry, std::io::Error>> + Debug, std::io::Error> {\n\n filtered_entries(path, option, |x| x.is_dir())\n\n}\n\n\n", "file_path": "src/fs/enumerate.rs", "rank": 23, "score": 95658.74715148477 }, { "content": "/// initializes `ari`, setting up the environment for use.\n\npub fn initialize() {\n\n INITIALIZED.call_once(|| {\n\n crate::os::initialize();\n\n });\n\n}\n\n\n", "file_path": "src/core/mod.rs", "rank": 24, "score": 95658.74715148477 }, { "content": "#[cfg(windows)]\n\npub fn initialize() {\n\n self::win::initialize();\n\n}\n\n\n\n\n\n#[cfg(windows)]\n\npub use crate::os::win::process::*;\n", "file_path": "src/os/mod.rs", "rank": 25, "score": 95658.74715148477 }, { "content": "pub fn files(\n\n path: impl AsRef<Path>,\n\n option: SearchOption,\n\n) -> Result<impl Iterator<Item = Result<FsEntry, std::io::Error>> + Debug, std::io::Error> {\n\n filtered_entries(path, option, |x| x.is_file())\n\n}\n\n\n\n\n", "file_path": "src/fs/enumerate.rs", "rank": 26, "score": 95658.74715148477 }, { "content": "/// a trait that describes how we treat return values in a hr-style function call.\n\npub trait HrLikeStatusCode: Copy {\n\n fn ok(self: Self) -> bool;\n\n fn error(self: Self) -> std::io::Error;\n\n}\n\n\n\nimpl HrLikeStatusCode for HRESULT {\n\n fn ok(self: HRESULT) -> bool {\n\n SUCCEEDED(self)\n\n }\n\n\n\n fn error(self: HRESULT) -> std::io::Error {\n\n std::io::Error::from_raw_os_error(self)\n\n }\n\n}\n\n\n\nimpl HrLikeStatusCode for bool {\n\n fn ok(self: bool) -> bool {\n\n self\n\n }\n\n\n", "file_path": "src/os/win/hr.rs", "rank": 27, "score": 91098.7916926505 }, { "content": "pub fn array_32() -> [u8; 32] {\n\n rand::random::<[u8; 32]>()\n\n}\n", "file_path": "src/random/mod.rs", "rank": 28, "score": 89091.42220901788 }, { "content": "pub fn array_16() -> [u8; 16] {\n\n rand::random::<[u8; 16]>()\n\n}\n\n\n", "file_path": "src/random/mod.rs", "rank": 29, "score": 89091.42220901788 }, { "content": "pub trait GenericHandleDtor<THandle>\n\nwhere\n\n THandle: Copy,\n\n{\n\n fn destroy(handle: THandle);\n\n}\n\n\n\n#[derive(Hash, PartialEq, Eq, PartialOrd, Ord)]\n\npub struct GenericHandle<THandle, TDestructor>\n\nwhere\n\n THandle: Copy + Eq,\n\n TDestructor: GenericHandleDtor<THandle>,\n\n{\n\n handle: THandle,\n\n phantom: PhantomData<TDestructor>,\n\n}\n\n\n\nimpl<THandle, TDestructor> GenericHandle<THandle, TDestructor>\n\nwhere\n\n THandle: Copy + Eq,\n", "file_path": "src/os/win/handle/generic_handle.rs", "rank": 30, "score": 87851.71160229167 }, { "content": "// asserts (at compile time) that some object is `Sync` or `Send`.\n\npub fn assert_send(_: impl Send) {}\n\n\n", "file_path": "src/core/mod.rs", "rank": 31, "score": 83059.678609706 }, { "content": "pub fn to_hex(data: &[u8]) -> String {\n\n format!(\"{:x}\", HexSlice(data))\n\n}\n\n\n", "file_path": "src/fmt/hex.rs", "rank": 32, "score": 83059.678609706 }, { "content": "pub fn assert_sync(_: impl Sync) {}\n\n\n", "file_path": "src/core/mod.rs", "rank": 33, "score": 83059.678609706 }, { "content": "#[cfg(feature = \"asm\")]\n\npub fn keep<T>(x: T) -> T {\n\n unsafe { llvm_asm![\"\" : : \"r\"(&x)] }\n\n x\n\n}\n\n\n", "file_path": "src/core/mod.rs", "rank": 34, "score": 81482.71073962163 }, { "content": "pub fn from_utf16_lossy(data: &[u16]) -> String {\n\n String::from_utf16_lossy(data)\n\n}\n\n\n", "file_path": "src/str/mod.rs", "rank": 35, "score": 81157.65208888921 }, { "content": "pub fn alphanumeric_string(length: usize) -> String {\n\n RandomAlphanumeric {\n\n random: &mut rand::thread_rng(),\n\n }\n\n .take(length)\n\n .collect()\n\n}\n\n\n", "file_path": "src/random/mod.rs", "rank": 36, "score": 81157.65208888921 }, { "content": "pub fn alpha_string(length: usize) -> String {\n\n RandomAlphabet {\n\n random: &mut rand::thread_rng(),\n\n }\n\n .take(length)\n\n .collect()\n\n}\n\n\n", "file_path": "src/random/mod.rs", "rank": 37, "score": 81157.65208888921 }, { "content": "pub fn vec(length: usize) -> Vec<u8> {\n\n let mut buffer = vec![0; length];\n\n let mut random = rand::thread_rng();\n\n\n\n random.fill(&mut buffer[..]);\n\n buffer\n\n}\n\n\n\n// todo: use const generics.\n\n\n", "file_path": "src/random/mod.rs", "rank": 38, "score": 79580.68421880485 }, { "content": "/// convert a singular `T` into a single element slice of `T`.\n\npub fn as_slice<T>(item: &T) -> &[T] {\n\n // safe: the memory layout of a singular `T` is always the same as an array of one `T`.\n\n unsafe { std::slice::from_raw_parts(item, 1) }\n\n}\n\n\n", "file_path": "src/core/mod.rs", "rank": 39, "score": 79580.68421880485 }, { "content": "pub fn to_utf16(string: &str) -> Vec<u16> {\n\n string.encode_utf16().collect()\n\n}\n\n\n", "file_path": "src/str/mod.rs", "rank": 40, "score": 79580.68421880485 }, { "content": "/// clears `stdout`.\n\npub fn clear() -> Result<(), std::io::Error> {\n\n clear_into(&mut std::io::stdout())\n\n}\n\n\n", "file_path": "src/console/mod.rs", "rank": 41, "score": 79580.68421880485 }, { "content": "pub fn from_utf16_lossy_null(data: &[u16]) -> String {\n\n let data = utf16_extent(data);\n\n\n\n String::from_utf16_lossy(data)\n\n}\n\n\n\n\n", "file_path": "src/str/mod.rs", "rank": 42, "score": 79392.07267754193 }, { "content": "pub fn from_utf16(data: &[u16]) -> OsString {\n\n OsString::from_wide(data)\n\n}\n\n\n", "file_path": "src/os/win/mod.rs", "rank": 43, "score": 79392.07267754193 }, { "content": "pub fn to_utf16_null(string: &str) -> Vec<u16> {\n\n string.encode_utf16().chain(Some(0)).collect()\n\n}\n\n\n\n\n", "file_path": "src/str/mod.rs", "rank": 44, "score": 77815.10480745757 }, { "content": "// returns the volume name for some path, intended for display.\n\npub fn volume_name(path: &Path) -> Option<String> {\n\n fn display(string: &OsStr) -> Cow<str> {\n\n string.to_string_lossy()\n\n }\n\n\n\n if let Some(component) = path.components().next() {\n\n let volume = match component {\n\n Component::Prefix(prefix) => match prefix.kind() {\n\n Prefix::Verbatim(name) => format!(\"{}\", display(name)),\n\n Prefix::VerbatimUNC(server, share) => format!(\"{}\\\\{}\", display(server), display(share)),\n\n Prefix::VerbatimDisk(disk) => format!(\"{}:\\\\\", disk as char),\n\n Prefix::DeviceNS(namespace) => format!(\"{}\", display(namespace)),\n\n Prefix::UNC(server, share) => format!(\"{}\\\\{}\\\\\", display(server), display(share)),\n\n Prefix::Disk(disk) => format!(\"{}:\\\\\", disk as char),\n\n },\n\n Component::RootDir => \"/\".to_owned(),\n\n Component::CurDir => \".\".to_owned(),\n\n Component::ParentDir => \"..\".to_owned(),\n\n Component::Normal(x) => x.to_string_lossy().into(),\n\n };\n\n\n\n Some(volume)\n\n } else {\n\n None\n\n }\n\n}\n", "file_path": "src/path/mod.rs", "rank": 45, "score": 77815.10480745757 }, { "content": "pub fn assert_send_sync(_: impl Send + Sync) {}\n\n\n", "file_path": "src/core/mod.rs", "rank": 46, "score": 77815.10480745757 }, { "content": "pub fn from_utf16_null(data: &[u16]) -> OsString {\n\n let length = data.iter().position(|x| *x == 0).unwrap_or(data.len());\n\n\n\n OsString::from_wide(&data[..length])\n\n}\n\n\n\n\n\npub unsafe fn from_utf16_ptr(data: *const u16, length: usize) -> OsString {\n\n assert![!data.is_null()];\n\n\n\n let slice = std::slice::from_raw_parts(data, length);\n\n OsString::from_wide(slice)\n\n}\n\n\n\npub unsafe fn from_utf16_ptr_null(data: *const u16) -> OsString {\n\n assert![!data.is_null()];\n\n\n\n let length = (0..std::isize::MAX)\n\n .position(|i| *data.offset(i) == 0)\n\n .expect(\"data must be null terminated\");\n\n\n\n let slice = std::slice::from_raw_parts(data, length);\n\n\n\n OsString::from_wide(slice)\n\n}\n\n\n\n\n\n// :: os versions and features.\n\n\n", "file_path": "src/os/win/mod.rs", "rank": 47, "score": 77748.76617469825 }, { "content": "pub fn string(alphabet: &[char], length: usize) -> String {\n\n RandomCharacter {\n\n alphabet: alphabet,\n\n random: &mut rand::thread_rng(),\n\n }\n\n .take(length)\n\n .collect()\n\n}\n\n\n", "file_path": "src/random/mod.rs", "rank": 48, "score": 76386.5534834346 }, { "content": "/// reads stdin until it encounters a new line, consuming it.\n\npub fn read_enter_key() -> Result<(), std::io::Error> {\n\n let mut stream = std::io::stdin();\n\n let character = &mut [0u8];\n\n\n\n loop {\n\n match stream.read(character)? {\n\n 1 if character[0] == b'\\n' => return Ok(()),\n\n 0 => continue,\n\n 1 => continue,\n\n _ => panic![\"invariant: read of one byte cannot exceed one byte.\"],\n\n }\n\n }\n\n}\n", "file_path": "src/io/stdin.rs", "rank": 49, "score": 76171.7983046139 }, { "content": "pub fn module_handle(name: &str) -> Option<HMODULE> {\n\n unsafe {\n\n let name = crate::os::win::to_utf16_null(name);\n\n let handle = GetModuleHandleW(name.as_ptr());\n\n\n\n match handle.is_null() {\n\n true => None,\n\n false => Some(handle),\n\n }\n\n }\n\n}\n\n\n\n\n\n#[derive(Debug)]\n\npub struct Library {\n\n handle: HMODULE,\n\n}\n\n\n\nimpl Library {\n\n pub fn open(name: &str) -> Result<Library, std::io::Error> {\n", "file_path": "src/os/win/library.rs", "rank": 50, "score": 76171.7983046139 }, { "content": "/// compares and returns the maximum of two values.\n\n///\n\n/// returns the second argument if the comparison determines them to be equal.\n\n///\n\n/// # examples.\n\n///\n\n/// ```\n\n/// assert_eq!(2, ari::cmp::partial_max(1, 2));\n\n/// assert_eq!(2, ari::cmp::partial_max(2, 2));\n\n/// ```\n\npub fn partial_max<T>(a: T, b: T) -> T\n\nwhere\n\n T: PartialOrd,\n\n{\n\n match a.partial_cmp(&b) {\n\n Some(Ordering::Greater) | Some(Ordering::Equal) => a,\n\n Some(Ordering::Less) | None => b,\n\n }\n\n}\n\n\n\n\n", "file_path": "src/cmp/mod.rs", "rank": 51, "score": 75086.40799561937 }, { "content": "/// a comparison function for floating point numbers.\n\n///\n\n/// nan values are ordered at the end.\n\n///\n\n/// # examples.\n\n///\n\n/// ```\n\n/// # use std::cmp::Ordering;\n\n///\n\n/// assert_eq!(Ordering::Less, ari::cmp::compare_floating(&1.0, &2.0));\n\n/// assert_eq!(Ordering::Equal, ari::cmp::compare_floating(&2.0, &2.0));\n\n/// ```\n\npub fn compare_floating<T>(a: &T, b: &T) -> Ordering\n\nwhere\n\n T: Float + Copy + PartialOrd,\n\n{\n\n match (a, b) {\n\n (x, y) if x.is_nan() && y.is_nan() => Ordering::Equal,\n\n (x, _) if x.is_nan() => Ordering::Greater,\n\n (_, y) if y.is_nan() => Ordering::Less,\n\n (_, _) => a.partial_cmp(b).unwrap(),\n\n }\n\n}\n\n\n\n\n", "file_path": "src/cmp/mod.rs", "rank": 52, "score": 75086.40799561937 }, { "content": "/// compares and returns the minimum of two values.\n\n///\n\n/// returns the first argument if the comparison determines them to be equal.\n\n///\n\n/// # examples.\n\n///\n\n/// ```\n\n/// assert_eq!(1, ari::cmp::partial_min(1, 2));\n\n/// assert_eq!(2, ari::cmp::partial_min(2, 2));\n\n/// ```\n\npub fn partial_min<T>(a: T, b: T) -> T\n\nwhere\n\n T: PartialOrd,\n\n{\n\n match a.partial_cmp(&b) {\n\n Some(Ordering::Less) | Some(Ordering::Equal) => a,\n\n Some(Ordering::Greater) | None => b,\n\n }\n\n}\n\n\n", "file_path": "src/cmp/mod.rs", "rank": 53, "score": 75086.40799561937 }, { "content": "pub fn from_utf16(data: &[u16]) -> Result<String, FromUtf16Error> {\n\n String::from_utf16(data)\n\n}\n\n\n", "file_path": "src/str/mod.rs", "rank": 54, "score": 74743.24698059093 }, { "content": "/// convert an `Option<T>` into a zero or single element slice of `T`.\n\npub fn option_as_slice<T>(value: &Option<T>) -> &[T] {\n\n match value {\n\n Some(x) => as_slice(x),\n\n None => &[],\n\n }\n\n}\n\n\n", "file_path": "src/core/mod.rs", "rank": 55, "score": 74743.24698059093 }, { "content": "pub fn hash_slice(data: &[u8], algorithm: HashAlgorithm) -> Hash {\n\n let digest = ring::digest::digest(algorithm.into(), data);\n\n\n\n Hash { digest }\n\n}\n\n\n", "file_path": "src/crypto/hash.rs", "rank": 56, "score": 73209.93671167154 }, { "content": "pub fn from_utf16_null(data: &[u16]) -> Result<String, FromUtf16Error> {\n\n let data = utf16_extent(data);\n\n\n\n String::from_utf16(data)\n\n}\n\n\n\n\n", "file_path": "src/str/mod.rs", "rank": 57, "score": 73209.93671167154 }, { "content": "pub fn os_version() -> Result<OsVersion, std::io::Error> {\n\n let x = unsafe {\n\n crate::os::win::hr::call(|x: *mut OSVERSIONINFOW| {\n\n (*x).dwOSVersionInfoSize = std::mem::size_of::<OSVERSIONINFOW>() as u32;\n\n\n\n GetVersionExW(x) != 0\n\n })\n\n }?;\n\n\n\n Ok(OsVersion {\n\n major: x.dwMajorVersion as usize,\n\n minor: x.dwMinorVersion as usize,\n\n build: x.dwBuildNumber as usize,\n\n })\n\n}\n", "file_path": "src/os/win/mod.rs", "rank": 58, "score": 71775.93627978118 }, { "content": "pub fn to_utf16(string: impl AsRef<OsStr>) -> Vec<u16> {\n\n string.as_ref().encode_wide().collect()\n\n}\n\n\n", "file_path": "src/os/win/mod.rs", "rank": 59, "score": 70475.79079196595 }, { "content": "/// invokes a closure, aborting the process if a panic occurs.\n\npub fn catch_abort<TFunction, TReturn>(function: TFunction) -> TReturn\n\nwhere\n\n TFunction: FnOnce() -> TReturn,\n\n{\n\n // \"unwind safe\" because we are immediately aborting after panic.\n\n std::panic::catch_unwind(AssertUnwindSafe(function)).unwrap_or_else(|_| std::process::abort())\n\n}\n\n\n\n\n\n/// a contiguous slice of `T` pointed to by `source`. ffi compatible.\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]\n\n#[repr(transparent)]\n\npub struct Bunch<T> {\n\n pub source: *mut T,\n\n}\n\n\n\nimpl<T> Bunch<T> {\n\n pub fn new(source: *mut T) -> Bunch<T> {\n\n Bunch { source }\n\n }\n", "file_path": "src/ffi/mod.rs", "rank": 60, "score": 69169.61971476361 }, { "content": "pub fn to_utf16_null(string: impl AsRef<OsStr>) -> Vec<u16> {\n\n string.as_ref().encode_wide().chain(Some(0)).collect()\n\n}\n\n\n\n\n", "file_path": "src/os/win/mod.rs", "rank": 61, "score": 69131.75465639813 }, { "content": "/// peforms a linear interpolation between `a` and `b`.\n\npub fn lerp<T, U>(a: T, b: T, amount: U) -> T\n\nwhere\n\n T: Add<Output = T> + Mul<U, Output = T>,\n\n U: Float + One,\n\n{\n\n a * (U::one() - amount) + b * amount\n\n}\n\n\n", "file_path": "src/math/mod.rs", "rank": 62, "score": 68627.23181321633 }, { "content": "pub fn from_hex(string: &str) -> Result<Vec<u8>, std::io::Error> {\n\n let mut data = Vec::with_capacity(string.len() / 2);\n\n let mut value = 0;\n\n let mut processed = 0;\n\n\n\n for byte in string.bytes() {\n\n value <<= 4;\n\n\n\n #[rustfmt::skip]\n\n match byte {\n\n b'A'..=b'F' => value |= byte - b'A' + 10,\n\n b'a'..=b'f' => value |= byte - b'a' + 10,\n\n b'0'..=b'9' => value |= byte - b'0',\n\n\n\n b' ' => { value >>= 4; continue; },\n\n b'\\r' => { value >>= 4; continue; },\n\n b'\\n' => { value >>= 4; continue; },\n\n b'\\t' => { value >>= 4; continue; },\n\n _ => return Err(std::io::ErrorKind::InvalidInput.into()),\n\n }\n", "file_path": "src/fmt/hex.rs", "rank": 63, "score": 68197.17777797549 }, { "content": "/// peforms a linear interpolation between `a` and `b`, returning a value that is bounded to `[a, b]`.\n\npub fn bounded_lerp<T, U>(a: T, b: T, amount: U) -> T\n\nwhere\n\n T: Add<Output = T> + Mul<U, Output = T>,\n\n U: Float + Zero + One,\n\n{\n\n lerp(a, b, match amount {\n\n amount if amount < U::zero() => U::zero(),\n\n amount if amount > U::one() => U::one(),\n\n amount => amount,\n\n })\n\n}\n", "file_path": "src/math/mod.rs", "rank": 64, "score": 67193.23138132597 }, { "content": "/// opens a text file, reads the contents of the file into a string, and then closes the file.\n\npub fn read_all_text(path: impl AsRef<Path>) -> Result<String, std::io::Error> {\n\n let bytes = read_all_bytes(path)?;\n\n\n\n String::from_utf8(bytes).map_err(|_| std::io::ErrorKind::InvalidData.into())\n\n}\n\n\n", "file_path": "src/fs/mod.rs", "rank": 65, "score": 64586.914816308396 }, { "content": "pub fn allocation_granularity(path: impl AsRef<Path>) -> Result<u64, std::io::Error> {\n\n get_volume_information(path).map(|x| x.allocation_granularity)\n\n}\n", "file_path": "src/fs/mod.rs", "rank": 66, "score": 64586.914816308396 }, { "content": "pub fn volume_available_bytes(path: impl AsRef<Path>) -> Result<u64, std::io::Error> {\n\n get_volume_information(path).map(|x| x.available_bytes)\n\n}\n\n\n", "file_path": "src/fs/mod.rs", "rank": 67, "score": 63399.150659115374 }, { "content": "pub fn volume_free_bytes(path: impl AsRef<Path>) -> Result<u64, std::io::Error> {\n\n get_volume_information(path).map(|x| x.free_bytes)\n\n}\n\n\n", "file_path": "src/fs/mod.rs", "rank": 68, "score": 63399.150659115374 }, { "content": "pub fn volume_total_bytes(path: impl AsRef<Path>) -> Result<u64, std::io::Error> {\n\n get_volume_information(path).map(|x| x.total_bytes)\n\n}\n\n\n", "file_path": "src/fs/mod.rs", "rank": 69, "score": 63399.150659115374 }, { "content": "/// opens a binary file, reads the contents of the file into a vec<u8>, and then closes the file.\n\npub fn read_all_bytes(path: impl AsRef<Path>) -> Result<Vec<u8>, std::io::Error> {\n\n let mut file = File::open(path)?;\n\n\n\n file.read_as_bytes()\n\n}\n\n\n", "file_path": "src/fs/mod.rs", "rank": 70, "score": 62471.6937646336 }, { "content": "/// creates a new file, write the contents to the file, and then closes the file. if the target file already exists, it\n\n/// is overwritten.\n\npub fn write_all_text(path: impl AsRef<Path>, data: String) -> Result<(), std::io::Error> {\n\n write_all_bytes(path, &data.into_bytes())\n\n}\n\n\n\n\n", "file_path": "src/fs/mod.rs", "rank": 71, "score": 62471.6937646336 }, { "content": "/// opens a text file, reads the all lines of the file into a `vec<string>`, and then closes the file.\n\npub fn read_all_lines(path: impl AsRef<Path>) -> Result<Vec<String>, std::io::Error> {\n\n let mut lines = read_all_text(path)?\n\n .split('\\n')\n\n .map(|x| x.to_owned())\n\n .collect::<Vec<_>>();\n\n\n\n for line in &mut lines {\n\n if line.ends_with('\\r') {\n\n line.pop();\n\n }\n\n }\n\n\n\n Ok(lines)\n\n}\n\n\n", "file_path": "src/fs/mod.rs", "rank": 72, "score": 62471.6937646336 }, { "content": "/// creates a new file, writes the specified byte slice to the file, and then closes the file. if the target file\n\n/// already exists, it is overwritten.\n\npub fn write_all_bytes(path: impl AsRef<Path>, data: &[u8]) -> Result<(), std::io::Error> {\n\n File::create(path).and_then(|mut file| file.write_all(data))\n\n}\n\n\n", "file_path": "src/fs/mod.rs", "rank": 73, "score": 62471.6937646336 }, { "content": "pub fn get_volume_information(path: impl AsRef<Path>) -> Result<VolumeInformation, std::io::Error> {\n\n crate::fs::sys::get_volume_information(path.as_ref())\n\n}\n\n\n", "file_path": "src/fs/mod.rs", "rank": 74, "score": 62279.49356673639 }, { "content": "trait Sip {\n\n fn c_rounds(_: &mut State);\n\n fn d_rounds(_: &mut State);\n\n}\n\n\n", "file_path": "src/crypto/sip.rs", "rank": 75, "score": 61330.63855414263 }, { "content": "/// returns all keys in an `Iterator<Item = (Key, Value)>`.\n\npub fn keys<K, V>(source: impl IntoIterator<Item = (K, V)>) -> impl Iterator<Item = K> {\n\n source.into_iter().map(|(k, _)| k)\n\n}\n\n\n", "file_path": "src/collections/mod.rs", "rank": 76, "score": 59694.10092581615 }, { "content": "/// returns all values in an `Iterator<Item = (Key, Value)>`.\n\npub fn values<K, V>(source: impl IntoIterator<Item = (K, V)>) -> impl Iterator<Item = V> {\n\n source.into_iter().map(|(_, v)| v)\n\n}\n", "file_path": "src/collections/mod.rs", "rank": 77, "score": 59694.10092581615 }, { "content": "/// calls a `function(..., *mut out_value) -> code`, transforming its return value into a `Result<T, TStatusCode>`.\n\n///\n\n/// # remarks.\n\n///\n\n/// this function provides you a pointer to a zero-initialized `T` which will be returned on success. the provided\n\n/// callback is expected to fill out this value when successful.\n\n///\n\n/// this pattern is very common in the windows api - especially for functions returning `HRESULT`s.\n\n///\n\n/// # return value.\n\n///\n\n/// if `function(..., *mut T)` was:\n\n/// - success: returns T\n\n/// - failure: returns StatusCode\n\npub fn raw_call<TFunction, TStatusCode, T>(function: TFunction) -> Result<T, TStatusCode>\n\nwhere\n\n TFunction: FnOnce(*mut T) -> TStatusCode,\n\n TStatusCode: HrLikeStatusCode,\n\n{\n\n let mut value = unsafe { std::mem::zeroed::<T>() };\n\n let returned = function(&mut value);\n\n\n\n match HrLikeStatusCode::ok(returned) {\n\n true => Ok(value),\n\n false => Err(returned),\n\n }\n\n}\n\n\n\n\n", "file_path": "src/os/win/hr.rs", "rank": 78, "score": 59383.387674533915 }, { "content": "/// calls a `function(..., *mut out_value) -> code`, transforming its return value into a `Result<T, std::io::Error>`.\n\n///\n\n/// # remarks.\n\n///\n\n/// this function provides you a pointer to a zero-initialized `T` which will be returned on success. the provided\n\n/// callback is expected to fill out this value when successful.\n\n///\n\n/// this pattern is very common in the windows api - especially for functions returning `HRESULT`s.\n\n///\n\n/// # return value.\n\n///\n\n/// if `function(..., *mut T)` was:\n\n/// - success: returns T\n\n/// - failure: returns std::io::Error (GetLastError)\n\npub fn call<TFunction, TStatusCode, T>(function: TFunction) -> Result<T, std::io::Error>\n\nwhere\n\n TFunction: FnOnce(*mut T) -> TStatusCode,\n\n TStatusCode: HrLikeStatusCode,\n\n{\n\n raw_call(function).map_err(TStatusCode::error)\n\n}\n\n\n", "file_path": "src/os/win/hr.rs", "rank": 79, "score": 58350.29412759016 }, { "content": "/// calls `function`, which returns an instance of `T` on success or `null` on failure.\n\n///\n\n/// on failure, the failure reason is queried using `GetLastError`.\n\npub fn gdi_call<TFunction, T>(function: TFunction) -> Result<GdiObject<T>, std::io::Error>\n\nwhere\n\n TFunction: FnOnce() -> *mut T,\n\n{\n\n let pointer = function();\n\n\n\n match pointer.is_null() {\n\n true => Err(std::io::Error::last_os_error()),\n\n false => Ok(GdiObject::new(pointer)),\n\n }\n\n}\n", "file_path": "src/os/win/gdi.rs", "rank": 80, "score": 58347.76775073593 }, { "content": "/// calls a `function(..., *mut out_value) -> code`, transforming its return value into a `Result<ComPtr<T>,\n\n/// std::io::Error>`.\n\n///\n\n/// # remarks.\n\n///\n\n/// this function provides you a pointer to a `*mut T`. the provided callback is expected update set this value to a\n\n/// valid com object on success.\n\n///\n\n/// this pattern is very common in the windows api.\n\n///\n\n/// # return value.\n\n///\n\n/// if `function(..., *mut T)` was:\n\n/// - success: returns ComPtr<T>\n\n/// - failure: returns TStatusCode\n\npub fn com_raw_call<TFunction, TStatusCode, T>(function: TFunction) -> Result<ComPtr<T>, TStatusCode>\n\nwhere\n\n TFunction: FnOnce(*mut *mut T) -> TStatusCode,\n\n TStatusCode: HrLikeStatusCode,\n\n{\n\n let mut value = std::ptr::null_mut();\n\n let returned = function(&mut value);\n\n\n\n match HrLikeStatusCode::ok(returned) {\n\n true => Ok(unsafe { ComPtr::new(value) }),\n\n false => Err(returned),\n\n }\n\n}\n\n\n\n\n", "file_path": "src/os/win/hr.rs", "rank": 81, "score": 55942.166995214364 }, { "content": "/// calls a `function(..., *mut out_value) -> code`, transforming its return value into a `Result<ComPtr<T>,\n\n/// std::io::Error>`.\n\n///\n\n/// # remarks.\n\n///\n\n/// this function provides you a pointer to a `*mut T`. the provided callback is expected update set this value to a\n\n/// valid com object on success.\n\n///\n\n/// this pattern is very common in the windows api.\n\n///\n\n/// # return value.\n\n///\n\n/// if `function(..., *mut T)` was:\n\n/// - success: returns ComPtr<T>\n\n/// - failure: returns std::io::Error (GetLastError)\n\npub fn com_call<TFunction, TStatusCode, T>(function: TFunction) -> Result<ComPtr<T>, std::io::Error>\n\nwhere\n\n TFunction: FnOnce(*mut *mut T) -> TStatusCode,\n\n TStatusCode: HrLikeStatusCode,\n\n{\n\n com_raw_call(function).map_err(TStatusCode::error)\n\n}\n\n\n", "file_path": "src/os/win/hr.rs", "rank": 82, "score": 54928.09279576353 }, { "content": "fn filtered_entries(\n\n path: impl AsRef<Path>,\n\n option: SearchOption,\n\n predicate: impl Fn(FileType) -> bool,\n\n) -> Result<impl Iterator<Item = Result<FsEntry, std::io::Error>> + Debug, std::io::Error> {\n\n macro_rules! bubble {\n\n ($expression: expr) => {{\n\n match $expression {\n\n Ok(x) => x,\n\n Err(e) => return Some(Err(e)),\n\n }\n\n }};\n\n }\n\n\n\n entries(path, option).map(move |sequence| {\n\n sequence.filter_map(move |r| {\n\n let entry = bubble![r];\n\n let ty = entry.ty();\n\n\n\n if predicate(ty) { Some(Ok(entry)) } else { None }\n\n })\n\n })\n\n}\n\n\n\n\n", "file_path": "src/fs/enumerate.rs", "rank": 83, "score": 50810.39185333243 }, { "content": "fn utf16_extent(data: &[u16]) -> &[u16] {\n\n let length = data.iter().position(|x| *x == 0).unwrap_or(data.len());\n\n\n\n &data[..length]\n\n}\n", "file_path": "src/str/mod.rs", "rank": 84, "score": 43865.07987055979 }, { "content": "// why this is ok: https://github.com/rust-lang/rust/blob/b16c7a235fa0f57fed6b7ec13ffd3cff1bcdd9ad/src/libstd/path.rs#L88\n\nfn os_str_as_u8_slice(os: &OsStr) -> &[u8] {\n\n unsafe { &*(os as *const OsStr as *const [u8]) }\n\n}\n\n\n\nunsafe fn u8_slice_as_os_str(slice: &[u8]) -> &OsStr {\n\n &*(slice as *const [u8] as *const OsStr)\n\n}\n", "file_path": "src/path/util.rs", "rank": 85, "score": 41198.7255226578 }, { "content": " /// ```\n\n #[inline]\n\n pub fn new(storage: TStorage) -> Self {\n\n BitField {\n\n storage,\n\n alignment: [],\n\n }\n\n }\n\n\n\n /// retrieves the bit at `index`.\n\n ///\n\n /// # examples.\n\n ///\n\n /// ```\n\n /// # use ari::BitField;\n\n ///\n\n /// let mut x: BitField<[u8; 4], u32> = BitField::new([0u8; 4]);\n\n ///\n\n /// assert_eq!(x.get(0), false);\n\n /// ```\n", "file_path": "src/core/mod.rs", "rank": 87, "score": 8.992947348492592 }, { "content": " ///\n\n /// let mut x: BitField<[u8; 4], u32> = BitField::new([0u8; 4]);\n\n ///\n\n /// x.set(0, true);\n\n ///\n\n /// assert_eq!(x.get(0), true);\n\n /// ```\n\n #[inline]\n\n pub fn set(&mut self, index: usize, value: bool) {\n\n let storage = self.storage.as_mut();\n\n\n\n debug_assert![storage.len() >= index / 8];\n\n\n\n #[rustfmt::skip]\n\n let shift = if cfg!(target_endian = \"little\") { index % 8 } else { 7 - (index % 8) };\n\n let byte = &mut storage[index / 8];\n\n let mask = 1 << shift;\n\n\n\n match value {\n\n true => *byte |= mask,\n", "file_path": "src/core/mod.rs", "rank": 88, "score": 8.771935629437941 }, { "content": "}\n\n\n\n\n\n/// an atomic boolean that always uses acquire and release semantics.\n\n#[derive(Debug)]\n\npub struct AtomicArBool {\n\n value: AtomicBool,\n\n}\n\n\n\nimpl AtomicArBool {\n\n pub const fn new(value: bool) -> AtomicArBool {\n\n AtomicArBool {\n\n value: AtomicBool::new(value),\n\n }\n\n }\n\n\n\n pub fn get(&self) -> bool {\n\n self.value.load(Ordering::Acquire)\n\n }\n\n\n", "file_path": "src/sync/mod.rs", "rank": 94, "score": 7.70825456397172 }, { "content": "impl AtomicRelaxedBool {\n\n pub const fn new(value: bool) -> AtomicRelaxedBool {\n\n AtomicRelaxedBool {\n\n value: AtomicBool::new(value),\n\n }\n\n }\n\n\n\n pub fn get(&self) -> bool {\n\n self.value.load(Ordering::Relaxed)\n\n }\n\n\n\n pub fn set(&self, value: bool) {\n\n self.value.store(value, Ordering::Relaxed)\n\n }\n\n}\n\n\n\nimpl Default for AtomicRelaxedBool {\n\n fn default() -> AtomicRelaxedBool {\n\n AtomicRelaxedBool {\n\n value: AtomicBool::default(),\n\n }\n\n }\n\n}\n", "file_path": "src/sync/mod.rs", "rank": 95, "score": 7.633397118076613 }, { "content": " pub fn as_mut(&mut self) -> &mut T {\n\n unsafe { self.pointer.as_mut() }\n\n }\n\n\n\n pub fn as_ptr(&self) -> *const T {\n\n self.pointer.as_ptr()\n\n }\n\n\n\n pub fn as_mut_ptr(&self) -> *mut T {\n\n self.pointer.as_ptr()\n\n }\n\n\n\n pub fn as_unknown(&self) -> *mut IUnknown {\n\n self.pointer.as_ptr() as *mut IUnknown\n\n }\n\n\n\n /// consumes this `ComPtr`, returning the wrapped pointer.\n\n ///\n\n /// after this function returns, the caller is responsible for the pointer instance previously managed by this\n\n /// `ComPtr`. callers should then invoke `IUnknown::Release` when done.\n", "file_path": "src/os/win/com.rs", "rank": 97, "score": 7.538366603195166 }, { "content": "use winapi::um::handleapi::CloseHandle;\n\nuse winapi::um::winnt::HANDLE;\n\n\n\n\n\n#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]\n\npub struct WindowsHandle {\n\n handle: HANDLE,\n\n}\n\n\n\nimpl WindowsHandle {\n\n pub fn new(handle: HANDLE) -> WindowsHandle {\n\n WindowsHandle { handle: handle }\n\n }\n\n\n\n pub fn create(\n\n create: impl FnOnce() -> HANDLE,\n\n valid: impl FnOnce(HANDLE) -> bool,\n\n ) -> Result<WindowsHandle, std::io::Error> {\n\n let handle = create();\n\n\n", "file_path": "src/os/win/handle/windows_handle.rs", "rank": 99, "score": 7.297452434486694 } ]
Rust
arch/rv32i/src/syscall.rs
wjakobczyk/tock
af1efe87f3f52f9dc923f0ca936091f7681ce59a
use core::fmt::Write; use crate::csr::mcause; use kernel; use kernel::syscall::ContextSwitchReason; #[derive(Default)] #[repr(C)] pub struct Riscv32iStoredState { regs: [usize; 31], pc: usize, mcause: usize, mtval: usize, } const R_RA: usize = 0; const R_SP: usize = 1; const R_A0: usize = 9; const R_A1: usize = 10; const R_A2: usize = 11; const R_A3: usize = 12; const R_A4: usize = 13; pub struct SysCall(()); impl SysCall { pub const unsafe fn new() -> SysCall { SysCall(()) } } impl kernel::syscall::UserspaceKernelBoundary for SysCall { type StoredState = Riscv32iStoredState; unsafe fn initialize_process( &self, stack_pointer: *const usize, _stack_size: usize, state: &mut Self::StoredState, ) -> Result<*const usize, ()> { state.regs.iter_mut().for_each(|x| *x = 0); state.pc = 0; state.mcause = 0; state.regs[R_SP] = stack_pointer as usize; Ok(stack_pointer as *mut usize) } unsafe fn set_syscall_return_value( &self, _stack_pointer: *const usize, state: &mut Self::StoredState, return_value: isize, ) { state.regs[R_A0] = return_value as usize; } unsafe fn set_process_function( &self, stack_pointer: *const usize, _remaining_stack_memory: usize, state: &mut Riscv32iStoredState, callback: kernel::procs::FunctionCall, ) -> Result<*mut usize, *mut usize> { state.regs[R_A0] = callback.argument0; state.regs[R_A1] = callback.argument1; state.regs[R_A2] = callback.argument2; state.regs[R_A3] = callback.argument3; state.regs[R_RA] = state.pc; state.pc = callback.pc; Ok(stack_pointer as *mut usize) } #[cfg(not(any(target_arch = "riscv32", target_os = "none")))] unsafe fn switch_to_process( &self, _stack_pointer: *const usize, _state: &mut Riscv32iStoredState, ) -> (*mut usize, ContextSwitchReason) { let _cause = mcause::Trap::from(_state.mcause); let _arg4 = _state.regs[R_A4]; unimplemented!() } #[cfg(all(target_arch = "riscv32", target_os = "none"))] unsafe fn switch_to_process( &self, _stack_pointer: *const usize, state: &mut Riscv32iStoredState, ) -> (*mut usize, ContextSwitchReason) { llvm_asm! (" // Before switching to the app we need to save the kernel registers to // the kernel stack. We then save the stack pointer in the mscratch // CSR (0x340) so we can retrieve it after returning to the kernel // from the app. // // A few values get saved to the kernel stack, including an app // register temporarily after entering the trap handler. Here is a // memory map to make it easier to keep track: // // ``` // 34*4(sp): <- original stack pointer // 33*4(sp): // 32*4(sp): x31 // 31*4(sp): x30 // 30*4(sp): x29 // 29*4(sp): x28 // 28*4(sp): x27 // 27*4(sp): x26 // 26*4(sp): x25 // 25*4(sp): x24 // 24*4(sp): x23 // 23*4(sp): x22 // 22*4(sp): x21 // 21*4(sp): x20 // 20*4(sp): x19 // 19*4(sp): x18 // 18*4(sp): x17 // 17*4(sp): x16 // 16*4(sp): x15 // 15*4(sp): x14 // 14*4(sp): x13 // 13*4(sp): x12 // 12*4(sp): x11 // 11*4(sp): x10 // 10*4(sp): x9 // 9*4(sp): x8 // 8*4(sp): x7 // 7*4(sp): x6 // 6*4(sp): x5 // 5*4(sp): x4 // 4*4(sp): x3 // 3*4(sp): x1 // 2*4(sp): _return_to_kernel (address to resume after trap) // 1*4(sp): *state (Per-process StoredState struct) // 0*4(sp): app s0 <- new stack pointer // ``` addi sp, sp, -34*4 // Move the stack pointer down to make room. sw x1, 3*4(sp) // Save all of the registers on the kernel stack. sw x3, 4*4(sp) sw x4, 5*4(sp) sw x5, 6*4(sp) sw x6, 7*4(sp) sw x7, 8*4(sp) sw x8, 9*4(sp) sw x9, 10*4(sp) sw x10, 11*4(sp) sw x11, 12*4(sp) sw x12, 13*4(sp) sw x13, 14*4(sp) sw x14, 15*4(sp) sw x15, 16*4(sp) sw x16, 17*4(sp) sw x17, 18*4(sp) sw x18, 19*4(sp) sw x19, 20*4(sp) sw x20, 21*4(sp) sw x21, 22*4(sp) sw x22, 23*4(sp) sw x23, 24*4(sp) sw x24, 25*4(sp) sw x25, 26*4(sp) sw x26, 27*4(sp) sw x27, 28*4(sp) sw x28, 29*4(sp) sw x29, 30*4(sp) sw x30, 31*4(sp) sw x31, 32*4(sp) sw $0, 1*4(sp) // Store process state pointer on stack as well. // We need to have the available for after the app // returns to the kernel so we can store its // registers. // From here on we can't allow the CPU to take interrupts // anymore, as that might result in the trap handler // believing that a context switch to userspace already // occurred (as mscratch is non-zero). Restore the userspace // state fully prior to enabling interrupts again // (implicitly using mret). // // If this is executed _after_ setting mscratch, this result // in the race condition of [PR // 2308](https://github.com/tock/tock/pull/2308) // Therefore, clear the following bits in mstatus first: // 0x00000008 -> bit 3 -> MIE (disabling interrupts here) // + 0x00001800 -> bits 11,12 -> MPP (switch to usermode on mret) li t0, 0x00001808 csrrc x0, 0x300, t0 // clear bits in mstatus, don't care about read // Afterwards, set the following bits in mstatus: // 0x00000080 -> bit 7 -> MPIE (enable interrupts on mret) li t0, 0x00000080 csrrs x0, 0x300, t0 // set bits in mstatus, don't care about read // Store the address to jump back to on the stack so that the trap // handler knows where to return to after the app stops executing. lui t0, %hi(_return_to_kernel) addi t0, t0, %lo(_return_to_kernel) sw t0, 2*4(sp) csrw 0x340, sp // Save stack pointer in mscratch. This allows // us to find it when the app returns back to // the kernel. // We have to set the mepc CSR with the PC we want the app to start // executing at. This has been saved in Riscv32iStoredState for us // (either when the app returned back to the kernel or in the // `set_process_function()` function). lw t0, 31*4($0) // Retrieve the PC from Riscv32iStoredState csrw 0x341, t0 // Set mepc CSR. This is the PC we want to go to. // Restore all of the app registers from what we saved. If this is the // first time running the app then most of these values are // irrelevant, However we do need to set the four arguments to the // `_start_ function in the app. If the app has been executing then this // allows the app to correctly resume. mv t0, $0 // Save the state pointer to a specific register. lw x1, 0*4(t0) // ra lw x2, 1*4(t0) // sp lw x3, 2*4(t0) // gp lw x4, 3*4(t0) // tp lw x6, 5*4(t0) // t1 lw x7, 6*4(t0) // t2 lw x8, 7*4(t0) // s0,fp lw x9, 8*4(t0) // s1 lw x10, 9*4(t0) // a0 lw x11, 10*4(t0) // a1 lw x12, 11*4(t0) // a2 lw x13, 12*4(t0) // a3 lw x14, 13*4(t0) // a4 lw x15, 14*4(t0) // a5 lw x16, 15*4(t0) // a6 lw x17, 16*4(t0) // a7 lw x18, 17*4(t0) // s2 lw x19, 18*4(t0) // s3 lw x20, 19*4(t0) // s4 lw x21, 20*4(t0) // s5 lw x22, 21*4(t0) // s6 lw x23, 22*4(t0) // s7 lw x24, 23*4(t0) // s8 lw x25, 24*4(t0) // s9 lw x26, 25*4(t0) // s10 lw x27, 26*4(t0) // s11 lw x28, 27*4(t0) // t3 lw x29, 28*4(t0) // t4 lw x30, 29*4(t0) // t5 lw x31, 30*4(t0) // t6 lw x5, 4*4(t0) // t0. Do last since we overwrite our pointer. // Call mret to jump to where mepc points, switch to user mode, and // start running the app. mret // This is where the trap handler jumps back to after the app stops // executing. _return_to_kernel: // We have already stored the app registers in the trap handler. We // can restore the kernel registers before resuming kernel code. lw x1, 3*4(sp) lw x3, 4*4(sp) lw x4, 5*4(sp) lw x5, 6*4(sp) lw x6, 7*4(sp) lw x7, 8*4(sp) lw x8, 9*4(sp) lw x9, 10*4(sp) lw x10, 11*4(sp) lw x11, 12*4(sp) lw x12, 13*4(sp) lw x13, 14*4(sp) lw x14, 15*4(sp) lw x15, 16*4(sp) lw x16, 17*4(sp) lw x17, 18*4(sp) lw x18, 19*4(sp) lw x19, 20*4(sp) lw x20, 21*4(sp) lw x21, 22*4(sp) lw x22, 23*4(sp) lw x23, 24*4(sp) lw x24, 25*4(sp) lw x25, 26*4(sp) lw x26, 27*4(sp) lw x27, 28*4(sp) lw x28, 29*4(sp) lw x29, 30*4(sp) lw x30, 31*4(sp) lw x31, 32*4(sp) addi sp, sp, 34*4 // Reset kernel stack pointer " : : "r"(state as *mut Riscv32iStoredState) : "memory" : "volatile"); let ret = match mcause::Trap::from(state.mcause) { mcause::Trap::Interrupt(_intr) => { ContextSwitchReason::Interrupted } mcause::Trap::Exception(excp) => { match excp { mcause::Exception::UserEnvCall | mcause::Exception::MachineEnvCall => { state.pc += 4; let syscall = kernel::syscall::Syscall::from_register_arguments( state.regs[R_A0] as u8, state.regs[R_A1], state.regs[R_A2], state.regs[R_A3], state.regs[R_A4], ); match syscall { Some(s) => ContextSwitchReason::SyscallFired { syscall: s }, None => ContextSwitchReason::Fault, } } _ => { ContextSwitchReason::Fault } } } }; let new_stack_pointer = state.regs[R_SP]; (new_stack_pointer as *mut usize, ret) } unsafe fn print_context( &self, stack_pointer: *const usize, state: &Riscv32iStoredState, writer: &mut dyn Write, ) { let _ = writer.write_fmt(format_args!( "\ \r\n R0 : {:#010X} R16: {:#010X}\ \r\n R1 : {:#010X} R17: {:#010X}\ \r\n R2 : {:#010X} R18: {:#010X}\ \r\n R3 : {:#010X} R19: {:#010X}\ \r\n R4 : {:#010X} R20: {:#010X}\ \r\n R5 : {:#010X} R21: {:#010X}\ \r\n R6 : {:#010X} R22: {:#010X}\ \r\n R7 : {:#010X} R23: {:#010X}\ \r\n R8 : {:#010X} R24: {:#010X}\ \r\n R9 : {:#010X} R25: {:#010X}\ \r\n R10: {:#010X} R26: {:#010X}\ \r\n R11: {:#010X} R27: {:#010X}\ \r\n R12: {:#010X} R28: {:#010X}\ \r\n R13: {:#010X} R29: {:#010X}\ \r\n R14: {:#010X} R30: {:#010X}\ \r\n R15: {:#010X} R31: {:#010X}\ \r\n PC : {:#010X} SP : {:#010X}\ \r\n\ \r\n mcause: {:#010X} (", 0, state.regs[15], state.regs[0], state.regs[16], state.regs[1], state.regs[17], state.regs[2], state.regs[18], state.regs[3], state.regs[19], state.regs[4], state.regs[20], state.regs[5], state.regs[21], state.regs[6], state.regs[22], state.regs[7], state.regs[23], state.regs[8], state.regs[24], state.regs[9], state.regs[25], state.regs[10], state.regs[26], state.regs[11], state.regs[27], state.regs[12], state.regs[28], state.regs[13], state.regs[29], state.regs[14], state.regs[30], state.pc, stack_pointer as usize, state.mcause, )); crate::print_mcause(mcause::Trap::from(state.mcause), writer); let _ = writer.write_fmt(format_args!( ")\ \r\n mtval: {:#010X}\ \r\n\r\n", state.mtval, )); } }
use core::fmt::Write; use crate::csr::mcause; use kernel; use kernel::syscall::ContextSwitchReason; #[derive(Default)] #[repr(C)] pub struct Riscv32iStoredState { regs: [usize; 31], pc: usize, mcause: usize, mtval: usize, } const R_RA: usize = 0; const R_SP: usize = 1; const R_A0: usize = 9; const R_A1: usize = 10; const R_A2: usize = 11; const R_A3: usize = 12; const R_A4: usize = 13; pub struct SysCall(()); impl SysCall { pub const unsafe fn new() -> SysCall { SysCall(()) } } impl kernel::syscall::UserspaceKernelBoundary for SysCall { type StoredState = Riscv32iStoredState;
unsafe fn set_syscall_return_value( &self, _stack_pointer: *const usize, state: &mut Self::StoredState, return_value: isize, ) { state.regs[R_A0] = return_value as usize; } unsafe fn set_process_function( &self, stack_pointer: *const usize, _remaining_stack_memory: usize, state: &mut Riscv32iStoredState, callback: kernel::procs::FunctionCall, ) -> Result<*mut usize, *mut usize> { state.regs[R_A0] = callback.argument0; state.regs[R_A1] = callback.argument1; state.regs[R_A2] = callback.argument2; state.regs[R_A3] = callback.argument3; state.regs[R_RA] = state.pc; state.pc = callback.pc; Ok(stack_pointer as *mut usize) } #[cfg(not(any(target_arch = "riscv32", target_os = "none")))] unsafe fn switch_to_process( &self, _stack_pointer: *const usize, _state: &mut Riscv32iStoredState, ) -> (*mut usize, ContextSwitchReason) { let _cause = mcause::Trap::from(_state.mcause); let _arg4 = _state.regs[R_A4]; unimplemented!() } #[cfg(all(target_arch = "riscv32", target_os = "none"))] unsafe fn switch_to_process( &self, _stack_pointer: *const usize, state: &mut Riscv32iStoredState, ) -> (*mut usize, ContextSwitchReason) { llvm_asm! (" // Before switching to the app we need to save the kernel registers to // the kernel stack. We then save the stack pointer in the mscratch // CSR (0x340) so we can retrieve it after returning to the kernel // from the app. // // A few values get saved to the kernel stack, including an app // register temporarily after entering the trap handler. Here is a // memory map to make it easier to keep track: // // ``` // 34*4(sp): <- original stack pointer // 33*4(sp): // 32*4(sp): x31 // 31*4(sp): x30 // 30*4(sp): x29 // 29*4(sp): x28 // 28*4(sp): x27 // 27*4(sp): x26 // 26*4(sp): x25 // 25*4(sp): x24 // 24*4(sp): x23 // 23*4(sp): x22 // 22*4(sp): x21 // 21*4(sp): x20 // 20*4(sp): x19 // 19*4(sp): x18 // 18*4(sp): x17 // 17*4(sp): x16 // 16*4(sp): x15 // 15*4(sp): x14 // 14*4(sp): x13 // 13*4(sp): x12 // 12*4(sp): x11 // 11*4(sp): x10 // 10*4(sp): x9 // 9*4(sp): x8 // 8*4(sp): x7 // 7*4(sp): x6 // 6*4(sp): x5 // 5*4(sp): x4 // 4*4(sp): x3 // 3*4(sp): x1 // 2*4(sp): _return_to_kernel (address to resume after trap) // 1*4(sp): *state (Per-process StoredState struct) // 0*4(sp): app s0 <- new stack pointer // ``` addi sp, sp, -34*4 // Move the stack pointer down to make room. sw x1, 3*4(sp) // Save all of the registers on the kernel stack. sw x3, 4*4(sp) sw x4, 5*4(sp) sw x5, 6*4(sp) sw x6, 7*4(sp) sw x7, 8*4(sp) sw x8, 9*4(sp) sw x9, 10*4(sp) sw x10, 11*4(sp) sw x11, 12*4(sp) sw x12, 13*4(sp) sw x13, 14*4(sp) sw x14, 15*4(sp) sw x15, 16*4(sp) sw x16, 17*4(sp) sw x17, 18*4(sp) sw x18, 19*4(sp) sw x19, 20*4(sp) sw x20, 21*4(sp) sw x21, 22*4(sp) sw x22, 23*4(sp) sw x23, 24*4(sp) sw x24, 25*4(sp) sw x25, 26*4(sp) sw x26, 27*4(sp) sw x27, 28*4(sp) sw x28, 29*4(sp) sw x29, 30*4(sp) sw x30, 31*4(sp) sw x31, 32*4(sp) sw $0, 1*4(sp) // Store process state pointer on stack as well. // We need to have the available for after the app // returns to the kernel so we can store its // registers. // From here on we can't allow the CPU to take interrupts // anymore, as that might result in the trap handler // believing that a context switch to userspace already // occurred (as mscratch is non-zero). Restore the userspace // state fully prior to enabling interrupts again // (implicitly using mret). // // If this is executed _after_ setting mscratch, this result // in the race condition of [PR // 2308](https://github.com/tock/tock/pull/2308) // Therefore, clear the following bits in mstatus first: // 0x00000008 -> bit 3 -> MIE (disabling interrupts here) // + 0x00001800 -> bits 11,12 -> MPP (switch to usermode on mret) li t0, 0x00001808 csrrc x0, 0x300, t0 // clear bits in mstatus, don't care about read // Afterwards, set the following bits in mstatus: // 0x00000080 -> bit 7 -> MPIE (enable interrupts on mret) li t0, 0x00000080 csrrs x0, 0x300, t0 // set bits in mstatus, don't care about read // Store the address to jump back to on the stack so that the trap // handler knows where to return to after the app stops executing. lui t0, %hi(_return_to_kernel) addi t0, t0, %lo(_return_to_kernel) sw t0, 2*4(sp) csrw 0x340, sp // Save stack pointer in mscratch. This allows // us to find it when the app returns back to // the kernel. // We have to set the mepc CSR with the PC we want the app to start // executing at. This has been saved in Riscv32iStoredState for us // (either when the app returned back to the kernel or in the // `set_process_function()` function). lw t0, 31*4($0) // Retrieve the PC from Riscv32iStoredState csrw 0x341, t0 // Set mepc CSR. This is the PC we want to go to. // Restore all of the app registers from what we saved. If this is the // first time running the app then most of these values are // irrelevant, However we do need to set the four arguments to the // `_start_ function in the app. If the app has been executing then this // allows the app to correctly resume. mv t0, $0 // Save the state pointer to a specific register. lw x1, 0*4(t0) // ra lw x2, 1*4(t0) // sp lw x3, 2*4(t0) // gp lw x4, 3*4(t0) // tp lw x6, 5*4(t0) // t1 lw x7, 6*4(t0) // t2 lw x8, 7*4(t0) // s0,fp lw x9, 8*4(t0) // s1 lw x10, 9*4(t0) // a0 lw x11, 10*4(t0) // a1 lw x12, 11*4(t0) // a2 lw x13, 12*4(t0) // a3 lw x14, 13*4(t0) // a4 lw x15, 14*4(t0) // a5 lw x16, 15*4(t0) // a6 lw x17, 16*4(t0) // a7 lw x18, 17*4(t0) // s2 lw x19, 18*4(t0) // s3 lw x20, 19*4(t0) // s4 lw x21, 20*4(t0) // s5 lw x22, 21*4(t0) // s6 lw x23, 22*4(t0) // s7 lw x24, 23*4(t0) // s8 lw x25, 24*4(t0) // s9 lw x26, 25*4(t0) // s10 lw x27, 26*4(t0) // s11 lw x28, 27*4(t0) // t3 lw x29, 28*4(t0) // t4 lw x30, 29*4(t0) // t5 lw x31, 30*4(t0) // t6 lw x5, 4*4(t0) // t0. Do last since we overwrite our pointer. // Call mret to jump to where mepc points, switch to user mode, and // start running the app. mret // This is where the trap handler jumps back to after the app stops // executing. _return_to_kernel: // We have already stored the app registers in the trap handler. We // can restore the kernel registers before resuming kernel code. lw x1, 3*4(sp) lw x3, 4*4(sp) lw x4, 5*4(sp) lw x5, 6*4(sp) lw x6, 7*4(sp) lw x7, 8*4(sp) lw x8, 9*4(sp) lw x9, 10*4(sp) lw x10, 11*4(sp) lw x11, 12*4(sp) lw x12, 13*4(sp) lw x13, 14*4(sp) lw x14, 15*4(sp) lw x15, 16*4(sp) lw x16, 17*4(sp) lw x17, 18*4(sp) lw x18, 19*4(sp) lw x19, 20*4(sp) lw x20, 21*4(sp) lw x21, 22*4(sp) lw x22, 23*4(sp) lw x23, 24*4(sp) lw x24, 25*4(sp) lw x25, 26*4(sp) lw x26, 27*4(sp) lw x27, 28*4(sp) lw x28, 29*4(sp) lw x29, 30*4(sp) lw x30, 31*4(sp) lw x31, 32*4(sp) addi sp, sp, 34*4 // Reset kernel stack pointer " : : "r"(state as *mut Riscv32iStoredState) : "memory" : "volatile"); let ret = match mcause::Trap::from(state.mcause) { mcause::Trap::Interrupt(_intr) => { ContextSwitchReason::Interrupted } mcause::Trap::Exception(excp) => { match excp { mcause::Exception::UserEnvCall | mcause::Exception::MachineEnvCall => { state.pc += 4; let syscall = kernel::syscall::Syscall::from_register_arguments( state.regs[R_A0] as u8, state.regs[R_A1], state.regs[R_A2], state.regs[R_A3], state.regs[R_A4], ); match syscall { Some(s) => ContextSwitchReason::SyscallFired { syscall: s }, None => ContextSwitchReason::Fault, } } _ => { ContextSwitchReason::Fault } } } }; let new_stack_pointer = state.regs[R_SP]; (new_stack_pointer as *mut usize, ret) } unsafe fn print_context( &self, stack_pointer: *const usize, state: &Riscv32iStoredState, writer: &mut dyn Write, ) { let _ = writer.write_fmt(format_args!( "\ \r\n R0 : {:#010X} R16: {:#010X}\ \r\n R1 : {:#010X} R17: {:#010X}\ \r\n R2 : {:#010X} R18: {:#010X}\ \r\n R3 : {:#010X} R19: {:#010X}\ \r\n R4 : {:#010X} R20: {:#010X}\ \r\n R5 : {:#010X} R21: {:#010X}\ \r\n R6 : {:#010X} R22: {:#010X}\ \r\n R7 : {:#010X} R23: {:#010X}\ \r\n R8 : {:#010X} R24: {:#010X}\ \r\n R9 : {:#010X} R25: {:#010X}\ \r\n R10: {:#010X} R26: {:#010X}\ \r\n R11: {:#010X} R27: {:#010X}\ \r\n R12: {:#010X} R28: {:#010X}\ \r\n R13: {:#010X} R29: {:#010X}\ \r\n R14: {:#010X} R30: {:#010X}\ \r\n R15: {:#010X} R31: {:#010X}\ \r\n PC : {:#010X} SP : {:#010X}\ \r\n\ \r\n mcause: {:#010X} (", 0, state.regs[15], state.regs[0], state.regs[16], state.regs[1], state.regs[17], state.regs[2], state.regs[18], state.regs[3], state.regs[19], state.regs[4], state.regs[20], state.regs[5], state.regs[21], state.regs[6], state.regs[22], state.regs[7], state.regs[23], state.regs[8], state.regs[24], state.regs[9], state.regs[25], state.regs[10], state.regs[26], state.regs[11], state.regs[27], state.regs[12], state.regs[28], state.regs[13], state.regs[29], state.regs[14], state.regs[30], state.pc, stack_pointer as usize, state.mcause, )); crate::print_mcause(mcause::Trap::from(state.mcause), writer); let _ = writer.write_fmt(format_args!( ")\ \r\n mtval: {:#010X}\ \r\n\r\n", state.mtval, )); } }
unsafe fn initialize_process( &self, stack_pointer: *const usize, _stack_size: usize, state: &mut Self::StoredState, ) -> Result<*const usize, ()> { state.regs.iter_mut().for_each(|x| *x = 0); state.pc = 0; state.mcause = 0; state.regs[R_SP] = stack_pointer as usize; Ok(stack_pointer as *mut usize) }
function_block-full_function
[ { "content": "/// State that is stored in each process's grant region to support IPC.\n\nstruct IPCData<const NUM_PROCS: usize> {\n\n /// An array of app slices that this application has shared with other\n\n /// applications.\n\n shared_memory: [Option<AppSlice<Shared, u8>>; NUM_PROCS],\n\n /// An array of callbacks this process has registered to receive callbacks\n\n /// from other services.\n\n client_callbacks: [Option<Callback>; NUM_PROCS],\n\n /// The callback setup by a service. Each process can only be one service.\n\n callback: Option<Callback>,\n\n}\n\n\n\nimpl<const NUM_PROCS: usize> Default for IPCData<NUM_PROCS> {\n\n fn default() -> IPCData<NUM_PROCS> {\n\n // need this until const_in_array_repeat_expressions is stable\n\n const NONE_APPSLICE: Option<AppSlice<Shared, u8>> = None;\n\n IPCData {\n\n shared_memory: [NONE_APPSLICE; NUM_PROCS],\n\n client_callbacks: [None; NUM_PROCS],\n\n callback: None,\n\n }\n", "file_path": "kernel/src/ipc.rs", "rank": 0, "score": 258361.44150513987 }, { "content": "pub fn debug_flush_queue_() {\n\n let writer = unsafe { get_debug_writer() };\n\n\n\n unsafe { DEBUG_QUEUE.as_deref_mut() }.map(|buffer| {\n\n buffer.dw.map(|dw| {\n\n dw.ring_buffer.map(|ring_buffer| {\n\n writer.write_ring_buffer(ring_buffer);\n\n ring_buffer.empty();\n\n });\n\n });\n\n });\n\n}\n\n\n\n/// This macro prints a new line to an internal ring buffer, the contents of\n\n/// which are only flushed with `debug_flush_queue!` and in the panic handler.\n\n#[macro_export]\n\nmacro_rules! debug_enqueue {\n\n () => ({\n\n debug_enqueue!(\"\")\n\n });\n", "file_path": "kernel/src/debug.rs", "rank": 1, "score": 227250.94463266467 }, { "content": "pub fn debug_regs() {\n\n debug!(\n\n \" registers:\\\n\n \\n USBFSM={:08x}\\\n\n \\n USBCON={:08x}\\\n\n \\n USBSTA={:08x}\\\n\n \\n UDESC={:08x}\\\n\n \\n UDCON={:08x}\\\n\n \\n UDINTE={:08x}\\\n\n \\n UDINT={:08x}\\\n\n \\n UERST={:08x}\\\n\n \\n UECFG0={:08x}\\\n\n \\n UECON0={:08x}\",\n\n USBFSM.read(),\n\n USBCON.read(),\n\n USBSTA.read(),\n\n UDESC.read(),\n\n UDCON.read(),\n\n UDINTE.read(),\n\n UDINT.read(),\n\n UERST.read(),\n\n UECFG0.read(),\n\n UECON0.read()\n\n );\n\n}\n\n*/\n", "file_path": "chips/sam4l/src/usbc/debug.rs", "rank": 2, "score": 223416.87303220172 }, { "content": "/// Are there any pending `DeferredCall`s?\n\npub fn has_tasks() -> bool {\n\n DEFERRED_CALL.load_relaxed() != 0\n\n}\n\n\n\n/// Represents a way to generate an asynchronous call without a hardware\n\n/// interrupt. Supports up to 32 possible deferrable tasks.\n\npub struct DeferredCall<T>(T);\n\n\n\nimpl<T: Into<usize> + TryFrom<usize> + Copy> DeferredCall<T> {\n\n /// Creates a new DeferredCall\n\n ///\n\n /// Only create one per task, preferably in the module that it will be used\n\n /// in.\n\n pub const unsafe fn new(task: T) -> Self {\n\n DeferredCall(task)\n\n }\n\n\n\n /// Set the `DeferredCall` as pending\n\n pub fn set(&self) {\n\n DEFERRED_CALL.fetch_or_relaxed(1 << self.0.into() as usize);\n", "file_path": "kernel/src/common/deferred_call.rs", "rank": 3, "score": 216301.0443983336 }, { "content": "/// Helper function to load processes from flash into an array of active\n\n/// processes. This is the default template for loading processes, but a board\n\n/// is able to create its own `load_processes()` function and use that instead.\n\n///\n\n/// Processes are found in flash starting from the given address and iterating\n\n/// through Tock Binary Format (TBF) headers. Processes are given memory out of\n\n/// the `app_memory` buffer until either the memory is exhausted or the\n\n/// allocated number of processes are created. A reference to each process is\n\n/// stored in the provided `procs` array. How process faults are handled by the\n\n/// kernel must be provided and is assigned to every created process.\n\n///\n\n/// This function is made `pub` so that board files can use it, but loading\n\n/// processes from slices of flash an memory is fundamentally unsafe. Therefore,\n\n/// we require the `ProcessManagementCapability` to call this function.\n\n///\n\n/// Returns `Ok(())` if process discovery went as expected. Returns a\n\n/// `ProcessLoadError` if something goes wrong during TBF parsing or process\n\n/// creation.\n\npub fn load_processes<C: Chip>(\n\n kernel: &'static Kernel,\n\n chip: &'static C,\n\n app_flash: &'static [u8],\n\n app_memory: &'static mut [u8],\n\n procs: &'static mut [Option<&'static dyn ProcessType>],\n\n fault_response: FaultResponse,\n\n _capability: &dyn ProcessManagementCapability,\n\n) -> Result<(), ProcessLoadError> {\n\n if config::CONFIG.debug_load_processes {\n\n debug!(\n\n \"Loading processes from flash={:#010X}-{:#010X} into sram={:#010X}-{:#010X}\",\n\n app_flash.as_ptr() as usize,\n\n app_flash.as_ptr() as usize + app_flash.len() - 1,\n\n app_memory.as_ptr() as usize,\n\n app_memory.as_ptr() as usize + app_memory.len() - 1\n\n );\n\n }\n\n\n\n let mut remaining_flash = app_flash;\n", "file_path": "kernel/src/process.rs", "rank": 4, "score": 210808.57136104754 }, { "content": "pub fn begin_debug_fmt(args: Arguments) {\n\n let writer = unsafe { get_debug_writer() };\n\n\n\n let _ = write(writer, args);\n\n let _ = writer.write_str(\"\\r\\n\");\n\n writer.publish_bytes();\n\n}\n\n\n", "file_path": "kernel/src/debug.rs", "rank": 5, "score": 206740.16403144802 }, { "content": "pub fn debug_enqueue_fmt(args: Arguments) {\n\n unsafe { DEBUG_QUEUE.as_deref_mut() }.map(|buffer| {\n\n let _ = write(buffer, args);\n\n let _ = buffer.write_str(\"\\r\\n\");\n\n });\n\n}\n\n\n", "file_path": "kernel/src/debug.rs", "rank": 6, "score": 206740.16403144802 }, { "content": "/// This trait must be implemented by the architecture of the chip Tock is\n\n/// running on. It allows the kernel to manage switching to and from processes\n\n/// in an architecture-agnostic manner.\n\npub trait UserspaceKernelBoundary {\n\n /// Some architecture-specific struct containing per-process state that must\n\n /// be kept while the process is not running. For example, for keeping CPU\n\n /// registers that aren't stored on the stack.\n\n ///\n\n /// Implementations should **not** rely on the `Default` constructor (custom\n\n /// or derived) for any initialization of a process's stored state. The\n\n /// initialization must happen in the `initialize_process()` function.\n\n type StoredState: Default;\n\n\n\n /// Called by the kernel after it has memory allocated to it but before it\n\n /// is allowed to begin executing. Allows for architecture-specific process\n\n /// setup, e.g. allocating a syscall stack frame.\n\n ///\n\n /// This function must also initialize the stored state (if needed).\n\n ///\n\n /// This function may be called multiple times on the same process. For\n\n /// example, if a process crashes and is to be restarted, this must be\n\n /// called. Or if the process is moved this may need to be called.\n\n unsafe fn initialize_process(\n", "file_path": "kernel/src/syscall.rs", "rank": 7, "score": 206203.17478484788 }, { "content": "pub fn abs(n: f32) -> f32 {\n\n f32::from_bits(n.to_bits() & 0x7FFF_FFFF)\n\n}\n\n\n", "file_path": "kernel/src/common/math.rs", "rank": 8, "score": 206166.94794322015 }, { "content": "pub fn log10(x: f32) -> f32 {\n\n //using change of base log10(x) = ln(x)/ln(10)\n\n let ln10_recip = f32::consts::LOG10_E;\n\n let fract_base_ln = ln10_recip;\n\n let value_ln = ln_1to2_series_approximation(x);\n\n value_ln * fract_base_ln\n\n}\n\n\n\n//-----------------------------------------------------------\n", "file_path": "kernel/src/common/math.rs", "rank": 9, "score": 206166.94794322015 }, { "content": "/// AtomicUsize with no CAS operations that works on targets that have \"no atomic\n\n/// support\" according to their specification. This makes it work on thumbv6\n\n/// platforms.\n\n///\n\n/// Borrowed from https://github.com/japaric/heapless/blob/master/src/ring_buffer/mod.rs\n\n/// See: https://github.com/japaric/heapless/commit/37c8b5b63780ed8811173dc1ec8859cd99efa9ad\n\nstruct AtomicUsize {\n\n v: UnsafeCell<usize>,\n\n}\n\n\n\nimpl AtomicUsize {\n\n pub(crate) const fn new(v: usize) -> AtomicUsize {\n\n AtomicUsize {\n\n v: UnsafeCell::new(v),\n\n }\n\n }\n\n\n\n pub(crate) fn load_relaxed(&self) -> usize {\n\n unsafe { intrinsics::atomic_load_relaxed(self.v.get()) }\n\n }\n\n\n\n pub(crate) fn store_relaxed(&self, val: usize) {\n\n unsafe { intrinsics::atomic_store_relaxed(self.v.get(), val) }\n\n }\n\n\n\n pub(crate) fn fetch_or_relaxed(&self, val: usize) {\n\n unsafe { intrinsics::atomic_store_relaxed(self.v.get(), self.load_relaxed() | val) }\n\n }\n\n}\n\n\n\nunsafe impl Sync for AtomicUsize {}\n\n\n\nstatic DEFERRED_CALL: AtomicUsize = AtomicUsize::new(0);\n\n\n", "file_path": "kernel/src/common/deferred_call.rs", "rank": 10, "score": 197080.68176233937 }, { "content": "/// This trait is implemented by process structs.\n\npub trait ProcessType {\n\n /// Returns the process's identifier\n\n fn appid(&self) -> AppId;\n\n\n\n /// Queue a `Task` for the process. This will be added to a per-process\n\n /// buffer and executed by the scheduler. `Task`s are some function the app\n\n /// should run, for example a callback or an IPC call.\n\n ///\n\n /// This function returns `true` if the `Task` was successfully enqueued,\n\n /// and `false` otherwise. This is represented as a simple `bool` because\n\n /// this is passed to the capsule that tried to schedule the `Task`.\n\n ///\n\n /// This will fail if the process is no longer active, and therefore cannot\n\n /// execute any new tasks.\n\n fn enqueue_task(&self, task: Task) -> bool;\n\n\n\n /// Returns whether this process is ready to execute.\n\n fn ready(&self) -> bool;\n\n\n\n /// Remove the scheduled operation from the front of the queue and return it\n", "file_path": "kernel/src/process.rs", "rank": 11, "score": 196686.41037206864 }, { "content": "/// Implementation required for the flash controller hardware. This\n\n/// should read, write and erase flash from the hardware using the\n\n/// flash controller.\n\n///\n\n/// This is the public trait for the Flash controller implementation.\n\n///\n\n/// The size of the regions (pages) must be the smallest size that can be\n\n/// erased in a single operation. This is specified as the constant `S`\n\n/// when implementing `FlashController` and `TicKV` and it must match\n\n/// the length of the `read_buffer`.\n\n///\n\n/// The start and end address of the FlashController must be aligned\n\n/// to the size of regions.\n\n/// All `region_number`s and `address`es are offset from zero. If you\n\n/// want to use flash that doesn't start at zero, or is a partition\n\n/// offset from the start of flash you will need to add that offset\n\n/// to the values in your implementation.\n\n///\n\n/// The boiler plate for an implementation will look something like this\n\n///\n\n/// ```rust\n\n/// use tickv::error_codes::ErrorCode;\n\n/// use tickv::flash_controller::FlashController;\n\n///\n\n/// #[derive(Default)]\n\n/// struct FlashCtrl {}\n\n///\n\n/// impl FlashCtrl {\n\n/// fn new() -> Self {\n\n/// Self { /* fields */ }\n\n/// }\n\n/// }\n\n///\n\n/// impl FlashController<1024> for FlashCtrl {\n\n/// fn read_region(&self, region_number: usize, offset: usize, buf: &mut [u8; 1024]) -> Result<(), ErrorCode> {\n\n/// unimplemented!()\n\n/// }\n\n///\n\n/// fn write(&self, address: usize, buf: &[u8]) -> Result<(), ErrorCode> {\n\n/// unimplemented!()\n\n/// }\n\n///\n\n/// fn erase_region(&self, region_number: usize) -> Result<(), ErrorCode> {\n\n/// unimplemented!()\n\n/// }\n\n/// }\n\n/// ```\n\npub trait FlashController<const S: usize> {\n\n /// This function must read the data from the flash region specified by\n\n /// `region_number` into `buf`. The length of the data read should be the\n\n /// same length as buf. `offset` indicates an offset into the region that\n\n /// should be read.\n\n ///\n\n /// On success it should return nothing, on failure it\n\n /// should return ErrorCode::ReadFail.\n\n ///\n\n /// If the read operation is to be complete asynchronously then\n\n /// `read_region()` can return `ErrorCode::ReadNotReady(region_number)`.\n\n /// By returning `ErrorCode::ReadNotReady(region_number)`\n\n /// `read_region()` can indicate that the operation should be retried in\n\n /// the future.\n\n /// After running the `continue_()` functions after a async\n\n /// `read_region()` has returned `ErrorCode::ReadNotReady(region_number)`\n\n /// the `read_region()` function will be called again and this time should\n\n /// return the data.\n\n fn read_region(\n\n &self,\n", "file_path": "libraries/tickv/src/flash_controller.rs", "rank": 12, "score": 196072.6010847733 }, { "content": "/// Get log base 2 of a number.\n\n/// Note: this is the floor of the result. Also, an input of 0 results in an\n\n/// output of 0\n\npub fn log_base_two(num: u32) -> u32 {\n\n if num == 0 {\n\n 0\n\n } else {\n\n 31 - num.leading_zeros()\n\n }\n\n}\n\n\n", "file_path": "kernel/src/common/math.rs", "rank": 13, "score": 194621.1972374323 }, { "content": "/// Log base 2 of 64 bit unsigned integers.\n\npub fn log_base_two_u64(num: u64) -> u32 {\n\n if num == 0 {\n\n 0\n\n } else {\n\n 63 - num.leading_zeros()\n\n }\n\n}\n\n\n\n// f32 log10 function adapted from [micromath](https://github.com/NeoBirth/micromath)\n\nconst EXPONENT_MASK: u32 = 0b01111111_10000000_00000000_00000000;\n\nconst EXPONENT_BIAS: u32 = 127;\n\n\n", "file_path": "kernel/src/common/math.rs", "rank": 14, "score": 191150.1552181449 }, { "content": "/// Get closest power of two greater than the given number.\n\npub fn closest_power_of_two(mut num: u32) -> u32 {\n\n num -= 1;\n\n num |= num >> 1;\n\n num |= num >> 2;\n\n num |= num >> 4;\n\n num |= num >> 8;\n\n num |= num >> 16;\n\n num += 1;\n\n num\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, Ord)]\n\npub struct PowerOfTwo(u32);\n\n\n\n/// Represents an integral power-of-two as an exponent\n\nimpl PowerOfTwo {\n\n /// Returns the base-2 exponent as a numeric type\n\n pub fn exp<R>(self) -> R\n\n where\n\n R: From<u32>,\n", "file_path": "kernel/src/common/math.rs", "rank": 15, "score": 187211.0182095367 }, { "content": "pub fn new_dma1_stream<'a>(dma: &'a Dma1) -> [Stream<'a>; 8] {\n\n [\n\n Stream::new(StreamId::Stream0, dma),\n\n Stream::new(StreamId::Stream1, dma),\n\n Stream::new(StreamId::Stream2, dma),\n\n Stream::new(StreamId::Stream3, dma),\n\n Stream::new(StreamId::Stream4, dma),\n\n Stream::new(StreamId::Stream5, dma),\n\n Stream::new(StreamId::Stream6, dma),\n\n Stream::new(StreamId::Stream7, dma),\n\n ]\n\n}\n\n\n", "file_path": "chips/stm32f4xx/src/dma1.rs", "rank": 16, "score": 182145.27913453584 }, { "content": "// Table 2.5\n\n// http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0553a/CHDBIBGJ.html\n\npub fn ipsr_isr_number_to_str(isr_number: usize) -> &'static str {\n\n match isr_number {\n\n 0 => \"Thread Mode\",\n\n 1 => \"Reserved\",\n\n 2 => \"NMI\",\n\n 3 => \"HardFault\",\n\n 4 => \"MemManage\",\n\n 5 => \"BusFault\",\n\n 6 => \"UsageFault\",\n\n 7..=10 => \"Reserved\",\n\n 11 => \"SVCall\",\n\n 12 => \"Reserved for Debug\",\n\n 13 => \"Reserved\",\n\n 14 => \"PendSV\",\n\n 15 => \"SysTick\",\n\n 16..=255 => \"IRQn\",\n\n _ => \"(Unknown! Illegal value?)\",\n\n }\n\n}\n\n\n", "file_path": "arch/cortex-m/src/lib.rs", "rank": 17, "score": 181123.89583408932 }, { "content": "fn exceeded_check(size: usize, allocated: usize) -> &'static str {\n\n if size > allocated {\n\n \" EXCEEDED!\"\n\n } else {\n\n \" \"\n\n }\n\n}\n\n\n\nimpl<C: 'static + Chip> Process<'_, C> {\n\n const INITIAL_APP_MEMORY_SIZE: usize = 3 * 1024;\n\n\n\n // Memory offset for callback ring buffer (10 element length).\n\n const CALLBACK_LEN: usize = 10;\n\n const CALLBACKS_OFFSET: usize = mem::size_of::<Task>() * Self::CALLBACK_LEN;\n\n\n\n // Memory offset to make room for this process's metadata.\n\n const PROCESS_STRUCT_OFFSET: usize = mem::size_of::<Process<C>>();\n\n\n\n pub(crate) unsafe fn create(\n\n kernel: &'static Kernel,\n", "file_path": "kernel/src/process.rs", "rank": 18, "score": 179761.95327884442 }, { "content": "/// NOP instruction (mock)\n\npub fn nop() {\n\n unimplemented!()\n\n}\n\n\n\n#[cfg(not(any(target_arch = \"riscv32\", target_os = \"none\")))]\n\n/// WFI instruction (mock)\n\npub unsafe fn wfi() {\n\n unimplemented!()\n\n}\n", "file_path": "arch/rv32i/src/support.rs", "rank": 19, "score": 178026.18853822554 }, { "content": "/// NOP instruction (mock)\n\npub fn nop() {\n\n unimplemented!()\n\n}\n\n\n\n#[cfg(not(any(target_arch = \"arm\", target_os = \"none\")))]\n\n/// WFI instruction (mock)\n\npub unsafe fn wfi() {\n\n unimplemented!()\n\n}\n\n\n\n#[cfg(not(any(target_arch = \"arm\", target_os = \"none\")))]\n\npub unsafe fn atomic<F, R>(_f: F) -> R\n\nwhere\n\n F: FnOnce() -> R,\n\n{\n\n unimplemented!()\n\n}\n", "file_path": "arch/cortex-m/src/support.rs", "rank": 20, "score": 178026.18853822554 }, { "content": "/// Implement this trait and use `set_client()` in order to receive callbacks.\n\npub trait Client<'a, T: DigestType> {\n\n /// This callback is called when the data has been added to the digest\n\n /// engine.\n\n /// On error or success `data` will contain a reference to the original\n\n /// data supplied to `add_data()`.\n\n fn add_data_done(&'a self, result: Result<(), ReturnCode>, data: &'static mut [u8]);\n\n\n\n /// This callback is called when a digest is computed.\n\n /// On error or success `digest` will contain a reference to the original\n\n /// data supplied to `run()`.\n\n fn hash_done(&'a self, result: Result<(), ReturnCode>, digest: &'static mut T);\n\n}\n\n\n", "file_path": "kernel/src/hil/digest.rs", "rank": 21, "score": 175478.08839617844 }, { "content": "/// Computes a digest (cryptographic hash) over data\n\npub trait Digest<'a, T: DigestType> {\n\n /// Set the client instance which will receive `hash_done()` and\n\n /// `add_data_done()` callbacks.\n\n /// This callback is called when the data has been added to the digest\n\n /// engine.\n\n /// The callback should follow the `Client` `add_data_done` callback.\n\n fn set_client(&'a self, client: &'a dyn Client<'a, T>);\n\n\n\n /// Add data to the digest block. This is the data that will be used\n\n /// for the hash function.\n\n /// Returns the number of bytes parsed on success\n\n /// There is no guarantee the data has been written until the `add_data_done()`\n\n /// callback is fired.\n\n /// On error the return value will contain a return code and the original data\n\n fn add_data(\n\n &self,\n\n data: LeasableBuffer<'static, u8>,\n\n ) -> Result<usize, (ReturnCode, &'static mut [u8])>;\n\n\n\n /// Request the hardware block to generate a Digest and stores the returned\n", "file_path": "kernel/src/hil/digest.rs", "rank": 22, "score": 175471.7313699796 }, { "content": "/// Setup the internal 32kHz RC oscillator.\n\npub fn enable_rc32k() {\n\n let rc32kcr = BSCIF.rc32kcr.extract();\n\n // Unlock the BSCIF::RC32KCR register\n\n BSCIF\n\n .unlock\n\n .write(Unlock::KEY.val(0xAA) + Unlock::ADDR.val(0x24));\n\n // Write the BSCIF::RC32KCR register.\n\n // Enable the generic clock source, the temperature compensation, and the\n\n // 32k output.\n\n BSCIF.rc32kcr.modify_no_read(\n\n rc32kcr,\n\n RC32Control::EN32K::OutputEnable\n\n + RC32Control::TCEN::TempCompensated\n\n + RC32Control::EN::GclkSourceEnable,\n\n );\n\n // Wait for it to be ready, although it feels like this won't do anything\n\n while !BSCIF.rc32kcr.is_set(RC32Control::EN) {}\n\n\n\n // Load magic calibration value for the 32KHz RC oscillator\n\n //\n\n // Unlock the BSCIF::RC32KTUNE register\n\n BSCIF\n\n .unlock\n\n .write(Unlock::KEY.val(0xAA) + Unlock::ADDR.val(0x28));\n\n // Write the BSCIF::RC32KTUNE register\n\n BSCIF\n\n .rc32ktune\n\n .write(RC32kTuning::COARSE.val(0x1d) + RC32kTuning::FINE.val(0x15));\n\n}\n\n\n", "file_path": "chips/sam4l/src/bscif.rs", "rank": 23, "score": 175003.63882300933 }, { "content": "pub fn oscillator_disable() {\n\n unlock(Register::OSCCTRL0);\n\n SCIF.oscctrl0.write(Oscillator::OSCEN::CLEAR);\n\n}\n\n\n", "file_path": "chips/sam4l/src/scif.rs", "rank": 24, "score": 175003.63882300933 }, { "content": "/// Transform descriptor structs into descriptor buffers that can be\n\n/// passed into the control endpoint handler. Each endpoint descriptor list\n\n/// corresponds to the matching index in the interface descriptor list. For\n\n/// example, if the interface descriptor list contains `[ID1, ID2, ID3]`,\n\n/// and the endpoint descriptors list is `[[ED1, ED2], [ED3, ED4, ED5],\n\n/// [ED6]]`, then the third interface descriptor (`ID3`) has one\n\n/// corresponding endpoint descriptor (`ED6`).\n\npub fn create_descriptor_buffers(\n\n device_descriptor: DeviceDescriptor,\n\n mut configuration_descriptor: ConfigurationDescriptor,\n\n interface_descriptor: &mut [InterfaceDescriptor],\n\n endpoint_descriptors: &[&[EndpointDescriptor]],\n\n hid_descriptor: Option<&HIDDescriptor>,\n\n cdc_descriptor: Option<&[CdcInterfaceDescriptor]>,\n\n) -> (DeviceBuffer, DescriptorBuffer) {\n\n // Create device descriptor buffer and fill.\n\n // Cell doesn't implement Copy, so here we are.\n\n let mut dev_buf = DeviceBuffer {\n\n buf: [\n\n Cell::default(),\n\n Cell::default(),\n\n Cell::default(),\n\n Cell::default(),\n\n Cell::default(),\n\n Cell::default(),\n\n Cell::default(),\n\n Cell::default(),\n", "file_path": "capsules/src/usb/descriptors.rs", "rank": 25, "score": 172150.45791999187 }, { "content": "/// Decompresses a 6loWPAN header into a full IPv6 header\n\n///\n\n/// This function decompresses the header found in `buf` and writes it\n\n/// `out_buf`. It does not, though, copy payload bytes or a non-compressed next\n\n/// header. As a result, the caller should copy the `buf.len - consumed`\n\n/// remaining bytes from `buf` to `out_buf`.\n\n///\n\n///\n\n/// Note that in the case of fragmentation, the total length of the IPv6\n\n/// packet cannot be inferred from a single frame, and is instead provided\n\n/// by the dgram_size field in the fragmentation header. Thus, if we are\n\n/// decompressing a fragment, we rely on the dgram_size field; otherwise,\n\n/// we infer the length from the size of buf.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `ctx_store` - ???\n\n///\n\n/// * `buf` - A slice containing the 6LowPAN packet along with its payload.\n\n///\n\n/// * `src_mac_addr` - the 16-bit MAC address of the frame sender.\n\n///\n\n/// * `dst_mac_addr` - the 16-bit MAC address of the frame receiver.\n\n///\n\n/// * `out_buf` - A buffer to write the output to. Must be at least large enough\n\n/// to store an IPv6 header (XX bytes).\n\n///\n\n/// * `dgram_size` - If `is_fragment` is `true`, this is used as the IPv6\n\n/// packets total payload size. Otherwise, this is ignored.\n\n///\n\n/// * `is_fragment` - ???\n\n///\n\n/// # Returns\n\n///\n\n/// `Ok((consumed, written))` if decompression is successful.\n\n///\n\n/// * `consumed` is the number of header bytes consumed from the 6LoWPAN header\n\n///\n\n/// * `written` is the number of uncompressed header bytes written into\n\n/// `out_buf`.\n\npub fn decompress(\n\n ctx_store: &dyn ContextStore,\n\n buf: &[u8],\n\n src_mac_addr: MacAddress,\n\n dst_mac_addr: MacAddress,\n\n out_buf: &mut [u8],\n\n dgram_size: u16,\n\n is_fragment: bool,\n\n) -> Result<(usize, usize), ()> {\n\n // Get the LOWPAN_IPHC header (the first two bytes are the header)\n\n let iphc_header_1: u8 = buf[0];\n\n let iphc_header_2: u8 = buf[1];\n\n let mut consumed: usize = 2;\n\n\n\n let mut ip6_header = IP6Header::new();\n\n let mut written: usize = mem::size_of::<IP6Header>();\n\n\n\n // Decompress CID and CIE fields if they exist\n\n let (src_ctx, dst_ctx) = decompress_cie(ctx_store, iphc_header_1, &buf, &mut consumed)?;\n\n\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_compression.rs", "rank": 26, "score": 172148.5592200582 }, { "content": "pub fn setup_rc_1mhz() {\n\n let rc1mcr = BSCIF.rc1mcr.extract();\n\n // Unlock the BSCIF::RC32KCR register\n\n BSCIF\n\n .unlock\n\n .write(Unlock::KEY.val(0xAA) + Unlock::ADDR.val(0x58));\n\n // Enable the RC1M\n\n BSCIF\n\n .rc1mcr\n\n .modify_no_read(rc1mcr, RC1MClockConfig::CLKOEN::Output);\n\n\n\n // Wait for the RC1M to be enabled\n\n while !BSCIF.rc1mcr.is_set(RC1MClockConfig::CLKOEN) {}\n\n}\n\n\n\npub unsafe fn disable_rc_1mhz() {\n\n let rc1mcr = BSCIF.rc1mcr.extract();\n\n // Unlock the BSCIF::RC32KCR register\n\n BSCIF\n\n .unlock\n\n .write(Unlock::KEY.val(0xAA) + Unlock::ADDR.val(0x58));\n\n // Disable the RC1M\n\n BSCIF\n\n .rc1mcr\n\n .modify_no_read(rc1mcr, RC1MClockConfig::CLKOEN::NotOutput);\n\n\n\n // Wait for the RC1M to be disabled\n\n while BSCIF.rc1mcr.is_set(RC1MClockConfig::CLKOEN) {}\n\n}\n", "file_path": "chips/sam4l/src/bscif.rs", "rank": 27, "score": 172145.46886695537 }, { "content": "/// Blinks a recognizable pattern forever.\n\n///\n\n/// If a multi-color LED is used for the panic pattern, it is\n\n/// advised to turn off other LEDs before calling this method.\n\n///\n\n/// Generally, boards should blink red during panic if possible,\n\n/// otherwise choose the 'first' or most prominent LED. Some\n\n/// boards may find it appropriate to blink multiple LEDs (e.g.\n\n/// one on the top and one on the bottom), thus this method\n\n/// accepts an array, however most will only need one.\n\npub fn panic_blink_forever<L: hil::led::Led>(leds: &mut [&L]) -> ! {\n\n leds.iter_mut().for_each(|led| led.init());\n\n loop {\n\n for _ in 0..1000000 {\n\n leds.iter_mut().for_each(|led| led.on());\n\n }\n\n for _ in 0..100000 {\n\n leds.iter_mut().for_each(|led| led.off());\n\n }\n\n for _ in 0..1000000 {\n\n leds.iter_mut().for_each(|led| led.on());\n\n }\n\n for _ in 0..500000 {\n\n leds.iter_mut().for_each(|led| led.off());\n\n }\n\n }\n\n}\n\n\n\n// panic! support routines\n\n///////////////////////////////////////////////////////////////////\n", "file_path": "kernel/src/debug.rs", "rank": 28, "score": 171811.98091331928 }, { "content": "/// Implement this trait and use `set_client()` in order to receive callbacks.\n\npub trait Client<'a, K: KeyType> {\n\n /// This callback is called when the append_key operation completes\n\n ///\n\n /// `result`: Nothing on success, 'ReturnCode' on error\n\n /// `unhashed_key`: The unhashed_key buffer\n\n /// `key_buf`: The key_buf buffer\n\n fn generate_key_complete(\n\n &'a self,\n\n result: Result<(), ReturnCode>,\n\n unhashed_key: &'static [u8],\n\n key_buf: &'static K,\n\n );\n\n\n\n /// This callback is called when the append_key operation completes\n\n ///\n\n /// `result`: Nothing on success, 'ReturnCode' on error\n\n /// `key`: The key buffer\n\n /// `value`: The value buffer\n\n fn append_key_complete(\n\n &'a self,\n", "file_path": "kernel/src/hil/kv_system.rs", "rank": 29, "score": 171632.5578631602 }, { "content": "pub fn begin_debug_verbose_fmt(args: Arguments, file_line: &(&'static str, u32)) {\n\n let writer = unsafe { get_debug_writer() };\n\n\n\n writer.increment_count();\n\n let count = writer.get_count();\n\n\n\n let (file, line) = *file_line;\n\n let _ = writer.write_fmt(format_args!(\"TOCK_DEBUG({}): {}:{}: \", count, file, line));\n\n let _ = write(writer, args);\n\n let _ = writer.write_str(\"\\r\\n\");\n\n writer.publish_bytes();\n\n}\n\n\n\n/// In-kernel `println()` debugging.\n\n#[macro_export]\n\nmacro_rules! debug {\n\n () => ({\n\n // Allow an empty debug!() to print the location when hit\n\n debug!(\"\")\n\n });\n", "file_path": "kernel/src/debug.rs", "rank": 30, "score": 171398.1954754254 }, { "content": "/// Parse a TBF header stored in flash.\n\n///\n\n/// The `header` must be a slice that only contains the TBF header. The caller\n\n/// should use the `parse_tbf_header_lengths()` function to determine this\n\n/// length to create the correct sized slice.\n\npub fn parse_tbf_header(\n\n header: &'static [u8],\n\n version: u16,\n\n) -> Result<types::TbfHeader, types::TbfParseError> {\n\n match version {\n\n 2 => {\n\n // Get the required base. This will succeed because we parsed the\n\n // first bit of the header already in `parse_tbf_header_lengths()`.\n\n let tbf_header_base: types::TbfHeaderV2Base = header.try_into()?;\n\n\n\n // Calculate checksum. The checksum is the XOR of each 4 byte word\n\n // in the header.\n\n let mut checksum: u32 = 0;\n\n\n\n // Get an iterator across 4 byte fields in the header.\n\n let header_iter = header.chunks_exact(4);\n\n\n\n // Iterate all chunks and XOR the chunks to compute the checksum.\n\n for (i, chunk) in header_iter.enumerate() {\n\n let word = u32::from_le_bytes(chunk.try_into()?);\n", "file_path": "libraries/tock-tbf/src/parse.rs", "rank": 31, "score": 169444.23403241206 }, { "content": "pub fn setup_dfll_rc32k_48mhz() {\n\n fn wait_dfll0_ready() {\n\n while !SCIF.pclksr.is_set(Interrupt::DFLL0RDY) {}\n\n }\n\n\n\n // Check to see if the DFLL is already setup or is not locked\n\n if !SCIF.dfll0conf.is_set(Dfll::EN) || !SCIF.pclksr.is_set(Interrupt::DFLL0LOCKF) {\n\n // Enable the GENCLK_SRC_RC32K\n\n if !bscif::rc32k_enabled() {\n\n bscif::enable_rc32k();\n\n }\n\n\n\n // Next, initialize closed-loop mode ...\n\n\n\n // Must do a SCIF sync before reading the SCIF registers?\n\n // 13.7.16: \"To be able to read the current value of DFLLxVAL or DFLLxRATIO, this bit must\n\n // be written to one. The updated value are available in DFLLxVAL or DFLLxRATIO when\n\n // PCLKSR.DFLL0RDY is set.\"\n\n SCIF.dfll0sync.set(0x01);\n\n wait_dfll0_ready();\n", "file_path": "chips/sam4l/src/scif.rs", "rank": 32, "score": 169438.6240944395 }, { "content": "/// Implement this trait and use `set_client()` in order to receive callbacks.\n\npub trait Client<'a, T: UsbHidType> {\n\n /// Called when a packet is received.\n\n /// This will return the buffer passed into `receive_buffer()` as well as\n\n /// the endpoint where the data was received. If the buffer length is smaller\n\n /// then the data length the buffer will only contain part of the packet and\n\n /// `result` will contain indicate an `ESIZE` error. Result will indicate\n\n /// `ECANCEL` if a receive was cancelled by `receive_cancel()` but the\n\n /// callback still occured. See `receive_cancel()` for more details.\n\n fn packet_received(&'a self, result: ReturnCode, buffer: &'static mut T, endpoint: usize);\n\n\n\n /// Called when a packet has been finished transmitting.\n\n /// This will return the buffer passed into `send_buffer()` as well as\n\n /// the endpoint where the data was sent. If not all of the data could\n\n /// be sent the `result` will contain the `ESIZE` error. Result will\n\n /// indicate `ECANCEL` if a send was cancelled by `send_cancel()`\n\n /// but the callback still occured. See `send_cancel()` for more\n\n /// details.\n\n fn packet_transmitted(&'a self, result: ReturnCode, buffer: &'static mut T, endpoint: usize);\n\n\n\n /// Called when checking if we can start a new receive operation.\n\n /// Should return true if we are ready to receive and not currently\n\n /// in the process of receiving anything. That is if we are currently\n\n /// idle.\n\n /// If there is an outstanding call to receive, a callback already\n\n /// waiting to be called then this will return false.\n\n fn can_receive(&'a self) -> bool;\n\n}\n\n\n", "file_path": "kernel/src/hil/usb_hid.rs", "rank": 33, "score": 167980.39053118354 }, { "content": "pub fn all_earlgrey_nexysvideo_tests() {\n\n println!(\"Tock board-runner starting...\");\n\n println!();\n\n println!(\"Running earlgrey_nexysvideo tests...\");\n\n earlgrey_nexysvideo_c_hello()\n\n .unwrap_or_else(|e| panic!(\"earlgrey_nexysvideo job failed with {}\", e));\n\n earlgrey_nexysvideo_blink()\n\n .unwrap_or_else(|e| panic!(\"earlgrey_nexysvideo job failed with {}\", e));\n\n earlgrey_nexysvideo_c_hello_and_printf_long()\n\n .unwrap_or_else(|e| panic!(\"earlgrey_nexysvideo job failed with {}\", e));\n\n earlgrey_nexysvideo_recv_short_and_recv_long()\n\n .unwrap_or_else(|e| panic!(\"earlgrey_nexysvideo job failed with {}\", e));\n\n earlgrey_nexysvideo_blink_and_c_hello_and_buttons()\n\n .unwrap_or_else(|e| panic!(\"earlgrey_nexysvideo job failed with {}\", e));\n\n earlgrey_nexysvideo_console_recv_short()\n\n .unwrap_or_else(|e| panic!(\"earlgrey_nexysvideo job failed with {}\", e));\n\n earlgrey_nexysvideo_console_timeout()\n\n .unwrap_or_else(|e| panic!(\"earlgrey_nexysvideo job failed with {}\", e));\n\n\n\n // Disabled by default.\n", "file_path": "tools/board-runner/src/earlgrey_nexysvideo.rs", "rank": 34, "score": 166871.3966229568 }, { "content": "pub fn compute_udp_checksum(\n\n ip6_header: &IP6Header,\n\n udp_header: &UDPHeader,\n\n udp_length: u16,\n\n payload: &[u8],\n\n) -> u16 {\n\n //This checksum is calculated according to some of the recommendations found in RFC 1071.\n\n\n\n let src_port = udp_header.get_src_port();\n\n let dst_port = udp_header.get_dst_port();\n\n let mut sum: u32 = 0;\n\n {\n\n //First, iterate through src/dst address and add them to the sum\n\n let mut i = 0;\n\n while i <= 14 {\n\n let msb_src: u16 = ((ip6_header.src_addr.0[i]) as u16) << 8;\n\n let lsb_src: u16 = ip6_header.src_addr.0[i + 1] as u16;\n\n let temp_src: u16 = msb_src + lsb_src;\n\n sum += temp_src as u32;\n\n\n", "file_path": "capsules/src/net/ipv6/ip_utils.rs", "rank": 35, "score": 166871.3966229568 }, { "content": "/// Parse the TBF header length and the entire length of the TBF binary.\n\n///\n\n/// ## Return\n\n///\n\n/// If all parsing is successful:\n\n/// - Ok((Version, TBF header length, entire TBF length))\n\n///\n\n/// If we cannot parse the header because we have run out of flash, or the\n\n/// values are entirely wrong we return `UnableToParse`. This means we have hit\n\n/// the end of apps in flash.\n\n/// - Err(InitialTbfParseError::UnableToParse)\n\n///\n\n/// Any other error we return an error and the length of the entire app so that\n\n/// we can skip over it and check for the next app.\n\n/// - Err(InitialTbfParseError::InvalidHeader(app_length))\n\npub fn parse_tbf_header_lengths(\n\n app: &'static [u8; 8],\n\n) -> Result<(u16, u16, u32), types::InitialTbfParseError> {\n\n // Version is the first 16 bits of the app TBF contents. We need this to\n\n // correctly parse the other lengths.\n\n //\n\n // ## Safety\n\n // We trust that the version number has been checked prior to running this\n\n // parsing code. That is, whatever loaded this application has verified that\n\n // the version is valid and therefore we can trust it.\n\n let version = u16::from_le_bytes([app[0], app[1]]);\n\n\n\n match version {\n\n 2 => {\n\n // In version 2, the next 16 bits after the version represent\n\n // the size of the TBF header in bytes.\n\n let tbf_header_size = u16::from_le_bytes([app[2], app[3]]);\n\n\n\n // The next 4 bytes are the size of the entire app's TBF space\n\n // including the header. This also must be checked before parsing\n", "file_path": "libraries/tock-tbf/src/parse.rs", "rank": 36, "score": 166871.3966229568 }, { "content": "pub fn compute_icmp_checksum(\n\n ipv6_header: &IP6Header,\n\n icmp_header: &ICMP6Header,\n\n payload: &[u8],\n\n) -> u16 {\n\n let mut sum: u32 = 0;\n\n\n\n // add ipv6 pseudo-header\n\n sum += compute_ipv6_ph_sum(ipv6_header);\n\n\n\n // add type and code\n\n let msb = (icmp_header.get_type_as_int() as u32) << 8;\n\n let lsb = icmp_header.get_code() as u32;\n\n sum += msb + lsb;\n\n\n\n // add options\n\n match icmp_header.get_options() {\n\n ICMP6HeaderOptions::Type1 { unused } | ICMP6HeaderOptions::Type3 { unused } => {\n\n sum += unused >> 16; // upper 16 bits\n\n sum += unused & 0xffff; // lower 16 bits\n", "file_path": "capsules/src/net/ipv6/ip_utils.rs", "rank": 37, "score": 166871.3966229568 }, { "content": "pub fn all_artemis_nano_tests() {\n\n println!(\"Tock board-runner starting...\");\n\n println!();\n\n println!(\"Running artemis_nano tests...\");\n\n artemis_nano_c_hello().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n artemis_nano_blink().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n // Doesn't work\n\n // artemis_nano_sensors().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n // Doesn't work\n\n // artemis_nano_c_hello_and_printf_long().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n artemis_nano_blink_and_c_hello_and_buttons()\n\n .unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n\n\n artemis_nano_malloc_test1().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n // Doesn't work\n\n // artemis_nano_stack_size_test1().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n // Doesn't work\n\n // artemis_nano_stack_size_test2().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n // Doesn't work\n\n // artemis_nano_mpu_stack_growth().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n artemis_nano_mpu_walk_region().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n artemis_nano_multi_alarm_test()\n\n .unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n // Doesn't work\n\n // artemis_nano_lua().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n artemis_nano_whileone().unwrap_or_else(|e| panic!(\"artemis_nano job failed with {}\", e));\n\n\n\n println!(\"artemis_nano SUCCESS.\");\n\n}\n", "file_path": "tools/board-runner/src/artemis_nano.rs", "rank": 38, "score": 166871.3966229568 }, { "content": "pub fn rc32k_enabled() -> bool {\n\n BSCIF.rc32kcr.is_set(RC32Control::EN)\n\n}\n\n\n", "file_path": "chips/sam4l/src/bscif.rs", "rank": 39, "score": 165474.45956187343 }, { "content": "/// Compresses an IPv6 header into a 6loWPAN header\n\n///\n\n/// Constructs a 6LoWPAN header in `buf` from the given IPv6 datagram and\n\n/// 16-bit MAC addresses. If the compression was successful, returns\n\n/// `Ok((consumed, written))`, where `consumed` is the number of header\n\n/// bytes consumed from the IPv6 datagram `written` is the number of\n\n/// compressed header bytes written into `buf`. Payload bytes and\n\n/// non-compressed next headers are not written, so the remaining `buf.len()\n\n/// - consumed` bytes must still be copied over to `buf`.\n\npub fn compress<'a>(\n\n ctx_store: &dyn ContextStore,\n\n ip6_packet: &'a IP6Packet<'a>,\n\n src_mac_addr: MacAddress,\n\n dst_mac_addr: MacAddress,\n\n mut buf: &mut [u8],\n\n) -> Result<(usize, usize), ()> {\n\n // Note that consumed should be constant, and equal sizeof(IP6Header)\n\n //let (mut consumed, ip6_header) = IP6Header::decode(ip6_datagram).done().ok_or(())?;\n\n let mut consumed = 40; // TODO\n\n let ip6_header = ip6_packet.header;\n\n\n\n //let mut next_headers: &[u8] = &ip6_datagram[consumed..];\n\n\n\n // The first two bytes are the LOWPAN_IPHC header\n\n let mut written: usize = 2;\n\n\n\n // Initialize the LOWPAN_IPHC header\n\n buf[0..2].copy_from_slice(&iphc::DISPATCH);\n\n\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_compression.rs", "rank": 40, "score": 165474.45956187343 }, { "content": "/// The 'types' of USB HID, this should define the size of send/received packets\n\npub trait UsbHidType: Copy + Clone + Sized {}\n\n\n\nimpl UsbHidType for [u8; 64] {}\n\nimpl UsbHidType for [u8; 32] {}\n\nimpl UsbHidType for [u8; 16] {}\n\nimpl UsbHidType for [u8; 8] {}\n\n\n", "file_path": "kernel/src/hil/usb_hid.rs", "rank": 41, "score": 164507.4886409938 }, { "content": "pub trait UsbHid<'a, T: UsbHidType> {\n\n /// Sets the buffer to be sent and starts a send transaction.\n\n /// Once the packet is sent the `packet_transmitted()` callback will\n\n /// be triggered and no more data will be sent until\n\n /// this is called again.\n\n ///\n\n /// Once this is called, the implementation will wait until either\n\n /// the packet is sent or `send_cancel()` is called.\n\n ///\n\n /// Calling `send_buffer()` while there is an outstanding\n\n /// `send_buffer()` operation will return EBUSY.\n\n ///\n\n /// On success returns the length of data to be sent.\n\n /// On failure returns an error code and the buffer passed in.\n\n fn send_buffer(&'a self, send: &'static mut T) -> Result<usize, (ReturnCode, &'static mut T)>;\n\n\n\n /// Cancels a send called by `send_buffer()`.\n\n /// If `send_cancel()` successfully cancels a send transaction\n\n /// before the transaction has been acted upon this function will\n\n /// return the buffer passed via `send_buffer()` and no callback\n", "file_path": "kernel/src/hil/usb_hid.rs", "rank": 42, "score": 164501.0028460557 }, { "content": "/// Determines if the chip can safely go into deep sleep without preventing\n\n/// currently active peripherals from operating.\n\n///\n\n/// We look at the PM's clock mask registers and compare them against a set of\n\n/// known masks that include no peripherals that can't operate in deep\n\n/// sleep (or that have no function during sleep). Specifically:\n\n///\n\n/// * HSB may only have clocks for the flash (and PicoCache), APBx bridges, and PDCA on.\n\n///\n\n/// * PBA may only have I2C Slaves on as they can self-wake.\n\n///\n\n/// * PBB may only have clocks for the flash, HRAMC1 (also flash related), and PDCA on.\n\n///\n\n/// * PBC and PBD may have any clocks on.\n\n///\n\n/// This means it is the responsibility of each peripheral to disable it's clock\n\n/// mask whenever it is idle.\n\n///\n\n/// A special note here regarding the PDCA (Peripheral DMA Controller) clock.\n\n/// If the core deep sleeps while a DMA operation is active, it is transparently paused\n\n/// and resumed when the core wakes again. If a peripheral needs a DMA operation to complete\n\n/// before sleeping, the peripheral should inhibit sleep. The rationale here is to allow deep\n\n/// sleep for an I2C Slave peripheral configured to use DMA.\n\n///\n\n/// We also special case GPIO (which is in PBCMASK), and just see if any interrupts are pending\n\n/// through the INTERRUPT_COUNT variable.\n\npub fn deep_sleep_ready() -> bool {\n\n // HSB clocks that can be enabled and the core is permitted to enter deep sleep.\n\n let deep_sleep_hsbmask: FieldValue<u32, ClockMaskHsb::Register> =\n\n /* added by us */ ClockMaskHsb::PDCA::SET +\n\n /* default */ ClockMaskHsb::FLASHCALW::SET +\n\n /* added by us */ ClockMaskHsb::FLASHCALW_PICOCACHE::SET +\n\n /* default */ ClockMaskHsb::APBA_BRIDGE::SET +\n\n /* default */ ClockMaskHsb::APBB_BRIDGE::SET +\n\n /* default */ ClockMaskHsb::APBC_BRIDGE::SET +\n\n /* default */ ClockMaskHsb::APBD_BRIDGE::SET;\n\n\n\n // PBA clocks that can be enabled and the core is permitted to enter deep sleep.\n\n let deep_sleep_pbamask: FieldValue<u32, ClockMaskPba::Register> =\n\n /* added by us */ ClockMaskPba::TWIS0::SET +\n\n /* added by us */ ClockMaskPba::TWIS1::SET;\n\n\n\n // PBB clocks that can be enabled and the core is permitted to enter deep sleep.\n\n let deep_sleep_pbbmask: FieldValue<u32, ClockMaskPbb::Register> =\n\n /* default */ ClockMaskPbb::FLASHCALW::SET +\n\n /* added by us */ ClockMaskPbb::HRAMC1::SET +\n", "file_path": "chips/sam4l/src/pm.rs", "rank": 43, "score": 162770.8907133302 }, { "content": "pub fn unlock(register: Register) {\n\n SCIF.unlock\n\n .write(Unlock::KEY.val(0xAA) + Unlock::ADDR.val(register as u32));\n\n}\n\n\n", "file_path": "chips/sam4l/src/scif.rs", "rank": 44, "score": 159965.92517933733 }, { "content": "pub fn enable_clock(clock: Clock) {\n\n match clock {\n\n Clock::HSB(v) => mask_clock!(HSB_MASK_OFFSET: hsbmask | 1 << (v as u32)),\n\n Clock::PBA(v) => mask_clock!(PBA_MASK_OFFSET: pbamask | 1 << (v as u32)),\n\n Clock::PBB(v) => mask_clock!(PBB_MASK_OFFSET: pbbmask | 1 << (v as u32)),\n\n Clock::PBC(v) => mask_clock!(PBC_MASK_OFFSET: pbcmask | 1 << (v as u32)),\n\n Clock::PBD(v) => mask_clock!(PBD_MASK_OFFSET: pbdmask | 1 << (v as u32)),\n\n }\n\n}\n\n\n", "file_path": "chips/sam4l/src/pm.rs", "rank": 45, "score": 157259.08040682148 }, { "content": "pub fn oscillator_enable(internal: bool) {\n\n let mode = if internal {\n\n Oscillator::MODE::Crystal\n\n } else {\n\n Oscillator::MODE::External\n\n };\n\n unlock(Register::OSCCTRL0);\n\n SCIF.oscctrl0.write(Oscillator::OSCEN::SET + mode);\n\n}\n\n\n", "file_path": "chips/sam4l/src/scif.rs", "rank": 46, "score": 157259.08040682148 }, { "content": "pub fn disable_clock(clock: Clock) {\n\n match clock {\n\n Clock::HSB(v) => mask_clock!(HSB_MASK_OFFSET: hsbmask & !(1 << (v as u32))),\n\n Clock::PBA(v) => mask_clock!(PBA_MASK_OFFSET: pbamask & !(1 << (v as u32))),\n\n Clock::PBB(v) => mask_clock!(PBB_MASK_OFFSET: pbbmask & !(1 << (v as u32))),\n\n Clock::PBC(v) => mask_clock!(PBC_MASK_OFFSET: pbcmask & !(1 << (v as u32))),\n\n Clock::PBD(v) => mask_clock!(PBD_MASK_OFFSET: pbdmask & !(1 << (v as u32))),\n\n }\n\n}\n\n\n", "file_path": "chips/sam4l/src/pm.rs", "rank": 47, "score": 157259.08040682148 }, { "content": "/// The generic trait that particular kernel level memory protection unit\n\n/// implementations need to implement.\n\n///\n\n/// This trait provides generic functionality to extend the MPU trait above\n\n/// to also allow the kernel to protect itself. It is expected that only a\n\n/// limited number of SoCs can support this, which is why it is a seperate\n\n/// implementation.\n\npub trait KernelMPU {\n\n /// MPU-specific state that defines a particular configuration for the kernel\n\n /// MPU.\n\n /// That is, this should contain all of the required state such that the\n\n /// implementation can be passed an object of this type and it should be\n\n /// able to correctly and entirely configure the MPU.\n\n ///\n\n /// It is `Default` so we can create empty state when the kernel is\n\n /// created, and `Display` so that the `panic!()` output can display the\n\n /// current state to help with debugging.\n\n type KernelMpuConfig: Default + Display;\n\n\n\n /// Mark a region of memory that the Tock kernel owns.\n\n ///\n\n /// This function will optionally set the MPU to enforce the specified\n\n /// constraints for all accessess (even from the kernel).\n\n /// This should be used to mark read/write/execute areas of the Tock\n\n /// kernel to have the hardware enforce those permissions.\n\n ///\n\n /// If the KernelMPU trait is supported a board should use this function\n", "file_path": "kernel/src/platform/mpu.rs", "rank": 48, "score": 153559.96266304672 }, { "content": "pub fn generic_clock_disable(clock: GenericClock) {\n\n generic_clock_control_write(clock, GenericClockControl::CEN::CLEAR);\n\n}\n\n\n", "file_path": "chips/sam4l/src/scif.rs", "rank": 49, "score": 152253.71228748816 }, { "content": "/// State for helping with debugging apps.\n\n///\n\n/// These pointers and counters are not strictly required for kernel operation,\n\n/// but provide helpful information when an app crashes.\n\nstruct ProcessDebug {\n\n /// If this process was compiled for fixed addresses, save the address\n\n /// it must be at in flash. This is useful for debugging and saves having\n\n /// to re-parse the entire TBF header.\n\n fixed_address_flash: Option<u32>,\n\n\n\n /// If this process was compiled for fixed addresses, save the address\n\n /// it must be at in RAM. This is useful for debugging and saves having\n\n /// to re-parse the entire TBF header.\n\n fixed_address_ram: Option<u32>,\n\n\n\n /// Where the process has started its heap in RAM.\n\n app_heap_start_pointer: Option<*const u8>,\n\n\n\n /// Where the start of the stack is for the process. If the kernel does the\n\n /// PIC setup for this app then we know this, otherwise we need the app to\n\n /// tell us where it put its stack.\n\n app_stack_start_pointer: Option<*const u8>,\n\n\n\n /// How low have we ever seen the stack pointer.\n", "file_path": "kernel/src/process.rs", "rank": 50, "score": 150602.21065277862 }, { "content": "pub fn is_clock_enabled(clock: Clock) -> bool {\n\n match clock {\n\n Clock::HSB(v) => get_clock!(HSB_MASK_OFFSET: hsbmask & (1 << (v as u32))),\n\n Clock::PBA(v) => get_clock!(PBA_MASK_OFFSET: pbamask & (1 << (v as u32))),\n\n Clock::PBB(v) => get_clock!(PBB_MASK_OFFSET: pbbmask & (1 << (v as u32))),\n\n Clock::PBC(v) => get_clock!(PBC_MASK_OFFSET: pbcmask & (1 << (v as u32))),\n\n Clock::PBD(v) => get_clock!(PBD_MASK_OFFSET: pbdmask & (1 << (v as u32))),\n\n }\n\n}\n", "file_path": "chips/sam4l/src/pm.rs", "rank": 51, "score": 150066.29086276144 }, { "content": "// When reading from a buffer in host order\n\npub fn host_slice_to_u16(buf: &[u8]) -> u16 {\n\n ((buf[1] as u16) << 8) | (buf[0] as u16)\n\n}\n\n\n", "file_path": "capsules/src/net/util.rs", "rank": 52, "score": 147628.15021491086 }, { "content": "pub fn is_lowpan(packet: &[u8]) -> bool {\n\n (packet[0] & iphc::DISPATCH[0]) == iphc::DISPATCH[0]\n\n}\n\n\n", "file_path": "capsules/src/net/sixlowpan/sixlowpan_compression.rs", "rank": 53, "score": 147628.15021491086 }, { "content": "// When reading from a buffer in network order\n\npub fn network_slice_to_u16(buf: &[u8]) -> u16 {\n\n ((buf[0] as u16) << 8) | (buf[1] as u16)\n\n}\n\n\n", "file_path": "capsules/src/net/util.rs", "rank": 54, "score": 147628.15021491086 }, { "content": "/// The 'types' of digests, this should define the output size of the digest\n\n/// operations.\n\npub trait DigestType: Eq + Copy + Clone + Sized + AsRef<[u8]> + AsMut<[u8]> {}\n\n\n\nimpl DigestType for [u8; 32] {}\n\n\n", "file_path": "kernel/src/hil/digest.rs", "rank": 55, "score": 147499.1328677198 }, { "content": "/// A component encapsulates peripheral-specific and capsule-specific\n\n/// initialization for the Tock OS kernel in a factory method,\n\n/// which reduces repeated code and simplifies the boot sequence.\n\n///\n\n/// The `Component` trait encapsulates all of the initialization and\n\n/// configuration of a kernel extension inside the `finalize()` function\n\n/// call. The `Output` type defines what type this component generates.\n\n/// Note that instantiating a component does not necessarily\n\n/// instantiate the underlying `Output` type; instead, it is typically\n\n/// instantiated in the `finalize()` method. If instantiating and\n\n/// initializing the `Output` type requires parameters, these should be\n\n/// passed in the component's `new()` function.\n\npub trait Component {\n\n /// An optional type to specify the chip or board specific static memory\n\n /// that a component needs to setup the output object(s). This is the memory\n\n /// that `static_init!()` would normally setup, but generic components\n\n /// cannot setup static buffers for types which are chip-dependent, so those\n\n /// buffers have to be passed in manually, and the `StaticInput` type makes\n\n /// this possible.\n\n type StaticInput;\n\n\n\n /// The type (e.g., capsule, peripheral) that this implementation\n\n /// of Component produces via `finalize()`. This is typically a\n\n /// static reference (`&'static`).\n\n type Output;\n\n\n\n /// A factory method that returns an instance of the Output type of this\n\n /// Component implementation. This factory method may only be called once\n\n /// per Component instance. Used in the boot sequence to instantiate and\n\n /// initialize part of the Tock kernel. Some components need to use the\n\n /// `static_memory` argument to allow the board initialization code to pass\n\n /// in references to static memory that the component will use to setup the\n\n /// Output type object.\n\n unsafe fn finalize(self, static_memory: Self::StaticInput) -> Self::Output;\n\n}\n", "file_path": "kernel/src/component.rs", "rank": 56, "score": 145707.15332579636 }, { "content": "/// `Driver`s implement the three driver-specific system calls: `subscribe`,\n\n/// `command` and `allow`.\n\n///\n\n/// See [the module level documentation](index.html) for an overview of how\n\n/// system calls are assigned to drivers.\n\npub trait Driver {\n\n /// `subscribe` lets an application pass a callback to the driver to be\n\n /// called later. This returns `ENOSUPPORT` if not used.\n\n ///\n\n /// Calls to subscribe should do minimal synchronous work. Instead, they\n\n /// should defer most work and returns results to the application via the\n\n /// callback. For example, a subscribe call might setup a DMA transfer to\n\n /// read from a sensor, and asynchronously respond to the application by\n\n /// passing the result to the application via the callback.\n\n ///\n\n /// Drivers should allow each application to register a single callback for\n\n /// each minor number subscription. Thus, a second call to subscribe from\n\n /// the same application would replace a previous callback.\n\n ///\n\n /// This pushes most per-application virtualization to the application\n\n /// itself. For example, a timer driver exposes only one timer to each\n\n /// application, and the application is responsible for virtualizing that\n\n /// timer if it needs to.\n\n ///\n\n /// The driver should signal success or failure through the sign of the\n", "file_path": "kernel/src/driver.rs", "rank": 57, "score": 145689.41556154576 }, { "content": "pub trait Debug {\n\n fn write(&self, buf: &'static mut [u8], len: usize);\n\n}\n\n\n\n#[cfg(debug = \"true\")]\n\nimpl Default for Debug {\n\n fn write(&self, buf: &'static mut [u8], len: usize) {\n\n panic!(\n\n \"No registered kernel debug printer. Thrown printing {:?}\",\n\n buf\n\n );\n\n }\n\n}\n\n\n\npub unsafe fn flush<W: Write + IoWrite>(writer: &mut W) {\n\n if let Some(debug_writer) = try_get_debug_writer() {\n\n if let Some(ring_buffer) = debug_writer.extract() {\n\n if ring_buffer.has_elements() {\n\n let _ = writer.write_str(\n\n \"\\r\\n---| Debug buffer not empty. Flushing. May repeat some of last message(s):\\r\\n\",\n", "file_path": "kernel/src/debug.rs", "rank": 58, "score": 145689.41556154576 }, { "content": "/// Globally declare entry ID type.\n\ntype EntryID = usize;\n\n\n\n/// Maximum page header size.\n\npub const PAGE_HEADER_SIZE: usize = size_of::<EntryID>();\n\n/// Maximum entry header size.\n\npub const ENTRY_HEADER_SIZE: usize = size_of::<usize>();\n\n\n\n/// Byte used to pad the end of a page.\n\nconst PAD_BYTE: u8 = 0xFF;\n\n\n\n/// Log state keeps track of any in-progress asynchronous operations.\n", "file_path": "capsules/src/log.rs", "rank": 59, "score": 144643.83276777086 }, { "content": "/// The type of keys, this should define the output size of the digest\n\n/// operations.\n\npub trait KeyType: Eq + Copy + Clone + Sized + AsRef<[u8]> + AsMut<[u8]> {}\n\n\n", "file_path": "kernel/src/hil/kv_system.rs", "rank": 60, "score": 144625.36670695178 }, { "content": "#[derive(Default)]\n\nstruct MfProcState {\n\n /// Total CPU time used by this process while in current queue\n\n us_used_this_queue: Cell<u32>,\n\n}\n\n\n\n/// Nodes store per-process state\n\npub struct MLFQProcessNode<'a> {\n\n proc: &'static Option<&'static dyn ProcessType>,\n\n state: MfProcState,\n\n next: ListLink<'a, MLFQProcessNode<'a>>,\n\n}\n\n\n\nimpl<'a> MLFQProcessNode<'a> {\n\n pub fn new(proc: &'static Option<&'static dyn ProcessType>) -> MLFQProcessNode<'a> {\n\n MLFQProcessNode {\n\n proc,\n\n state: MfProcState::default(),\n\n next: ListLink::empty(),\n\n }\n\n }\n", "file_path": "kernel/src/sched/mlfq.rs", "rank": 61, "score": 144388.0445003289 }, { "content": "pub fn nrf52840_gpio_create<'a>() -> Port<'a, NUM_PINS> {\n\n Port::new([\n\n GPIOPin::new(Pin::P0_00),\n\n GPIOPin::new(Pin::P0_01),\n\n GPIOPin::new(Pin::P0_02),\n\n GPIOPin::new(Pin::P0_03),\n\n GPIOPin::new(Pin::P0_04),\n\n GPIOPin::new(Pin::P0_05),\n\n GPIOPin::new(Pin::P0_06),\n\n GPIOPin::new(Pin::P0_07),\n\n GPIOPin::new(Pin::P0_08),\n\n GPIOPin::new(Pin::P0_09),\n\n GPIOPin::new(Pin::P0_10),\n\n GPIOPin::new(Pin::P0_11),\n\n GPIOPin::new(Pin::P0_12),\n\n GPIOPin::new(Pin::P0_13),\n\n GPIOPin::new(Pin::P0_14),\n\n GPIOPin::new(Pin::P0_15),\n\n GPIOPin::new(Pin::P0_16),\n\n GPIOPin::new(Pin::P0_17),\n", "file_path": "chips/nrf52840/src/gpio.rs", "rank": 62, "score": 143689.01320630265 }, { "content": "pub fn nrf52833_gpio_create<'a>() -> Port<'a, NUM_PINS> {\n\n Port::new([\n\n GPIOPin::new(Pin::P0_00),\n\n GPIOPin::new(Pin::P0_01),\n\n GPIOPin::new(Pin::P0_02),\n\n GPIOPin::new(Pin::P0_03),\n\n GPIOPin::new(Pin::P0_04),\n\n GPIOPin::new(Pin::P0_05),\n\n GPIOPin::new(Pin::P0_06),\n\n GPIOPin::new(Pin::P0_07),\n\n GPIOPin::new(Pin::P0_08),\n\n GPIOPin::new(Pin::P0_09),\n\n GPIOPin::new(Pin::P0_10),\n\n GPIOPin::new(Pin::P0_11),\n\n GPIOPin::new(Pin::P0_12),\n\n GPIOPin::new(Pin::P0_13),\n\n GPIOPin::new(Pin::P0_14),\n\n GPIOPin::new(Pin::P0_15),\n\n GPIOPin::new(Pin::P0_16),\n\n GPIOPin::new(Pin::P0_17),\n", "file_path": "chips/nrf52833/src/gpio.rs", "rank": 63, "score": 143689.01320630265 }, { "content": "pub fn nrf52832_gpio_create<'a>() -> Port<'a, NUM_PINS> {\n\n Port::new([\n\n GPIOPin::new(Pin::P0_00),\n\n GPIOPin::new(Pin::P0_01),\n\n GPIOPin::new(Pin::P0_02),\n\n GPIOPin::new(Pin::P0_03),\n\n GPIOPin::new(Pin::P0_04),\n\n GPIOPin::new(Pin::P0_05),\n\n GPIOPin::new(Pin::P0_06),\n\n GPIOPin::new(Pin::P0_07),\n\n GPIOPin::new(Pin::P0_08),\n\n GPIOPin::new(Pin::P0_09),\n\n GPIOPin::new(Pin::P0_10),\n\n GPIOPin::new(Pin::P0_11),\n\n GPIOPin::new(Pin::P0_12),\n\n GPIOPin::new(Pin::P0_13),\n\n GPIOPin::new(Pin::P0_14),\n\n GPIOPin::new(Pin::P0_15),\n\n GPIOPin::new(Pin::P0_16),\n\n GPIOPin::new(Pin::P0_17),\n", "file_path": "chips/nrf52832/src/gpio.rs", "rank": 64, "score": 143689.01320630265 }, { "content": "/// A wrapper around `Cell<State>` is used by `Process` to prevent bugs arising from\n\n/// the state duplication in the kernel work tracking and process state tracking.\n\nstruct ProcessStateCell<'a> {\n\n state: Cell<State>,\n\n kernel: &'a Kernel,\n\n}\n\n\n\nimpl<'a> ProcessStateCell<'a> {\n\n fn new(kernel: &'a Kernel) -> Self {\n\n Self {\n\n state: Cell::new(State::Unstarted),\n\n kernel,\n\n }\n\n }\n\n\n\n fn get(&self) -> State {\n\n self.state.get()\n\n }\n\n\n\n fn update(&self, new_state: State) {\n\n let old_state = self.state.get();\n\n\n", "file_path": "kernel/src/process.rs", "rank": 65, "score": 143241.81490944602 }, { "content": "/// Interface for individual boards.\n\n///\n\n/// Each board should define a struct which implements this trait. This trait is\n\n/// the core for how syscall dispatching is handled, and the implementation is\n\n/// responsible for dispatching to drivers for each system call number.\n\n///\n\n/// ## Example\n\n///\n\n/// ```ignore\n\n/// struct Hail {\n\n/// console: &'static capsules::console::Console<'static>,\n\n/// ipc: kernel::ipc::IPC,\n\n/// dac: &'static capsules::dac::Dac<'static>,\n\n/// }\n\n///\n\n/// impl Platform for Hail {\n\n/// fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R\n\n/// where\n\n/// F: FnOnce(Option<&dyn kernel::Driver>) -> R,\n\n/// {\n\n/// match driver_num {\n\n/// capsules::console::DRIVER_NUM => f(Some(self.console)),\n\n/// kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)),\n\n/// capsules::dac::DRIVER_NUM => f(Some(self.dac)),\n\n///\n\n/// _ => f(None),\n\n/// }\n\n/// }\n\n/// }\n\n/// ```\n\npub trait Platform {\n\n /// Platform-specific mapping of syscall numbers to objects that implement\n\n /// the Driver methods for that syscall.\n\n fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R\n\n where\n\n F: FnOnce(Option<&dyn Driver>) -> R;\n\n\n\n /// Check the platform-provided system call filter for all non-yield system\n\n /// calls. If the system call is allowed for the provided process then\n\n /// return Ok(()). Otherwise, return Err with a ReturnCode that will be\n\n /// returned to the calling application. The default implementation allows\n\n /// all system calls. This API should be considered unstable, and is likely\n\n /// to change in the future.\n\n fn filter_syscall(\n\n &self,\n\n _process: &dyn process::ProcessType,\n\n _syscall: &syscall::Syscall,\n\n ) -> Result<(), returncode::ReturnCode> {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "kernel/src/platform/mod.rs", "rank": 66, "score": 142527.35345092136 }, { "content": "/// Interface for individual MCUs.\n\n///\n\n/// The trait defines chip-specific properties of Tock's operation. These\n\n/// include whether and which memory protection mechanism and scheduler_timer to use,\n\n/// how to switch between the kernel and userland applications, and how to\n\n/// handle hardware events.\n\n///\n\n/// Each microcontroller should define a struct and implement this trait.\n\npub trait Chip {\n\n /// The particular Memory Protection Unit (MPU) for this chip.\n\n type MPU: mpu::MPU;\n\n\n\n /// The implementation of the interface between userspace and the kernel for\n\n /// this specific chip. Likely this is architecture specific, but individual\n\n /// chips may have various custom requirements.\n\n type UserspaceKernelBoundary: syscall::UserspaceKernelBoundary;\n\n\n\n /// The implementation of the timer used to create the timeslices provided\n\n /// to applications.\n\n type SchedulerTimer: scheduler_timer::SchedulerTimer;\n\n\n\n /// The implementation of the WatchDog timer used to monitor the running\n\n /// of the kernel.\n\n type WatchDog: watchdog::WatchDog;\n\n\n\n /// The kernel calls this function to tell the chip to check for all pending\n\n /// interrupts and to correctly dispatch them to the peripheral drivers for\n\n /// the chip.\n", "file_path": "kernel/src/platform/mod.rs", "rank": 67, "score": 142514.0984587902 }, { "content": "/// The generic trait that particular memory protection unit implementations\n\n/// need to implement.\n\n///\n\n/// This trait is a blend of relatively generic MPU functionality that should be\n\n/// common across different MPU implementations, and more specific requirements\n\n/// that Tock needs to support protecting applications. While a less\n\n/// Tock-specific interface may be desirable, due to the sometimes complex\n\n/// alignment rules and other restrictions imposed by MPU hardware, some of the\n\n/// Tock details have to be passed into this interface. That allows the MPU\n\n/// implementation to have more flexibility when satisfying the protection\n\n/// requirements, and also allows the MPU to specify some addresses used by the\n\n/// kernel when deciding where to place certain application memory regions so\n\n/// that the MPU can appropriately provide protection for those memory regions.\n\npub trait MPU {\n\n /// MPU-specific state that defines a particular configuration for the MPU.\n\n /// That is, this should contain all of the required state such that the\n\n /// implementation can be passed an object of this type and it should be\n\n /// able to correctly and entirely configure the MPU.\n\n ///\n\n /// This state will be held on a per-process basis as a way to cache all of\n\n /// the process settings. When the kernel switches to a new process it will\n\n /// use the `MpuConfig` for that process to quickly configure the MPU.\n\n ///\n\n /// It is `Default` so we can create empty state when the process is\n\n /// created, and `Display` so that the `panic!()` output can display the\n\n /// current state to help with debugging.\n\n type MpuConfig: Default + Display;\n\n\n\n /// Clears the MPU.\n\n ///\n\n /// This function will clear any access control enforced by the\n\n /// MPU where possible.\n\n /// On some hardware it is impossible to reset the MPU after it has\n", "file_path": "kernel/src/platform/mpu.rs", "rank": 68, "score": 142506.19606214415 }, { "content": "/// Represents a clock's frequency in Hz, allowing code to transform\n\n/// between computer time units and wall clock time. It is typically\n\n/// an associated type for an implementation of the `Time` trait.\n\npub trait Frequency {\n\n /// Returns frequency in Hz.\n\n fn frequency() -> u32;\n\n}\n\n\n", "file_path": "kernel/src/hil/time.rs", "rank": 69, "score": 142503.87156077684 }, { "content": "/// This trait is similar to std::io::Write in that it takes bytes instead of a string (contrary to\n\n/// core::fmt::Write), but io::Write isn't available in no_std (due to std::io::Error not being\n\n/// available).\n\n///\n\n/// Also, in our use cases, writes are infaillible, so the write function just doesn't return\n\n/// anything.\n\n///\n\n/// See also the tracking issue: <https://github.com/rust-lang/rfcs/issues/2262>\n\npub trait IoWrite {\n\n fn write(&mut self, buf: &[u8]);\n\n\n\n fn write_ring_buffer<'a>(&mut self, buf: &RingBuffer<'a, u8>) {\n\n let (left, right) = buf.as_slices();\n\n if let Some(slice) = left {\n\n self.write(slice);\n\n }\n\n if let Some(slice) = right {\n\n self.write(slice);\n\n }\n\n }\n\n}\n\n\n\n///////////////////////////////////////////////////////////////////\n\n// panic! support routines\n\n\n\n/// Tock default panic routine.\n\n///\n\n/// **NOTE:** The supplied `writer` must be synchronous.\n", "file_path": "kernel/src/debug.rs", "rank": 70, "score": 142502.790028991 }, { "content": "/// Interface for users of EIC. In order\n\n/// to execute interrupts, the user must implement\n\n/// this `Client` interface.\n\npub trait Client {\n\n /// Called when an interrupt occurs.\n\n fn fired(&self);\n\n}\n", "file_path": "kernel/src/hil/eic.rs", "rank": 71, "score": 142497.92977191505 }, { "content": "pub trait Output {\n\n /// Set the GPIO pin high. If the pin is not an output or\n\n /// input/output, this call is ignored.\n\n fn set(&self);\n\n\n\n /// Set the GPIO pin low. If the pin is not an output or\n\n /// input/output, this call is ignored.\n\n fn clear(&self);\n\n\n\n /// Toggle the GPIO pin. If the pin was high, set it low. If\n\n /// the pin was low, set it high. If the pin is not an output or\n\n /// input/output, this call is ignored. Return the new value\n\n /// of the pin.\n\n fn toggle(&self) -> bool;\n\n\n\n /// Activate or deactivate a GPIO pin, for a given activation mode.\n\n fn write_activation(&self, state: ActivationState, mode: ActivationMode) {\n\n match (state, mode) {\n\n (ActivationState::Active, ActivationMode::ActiveHigh)\n\n | (ActivationState::Inactive, ActivationMode::ActiveLow) => {\n\n self.set();\n\n }\n\n (ActivationState::Active, ActivationMode::ActiveLow)\n\n | (ActivationState::Inactive, ActivationMode::ActiveHigh) => {\n\n self.clear();\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "kernel/src/hil/gpio.rs", "rank": 72, "score": 142497.92977191505 }, { "content": "/// Shared interface for configuring components.\n\npub trait Controller {\n\n type Config;\n\n\n\n fn configure(&self, _: Self::Config);\n\n}\n", "file_path": "kernel/src/hil/mod.rs", "rank": 73, "score": 142497.92977191505 }, { "content": "pub trait Client {\n\n /// Called when set_addr, write or read are complete\n\n ///\n\n /// set_address does not return a buffer\n\n /// write and read return a buffer\n\n /// len should be set to the number of data elements written\n\n fn command_complete(&self, buffer: Option<&'static mut [u8]>, len: usize);\n\n}\n", "file_path": "kernel/src/hil/bus8080.rs", "rank": 74, "score": 142497.92977191505 }, { "content": "/// Simple on/off interface for LED pins.\n\n///\n\n/// Since GPIO pins are synchronous in Tock the LED interface is synchronous as\n\n/// well.\n\npub trait Led {\n\n /// Initialize the LED. Must be called before the LED is used.\n\n fn init(&self);\n\n\n\n /// Turn the LED on.\n\n fn on(&self);\n\n\n\n /// Turn the LED off.\n\n fn off(&self);\n\n\n\n /// Toggle the LED.\n\n fn toggle(&self);\n\n\n\n /// Return the on/off state of the LED. `true` if the LED is on, `false` if\n\n /// it is off.\n\n fn read(&self) -> bool;\n\n}\n\n\n\n/// For LEDs in which on is when GPIO is high.\n\npub struct LedHigh<'a, P: gpio::Pin> {\n", "file_path": "kernel/src/hil/led.rs", "rank": 75, "score": 142497.92977191505 }, { "content": "/// Trait for handling callbacks from simple ADC calls.\n\npub trait Client {\n\n /// Called when a sample is ready.\n\n fn sample_ready(&self, sample: u16);\n\n}\n\n\n\n// *** Interfaces for high-speed, buffered ADC sampling ***\n\n\n", "file_path": "kernel/src/hil/adc.rs", "rank": 76, "score": 142497.92977191505 }, { "content": "/// Interface for users of synchronous GPIO interrupts. In order\n\n/// to receive interrupts, the user must implement\n\n/// this `Client` interface.\n\npub trait Client {\n\n /// Called when an interrupt occurs. The `identifier` will\n\n /// be the same value that was passed to `enable_interrupt()`\n\n /// when the interrupt was configured.\n\n fn fired(&self);\n\n}\n\n\n", "file_path": "kernel/src/hil/gpio.rs", "rank": 77, "score": 142497.92977191505 }, { "content": "/// Simple interface for reading an ADC sample on any channel.\n\npub trait Adc {\n\n /// The chip-dependent type of an ADC channel.\n\n type Channel: PartialEq;\n\n\n\n /// Request a single ADC sample on a particular channel.\n\n /// Used for individual samples that have no timing requirements.\n\n /// All ADC samples will be the raw ADC value left-justified in the u16.\n\n fn sample(&self, channel: &Self::Channel) -> ReturnCode;\n\n\n\n /// Request repeated ADC samples on a particular channel.\n\n /// Callbacks will occur at the given frequency with low jitter and can be\n\n /// set to any frequency supported by the chip implementation. However\n\n /// callbacks may be limited based on how quickly the system can service\n\n /// individual samples, leading to missed samples at high frequencies.\n\n /// All ADC samples will be the raw ADC value left-justified in the u16.\n\n fn sample_continuous(&self, channel: &Self::Channel, frequency: u32) -> ReturnCode;\n\n\n\n /// Stop a sampling operation.\n\n /// Can be used to stop any simple or high-speed sampling operation. No\n\n /// further callbacks will occur.\n", "file_path": "kernel/src/hil/adc.rs", "rank": 78, "score": 142497.92977191505 }, { "content": "/// An [Rng](trait.Rng.html) client\n\n///\n\n/// Clients of an [Rng](trait.Rng.html) must implement this trait.\n\npub trait Client {\n\n /// Called by the (RNG)[trait.RNG.html] when there are one or more random\n\n /// numbers available\n\n ///\n\n /// `randomness` in an `Iterator` of available random numbers. The amount of\n\n /// randomness available may increase if `randomness` is not consumed\n\n /// quickly so clients should not rely on iterator termination to finish\n\n /// consuming random numbers.\n\n ///\n\n /// The client returns either `Continue::More` if the iterator did not have\n\n /// enough random values and the client would like to be called again when\n\n /// more is available, or `Continue::Done`.\n\n ///\n\n /// If randoness_available is triggered after a call to cancel()\n\n /// then error MUST be ECANCEL and randomness MAY contain\n\n /// random bits.\n\n fn randomness_available(\n\n &self,\n\n randomness: &mut dyn Iterator<Item = u32>,\n\n error: ReturnCode,\n\n ) -> Continue;\n\n}\n\n\n\n/// Generic interface for a synchronous 32-bit random number\n\n/// generator.\n\n\n", "file_path": "kernel/src/hil/rng.rs", "rank": 79, "score": 142497.92977191505 }, { "content": "pub trait Screen {\n\n /// Returns a tuple (width, height) with the current resolution (in pixels)\n\n /// This function is synchronous as the driver should know this value without\n\n /// requesting it from the screen.\n\n ///\n\n /// note that width and height may change due to rotation\n\n fn get_resolution(&self) -> (usize, usize);\n\n\n\n /// Returns the current pixel format\n\n /// This function is synchronous as the driver should know this value without\n\n /// requesting it from the screen.\n\n fn get_pixel_format(&self) -> ScreenPixelFormat;\n\n\n\n /// Returns the current rotation.\n\n /// This function is synchronous as the driver should know this value without\n\n /// requesting it from the screen.\n\n fn get_rotation(&self) -> ScreenRotation;\n\n\n\n /// Sets the video memory frame.\n\n /// This function has to be called before the first call to the write function.\n", "file_path": "kernel/src/hil/screen.rs", "rank": 80, "score": 142497.92977191505 }, { "content": "/// PWM control for a single pin.\n\npub trait Pwm {\n\n /// The chip-dependent type of a PWM pin.\n\n type Pin;\n\n\n\n /// Generate a PWM single on the given pin at the given frequency and duty\n\n /// cycle.\n\n ///\n\n /// - `frequency_hz` is specified in Hertz.\n\n /// - `duty_cycle` is specified as a portion of the max duty cycle supported\n\n /// by the chip. Clients should call `get_maximum_duty_cycle()` to get the\n\n /// value that corresponds to 100% duty cycle, and divide that\n\n /// appropriately to get the desired duty cycle value. For example, a 25%\n\n /// duty cycle would be `PWM0.get_maximum_duty_cycle() / 4`.\n\n fn start(&self, pin: &Self::Pin, frequency_hz: usize, duty_cycle: usize) -> ReturnCode;\n\n\n\n /// Stop a PWM pin output.\n\n fn stop(&self, pin: &Self::Pin) -> ReturnCode;\n\n\n\n /// Return the maximum PWM frequency supported by the PWM implementation.\n\n /// The frequency will be specified in Hertz.\n", "file_path": "kernel/src/hil/pwm.rs", "rank": 81, "score": 142497.92977191505 }, { "content": "/// A page of writable persistent flash memory.\n\npub trait Flash {\n\n /// Type of a single flash page for the given implementation.\n\n type Page: AsMut<[u8]> + Default;\n\n\n\n /// Read a page of flash into the buffer.\n\n fn read_page(\n\n &self,\n\n page_number: usize,\n\n buf: &'static mut Self::Page,\n\n ) -> Result<(), (ReturnCode, &'static mut Self::Page)>;\n\n\n\n /// Write a page of flash from the buffer.\n\n fn write_page(\n\n &self,\n\n page_number: usize,\n\n buf: &'static mut Self::Page,\n\n ) -> Result<(), (ReturnCode, &'static mut Self::Page)>;\n\n\n\n /// Erase a page of flash by setting every byte to 0xFF.\n\n fn erase_page(&self, page_number: usize) -> ReturnCode;\n\n}\n\n\n", "file_path": "kernel/src/hil/flash.rs", "rank": 82, "score": 142497.92977191505 }, { "content": "/// Control and configure a GPIO pin.\n\npub trait Configure {\n\n /// Return the current pin configuration.\n\n fn configuration(&self) -> Configuration;\n\n\n\n /// Make the pin an output, returning the current configuration,\n\n /// which should be either `Configuration::Output` or\n\n /// `Configuration::InputOutput`.\n\n fn make_output(&self) -> Configuration;\n\n /// Disable the pin as an output, returning the current configuration.\n\n fn disable_output(&self) -> Configuration;\n\n\n\n /// Make the pin an input, returning the current configuration,\n\n /// which should be ither `Configuration::Input` or\n\n /// `Configuration::InputOutput`.\n\n fn make_input(&self) -> Configuration;\n\n /// Disable the pin as an input, returning the current configuration.\n\n fn disable_input(&self) -> Configuration;\n\n\n\n /// Put a pin into its lowest power state, with no guarantees on\n\n /// if it is enabled or not. Implementations are free to use any\n", "file_path": "kernel/src/hil/gpio.rs", "rank": 83, "score": 142497.92977191505 }, { "content": "pub trait Input {\n\n /// Get the current state of an input GPIO pin. For an output\n\n /// pin, return the output; for an input pin, return the input;\n\n /// for disabled or function pins the value is undefined.\n\n fn read(&self) -> bool;\n\n\n\n /// Get the current state of a GPIO pin, for a given activation mode.\n\n fn read_activation(&self, mode: ActivationMode) -> ActivationState {\n\n let value = self.read();\n\n match (mode, value) {\n\n (ActivationMode::ActiveHigh, true) | (ActivationMode::ActiveLow, false) => {\n\n ActivationState::Active\n\n }\n\n (ActivationMode::ActiveLow, true) | (ActivationMode::ActiveHigh, false) => {\n\n ActivationState::Inactive\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "kernel/src/hil/gpio.rs", "rank": 84, "score": 142497.92977191505 }, { "content": "/// Trait for configuring a UART.\n\npub trait Configure {\n\n /// Returns SUCCESS, or\n\n /// - EOFF: The underlying hardware is currently not available, perhaps\n\n /// because it has not been initialized or in the case of a shared\n\n /// hardware USART controller because it is set up for SPI.\n\n /// - EINVAL: Impossible parameters (e.g. a `baud_rate` of 0)\n\n /// - ENOSUPPORT: The underlying UART cannot satisfy this configuration.\n\n fn configure(&self, params: Parameters) -> ReturnCode;\n\n}\n\n\n", "file_path": "kernel/src/hil/uart.rs", "rank": 85, "score": 142497.92977191505 }, { "content": "pub trait Client {\n\n /// Receive the successful result of a CRC calculation\n\n fn receive_result(&self, _: u32);\n\n}\n", "file_path": "kernel/src/hil/crc.rs", "rank": 86, "score": 142497.92977191505 }, { "content": "/// An [Entropy32](trait.Entropy32.html) client\n\n///\n\n/// Clients of an [Entropy32](trait.Entropy32.html) must implement this trait.\n\npub trait Client32 {\n\n /// Called by the (Entropy)[trait.Entropy32.html] when there is entropy\n\n /// available.\n\n ///\n\n /// `entropy` in an `Iterator` of available entropy. The amount of\n\n /// entropy available may increase if `entropy` is not consumed\n\n /// quickly so clients should not rely on iterator termination to\n\n /// finish consuming entropy.\n\n ///\n\n /// The client returns either `Continue::More` if the iterator did\n\n /// not have enough entropy (indicating another\n\n /// `entropy_available` callback is requested) and the client\n\n /// would like to be called again when more is available, or\n\n /// `Continue::Done`, which indicates `entropy_available` should\n\n /// not be called again until `get()` is called.\n\n ///\n\n /// If `entropy_available` is triggered after a call to `cancel()`\n\n /// then error MUST be ECANCEL and `entropy` MAY contain bits of\n\n /// entropy.\n\n fn entropy_available(\n\n &self,\n\n entropy: &mut dyn Iterator<Item = u32>,\n\n error: ReturnCode,\n\n ) -> Continue;\n\n}\n\n\n", "file_path": "kernel/src/hil/entropy.rs", "rank": 87, "score": 142497.92977191505 }, { "content": "/// An [Entropy8](trait.Entropy8.html) client\n\n///\n\n/// Clients of an [Entropy8](trait.Entropy8.html) must implement this trait.\n\npub trait Client8 {\n\n /// Called by the (Entropy)[trait.Entropy8.html] when there are\n\n /// one or more bytes of entropy available.\n\n ///\n\n /// `entropy` in an `Iterator` of available entropy. The amount of\n\n /// entropy available may increase if `entropy` is not consumed\n\n /// quickly so clients should not rely on iterator termination to\n\n /// finish consuming entropy.\n\n ///\n\n /// The client returns either `Continue::More` if the iterator did\n\n /// not have enough entropy (indicating another\n\n /// `entropy_available` callback is requested) and the client\n\n /// would like to be called again when more is available, or\n\n /// `Continue::Done`, which indicates `entropy_available` should\n\n /// not be called again until `get()` is called.\n\n ///\n\n /// If `entropy_available` is triggered after a call to `cancel()`\n\n /// then error MUST be ECANCEL and `entropy` MAY contain bits of\n\n /// entropy.\n\n fn entropy_available(\n\n &self,\n\n entropy: &mut dyn Iterator<Item = u8>,\n\n error: ReturnCode,\n\n ) -> Continue;\n\n}\n", "file_path": "kernel/src/hil/entropy.rs", "rank": 88, "score": 142497.92977191505 }, { "content": "/// Represents a moment in time, obtained by calling `now`.\n\npub trait Time {\n\n /// The number of ticks per second\n\n type Frequency: Frequency;\n\n /// The width of a time value\n\n type Ticks: Ticks;\n\n\n\n /// Returns a timestamp. Depending on the implementation of\n\n /// Time, this could represent either a static timestamp or\n\n /// a sample of a counter; if an implementation relies on\n\n /// it being constant or changing it should use `Timestamp`\n\n /// or `Counter`.\n\n fn now(&self) -> Self::Ticks;\n\n\n\n /// Returns the number of ticks in the provided number of seconds,\n\n /// rounding down any fractions. If the value overflows Ticks it\n\n /// returns `Ticks::max_value()`.\n\n fn ticks_from_seconds(s: u32) -> Self::Ticks {\n\n let val: u64 = Self::Frequency::frequency() as u64 * s as u64;\n\n ticks_from_val(val)\n\n }\n", "file_path": "kernel/src/hil/time.rs", "rank": 89, "score": 142497.92977191505 }, { "content": "pub fn decode_u8(buf: &[u8]) -> SResult<u8> {\n\n stream_len_cond!(buf, 1);\n\n stream_done!(1, buf[0]);\n\n}\n\n\n", "file_path": "capsules/src/net/stream.rs", "rank": 90, "score": 141370.4619322067 }, { "content": "pub fn decode_u16(buf: &[u8]) -> SResult<u16> {\n\n stream_len_cond!(buf, 2);\n\n stream_done!(2, (buf[0] as u16) << 8 | (buf[1] as u16));\n\n}\n\n\n", "file_path": "capsules/src/net/stream.rs", "rank": 91, "score": 141370.4619322067 }, { "content": "pub fn decode_u32(buf: &[u8]) -> SResult<u32> {\n\n stream_len_cond!(buf, 4);\n\n let b = (buf[0] as u32) << 24 | (buf[1] as u32) << 16 | (buf[2] as u32) << 8 | (buf[3] as u32);\n\n stream_done!(4, b);\n\n}\n\n\n", "file_path": "capsules/src/net/stream.rs", "rank": 92, "score": 141370.4619322067 }, { "content": "fn pixels_in_bytes(pixels: usize, bits_per_pixel: usize) -> usize {\n\n let bytes = pixels * bits_per_pixel / 8;\n\n if pixels * bits_per_pixel % 8 != 0 {\n\n bytes + 1\n\n } else {\n\n bytes\n\n }\n\n}\n\n\n\npub struct App {\n\n callback: Option<Callback>,\n\n pending_command: bool,\n\n shared: Option<AppSlice<Shared, u8>>,\n\n write_position: usize,\n\n write_len: usize,\n\n command: ScreenCommand,\n\n x: usize,\n\n y: usize,\n\n width: usize,\n\n height: usize,\n", "file_path": "capsules/src/screen.rs", "rank": 93, "score": 139861.85557193225 }, { "content": "/// A trait for implementing a watchdog in the kernel.\n\n/// This trait is called from the `kernel_loop()` code to setup\n\n/// and maintain the watchdog timer.\n\n/// It is up to the specific `Chip` how it will handle watchdog interrupts.\n\npub trait WatchDog {\n\n /// This function must enable the watchdog timer and configure it to\n\n /// trigger regulary. The period of the timer is left to the implementation\n\n /// to decide. The implementation must ensure that it doesn't trigger too\n\n /// early (when we haven't hung for example) or too late as to not catch\n\n /// faults.\n\n /// After calling this function the watchdog must be running.\n\n fn setup(&self) {}\n\n\n\n /// This function must tickle the watchdog to reset the timer.\n\n /// If the watchdog was previously suspended then this should also\n\n /// resume the timer.\n\n fn tickle(&self) {}\n\n\n\n /// Suspends the watchdog timer. After calling this the timer should not\n\n /// fire until after `tickle()` has been called. This function is called\n\n /// before sleeping.\n\n fn suspend(&self) {}\n\n\n\n /// Resumes the watchdog timer. After calling this the timer should be\n\n /// running again. This is called after returning from sleep, after\n\n /// `suspend()` was called.\n\n fn resume(&self) {\n\n self.tickle();\n\n }\n\n}\n\n\n\n/// Implement default WatchDog trait for unit.\n\nimpl WatchDog for () {}\n", "file_path": "kernel/src/platform/watchdog.rs", "rank": 94, "score": 139491.9158396224 }, { "content": "/// Simple interface for using the DAC.\n\npub trait DacChannel {\n\n /// Initialize and enable the DAC.\n\n fn initialize(&self) -> ReturnCode;\n\n\n\n /// Set the DAC output value.\n\n fn set_value(&self, value: usize) -> ReturnCode;\n\n}\n", "file_path": "kernel/src/hil/dac.rs", "rank": 95, "score": 139491.438807689 }, { "content": "/// Generic trait for implementing process restart policies.\n\n///\n\n/// This policy allows a board to specify how the kernel should decide whether\n\n/// to restart an app after it crashes.\n\npub trait ProcessRestartPolicy {\n\n /// Decide whether to restart the `process` or not.\n\n ///\n\n /// Returns `true` if the process should be restarted, `false` otherwise.\n\n fn should_restart(&self, process: &dyn ProcessType) -> bool;\n\n}\n\n\n\n/// Implementation of `ProcessRestartPolicy` that uses a threshold to decide\n\n/// whether to restart an app. If the app has been restarted more times than the\n\n/// threshold then the app will no longer be restarted.\n\npub struct ThresholdRestart {\n\n threshold: usize,\n\n}\n\n\n\nimpl ThresholdRestart {\n\n pub const fn new(threshold: usize) -> ThresholdRestart {\n\n ThresholdRestart { threshold }\n\n }\n\n}\n\n\n", "file_path": "kernel/src/process.rs", "rank": 96, "score": 139490.84588935526 }, { "content": "/// The `SpiMaster` trait for interacting with SPI slave\n\n/// devices at a byte or buffer level.\n\n///\n\n/// Using SpiMaster normally involves three steps:\n\n///\n\n/// 1. Configure the SPI bus for a peripheral\n\n/// 1a. Call set_chip_select to select which peripheral and\n\n/// turn on SPI\n\n/// 1b. Call set operations as needed to configure bus\n\n/// NOTE: You MUST select the chip select BEFORE configuring\n\n/// SPI settings.\n\n/// 2. Invoke read, write, read_write on SpiMaster\n\n/// 3a. Call clear_chip_select to turn off bus, or\n\n/// 3b. Call set_chip_select to choose another peripheral,\n\n/// go to step 1b or 2.\n\n///\n\n/// This interface assumes that the SPI configuration for\n\n/// a particular peripheral persists across chip select. For\n\n/// example, with this set of calls:\n\n///\n\n/// specify_chip_select(1);\n\n/// set_phase(SampleLeading);\n\n/// specify_chip_select(2);\n\n/// set_phase(SampleTrailing);\n\n/// specify_chip_select(1);\n\n/// write_byte(0); // Uses SampleLeading\n\n///\n\n/// If additional chip selects are needed, they can be performed\n\n/// with GPIO and manual re-initialization of settings.\n\n///\n\n/// specify_chip_select(0);\n\n/// set_phase(SampleLeading);\n\n/// pin_a.set();\n\n/// write_byte(0xaa); // Uses SampleLeading\n\n/// pin_a.clear();\n\n/// set_phase(SampleTrailing);\n\n/// pin_b.set();\n\n/// write_byte(0xaa); // Uses SampleTrailing\n\n///\n\npub trait SpiMaster {\n\n type ChipSelect: Copy;\n\n\n\n fn set_client(&self, client: &'static dyn SpiMasterClient);\n\n\n\n fn init(&self);\n\n fn is_busy(&self) -> bool;\n\n\n\n /// Perform an asynchronous read/write operation, whose\n\n /// completion is signaled by invoking SpiMasterClient on\n\n /// the initialized client. write_buffer must be Some,\n\n /// read_buffer may be None. If read_buffer is Some, the\n\n /// length of the operation is the minimum of the size of\n\n /// the two buffers.\n\n fn read_write_bytes(\n\n &self,\n\n write_buffer: &'static mut [u8],\n\n read_buffer: Option<&'static mut [u8]>,\n\n len: usize,\n\n ) -> ReturnCode;\n", "file_path": "kernel/src/hil/spi.rs", "rank": 97, "score": 139490.84212784347 }, { "content": " yield_pc: usize,\n\n psr: usize,\n\n}\n\n\n\n/// Implementation of the `UserspaceKernelBoundary` for the Cortex-M non-floating point\n\n/// architecture.\n\npub struct SysCall();\n\n\n\nimpl SysCall {\n\n pub const unsafe fn new() -> SysCall {\n\n SysCall()\n\n }\n\n}\n\n\n\nimpl kernel::syscall::UserspaceKernelBoundary for SysCall {\n\n type StoredState = CortexMStoredState;\n\n\n\n unsafe fn initialize_process(\n\n &self,\n\n stack_pointer: *const usize,\n", "file_path": "arch/cortex-m/src/syscall.rs", "rank": 98, "score": 47.17207991560203 } ]
Rust
src/rtc0.rs
cvetaevvitaliy/nrf52840-pac
bf07243a5a043883d915999f0f8ccd6cbf6229b8
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Start RTC COUNTER"] pub tasks_start: TASKS_START, #[doc = "0x04 - Stop RTC COUNTER"] pub tasks_stop: TASKS_STOP, #[doc = "0x08 - Clear RTC COUNTER"] pub tasks_clear: TASKS_CLEAR, #[doc = "0x0c - Set COUNTER to 0xFFFFF0"] pub tasks_trigovrflw: TASKS_TRIGOVRFLW, _reserved0: [u8; 240usize], #[doc = "0x100 - Event on COUNTER increment"] pub events_tick: EVENTS_TICK, #[doc = "0x104 - Event on COUNTER overflow"] pub events_ovrflw: EVENTS_OVRFLW, _reserved1: [u8; 56usize], #[doc = "0x140 - Description collection\\[n\\]: Compare event on CC\\[n\\] match"] pub events_compare: [EVENTS_COMPARE; 4], _reserved2: [u8; 436usize], #[doc = "0x304 - Enable interrupt"] pub intenset: INTENSET, #[doc = "0x308 - Disable interrupt"] pub intenclr: INTENCLR, _reserved3: [u8; 52usize], #[doc = "0x340 - Enable or disable event routing"] pub evten: EVTEN, #[doc = "0x344 - Enable event routing"] pub evtenset: EVTENSET, #[doc = "0x348 - Disable event routing"] pub evtenclr: EVTENCLR, _reserved4: [u8; 440usize], #[doc = "0x504 - Current COUNTER value"] pub counter: COUNTER, #[doc = "0x508 - 12 bit prescaler for COUNTER frequency (32768/(PRESCALER+1)).Must be written when RTC is stopped"] pub prescaler: PRESCALER, _reserved5: [u8; 52usize], #[doc = "0x540 - Description collection\\[n\\]: Compare register n"] pub cc: [CC; 4], } #[doc = "Start RTC COUNTER"] pub struct TASKS_START { register: ::vcell::VolatileCell<u32>, } #[doc = "Start RTC COUNTER"] pub mod tasks_start; #[doc = "Stop RTC COUNTER"] pub struct TASKS_STOP { register: ::vcell::VolatileCell<u32>, } #[doc = "Stop RTC COUNTER"] pub mod tasks_stop; #[doc = "Clear RTC COUNTER"] pub struct TASKS_CLEAR { register: ::vcell::VolatileCell<u32>, } #[doc = "Clear RTC COUNTER"] pub mod tasks_clear; #[doc = "Set COUNTER to 0xFFFFF0"] pub struct TASKS_TRIGOVRFLW { register: ::vcell::VolatileCell<u32>, } #[doc = "Set COUNTER to 0xFFFFF0"] pub mod tasks_trigovrflw; #[doc = "Event on COUNTER increment"] pub struct EVENTS_TICK { register: ::vcell::VolatileCell<u32>, } #[doc = "Event on COUNTER increment"] pub mod events_tick; #[doc = "Event on COUNTER overflow"] pub struct EVENTS_OVRFLW { register: ::vcell::VolatileCell<u32>, } #[doc = "Event on COUNTER overflow"] pub mod events_ovrflw; #[doc = "Description collection\\[n\\]: Compare event on CC\\[n\\] match"] pub struct EVENTS_COMPARE { register: ::vcell::VolatileCell<u32>, } #[doc = "Description collection\\[n\\]: Compare event on CC\\[n\\] match"] pub mod events_compare; #[doc = "Enable interrupt"] pub struct INTENSET { register: ::vcell::VolatileCell<u32>, } #[doc = "Enable interrupt"] pub mod intenset; #[doc = "Disable interrupt"] pub struct INTENCLR { register: ::vcell::VolatileCell<u32>, } #[doc = "Disable interrupt"] pub mod intenclr; #[doc = "Enable or disable event routing"] pub struct EVTEN { register: ::vcell::VolatileCell<u32>, } #[doc = "Enable or disable event routing"] pub mod evten; #[doc = "Enable event routing"] pub struct EVTENSET { register: ::vcell::VolatileCell<u32>, } #[doc = "Enable event routing"] pub mod evtenset; #[doc = "Disable event routing"] pub struct EVTENCLR { register: ::vcell::VolatileCell<u32>, } #[doc = "Disable event routing"] pub mod evtenclr; #[doc = "Current COUNTER value"] pub struct COUNTER { register: ::vcell::VolatileCell<u32>, } #[doc = "Current COUNTER value"] pub mod counter; #[doc = "12 bit prescaler for COUNTER frequency (32768/(PRESCALER+1)).Must be written when RTC is stopped"] pub struct PRESCALER { register: ::vcell::VolatileCell<u32>, } #[doc = "12 bit prescaler for COUNTER frequency (32768/(PRESCALER+1)).Must be written when RTC is stopped"] pub mod prescaler; #[doc = "Description collection\\[n\\]: Compare register n"] pub struct CC { register: ::vcell::VolatileCell<u32>, } #[doc = "Description collection\\[n\\]: Compare register n"] pub mod cc;
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Start RTC COUNTER"
top; #[doc = "Clear RTC COUNTER"] pub struct TASKS_CLEAR { register: ::vcell::VolatileCell<u32>, } #[doc = "Clear RTC COUNTER"] pub mod tasks_clear; #[doc = "Set COUNTER to 0xFFFFF0"] pub struct TASKS_TRIGOVRFLW { register: ::vcell::VolatileCell<u32>, } #[doc = "Set COUNTER to 0xFFFFF0"] pub mod tasks_trigovrflw; #[doc = "Event on COUNTER increment"] pub struct EVENTS_TICK { register: ::vcell::VolatileCell<u32>, } #[doc = "Event on COUNTER increment"] pub mod events_tick; #[doc = "Event on COUNTER overflow"] pub struct EVENTS_OVRFLW { register: ::vcell::VolatileCell<u32>, } #[doc = "Event on COUNTER overflow"] pub mod events_ovrflw; #[doc = "Description collection\\[n\\]: Compare event on CC\\[n\\] match"] pub struct EVENTS_COMPARE { register: ::vcell::VolatileCell<u32>, } #[doc = "Description collection\\[n\\]: Compare event on CC\\[n\\] match"] pub mod events_compare; #[doc = "Enable interrupt"] pub struct INTENSET { register: ::vcell::VolatileCell<u32>, } #[doc = "Enable interrupt"] pub mod intenset; #[doc = "Disable interrupt"] pub struct INTENCLR { register: ::vcell::VolatileCell<u32>, } #[doc = "Disable interrupt"] pub mod intenclr; #[doc = "Enable or disable event routing"] pub struct EVTEN { register: ::vcell::VolatileCell<u32>, } #[doc = "Enable or disable event routing"] pub mod evten; #[doc = "Enable event routing"] pub struct EVTENSET { register: ::vcell::VolatileCell<u32>, } #[doc = "Enable event routing"] pub mod evtenset; #[doc = "Disable event routing"] pub struct EVTENCLR { register: ::vcell::VolatileCell<u32>, } #[doc = "Disable event routing"] pub mod evtenclr; #[doc = "Current COUNTER value"] pub struct COUNTER { register: ::vcell::VolatileCell<u32>, } #[doc = "Current COUNTER value"] pub mod counter; #[doc = "12 bit prescaler for COUNTER frequency (32768/(PRESCALER+1)).Must be written when RTC is stopped"] pub struct PRESCALER { register: ::vcell::VolatileCell<u32>, } #[doc = "12 bit prescaler for COUNTER frequency (32768/(PRESCALER+1)).Must be written when RTC is stopped"] pub mod prescaler; #[doc = "Description collection\\[n\\]: Compare register n"] pub struct CC { register: ::vcell::VolatileCell<u32>, } #[doc = "Description collection\\[n\\]: Compare register n"] pub mod cc;
] pub tasks_start: TASKS_START, #[doc = "0x04 - Stop RTC COUNTER"] pub tasks_stop: TASKS_STOP, #[doc = "0x08 - Clear RTC COUNTER"] pub tasks_clear: TASKS_CLEAR, #[doc = "0x0c - Set COUNTER to 0xFFFFF0"] pub tasks_trigovrflw: TASKS_TRIGOVRFLW, _reserved0: [u8; 240usize], #[doc = "0x100 - Event on COUNTER increment"] pub events_tick: EVENTS_TICK, #[doc = "0x104 - Event on COUNTER overflow"] pub events_ovrflw: EVENTS_OVRFLW, _reserved1: [u8; 56usize], #[doc = "0x140 - Description collection\\[n\\]: Compare event on CC\\[n\\] match"] pub events_compare: [EVENTS_COMPARE; 4], _reserved2: [u8; 436usize], #[doc = "0x304 - Enable interrupt"] pub intenset: INTENSET, #[doc = "0x308 - Disable interrupt"] pub intenclr: INTENCLR, _reserved3: [u8; 52usize], #[doc = "0x340 - Enable or disable event routing"] pub evten: EVTEN, #[doc = "0x344 - Enable event routing"] pub evtenset: EVTENSET, #[doc = "0x348 - Disable event routing"] pub evtenclr: EVTENCLR, _reserved4: [u8; 440usize], #[doc = "0x504 - Current COUNTER value"] pub counter: COUNTER, #[doc = "0x508 - 12 bit prescaler for COUNTER frequency (32768/(PRESCALER+1)).Must be written when RTC is stopped"] pub prescaler: PRESCALER, _reserved5: [u8; 52usize], #[doc = "0x540 - Description collection\\[n\\]: Compare register n"] pub cc: [CC; 4], } #[doc = "Start RTC COUNTER"] pub struct TASKS_START { register: ::vcell::VolatileCell<u32>, } #[doc = "Start RTC COUNTER"] pub mod tasks_start; #[doc = "Stop RTC COUNTER"] pub struct TASKS_STOP { register: ::vcell::VolatileCell<u32>, } #[doc = "Stop RTC COUNTER"] pub mod tasks_s
random
[ { "content": "#[doc = r\" Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\nimpl super::COUNTER {\n\n #[doc = r\" Reads the contents of the register\"]\n\n #[inline]\n\n pub fn read(&self) -> R {\n\n R {\n\n bits: self.register.get(),\n\n }\n\n }\n\n}\n\n#[doc = r\" Value of the field\"]\n\npub struct COUNTERR {\n\n bits: u32,\n\n}\n\nimpl COUNTERR {\n\n #[doc = r\" Value of the field as raw bits\"]\n\n #[inline]\n", "file_path": "src/rtc0/counter.rs", "rank": 0, "score": 56765.68868242313 }, { "content": " pub fn bits(&self) -> u32 {\n\n self.bits\n\n }\n\n}\n\nimpl R {\n\n #[doc = r\" Value of the register as raw bits\"]\n\n #[inline]\n\n pub fn bits(&self) -> u32 {\n\n self.bits\n\n }\n\n #[doc = \"Bits 0:23 - Counter value\"]\n\n #[inline]\n\n pub fn counter(&self) -> COUNTERR {\n\n let bits = {\n\n const MASK: u32 = 16777215;\n\n const OFFSET: u8 = 0;\n\n ((self.bits >> OFFSET) & MASK as u32) as u32\n\n };\n\n COUNTERR { bits }\n\n }\n\n}\n", "file_path": "src/rtc0/counter.rs", "rank": 1, "score": 56762.729811311234 }, { "content": "#[doc = r\" Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\nimpl super::START {\n\n #[doc = r\" Reads the contents of the register\"]\n\n #[inline]\n\n pub fn read(&self) -> R {\n\n R {\n\n bits: self.register.get(),\n\n }\n\n }\n\n}\n\n#[doc = r\" Value of the field\"]\n\npub struct STARTR {\n\n bits: u32,\n\n}\n\nimpl STARTR {\n\n #[doc = r\" Value of the field as raw bits\"]\n\n #[inline]\n", "file_path": "src/mwu/pregion/start.rs", "rank": 2, "score": 54270.283138124665 }, { "content": "#[doc = r\" Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::START {\n\n #[doc = r\" Modifies the contents of the register\"]\n\n #[inline]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n let r = R { bits: bits };\n\n let mut w = W { bits: bits };\n\n f(&r, &mut w);\n\n self.register.set(w.bits);\n", "file_path": "src/mwu/region/start.rs", "rank": 3, "score": 54269.71135411996 }, { "content": "#[doc = r\" Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::EVENTS_STARTED {\n\n #[doc = r\" Modifies the contents of the register\"]\n\n #[inline]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n let r = R { bits: bits };\n\n let mut w = W { bits: bits };\n\n f(&r, &mut w);\n\n self.register.set(w.bits);\n", "file_path": "src/spim0/events_started.rs", "rank": 4, "score": 54269.6113754106 }, { "content": "#[doc = r\" Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::EVENTS_STARTED {\n\n #[doc = r\" Modifies the contents of the register\"]\n\n #[inline]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n let r = R { bits: bits };\n\n let mut w = W { bits: bits };\n\n f(&r, &mut w);\n\n self.register.set(w.bits);\n", "file_path": "src/saadc/events_started.rs", "rank": 5, "score": 54269.6113754106 }, { "content": "#[doc = r\" Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::EVENTS_STARTED {\n\n #[doc = r\" Modifies the contents of the register\"]\n\n #[inline]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n let r = R { bits: bits };\n\n let mut w = W { bits: bits };\n\n f(&r, &mut w);\n\n self.register.set(w.bits);\n", "file_path": "src/nfct/events_started.rs", "rank": 6, "score": 54269.6113754106 }, { "content": "#[doc = r\" Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::EVENTS_STARTED {\n\n #[doc = r\" Modifies the contents of the register\"]\n\n #[inline]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n let r = R { bits: bits };\n\n let mut w = W { bits: bits };\n\n f(&r, &mut w);\n\n self.register.set(w.bits);\n", "file_path": "src/usbd/events_started.rs", "rank": 7, "score": 54269.6113754106 }, { "content": "#[doc = r\" Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::EVENTS_STARTED {\n\n #[doc = r\" Modifies the contents of the register\"]\n\n #[inline]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n let r = R { bits: bits };\n\n let mut w = W { bits: bits };\n\n f(&r, &mut w);\n\n self.register.set(w.bits);\n", "file_path": "src/pdm/events_started.rs", "rank": 8, "score": 54269.6113754106 }, { "content": " #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n\n pub unsafe fn bits(self, value: u32) -> &'a mut W {\n\n const MASK: u32 = 4294967295;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl R {\n\n #[doc = r\" Value of the register as raw bits\"]\n\n #[inline]\n\n pub fn bits(&self) -> u32 {\n\n self.bits\n\n }\n\n #[doc = \"Bits 0:31 - Start address for region\"]\n\n #[inline]\n\n pub fn start(&self) -> STARTR {\n\n let bits = {\n", "file_path": "src/mwu/region/start.rs", "rank": 9, "score": 54265.86541608738 }, { "content": " pub fn bits(&self) -> u32 {\n\n self.bits\n\n }\n\n}\n\nimpl R {\n\n #[doc = r\" Value of the register as raw bits\"]\n\n #[inline]\n\n pub fn bits(&self) -> u32 {\n\n self.bits\n\n }\n\n #[doc = \"Bits 0:31 - Reserved for future use\"]\n\n #[inline]\n\n pub fn start(&self) -> STARTR {\n\n let bits = {\n\n const MASK: u32 = 4294967295;\n\n const OFFSET: u8 = 0;\n\n ((self.bits >> OFFSET) & MASK as u32) as u32\n\n };\n\n STARTR { bits }\n\n }\n\n}\n", "file_path": "src/mwu/pregion/start.rs", "rank": 10, "score": 54265.618182756625 }, { "content": " }\n\n #[doc = r\" Reads the contents of the register\"]\n\n #[inline]\n\n pub fn read(&self) -> R {\n\n R {\n\n bits: self.register.get(),\n\n }\n\n }\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n #[doc = r\" Writes the reset value to the register\"]\n\n #[inline]\n", "file_path": "src/mwu/region/start.rs", "rank": 11, "score": 54264.70691797162 }, { "content": " }\n\n #[doc = r\" Reads the contents of the register\"]\n\n #[inline]\n\n pub fn read(&self) -> R {\n\n R {\n\n bits: self.register.get(),\n\n }\n\n }\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n #[doc = r\" Writes the reset value to the register\"]\n\n #[inline]\n", "file_path": "src/saadc/events_started.rs", "rank": 12, "score": 54264.70691797162 }, { "content": " }\n\n #[doc = r\" Reads the contents of the register\"]\n\n #[inline]\n\n pub fn read(&self) -> R {\n\n R {\n\n bits: self.register.get(),\n\n }\n\n }\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n #[doc = r\" Writes the reset value to the register\"]\n\n #[inline]\n", "file_path": "src/spim0/events_started.rs", "rank": 13, "score": 54264.70691797162 }, { "content": " }\n\n #[doc = r\" Reads the contents of the register\"]\n\n #[inline]\n\n pub fn read(&self) -> R {\n\n R {\n\n bits: self.register.get(),\n\n }\n\n }\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n #[doc = r\" Writes the reset value to the register\"]\n\n #[inline]\n", "file_path": "src/usbd/events_started.rs", "rank": 14, "score": 54264.70691797162 }, { "content": " }\n\n #[doc = r\" Reads the contents of the register\"]\n\n #[inline]\n\n pub fn read(&self) -> R {\n\n R {\n\n bits: self.register.get(),\n\n }\n\n }\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n #[doc = r\" Writes the reset value to the register\"]\n\n #[inline]\n", "file_path": "src/nfct/events_started.rs", "rank": 15, "score": 54264.70691797162 }, { "content": " }\n\n #[doc = r\" Reads the contents of the register\"]\n\n #[inline]\n\n pub fn read(&self) -> R {\n\n R {\n\n bits: self.register.get(),\n\n }\n\n }\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n #[doc = r\" Writes the reset value to the register\"]\n\n #[inline]\n", "file_path": "src/pdm/events_started.rs", "rank": 16, "score": 54264.70691797162 }, { "content": " pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl R {\n\n #[doc = r\" Value of the register as raw bits\"]\n\n #[inline]\n\n pub fn bits(&self) -> u32 {\n\n self.bits\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn events_started(&self) -> EVENTS_STARTEDR {\n\n let bits = {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n", "file_path": "src/nfct/events_started.rs", "rank": 17, "score": 54264.384664457524 }, { "content": " pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl R {\n\n #[doc = r\" Value of the register as raw bits\"]\n\n #[inline]\n\n pub fn bits(&self) -> u32 {\n\n self.bits\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn events_started(&self) -> EVENTS_STARTEDR {\n\n let bits = {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n", "file_path": "src/saadc/events_started.rs", "rank": 18, "score": 54264.384664457524 }, { "content": " pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl R {\n\n #[doc = r\" Value of the register as raw bits\"]\n\n #[inline]\n\n pub fn bits(&self) -> u32 {\n\n self.bits\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn events_started(&self) -> EVENTS_STARTEDR {\n\n let bits = {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n", "file_path": "src/spim0/events_started.rs", "rank": 19, "score": 54264.384664457524 }, { "content": " pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl R {\n\n #[doc = r\" Value of the register as raw bits\"]\n\n #[inline]\n\n pub fn bits(&self) -> u32 {\n\n self.bits\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn events_started(&self) -> EVENTS_STARTEDR {\n\n let bits = {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n", "file_path": "src/pdm/events_started.rs", "rank": 20, "score": 54264.384664457524 }, { "content": " pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl R {\n\n #[doc = r\" Value of the register as raw bits\"]\n\n #[inline]\n\n pub fn bits(&self) -> u32 {\n\n self.bits\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn events_started(&self) -> EVENTS_STARTEDR {\n\n let bits = {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n", "file_path": "src/usbd/events_started.rs", "rank": 21, "score": 54264.384664457524 }, { "content": "#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::TASKS_START {\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _TASKS_STARTW<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "src/comp/tasks_start.rs", "rank": 22, "score": 54262.70893590502 }, { "content": "#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::TASKS_START {\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _TASKS_STARTW<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "src/i2s/tasks_start.rs", "rank": 23, "score": 54262.70893590502 }, { "content": "#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::TASKS_START {\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _TASKS_STARTW<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "src/rng/tasks_start.rs", "rank": 24, "score": 54262.70893590502 }, { "content": "#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::TASKS_START {\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _TASKS_STARTW<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "src/qdec/tasks_start.rs", "rank": 25, "score": 54262.70893590502 }, { "content": "#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::TASKS_START {\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _TASKS_STARTW<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "src/rtc0/tasks_start.rs", "rank": 26, "score": 54262.70893590502 }, { "content": "#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::TASKS_START {\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _TASKS_STARTW<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "src/timer0/tasks_start.rs", "rank": 27, "score": 54262.70893590502 }, { "content": "#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::TASKS_START {\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _TASKS_STARTW<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "src/pdm/tasks_start.rs", "rank": 28, "score": 54262.70893590502 }, { "content": "#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::TASKS_START {\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _TASKS_STARTW<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "src/spim0/tasks_start.rs", "rank": 29, "score": 54262.70893590502 }, { "content": "#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::TASKS_START {\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _TASKS_STARTW<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "src/radio/tasks_start.rs", "rank": 30, "score": 54262.70893590502 }, { "content": "#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::TASKS_START {\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _TASKS_STARTW<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "src/saadc/tasks_start.rs", "rank": 31, "score": 54262.70893590502 }, { "content": "#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::TASKS_START {\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _TASKS_STARTW<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "src/aar/tasks_start.rs", "rank": 32, "score": 54262.70893590502 }, { "content": "#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::TASKS_START {\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _TASKS_STARTW<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "src/wdt/tasks_start.rs", "rank": 33, "score": 54262.70893590502 }, { "content": "#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::TASKS_START {\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _TASKS_STARTW<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "src/lpcomp/tasks_start.rs", "rank": 34, "score": 54262.70893590502 }, { "content": "#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::TASKS_START {\n\n #[doc = r\" Writes to the register\"]\n\n #[inline]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n let mut w = W::reset_value();\n\n f(&mut w);\n\n self.register.set(w.bits);\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _TASKS_STARTW<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "src/temp/tasks_start.rs", "rank": 35, "score": 54262.70893590502 }, { "content": " const MASK: u32 = 4294967295;\n\n const OFFSET: u8 = 0;\n\n ((self.bits >> OFFSET) & MASK as u32) as u32\n\n };\n\n STARTR { bits }\n\n }\n\n}\n\nimpl W {\n\n #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bits 0:31 - Start address for region\"]\n\n #[inline]\n\n pub fn start(&mut self) -> _STARTW {\n\n _STARTW { w: self }\n\n }\n\n}\n", "file_path": "src/mwu/region/start.rs", "rank": 36, "score": 54262.69955210827 }, { "content": " #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn tasks_start(&mut self) -> _TASKS_STARTW {\n\n _TASKS_STARTW { w: self }\n\n }\n\n}\n", "file_path": "src/lpcomp/tasks_start.rs", "rank": 37, "score": 54262.23474981973 }, { "content": " #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn tasks_start(&mut self) -> _TASKS_STARTW {\n\n _TASKS_STARTW { w: self }\n\n }\n\n}\n", "file_path": "src/radio/tasks_start.rs", "rank": 38, "score": 54262.23474981973 }, { "content": " #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn tasks_start(&mut self) -> _TASKS_STARTW {\n\n _TASKS_STARTW { w: self }\n\n }\n\n}\n", "file_path": "src/pdm/tasks_start.rs", "rank": 39, "score": 54262.23474981973 }, { "content": " #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn tasks_start(&mut self) -> _TASKS_STARTW {\n\n _TASKS_STARTW { w: self }\n\n }\n\n}\n", "file_path": "src/timer0/tasks_start.rs", "rank": 40, "score": 54262.23474981973 }, { "content": " #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn tasks_start(&mut self) -> _TASKS_STARTW {\n\n _TASKS_STARTW { w: self }\n\n }\n\n}\n", "file_path": "src/i2s/tasks_start.rs", "rank": 41, "score": 54262.23474981973 }, { "content": " #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn tasks_start(&mut self) -> _TASKS_STARTW {\n\n _TASKS_STARTW { w: self }\n\n }\n\n}\n", "file_path": "src/temp/tasks_start.rs", "rank": 42, "score": 54262.23474981973 }, { "content": " #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn tasks_start(&mut self) -> _TASKS_STARTW {\n\n _TASKS_STARTW { w: self }\n\n }\n\n}\n", "file_path": "src/wdt/tasks_start.rs", "rank": 43, "score": 54262.23474981973 }, { "content": " #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn tasks_start(&mut self) -> _TASKS_STARTW {\n\n _TASKS_STARTW { w: self }\n\n }\n\n}\n", "file_path": "src/rtc0/tasks_start.rs", "rank": 44, "score": 54262.23474981973 }, { "content": " #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn tasks_start(&mut self) -> _TASKS_STARTW {\n\n _TASKS_STARTW { w: self }\n\n }\n\n}\n", "file_path": "src/qdec/tasks_start.rs", "rank": 45, "score": 54262.23474981973 }, { "content": " #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn tasks_start(&mut self) -> _TASKS_STARTW {\n\n _TASKS_STARTW { w: self }\n\n }\n\n}\n", "file_path": "src/comp/tasks_start.rs", "rank": 46, "score": 54262.23474981973 }, { "content": " #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn tasks_start(&mut self) -> _TASKS_STARTW {\n\n _TASKS_STARTW { w: self }\n\n }\n\n}\n", "file_path": "src/rng/tasks_start.rs", "rank": 47, "score": 54262.23474981973 }, { "content": " #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn tasks_start(&mut self) -> _TASKS_STARTW {\n\n _TASKS_STARTW { w: self }\n\n }\n\n}\n", "file_path": "src/spim0/tasks_start.rs", "rank": 48, "score": 54262.23474981973 }, { "content": " #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn tasks_start(&mut self) -> _TASKS_STARTW {\n\n _TASKS_STARTW { w: self }\n\n }\n\n}\n", "file_path": "src/aar/tasks_start.rs", "rank": 49, "score": 54262.23474981973 }, { "content": " #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn tasks_start(&mut self) -> _TASKS_STARTW {\n\n _TASKS_STARTW { w: self }\n\n }\n\n}\n", "file_path": "src/saadc/tasks_start.rs", "rank": 50, "score": 54262.23474981973 }, { "content": " ((self.bits >> OFFSET) & MASK as u32) != 0\n\n };\n\n EVENTS_STARTEDR { bits }\n\n }\n\n}\n\nimpl W {\n\n #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn events_started(&mut self) -> _EVENTS_STARTEDW {\n\n _EVENTS_STARTEDW { w: self }\n\n }\n\n}\n", "file_path": "src/saadc/events_started.rs", "rank": 51, "score": 54261.416481285436 }, { "content": " ((self.bits >> OFFSET) & MASK as u32) != 0\n\n };\n\n EVENTS_STARTEDR { bits }\n\n }\n\n}\n\nimpl W {\n\n #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn events_started(&mut self) -> _EVENTS_STARTEDW {\n\n _EVENTS_STARTEDW { w: self }\n\n }\n\n}\n", "file_path": "src/pdm/events_started.rs", "rank": 52, "score": 54261.416481285436 }, { "content": " ((self.bits >> OFFSET) & MASK as u32) != 0\n\n };\n\n EVENTS_STARTEDR { bits }\n\n }\n\n}\n\nimpl W {\n\n #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn events_started(&mut self) -> _EVENTS_STARTEDW {\n\n _EVENTS_STARTEDW { w: self }\n\n }\n\n}\n", "file_path": "src/usbd/events_started.rs", "rank": 53, "score": 54261.416481285436 }, { "content": " ((self.bits >> OFFSET) & MASK as u32) != 0\n\n };\n\n EVENTS_STARTEDR { bits }\n\n }\n\n}\n\nimpl W {\n\n #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn events_started(&mut self) -> _EVENTS_STARTEDW {\n\n _EVENTS_STARTEDW { w: self }\n\n }\n\n}\n", "file_path": "src/nfct/events_started.rs", "rank": 54, "score": 54261.416481285436 }, { "content": " ((self.bits >> OFFSET) & MASK as u32) != 0\n\n };\n\n EVENTS_STARTEDR { bits }\n\n }\n\n}\n\nimpl W {\n\n #[doc = r\" Reset value of the register\"]\n\n #[inline]\n\n pub fn reset_value() -> W {\n\n W { bits: 0 }\n\n }\n\n #[doc = r\" Writes raw bits to the register\"]\n\n #[inline]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n\n self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bit 0\"]\n\n #[inline]\n\n pub fn events_started(&mut self) -> _EVENTS_STARTEDW {\n\n _EVENTS_STARTEDW { w: self }\n\n }\n\n}\n", "file_path": "src/spim0/events_started.rs", "rank": 55, "score": 54261.416481285436 }, { "content": " pub fn reset(&self) {\n\n self.write(|w| w)\n\n }\n\n}\n\n#[doc = r\" Value of the field\"]\n\npub struct STARTR {\n\n bits: u32,\n\n}\n\nimpl STARTR {\n\n #[doc = r\" Value of the field as raw bits\"]\n\n #[inline]\n\n pub fn bits(&self) -> u32 {\n\n self.bits\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _STARTW<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> _STARTW<'a> {\n", "file_path": "src/mwu/region/start.rs", "rank": 56, "score": 54251.20156564765 }, { "content": " pub fn reset(&self) {\n\n self.write(|w| w)\n\n }\n\n}\n\n#[doc = r\" Value of the field\"]\n\npub struct EVENTS_STARTEDR {\n\n bits: bool,\n\n}\n\nimpl EVENTS_STARTEDR {\n\n #[doc = r\" Value of the field as raw bits\"]\n\n #[inline]\n\n pub fn bit(&self) -> bool {\n\n self.bits\n\n }\n\n #[doc = r\" Returns `true` if the bit is clear (0)\"]\n\n #[inline]\n\n pub fn bit_is_clear(&self) -> bool {\n\n !self.bit()\n\n }\n\n #[doc = r\" Returns `true` if the bit is set (1)\"]\n", "file_path": "src/spim0/events_started.rs", "rank": 57, "score": 54251.09933924181 }, { "content": " pub fn reset(&self) {\n\n self.write(|w| w)\n\n }\n\n}\n\n#[doc = r\" Value of the field\"]\n\npub struct EVENTS_STARTEDR {\n\n bits: bool,\n\n}\n\nimpl EVENTS_STARTEDR {\n\n #[doc = r\" Value of the field as raw bits\"]\n\n #[inline]\n\n pub fn bit(&self) -> bool {\n\n self.bits\n\n }\n\n #[doc = r\" Returns `true` if the bit is clear (0)\"]\n\n #[inline]\n\n pub fn bit_is_clear(&self) -> bool {\n\n !self.bit()\n\n }\n\n #[doc = r\" Returns `true` if the bit is set (1)\"]\n", "file_path": "src/usbd/events_started.rs", "rank": 58, "score": 54251.09933924181 }, { "content": " pub fn reset(&self) {\n\n self.write(|w| w)\n\n }\n\n}\n\n#[doc = r\" Value of the field\"]\n\npub struct EVENTS_STARTEDR {\n\n bits: bool,\n\n}\n\nimpl EVENTS_STARTEDR {\n\n #[doc = r\" Value of the field as raw bits\"]\n\n #[inline]\n\n pub fn bit(&self) -> bool {\n\n self.bits\n\n }\n\n #[doc = r\" Returns `true` if the bit is clear (0)\"]\n\n #[inline]\n\n pub fn bit_is_clear(&self) -> bool {\n\n !self.bit()\n\n }\n\n #[doc = r\" Returns `true` if the bit is set (1)\"]\n", "file_path": "src/nfct/events_started.rs", "rank": 59, "score": 54251.09933924181 }, { "content": " pub fn reset(&self) {\n\n self.write(|w| w)\n\n }\n\n}\n\n#[doc = r\" Value of the field\"]\n\npub struct EVENTS_STARTEDR {\n\n bits: bool,\n\n}\n\nimpl EVENTS_STARTEDR {\n\n #[doc = r\" Value of the field as raw bits\"]\n\n #[inline]\n\n pub fn bit(&self) -> bool {\n\n self.bits\n\n }\n\n #[doc = r\" Returns `true` if the bit is clear (0)\"]\n\n #[inline]\n\n pub fn bit_is_clear(&self) -> bool {\n\n !self.bit()\n\n }\n\n #[doc = r\" Returns `true` if the bit is set (1)\"]\n", "file_path": "src/pdm/events_started.rs", "rank": 60, "score": 54251.09933924181 }, { "content": " pub fn reset(&self) {\n\n self.write(|w| w)\n\n }\n\n}\n\n#[doc = r\" Value of the field\"]\n\npub struct EVENTS_STARTEDR {\n\n bits: bool,\n\n}\n\nimpl EVENTS_STARTEDR {\n\n #[doc = r\" Value of the field as raw bits\"]\n\n #[inline]\n\n pub fn bit(&self) -> bool {\n\n self.bits\n\n }\n\n #[doc = r\" Returns `true` if the bit is clear (0)\"]\n\n #[inline]\n\n pub fn bit_is_clear(&self) -> bool {\n\n !self.bit()\n\n }\n\n #[doc = r\" Returns `true` if the bit is set (1)\"]\n", "file_path": "src/saadc/events_started.rs", "rank": 61, "score": 54251.09933924181 }, { "content": " #[inline]\n\n pub fn bit_is_set(&self) -> bool {\n\n self.bit()\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _EVENTS_STARTEDW<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> _EVENTS_STARTEDW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n", "file_path": "src/saadc/events_started.rs", "rank": 62, "score": 54251.05597926999 }, { "content": " #[inline]\n\n pub fn bit_is_set(&self) -> bool {\n\n self.bit()\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _EVENTS_STARTEDW<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> _EVENTS_STARTEDW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n", "file_path": "src/nfct/events_started.rs", "rank": 63, "score": 54251.05597926999 }, { "content": " #[inline]\n\n pub fn bit_is_set(&self) -> bool {\n\n self.bit()\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _EVENTS_STARTEDW<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> _EVENTS_STARTEDW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n", "file_path": "src/usbd/events_started.rs", "rank": 64, "score": 54251.05597926999 }, { "content": " #[inline]\n\n pub fn bit_is_set(&self) -> bool {\n\n self.bit()\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _EVENTS_STARTEDW<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> _EVENTS_STARTEDW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n", "file_path": "src/pdm/events_started.rs", "rank": 65, "score": 54251.05597926999 }, { "content": " #[inline]\n\n pub fn bit_is_set(&self) -> bool {\n\n self.bit()\n\n }\n\n}\n\n#[doc = r\" Proxy\"]\n\npub struct _EVENTS_STARTEDW<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> _EVENTS_STARTEDW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n", "file_path": "src/spim0/events_started.rs", "rank": 66, "score": 54251.05597926999 }, { "content": "impl<'a> _TASKS_STARTW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl W {\n", "file_path": "src/spim0/tasks_start.rs", "rank": 67, "score": 54250.74541900825 }, { "content": "impl<'a> _TASKS_STARTW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl W {\n", "file_path": "src/lpcomp/tasks_start.rs", "rank": 68, "score": 54250.74541900825 }, { "content": "impl<'a> _TASKS_STARTW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl W {\n", "file_path": "src/i2s/tasks_start.rs", "rank": 69, "score": 54250.74541900825 }, { "content": "impl<'a> _TASKS_STARTW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl W {\n", "file_path": "src/aar/tasks_start.rs", "rank": 70, "score": 54250.74541900825 }, { "content": "impl<'a> _TASKS_STARTW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl W {\n", "file_path": "src/rng/tasks_start.rs", "rank": 71, "score": 54250.74541900825 }, { "content": "impl<'a> _TASKS_STARTW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl W {\n", "file_path": "src/qdec/tasks_start.rs", "rank": 72, "score": 54250.74541900825 }, { "content": "impl<'a> _TASKS_STARTW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl W {\n", "file_path": "src/saadc/tasks_start.rs", "rank": 73, "score": 54250.74541900825 }, { "content": "impl<'a> _TASKS_STARTW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl W {\n", "file_path": "src/radio/tasks_start.rs", "rank": 74, "score": 54250.74541900825 }, { "content": "impl<'a> _TASKS_STARTW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl W {\n", "file_path": "src/rtc0/tasks_start.rs", "rank": 75, "score": 54250.74541900825 }, { "content": "impl<'a> _TASKS_STARTW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl W {\n", "file_path": "src/temp/tasks_start.rs", "rank": 76, "score": 54250.74541900825 }, { "content": "impl<'a> _TASKS_STARTW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl W {\n", "file_path": "src/timer0/tasks_start.rs", "rank": 77, "score": 54250.74541900825 }, { "content": "impl<'a> _TASKS_STARTW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl W {\n", "file_path": "src/wdt/tasks_start.rs", "rank": 78, "score": 54250.74541900825 }, { "content": "impl<'a> _TASKS_STARTW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl W {\n", "file_path": "src/comp/tasks_start.rs", "rank": 79, "score": 54250.74541900825 }, { "content": "impl<'a> _TASKS_STARTW<'a> {\n\n #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n const MASK: bool = true;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFSET;\n\n self.w\n\n }\n\n}\n\nimpl W {\n", "file_path": "src/pdm/tasks_start.rs", "rank": 80, "score": 54250.74541900825 }, { "content": "#[doc = r\" Register block\"]\n\n#[repr(C)]\n\npub struct RegisterBlock {\n\n #[doc = \"0x00 - Enable RADIO in TX mode\"]\n\n pub tasks_txen: TASKS_TXEN,\n\n #[doc = \"0x04 - Enable RADIO in RX mode\"]\n\n pub tasks_rxen: TASKS_RXEN,\n\n #[doc = \"0x08 - Start RADIO\"]\n\n pub tasks_start: TASKS_START,\n\n #[doc = \"0x0c - Stop RADIO\"]\n\n pub tasks_stop: TASKS_STOP,\n\n #[doc = \"0x10 - Disable RADIO\"]\n\n pub tasks_disable: TASKS_DISABLE,\n\n #[doc = \"0x14 - Start the RSSI and take one single sample of the receive signal strength\"]\n\n pub tasks_rssistart: TASKS_RSSISTART,\n\n #[doc = \"0x18 - Stop the RSSI measurement\"]\n\n pub tasks_rssistop: TASKS_RSSISTOP,\n\n #[doc = \"0x1c - Start the bit counter\"]\n\n pub tasks_bcstart: TASKS_BCSTART,\n\n #[doc = \"0x20 - Stop the bit counter\"]\n", "file_path": "src/radio.rs", "rank": 83, "score": 24.8281775875448 }, { "content": "#[doc = r\" Register block\"]\n\n#[repr(C)]\n\npub struct RegisterBlock {\n\n #[doc = \"0x00 - Start the watchdog\"]\n\n pub tasks_start: TASKS_START,\n\n _reserved0: [u8; 252usize],\n\n #[doc = \"0x100 - Watchdog timeout\"]\n\n pub events_timeout: EVENTS_TIMEOUT,\n\n _reserved1: [u8; 512usize],\n\n #[doc = \"0x304 - Enable interrupt\"]\n\n pub intenset: INTENSET,\n\n #[doc = \"0x308 - Disable interrupt\"]\n\n pub intenclr: INTENCLR,\n\n _reserved2: [u8; 244usize],\n\n #[doc = \"0x400 - Run status\"]\n\n pub runstatus: RUNSTATUS,\n\n #[doc = \"0x404 - Request status\"]\n\n pub reqstatus: REQSTATUS,\n\n _reserved3: [u8; 252usize],\n\n #[doc = \"0x504 - Counter reload value\"]\n", "file_path": "src/wdt.rs", "rank": 84, "score": 24.627667164612017 }, { "content": " pub substatra: self::perregion::SUBSTATRA,\n\n}\n\n#[doc = r\" Register block\"]\n\n#[doc = \"Unspecified\"]\n\npub mod perregion;\n\n#[doc = r\" Register block\"]\n\n#[repr(C)]\n\npub struct REGION {\n\n #[doc = \"0x00 - Description cluster\\\\[n\\\\]: Start address for region n\"]\n\n pub start: self::region::START,\n\n #[doc = \"0x04 - Description cluster\\\\[n\\\\]: End address of region n\"]\n\n pub end: self::region::END,\n\n}\n\n#[doc = r\" Register block\"]\n\n#[doc = \"Unspecified\"]\n\npub mod region;\n\n#[doc = r\" Register block\"]\n\n#[repr(C)]\n\npub struct PREGION {\n\n #[doc = \"0x00 - Description cluster\\\\[n\\\\]: Reserved for future use\"]\n", "file_path": "src/mwu.rs", "rank": 85, "score": 24.33281551593889 }, { "content": "#[doc = r\" Register block\"]\n\n#[repr(C)]\n\npub struct RegisterBlock {\n\n #[doc = \"0x00 - Start Timer\"]\n\n pub tasks_start: TASKS_START,\n\n #[doc = \"0x04 - Stop Timer\"]\n\n pub tasks_stop: TASKS_STOP,\n\n #[doc = \"0x08 - Increment Timer (Counter mode only)\"]\n\n pub tasks_count: TASKS_COUNT,\n\n #[doc = \"0x0c - Clear time\"]\n\n pub tasks_clear: TASKS_CLEAR,\n\n #[doc = \"0x10 - Deprecated register - Shut down timer\"]\n\n pub tasks_shutdown: TASKS_SHUTDOWN,\n\n _reserved0: [u8; 44usize],\n\n #[doc = \"0x40 - Description collection\\\\[n\\\\]: Capture Timer value to CC\\\\[n\\\\] register\"]\n\n pub tasks_capture: [TASKS_CAPTURE; 6],\n\n _reserved1: [u8; 232usize],\n\n #[doc = \"0x140 - Description collection\\\\[n\\\\]: Compare event on CC\\\\[n\\\\] match\"]\n\n pub events_compare: [EVENTS_COMPARE; 6],\n\n _reserved2: [u8; 168usize],\n", "file_path": "src/timer0.rs", "rank": 86, "score": 23.79003926708871 }, { "content": "unsafe impl Send for TIMER0 {}\n\nimpl TIMER0 {\n\n #[doc = r\" Returns a pointer to the register block\"]\n\n pub fn ptr() -> *const timer0::RegisterBlock {\n\n 1073774592 as *const _\n\n }\n\n}\n\nimpl Deref for TIMER0 {\n\n type Target = timer0::RegisterBlock;\n\n fn deref(&self) -> &timer0::RegisterBlock {\n\n unsafe { &*TIMER0::ptr() }\n\n }\n\n}\n\n#[doc = \"Timer/Counter 0\"]\n\npub mod timer0;\n\n#[doc = \"Timer/Counter 1\"]\n\npub struct TIMER1 {\n\n _marker: PhantomData<*const ()>,\n\n}\n\nunsafe impl Send for TIMER1 {}\n", "file_path": "src/lib.rs", "rank": 87, "score": 23.706111491613484 }, { "content": " pub format: self::config::FORMAT,\n\n #[doc = \"0x24 - Enable channels.\"]\n\n pub channels: self::config::CHANNELS,\n\n}\n\n#[doc = r\" Register block\"]\n\n#[doc = \"Unspecified\"]\n\npub mod config;\n\n#[doc = r\" Register block\"]\n\n#[repr(C)]\n\npub struct RXD {\n\n #[doc = \"0x00 - Receive buffer RAM start address.\"]\n\n pub ptr: self::rxd::PTR,\n\n}\n\n#[doc = r\" Register block\"]\n\n#[doc = \"Unspecified\"]\n\npub mod rxd;\n\n#[doc = r\" Register block\"]\n\n#[repr(C)]\n\npub struct TXD {\n\n #[doc = \"0x00 - Transmit buffer RAM start address.\"]\n", "file_path": "src/i2s.rs", "rank": 88, "score": 23.651239216076863 }, { "content": "#[doc = \"Start address of flash block to be erased\"]\n\npub struct PTR {\n\n register: ::vcell::VolatileCell<u32>,\n\n}\n\n#[doc = \"Start address of flash block to be erased\"]\n\npub mod ptr;\n\n#[doc = \"Size of block to be erased.\"]\n\npub struct LEN {\n\n register: ::vcell::VolatileCell<u32>,\n\n}\n\n#[doc = \"Size of block to be erased.\"]\n\npub mod len;\n", "file_path": "src/qspi/erase.rs", "rank": 89, "score": 23.603811666623933 }, { "content": "impl TIMER1 {\n\n #[doc = r\" Returns a pointer to the register block\"]\n\n pub fn ptr() -> *const timer0::RegisterBlock {\n\n 1073778688 as *const _\n\n }\n\n}\n\nimpl Deref for TIMER1 {\n\n type Target = timer0::RegisterBlock;\n\n fn deref(&self) -> &timer0::RegisterBlock {\n\n unsafe { &*TIMER1::ptr() }\n\n }\n\n}\n\n#[doc = \"Timer/Counter 2\"]\n\npub struct TIMER2 {\n\n _marker: PhantomData<*const ()>,\n\n}\n\nunsafe impl Send for TIMER2 {}\n\nimpl TIMER2 {\n\n #[doc = r\" Returns a pointer to the register block\"]\n\n pub fn ptr() -> *const timer0::RegisterBlock {\n", "file_path": "src/lib.rs", "rank": 90, "score": 23.052302071680277 }, { "content": " register: ::vcell::VolatileCell<u32>,\n\n}\n\n#[doc = \"Start the RSSI and take one single sample of the receive signal strength\"]\n\npub mod tasks_rssistart;\n\n#[doc = \"Stop the RSSI measurement\"]\n\npub struct TASKS_RSSISTOP {\n\n register: ::vcell::VolatileCell<u32>,\n\n}\n\n#[doc = \"Stop the RSSI measurement\"]\n\npub mod tasks_rssistop;\n\n#[doc = \"Start the bit counter\"]\n\npub struct TASKS_BCSTART {\n\n register: ::vcell::VolatileCell<u32>,\n\n}\n\n#[doc = \"Start the bit counter\"]\n\npub mod tasks_bcstart;\n\n#[doc = \"Stop the bit counter\"]\n\npub struct TASKS_BCSTOP {\n\n register: ::vcell::VolatileCell<u32>,\n\n}\n", "file_path": "src/radio.rs", "rank": 91, "score": 22.7260188590954 }, { "content": " 1073782784 as *const _\n\n }\n\n}\n\nimpl Deref for TIMER2 {\n\n type Target = timer0::RegisterBlock;\n\n fn deref(&self) -> &timer0::RegisterBlock {\n\n unsafe { &*TIMER2::ptr() }\n\n }\n\n}\n\n#[doc = \"Real time counter 0\"]\n\npub struct RTC0 {\n\n _marker: PhantomData<*const ()>,\n\n}\n\nunsafe impl Send for RTC0 {}\n\nimpl RTC0 {\n\n #[doc = r\" Returns a pointer to the register block\"]\n\n pub fn ptr() -> *const rtc0::RegisterBlock {\n\n 1073786880 as *const _\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 92, "score": 22.632493479208822 }, { "content": " fn deref(&self) -> &swi0::RegisterBlock {\n\n unsafe { &*SWI5::ptr() }\n\n }\n\n}\n\n#[doc = \"Timer/Counter 3\"]\n\npub struct TIMER3 {\n\n _marker: PhantomData<*const ()>,\n\n}\n\nunsafe impl Send for TIMER3 {}\n\nimpl TIMER3 {\n\n #[doc = r\" Returns a pointer to the register block\"]\n\n pub fn ptr() -> *const timer0::RegisterBlock {\n\n 1073848320 as *const _\n\n }\n\n}\n\nimpl Deref for TIMER3 {\n\n type Target = timer0::RegisterBlock;\n\n fn deref(&self) -> &timer0::RegisterBlock {\n\n unsafe { &*TIMER3::ptr() }\n\n }\n", "file_path": "src/lib.rs", "rank": 93, "score": 22.623331352185122 }, { "content": " pub cnt: self::write::CNT,\n\n}\n\n#[doc = r\" Register block\"]\n\n#[doc = \"Unspecified\"]\n\npub mod write;\n\n#[doc = r\" Register block\"]\n\n#[repr(C)]\n\npub struct ERASE {\n\n #[doc = \"0x00 - Start address of flash block to be erased\"]\n\n pub ptr: self::erase::PTR,\n\n #[doc = \"0x04 - Size of block to be erased.\"]\n\n pub len: self::erase::LEN,\n\n}\n\n#[doc = r\" Register block\"]\n\n#[doc = \"Unspecified\"]\n\npub mod erase;\n\n#[doc = r\" Register block\"]\n\n#[repr(C)]\n\npub struct PSEL {\n\n #[doc = \"0x00 - Pin select for serial clock SCK\"]\n", "file_path": "src/qspi.rs", "rank": 94, "score": 22.553979896122417 }, { "content": "}\n\n#[doc = \"Timer/Counter 4\"]\n\npub struct TIMER4 {\n\n _marker: PhantomData<*const ()>,\n\n}\n\nunsafe impl Send for TIMER4 {}\n\nimpl TIMER4 {\n\n #[doc = r\" Returns a pointer to the register block\"]\n\n pub fn ptr() -> *const timer0::RegisterBlock {\n\n 1073852416 as *const _\n\n }\n\n}\n\nimpl Deref for TIMER4 {\n\n type Target = timer0::RegisterBlock;\n\n fn deref(&self) -> &timer0::RegisterBlock {\n\n unsafe { &*TIMER4::ptr() }\n\n }\n\n}\n\n#[doc = \"Pulse width modulation unit 0\"]\n\npub struct PWM0 {\n", "file_path": "src/lib.rs", "rank": 95, "score": 22.404801880081237 }, { "content": "pub struct TASKS_START {\n\n register: ::vcell::VolatileCell<u32>,\n\n}\n\n#[doc = \"Start Timer\"]\n\npub mod tasks_start;\n\n#[doc = \"Stop Timer\"]\n\npub struct TASKS_STOP {\n\n register: ::vcell::VolatileCell<u32>,\n\n}\n\n#[doc = \"Stop Timer\"]\n\npub mod tasks_stop;\n\n#[doc = \"Increment Timer (Counter mode only)\"]\n\npub struct TASKS_COUNT {\n\n register: ::vcell::VolatileCell<u32>,\n\n}\n\n#[doc = \"Increment Timer (Counter mode only)\"]\n\npub mod tasks_count;\n\n#[doc = \"Clear time\"]\n\npub struct TASKS_CLEAR {\n\n register: ::vcell::VolatileCell<u32>,\n", "file_path": "src/timer0.rs", "rank": 96, "score": 22.33317287205902 }, { "content": "}\n\nunsafe impl Send for SAADC {}\n\nimpl SAADC {\n\n #[doc = r\" Returns a pointer to the register block\"]\n\n pub fn ptr() -> *const saadc::RegisterBlock {\n\n 1073770496 as *const _\n\n }\n\n}\n\nimpl Deref for SAADC {\n\n type Target = saadc::RegisterBlock;\n\n fn deref(&self) -> &saadc::RegisterBlock {\n\n unsafe { &*SAADC::ptr() }\n\n }\n\n}\n\n#[doc = \"Successive approximation register (SAR) analog-to-digital converter\"]\n\npub mod saadc;\n\n#[doc = \"Timer/Counter 0\"]\n\npub struct TIMER0 {\n\n _marker: PhantomData<*const ()>,\n\n}\n", "file_path": "src/lib.rs", "rank": 97, "score": 22.3233381602359 }, { "content": " pub address: ADDRESS,\n\n}\n\n#[doc = r\" Register block\"]\n\n#[repr(C)]\n\npub struct PSEL {\n\n #[doc = \"0x00 - Pin select for SCL\"]\n\n pub scl: self::psel::SCL,\n\n #[doc = \"0x04 - Pin select for SDA\"]\n\n pub sda: self::psel::SDA,\n\n}\n\n#[doc = r\" Register block\"]\n\n#[doc = \"Unspecified\"]\n\npub mod psel;\n\n#[doc = \"Start TWI receive sequence\"]\n\npub struct TASKS_STARTRX {\n\n register: ::vcell::VolatileCell<u32>,\n\n}\n\n#[doc = \"Start TWI receive sequence\"]\n\npub mod tasks_startrx;\n\n#[doc = \"Start TWI transmit sequence\"]\n", "file_path": "src/twi0.rs", "rank": 98, "score": 22.244522825168396 }, { "content": "}\n\n#[doc = r\" Register block\"]\n\n#[doc = \"Unspecified\"]\n\npub mod sample;\n\n#[doc = \"Starts continuous PDM transfer\"]\n\npub struct TASKS_START {\n\n register: ::vcell::VolatileCell<u32>,\n\n}\n\n#[doc = \"Starts continuous PDM transfer\"]\n\npub mod tasks_start;\n\n#[doc = \"Stops PDM transfer\"]\n\npub struct TASKS_STOP {\n\n register: ::vcell::VolatileCell<u32>,\n\n}\n\n#[doc = \"Stops PDM transfer\"]\n\npub mod tasks_stop;\n\n#[doc = \"PDM transfer has started\"]\n\npub struct EVENTS_STARTED {\n\n register: ::vcell::VolatileCell<u32>,\n\n}\n", "file_path": "src/pdm.rs", "rank": 99, "score": 22.22085401931809 } ]
Rust
src/lexer.rs
mdlayher/monkey-rs
f7d7287a28c33c1cc833ffa0444405e5f5a3f04e
use crate::token::{Float, Integer, Radix, Token}; use std::error; use std::fmt; use std::num; use std::result; use std::str::FromStr; pub struct Lexer<'a> { input: &'a str, position: usize, read_position: usize, ch: char, } impl<'a> Lexer<'a> { pub fn new(input: &'a str) -> Self { let mut l = Lexer { input, position: 0, read_position: 0, ch: 0 as char, }; l.read_char(); l } pub fn lex(&mut self) -> Result<Vec<Token>> { let mut tokens = vec![]; loop { match self.next_token()? { t @ Token::Eof => { tokens.push(t); return Ok(tokens); } t => { tokens.push(t); } } } } pub fn next_token(&mut self) -> Result<Token> { self.skip_whitespace(); let t = match self.ch { '=' => { if self.peek_char() == '=' { self.read_char(); Token::Equal } else { Token::Assign } } '+' => Token::Plus, '-' => Token::Minus, '!' => { if self.peek_char() == '=' { self.read_char(); Token::NotEqual } else { Token::Bang } } '*' => Token::Asterisk, '/' => Token::Slash, '%' => Token::Percent, '<' => Token::LessThan, '>' => Token::GreaterThan, '&' => Token::Ampersand, ',' => Token::Comma, ':' => Token::Colon, ';' => Token::Semicolon, '(' => Token::LeftParen, ')' => Token::RightParen, '{' => Token::LeftBrace, '}' => Token::RightBrace, '[' => Token::LeftBracket, ']' => Token::RightBracket, '"' => self.read_string()?, '\u{0000}' => Token::Eof, _ => { if is_letter(self.ch) { let ident = self.read_identifier(); if let Some(key) = lookup_keyword(&ident) { return Ok(key); } else { return Ok(Token::Identifier(ident)); } } else if is_number(self.ch) { return self.read_number(); } else { Token::Illegal(self.ch) } } }; self.read_char(); Ok(t) } fn peek_char(&self) -> char { if self.read_position >= self.input.len() { 0 as char } else { if let Some(ch) = self.input.chars().nth(self.read_position) { ch } else { panic!("peeked out of range character") } } } fn read_char(&mut self) { if self.read_position >= self.input.len() { self.ch = 0 as char; } else { if let Some(ch) = self.input.chars().nth(self.read_position) { self.ch = ch; } else { panic!("read out of range character"); } } self.position = self.read_position; self.read_position += 1; } fn read_identifier(&mut self) -> String { let pos = self.position; while is_letter(self.ch) || self.ch.is_numeric() { self.read_char(); } self.input .chars() .skip(pos) .take(self.position - pos) .collect() } fn read_number(&mut self) -> Result<Token> { let pos = self.position; while (self.ch.is_ascii_alphanumeric() || self.ch == '.') && !self.ch.is_whitespace() { self.read_char(); } let chars: Vec<char> = self .input .chars() .skip(pos) .take(self.position - pos) .collect(); if chars.contains(&'.') { Ok(Token::Float(Float::from( f64::from_str(&chars.iter().collect::<String>()).map_err(Error::IllegalFloat)?, ))) } else { Ok(Token::Integer(parse_int(&chars)?)) } } fn read_string(&mut self) -> Result<Token> { let pos = self.position + 1; loop { self.read_char(); match self.ch { '"' => break, '\u{0000}' => { return Err(Error::UnexpectedEof); } _ => {} } } Ok(Token::String( self.input .chars() .skip(pos) .take(self.position - pos) .collect(), )) } fn skip_whitespace(&mut self) { while self.ch.is_ascii_whitespace() { self.read_char(); } } } fn lookup_keyword(s: &str) -> Option<Token> { match s { "fn" => Some(Token::Function), "let" => Some(Token::Let), "true" => Some(Token::True), "false" => Some(Token::False), "if" => Some(Token::If), "else" => Some(Token::Else), "return" => Some(Token::Return), "set" => Some(Token::Set), _ => None, } } fn is_letter(c: char) -> bool { c.is_ascii_alphabetic() || c == '_' } fn is_number(c: char) -> bool { ('0'..='9').contains(&c) } fn parse_int(chars: &[char]) -> Result<Integer> { if chars.len() < 2 { let raw: String = chars.iter().collect(); return Ok(Integer { radix: Radix::Decimal, value: raw.parse::<i64>().map_err(Error::IllegalInteger)?, }); } let (radix, skip) = match &chars[0..2] { ['0', 'b'] => (Radix::Binary, 2), ['0', 'x'] => (Radix::Hexadecimal, 2), ['0', 'o'] => (Radix::Octal, 2), ['0', '0'..='9'] => (Radix::Octal, 1), ['0', r] => { return Err(Error::IllegalIntegerRadix(*r)); } _ => (Radix::Decimal, 0), }; let raw: String = chars.iter().skip(skip).collect(); let base = match radix { Radix::Binary => 2, Radix::Decimal => 10, Radix::Hexadecimal => 16, Radix::Octal => 8, }; Ok(Integer { radix, value: i64::from_str_radix(&raw, base).map_err(Error::IllegalInteger)?, }) } pub type Result<T> = result::Result<T, Error>; #[derive(Debug, PartialEq)] pub enum Error { UnexpectedEof, IllegalFloat(num::ParseFloatError), IllegalIntegerRadix(char), IllegalInteger(num::ParseIntError), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::UnexpectedEof => write!(f, "unexpected EOF"), Error::IllegalFloat(err) => write!(f, "illegal floating point number: {}", err), Error::IllegalIntegerRadix(r) => write!(f, "illegal number radix: {}", r), Error::IllegalInteger(err) => write!(f, "illegal integer number: {}", err), } } } impl error::Error for Error { fn cause(&self) -> Option<&dyn error::Error> { match self { Error::IllegalFloat(err) => Some(err), Error::IllegalInteger(err) => Some(err), _ => None, } } }
use crate::token::{Float, Integer, Radix, Token}; use std::error; use std::fmt; use std::num; use std::result; use std::str::FromStr; pub struct Lexer<'a> { input: &'a str, position: usize, read_position: usize, ch: char, } impl<'a> Lexer<'a> { pub fn new(input: &'a str) -> Self { let mut l = Lexer { input, position: 0, read_position: 0, ch: 0 as char, }; l.read_char(); l }
]' => Token::RightBracket, '"' => self.read_string()?, '\u{0000}' => Token::Eof, _ => { if is_letter(self.ch) { let ident = self.read_identifier(); if let Some(key) = lookup_keyword(&ident) { return Ok(key); } else { return Ok(Token::Identifier(ident)); } } else if is_number(self.ch) { return self.read_number(); } else { Token::Illegal(self.ch) } } }; self.read_char(); Ok(t) } fn peek_char(&self) -> char { if self.read_position >= self.input.len() { 0 as char } else { if let Some(ch) = self.input.chars().nth(self.read_position) { ch } else { panic!("peeked out of range character") } } } fn read_char(&mut self) { if self.read_position >= self.input.len() { self.ch = 0 as char; } else { if let Some(ch) = self.input.chars().nth(self.read_position) { self.ch = ch; } else { panic!("read out of range character"); } } self.position = self.read_position; self.read_position += 1; } fn read_identifier(&mut self) -> String { let pos = self.position; while is_letter(self.ch) || self.ch.is_numeric() { self.read_char(); } self.input .chars() .skip(pos) .take(self.position - pos) .collect() } fn read_number(&mut self) -> Result<Token> { let pos = self.position; while (self.ch.is_ascii_alphanumeric() || self.ch == '.') && !self.ch.is_whitespace() { self.read_char(); } let chars: Vec<char> = self .input .chars() .skip(pos) .take(self.position - pos) .collect(); if chars.contains(&'.') { Ok(Token::Float(Float::from( f64::from_str(&chars.iter().collect::<String>()).map_err(Error::IllegalFloat)?, ))) } else { Ok(Token::Integer(parse_int(&chars)?)) } } fn read_string(&mut self) -> Result<Token> { let pos = self.position + 1; loop { self.read_char(); match self.ch { '"' => break, '\u{0000}' => { return Err(Error::UnexpectedEof); } _ => {} } } Ok(Token::String( self.input .chars() .skip(pos) .take(self.position - pos) .collect(), )) } fn skip_whitespace(&mut self) { while self.ch.is_ascii_whitespace() { self.read_char(); } } } fn lookup_keyword(s: &str) -> Option<Token> { match s { "fn" => Some(Token::Function), "let" => Some(Token::Let), "true" => Some(Token::True), "false" => Some(Token::False), "if" => Some(Token::If), "else" => Some(Token::Else), "return" => Some(Token::Return), "set" => Some(Token::Set), _ => None, } } fn is_letter(c: char) -> bool { c.is_ascii_alphabetic() || c == '_' } fn is_number(c: char) -> bool { ('0'..='9').contains(&c) } fn parse_int(chars: &[char]) -> Result<Integer> { if chars.len() < 2 { let raw: String = chars.iter().collect(); return Ok(Integer { radix: Radix::Decimal, value: raw.parse::<i64>().map_err(Error::IllegalInteger)?, }); } let (radix, skip) = match &chars[0..2] { ['0', 'b'] => (Radix::Binary, 2), ['0', 'x'] => (Radix::Hexadecimal, 2), ['0', 'o'] => (Radix::Octal, 2), ['0', '0'..='9'] => (Radix::Octal, 1), ['0', r] => { return Err(Error::IllegalIntegerRadix(*r)); } _ => (Radix::Decimal, 0), }; let raw: String = chars.iter().skip(skip).collect(); let base = match radix { Radix::Binary => 2, Radix::Decimal => 10, Radix::Hexadecimal => 16, Radix::Octal => 8, }; Ok(Integer { radix, value: i64::from_str_radix(&raw, base).map_err(Error::IllegalInteger)?, }) } pub type Result<T> = result::Result<T, Error>; #[derive(Debug, PartialEq)] pub enum Error { UnexpectedEof, IllegalFloat(num::ParseFloatError), IllegalIntegerRadix(char), IllegalInteger(num::ParseIntError), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::UnexpectedEof => write!(f, "unexpected EOF"), Error::IllegalFloat(err) => write!(f, "illegal floating point number: {}", err), Error::IllegalIntegerRadix(r) => write!(f, "illegal number radix: {}", r), Error::IllegalInteger(err) => write!(f, "illegal integer number: {}", err), } } } impl error::Error for Error { fn cause(&self) -> Option<&dyn error::Error> { match self { Error::IllegalFloat(err) => Some(err), Error::IllegalInteger(err) => Some(err), _ => None, } } }
pub fn lex(&mut self) -> Result<Vec<Token>> { let mut tokens = vec![]; loop { match self.next_token()? { t @ Token::Eof => { tokens.push(t); return Ok(tokens); } t => { tokens.push(t); } } } } pub fn next_token(&mut self) -> Result<Token> { self.skip_whitespace(); let t = match self.ch { '=' => { if self.peek_char() == '=' { self.read_char(); Token::Equal } else { Token::Assign } } '+' => Token::Plus, '-' => Token::Minus, '!' => { if self.peek_char() == '=' { self.read_char(); Token::NotEqual } else { Token::Bang } } '*' => Token::Asterisk, '/' => Token::Slash, '%' => Token::Percent, '<' => Token::LessThan, '>' => Token::GreaterThan, '&' => Token::Ampersand, ',' => Token::Comma, ':' => Token::Colon, ';' => Token::Semicolon, '(' => Token::LeftParen, ')' => Token::RightParen, '{' => Token::LeftBrace, '}' => Token::RightBrace, '[' => Token::LeftBracket, '
random
[ { "content": "fn compile(input: &str) -> Bytecode {\n\n let l = lexer::Lexer::new(input);\n\n\n\n let mut p = parser::Parser::new(l).expect(\"failed to create parser\");\n\n\n\n let prog = ast::Node::Program(p.parse().expect(\"failed to parse program\"));\n\n\n\n let mut c = Compiler::new();\n\n c.compile(prog).expect(\"failed to compile\");\n\n c.bytecode()\n\n}\n", "file_path": "tests/compiler.rs", "rank": 2, "score": 132452.98178625436 }, { "content": "fn assert_tokens_equal(want: &[Token], got: &[Token]) {\n\n assert_eq!(want.len(), got.len());\n\n\n\n for (a, b) in want.iter().zip(got) {\n\n assert_eq!(*a, *b);\n\n }\n\n}\n", "file_path": "tests/lexer.rs", "rank": 3, "score": 125467.81160524774 }, { "content": "fn parse(input: &str) -> ast::Program {\n\n let l = lexer::Lexer::new(input);\n\n\n\n let mut p = parser::Parser::new(l).expect(\"failed to create parser\");\n\n\n\n p.parse().expect(\"failed to parse program\")\n\n}\n", "file_path": "tests/parser.rs", "rank": 4, "score": 123787.42126429576 }, { "content": "fn compile(input: &str) -> compiler::Bytecode {\n\n let l = lexer::Lexer::new(input);\n\n\n\n let mut p = parser::Parser::new(l).expect(\"failed to create parser\");\n\n\n\n let prog = ast::Node::Program(p.parse().expect(\"failed to parse program\"));\n\n\n\n let mut c = compiler::Compiler::new();\n\n c.compile(prog).expect(\"failed to compile\");\n\n c.bytecode()\n\n}\n", "file_path": "tests/vm.rs", "rank": 5, "score": 123787.42126429576 }, { "content": "fn eval(input: &str) -> object::Object {\n\n eval_result(input).expect(\"failed to evaluate program\")\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 6, "score": 123787.42126429576 }, { "content": "#[test]\n\nfn lex_integer_literals() {\n\n let got = Lexer::new(\n\n \"\n\n101\n\n0b101\n\n0101\n\n0o101\n\n0x101;\n\n\",\n\n )\n\n .lex()\n\n .expect(\"failed to lex tokens\");\n\n\n\n let want = vec![\n\n Token::Integer(Integer {\n\n radix: Radix::Decimal,\n\n value: 101,\n\n }),\n\n Token::Integer(Integer {\n\n radix: Radix::Binary,\n", "file_path": "tests/lexer.rs", "rank": 9, "score": 109557.42762963928 }, { "content": "#[test]\n\nfn lex_next_token() {\n\n let got = Lexer::new(\n\n r#\"\n\nlet five = 5;\n\nlet ten = 10;\n\n\n\nlet add = fn(x, y) {\n\n x + y;\n\n};\n\n\n\nlet result = add(five, ten);\n\n\n\n!-/*5;\n\n5 < 10 > 5;\n\n\n\nif (5 < 10) {\n\n return true;\n\n} else {\n\n return false;\n\n}\n", "file_path": "tests/lexer.rs", "rank": 10, "score": 109404.85691570982 }, { "content": "fn assert_instructions(input: &str, want: &[u8], got: &[u8]) {\n\n let want_ins = Instructions::parse(want).expect(\"failed to parse want instructions\");\n\n let got_ins = Instructions::parse(got).expect(\"failed to parse got instructions\");\n\n\n\n assert_eq!(\n\n want_ins, got_ins,\n\n \"\\ninput: {}, unexpected instructions stream:\\nwant:\\n{}\\ngot:\\n{}\",\n\n input, want_ins, got_ins\n\n );\n\n}\n\n\n", "file_path": "tests/compiler.rs", "rank": 11, "score": 106898.09834061672 }, { "content": "fn eval_result(input: &str) -> evaluator::Result<object::Object> {\n\n let l = lexer::Lexer::new(input);\n\n\n\n let mut p = parser::Parser::new(l).expect(\"failed to create parser\");\n\n\n\n let prog = p.parse().expect(\"failed to parse program\");\n\n\n\n evaluator::eval(ast::Node::Program(prog), &mut object::Environment::new())\n\n}\n", "file_path": "tests/evaluator.rs", "rank": 12, "score": 106898.09834061672 }, { "content": "#[test]\n\nfn lex_illegal_number_radix() {\n\n let err = Lexer::new(\"0q000\")\n\n .lex()\n\n .expect_err(\"expected illegal radix error\");\n\n\n\n assert_eq!(err, Error::IllegalIntegerRadix('q'));\n\n}\n\n\n", "file_path": "tests/lexer.rs", "rank": 13, "score": 105425.08609524532 }, { "content": "#[test]\n\nfn token_display() {\n\n let tests = vec![\n\n (Token::Illegal('x'), \"illegal(x)\"),\n\n (Token::Eof, \"EOF\"),\n\n (\n\n Token::Identifier(\"string\".to_string()),\n\n \"identifier(string)\",\n\n ),\n\n (\n\n Token::Integer(Integer {\n\n radix: Radix::Decimal,\n\n value: 101,\n\n }),\n\n \"101\",\n\n ),\n\n (\n\n Token::Integer(Integer {\n\n radix: Radix::Binary,\n\n value: 0b101,\n\n }),\n", "file_path": "tests/token.rs", "rank": 14, "score": 92531.61260769909 }, { "content": "/// Evaluates an `ast::Node` and produces an `object::Object`.\n\npub fn eval(node: ast::Node, env: &mut object::Environment) -> Result<Object> {\n\n // TODO(mdlayher): clean up error handling via err_node.\n\n let err_node = node.clone();\n\n match node {\n\n ast::Node::Program(prog) => eval_program(prog, env),\n\n ast::Node::Statement(stmt) => match stmt {\n\n ast::Statement::Block(block) => eval_block_statement(block, env),\n\n ast::Statement::Expression(expr) => eval(ast::Node::Expression(expr), env),\n\n ast::Statement::Let(stmt) => {\n\n let obj = eval(ast::Node::Expression(stmt.value), env)?;\n\n\n\n // eval succeeded; capture this binding in our environment.\n\n env.set(stmt.name, &obj);\n\n Ok(obj)\n\n }\n\n ast::Statement::Return(ret) => Ok(Object::ReturnValue(Box::new(eval(\n\n ast::Node::Expression(ret.value),\n\n env,\n\n )?))),\n\n // The evaluator is deprecated and new types will be handled\n", "file_path": "src/evaluator.rs", "rank": 15, "score": 90305.74716875661 }, { "content": "/// Produces bytecode for one instruction from an input `Opcode` and its\n\n/// operands.\n\npub fn make(op: Opcode, operands: &[usize]) -> Result<Vec<u8>> {\n\n let def = lookup(op);\n\n\n\n // Ensure the correct number of operands were passed for this opcode.\n\n if operands.len() != def.operand_widths.len() {\n\n return Err(Error::Internal {\n\n op,\n\n kind: ErrorKind::BadNumberOperands {\n\n want: def.operand_widths.len(),\n\n got: operands.len(),\n\n },\n\n });\n\n }\n\n\n\n // Allocate enough space for the opcode and all of its operands.\n\n let mut buf = Vec::with_capacity(\n\n 1 + def\n\n .operand_widths\n\n .iter()\n\n .map(|w| *w as usize)\n", "file_path": "src/code.rs", "rank": 16, "score": 88202.62681443177 }, { "content": "// Determines the Precedence value of a given Token.\n\nfn precedence(tok: &Token) -> Precedence {\n\n match tok {\n\n Token::Equal => Precedence::Equals,\n\n Token::NotEqual => Precedence::Equals,\n\n Token::LessThan => Precedence::LessGreater,\n\n Token::GreaterThan => Precedence::LessGreater,\n\n Token::Plus => Precedence::Sum,\n\n Token::Minus => Precedence::Sum,\n\n Token::Slash => Precedence::Product,\n\n Token::Asterisk => Precedence::Product,\n\n Token::Percent => Precedence::Product,\n\n Token::LeftParen => Precedence::Call,\n\n Token::LeftBracket => Precedence::Index,\n\n\n\n _ => Precedence::Lowest,\n\n }\n\n}\n\n\n\n/// A Result type specialized use with for an Error.\n\npub type Result<T> = result::Result<T, Error>;\n", "file_path": "src/parser.rs", "rank": 17, "score": 86816.82713486059 }, { "content": "/// Returns all of the built-in functions.\n\npub fn builtins() -> Vec<Builtin> {\n\n vec![\n\n Builtin::First,\n\n Builtin::Last,\n\n Builtin::Len,\n\n Builtin::Push,\n\n Builtin::Puts,\n\n Builtin::Rest,\n\n ]\n\n}\n\n\n\nimpl From<u8> for Builtin {\n\n /// Convert from a u8 to a Builtin.\n\n fn from(v: u8) -> Self {\n\n match v {\n\n 0x00 => Builtin::First,\n\n 0x01 => Builtin::Last,\n\n 0x02 => Builtin::Len,\n\n 0x03 => Builtin::Push,\n\n 0x04 => Builtin::Puts,\n", "file_path": "src/object.rs", "rank": 18, "score": 86811.38672014297 }, { "content": "// Evaluates `l (op) r` and returns the result for simple mathematical operations.\n\nfn eval_infix_op(op: Token, l: f64, r: f64) -> f64 {\n\n match op {\n\n Token::Plus => l + r,\n\n Token::Minus => l - r,\n\n Token::Asterisk => l * r,\n\n Token::Slash => l / r,\n\n Token::Percent => l % r,\n\n\n\n _ => panic!(\"eval_infix_op called with unsupported operator\"),\n\n }\n\n}\n\n\n", "file_path": "src/evaluator.rs", "rank": 19, "score": 80009.7747458701 }, { "content": "#[test]\n\nfn evaluate_let_statement() {\n\n let tests = vec![\n\n (\"let a = 5; a;\", 5),\n\n (\"let a = 5 * 5; a;\", 25),\n\n (\"let a = 5; let b = a; b;\", 5),\n\n (\"let a = 5; let b = a; let c = a + b + 5; c\", 15),\n\n ];\n\n\n\n for (input, want) in tests {\n\n let got = if let object::Object::Integer(int) = eval(input) {\n\n int\n\n } else {\n\n panic!(\"not an integer object\");\n\n };\n\n\n\n assert_eq!(want, got);\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 20, "score": 79929.54688862507 }, { "content": "#[test]\n\nfn evaluate_integer_expression() {\n\n let tests = vec![\n\n (\"5\", 5),\n\n (\"10\", 10),\n\n (\"-5\", -5),\n\n (\"-10\", -10),\n\n (\"5 + 5 + 5 + 5 - 10\", 10),\n\n (\"2 * 2 * 2 *2 * 2\", 32),\n\n (\"-50 + 100 + -50\", 0),\n\n (\"50 / 2 * 2 + 10\", 60),\n\n (\"2 * (5 + 10)\", 30),\n\n (\"(5 + 10 * 2 + 15 / 3) * 2 + -10\", 50),\n\n (\"4 % 3\", 1),\n\n ];\n\n\n\n for (input, want) in tests {\n\n let got = if let object::Object::Integer(int) = eval(input) {\n\n int\n\n } else {\n\n panic!(\"not an integer object\");\n\n };\n\n\n\n assert_eq!(want, got);\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 21, "score": 79878.39029987305 }, { "content": "#[test]\n\nfn lex_illegal_number() {\n\n let inputs = vec![\"0bX\", \"0xX\", \"0oX\", \"1X\"];\n\n\n\n for input in inputs {\n\n let err = Lexer::new(input)\n\n .lex()\n\n .expect_err(&format!(\"expected illegal number error for {}\", input));\n\n\n\n match err {\n\n Error::IllegalInteger(_) => {}\n\n _ => panic!(\"unexpected error type: {:?}\", err),\n\n };\n\n }\n\n}\n\n\n", "file_path": "tests/lexer.rs", "rank": 22, "score": 79488.7186619796 }, { "content": "#[test]\n\nfn parse_integer_literal_expression() {\n\n let prog = parse(\"5;\");\n\n\n\n assert_eq!(prog.statements.len(), 1);\n\n\n\n let want = token::Integer {\n\n radix: token::Radix::Decimal,\n\n value: 5,\n\n };\n\n\n\n let got = if let ast::Statement::Expression(ast::Expression::Integer(int)) = &prog.statements[0]\n\n {\n\n int\n\n } else {\n\n panic!(\"not an integer expression\");\n\n };\n\n\n\n assert_eq!(want, *got);\n\n}\n\n\n", "file_path": "tests/parser.rs", "rank": 23, "score": 77090.16536436084 }, { "content": "#[test]\n\nfn parse_infix_integer_expressions() {\n\n let int = ast::Expression::Integer(token::Integer {\n\n radix: token::Radix::Decimal,\n\n value: 5,\n\n });\n\n\n\n let tests = vec![\n\n (\"5 + 5;\", token::Token::Plus),\n\n (\"5 - 5;\", token::Token::Minus),\n\n (\"5 * 5;\", token::Token::Asterisk),\n\n (\"5 / 5;\", token::Token::Slash),\n\n (\"5 % 5;\", token::Token::Percent),\n\n (\"5 > 5;\", token::Token::GreaterThan),\n\n (\"5 < 5;\", token::Token::LessThan),\n\n (\"5 == 5;\", token::Token::Equal),\n\n (\"5 != 5;\", token::Token::NotEqual),\n\n ];\n\n\n\n for (input, want_op) in tests {\n\n let prog = parse(input);\n", "file_path": "tests/parser.rs", "rank": 24, "score": 77090.16536436084 }, { "content": "#[test]\n\nfn parse_prefix_integer_expressions() {\n\n let tests = vec![\n\n (\"!5;\", token::Token::Bang, 5),\n\n (\"-15;\", token::Token::Minus, 15),\n\n ];\n\n\n\n for test in tests {\n\n let (input, want_op, want_int) = test;\n\n let prog = parse(input);\n\n\n\n let got =\n\n if let ast::Statement::Expression(ast::Expression::Prefix(pre)) = &prog.statements[0] {\n\n pre\n\n } else {\n\n panic!(\"not a prefix expression\");\n\n };\n\n\n\n let got_int = if let ast::Expression::Integer(int) = &*got.right {\n\n int\n\n } else {\n\n panic!(\"not an integer expression\");\n\n };\n\n\n\n assert_eq!(want_op, got.operator);\n\n assert_eq!(want_int, got_int.value)\n\n }\n\n}\n\n\n", "file_path": "tests/parser.rs", "rank": 25, "score": 77090.16536436084 }, { "content": "#[test]\n\nfn lex_string_unexpected_eof() {\n\n let err = Lexer::new(r#\"\"foobar \"#)\n\n .lex()\n\n .expect_err(\"expected unexpected EOF error\");\n\n\n\n assert_eq!(err, Error::UnexpectedEof);\n\n}\n\n\n", "file_path": "tests/lexer.rs", "rank": 26, "score": 76718.95591535675 }, { "content": "#[test]\n\nfn evaluate_let_statement_unknown_identifier() {\n\n let input = \"foobar\";\n\n\n\n let err = eval_result(input).expect_err(\"expected an error but none was found\");\n\n\n\n if let evaluator::Error::UnknownIdentifier(id) = err {\n\n assert_eq!(input, id);\n\n } else {\n\n panic!(\"not an unknown identifier error\");\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 27, "score": 74600.72301429554 }, { "content": "/// Executes a composite indexing operation.\n\npub fn composite_index(args: &[Object]) -> Result<Object> {\n\n assert_eq!(\n\n args.len(),\n\n 2,\n\n \"expected exactly 2 arguments for composite indexing operation\"\n\n );\n\n\n\n match (&args[0], &args[1]) {\n\n // Array with numeric index.\n\n (Object::Array(a), Object::Integer(i)) => {\n\n // Is the element in bounds? If not, return null.\n\n if *i >= 0 && (*i as usize) < a.elements.len() {\n\n Ok(a.elements[*i as usize].clone())\n\n } else {\n\n Ok(Object::Null)\n\n }\n\n }\n\n // Hash with some type of index.\n\n (object::Object::Hash(h), k) => {\n\n let k =\n", "file_path": "src/vm/op.rs", "rank": 28, "score": 72225.68045574405 }, { "content": "/// Builds a Set from stack objects.\n\npub fn build_set(args: &[Object]) -> Result<Object> {\n\n let mut set = BTreeSet::new();\n\n\n\n for a in args {\n\n // Only accept object::Hashable objects as keys.\n\n let arg = Hashable::try_from(a).map_err(|e| Error::Runtime(ErrorKind::Object(e)))?;\n\n\n\n // Do not allow duplicate keys in the set.\n\n if set.contains(&arg) {\n\n return Err(Error::Runtime(ErrorKind::DuplicateKey(arg)));\n\n }\n\n set.insert(arg);\n\n }\n\n\n\n Ok(Object::Set(Set { set }))\n\n}\n", "file_path": "src/vm/op.rs", "rank": 29, "score": 72225.68045574405 }, { "content": "/// Builds a Hash from stack objects.\n\npub fn build_hash(args: &[Object]) -> Result<Object> {\n\n if args.is_empty() {\n\n // No arguments, empty hash.\n\n return Ok(Object::Hash(Hash::default()));\n\n }\n\n\n\n // The parser and compiler should make this assertion hold.\n\n assert!(\n\n args.len() % 2 == 0,\n\n \"hash must contain an even number of objects\"\n\n );\n\n\n\n // Iterate two objects at a time for each key/value pair.\n\n let mut pairs = BTreeMap::new();\n\n\n\n let mut i = 0;\n\n while i < args.len() {\n\n // Only accept object::Hashable objects as keys.\n\n let k = Hashable::try_from(&args[i]).map_err(|e| Error::Runtime(ErrorKind::Object(e)))?;\n\n\n", "file_path": "src/vm/op.rs", "rank": 30, "score": 72225.68045574405 }, { "content": "/// Executes a binary float operation.\n\npub fn binary_float(op: BinaryOpcode, args: &[Object], l: f64, r: f64) -> Result<Object> {\n\n let out = match op {\n\n BinaryOpcode::Add => Object::Float(l + r),\n\n BinaryOpcode::Sub => Object::Float(l - r),\n\n BinaryOpcode::Mul => Object::Float(l * r),\n\n BinaryOpcode::Div => Object::Float(l / r),\n\n BinaryOpcode::Mod => Object::Float(l % r),\n\n BinaryOpcode::GreaterThan => Object::Boolean(l > r),\n\n BinaryOpcode::Equal | BinaryOpcode::NotEqual | BinaryOpcode::Index => {\n\n // Operator not supported with float arguments.\n\n return Err(Error::Runtime(ErrorKind::OperatorUnsupported(\n\n Opcode::Binary(op),\n\n args.to_vec(),\n\n )));\n\n }\n\n };\n\n\n\n Ok(out)\n\n}\n\n\n", "file_path": "src/vm/op.rs", "rank": 31, "score": 64400.410745940564 }, { "content": "/// Executes a binary set operation.\n\npub fn binary_set(op: BinaryOpcode, args: &[Object], l: &Set, r: &Set) -> Result<Object> {\n\n // Check for subset.\n\n if op == BinaryOpcode::GreaterThan {\n\n return Ok(if r.set.is_subset(&l.set) {\n\n object::TRUE\n\n } else {\n\n object::FALSE\n\n });\n\n }\n\n\n\n // TODO(mdlayher): work out the operator situation here, but this\n\n // is good enough for now.\n\n let set: BTreeSet<_> = match op {\n\n BinaryOpcode::Add => l.set.union(&r.set).cloned().collect(),\n\n BinaryOpcode::Sub => l.set.difference(&r.set).cloned().collect(),\n\n BinaryOpcode::Mul => l.set.intersection(&r.set).cloned().collect(),\n\n BinaryOpcode::Div => l.set.symmetric_difference(&r.set).cloned().collect(),\n\n _ => {\n\n return Err(Error::Runtime(ErrorKind::OperatorUnsupported(\n\n Opcode::Binary(op),\n\n args.to_vec(),\n\n )));\n\n }\n\n };\n\n\n\n Ok(Object::Set(object::Set { set }))\n\n}\n\n\n", "file_path": "src/vm/op.rs", "rank": 32, "score": 64400.410745940564 }, { "content": "/// Executes a pointer arithmetic operation.\n\npub fn pointer_arithmetic(op: BinaryOpcode, args: &[Object], l: i64, r: i64) -> Result<Object> {\n\n let out = match op {\n\n BinaryOpcode::Add => l + r,\n\n BinaryOpcode::Sub => l - r,\n\n _ => {\n\n // Reign in the pointer arithmetic madness!\n\n return Err(Error::Runtime(ErrorKind::OperatorUnsupported(\n\n Opcode::Binary(op),\n\n args.to_vec(),\n\n )));\n\n }\n\n };\n\n\n\n Ok(Object::Pointer(out as usize))\n\n}\n\n\n", "file_path": "src/vm/op.rs", "rank": 33, "score": 64400.410745940564 }, { "content": "/// Evaluates an object bound to an identifier and returns the result.\n\nfn eval_identifier(id: String, env: &mut object::Environment) -> Result<Object> {\n\n match object::Builtin::lookup(&id) {\n\n // Found a built-in.\n\n Some(b) => Ok(Object::Builtin(b)),\n\n\n\n // Didn't find a built-in, look for user-defined identifiers.\n\n None => Ok(env.get(&id).ok_or(Error::UnknownIdentifier(id))?.clone()),\n\n }\n\n}\n\n\n", "file_path": "src/evaluator.rs", "rank": 34, "score": 63437.087609852635 }, { "content": "/// Evaluates a program and returns the result.\n\nfn eval_program(prog: ast::Program, env: &mut object::Environment) -> Result<Object> {\n\n let mut result = Object::Null;\n\n\n\n for stmt in prog.statements {\n\n result = eval(ast::Node::Statement(stmt.clone()), env)?;\n\n\n\n // Handle early return statements if applicable, unwrapping the inner\n\n // value and terminating the program.\n\n if let Object::ReturnValue(value) = result {\n\n return Ok(*value);\n\n }\n\n }\n\n\n\n Ok(result)\n\n}\n\n\n", "file_path": "src/evaluator.rs", "rank": 35, "score": 60554.87079299558 }, { "content": "/// Evaluates an if/else expression to produce an Object.\n\nfn eval_if_expression(expr: ast::IfExpression, env: &mut object::Environment) -> Result<Object> {\n\n let condition = eval(ast::Node::Expression(*expr.condition), env)?;\n\n\n\n if is_truthy(&condition) {\n\n eval(\n\n ast::Node::Statement(ast::Statement::Block(expr.consequence)),\n\n env,\n\n )\n\n } else if let Some(alt) = expr.alternative {\n\n eval(ast::Node::Statement(ast::Statement::Block(alt)), env)\n\n } else {\n\n Ok(Object::Null)\n\n }\n\n}\n\n\n", "file_path": "src/evaluator.rs", "rank": 36, "score": 60554.87079299558 }, { "content": "#[derive(Debug)]\n\nstruct Emitted {\n\n op: Opcode,\n\n pos: usize,\n\n}\n\n\n\nimpl Compiler {\n\n pub fn new() -> Self {\n\n // Initialize the compiler and enter the \"main\" scope. Do not call\n\n // the enter_scope method to avoid creating an immediate outer\n\n // symbol table.\n\n let c = Self {\n\n scopes: vec![CompilationScope::default()],\n\n ..Self::default()\n\n };\n\n\n\n // Define builtins so we can emit the appropriate opcodes for\n\n // handling them.\n\n {\n\n let mut table = c.symbols.borrow_mut();\n\n for b in object::builtins() {\n", "file_path": "src/compiler/compile.rs", "rank": 37, "score": 57350.01993625685 }, { "content": "#[derive(Default)]\n\nstruct CompilationScope {\n\n instructions: Vec<u8>,\n\n last: Option<Emitted>,\n\n previous: Option<Emitted>,\n\n}\n\n\n", "file_path": "src/compiler/compile.rs", "rank": 38, "score": 55774.28152490087 }, { "content": "#[derive(Debug)]\n\nstruct Definition<'a> {\n\n name: &'a str,\n\n operand_widths: Vec<Width>,\n\n}\n\n\n", "file_path": "src/code.rs", "rank": 39, "score": 55368.58700888661 }, { "content": "/// Evaluates several expressions and produces objects for each of them.\n\nfn eval_expressions(\n\n expressions: Vec<ast::Expression>,\n\n env: &mut object::Environment,\n\n) -> Result<Vec<Object>> {\n\n let mut results = vec![];\n\n\n\n for expr in expressions {\n\n results.push(eval(ast::Node::Expression(expr), env)?);\n\n }\n\n\n\n Ok(results)\n\n}\n\n\n", "file_path": "src/evaluator.rs", "rank": 40, "score": 51316.02327415568 }, { "content": "#[test]\n\nfn compiler_ok() {\n\n let tests = vec![\n\n (\n\n \"1 + 2\",\n\n vec![\n\n // 1\n\n Constant as u8,\n\n 0x00,\n\n 0x00,\n\n // 2\n\n Constant as u8,\n\n 0x00,\n\n 0x01,\n\n // +, pop\n\n Add as u8,\n\n Pop as u8,\n\n ],\n\n vec![Object::Integer(1), Object::Integer(2)],\n\n ),\n\n (\n", "file_path": "tests/compiler.rs", "rank": 41, "score": 51316.02327415568 }, { "content": "/// Applies a function with arguments to produce a result object.\n\nfn apply_function(\n\n function: object::Function,\n\n args: &[Object],\n\n err_node: ast::Node,\n\n) -> Result<Object> {\n\n // Bind function arguments in an enclosed environment.\n\n let mut extended_env = extend_function_env(&function, args, err_node)?;\n\n let evaluated = eval(\n\n ast::Node::Statement(ast::Statement::Block(function.body)),\n\n &mut extended_env,\n\n )?;\n\n\n\n // If the function had an early return, stop evaluation.\n\n if let Object::ReturnValue(ret) = evaluated {\n\n Ok(*ret)\n\n } else {\n\n Ok(evaluated)\n\n }\n\n}\n\n\n", "file_path": "src/evaluator.rs", "rank": 42, "score": 51316.02327415568 }, { "content": "#[test]\n\nfn ast_display() {\n\n let program = ast::Program {\n\n statements: vec![ast::Statement::Let(ast::LetStatement {\n\n name: \"myVar\".to_string(),\n\n value: ast::Expression::Identifier(\"anotherVar\".to_string()),\n\n })],\n\n };\n\n\n\n assert_eq!(format!(\"{}\", program), \"let myVar = anotherVar;\")\n\n}\n", "file_path": "tests/ast.rs", "rank": 43, "score": 51316.02327415568 }, { "content": "#[test]\n\nfn evaluate_if_expression() {\n\n let ten = object::Object::Integer(10);\n\n let twenty = object::Object::Integer(20);\n\n let null = object::Object::Null;\n\n\n\n let tests = vec![\n\n (\"if (true) { 10 }\", &ten),\n\n (\"if (false) { 10 }\", &null),\n\n (\"if (1) { 10 }\", &ten),\n\n (\"if (1 < 2) { 10 }\", &ten),\n\n (\"if (1 > 2) { 10 }\", &null),\n\n (\"if (1 < 2) { 10 } else { 20 }\", &ten),\n\n (\"if (1 > 2) { 10 } else { 20 }\", &twenty),\n\n ];\n\n\n\n for (input, want) in tests {\n\n assert_eq!(want, &eval(input));\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 44, "score": 51316.02327415568 }, { "content": "#[test]\n\nfn parse_if_expressions() {\n\n let tests = vec![\"if (x < y) { x }\", \"if (x > y) { x } else { y }\"];\n\n\n\n for test in tests {\n\n let got = format!(\"{}\", parse(test));\n\n\n\n assert_eq!(test, got);\n\n }\n\n}\n\n\n", "file_path": "tests/parser.rs", "rank": 45, "score": 51316.02327415568 }, { "content": "#[test]\n\nfn parse_statements() {\n\n // Good enough!\n\n let prog =\n\n parse(\"let x = 0x005 % (0.1 + 6) + add(1, 2, mult(10, fn(x, y) { return x * y; }(2, 2)));\");\n\n\n\n let want =\n\n \"let x = ((0x5 % (0.1 + 6)) + add(1, 2, mult(10, fn(x, y) { return (x * y); }(2, 2))));\";\n\n\n\n assert_eq!(want, format!(\"{}\", prog));\n\n}\n\n\n", "file_path": "tests/parser.rs", "rank": 46, "score": 51316.02327415568 }, { "content": "/// Evaluates a block statement and returns the result.\n\nfn eval_block_statement(\n\n block: ast::BlockStatement,\n\n env: &mut object::Environment,\n\n) -> Result<Object> {\n\n let mut result = Object::Null;\n\n\n\n for stmt in block.statements {\n\n result = eval(ast::Node::Statement(stmt.clone()), env)?;\n\n\n\n // Handle early return statements if applicable, but do not unwrap the\n\n // inner value so that only this block statement terminates, and not\n\n // the entire program.\n\n if let Object::ReturnValue(_) = result {\n\n return Ok(result);\n\n }\n\n }\n\n\n\n Ok(result)\n\n}\n\n\n", "file_path": "src/evaluator.rs", "rank": 47, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn evaluate_return_statement() {\n\n let tests = vec![\n\n \"return 10;\",\n\n \"return 10; 9;\",\n\n \"return 2 * 5; 9\",\n\n \"9; return 2 * 5; 9;\",\n\n \"if (10 > 1) {\n\n if (10 > 1) {\n\n return 10;\n\n }\n\n\n\n return 1;\n\n }\",\n\n ];\n\n\n\n for input in tests {\n\n let got = if let object::Object::Integer(int) = eval(input) {\n\n int\n\n } else {\n\n panic!(\"not an integer object\");\n\n };\n\n\n\n assert_eq!(10, got);\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 48, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn evaluate_function_application() {\n\n let tests = vec![\n\n (\"let identity = fn(x) { x; }; identity(5);\", 5),\n\n (\"let identity = fn(x) { return x; }; identity(5);\", 5),\n\n (\"let double = fn(x) { x * 2; }; double(5);\", 10),\n\n (\"let add = fn(x, y) { x + y; } add(5, 5);\", 10),\n\n (\"fn(x) { x; }(5)\", 5),\n\n // Closures also work!\n\n (\n\n \"\n\nlet newAdder = fn(x) {\n\n fn(y) { x + y };\n\n};\n\n\n\nlet addTwo = newAdder(2);\n\naddTwo(2);\n\n\",\n\n 4,\n\n ),\n\n // And higher-order functions!\n", "file_path": "tests/evaluator.rs", "rank": 49, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn parse_string_expression() {\n\n let prog = parse(r#\"\"hello world\"\"#);\n\n\n\n assert_eq!(prog.statements.len(), 1);\n\n\n\n let want = \"hello world\";\n\n\n\n let got = if let ast::Statement::Expression(ast::Expression::String(s)) = &prog.statements[0] {\n\n s\n\n } else {\n\n panic!(\"not a string expression\");\n\n };\n\n\n\n assert_eq!(want, got);\n\n}\n\n\n", "file_path": "tests/parser.rs", "rank": 50, "score": 49809.681332213346 }, { "content": "/// Evaluates an infix expression to produce an Object.\n\nfn eval_infix_expression(\n\n expr: ast::InfixExpression,\n\n env: &mut object::Environment,\n\n err_node: ast::Node,\n\n) -> Result<Object> {\n\n let left = eval(ast::Node::Expression(*expr.left), env)?;\n\n let right = eval(ast::Node::Expression(*expr.right), env)?;\n\n\n\n // Left and right types must match.\n\n match (left, right) {\n\n (Object::Integer(l), Object::Integer(r)) => match expr.operator {\n\n Token::Plus | Token::Minus | Token::Asterisk | Token::Slash | Token::Percent => Ok(\n\n Object::Integer(eval_infix_op(expr.operator, l as f64, r as f64) as i64),\n\n ),\n\n Token::LessThan => Ok(Object::Boolean(l < r)),\n\n Token::GreaterThan => Ok(Object::Boolean(l > r)),\n\n Token::Equal => Ok(Object::Boolean(l == r)),\n\n Token::NotEqual => Ok(Object::Boolean(l != r)),\n\n\n\n _ => Err(Error::Evaluation(\n", "file_path": "src/evaluator.rs", "rank": 51, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn evaluate_array_object() {\n\n let got = if let object::Object::Array(arr) = eval(\"[1, 2 * 2, 3 + 3]\") {\n\n arr\n\n } else {\n\n panic!(\"not an array object\");\n\n };\n\n\n\n let want = vec![\n\n object::Object::Integer(1),\n\n object::Object::Integer(4),\n\n object::Object::Integer(6),\n\n ];\n\n\n\n assert_eq!(want.len(), got.elements.len());\n\n for e in want.iter().zip(got.elements.iter()) {\n\n assert_eq!(e.0, e.1);\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 52, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn parse_function_literals() {\n\n let tests = vec![\n\n (\"fn() {};\", \"fn() { }\"),\n\n (\"fn(x) { };\", \"fn(x) { }\"),\n\n (\"fn(x, y) { x + y; };\", \"fn(x, y) { (x + y) }\"),\n\n ];\n\n\n\n for (input, want) in tests {\n\n let got = format!(\"{}\", parse(input));\n\n\n\n assert_eq!(want, got);\n\n }\n\n}\n\n\n", "file_path": "tests/parser.rs", "rank": 53, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn parse_array_literal() {\n\n let tests = vec![\n\n (\"[1, 2 * 2, !true]\", vec![\"1\", \"(2 * 2)\", \"(!true)\"]),\n\n (\"[]\", vec![]),\n\n ];\n\n\n\n for (input, want) in tests {\n\n let prog = parse(input);\n\n\n\n assert_eq!(prog.statements.len(), 1);\n\n\n\n let got = if let ast::Statement::Expression(ast::Expression::Array(a)) = &prog.statements[0]\n\n {\n\n a\n\n } else {\n\n panic!(\"not an array literal expression\");\n\n };\n\n\n\n assert_eq!(got.elements.len(), want.len());\n\n for e in want.iter().zip(got.elements.iter()) {\n\n assert_eq!(*e.0, format!(\"{}\", e.1));\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/parser.rs", "rank": 54, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn vm_grow_stack() {\n\n // The VM should grow its stack as needed.\n\n let mut vm = Vm::with_stack_size(compile(\"1 + (1 + (1 + (1 + 1)))\"), 0);\n\n vm.run().expect(\"failed to run VM\");\n\n\n\n let stack = vm.dump_stack();\n\n\n\n // Expect the stack to have grown at least large enough to hold all 5\n\n // elements.\n\n assert!(stack.len() > 4, \"stack did not grow length\");\n\n assert!(stack.capacity() > 4, \"stack did not grow capacity\");\n\n}\n\n\n", "file_path": "tests/vm.rs", "rank": 55, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn vm_run_ok() {\n\n let tests = vec![\n\n (\"\", Object::Null),\n\n (\"1\", Object::Integer(1)),\n\n (\"1 + 2\", Object::Integer(3)),\n\n (\"2 - 1 - 1\", Object::Integer(0)),\n\n (\"2 * 2\", Object::Integer(4)),\n\n (\"10 / 3\", Object::Integer(3)),\n\n (\"10 % 3\", Object::Integer(1)),\n\n (\"1 * 1.0\", Object::Float(1.0)),\n\n (\"2.0 * 1\", Object::Float(2.0)),\n\n (\"1.0 + 1.0\", Object::Float(2.0)),\n\n (\"1.0 - 1.0\", Object::Float(0.0)),\n\n (\"2.0 * 1.0\", Object::Float(2.0)),\n\n (\"2.0 / 1.0\", Object::Float(2.0)),\n\n (\"4.0 % 3.0\", Object::Float(1.0)),\n\n (\"true\", object::TRUE),\n\n (\"false\", object::FALSE),\n\n (\"1 == 1\", object::TRUE),\n\n (\"1 != 1\", object::FALSE),\n", "file_path": "tests/vm.rs", "rank": 56, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn evaluate_builtin_last() {\n\n let tests = vec![\n\n (\"last([1, 2, 3])\", object::Object::Integer(3)),\n\n (\n\n r#\"last([\"hello\", \"world\"])\"#,\n\n object::Object::String(\"world\".to_string()),\n\n ),\n\n (\"last([])\", object::Object::Null),\n\n ];\n\n\n\n for (input, want) in tests {\n\n let got = eval(input);\n\n match got {\n\n object::Object::Integer(_) | object::Object::String(_) | object::Object::Null => {}\n\n _ => panic!(\"unexpected result object\"),\n\n };\n\n\n\n assert_eq!(want, got);\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 57, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn evaluate_builtin_push() {\n\n let tests = vec![\n\n (\n\n \"push([1, 2, 3], 4)\",\n\n object::Array {\n\n elements: vec![\n\n object::Object::Integer(1),\n\n object::Object::Integer(2),\n\n object::Object::Integer(3),\n\n object::Object::Integer(4),\n\n ],\n\n },\n\n ),\n\n (\n\n r#\"push([\"hello\"], \"world\")\"#,\n\n object::Array {\n\n elements: vec![\n\n object::Object::String(\"hello\".to_string()),\n\n object::Object::String(\"world\".to_string()),\n\n ],\n", "file_path": "tests/evaluator.rs", "rank": 58, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn evaluate_hash_objects() {\n\n let mut pairs = BTreeMap::new();\n\n pairs.insert(\n\n object::Hashable::String(\"one\".to_string()),\n\n object::Object::Integer(1),\n\n );\n\n pairs.insert(\n\n object::Hashable::Integer(2),\n\n object::Object::String(\"two\".to_string()),\n\n );\n\n pairs.insert(object::Hashable::Boolean(true), object::Object::Integer(3));\n\n\n\n let tests = vec![(\n\n r#\"\n\nlet two = 2;\n\n{\"one\": 1 + (0 * 1), two: \"two\", true: 3}\n\n \"#,\n\n object::Hash { pairs },\n\n )];\n\n\n", "file_path": "tests/evaluator.rs", "rank": 59, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn vm_runtime_errors() {\n\n let tests = vec![\n\n (\n\n \"1[0]\",\n\n ErrorKind::OperatorUnsupported(\n\n Opcode::Binary(BinaryOpcode::Index),\n\n vec![Object::Integer(1), Object::Integer(0)],\n\n ),\n\n ),\n\n (\n\n \"-true\",\n\n ErrorKind::OperatorUnsupported(Opcode::Unary(UnaryOpcode::Negate), vec![object::TRUE]),\n\n ),\n\n (\n\n \"true + false\",\n\n ErrorKind::OperatorUnsupported(\n\n Opcode::Binary(BinaryOpcode::Add),\n\n vec![object::TRUE, object::FALSE],\n\n ),\n\n ),\n", "file_path": "tests/vm.rs", "rank": 60, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn code_make_error() {\n\n let tests = vec![\n\n (\n\n Opcode::Control(ControlOpcode::Constant),\n\n vec![],\n\n ErrorKind::BadNumberOperands { want: 1, got: 0 },\n\n ),\n\n (\n\n Opcode::Control(ControlOpcode::Pop),\n\n vec![1],\n\n ErrorKind::BadNumberOperands { want: 0, got: 1 },\n\n ),\n\n (\n\n Opcode::Control(ControlOpcode::True),\n\n vec![1],\n\n ErrorKind::BadNumberOperands { want: 0, got: 1 },\n\n ),\n\n (\n\n Opcode::Control(ControlOpcode::False),\n\n vec![1],\n", "file_path": "tests/code.rs", "rank": 61, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn parse_call_expressions() {\n\n let tests = vec![\n\n (\"add(1, 2 * 3, 4 + 5);\", \"add(1, (2 * 3), (4 + 5))\"),\n\n (\"a + add(b * c) + d\", \"((a + add((b * c))) + d)\"),\n\n (\n\n \"add(a, b, 1, 2 * 3, 4 + 5, add(6, 7 * 8))\",\n\n \"add(a, b, 1, (2 * 3), (4 + 5), add(6, (7 * 8)))\",\n\n ),\n\n ];\n\n\n\n for (input, want) in tests {\n\n let got = format!(\"{}\", parse(input));\n\n\n\n assert_eq!(want, got);\n\n }\n\n}\n\n\n", "file_path": "tests/parser.rs", "rank": 62, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn parse_set_expressions() {\n\n let tests = vec![\n\n (r#\"set{1, \"foo\", true}\"#, r#\"set{1, \"foo\", true}\"#),\n\n (\"set{1}\", \"set{1}\"),\n\n // Duplicate elements permitted by the parser.\n\n (\"set{1, 1, 1, 2}\", \"set{1, 1, 1, 2}\"),\n\n ];\n\n\n\n for (input, want) in tests {\n\n let got = format!(\"{}\", parse(input));\n\n\n\n assert_eq!(want, got);\n\n }\n\n}\n\n\n", "file_path": "tests/parser.rs", "rank": 63, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn evaluate_boolean_expression() {\n\n let tests = vec![\n\n (\"true\", true),\n\n (\"false\", false),\n\n (\"true == true\", true),\n\n (\"false == false\", true),\n\n (\"true == false\", false),\n\n (\"true != false\", true),\n\n (\"false != true\", true),\n\n (\"(1 == 1) == true\", true),\n\n (\"(1 != 2) == true\", true),\n\n (\"(1 < 2) == true\", true),\n\n (\"(1 < 2) == false\", false),\n\n (\"(1 > 2) == true\", false),\n\n (\"(1 > 2) == false\", true),\n\n ];\n\n\n\n for (input, want) in tests {\n\n let got = if let object::Object::Boolean(b) = eval(input) {\n\n b\n\n } else {\n\n panic!(\"not a boolean object\");\n\n };\n\n\n\n assert_eq!(want, got);\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 64, "score": 49809.681332213346 }, { "content": "/// Evaluates a prefix expression to produce an Object.\n\nfn eval_prefix_expression(\n\n expr: ast::PrefixExpression,\n\n env: &mut object::Environment,\n\n err_node: ast::Node,\n\n) -> Result<Object> {\n\n // Evaluate the right side before applying the prefix operator.\n\n let right = eval(ast::Node::Expression(*expr.right), env)?;\n\n\n\n match expr.operator {\n\n // Logical negation.\n\n Token::Bang => match right {\n\n // Negate the input boolean.\n\n Object::Boolean(b) => Ok(Object::Boolean(!b)),\n\n // !null == true.\n\n Object::Null => Ok(Object::Boolean(true)),\n\n // 5 == true, so !5 == false.\n\n _ => Ok(Object::Boolean(false)),\n\n },\n\n // Negative numbers.\n\n Token::Minus => match right {\n", "file_path": "src/evaluator.rs", "rank": 65, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn evaluate_float_expression() {\n\n let tests = vec![\n\n (\"0.1\", 0.1),\n\n (\"-1.0 + 0.1\", -0.9),\n\n (\"1.0 - 1.0\", 0.0),\n\n (\"1.0 * 2.0\", 2.0),\n\n (\"0.1 / 10.0\", 0.01),\n\n (\"4.0 % 3.0\", 1.0),\n\n (\"1 + 0.1\", 1.1),\n\n (\"2 - 0.1\", 1.9),\n\n (\"1.0 * 3.0\", 3.0),\n\n (\"4 / 1.0\", 4.0),\n\n (\"5 % 3.0\", 2.0),\n\n ];\n\n\n\n for (input, want) in tests {\n\n let got = if let object::Object::Float(float) = eval(input) {\n\n float\n\n } else {\n\n panic!(\"not a float object\");\n\n };\n\n\n\n assert!((want - got).abs() < std::f64::EPSILON);\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 66, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn evaluate_builtin_first() {\n\n let tests = vec![\n\n (\"first([1, 2, 3])\", object::Object::Integer(1)),\n\n (\n\n r#\"first([\"hello\", \"world\"])\"#,\n\n object::Object::String(\"hello\".to_string()),\n\n ),\n\n (\"first([])\", object::Object::Null),\n\n ];\n\n\n\n for (input, want) in tests {\n\n let got = eval(input);\n\n match got {\n\n object::Object::Integer(_) | object::Object::String(_) | object::Object::Null => {}\n\n _ => panic!(\"unexpected result object\"),\n\n };\n\n\n\n assert_eq!(want, got);\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 67, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn evaluate_builtin_len() {\n\n let tests = vec![\n\n (r#\"len(\"\")\"#, 0),\n\n (r#\"len(\"four\")\"#, 4),\n\n (r#\"len(\"hello world\")\"#, 11),\n\n (\"len([1, 2, 3])\", 3),\n\n ];\n\n\n\n for (input, want) in tests {\n\n let got = if let object::Object::Integer(int) = eval(input) {\n\n int\n\n } else {\n\n panic!(\"not an integer object\");\n\n };\n\n\n\n assert_eq!(want, got);\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 68, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn evaluate_function_object() {\n\n let input = \"fn(x) { x + 2 };\";\n\n\n\n let got = if let object::Object::Function(func) = eval(input) {\n\n func\n\n } else {\n\n panic!(\"not a function object\");\n\n };\n\n\n\n assert_eq!(1, got.parameters.len());\n\n assert_eq!(\"x\", got.parameters[0]);\n\n\n\n assert_eq!(\"(x + 2)\", format!(\"{}\", got.body));\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 69, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn parse_identifier_expression() {\n\n let prog = parse(\"foobar;\");\n\n\n\n assert_eq!(prog.statements.len(), 1);\n\n\n\n let id =\n\n if let ast::Statement::Expression(ast::Expression::Identifier(id)) = &prog.statements[0] {\n\n id.to_string()\n\n } else {\n\n panic!(\"not an identifier expression\");\n\n };\n\n\n\n assert_eq!(\"foobar\", id);\n\n}\n\n\n", "file_path": "tests/parser.rs", "rank": 70, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn evaluate_prefix_expression() {\n\n let tests = vec![\n\n (\"!true\", false),\n\n (\"!false\", true),\n\n (\"!5\", false),\n\n (\"!!true\", true),\n\n (\"!!false\", false),\n\n (\"!!5\", true),\n\n ];\n\n\n\n for (input, want) in tests {\n\n let got = if let object::Object::Boolean(b) = eval(input) {\n\n b\n\n } else {\n\n panic!(\"not a boolean object\");\n\n };\n\n\n\n assert_eq!(want, got);\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 71, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn parse_operator_precedence() {\n\n let tests = vec![\n\n (\"-a * b\", \"((-a) * b)\"),\n\n (\"!-a\", \"(!(-a))\"),\n\n (\"a + b + c\", \"((a + b) + c)\"),\n\n (\"a + b - c\", \"((a + b) - c)\"),\n\n (\"a * b * c\", \"((a * b) * c)\"),\n\n (\"a * b / c\", \"((a * b) / c)\"),\n\n (\"a + b / c\", \"(a + (b / c))\"),\n\n (\"a + b * c + d / e - f\", \"(((a + (b * c)) + (d / e)) - f)\"),\n\n (\"3 + 4; -5 * 5\", \"(3 + 4)((-5) * 5)\"),\n\n (\"5 > 4 == 3 < 4\", \"((5 > 4) == (3 < 4))\"),\n\n (\"5 < 4 != 3 > 4\", \"((5 < 4) != (3 > 4))\"),\n\n (\n\n \"3 + 4 * 5 == 3 * 1 + 4 * 5\",\n\n \"((3 + (4 * 5)) == ((3 * 1) + (4 * 5)))\",\n\n ),\n\n (\"1 + 2 % 3\", \"(1 + (2 % 3))\"),\n\n (\"true\", \"true\"),\n\n (\"false\", \"false\"),\n", "file_path": "tests/parser.rs", "rank": 72, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn evaluate_string_expression() {\n\n let tests = vec![r#\"\"hello world\"\"#, r#\"\"hello\" + \" \" + \"world\"\"#];\n\n\n\n for input in tests {\n\n let got = if let object::Object::String(s) = eval(input) {\n\n s\n\n } else {\n\n panic!(\"not a string object\");\n\n };\n\n\n\n assert_eq!(\"hello world\", got);\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 73, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn parse_hash_expressions() {\n\n let tests = vec![\n\n (\n\n r#\"{\"one\": 1, \"two\": 2, \"three\": 3}\"#,\n\n r#\"{\"one\": 1, \"two\": 2, \"three\": 3}\"#,\n\n ),\n\n (\n\n r#\"{\"one\": 0 + 1, \"two\": 10 - 8, \"three\": 15 / 5}\"#,\n\n r#\"{\"one\": (0 + 1), \"two\": (10 - 8), \"three\": (15 / 5)}\"#,\n\n ),\n\n (\"{}\", \"{}\"),\n\n // Duplicate keys permitted by the parser.\n\n (\"{1: 1, 1: 1}\", \"{1: 1, 1: 1}\"),\n\n ];\n\n\n\n for (input, want) in tests {\n\n let got = format!(\"{}\", parse(input));\n\n\n\n assert_eq!(want, got);\n\n }\n\n}\n\n\n", "file_path": "tests/parser.rs", "rank": 74, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn evaluate_builtin_rest() {\n\n let tests = vec![\n\n (\n\n \"rest([1, 2, 3])\",\n\n object::Array {\n\n elements: vec![object::Object::Integer(2), object::Object::Integer(3)],\n\n },\n\n ),\n\n (\n\n r#\"rest([\"hello\", \"world\"])\"#,\n\n object::Array {\n\n elements: vec![object::Object::String(\"world\".to_string())],\n\n },\n\n ),\n\n (\n\n \"rest(rest(rest([1, 2, 3, 4])))\",\n\n object::Array {\n\n elements: vec![object::Object::Integer(4)],\n\n },\n\n ),\n", "file_path": "tests/evaluator.rs", "rank": 75, "score": 49809.681332213346 }, { "content": "// Extends a function's environment to bind its arguments.\n\nfn extend_function_env(\n\n func: &object::Function,\n\n args: &[Object],\n\n err_node: ast::Node,\n\n) -> Result<object::Environment> {\n\n if func.parameters.len() != args.len() {\n\n return Err(Error::Evaluation(\n\n err_node,\n\n format!(\n\n \"expected {} parameters to call function, but got {}\",\n\n func.parameters.len(),\n\n args.len()\n\n ),\n\n ));\n\n }\n\n\n\n let mut env = object::Environment::new_enclosed(func.env.clone());\n\n\n\n for (i, param) in func.parameters.iter().enumerate() {\n\n env.set(param.to_string(), &args[i]);\n\n }\n\n\n\n Ok(env)\n\n}\n\n\n", "file_path": "src/evaluator.rs", "rank": 76, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn parse_pointer_expressions() {\n\n let tests = vec![(\"&1\", \"(&1)\"), (\"&&1\", \"(&(&1))\"), (\"*&1\", \"(*(&1))\")];\n\n\n\n for (input, want) in tests {\n\n let got = format!(\"{}\", parse(input));\n\n\n\n assert_eq!(want, got);\n\n }\n\n}\n\n\n", "file_path": "tests/parser.rs", "rank": 77, "score": 49809.681332213346 }, { "content": "#[test]\n\nfn parse_float_literal_expression() {\n\n let prog = parse(\"0.1;\");\n\n\n\n assert_eq!(prog.statements.len(), 1);\n\n\n\n let want = 0.1;\n\n\n\n let got = if let ast::Statement::Expression(ast::Expression::Float(f)) = prog.statements[0] {\n\n f\n\n } else {\n\n panic!(\"not a float expression\");\n\n };\n\n\n\n // Direct equality comparison of floats isn't a good idea, see:\n\n // https://github.com/rust-lang/rust-clippy/issues/46.\n\n let float: f64 = got.into();\n\n assert!((want - float).abs() < std::f64::EPSILON);\n\n}\n\n\n", "file_path": "tests/parser.rs", "rank": 78, "score": 48446.07684796467 }, { "content": "#[test]\n\nfn evaluate_index_objects_errors() {\n\n let tests = vec![\"1[0]\", \"[1][true]\", r#\"1[\"hello\"]\"#, \"[0][fn(x) { x }]\"];\n\n\n\n for input in tests {\n\n let err = eval_result(input).expect_err(\"expected an error but none was found\");\n\n\n\n if let evaluator::Error::Evaluation(_, _) = err {\n\n continue;\n\n } else {\n\n panic!(\"not an evaluation error\");\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 79, "score": 48446.07684796467 }, { "content": "#[test]\n\nfn evaluate_function_application_error() {\n\n // Try to invoke add with one parameter in the body of apply.\n\n let err = eval_result(\n\n \"\n\nlet add = fn(x, y) { x + y };\n\nlet apply = fn(func, x, y) { func(x) };\n\napply(add, 2, 2);\n\n\",\n\n )\n\n .expect_err(\"expected an error but none was found\");\n\n\n\n if let evaluator::Error::Evaluation(node, _) = err {\n\n // Pinpoint the error.\n\n assert_eq!(\"func(x)\", format!(\"{}\", node));\n\n } else {\n\n panic!(\"expected evaluation error\");\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 80, "score": 48446.07684796467 }, { "content": "#[test]\n\nfn evaluate_builtin_first_errors() {\n\n let tests = vec![\"first()\", r#\"first(\"foo\", \"bar\")\"#];\n\n\n\n for input in tests {\n\n let err = eval_result(input).expect_err(\"expected an error but none was found\");\n\n\n\n if let evaluator::Error::Object(object::Error::Builtin(b, _)) = err {\n\n assert_eq!(object::Builtin::First, b);\n\n } else {\n\n panic!(\"not a built-in object error\");\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 81, "score": 48446.07684796467 }, { "content": "#[test]\n\nfn parse_prefix_boolean_expressions() {\n\n let tests = vec![\n\n (\"!true;\", token::Token::Bang, true),\n\n (\"!false;\", token::Token::Bang, false),\n\n ];\n\n\n\n for test in tests {\n\n let (input, want_op, want_bool) = test;\n\n let prog = parse(input);\n\n\n\n let got =\n\n if let ast::Statement::Expression(ast::Expression::Prefix(pre)) = &prog.statements[0] {\n\n pre\n\n } else {\n\n panic!(\"not a prefix expression\");\n\n };\n\n\n\n let got_bool = if let ast::Expression::Boolean(b) = &*got.right {\n\n b\n\n } else {\n\n panic!(\"not a boolean expression\");\n\n };\n\n\n\n assert_eq!(want_op, got.operator);\n\n assert_eq!(want_bool, *got_bool);\n\n }\n\n}\n\n\n", "file_path": "tests/parser.rs", "rank": 82, "score": 48446.07684796467 }, { "content": "#[test]\n\nfn parse_infix_boolean_expressions() {\n\n let etrue = ast::Expression::Boolean(true);\n\n let efalse = ast::Expression::Boolean(false);\n\n\n\n let tests = vec![\n\n (\"true == true\", &etrue, token::Token::Equal, &etrue),\n\n (\"true != false\", &etrue, token::Token::NotEqual, &efalse),\n\n (\"false == false\", &efalse, token::Token::Equal, &efalse),\n\n ];\n\n\n\n for (input, want_left, want_op, want_right) in tests {\n\n let prog = parse(input);\n\n\n\n let got =\n\n if let ast::Statement::Expression(ast::Expression::Infix(inf)) = &prog.statements[0] {\n\n inf\n\n } else {\n\n panic!(\"not an infix expression\");\n\n };\n\n\n\n assert_eq!(*want_left, *got.left);\n\n assert_eq!(want_op, got.operator);\n\n assert_eq!(*want_right, *got.right);\n\n }\n\n}\n\n\n", "file_path": "tests/parser.rs", "rank": 83, "score": 48446.07684796467 }, { "content": "#[test]\n\nfn evaluate_builtin_last_errors() {\n\n let tests = vec![\"last()\", r#\"last(\"foo\", \"bar\")\"#];\n\n\n\n for input in tests {\n\n let err = eval_result(input).expect_err(\"expected an error but none was found\");\n\n\n\n if let evaluator::Error::Object(object::Error::Builtin(b, _)) = err {\n\n assert_eq!(object::Builtin::Last, b);\n\n } else {\n\n panic!(\"not a built-in object error\");\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 84, "score": 48446.07684796467 }, { "content": "#[test]\n\nfn evaluate_builtin_len_errors() {\n\n let tests = vec![r#\"len()\"#, r#\"len(1)\"#, r#\"len(\"foo\", \"bar\")\"#];\n\n\n\n for input in tests {\n\n let err = eval_result(input).expect_err(\"expected an error but none was found\");\n\n\n\n if let evaluator::Error::Object(object::Error::Builtin(b, _)) = err {\n\n assert_eq!(object::Builtin::Len, b);\n\n } else {\n\n panic!(\"not a built-in object error\");\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 85, "score": 48446.07684796467 }, { "content": "#[test]\n\nfn evaluate_builtin_push_errors() {\n\n let tests = vec![\"push()\", \"push(1)\", r#\"push(\"foo\", \"bar\")\"#];\n\n\n\n for input in tests {\n\n let err = eval_result(input).expect_err(\"expected an error but none was found\");\n\n\n\n if let evaluator::Error::Object(object::Error::Builtin(b, _)) = err {\n\n assert_eq!(object::Builtin::Push, b);\n\n } else {\n\n panic!(\"not a built-in object error\");\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 86, "score": 48446.07684796467 }, { "content": "#[test]\n\nfn evaluate_array_index_objects() {\n\n let tests = vec![\n\n (\"[1, 2, 3][0]\", object::Object::Integer(1)),\n\n (\"[1, 2, 3][-1]\", object::Object::Null),\n\n (\"[2, 4, 6][4 - 4 * 1 + 2]\", object::Object::Integer(6)),\n\n (\n\n r#\"[\"hello\", \"world\", fn(x) { x }][2](1)\"#,\n\n object::Object::Integer(1),\n\n ),\n\n ];\n\n\n\n for (input, want) in tests {\n\n let got = eval(input);\n\n match got {\n\n object::Object::Integer(_) | object::Object::Null => {}\n\n _ => panic!(\"unexpected result object\"),\n\n };\n\n\n\n assert_eq!(want, got);\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 87, "score": 48446.07684796467 }, { "content": "#[test]\n\nfn code_make_parse_ok() {\n\n let tests = vec![\n\n (\n\n Opcode::Control(ControlOpcode::Constant),\n\n vec![65534],\n\n vec![ControlOpcode::Constant as u8, 0xff, 0xfe],\n\n ),\n\n (\n\n Opcode::Control(ControlOpcode::Pop),\n\n vec![],\n\n vec![ControlOpcode::Pop as u8],\n\n ),\n\n (\n\n Opcode::Control(ControlOpcode::True),\n\n vec![],\n\n vec![ControlOpcode::True as u8],\n\n ),\n\n (\n\n Opcode::Control(ControlOpcode::False),\n\n vec![],\n", "file_path": "tests/code.rs", "rank": 88, "score": 48446.07684796467 }, { "content": "#[test]\n\nfn evaluate_builtin_rest_errors() {\n\n let tests = vec![\"rest()\", r#\"rest(\"foo\", \"bar\")\"#];\n\n\n\n for input in tests {\n\n let err = eval_result(input).expect_err(\"expected an error but none was found\");\n\n\n\n if let evaluator::Error::Object(object::Error::Builtin(b, _)) = err {\n\n assert_eq!(object::Builtin::Rest, b);\n\n } else {\n\n panic!(\"not a built-in object error\");\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 89, "score": 48446.07684796467 }, { "content": "#[test]\n\nfn evaluate_hash_index_objects() {\n\n let tests = vec![\n\n (r#\"{\"foo\": 1}[\"bar\"]\"#, object::Object::Null),\n\n (r#\"{\"foo\": 1, \"bar\": 0}[\"foo\"]\"#, object::Object::Integer(1)),\n\n (r#\"{false: 1, true: 0}[false]\"#, object::Object::Integer(1)),\n\n (r#\"{10: 1, 1: 0}[10]\"#, object::Object::Integer(1)),\n\n (\n\n r#\"{1: 1, 0: 0}[fn(x) { x }(1)]\"#,\n\n object::Object::Integer(1),\n\n ),\n\n ];\n\n\n\n for (input, want) in tests {\n\n assert_eq!(want, eval(input));\n\n }\n\n}\n\n\n", "file_path": "tests/evaluator.rs", "rank": 90, "score": 48446.07684796467 }, { "content": "#[test]\n\nfn code_instructions_parse_io_unexpected_eof_error() {\n\n let tests = vec![vec![0x00, 0xff], vec![0x00, 0x00, 0x00, 0x00]];\n\n\n\n for tt in &tests {\n\n let err = Instructions::parse(tt).expect_err(\"parse did not return an error\");\n\n\n\n if let Error::Io(err) = err {\n\n assert_eq!(io::ErrorKind::UnexpectedEof, err.kind());\n\n } else {\n\n panic!(\"not an I/O error {:?}\", err);\n\n };\n\n }\n\n}\n", "file_path": "tests/code.rs", "rank": 91, "score": 45034.05434796756 }, { "content": "/// Determines if an object is truthy in Monkey.\n\nfn is_truthy(obj: &Object) -> bool {\n\n !matches!(obj, Object::Boolean(false) | Object::Null)\n\n}\n\n\n\n/// A Result type specialized use with for an Error.\n\npub type Result<T> = result::Result<T, Error>;\n\n\n\n/// Specifies the different classes of errors which may occur.\n\n#[derive(Debug, PartialEq)]\n\npub enum Error {\n\n Evaluation(ast::Node, String),\n\n Object(object::Error),\n\n UnknownIdentifier(String),\n\n}\n\n\n\nimpl fmt::Display for Error {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match self {\n\n Error::Evaluation(node, err) => write!(f, \"evaluating node {}: {}\", node, err),\n\n Error::Object(err) => err.fmt(f),\n", "file_path": "src/evaluator.rs", "rank": 92, "score": 41341.03546754183 }, { "content": "/// Look up the `Definition` for a given `Opcode`.\n\nfn lookup<'a>(op: Opcode) -> Definition<'a> {\n\n match op {\n\n Opcode::Control(c) => match c {\n\n ControlOpcode::Constant => Definition {\n\n name: \"Constant\",\n\n operand_widths: vec![Width::Two],\n\n },\n\n ControlOpcode::Pop => Definition {\n\n name: \"Pop\",\n\n operand_widths: vec![],\n\n },\n\n ControlOpcode::True => Definition {\n\n name: \"True\",\n\n operand_widths: vec![],\n\n },\n\n ControlOpcode::False => Definition {\n\n name: \"False\",\n\n operand_widths: vec![],\n\n },\n\n ControlOpcode::JumpNotTrue => Definition {\n", "file_path": "src/code.rs", "rank": 93, "score": 38781.30982804639 }, { "content": "fn builtin_len(args: &[Object]) -> Result<Object> {\n\n if args.len() != 1 {\n\n return Err(Error::Builtin(\n\n Builtin::Len,\n\n format!(\"expected 1 argument, but got {}\", args.len()),\n\n ));\n\n }\n\n\n\n match &args[0] {\n\n Object::Array(a) => Ok(Object::Integer(a.elements.len() as i64)),\n\n Object::String(s) => Ok(Object::Integer(s.len() as i64)),\n\n _ => Err(Error::Builtin(\n\n Builtin::Len,\n\n format!(\"argument {} cannot be used\", &args[0]),\n\n )),\n\n }\n\n}\n\n\n", "file_path": "src/object.rs", "rank": 94, "score": 37558.49498628285 }, { "content": "fn builtin_last(args: &[Object]) -> Result<Object> {\n\n if args.len() != 1 {\n\n return Err(Error::Builtin(\n\n Builtin::Last,\n\n format!(\"expected 1 argument, but got {}\", args.len()),\n\n ));\n\n }\n\n\n\n if let Object::Array(a) = &args[0] {\n\n if !a.elements.is_empty() {\n\n Ok(a.elements.last().unwrap().clone())\n\n } else {\n\n Ok(Object::Null)\n\n }\n\n } else {\n\n Err(Error::Builtin(\n\n Builtin::Last,\n\n format!(\"argument {} is not an array\", &args[0]),\n\n ))\n\n }\n\n}\n\n\n", "file_path": "src/object.rs", "rank": 95, "score": 37558.49498628285 }, { "content": "fn builtin_puts(args: &[Object]) -> Result<Object> {\n\n for a in args {\n\n println!(\"{}\", a);\n\n }\n\n Ok(Object::Null)\n\n}\n\n\n", "file_path": "src/object.rs", "rank": 96, "score": 37558.49498628285 }, { "content": "fn builtin_rest(args: &[Object]) -> Result<Object> {\n\n if args.len() != 1 {\n\n return Err(Error::Builtin(\n\n Builtin::Rest,\n\n format!(\"expected 1 argument, but got {}\", args.len()),\n\n ));\n\n }\n\n\n\n if let Object::Array(a) = &args[0] {\n\n if !a.elements.is_empty() {\n\n Ok(Object::Array(Array {\n\n elements: a.elements.iter().skip(1).cloned().collect(),\n\n }))\n\n } else {\n\n Ok(Object::Null)\n\n }\n\n } else {\n\n Err(Error::Builtin(\n\n Builtin::Rest,\n\n format!(\"argument {} is not an array\", &args[0]),\n", "file_path": "src/object.rs", "rank": 97, "score": 37558.49498628285 }, { "content": "fn builtin_push(args: &[Object]) -> Result<Object> {\n\n if args.len() != 2 {\n\n return Err(Error::Builtin(\n\n Builtin::Push,\n\n format!(\"expected 2 argument, but got {}\", args.len()),\n\n ));\n\n }\n\n\n\n let arr = if let Object::Array(a) = &args[0] {\n\n a\n\n } else {\n\n return Err(Error::Builtin(\n\n Builtin::Push,\n\n format!(\"first argument {} is not an array\", &args[0]),\n\n ));\n\n };\n\n\n\n let mut out = arr.elements.clone();\n\n out.push(args[1].clone());\n\n\n\n Ok(Object::Array(Array { elements: out }))\n\n}\n\n\n", "file_path": "src/object.rs", "rank": 98, "score": 37558.49498628285 }, { "content": "fn builtin_first(args: &[Object]) -> Result<Object> {\n\n if args.len() != 1 {\n\n return Err(Error::Builtin(\n\n Builtin::First,\n\n format!(\"expected 1 argument, but got {}\", args.len()),\n\n ));\n\n }\n\n\n\n if let Object::Array(a) = &args[0] {\n\n if !a.elements.is_empty() {\n\n Ok(a.elements.first().unwrap().clone())\n\n } else {\n\n Ok(Object::Null)\n\n }\n\n } else {\n\n Err(Error::Builtin(\n\n Builtin::First,\n\n format!(\"argument {} is not an array\", &args[0]),\n\n ))\n\n }\n\n}\n\n\n", "file_path": "src/object.rs", "rank": 99, "score": 37558.49498628285 } ]
Rust
runner/src/main.rs
Riey/gm-benchmark
afcabdebb82bdee9ab7fed69d46b3974ef44bff4
use ansi_term::Color; use anyhow::Context; use serde::{Deserialize, Serialize}; use std::fmt; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::time::{Duration, Instant}; use structopt::StructOpt; pub fn unknown_impl<T>(implementation: &str) -> anyhow::Result<T> { Err(anyhow::anyhow!( "Unknown implementation: {}", implementation )) } #[derive(Serialize, Deserialize, Clone, Copy)] pub enum LangType { Cpp, JavaScript, Python, Rust, } impl LangType { pub fn compile( self, opt: &Opt, program_path: &Path, implementation: &str, ) -> anyhow::Result<()> { let command = match self { LangType::Rust => match implementation { "rustc" => Some( Command::new("rustc") .current_dir(&opt.build_output) .stderr(Stdio::inherit()) .arg("-Ctarget-cpu=native") .arg("-Copt-level=2") .arg(program_path) .spawn()?, ), other => return unknown_impl(other), }, LangType::Cpp => match implementation { "g++" | "clang++" => Some( Command::new(implementation) .current_dir(&opt.build_output) .stderr(Stdio::inherit()) .arg("-o") .arg(program_path.file_stem().unwrap()) .arg("-march=native") .arg("-O3") .arg(program_path) .spawn()?, ), other => return unknown_impl(other), }, LangType::JavaScript | LangType::Python => None, }; if let Some(mut command) = command { let status = command .wait() .with_context(|| format!("Failed to compile with {}", implementation))?; assert!(status.success(), "Compile process failed!"); } Ok(()) } pub fn bench_command( self, opt: &Opt, program_path: &Path, implementation: &str, ) -> anyhow::Result<Command> { match self { LangType::JavaScript => { let mut com = Command::new(match implementation { "node" => "node", other => return unknown_impl(other), }); com.arg(program_path); Ok(com) } LangType::Python => { let mut com = Command::new(match implementation { "pypy" => "pypy", "python" => "python", other => return unknown_impl(other), }); com.arg(program_path); Ok(com) } LangType::Cpp | LangType::Rust => Ok(Command::new( opt.build_output.join(program_path.file_stem().unwrap()), )), } } } impl fmt::Display for LangType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { LangType::JavaScript => write!(f, "{}", Color::Yellow.paint("JavaScript")), LangType::Python => write!(f, "{}", Color::Blue.paint("Python")), LangType::Cpp => write!(f, "{}", Color::Cyan.paint("C++")), LangType::Rust => write!(f, "{}", Color::Red.paint("Rust")), } } } #[derive(Serialize, Deserialize)] pub struct Program { lang: LangType, #[serde(rename = "impl")] implementations: Vec<String>, idiomatic: bool, path: String, } impl Program { pub fn bench( &self, opt: &Opt, args: &[String], stdin_content: &[u8], expect_stdout: &[u8], ) -> anyhow::Result<()> { let program_path = opt.target.join(&self.path); for implementation in &self.implementations { let impl_color = Color::Purple.paint(implementation); println!("Start compile {} with {}", self.lang, impl_color); let compile_start = Instant::now(); self.lang .compile(opt, &program_path, implementation) .with_context(|| format!("Compile failed with {}", implementation))?; println!( "Compile with {} complete! elapsed: {}s", impl_color, Color::Yellow.paint(compile_start.elapsed().as_secs_f64().to_string()) ); let mut sum = Duration::new(0, 0); for i in 0..opt.bench_iter_count { let mut command = self .lang .bench_command(opt, &program_path, implementation)?; command .current_dir(&opt.build_output) .args(args) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::inherit()); let start = Instant::now(); let mut bench_process = command .spawn() .with_context(|| format!("Benchmark command failed with {}", implementation))?; bench_process .stdin .as_mut() .unwrap() .write_all(stdin_content)?; let output = bench_process.wait_with_output()?; let elapsed = start.elapsed(); assert!(output.status.success()); if i % 5 == 0 { println!( "Benchmark {}[{}] {}/{} elapsed: {}s", self.lang, impl_color, i, opt.bench_iter_count, Color::Yellow.paint(elapsed.as_secs_f64().to_string()) ); } sum += elapsed; assert_eq!(expect_stdout, output.stdout.as_slice()); } let average = sum / opt.bench_iter_count; println!( "Benchmark {}[{}] done! average: {}s", self.lang, impl_color, Color::Yellow.paint(average.as_secs_f64().to_string()), ); } Ok(()) } } #[derive(Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] enum ProgramStdinType { File, Text, } impl ProgramStdinType { pub fn get_bytes(&self, target_path: &Path, content: &str) -> anyhow::Result<Vec<u8>> { match self { ProgramStdinType::File => Ok(fs::read(Path::new(target_path).join(content))?), ProgramStdinType::Text => Ok(content.as_bytes().to_vec()), } } } #[derive(Serialize, Deserialize)] pub struct ProgramStdin { #[serde(rename = "type")] ty: ProgramStdinType, content: String, } impl ProgramStdin { pub fn get_bytes(&self, path: &Path) -> anyhow::Result<Vec<u8>> { self.ty.get_bytes(path, &self.content) } } #[derive(Serialize, Deserialize)] pub struct Bench { name: String, args: Vec<String>, stdin: Option<ProgramStdin>, stdout: String, programs: Vec<Program>, } impl Bench { pub fn bench(&self, opt: &Opt) -> anyhow::Result<()> { let bench_name = Color::Cyan.paint(&self.name); println!("Start {}...", bench_name); let stdin_content: Vec<u8> = self .stdin .as_ref() .map(|stdin| stdin.get_bytes(&opt.target)) .transpose()? .unwrap_or_default(); let args: Vec<String> = self .args .iter() .map(|arg| match arg.as_str() { "$CONTENT_LENGTH$" => stdin_content.len().to_string(), arg => arg.to_string(), }) .collect(); for program in self.programs.iter() { program.bench(opt, &args, &stdin_content, self.stdout.as_bytes())?; } Ok(()) } } #[derive(StructOpt)] #[structopt(name = "gm_benchmark_runner", about = "Benchmark Runner")] pub struct Opt { #[structopt(short = "b", about = "Path for store build output")] build_output: PathBuf, #[structopt(short = "t", about = "Path where bench.yml exists")] target: PathBuf, #[structopt(short = "c", about = "How many bench iterate", default_value = "10")] bench_iter_count: u32, } fn main() -> anyhow::Result<()> { let opt = Opt::from_args(); if !opt.build_output.exists() { std::fs::create_dir_all(&opt.build_output)?; } let bench: Bench = serde_yaml::from_reader(fs::File::open(opt.target.join("bench.yml"))?)?; bench .bench(&opt) .with_context(|| format!("Failed to benchmark {}", bench.name)) }
use ansi_term::Color; use anyhow::Context; use serde::{Deserialize, Serialize}; use std::fmt; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::time::{Duration, Instant}; use structopt::StructOpt; pub fn unknown_impl<T>(implementation: &str) -> anyhow::Result<T> { Err(anyhow::anyhow!( "Unknown implementation: {}", implementation )) } #[derive(Serialize, Deserialize, Clone, Copy)] pub enum LangType { Cpp, JavaScript, Python, Rust, } impl LangType { pub fn compile( self, opt: &Opt, program_path: &Path, implementation: &str, ) -> anyhow::Result<()> { let command = match self { LangType::Rust => match implementation { "rustc" =>
, other => return unknown_impl(other), }, LangType::Cpp => match implementation { "g++" | "clang++" => Some( Command::new(implementation) .current_dir(&opt.build_output) .stderr(Stdio::inherit()) .arg("-o") .arg(program_path.file_stem().unwrap()) .arg("-march=native") .arg("-O3") .arg(program_path) .spawn()?, ), other => return unknown_impl(other), }, LangType::JavaScript | LangType::Python => None, }; if let Some(mut command) = command { let status = command .wait() .with_context(|| format!("Failed to compile with {}", implementation))?; assert!(status.success(), "Compile process failed!"); } Ok(()) } pub fn bench_command( self, opt: &Opt, program_path: &Path, implementation: &str, ) -> anyhow::Result<Command> { match self { LangType::JavaScript => { let mut com = Command::new(match implementation { "node" => "node", other => return unknown_impl(other), }); com.arg(program_path); Ok(com) } LangType::Python => { let mut com = Command::new(match implementation { "pypy" => "pypy", "python" => "python", other => return unknown_impl(other), }); com.arg(program_path); Ok(com) } LangType::Cpp | LangType::Rust => Ok(Command::new( opt.build_output.join(program_path.file_stem().unwrap()), )), } } } impl fmt::Display for LangType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { LangType::JavaScript => write!(f, "{}", Color::Yellow.paint("JavaScript")), LangType::Python => write!(f, "{}", Color::Blue.paint("Python")), LangType::Cpp => write!(f, "{}", Color::Cyan.paint("C++")), LangType::Rust => write!(f, "{}", Color::Red.paint("Rust")), } } } #[derive(Serialize, Deserialize)] pub struct Program { lang: LangType, #[serde(rename = "impl")] implementations: Vec<String>, idiomatic: bool, path: String, } impl Program { pub fn bench( &self, opt: &Opt, args: &[String], stdin_content: &[u8], expect_stdout: &[u8], ) -> anyhow::Result<()> { let program_path = opt.target.join(&self.path); for implementation in &self.implementations { let impl_color = Color::Purple.paint(implementation); println!("Start compile {} with {}", self.lang, impl_color); let compile_start = Instant::now(); self.lang .compile(opt, &program_path, implementation) .with_context(|| format!("Compile failed with {}", implementation))?; println!( "Compile with {} complete! elapsed: {}s", impl_color, Color::Yellow.paint(compile_start.elapsed().as_secs_f64().to_string()) ); let mut sum = Duration::new(0, 0); for i in 0..opt.bench_iter_count { let mut command = self .lang .bench_command(opt, &program_path, implementation)?; command .current_dir(&opt.build_output) .args(args) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::inherit()); let start = Instant::now(); let mut bench_process = command .spawn() .with_context(|| format!("Benchmark command failed with {}", implementation))?; bench_process .stdin .as_mut() .unwrap() .write_all(stdin_content)?; let output = bench_process.wait_with_output()?; let elapsed = start.elapsed(); assert!(output.status.success()); if i % 5 == 0 { println!( "Benchmark {}[{}] {}/{} elapsed: {}s", self.lang, impl_color, i, opt.bench_iter_count, Color::Yellow.paint(elapsed.as_secs_f64().to_string()) ); } sum += elapsed; assert_eq!(expect_stdout, output.stdout.as_slice()); } let average = sum / opt.bench_iter_count; println!( "Benchmark {}[{}] done! average: {}s", self.lang, impl_color, Color::Yellow.paint(average.as_secs_f64().to_string()), ); } Ok(()) } } #[derive(Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] enum ProgramStdinType { File, Text, } impl ProgramStdinType { pub fn get_bytes(&self, target_path: &Path, content: &str) -> anyhow::Result<Vec<u8>> { match self { ProgramStdinType::File => Ok(fs::read(Path::new(target_path).join(content))?), ProgramStdinType::Text => Ok(content.as_bytes().to_vec()), } } } #[derive(Serialize, Deserialize)] pub struct ProgramStdin { #[serde(rename = "type")] ty: ProgramStdinType, content: String, } impl ProgramStdin { pub fn get_bytes(&self, path: &Path) -> anyhow::Result<Vec<u8>> { self.ty.get_bytes(path, &self.content) } } #[derive(Serialize, Deserialize)] pub struct Bench { name: String, args: Vec<String>, stdin: Option<ProgramStdin>, stdout: String, programs: Vec<Program>, } impl Bench { pub fn bench(&self, opt: &Opt) -> anyhow::Result<()> { let bench_name = Color::Cyan.paint(&self.name); println!("Start {}...", bench_name); let stdin_content: Vec<u8> = self .stdin .as_ref() .map(|stdin| stdin.get_bytes(&opt.target)) .transpose()? .unwrap_or_default(); let args: Vec<String> = self .args .iter() .map(|arg| match arg.as_str() { "$CONTENT_LENGTH$" => stdin_content.len().to_string(), arg => arg.to_string(), }) .collect(); for program in self.programs.iter() { program.bench(opt, &args, &stdin_content, self.stdout.as_bytes())?; } Ok(()) } } #[derive(StructOpt)] #[structopt(name = "gm_benchmark_runner", about = "Benchmark Runner")] pub struct Opt { #[structopt(short = "b", about = "Path for store build output")] build_output: PathBuf, #[structopt(short = "t", about = "Path where bench.yml exists")] target: PathBuf, #[structopt(short = "c", about = "How many bench iterate", default_value = "10")] bench_iter_count: u32, } fn main() -> anyhow::Result<()> { let opt = Opt::from_args(); if !opt.build_output.exists() { std::fs::create_dir_all(&opt.build_output)?; } let bench: Bench = serde_yaml::from_reader(fs::File::open(opt.target.join("bench.yml"))?)?; bench .bench(&opt) .with_context(|| format!("Failed to benchmark {}", bench.name)) }
Some( Command::new("rustc") .current_dir(&opt.build_output) .stderr(Stdio::inherit()) .arg("-Ctarget-cpu=native") .arg("-Copt-level=2") .arg(program_path) .spawn()?, )
call_expression
[ { "content": "fn main() {\n\n let stdin = io::stdin();\n\n let stdin = stdin.lock();\n\n let mut stdin = BufReader::with_capacity(8196, stdin);\n\n let stdout = io::stdout();\n\n let stdout = stdout.lock();\n\n let mut stdout = BufWriter::with_capacity(8196, stdout);\n\n\n\n let source_length = env::args().nth(1).unwrap().parse().unwrap();\n\n let mut source = vec![0u8; source_length];\n\n stdin.read(&mut source).unwrap();\n\n\n\n let mut program = Program::new(&source, &mut stdin, &mut stdout);\n\n\n\n program.run();\n\n}\n", "file_path": "brainfuck/bf.rs", "rank": 1, "score": 31927.05060191453 }, { "content": "# gm-benchmark\n\n\n\n## Requirements\n\n\n\n* Unix-like OS\n\n* gcc, pypy, python, nodejs, cargo, rustc\n\n\n\n## Results\n\n\n\n```\n\ngm-benchmark on  master\n\n❯ ./bench.sh\n\n Compiling gm-benchmark-runner v0.1.0 (/home/riey/repos/gm-benchmark/runner)\n\n Finished release [optimized] target(s) in 2.28s\n\n Running `target/release/gm-benchmark-runner -b ../build -t ../brainfuck -c 20`\n\nStart BrainFuck...\n\nStart compile C++ with g++\n\nCompile with g++ complete! elapsed: 0.468922542s\n\nBenchmark C++[g++] 0/20 elapsed: 0.064352149s\n\nBenchmark C++[g++] 5/20 elapsed: 0.063907538s\n\nBenchmark C++[g++] 10/20 elapsed: 0.063817828s\n\nBenchmark C++[g++] 15/20 elapsed: 0.063910948s\n\nBenchmark C++[g++] done! average: 0.064002978s\n\nStart compile C++ with clang++\n\nCompile with clang++ complete! elapsed: 0.586371246s\n\nBenchmark C++[clang++] 0/20 elapsed: 0.06576287s\n\nBenchmark C++[clang++] 5/20 elapsed: 0.06575673s\n\nBenchmark C++[clang++] 10/20 elapsed: 0.065752121s\n\nBenchmark C++[clang++] 15/20 elapsed: 0.06595576s\n\nBenchmark C++[clang++] done! average: 0.065668244s\n\nStart compile Rust with rustc\n\nCompile with rustc complete! elapsed: 0.396574034s\n\nBenchmark Rust[rustc] 0/20 elapsed: 0.067885692s\n\nBenchmark Rust[rustc] 5/20 elapsed: 0.067982193s\n\nBenchmark Rust[rustc] 10/20 elapsed: 0.067802252s\n\nBenchmark Rust[rustc] 15/20 elapsed: 0.067944223s\n\nBenchmark Rust[rustc] done! average: 0.068089419s\n\nStart compile JavaScript with node\n\nCompile with node complete! elapsed: 0.00000005s\n\nBenchmark JavaScript[node] 0/20 elapsed: 0.892223349s\n\nBenchmark JavaScript[node] 5/20 elapsed: 0.774663456s\n\nBenchmark JavaScript[node] 10/20 elapsed: 0.756950884s\n\nBenchmark JavaScript[node] 15/20 elapsed: 0.758659316s\n\nBenchmark JavaScript[node] done! average: 0.796712597s\n\nStart compile Python with pypy\n\nCompile with pypy complete! elapsed: 0.00000007s\n\nBenchmark Python[pypy] 0/20 elapsed: 0.341406577s\n\nBenchmark Python[pypy] 5/20 elapsed: 0.337021411s\n\nBenchmark Python[pypy] 10/20 elapsed: 0.339060183s\n\nBenchmark Python[pypy] 15/20 elapsed: 0.326501988s\n\nBenchmark Python[pypy] done! average: 0.337167788s\n\n```\n", "file_path": "README.md", "rank": 13, "score": 7.188781885390611 }, { "content": " pub fn run(&mut self) {\n\n let mut pc = 0;\n\n let mut ptr = 0;\n\n let mut tape = vec![0; 8096];\n\n while let Some(byte) = self.source.get(pc).copied() {\n\n match byte {\n\n b'>' => {\n\n ptr += 1;\n\n if ptr >= tape.len() {\n\n tape.push(0);\n\n }\n\n }\n\n b'<' => {\n\n ptr -= 1;\n\n }\n\n b'+' => {\n\n tape[ptr] += 1;\n\n }\n\n b'-' => {\n\n tape[ptr] -= 1;\n", "file_path": "brainfuck/bf.rs", "rank": 15, "score": 4.426611058640756 }, { "content": "use std::env;\n\nuse std::io::{self, BufReader, BufWriter, Bytes, Read, Write};\n\nuse std::iter;\n\n\n", "file_path": "brainfuck/bf.rs", "rank": 18, "score": 2.588917400482009 }, { "content": "#include <cstdio>\n\n#include <string>\n\n#include <vector>\n\n#include <stack>\n\n#include <map>\n\n\n\n#include <unistd.h>\n\n\n\nusing namespace std;\n\n\n", "file_path": "brainfuck/bf.cc", "rank": 20, "score": 1.84167408341657 }, { "content": " b']' => {\n\n let left = stack.pop().unwrap();\n\n let right = bf_source.len();\n\n bf_source.push(*s);\n\n bracket_pc[left] = right;\n\n bracket_pc[right] = left;\n\n }\n\n _ => continue,\n\n }\n\n bf_source.push(*s);\n\n }\n\n\n\n Self {\n\n out,\n\n input: input.bytes(),\n\n source: bf_source,\n\n bracket_pc,\n\n }\n\n }\n\n\n", "file_path": "brainfuck/bf.rs", "rank": 21, "score": 1.4374088928233677 } ]
Rust
core/bin/zksync_api/src/fee_ticker/mod.rs
vikkkko/zksyncM
e7376b09429f4d261e1038876f1ee9b1b8d26fc9
use std::collections::{HashMap, HashSet}; use bigdecimal::BigDecimal; use futures::{ channel::{mpsc::Receiver, oneshot}, StreamExt, }; use num::{ rational::Ratio, traits::{Inv, Pow}, BigUint, }; use serde::{Deserialize, Serialize}; use tokio::task::JoinHandle; use zksync_config::{FeeTickerOptions, TokenPriceSource}; use zksync_storage::ConnectionPool; use zksync_types::{ Address, ChangePubKeyOp, Token, TokenId, TokenLike, TransferOp, TransferToNewOp, TxFeeTypes, WithdrawOp, }; use zksync_utils::ratio_to_big_decimal; use crate::fee_ticker::{ fee_token_validator::FeeTokenValidator, ticker_api::{ coingecko::CoinGeckoAPI, coinmarkercap::CoinMarketCapAPI, FeeTickerAPI, TickerApi, CONNECTION_TIMEOUT, }, ticker_info::{FeeTickerInfo, TickerInfo}, }; use crate::utils::token_db_cache::TokenDBCache; pub use self::fee::*; mod constants; mod fee; mod fee_token_validator; mod ticker_api; mod ticker_info; #[cfg(test)] mod tests; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct GasOperationsCost { standard_cost: HashMap<OutputFeeType, BigUint>, subsidize_cost: HashMap<OutputFeeType, BigUint>, } impl GasOperationsCost { pub fn from_constants(fast_processing_coeff: f64) -> Self { let standard_fast_withdrawal_cost = (constants::BASE_WITHDRAW_COST as f64 * fast_processing_coeff) as u32; let subsidy_fast_withdrawal_cost = (constants::SUBSIDY_WITHDRAW_COST as f64 * fast_processing_coeff) as u32; let standard_cost = vec![ ( OutputFeeType::Transfer, constants::BASE_TRANSFER_COST.into(), ), ( OutputFeeType::TransferToNew, constants::BASE_TRANSFER_TO_NEW_COST.into(), ), ( OutputFeeType::Withdraw, constants::BASE_WITHDRAW_COST.into(), ), ( OutputFeeType::FastWithdraw, standard_fast_withdrawal_cost.into(), ), ( OutputFeeType::ChangePubKey { onchain_pubkey_auth: false, }, constants::BASE_CHANGE_PUBKEY_OFFCHAIN_COST.into(), ), ( OutputFeeType::ChangePubKey { onchain_pubkey_auth: true, }, constants::BASE_CHANGE_PUBKEY_ONCHAIN_COST.into(), ), ] .into_iter() .collect::<HashMap<_, _>>(); let subsidize_cost = vec![ ( OutputFeeType::Transfer, constants::SUBSIDY_TRANSFER_COST.into(), ), ( OutputFeeType::TransferToNew, constants::SUBSIDY_TRANSFER_TO_NEW_COST.into(), ), ( OutputFeeType::Withdraw, constants::SUBSIDY_WITHDRAW_COST.into(), ), ( OutputFeeType::FastWithdraw, subsidy_fast_withdrawal_cost.into(), ), ( OutputFeeType::ChangePubKey { onchain_pubkey_auth: false, }, constants::SUBSIDY_CHANGE_PUBKEY_OFFCHAIN_COST.into(), ), ( OutputFeeType::ChangePubKey { onchain_pubkey_auth: true, }, constants::BASE_CHANGE_PUBKEY_ONCHAIN_COST.into(), ), ] .into_iter() .collect::<HashMap<_, _>>(); Self { standard_cost, subsidize_cost, } } } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct TickerConfig { zkp_cost_chunk_usd: Ratio<BigUint>, gas_cost_tx: GasOperationsCost, tokens_risk_factors: HashMap<TokenId, Ratio<BigUint>>, not_subsidized_tokens: HashSet<Address>, } #[derive(Debug, PartialEq, Eq)] pub enum TokenPriceRequestType { USDForOneWei, USDForOneToken, } #[derive(Debug)] pub enum TickerRequest { GetTxFee { tx_type: TxFeeTypes, address: Address, token: TokenLike, response: oneshot::Sender<Result<Fee, anyhow::Error>>, }, GetTokenPrice { token: TokenLike, response: oneshot::Sender<Result<BigDecimal, anyhow::Error>>, req_type: TokenPriceRequestType, }, IsTokenAllowed { token: TokenLike, response: oneshot::Sender<Result<bool, anyhow::Error>>, }, } struct FeeTicker<API, INFO> { api: API, info: INFO, requests: Receiver<TickerRequest>, config: TickerConfig, validator: FeeTokenValidator, } #[must_use] pub fn run_ticker_task( db_pool: ConnectionPool, tricker_requests: Receiver<TickerRequest>, ) -> JoinHandle<()> { let config = FeeTickerOptions::from_env(); let ticker_config = TickerConfig { zkp_cost_chunk_usd: Ratio::from_integer(BigUint::from(10u32).pow(3u32)).inv(), gas_cost_tx: GasOperationsCost::from_constants(config.fast_processing_coeff), tokens_risk_factors: HashMap::new(), not_subsidized_tokens: config.not_subsidized_tokens, }; let cache = TokenDBCache::new(db_pool.clone()); let validator = FeeTokenValidator::new(cache, config.disabled_tokens); let client = reqwest::ClientBuilder::new() .timeout(CONNECTION_TIMEOUT) .connect_timeout(CONNECTION_TIMEOUT) .build() .expect("Failed to build reqwest::Client"); match config.token_price_source { TokenPriceSource::CoinMarketCap { base_url } => { let token_price_api = CoinMarketCapAPI::new(client, base_url); let ticker_api = TickerApi::new(db_pool.clone(), token_price_api); let ticker_info = TickerInfo::new(db_pool); let fee_ticker = FeeTicker::new( ticker_api, ticker_info, tricker_requests, ticker_config, validator, ); tokio::spawn(fee_ticker.run()) } TokenPriceSource::CoinGecko { base_url } => { let token_price_api = CoinGeckoAPI::new(client, base_url).expect("failed to init CoinGecko client"); let ticker_api = TickerApi::new(db_pool.clone(), token_price_api); let ticker_info = TickerInfo::new(db_pool); let fee_ticker = FeeTicker::new( ticker_api, ticker_info, tricker_requests, ticker_config, validator, ); tokio::spawn(fee_ticker.run()) } } } impl<API: FeeTickerAPI, INFO: FeeTickerInfo> FeeTicker<API, INFO> { fn new( api: API, info: INFO, requests: Receiver<TickerRequest>, config: TickerConfig, validator: FeeTokenValidator, ) -> Self { Self { api, info, requests, config, validator, } } async fn run(mut self) { while let Some(request) = self.requests.next().await { match request { TickerRequest::GetTxFee { tx_type, token, response, address, } => { let fee = self .get_fee_from_ticker_in_wei(tx_type, token, address) .await; response.send(fee).unwrap_or_default(); } TickerRequest::GetTokenPrice { token, response, req_type, } => { let price = self.get_token_price(token, req_type).await; response.send(price).unwrap_or_default(); } TickerRequest::IsTokenAllowed { token, response } => { let allowed = self.validator.token_allowed(token).await; response.send(allowed).unwrap_or_default(); } } } } async fn get_token_price( &self, token: TokenLike, request_type: TokenPriceRequestType, ) -> Result<BigDecimal, anyhow::Error> { let factor = match request_type { TokenPriceRequestType::USDForOneWei => { let token_decimals = self.api.get_token(token.clone()).await?.decimals; BigUint::from(10u32).pow(u32::from(token_decimals)) } TokenPriceRequestType::USDForOneToken => BigUint::from(1u32), }; self.api .get_last_quote(token) .await .map(|price| ratio_to_big_decimal(&(price.usd_price / factor), 100)) } async fn is_account_new(&mut self, address: Address) -> bool { self.info.is_account_new(address).await } async fn is_token_subsidized(&mut self, token: Token) -> bool { !self.config.not_subsidized_tokens.contains(&token.address) } async fn get_fee_from_ticker_in_wei( &mut self, tx_type: TxFeeTypes, token: TokenLike, recipient: Address, ) -> Result<Fee, anyhow::Error> { let zkp_cost_chunk = self.config.zkp_cost_chunk_usd.clone(); let token = self.api.get_token(token).await?; let token_risk_factor = self .config .tokens_risk_factors .get(&token.id) .cloned() .unwrap_or_else(|| Ratio::from_integer(1u32.into())); let (fee_type, op_chunks) = match tx_type { TxFeeTypes::Withdraw => (OutputFeeType::Withdraw, WithdrawOp::CHUNKS), TxFeeTypes::FastWithdraw => (OutputFeeType::FastWithdraw, WithdrawOp::CHUNKS), TxFeeTypes::Transfer => { if self.is_account_new(recipient).await { (OutputFeeType::TransferToNew, TransferToNewOp::CHUNKS) } else { (OutputFeeType::Transfer, TransferOp::CHUNKS) } } TxFeeTypes::ChangePubKey { onchain_pubkey_auth, } => ( OutputFeeType::ChangePubKey { onchain_pubkey_auth, }, ChangePubKeyOp::CHUNKS, ), }; let op_chunks = BigUint::from(op_chunks); let gas_tx_amount = { let is_token_subsidized = self.is_token_subsidized(token.clone()).await; if is_token_subsidized { self.config .gas_cost_tx .subsidize_cost .get(&fee_type) .cloned() .unwrap() } else { self.config .gas_cost_tx .standard_cost .get(&fee_type) .cloned() .unwrap() } }; let gas_price_wei = self.api.get_gas_price_wei().await?; let wei_price_usd = self.api.get_last_quote(TokenLike::Id(0)).await?.usd_price / BigUint::from(10u32).pow(18u32); let token_price_usd = self .api .get_last_quote(TokenLike::Id(token.id)) .await? .usd_price / BigUint::from(10u32).pow(u32::from(token.decimals)) * BigUint::from(10000u32); let zkp_fee = (zkp_cost_chunk * op_chunks) * token_risk_factor.clone() / token_price_usd.clone() * BigUint::from(0u32); let gas_fee = (wei_price_usd * gas_tx_amount.clone() * gas_price_wei.clone()) * token_risk_factor / token_price_usd * BigUint::from(0u32); Ok(Fee::new( fee_type, zkp_fee, gas_fee, gas_tx_amount, gas_price_wei, )) } }
use std::collections::{HashMap, HashSet}; use bigdecimal::BigDecimal; use futures::{ channel::{mpsc::Receiver, oneshot}, StreamExt, }; use num::{ rational::Ratio, traits::{Inv, Pow}, BigUint, }; use serde::{Deserialize, Serialize}; use tokio::task::JoinHandle; use zksync_config::{FeeTickerOptions, TokenPriceSource}; use zksync_storage::ConnectionPool; use zksync_types::{ Address, ChangePubKeyOp, Token, TokenId, TokenLike, TransferOp, TransferToNewOp, TxFeeTypes, WithdrawOp, }; use zksync_utils::ratio_to_big_decimal; use crate::fee_ticker::{ fee_token_validator::FeeTokenValidator, ticker_api::{ coingecko::CoinGeckoAPI, coinmarkercap::CoinMarketCapAPI, FeeTickerAPI, TickerApi, CONNECTION_TIMEOUT, }, ticker_info::{FeeTickerInfo, TickerInfo}, }; use crate::utils::token_db_cache::TokenDBCache; pub use self::fee::*; mod constants; mod fee; mod fee_token_validator; mod ticker_api; mod ticker_info; #[cfg(test)] mod tests; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct GasOperationsCost { standard_cost: HashMap<OutputFeeType, BigUint>, subsidize_cost: HashMap<OutputFeeType, BigUint>, } impl GasOperationsCost { pub fn from_constants(fast_processing_coeff: f64) -> Self { let standard_fast_withdrawal_cost = (constants::BASE_WITHDRAW_COST as f64 * fast_processing_coeff) as u32; let subsidy_fast_withdrawal_cost = (constants::SUBSIDY_WITHDRAW_COST as f64 * fast_processing_coeff) as u32; let standard_cost = vec![ ( OutputFeeType::Transfer, constants::BASE_TRANSFER_COST.into(), ), ( OutputFeeType::TransferToNew, constants::BASE_TRANSFER_TO_NEW_COST.into(), ), ( OutputFeeType::Withdraw, constants::BASE_WITHDRAW_COST.into(), ), ( OutputFeeType::FastWithdraw, standard_fast_withdrawal_cost.into(), ), ( OutputFeeType::ChangePubKey { onchain_pubkey_auth: false, }, constants::BASE_CHANGE_PUBKEY_OFFCHAIN_COST.into(), ), ( OutputFeeType::ChangePubKey { onchain_pubkey_auth: true, }, constants::BASE_CHANGE_PUBKEY_ONCHAIN_COST.into(), ), ] .into_iter() .collect::<HashMap<_, _>>(); let subsidize_cost = vec![ ( OutputFeeType::Transfer, constants::SUBSIDY_TRANSFER_COST.into(), ), ( OutputFeeType::TransferToNew, constants::SUBSIDY_TRANSFER_TO_NEW_COST.into(), ), ( OutputFeeType::Withdraw, constants::SUBSIDY_WITHDRAW_COST.into(), ), ( OutputFeeType::FastWithdraw, subsidy_fast_withdrawal_cost.into(), ), ( OutputFeeType::ChangePubKey { onchain_pubkey_auth: false, }, constants::SUBSIDY_CHANGE_PUBKEY_OFFCHAIN_COST.into(), ), ( OutputFeeType::ChangePubKey { onchain_pubkey_auth: true, }, constants::BASE_CHANGE_PUBKEY_ONCHAIN_COST.into(), ), ] .into_iter() .collect::<HashMap<_, _>>(); Self { standard_cost, subsidize_cost, } } } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct TickerConfig { zkp_cost_chunk_usd: Ratio<BigUint>, gas_cost_tx: GasOperationsCost, tokens_risk_factors: HashMap<TokenId, Ratio<BigUint>>, not_subsidized_tokens: HashSet<Address>, } #[derive(Debug, PartialEq, Eq)] pub enum TokenPriceRequestType { USDForOneWei, USDForOneToken, } #[derive(Debug)] pub enum TickerRequest { GetTxFee { tx_type: TxFeeTypes, address: Address, token: TokenLike, response: oneshot::Sender<Result<Fee, anyhow::Error>>, }, GetTokenPrice { token: TokenLike, response: oneshot::Sender<Result<BigDecimal, anyhow::Error>>, req_type: TokenPriceRequestType, }, IsTokenAllowed { token: TokenLike, response: oneshot::Sender<Result<bool, anyhow::Error>>, }, } struct FeeTicker<API, INFO> { api: API, info: INFO, requests: Receiver<TickerRequest>, config: TickerConfig, validator: FeeTokenValidator, } #[must_use] pub fn run_ticker_task( db_pool: ConnectionPool, tricker_requests: Receiver<TickerRequest>, ) -> JoinHandle<()> { let config = FeeTickerOptions::from_env(); let ticker_config = TickerConfig { zkp_cost_chunk_usd: Ratio::from_integer(BigUint::from(10u32).pow(3u32)).inv(), gas_cost_tx: GasOperationsCost::from_constants(config.fast_processing_coeff), tokens_risk_factors: HashMap::new(), not_subsidized_tokens: config.not_subsidized_tokens, }; let cache = TokenDBCache::new(db_pool.clone()); let validator = FeeTokenValidator::new(cache, config.disabled_tokens); let client = reqwest::ClientBuilder::new() .timeout(CONNECTION_TIMEOUT) .connect_timeout(CONNECTION_TIMEOUT) .build() .expect("Failed to build reqwest::Client"); match config.token_price_source { TokenPriceSource::CoinMarketCap { base_url } => { let token_price_api = CoinMarketCapAPI::new(client, base_url); let ticker_api = TickerApi::new(db_pool.clone(), token_price_api); let ticker_info = TickerInfo::new(db_pool); let fee_ticker = FeeTicker::new( ticker_api, ticker_info, tricker_requests, ticker_config, validator, ); tokio::spawn(fee_ticker.run()) } TokenPriceSource::CoinGecko { base_url } => { let token_price_api = CoinGeckoAPI::new(client, base_url).expect("failed to init CoinGecko client"); let ticker_api = TickerApi::new(db_pool.clone(), token_price_api); let ticker_info = TickerInfo::new(db_pool); let fee_ticker = FeeTicker::new( ticker_api, ticker_info, tricker_requests, ticker_config, validator, ); tokio::spawn(fee_ticker.run()) } } } impl<API: FeeTickerAPI, INFO: FeeTickerInfo> FeeTicker<API, INFO> { fn new( api: API, info: INFO, requests: Receiver<TickerRequest>, config: TickerConfig, validator: FeeTokenValidator, ) -> Self { Self { api, info, requests, config, validator, } } async fn run(mut self) { while let Some(request) = self.requests.next().await { match request { TickerRequest::GetTxFee { tx_type, token, response, address, } => { let fee = self .get_fee_from_ticker_in_wei(tx_type, token, address) .await; response.send(fee).unwrap_or_default(); } TickerRequest::GetTokenPrice { token, response, req_type, } => { let price = self.get_token_price(token, req_type).await; response.send(price).unwrap_or_default(); } TickerRequest::IsTokenAllowed { token, response } => { let allowed = self.validator.token_allowed(token).await; response.send(allowed).unwrap_or_default(); } } } } async fn get_token_price( &self, token: TokenLike, request_type: TokenPriceRequestType, ) -> Result<BigDecimal, anyhow::Error> { let factor =
; self.api .get_last_quote(token) .await .map(|price| ratio_to_big_decimal(&(price.usd_price / factor), 100)) } async fn is_account_new(&mut self, address: Address) -> bool { self.info.is_account_new(address).await } async fn is_token_subsidized(&mut self, token: Token) -> bool { !self.config.not_subsidized_tokens.contains(&token.address) } async fn get_fee_from_ticker_in_wei( &mut self, tx_type: TxFeeTypes, token: TokenLike, recipient: Address, ) -> Result<Fee, anyhow::Error> { let zkp_cost_chunk = self.config.zkp_cost_chunk_usd.clone(); let token = self.api.get_token(token).await?; let token_risk_factor = self .config .tokens_risk_factors .get(&token.id) .cloned() .unwrap_or_else(|| Ratio::from_integer(1u32.into())); let (fee_type, op_chunks) = match tx_type { TxFeeTypes::Withdraw => (OutputFeeType::Withdraw, WithdrawOp::CHUNKS), TxFeeTypes::FastWithdraw => (OutputFeeType::FastWithdraw, WithdrawOp::CHUNKS), TxFeeTypes::Transfer => { if self.is_account_new(recipient).await { (OutputFeeType::TransferToNew, TransferToNewOp::CHUNKS) } else { (OutputFeeType::Transfer, TransferOp::CHUNKS) } } TxFeeTypes::ChangePubKey { onchain_pubkey_auth, } => ( OutputFeeType::ChangePubKey { onchain_pubkey_auth, }, ChangePubKeyOp::CHUNKS, ), }; let op_chunks = BigUint::from(op_chunks); let gas_tx_amount = { let is_token_subsidized = self.is_token_subsidized(token.clone()).await; if is_token_subsidized { self.config .gas_cost_tx .subsidize_cost .get(&fee_type) .cloned() .unwrap() } else { self.config .gas_cost_tx .standard_cost .get(&fee_type) .cloned() .unwrap() } }; let gas_price_wei = self.api.get_gas_price_wei().await?; let wei_price_usd = self.api.get_last_quote(TokenLike::Id(0)).await?.usd_price / BigUint::from(10u32).pow(18u32); let token_price_usd = self .api .get_last_quote(TokenLike::Id(token.id)) .await? .usd_price / BigUint::from(10u32).pow(u32::from(token.decimals)) * BigUint::from(10000u32); let zkp_fee = (zkp_cost_chunk * op_chunks) * token_risk_factor.clone() / token_price_usd.clone() * BigUint::from(0u32); let gas_fee = (wei_price_usd * gas_tx_amount.clone() * gas_price_wei.clone()) * token_risk_factor / token_price_usd * BigUint::from(0u32); Ok(Fee::new( fee_type, zkp_fee, gas_fee, gas_tx_amount, gas_price_wei, )) } }
match request_type { TokenPriceRequestType::USDForOneWei => { let token_decimals = self.api.get_token(token.clone()).await?.decimals; BigUint::from(10u32).pow(u32::from(token_decimals)) } TokenPriceRequestType::USDForOneToken => BigUint::from(1u32), }
if_condition
[ { "content": "/// Runs the massive API spam routine.\n\n///\n\n/// This process will continue until the cancel command is occurred or the limit is reached.\n\npub fn run(monitor: Monitor) -> (ApiTestsFuture, CancellationToken) {\n\n let cancellation = CancellationToken::default();\n\n\n\n let token = cancellation.clone();\n\n let future = async move {\n\n log::info!(\"API tests starting...\");\n\n\n\n let mut builder = ApiTestsBuilder::new(token.clone());\n\n builder = sdk_tests::wire_tests(builder, &monitor);\n\n builder = rest_api_tests::wire_tests(builder, &monitor);\n\n let report = builder.run().await;\n\n\n\n log::info!(\"API tests finished\");\n\n\n\n report\n\n }\n\n .boxed();\n\n\n\n (future, cancellation)\n\n}\n", "file_path": "core/tests/loadtest/src/api/mod.rs", "rank": 0, "score": 381856.9270723658 }, { "content": "/// Initialize plasma state with one account - fee account.\n\npub fn genesis_state(fee_account_address: &Address) -> ZkSyncStateInitParams {\n\n let operator_account = Account::default_with_address(fee_account_address);\n\n let mut params = ZkSyncStateInitParams::new();\n\n params.insert_account(0, operator_account);\n\n params\n\n}\n", "file_path": "core/tests/testkit/src/lib.rs", "rank": 1, "score": 350445.82438019896 }, { "content": "/// First is vec of test acccounts, second is commit account\n\npub fn get_test_accounts() -> (Vec<ETHAccountInfo>, ETHAccountInfo) {\n\n let stdout = run_external_command(\"zk\", &[\"run\", \"test-accounts\"]);\n\n\n\n if let Ok(mut parsed) = serde_json::from_str::<Vec<ETHAccountInfo>>(&stdout) {\n\n let commit_account = parsed.remove(0);\n\n assert!(\n\n !parsed.is_empty(),\n\n \"can't use testkit without test accounts\"\n\n );\n\n return (parsed, commit_account);\n\n }\n\n\n\n panic!(\"Print test accounts script output is not parsed correctly\")\n\n}\n", "file_path": "core/tests/testkit/src/external_commands.rs", "rank": 2, "score": 320446.10878266586 }, { "content": "pub fn stored_str_address_to_address(address: &str) -> Address {\n\n assert_eq!(address.len(), 42, \"db stored token address length\");\n\n address[2..]\n\n .parse()\n\n .expect(\"failed to parse stored db address\")\n\n}\n\n\n\n#[cfg(test)]\n\npub mod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn address_store_roundtrip() {\n\n let address = Address::random();\n\n let stored_address = address_to_stored_string(&address);\n\n assert_eq!(address, stored_str_address_to_address(&stored_address));\n\n }\n\n}\n", "file_path": "core/lib/storage/src/tokens/utils.rs", "rank": 3, "score": 297136.47529265424 }, { "content": "pub fn address_to_stored_string(address: &Address) -> String {\n\n format!(\"0x{:x}\", address)\n\n}\n\n\n", "file_path": "core/lib/storage/src/tokens/utils.rs", "rank": 4, "score": 296482.3332200421 }, { "content": "/// Saves specified wallet in the file log.\n\npub fn save_wallet(info: AccountInfo) {\n\n let msg = Message::WalletCreated(info);\n\n\n\n tokio::spawn(async move {\n\n session()\n\n .sender\n\n .clone()\n\n .send(msg)\n\n .await\n\n .expect(\"Unable to save wallet\")\n\n });\n\n}\n\n\n", "file_path": "core/tests/loadtest/src/session.rs", "rank": 5, "score": 290035.9239539036 }, { "content": "/// Converts \"gwei\" amount to the \"wei\".\n\npub fn gwei_to_wei(gwei: impl Into<BigUint>) -> BigUint {\n\n gwei.into() * BigUint::from(10u64.pow(9))\n\n}\n\n\n\n/// Creates a future which represents a collection of the outputs of the futures\n\n/// given.\n\n///\n\n/// But unlike the `futures::future::join_all` method, it performs futures in chunks\n\n/// to reduce descriptors usage.\n\npub async fn wait_all_chunks<I>(chunk_sizes: &[usize], i: I) -> Vec<<I::Item as Future>::Output>\n\nwhere\n\n I: IntoIterator,\n\n I::Item: Future,\n\n{\n\n let mut output = Vec::new();\n\n for chunk in DynamicChunks::new(i, chunk_sizes) {\n\n let values = futures::future::join_all(chunk).await;\n\n output.extend(values);\n\n }\n\n output\n", "file_path": "core/tests/loadtest/src/utils.rs", "rank": 6, "score": 286200.35024393495 }, { "content": "/// Transforms the fee amount into the packed form.\n\n/// As the packed form for fee is smaller than one for the token,\n\n/// the same value must be packable as a token amount, but not packable\n\n/// as a fee amount.\n\n/// If the provided fee amount is not packable, it is rounded down to the\n\n/// closest amount that fits in packed form. As a result, some precision will be lost.\n\npub fn pack_fee_amount(amount: &BigUint) -> Vec<u8> {\n\n FloatConversions::pack(\n\n amount,\n\n params::FEE_EXPONENT_BIT_WIDTH,\n\n params::FEE_MANTISSA_BIT_WIDTH,\n\n )\n\n}\n\n\n", "file_path": "core/lib/types/src/helpers.rs", "rank": 7, "score": 283224.3551504601 }, { "content": "/// Transforms the token amount into packed form.\n\n/// If the provided token amount is not packable, it is rounded down to the\n\n/// closest amount that fits in packed form. As a result, some precision will be lost.\n\npub fn pack_token_amount(amount: &BigUint) -> Vec<u8> {\n\n FloatConversions::pack(\n\n amount,\n\n params::AMOUNT_EXPONENT_BIT_WIDTH,\n\n params::AMOUNT_MANTISSA_BIT_WIDTH,\n\n )\n\n}\n\n\n", "file_path": "core/lib/types/src/helpers.rs", "rank": 8, "score": 283107.30987859267 }, { "content": "pub fn run_upgrade_franklin(franklin_address: Address, upgrade_gatekeeper_address: Address) {\n\n run_external_command(\n\n \"zk\",\n\n &[\n\n \"run\",\n\n \"test-upgrade\",\n\n &format!(\"0x{:x}\", franklin_address),\n\n &format!(\"0x{:x}\", upgrade_gatekeeper_address),\n\n ],\n\n );\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct ETHAccountInfo {\n\n pub address: Address,\n\n pub private_key: H256,\n\n}\n\n\n", "file_path": "core/tests/testkit/src/external_commands.rs", "rank": 9, "score": 281361.54248261766 }, { "content": "pub fn resize_grow_only<T: Clone>(to_resize: &mut Vec<T>, new_size: usize, pad_with: T) {\n\n assert!(to_resize.len() <= new_size);\n\n to_resize.resize(new_size, pad_with);\n\n}\n\n\n", "file_path": "core/lib/circuit/src/utils.rs", "rank": 10, "score": 278639.9531503285 }, { "content": "#[proc_macro_attribute]\n\npub fn test(_args: TokenStream, item: TokenStream) -> TokenStream {\n\n let input = syn::parse_macro_input!(item as syn::ItemFn);\n\n\n\n for attr in &input.attrs {\n\n if attr.path.is_ident(\"test\") {\n\n let msg = \"second test attribute is supplied\";\n\n return syn::Error::new_spanned(&attr, msg)\n\n .to_compile_error()\n\n .into();\n\n }\n\n }\n\n\n\n parse_knobs(input).unwrap_or_else(|e| e.to_compile_error().into())\n\n}\n", "file_path": "core/lib/storage/db_test_macro/src/lib.rs", "rank": 11, "score": 270265.857671706 }, { "content": "pub fn reverse_bytes<T: Clone>(bits: &[T]) -> Vec<T> {\n\n bits.chunks(8)\n\n .rev()\n\n .map(|x| x.to_vec())\n\n .fold(Vec::new(), |mut acc, mut byte| {\n\n acc.append(&mut byte);\n\n acc\n\n })\n\n}\n\n\n", "file_path": "core/lib/circuit/src/utils.rs", "rank": 12, "score": 270096.8434040484 }, { "content": "/// Generates a random account with a set of changes.\n\npub fn gen_acc_random_updates<R: Rng>(rng: &mut R) -> impl Iterator<Item = (u32, AccountUpdate)> {\n\n let id: u32 = rng.gen();\n\n let balance = u128::from(rng.gen::<u64>());\n\n let nonce: u32 = rng.gen();\n\n let pub_key_hash = PubKeyHash { data: rng.gen() };\n\n let address: Address = rng.gen::<[u8; 20]>().into();\n\n\n\n let mut a = Account::default_with_address(&address);\n\n let old_nonce = nonce;\n\n a.nonce = old_nonce + 2;\n\n a.pub_key_hash = pub_key_hash;\n\n\n\n let old_balance = a.get_balance(0);\n\n a.set_balance(0, BigUint::from(balance));\n\n let new_balance = a.get_balance(0);\n\n vec![\n\n (\n\n id,\n\n AccountUpdate::Create {\n\n nonce: old_nonce,\n", "file_path": "core/lib/storage/src/test_data.rs", "rank": 13, "score": 267668.19504536863 }, { "content": "#[derive(Debug, Clone)]\n\nstruct RestApiClient {\n\n inner: reqwest::Client,\n\n url: String,\n\n pool: ApiDataPool,\n\n}\n\n\n", "file_path": "core/tests/loadtest/src/api/rest_api_tests.rs", "rank": 14, "score": 258849.5064615024 }, { "content": "/// Takes name of the config, extends it to the constant and volatile config paths,\n\n/// loads them and merged into on object.\n\nfn merge_configs(config: &str) -> serde_json::Value {\n\n let mut constant_config = load_json(&config_path(&format!(\"constant/{}\", config)));\n\n let mut volatile_config = load_json(&config_path(&format!(\"volatile/{}\", config)));\n\n\n\n constant_config\n\n .as_object_mut()\n\n .expect(\"Cannot merge not at object\")\n\n .append(volatile_config.as_object_mut().unwrap());\n\n\n\n constant_config\n\n}\n\n\n\n/// Configuration for EIP1271-compatible test smart wallet.\n\n#[derive(Debug, Deserialize)]\n\npub struct EIP1271Config {\n\n /// Private key of the account owner (to sign transactions).\n\n pub owner_private_key: H256,\n\n /// Address of the account owner (set in contract).\n\n pub owner_address: Address,\n\n /// Address of the smart wallet contract.\n", "file_path": "core/lib/config/src/test_config/mod.rs", "rank": 15, "score": 254575.94909299855 }, { "content": "/// Max token id, based on the number of processable tokens\n\npub fn max_token_id() -> TokenId {\n\n number_of_processable_tokens() as u16 - 1\n\n}\n\n\n\npub const ETH_TOKEN_ID: TokenId = 0;\n\n\n\npub const ACCOUNT_ID_BIT_WIDTH: usize = 32;\n\n\n\npub const INPUT_DATA_ADDRESS_BYTES_WIDTH: usize = 32;\n\npub const INPUT_DATA_BLOCK_NUMBER_BYTES_WIDTH: usize = 32;\n\npub const INPUT_DATA_FEE_ACC_BYTES_WIDTH_WITH_EMPTY_OFFSET: usize = 32;\n\npub const INPUT_DATA_FEE_ACC_BYTES_WIDTH: usize = 3;\n\npub const INPUT_DATA_ROOT_BYTES_WIDTH: usize = 32;\n\npub const INPUT_DATA_EMPTY_BYTES_WIDTH: usize = 64;\n\npub const INPUT_DATA_ROOT_HASH_BYTES_WIDTH: usize = 32;\n\n\n\npub const TOKEN_BIT_WIDTH: usize = 16;\n\npub const TX_TYPE_BIT_WIDTH: usize = 8;\n\n\n\n/// Account subtree hash width\n", "file_path": "core/lib/crypto/src/params.rs", "rank": 16, "score": 253001.14551724738 }, { "content": "/// Saves specified error message in the file log.\n\npub fn save_error(category: &str, reason: impl Display) {\n\n let msg = Message::ErrorOccurred {\n\n category: category.to_string(),\n\n reason: reason.to_string(),\n\n };\n\n\n\n tokio::spawn(async move {\n\n session()\n\n .sender\n\n .clone()\n\n .send(msg)\n\n .await\n\n .expect(\"Unable to save error message\")\n\n });\n\n}\n\n\n\nasync fn run_messages_writer(\n\n out_dir: PathBuf,\n\n mut receiver: Receiver<Message>,\n\n) -> anyhow::Result<()> {\n", "file_path": "core/tests/loadtest/src/session.rs", "rank": 17, "score": 252618.72025265533 }, { "content": "pub fn eth_address_to_fr(address: &Address) -> Fr {\n\n ff::from_hex(&format!(\"{:x}\", address)).unwrap()\n\n}\n", "file_path": "core/lib/crypto/src/circuit/utils.rs", "rank": 18, "score": 250951.35150764545 }, { "content": "/// Creates a fixed-seed RNG for tests.\n\npub fn create_rng() -> XorShiftRng {\n\n XorShiftRng::from_seed([0, 1, 2, 3])\n\n}\n", "file_path": "core/lib/storage/src/tests/mod.rs", "rank": 19, "score": 247936.14489860175 }, { "content": "#[test]\n\nfn test_tokens_cache() {\n\n let mut tokens: HashMap<String, Token> = HashMap::default();\n\n\n\n let token_eth = Token::new(0, H160::default(), \"ETH\", 18);\n\n tokens.insert(\"ETH\".to_string(), token_eth.clone());\n\n let token_dai = Token::new(1, H160::random(), \"DAI\", 18);\n\n tokens.insert(\"DAI\".to_string(), token_dai.clone());\n\n\n\n let uncahed_token = Token::new(2, H160::random(), \"UNC\", 5);\n\n\n\n let tokens_hash = TokensCache::new(tokens);\n\n\n\n assert_eq!(\n\n tokens_hash.resolve(token_eth.address.into()),\n\n Some(token_eth.clone())\n\n );\n\n assert_eq!(\n\n tokens_hash.resolve(token_eth.id.into()),\n\n Some(token_eth.clone())\n\n );\n", "file_path": "sdk/zksync-rs/tests/unit.rs", "rank": 20, "score": 247901.50631756644 }, { "content": "pub fn wire_tests<'a>(builder: ApiTestsBuilder<'a>, monitor: &'a Monitor) -> ApiTestsBuilder<'a> {\n\n let rest_api_url = TestConfig::load().api.rest_api_url;\n\n\n\n let client = RestApiClient::new(rest_api_url, monitor.api_data_pool.clone());\n\n declare_tests!(\n\n (builder, client) =>\n\n testnet_config,\n\n status,\n\n tokens,\n\n tx_history,\n\n tx_history_older_than,\n\n tx_history_newer_than,\n\n executed_tx_by_hash,\n\n tx_by_hash,\n\n priority_operations,\n\n block_tx,\n\n block_transactions,\n\n block_by_id,\n\n blocks,\n\n explorer_search,\n\n withdrawal_processing_time,\n\n )\n\n}\n", "file_path": "core/tests/loadtest/src/api/rest_api_tests.rs", "rank": 21, "score": 247402.8344709513 }, { "content": "#[doc(hidden)]\n\npub fn get_genesis_token_list(network: &str) -> Result<Vec<TokenGenesisListItem>, anyhow::Error> {\n\n let mut file_path = parse_env::<PathBuf>(\"ZKSYNC_HOME\");\n\n file_path.push(\"etc\");\n\n file_path.push(\"tokens\");\n\n file_path.push(network);\n\n file_path.set_extension(\"json\");\n\n Ok(serde_json::from_str(&read_to_string(file_path)?)?)\n\n}\n\n\n\n/// Token price known to the zkSync network.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct TokenPrice {\n\n #[serde(with = \"UnsignedRatioSerializeAsDecimal\")]\n\n pub usd_price: Ratio<BigUint>,\n\n pub last_updated: DateTime<Utc>,\n\n}\n\n\n\n/// Type of transaction fees that exist in the zkSync network.\n\n#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Hash, Eq)]\n\npub enum TxFeeTypes {\n", "file_path": "core/lib/types/src/tokens.rs", "rank": 22, "score": 245782.3890399822 }, { "content": "pub fn wire_tests<'a>(builder: ApiTestsBuilder<'a>, monitor: &'a Monitor) -> ApiTestsBuilder<'a> {\n\n builder\n\n .append(\"provider/tokens\", move || async move {\n\n monitor.provider.tokens().await?;\n\n Ok(())\n\n })\n\n .append(\"provider/contract_address\", move || async move {\n\n monitor.provider.contract_address().await?;\n\n Ok(())\n\n })\n\n .append(\"provider/account_info\", move || async move {\n\n monitor\n\n .provider\n\n .account_info(monitor.api_data_pool.read().await.random_address().0)\n\n .await?;\n\n Ok(())\n\n })\n\n .append(\"provider/get_tx_fee\", move || async move {\n\n monitor\n\n .provider\n", "file_path": "core/tests/loadtest/src/api/sdk_tests.rs", "rank": 23, "score": 245503.14558769242 }, { "content": "#[derive(Debug, Default)]\n\nstruct MeasureOutput {\n\n category: String,\n\n samples: Vec<Sample>,\n\n total_requests_count: usize,\n\n failed_requests_count: usize,\n\n}\n\n\n\nimpl From<MeasureOutput> for (String, ApiTestsReport) {\n\n fn from(output: MeasureOutput) -> Self {\n\n (\n\n output.category,\n\n ApiTestsReport {\n\n total_requests_count: output.total_requests_count,\n\n failed_requests_count: output.failed_requests_count,\n\n summary: FiveSummaryStats::from_samples(&output.samples),\n\n },\n\n )\n\n }\n\n}\n\n\n", "file_path": "core/tests/loadtest/src/api/mod.rs", "rank": 24, "score": 239132.8848445785 }, { "content": "/// Deserializes either a `String` or `Vec<u8>` into `Vec<u8>`.\n\n/// The reason we cannot expect just a vector is backward compatibility: messages\n\n/// used to be stored as strings.\n\npub fn deserialize_eth_message<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n struct StringOrVec;\n\n\n\n impl<'de> Visitor<'de> for StringOrVec {\n\n type Value = Vec<u8>;\n\n\n\n fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {\n\n formatter.write_str(\"a byte array or a string\")\n\n }\n\n\n\n fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>\n\n where\n\n E: Error,\n\n {\n\n Ok(v.as_bytes().to_vec())\n\n }\n\n\n", "file_path": "core/lib/types/src/tx/utils.rs", "rank": 25, "score": 235049.97421539805 }, { "content": "pub fn pack_bits_into_bytes(bits: Vec<bool>) -> Vec<u8> {\n\n let mut message_bytes: Vec<u8> = Vec::with_capacity(bits.len() / 8);\n\n let byte_chunks = bits.chunks(8);\n\n for byte_chunk in byte_chunks {\n\n let mut byte = 0u8;\n\n for (i, bit) in byte_chunk.iter().enumerate() {\n\n if *bit {\n\n byte |= 1 << i;\n\n }\n\n }\n\n message_bytes.push(byte);\n\n }\n\n message_bytes\n\n}\n\n\n", "file_path": "sdk/zksync-crypto/src/utils.rs", "rank": 26, "score": 231105.8245251186 }, { "content": "/// Transforms relative path like `constant/eip1271.json` into full path like\n\n/// `$ZKSYNC_HOME/etc/test_config/constant/eip1271.json`.\n\nfn config_path(postfix: &str) -> String {\n\n let home = std::env::var(\"ZKSYNC_HOME\").expect(\"ZKSYNC_HOME variable must be set\");\n\n\n\n format!(\"{}/etc/test_config/{}\", home, postfix)\n\n}\n\n\n", "file_path": "core/lib/config/src/test_config/mod.rs", "rank": 27, "score": 230366.89051529174 }, { "content": "pub fn str_to_address(value: &str) -> Result<Address> {\n\n let str_addr = value[\"0x\".len()..].parse().context(\"Error parse address\")?;\n\n Ok(str_addr)\n\n}\n\n\n", "file_path": "infrastructure/tok_cli/src/utils.rs", "rank": 28, "score": 229136.7074312484 }, { "content": "/// Returns the closest possible packable token amount.\n\n/// Returned amount is always less or equal to the provided amount.\n\npub fn closest_packable_fee_amount(amount: &BigUint) -> BigUint {\n\n let fee_packed = pack_fee_amount(&amount);\n\n unpack_fee_amount(&fee_packed).expect(\"fee repacking\")\n\n}\n\n\n", "file_path": "core/lib/types/src/helpers.rs", "rank": 29, "score": 227611.8344773456 }, { "content": "/// Returns the closest possible packable fee amount.\n\n/// Returned amount is always less or equal to the provided amount.\n\npub fn closest_packable_token_amount(amount: &BigUint) -> BigUint {\n\n let fee_packed = pack_token_amount(&amount);\n\n unpack_token_amount(&fee_packed).expect(\"token amount repacking\")\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use crate::TokenLike;\n\n use serde::{Deserialize, Serialize};\n\n\n\n #[test]\n\n fn test_roundtrip() {\n\n let zero = BigUint::from_u32(1).unwrap();\n\n let one = BigUint::from_u32(1).unwrap();\n\n {\n\n let round_trip_zero = unpack_token_amount(&pack_token_amount(&zero));\n\n let round_trip_one = unpack_token_amount(&pack_token_amount(&one));\n\n assert_eq!(Some(zero.clone()), round_trip_zero);\n\n assert_eq!(Some(one.clone()), round_trip_one);\n", "file_path": "core/lib/types/src/helpers.rs", "rank": 30, "score": 227502.91748172935 }, { "content": "#[test]\n\n#[ignore]\n\nfn corrupted_validator_audit_path() {\n\n // Perform some operations\n\n let mut circuit = apply_many_ops();\n\n\n\n // Corrupt merkle proof.\n\n circuit.validator_audit_path[0] = Some(Default::default());\n\n\n\n // Corrupted proof will lead to incorrect root hash.\n\n // See `circuit.rs` for details.\n\n let expected_msg = \"root before applying fees is correct\";\n\n\n\n let error = check_circuit_non_panicking(circuit)\n\n .expect_err(\"Corrupted operations list should lead to an error\");\n\n\n\n assert!(\n\n error.contains(expected_msg),\n\n \"corrupted_operations: Got error message '{}', but expected '{}'\",\n\n error,\n\n expected_msg\n\n );\n\n}\n", "file_path": "core/lib/circuit/src/witness/tests/mod.rs", "rank": 31, "score": 225659.8553316719 }, { "content": "pub fn round_precision(num: &Ratio<BigUint>, precision: usize) -> Ratio<BigUint> {\n\n let ten_pow = BigUint::from(10u32).pow(precision);\n\n let numerator = (num * &ten_pow).trunc().to_integer();\n\n Ratio::new(numerator, ten_pow)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use std::str::FromStr;\n\n\n\n #[test]\n\n fn test_ratio_to_big_decimal() {\n\n let ratio = Ratio::from_integer(BigUint::from(0u32));\n\n let dec = ratio_to_big_decimal(&ratio, 1);\n\n assert_eq!(dec.to_string(), \"0.0\");\n\n let ratio = Ratio::from_integer(BigUint::from(1234u32));\n\n let dec = ratio_to_big_decimal(&ratio, 7);\n\n assert_eq!(dec.to_string(), \"1234.0000000\");\n\n // 4 divided by 9 is 0.(4).\n", "file_path": "core/lib/utils/src/convert.rs", "rank": 32, "score": 224686.25516293186 }, { "content": "/// Converts `BigUint` value into the corresponding `U256` value.\n\npub fn biguint_to_u256(value: BigUint) -> U256 {\n\n let bytes = value.to_bytes_le();\n\n U256::from_little_endian(&bytes)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n fn biguint_u256_conversion_roundrip(u256: U256) {\n\n let biguint = u256_to_biguint(u256);\n\n // Make sure that the string representations are the same.\n\n assert_eq!(biguint.to_string(), u256.to_string());\n\n\n\n let restored = biguint_to_u256(biguint);\n\n assert_eq!(u256, restored);\n\n }\n\n\n\n #[test]\n\n fn test_zero_conversion() {\n", "file_path": "sdk/zksync-rs/src/utils.rs", "rank": 33, "score": 222714.71282336378 }, { "content": "/// Converts `U256` into the corresponding `BigUint` value.\n\npub fn u256_to_biguint(value: U256) -> BigUint {\n\n let mut bytes = [0u8; 32];\n\n value.to_little_endian(&mut bytes);\n\n BigUint::from_bytes_le(&bytes)\n\n}\n\n\n", "file_path": "sdk/zksync-rs/src/utils.rs", "rank": 34, "score": 222714.71282336378 }, { "content": "pub fn pub_key_hash(pub_key: &PublicKey<Engine>) -> Vec<u8> {\n\n let (pub_x, pub_y) = pub_key.0.into_xy();\n\n let pub_key_hash = rescue_hash_elements(&[pub_x, pub_y]);\n\n let mut pub_key_hash_bits = Vec::with_capacity(NEW_PUBKEY_HASH_WIDTH);\n\n append_le_fixed_width(&mut pub_key_hash_bits, &pub_key_hash, NEW_PUBKEY_HASH_WIDTH);\n\n let mut bytes = le_bit_vector_into_bytes(&pub_key_hash_bits);\n\n bytes.reverse();\n\n bytes\n\n}\n\n\n", "file_path": "sdk/zksync-crypto/src/utils.rs", "rank": 35, "score": 221198.80668314896 }, { "content": "/// Checks whether the fee amount can be packed (and thus used in the transaction).\n\npub fn is_fee_amount_packable(amount: &BigUint) -> bool {\n\n Some(amount.clone()) == unpack_fee_amount(&pack_fee_amount(amount))\n\n}\n\n\n", "file_path": "core/lib/types/src/helpers.rs", "rank": 36, "score": 220204.86055772827 }, { "content": "/// Checks whether the token amount can be packed (and thus used in the transaction).\n\npub fn is_token_amount_packable(amount: &BigUint) -> bool {\n\n Some(amount.clone()) == unpack_token_amount(&pack_token_amount(amount))\n\n}\n\n\n", "file_path": "core/lib/types/src/helpers.rs", "rank": 37, "score": 220091.97746348212 }, { "content": "pub fn serialize_proof(\n\n proof: &Proof<Engine, PlonkCsWidth4WithNextStepParams>,\n\n) -> EncodedProofPlonk {\n\n let mut inputs = vec![];\n\n for input in proof.input_values.iter() {\n\n let ser = EthereumSerializer::serialize_fe(input);\n\n inputs.push(ser);\n\n }\n\n let mut serialized_proof = vec![];\n\n\n\n for c in proof.wire_commitments.iter() {\n\n let (x, y) = EthereumSerializer::serialize_g1(c);\n\n serialized_proof.push(x);\n\n serialized_proof.push(y);\n\n }\n\n\n\n let (x, y) = EthereumSerializer::serialize_g1(&proof.grand_product_commitment);\n\n serialized_proof.push(x);\n\n serialized_proof.push(y);\n\n\n", "file_path": "core/lib/prover_utils/src/lib.rs", "rank": 38, "score": 218787.21933626832 }, { "content": "pub fn apply_fee(\n\n tree: &mut CircuitAccountTree,\n\n validator_address: u32,\n\n token: u32,\n\n fee: u128,\n\n) -> (Fr, AccountWitness<Bn256>) {\n\n let fee_fe = Fr::from_str(&fee.to_string()).unwrap();\n\n let mut validator_leaf = tree\n\n .remove(validator_address)\n\n .expect(\"validator_leaf is empty\");\n\n let validator_account_witness = AccountWitness::from_circuit_account(&validator_leaf);\n\n\n\n let mut balance = validator_leaf.subtree.remove(token).unwrap_or_default();\n\n balance.value.add_assign(&fee_fe);\n\n validator_leaf.subtree.insert(token, balance);\n\n\n\n tree.insert(validator_address, validator_leaf);\n\n\n\n let root_after_fee = tree.root_hash();\n\n (root_after_fee, validator_account_witness)\n\n}\n\n\n", "file_path": "core/lib/circuit/src/witness/utils.rs", "rank": 39, "score": 218749.17290989187 }, { "content": "pub fn ratio_to_big_decimal(num: &Ratio<BigUint>, precision: usize) -> BigDecimal {\n\n let bigint = round_precision_raw_no_div(num, precision)\n\n .to_bigint()\n\n .unwrap();\n\n BigDecimal::new(bigint, precision as i64)\n\n}\n\n\n", "file_path": "core/lib/utils/src/convert.rs", "rank": 40, "score": 218641.07858628067 }, { "content": "/// This method initializes params for current thread, otherwise they will be initialized when signing\n\n/// first message.\n\npub fn zksync_crypto_init() {\n\n JUBJUB_PARAMS.with(|_| {});\n\n RESCUE_PARAMS.with(|_| {});\n\n set_panic_hook();\n\n}\n\n\n", "file_path": "sdk/zksync-crypto/src/lib.rs", "rank": 41, "score": 218635.56747408374 }, { "content": "/// Formats amount in wei to tokens.\n\n/// Behaves just like js ethers.utils.formatEther\n\npub fn format_ether(wei: impl ToString) -> String {\n\n format_units(wei, 18)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_format_units() {\n\n // Test vector of (decimals, wei input, expected output)\n\n let vals = vec![\n\n (0, \"1000000000000000100000\", \"1000000000000000100000.0\"),\n\n (1, \"0\", \"0.0\"),\n\n (1, \"11000000000000000000\", \"1100000000000000000.0\"),\n\n (2, \"0\", \"0.0\"),\n\n (2, \"1000000000000000100000\", \"10000000000000001000.0\"),\n\n (4, \"10001000000\", \"1000100.0\"),\n\n (4, \"10100000000000000000000\", \"1010000000000000000.0\"),\n\n (4, \"110\", \"0.011\"),\n", "file_path": "core/lib/utils/src/format.rs", "rank": 42, "score": 216660.02064091858 }, { "content": "/// Generates dummy operation with the default `new_root_hash` in the block.\n\npub fn gen_operation(\n\n block_number: BlockNumber,\n\n action: Action,\n\n block_chunks_size: usize,\n\n) -> Operation {\n\n gen_operation_with_txs(block_number, action, block_chunks_size, vec![])\n\n}\n\n\n", "file_path": "core/lib/storage/src/test_data.rs", "rank": 43, "score": 216641.3421074187 }, { "content": "pub fn bytes_into_be_bits(bytes: &[u8]) -> Vec<bool> {\n\n let mut bits = Vec::with_capacity(bytes.len() * 8);\n\n for byte in bytes {\n\n let mut temp = *byte;\n\n for _ in 0..8 {\n\n bits.push(temp & 0x80 == 0x80);\n\n temp <<= 1;\n\n }\n\n }\n\n bits\n\n}\n\n\n", "file_path": "sdk/zksync-crypto/src/utils.rs", "rank": 44, "score": 216525.10787160744 }, { "content": "fn load_json(path: &str) -> serde_json::Value {\n\n serde_json::from_str(&fs::read_to_string(path).expect(\"Invalid config path\"))\n\n .expect(\"Invalid config format\")\n\n}\n\n\n", "file_path": "core/lib/config/src/test_config/mod.rs", "rank": 45, "score": 216211.18906777335 }, { "content": "pub fn deploy_contracts(use_prod_contracts: bool, genesis_root: Fr) -> Contracts {\n\n let mut args = vec![\"run\", \"deploy-testkit\", \"--genesisRoot\"];\n\n let genesis_root = format!(\"0x{}\", genesis_root.to_hex());\n\n args.push(genesis_root.as_str());\n\n if use_prod_contracts {\n\n args.push(\"--prodContracts\");\n\n }\n\n let stdout = run_external_command(\"zk\", &args);\n\n\n\n let mut contracts = HashMap::new();\n\n for std_out_line in stdout.split_whitespace().collect::<Vec<_>>() {\n\n if let Some((name, address)) = get_contract_address(std_out_line) {\n\n contracts.insert(name, address);\n\n }\n\n }\n\n\n\n Contracts {\n\n governance: contracts\n\n .remove(\"GOVERNANCE_ADDR\")\n\n .expect(\"GOVERNANCE_ADDR missing\"),\n", "file_path": "core/tests/testkit/src/external_commands.rs", "rank": 46, "score": 215885.528569711 }, { "content": "// Provides a quasi-random non-zero `Fr` to substitute an incorrect `Fr` value.\n\npub fn incorrect_fr() -> Fr {\n\n Fr::from_str(\"12345\").unwrap()\n\n}\n\n\n\n/// Helper structure to generate `ZkSyncState` and `CircuitAccountTree`.\n\n#[derive(Debug)]\n\npub struct ZkSyncStateGenerator;\n\n\n\nimpl ZkSyncStateGenerator {\n\n fn create_state(accounts: AccountMap) -> (ZkSyncState, CircuitAccountTree) {\n\n let plasma_state = ZkSyncState::from_acc_map(accounts, 1);\n\n\n\n let mut circuit_account_tree =\n\n CircuitAccountTree::new(zksync_crypto::params::account_tree_depth());\n\n for (id, account) in plasma_state.get_accounts() {\n\n circuit_account_tree.insert(id, CircuitAccount::from(account))\n\n }\n\n\n\n (plasma_state, circuit_account_tree)\n\n }\n", "file_path": "core/lib/circuit/src/witness/tests/test_utils.rs", "rank": 47, "score": 214137.2385185036 }, { "content": "pub fn fr_from_bytes(bytes: Vec<u8>) -> Fr {\n\n let mut fr_repr = <Fr as PrimeField>::Repr::default();\n\n fr_repr.read_be(&*bytes).unwrap();\n\n Fr::from_repr(fr_repr).unwrap()\n\n}\n\n\n\n/// Gathered signature data for calculating the operations in several\n\n/// witness structured (e.g. `TransferWitness` or `WithdrawWitness`).\n\n#[derive(Debug, Clone)]\n\npub struct SigDataInput {\n\n pub first_sig_msg: Fr,\n\n pub second_sig_msg: Fr,\n\n pub third_sig_msg: Fr,\n\n pub signature: SignatureData,\n\n pub signer_pub_key_packed: Vec<Option<bool>>,\n\n}\n\n\n\nimpl SigDataInput {\n\n /// Creates a new `SigDataInput` from the raw tx contents, signature and public key\n\n /// of the author.\n", "file_path": "core/lib/circuit/src/witness/utils.rs", "rank": 48, "score": 214081.46804960174 }, { "content": "/// Generates dummy operation with the unique `new_root_hash` in the block.\n\npub fn gen_unique_operation(\n\n block_number: BlockNumber,\n\n action: Action,\n\n block_chunks_size: usize,\n\n) -> Operation {\n\n gen_unique_operation_with_txs(block_number, action, block_chunks_size, vec![])\n\n}\n\n\n", "file_path": "core/lib/storage/src/test_data.rs", "rank": 49, "score": 213954.0530781601 }, { "content": "/// Generates dummy operation with the default `new_root_hash` in the block and given set of transactions.\n\npub fn gen_operation_with_txs(\n\n block_number: BlockNumber,\n\n action: Action,\n\n block_chunks_size: usize,\n\n txs: Vec<ExecutedOperations>,\n\n) -> Operation {\n\n Operation {\n\n id: None,\n\n action,\n\n block: Block {\n\n block_number,\n\n new_root_hash: Fr::default(),\n\n fee_account: 0,\n\n block_transactions: txs,\n\n processed_priority_ops: (0, 0),\n\n block_chunks_size,\n\n commit_gas_limit: 1_000_000.into(),\n\n verify_gas_limit: 1_500_000.into(),\n\n },\n\n }\n\n}\n\n\n", "file_path": "core/lib/storage/src/test_data.rs", "rank": 50, "score": 213953.93331085256 }, { "content": "#[test]\n\nfn test_new_transpile_deposit_franklin_existing_account_validate_only() {\n\n const NUM_DEPOSITS: usize = 50;\n\n println!(\n\n \"Testing for {} deposits {} chunks\",\n\n NUM_DEPOSITS,\n\n DepositOp::CHUNKS * NUM_DEPOSITS\n\n );\n\n let account = WitnessTestAccount::new_empty(1);\n\n\n\n let deposit_to_account_id = account.id;\n\n let deposit_to_account_address = account.account.address;\n\n let (mut plasma_state, mut circuit_tree) = ZkSyncStateGenerator::generate(&vec![account]);\n\n let mut witness_accum = WitnessBuilder::new(&mut circuit_tree, 0, 1);\n\n\n\n let deposit_op = DepositOp {\n\n priority_op: Deposit {\n\n from: deposit_to_account_address,\n\n token: 0,\n\n amount: BigUint::from(1u32),\n\n to: deposit_to_account_address,\n", "file_path": "core/lib/circuit/src/playground/plonk_playground.rs", "rank": 51, "score": 213630.50427078764 }, { "content": "pub fn is_signature_from_address(\n\n signature: &PackedEthSignature,\n\n msg: &[u8],\n\n address: Address,\n\n) -> Result<bool, SignerError> {\n\n let signature_is_correct = signature\n\n .signature_recover_signer(msg)\n\n .map_err(|err| SignerError::RecoverAddress(err.to_string()))?\n\n == address;\n\n Ok(signature_is_correct)\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub enum AddressOrIndex {\n\n Address(Address),\n\n Index(usize),\n\n}\n\n\n\n/// Describes whether to add a prefix `\\x19Ethereum Signed Message:\\n`\n\n/// when requesting a message signature.\n", "file_path": "core/lib/eth_signer/src/json_rpc_signer.rs", "rank": 52, "score": 213437.72028984275 }, { "content": "/// Number of supported tokens.\n\npub fn total_tokens() -> usize {\n\n 2usize.pow(balance_tree_depth() as u32)\n\n}\n\n\n", "file_path": "core/lib/crypto/src/params.rs", "rank": 53, "score": 211940.7655402151 }, { "content": "/// Attempts to unpack the fee amount.\n\npub fn unpack_fee_amount(data: &[u8]) -> Option<BigUint> {\n\n FloatConversions::unpack(\n\n data,\n\n params::FEE_EXPONENT_BIT_WIDTH,\n\n params::FEE_MANTISSA_BIT_WIDTH,\n\n )\n\n .and_then(BigUint::from_u128)\n\n}\n\n\n", "file_path": "core/lib/types/src/helpers.rs", "rank": 54, "score": 211749.80132671082 }, { "content": "pub fn le_bit_vector_into_bytes(bits: &[bool]) -> Vec<u8> {\n\n let mut bytes: Vec<u8> = Vec::with_capacity(bits.len() / 8);\n\n\n\n let byte_chunks = bits.chunks(8);\n\n\n\n for byte_chunk in byte_chunks {\n\n let mut byte = 0u8;\n\n // pack just in order\n\n for (i, bit) in byte_chunk.iter().enumerate() {\n\n if *bit {\n\n byte |= 1 << i;\n\n }\n\n }\n\n bytes.push(byte);\n\n }\n\n\n\n bytes\n\n}\n\n\n", "file_path": "sdk/zksync-crypto/src/utils.rs", "rank": 55, "score": 211722.52910056023 }, { "content": "pub fn be_bit_vector_into_bytes(bits: &[bool]) -> Vec<u8> {\n\n let mut bytes: Vec<u8> = vec![];\n\n\n\n let byte_chunks = bits.chunks(8);\n\n\n\n for byte_chunk in byte_chunks {\n\n let mut byte = 0u8;\n\n // pack just in order\n\n for (i, bit) in byte_chunk.iter().enumerate() {\n\n if *bit {\n\n byte |= 1 << (7 - i);\n\n }\n\n }\n\n bytes.push(byte);\n\n }\n\n\n\n bytes\n\n}\n\n\n\npub(crate) fn append_le_fixed_width<P: PrimeField>(content: &mut Vec<bool>, x: &P, width: usize) {\n\n let mut token_bits: Vec<bool> = BitIterator::new(x.into_repr()).collect();\n\n token_bits.reverse();\n\n // token_bits.truncate(width);\n\n token_bits.resize(width, false);\n\n content.extend(token_bits);\n\n}\n\n\n", "file_path": "core/lib/crypto/src/circuit/utils.rs", "rank": 56, "score": 211722.52910056023 }, { "content": "pub fn rescue_hash_tx_msg(msg: &[u8]) -> Vec<u8> {\n\n let mut msg_bits = bytes_into_be_bits(msg);\n\n msg_bits.resize(PAD_MSG_BEFORE_HASH_BITS_LEN, false);\n\n let hash_fr = rescue_hash_fr(msg_bits);\n\n let mut hash_bits = Vec::new();\n\n append_le_fixed_width(&mut hash_bits, &hash_fr, 256);\n\n pack_bits_into_bytes(hash_bits)\n\n}\n", "file_path": "sdk/zksync-crypto/src/utils.rs", "rank": 57, "score": 211722.52910056023 }, { "content": "pub fn rescue_hash_tx_msg(msg: &[u8]) -> Vec<u8> {\n\n let mut msg_bits = BitConvert::from_be_bytes(msg);\n\n msg_bits.resize(params::PAD_MSG_BEFORE_HASH_BITS_LEN, false);\n\n let hasher = &params::RESCUE_HASHER as &BabyRescueHasher;\n\n let hash_fr = hasher.hash_bits(msg_bits.into_iter());\n\n let mut hash_bits = Vec::new();\n\n append_le_fixed_width(&mut hash_bits, &hash_fr, 256);\n\n BitConvert::into_bytes(hash_bits)\n\n}\n\n\n", "file_path": "core/lib/crypto/src/primitives.rs", "rank": 58, "score": 211722.52910056023 }, { "content": "/// Attempts to unpack the token amount.\n\npub fn unpack_token_amount(data: &[u8]) -> Option<BigUint> {\n\n FloatConversions::unpack(\n\n data,\n\n params::AMOUNT_EXPONENT_BIT_WIDTH,\n\n params::AMOUNT_MANTISSA_BIT_WIDTH,\n\n )\n\n .and_then(BigUint::from_u128)\n\n}\n\n\n", "file_path": "core/lib/types/src/helpers.rs", "rank": 59, "score": 211638.87110716148 }, { "content": "/// Generates dummy operation with the unique `new_root_hash` in the block and\n\n/// given set of transactions..\n\npub fn gen_unique_operation_with_txs(\n\n block_number: BlockNumber,\n\n action: Action,\n\n block_chunks_size: usize,\n\n txs: Vec<ExecutedOperations>,\n\n) -> Operation {\n\n Operation {\n\n id: None,\n\n action,\n\n block: Block {\n\n block_number,\n\n new_root_hash: dummy_root_hash_for_block(block_number),\n\n fee_account: 0,\n\n block_transactions: txs,\n\n processed_priority_ops: (0, 0),\n\n block_chunks_size,\n\n commit_gas_limit: 1_000_000.into(),\n\n verify_gas_limit: 1_500_000.into(),\n\n },\n\n }\n\n}\n", "file_path": "core/lib/storage/src/test_data.rs", "rank": 60, "score": 211364.8989890879 }, { "content": "/// Creates several random updates for the provided account map,\n\n/// and returns the resulting account map together with the list\n\n/// of generated updates.\n\npub fn apply_random_updates(\n\n mut accounts: AccountMap,\n\n rng: &mut XorShiftRng,\n\n) -> (AccountMap, Vec<(u32, AccountUpdate)>) {\n\n let updates = (0..3)\n\n .map(|_| gen_acc_random_updates(rng))\n\n .flatten()\n\n .collect::<AccountUpdates>();\n\n apply_updates(&mut accounts, updates.clone());\n\n (accounts, updates)\n\n}\n\n\n\n/// Here we create updates for blocks 1,2,3 (commit 3 blocks)\n\n/// We apply updates for blocks 1,2 (verify 2 blocks)\n\n/// Make sure that we can get state for all blocks.\n\n#[db_test]\n\nasync fn test_commit_rewind(mut storage: StorageProcessor<'_>) -> QueryResult<()> {\n\n let _ = env_logger::try_init();\n\n let mut rng = create_rng();\n\n\n", "file_path": "core/lib/storage/src/tests/chain/block.rs", "rank": 61, "score": 211359.61700954865 }, { "content": "// Thread join handle and stop channel sender.\n\npub fn spawn_state_keeper(\n\n fee_account: &Address,\n\n) -> (JoinHandle<()>, oneshot::Sender<()>, StateKeeperChannels) {\n\n let (proposed_blocks_sender, proposed_blocks_receiver) = mpsc::channel(256);\n\n let (state_keeper_req_sender, state_keeper_req_receiver) = mpsc::channel(256);\n\n\n\n let max_ops_in_block = 1000;\n\n let ops_chunks = vec![\n\n TransferToNewOp::CHUNKS,\n\n TransferOp::CHUNKS,\n\n DepositOp::CHUNKS,\n\n FullExitOp::CHUNKS,\n\n WithdrawOp::CHUNKS,\n\n ];\n\n let mut block_chunks_sizes = (0..max_ops_in_block)\n\n .cartesian_product(ops_chunks)\n\n .map(|(x, y)| x * y)\n\n .collect::<Vec<_>>();\n\n block_chunks_sizes.sort_unstable();\n\n block_chunks_sizes.dedup();\n", "file_path": "core/tests/testkit/src/state_keeper_utils.rs", "rank": 62, "score": 211359.61700954865 }, { "content": "pub fn big_decimal_to_ratio(num: &BigDecimal) -> Result<Ratio<BigUint>, anyhow::Error> {\n\n let (big_int, exp) = num.as_bigint_and_exponent();\n\n anyhow::ensure!(!big_int.is_negative(), \"BigDecimal should be unsigned\");\n\n let big_uint = big_int.to_biguint().unwrap();\n\n let ten_pow = BigUint::from(10 as u32).pow(exp as u128);\n\n Ok(Ratio::new(big_uint, ten_pow))\n\n}\n\n\n", "file_path": "core/lib/utils/src/convert.rs", "rank": 63, "score": 211138.42573415558 }, { "content": "#[wasm_bindgen(js_name = pubKeyHash)]\n\npub fn pub_key_hash(pubkey: &[u8]) -> Result<Vec<u8>, JsValue> {\n\n let pubkey = JUBJUB_PARAMS\n\n .with(|params| PublicKey::read(&pubkey[..], params))\n\n .map_err(|_| JsValue::from_str(\"couldn't read public key\"))?;\n\n Ok(utils::pub_key_hash(&pubkey))\n\n}\n\n\n", "file_path": "sdk/zksync-crypto/src/lib.rs", "rank": 64, "score": 210352.51647406572 }, { "content": "/// Generic test scenario does the following:\n\n/// - Initializes plasma state\n\n/// - Applies the provided operation on plasma\n\n/// - Applies the provided operation on circuit\n\n/// - Verifies that root hashes in plasma and circuit match\n\n/// - Verifies that there are no unsatisfied constraints in the circuit.\n\npub fn generic_test_scenario<W, F>(\n\n accounts: &[WitnessTestAccount],\n\n op: W::OperationType,\n\n input: W::CalculateOpsInput,\n\n apply_op_on_plasma: F,\n\n) where\n\n W: Witness,\n\n F: FnOnce(&mut ZkSyncState, &W::OperationType) -> Vec<CollectedFee>,\n\n{\n\n // Initialize Plasma and WitnessBuilder.\n\n let (mut plasma_state, mut circuit_account_tree) = ZkSyncStateGenerator::generate(&accounts);\n\n let mut witness_accum = WitnessBuilder::new(&mut circuit_account_tree, FEE_ACCOUNT_ID, 1);\n\n\n\n // Apply op on plasma\n\n let fees = apply_op_on_plasma(&mut plasma_state, &op);\n\n plasma_state.collect_fee(&fees, FEE_ACCOUNT_ID);\n\n\n\n // Apply op on circuit\n\n let witness = W::apply_tx(&mut witness_accum.account_tree, &op);\n\n let circuit_operations = witness.calculate_operations(input);\n", "file_path": "core/lib/circuit/src/witness/tests/test_utils.rs", "rank": 65, "score": 209940.3840905124 }, { "content": "pub fn build_block_witness<'a>(\n\n account_tree: &'a mut CircuitAccountTree,\n\n block: &Block,\n\n) -> Result<WitnessBuilder<'a>, anyhow::Error> {\n\n let block_number = block.block_number;\n\n let block_size = block.block_chunks_size;\n\n\n\n log::info!(\"building prover data for block {}\", &block_number);\n\n\n\n let mut witness_accum = WitnessBuilder::new(account_tree, block.fee_account, block_number);\n\n\n\n let ops = block\n\n .block_transactions\n\n .iter()\n\n .filter_map(|tx| tx.get_executed_op().cloned());\n\n\n\n let mut operations = vec![];\n\n let mut pub_data = vec![];\n\n let mut fees = vec![];\n\n for op in ops {\n", "file_path": "core/lib/circuit/src/witness/utils.rs", "rank": 66, "score": 209412.29241051347 }, { "content": "/// Number of tokens that are processed by this release\n\npub fn number_of_processable_tokens() -> usize {\n\n let num = 128;\n\n\n\n assert!(num <= total_tokens());\n\n assert!(num.is_power_of_two());\n\n\n\n num\n\n}\n\n\n", "file_path": "core/lib/crypto/src/params.rs", "rank": 67, "score": 209216.34093143194 }, { "content": "/// Does the same operations as the `generic_test_scenario`, but assumes\n\n/// that input for `calculate_operations` is corrupted and will lead to an error.\n\n/// The error is caught and checked to match the provided message.\n\npub fn corrupted_input_test_scenario<W, F>(\n\n accounts: &[WitnessTestAccount],\n\n op: W::OperationType,\n\n input: W::CalculateOpsInput,\n\n expected_msg: &str,\n\n apply_op_on_plasma: F,\n\n) where\n\n W: Witness,\n\n W::CalculateOpsInput: Clone + std::fmt::Debug,\n\n F: FnOnce(&mut ZkSyncState, &W::OperationType) -> Vec<CollectedFee>,\n\n{\n\n // Initialize Plasma and WitnessBuilder.\n\n let (mut plasma_state, mut circuit_account_tree) = ZkSyncStateGenerator::generate(&accounts);\n\n let mut witness_accum = WitnessBuilder::new(&mut circuit_account_tree, FEE_ACCOUNT_ID, 1);\n\n\n\n // Apply op on plasma\n\n let fees = apply_op_on_plasma(&mut plasma_state, &op);\n\n plasma_state.collect_fee(&fees, FEE_ACCOUNT_ID);\n\n\n\n // Apply op on circuit\n", "file_path": "core/lib/circuit/src/witness/tests/test_utils.rs", "rank": 68, "score": 207930.41466734762 }, { "content": "/// Performs the operation on the circuit, but not on the plasma,\n\n/// since the operation is meant to be incorrect and should result in an error.\n\n/// The error is caught and checked to match the provided message.\n\npub fn incorrect_op_test_scenario<W, F>(\n\n accounts: &[WitnessTestAccount],\n\n op: W::OperationType,\n\n input: W::CalculateOpsInput,\n\n expected_msg: &str,\n\n collect_fees: F,\n\n) where\n\n W: Witness,\n\n W::CalculateOpsInput: Clone + std::fmt::Debug,\n\n F: FnOnce() -> Vec<CollectedFee>,\n\n{\n\n // Initialize WitnessBuilder.\n\n let (_, mut circuit_account_tree) = ZkSyncStateGenerator::generate(&accounts);\n\n let mut witness_accum = WitnessBuilder::new(&mut circuit_account_tree, FEE_ACCOUNT_ID, 1);\n\n\n\n // Collect fees without actually applying the tx on plasma\n\n let fees = collect_fees();\n\n\n\n // Apply op on circuit\n\n let witness = W::apply_tx(&mut witness_accum.account_tree, &op);\n", "file_path": "core/lib/circuit/src/witness/tests/test_utils.rs", "rank": 69, "score": 207925.38118387916 }, { "content": "/// Generates proof for exit given circuit using step-by-step algorithm.\n\npub fn gen_verified_proof_for_exit_circuit<C: Circuit<Engine> + Clone>(\n\n circuit: C,\n\n) -> Result<EncodedProofPlonk, anyhow::Error> {\n\n let vk = VerificationKey::read(File::open(get_exodus_verification_key_path())?)?;\n\n\n\n log::info!(\"Proof for circuit started\");\n\n\n\n let hints = transpile(circuit.clone())?;\n\n let setup = setup(circuit.clone(), &hints)?;\n\n let size_log2 = setup.n.next_power_of_two().trailing_zeros();\n\n\n\n let size_log2 = std::cmp::max(size_log2, SETUP_MIN_POW2); // for exit circuit\n\n let key_monomial_form = get_universal_setup_monomial_form(size_log2, false)?;\n\n\n\n let proof = prove_by_steps::<_, _, RollingKeccakTranscript<Fr>>(\n\n circuit,\n\n &hints,\n\n &setup,\n\n None,\n\n &key_monomial_form,\n\n )?;\n\n\n\n let valid = verify::<_, RollingKeccakTranscript<Fr>>(&proof, &vk)?;\n\n anyhow::ensure!(valid, \"proof for exit is invalid\");\n\n\n\n log::info!(\"Proof for circuit successful\");\n\n Ok(serialize_proof(&proof))\n\n}\n\n\n", "file_path": "core/lib/prover_utils/src/lib.rs", "rank": 70, "score": 207393.96113381453 }, { "content": "/// Depth of the left subtree of the account tree that can be used in the current version of the circuit.\n\npub fn used_account_subtree_depth() -> usize {\n\n let num = 24; // total accounts = 2.pow(num) ~ 16mil\n\n\n\n assert!(num <= account_tree_depth());\n\n\n\n num\n\n}\n\n\n", "file_path": "core/lib/crypto/src/params.rs", "rank": 71, "score": 206770.55353068557 }, { "content": "fn gen_pk_and_msg() -> (PrivateKey<Engine>, Vec<Vec<u8>>) {\n\n let mut rng = XorShiftRng::from_seed([1, 2, 3, 4]);\n\n\n\n let pk = PrivateKey(rng.gen());\n\n\n\n let mut messages = Vec::new();\n\n messages.push(Vec::<u8>::new());\n\n messages.push(b\"hello world\".to_vec());\n\n\n\n (pk, messages)\n\n}\n\n\n", "file_path": "core/lib/types/src/tx/tests.rs", "rank": 72, "score": 206646.5863697409 }, { "content": "fn balance_per_wallet(fees: &Fees) -> BigUint {\n\n &fees.eth * BigUint::from(2_u64)\n\n}\n\n\n\n#[async_trait]\n\nimpl Scenario for FullExitScenario {\n\n fn requested_resources(&self, fees: &Fees) -> ScenarioResources {\n\n let balance_per_wallet = balance_per_wallet(fees);\n\n\n\n ScenarioResources {\n\n wallets_amount: self.config.wallets_amount,\n\n balance_per_wallet,\n\n }\n\n }\n\n\n\n async fn prepare(\n\n &mut self,\n\n monitor: &Monitor,\n\n fees: &Fees,\n\n wallets: &[TestWallet],\n", "file_path": "core/tests/loadtest/src/scenarios/full_exit.rs", "rank": 73, "score": 205612.61317617586 }, { "content": "pub fn create_withdraw_tx() -> ExecutedOperations {\n\n let withdraw_op = ZkSyncOp::Withdraw(Box::new(WithdrawOp {\n\n tx: Withdraw::new(\n\n 0,\n\n Default::default(),\n\n Default::default(),\n\n 0,\n\n 100u32.into(),\n\n 10u32.into(),\n\n 12,\n\n None,\n\n ),\n\n account_id: 0,\n\n }));\n\n\n\n let executed_withdraw_op = ExecutedTx {\n\n signed_tx: withdraw_op.try_get_tx().unwrap().into(),\n\n success: true,\n\n op: Some(withdraw_op),\n\n fail_reason: None,\n\n block_index: None,\n\n created_at: Utc::now(),\n\n batch_id: None,\n\n };\n\n\n\n ExecutedOperations::Tx(Box::new(executed_withdraw_op))\n\n}\n\n\n", "file_path": "core/lib/types/src/tests/utils.rs", "rank": 74, "score": 202170.90849187906 }, { "content": "/// Formats amount in wei to tokens with precision.\n\n/// Behaves just like ethers.utils.formatUnits\n\npub fn format_units(wei: impl ToString, units: u8) -> String {\n\n let mut chars: VecDeque<char> = wei.to_string().chars().collect();\n\n\n\n while chars.len() < units as usize {\n\n chars.push_front('0');\n\n }\n\n chars.insert(chars.len() - units as usize, '.');\n\n if *chars.front().unwrap() == '.' {\n\n chars.push_front('0');\n\n }\n\n while *chars.back().unwrap() == '0' {\n\n chars.pop_back();\n\n }\n\n if *chars.back().unwrap() == '.' {\n\n chars.push_back('0');\n\n }\n\n chars.iter().collect()\n\n}\n\n\n", "file_path": "core/lib/utils/src/format.rs", "rank": 75, "score": 201980.28244135852 }, { "content": "pub fn empty_account_as_field_elements<E: Engine>() -> Vec<E::Fr> {\n\n let acc = CircuitAccount::<Bn256>::default();\n\n let bits = acc.get_bits_le();\n\n\n\n use crate::franklin_crypto::circuit::multipack;\n\n\n\n multipack::compute_multipacking::<E>(&bits)\n\n}\n\n\n\n/// Representation of the zkSync account used in the `zksync_circuit`.\n\n#[derive(Clone)]\n\npub struct CircuitAccount<E: RescueEngine> {\n\n pub subtree: SparseMerkleTree<Balance<E>, E::Fr, RescueHasher<E>>,\n\n pub nonce: E::Fr,\n\n pub pub_key_hash: E::Fr,\n\n pub address: E::Fr,\n\n}\n\n\n\nimpl<E: RescueEngine> GetBits for CircuitAccount<E> {\n\n fn get_bits_le(&self) -> Vec<bool> {\n", "file_path": "core/lib/crypto/src/circuit/account.rs", "rank": 76, "score": 201976.00031717098 }, { "content": "pub fn allocate_numbers_vec<E, CS>(\n\n mut cs: CS,\n\n witness_vec: &[Option<E::Fr>],\n\n) -> Result<Vec<AllocatedNum<E>>, SynthesisError>\n\nwhere\n\n E: Engine,\n\n CS: ConstraintSystem<E>,\n\n{\n\n let mut allocated = vec![];\n\n for (i, e) in witness_vec.iter().enumerate() {\n\n let path_element =\n\n AllocatedNum::alloc(cs.namespace(|| format!(\"path element{}\", i)), || {\n\n Ok(*e.get()?)\n\n })?;\n\n allocated.push(path_element);\n\n }\n\n\n\n Ok(allocated)\n\n}\n\n\n", "file_path": "core/lib/circuit/src/utils.rs", "rank": 77, "score": 201164.1700635365 }, { "content": "pub fn print_boolean_vec(bits: &[Boolean]) {\n\n let mut bytes = vec![];\n\n for slice in bits.chunks(8) {\n\n let mut b = 0u8;\n\n for (i, bit) in slice.iter().enumerate() {\n\n if bit.get_value().unwrap() {\n\n b |= 1u8 << (7 - i);\n\n }\n\n }\n\n bytes.push(b);\n\n }\n\n}\n\n\n", "file_path": "core/lib/circuit/src/utils.rs", "rank": 78, "score": 201164.1700635365 }, { "content": "#[test]\n\n#[ignore]\n\nfn test_transfer_to_new_success() {\n\n // Test vector of (initial_balance, transfer_amount, fee_amount).\n\n let test_vector = vec![\n\n (10u64, 7u64, 3u64), // Basic transfer\n\n (0, 0, 0), // Zero transfer\n\n (std::u64::MAX, 1, 1), // Small transfer from rich account,\n\n (std::u64::MAX, 10000, 1), // Big transfer from rich account (too big values can't be used, since they're not packable),\n\n (std::u64::MAX, 1, 10000), // Very big fee\n\n ];\n\n\n\n for (initial_balance, transfer_amount, fee_amount) in test_vector {\n\n // Input data.\n\n let accounts = vec![WitnessTestAccount::new(1, initial_balance)];\n\n let account_from = &accounts[0];\n\n let account_to = WitnessTestAccount::new_empty(2); // Will not be included into state.\n\n let transfer_op = TransferToNewOp {\n\n tx: account_from\n\n .zksync_account\n\n .sign_transfer(\n\n 0,\n", "file_path": "core/lib/circuit/src/witness/tests/transfer_to_new.rs", "rank": 79, "score": 200929.8734901435 }, { "content": "/// Returns `ethabi::Contract` object for ERC-20 smart contract interface.\n\npub fn ierc20_contract() -> ethabi::Contract {\n\n load_contract(IERC20_INTERFACE)\n\n}\n\n\n\n/// `EthereumProvider` gains access to on-chain operations, such as deposits and full exits.\n\n/// Methods to interact with Ethereum return corresponding Ethereum transaction hash.\n\n/// In order to monitor transaction execution, an Ethereum node `web3` API is exposed\n\n/// via `EthereumProvider::web3` method.\n\n#[derive(Debug)]\n\npub struct EthereumProvider<S: EthereumSigner> {\n\n tokens_cache: TokensCache,\n\n eth_client: ETHClient<Http, S>,\n\n erc20_abi: ethabi::Contract,\n\n confirmation_timeout: Duration,\n\n}\n\n\n\nimpl<S: EthereumSigner> EthereumProvider<S> {\n\n /// Creates a new Ethereum provider.\n\n pub async fn new<P: Provider>(\n\n provider: &P,\n", "file_path": "sdk/zksync-rs/src/ethereum/mod.rs", "rank": 80, "score": 200427.48145652632 }, { "content": "/// Returns `ethabi::Contract` object for zkSync smart contract.\n\npub fn zksync_contract() -> ethabi::Contract {\n\n load_contract(ZKSYNC_INTERFACE)\n\n}\n\n\n", "file_path": "sdk/zksync-rs/src/ethereum/mod.rs", "rank": 81, "score": 200427.48145652632 }, { "content": "pub fn create_full_exit_op() -> ExecutedOperations {\n\n let priority_op = FullExit {\n\n account_id: 0,\n\n eth_address: Address::zero(),\n\n token: 0,\n\n };\n\n ExecutedOperations::PriorityOp(Box::new(ExecutedPriorityOp {\n\n priority_op: PriorityOp {\n\n serial_id: 0,\n\n data: ZkSyncPriorityOp::FullExit(priority_op.clone()),\n\n deadline_block: 0,\n\n eth_hash: Vec::new(),\n\n eth_block: 0,\n\n },\n\n op: ZkSyncOp::FullExit(Box::new(FullExitOp {\n\n priority_op,\n\n withdraw_amount: None,\n\n })),\n\n block_index: 0,\n\n created_at: Utc::now(),\n\n }))\n\n}\n\n\n", "file_path": "core/lib/types/src/tests/utils.rs", "rank": 82, "score": 199762.8810590302 }, { "content": "pub fn create_change_pubkey_tx() -> ExecutedOperations {\n\n let change_pubkey_op = ZkSyncOp::ChangePubKeyOffchain(Box::new(ChangePubKeyOp {\n\n tx: ChangePubKey::new(\n\n 1,\n\n Default::default(),\n\n Default::default(),\n\n 0,\n\n Default::default(),\n\n Default::default(),\n\n None,\n\n None,\n\n ),\n\n account_id: 0,\n\n }));\n\n\n\n let executed_change_pubkey_op = ExecutedTx {\n\n signed_tx: change_pubkey_op.try_get_tx().unwrap().into(),\n\n success: true,\n\n op: Some(change_pubkey_op),\n\n fail_reason: None,\n\n block_index: None,\n\n created_at: Utc::now(),\n\n batch_id: None,\n\n };\n\n\n\n ExecutedOperations::Tx(Box::new(executed_change_pubkey_op))\n\n}\n", "file_path": "core/lib/types/src/tests/utils.rs", "rank": 83, "score": 199762.8810590302 }, { "content": "/// Generates several different `SignedFranlinTx` objects.\n\nfn franklin_txs() -> Vec<SignedZkSyncTx> {\n\n let transfer_1 = Transfer::new(\n\n 42,\n\n Address::random(),\n\n Address::random(),\n\n 0,\n\n 100u32.into(),\n\n 10u32.into(),\n\n 10,\n\n None,\n\n );\n\n\n\n let transfer_2 = Transfer::new(\n\n 4242,\n\n Address::random(),\n\n Address::random(),\n\n 0,\n\n 500u32.into(),\n\n 20u32.into(),\n\n 11,\n", "file_path": "core/lib/storage/src/tests/chain/mempool.rs", "rank": 84, "score": 198399.14261701197 }, { "content": "#[wasm_bindgen(js_name = privateKeyFromSeed)]\n\npub fn private_key_from_seed(seed: &[u8]) -> Result<Vec<u8>, JsValue> {\n\n if seed.len() < 32 {\n\n return Err(JsValue::from_str(\"Seed is too short\"));\n\n };\n\n\n\n let sha256_bytes = |input: &[u8]| -> Vec<u8> {\n\n let mut hasher = Sha256::new();\n\n hasher.input(input);\n\n hasher.result().to_vec()\n\n };\n\n\n\n let mut effective_seed = sha256_bytes(seed);\n\n\n\n loop {\n\n let raw_priv_key = sha256_bytes(&effective_seed);\n\n let mut fs_repr = FsRepr::default();\n\n fs_repr\n\n .read_be(&raw_priv_key[..])\n\n .expect(\"failed to read raw_priv_key\");\n\n if Fs::from_repr(fs_repr).is_ok() {\n\n return Ok(raw_priv_key);\n\n } else {\n\n effective_seed = raw_priv_key;\n\n }\n\n }\n\n}\n\n\n", "file_path": "sdk/zksync-crypto/src/lib.rs", "rank": 85, "score": 197376.52503780834 }, { "content": "/// Verifies that circuit has no unsatisfied constraints, and panics otherwise.\n\npub fn check_circuit(circuit: ZkSyncCircuit<Engine>) {\n\n check_circuit_non_panicking(circuit).expect(\"ERROR satisfying the constraints:\")\n\n}\n\n\n", "file_path": "core/lib/circuit/src/witness/tests/test_utils.rs", "rank": 86, "score": 195259.0389640018 }, { "content": "#[wasm_bindgen]\n\npub fn private_key_to_pubkey(private_key: &[u8]) -> Result<Vec<u8>, JsValue> {\n\n let mut pubkey_buf = Vec::with_capacity(PACKED_POINT_SIZE);\n\n\n\n let pubkey = privkey_to_pubkey_internal(private_key)?;\n\n\n\n pubkey\n\n .write(&mut pubkey_buf)\n\n .expect(\"failed to write pubkey to buffer\");\n\n\n\n Ok(pubkey_buf)\n\n}\n\n\n\n#[wasm_bindgen]\n", "file_path": "sdk/zksync-crypto/src/lib.rs", "rank": 87, "score": 195246.85215035628 }, { "content": "#[test]\n\nfn test_tree_state() {\n\n let mut state = ZkSyncState::empty();\n\n let empty_root = state.root_hash();\n\n state.insert_account(0, Default::default());\n\n let empty_acc_root = state.root_hash();\n\n\n\n // Tree contains \"empty\" accounts by default, inserting an empty account shouldn't change state.\n\n assert_eq!(empty_root, empty_acc_root);\n\n\n\n let mut balance_account = Account::default();\n\n balance_account.set_balance(0, 100u64.into());\n\n state.insert_account(1, balance_account.clone());\n\n let balance_root = state.root_hash();\n\n\n\n balance_account.set_balance(0, 0u64.into());\n\n state.insert_account(1, balance_account.clone());\n\n let no_balance_root = state.root_hash();\n\n\n\n // Account with manually set 0 token amount should be considered empty as well.\n\n assert_eq!(no_balance_root, empty_acc_root);\n\n\n\n balance_account.set_balance(0, 100u64.into());\n\n state.insert_account(1, balance_account);\n\n let restored_balance_root = state.root_hash();\n\n\n\n // After we restored previously observed balance, root should be identical.\n\n assert_eq!(balance_root, restored_balance_root);\n\n}\n", "file_path": "core/lib/state/src/tests/mod.rs", "rank": 88, "score": 194967.6584835332 }, { "content": "#[test]\n\n#[ignore]\n\nfn composite_test() {\n\n // Perform some operations\n\n let circuit = apply_many_ops();\n\n\n\n // Verify that there are no unsatisfied constraints\n\n check_circuit(circuit);\n\n}\n\n\n\n/// Checks that corrupted list of operations in block leads to predictable errors.\n\n/// Check for chunk in the end of the operations list.\n", "file_path": "core/lib/circuit/src/witness/tests/mod.rs", "rank": 89, "score": 194967.6125588157 }, { "content": "fn get_contract_address(deploy_script_out: &str) -> Option<(String, Address)> {\n\n if let Some(output) = deploy_script_out.strip_prefix(\"GOVERNANCE_ADDR=0x\") {\n\n Some((\n\n String::from(\"GOVERNANCE_ADDR\"),\n\n Address::from_str(output).expect(\"can't parse contract address\"),\n\n ))\n\n } else if let Some(output) = deploy_script_out.strip_prefix(\"VERIFIER_ADDR=0x\") {\n\n Some((\n\n String::from(\"VERIFIER_ADDR\"),\n\n Address::from_str(output).expect(\"can't parse contract address\"),\n\n ))\n\n } else if let Some(output) = deploy_script_out.strip_prefix(\"CONTRACT_ADDR=0x\") {\n\n Some((\n\n String::from(\"CONTRACT_ADDR\"),\n\n Address::from_str(output).expect(\"can't parse contract address\"),\n\n ))\n\n } else if let Some(output) = deploy_script_out.strip_prefix(\"UPGRADE_GATEKEEPER_ADDR=0x\") {\n\n Some((\n\n String::from(\"UPGRADE_GATEKEEPER_ADDR\"),\n\n Address::from_str(output).expect(\"can't parse contract address\"),\n", "file_path": "core/tests/testkit/src/external_commands.rs", "rank": 90, "score": 194777.2645680698 }, { "content": "pub fn parse_ether(eth_value: &str) -> Result<BigUint, anyhow::Error> {\n\n let split = eth_value.split('.').collect::<Vec<&str>>();\n\n ensure!(split.len() == 1 || split.len() == 2, \"Wrong eth value\");\n\n let string_wei_value = if split.len() == 1 {\n\n format!(\"{}000000000000000000\", split[0])\n\n } else if split.len() == 2 {\n\n let before_dot = split[0];\n\n let after_dot = split[1];\n\n ensure!(\n\n after_dot.len() <= 18,\n\n \"ETH value can have up to 18 digits after dot.\"\n\n );\n\n let zeros_to_pad = 18 - after_dot.len();\n\n format!(\"{}{}{}\", before_dot, after_dot, \"0\".repeat(zeros_to_pad))\n\n } else {\n\n unreachable!()\n\n };\n\n\n\n Ok(BigUint::from_str(&string_wei_value)?)\n\n}\n\n\n\n/// Used to sign and post ETH transactions for the zkSync contracts.\n\n#[derive(Debug, Clone)]\n\npub struct EthereumAccount<T: Transport> {\n\n pub private_key: H256,\n\n pub address: Address,\n\n pub main_contract_eth_client: ETHClient<T, PrivateKeySigner>,\n\n}\n\n\n", "file_path": "core/tests/testkit/src/eth_account.rs", "rank": 91, "score": 193429.5569024766 }, { "content": "pub fn noop_operation(tree: &CircuitAccountTree, acc_id: u32) -> Operation<Bn256> {\n\n let signature_data = SignatureData::init_empty();\n\n let first_sig_msg = Fr::zero();\n\n let second_sig_msg = Fr::zero();\n\n let third_sig_msg = Fr::zero();\n\n let signer_pub_key_packed = [Some(false); 256];\n\n\n\n let acc = tree.get(acc_id).unwrap();\n\n let account_address_fe = Fr::from_str(&acc_id.to_string()).unwrap();\n\n let token_fe = Fr::zero();\n\n let balance_value = match acc.subtree.get(0) {\n\n None => Fr::zero(),\n\n Some(bal) => bal.value,\n\n };\n\n let pubdata = vec![false; CHUNK_BIT_WIDTH];\n\n let pubdata_chunks: Vec<_> = pubdata\n\n .chunks(CHUNK_BIT_WIDTH)\n\n .map(|x| le_bit_vector_into_field_element(&x.to_vec()))\n\n .collect();\n\n let (audit_account, audit_balance) = get_audits(tree, acc_id, 0);\n", "file_path": "core/lib/circuit/src/witness/noop.rs", "rank": 92, "score": 193314.66580539936 }, { "content": "#[test]\n\n#[ignore]\n\nfn test_transfer_to_self() {\n\n // Input data.\n\n let accounts = vec![WitnessTestAccount::new(1, 10)];\n\n let account = &accounts[0];\n\n let transfer_op = TransferOp {\n\n tx: account\n\n .zksync_account\n\n .sign_transfer(\n\n 0,\n\n \"\",\n\n BigUint::from(7u32),\n\n BigUint::from(3u32),\n\n &account.account.address,\n\n None,\n\n true,\n\n )\n\n .0,\n\n from: account.id,\n\n to: account.id,\n\n };\n", "file_path": "core/lib/circuit/src/witness/tests/transfer.rs", "rank": 93, "score": 193290.97294043086 }, { "content": "pub fn bench_signatures(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"Signature verify\");\n\n group.throughput(Throughput::Elements(1));\n\n group.bench_function(\n\n \"bench_signature_verify_zksync_musig\",\n\n bench_signature_zksync_musig_verify,\n\n );\n\n group.bench_function(\n\n \"bench_signature_verify_eth_packed\",\n\n bench_signature_verify_eth_packed,\n\n );\n\n group.bench_function(\n\n \"bench_signature_seckp_recover\",\n\n bench_signature_seckp_recover,\n\n );\n\n group.finish();\n\n}\n\n\n\ncriterion_group!(signature_benches, bench_signatures);\n", "file_path": "core/lib/types/benches/criterion/signatures/mod.rs", "rank": 94, "score": 193216.87170129502 }, { "content": "pub fn bench_primitives(c: &mut Criterion) {\n\n c.bench_function(\"u64_get_bits_le\", bench_u64_get_bits_le);\n\n\n\n let mut group = c.benchmark_group(\"Bit Converters\");\n\n\n\n group.throughput(Throughput::Bytes(BYTE_SLICE_SIZE as u64));\n\n group.bench_function(\"bytes_into_be_bits\", bench_bytes_into_be_bits);\n\n group.bench_function(\"pack_bits_into_bytes\", bench_pack_bits_into_bytes);\n\n group.bench_function(\n\n \"pack_bits_into_bytes_in_order\",\n\n bench_pack_bits_into_bytes_in_order,\n\n );\n\n group.bench_function(\"BitIterator::next\", bench_bit_iterator_le_next);\n\n\n\n group.finish();\n\n\n\n c.bench_function(\n\n \"bench_circuit_account_transform\",\n\n bench_circuit_account_transform,\n\n );\n\n}\n\n\n\ncriterion_group!(primitives_benches, bench_primitives);\n", "file_path": "core/lib/types/benches/criterion/primitives/mod.rs", "rank": 95, "score": 193216.87170129502 }, { "content": "#[wasm_bindgen]\n\npub fn private_key_to_pubkey_hash(private_key: &[u8]) -> Result<Vec<u8>, JsValue> {\n\n Ok(utils::pub_key_hash(&privkey_to_pubkey_internal(\n\n private_key,\n\n )?))\n\n}\n\n\n", "file_path": "sdk/zksync-crypto/src/lib.rs", "rank": 96, "score": 193186.2119009261 }, { "content": "#[test]\n\nfn test_priority_op_from_valid_logs() {\n\n let valid_logs = [\n\n Log {\n\n address: Address::from_str(\"bd2ea2073d4efa1a82269800a362f889545983c2\").unwrap(),\n\n topics: vec![H256::from_str(\n\n \"d0943372c08b438a88d4b39d77216901079eda9ca59d45349841c099083b6830\",\n\n )\n\n .unwrap()],\n\n data: Bytes(vec![\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 54, 97, 92, 243, 73, 215, 246, 52, 72, 145,\n\n 177, 231, 202, 124, 114, 136, 63, 93, 192, 73, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\n 160, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\n 0, 0, 0, 18, 133, 59, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 108,\n\n 107, 147, 91, 139, 189, 64, 0, 0, 111, 183, 165, 210, 134, 53, 93, 80, 193, 119,\n\n 133, 131, 237, 37, 53, 35, 227, 136, 205, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n", "file_path": "core/lib/types/src/tests/hardcoded.rs", "rank": 97, "score": 190867.49058999593 }, { "content": "#[test]\n\n#[ignore]\n\n#[should_panic(expected = \"assertion failed: (acc.address == deposit.address)\")]\n\nfn test_incorrect_deposit_address() {\n\n const TOKEN_ID: u16 = 0;\n\n const TOKEN_AMOUNT: u32 = 100;\n\n\n\n let accounts = vec![WitnessTestAccount::new_empty(1)];\n\n let account = &accounts[0];\n\n\n\n // Create a deposit operation with an incorrect recipient address.\n\n let deposit_op = DepositOp {\n\n priority_op: Deposit {\n\n from: account.account.address,\n\n token: TOKEN_ID,\n\n amount: BigUint::from(TOKEN_AMOUNT),\n\n to: Default::default(),\n\n },\n\n account_id: account.id,\n\n };\n\n\n\n // Attempt to apply incorrect operation should result in an assertion failure.\n\n generic_test_scenario::<DepositWitness<Bn256>, _>(\n", "file_path": "core/lib/circuit/src/witness/tests/deposit.rs", "rank": 98, "score": 190844.1057650565 }, { "content": "#[test]\n\nfn test_ethereum_signature_verify_with_serialization() {\n\n let address: Address = \"52312AD6f01657413b2eaE9287f6B9ADaD93D5FE\".parse().unwrap();\n\n let message = \"hello world\";\n\n #[derive(Debug, Serialize, Deserialize, PartialEq)]\n\n struct TestSignatureSerialize {\n\n signature: PackedEthSignature,\n\n }\n\n\n\n // signature calculated using ethers.js signer\n\n let test_signature_serialize = \"{ \\\"signature\\\": \\\"0x111ea2824732851dd0893eaa5873597ba38ed08b69f6d8a0d7f5da810335566403d05281b1f56d12ca653e32eb7d67b76814b0cc8b0da2d7ad2c862d575329951b\\\"}\";\n\n\n\n // test serialization\n\n let deserialized_signature: TestSignatureSerialize =\n\n serde_json::from_str(test_signature_serialize).expect(\"signature deserialize\");\n\n let signature_after_roundtrip: TestSignatureSerialize = serde_json::from_str(\n\n &serde_json::to_string(&deserialized_signature).expect(\"signature serialize roundtrip\"),\n\n )\n\n .expect(\"signature deserialize roundtrip\");\n\n assert_eq!(\n\n deserialized_signature, signature_after_roundtrip,\n", "file_path": "core/lib/types/src/tx/tests.rs", "rank": 99, "score": 190832.78977324034 } ]
Rust
devolutions-gateway/src/rdp/sequence_future/post_mcs.rs
Devolutions/devolutions-gateway
80d83f7a07cd7a695f1f5ec30968efd59161b513
mod licensing; use std::io; use bytes::BytesMut; use ironrdp::mcs::SendDataContext; use ironrdp::rdp::server_license::LicenseEncryptionData; use ironrdp::{ClientInfoPdu, McsPdu, PduParsing, ShareControlHeader, ShareControlPdu}; use slog_scope::{debug, trace, warn}; use tokio::net::TcpStream; use tokio_rustls::TlsStream; use tokio_util::codec::Framed; use super::{FutureState, NextStream, SequenceFutureProperties}; use crate::rdp::filter::{Filter, FilterConfig}; use crate::transport::mcs::SendDataContextTransport; use licensing::{process_challenge, process_license_request, process_upgrade_license, LicenseCredentials, LicenseData}; pub type PostMcsFutureTransport = Framed<TlsStream<TcpStream>, SendDataContextTransport>; pub struct PostMcs { sequence_state: SequenceState, filter: Option<FilterConfig>, originator_id: Option<u16>, license_data: LicenseData, } impl PostMcs { pub fn new(filter: FilterConfig) -> Self { Self { sequence_state: SequenceState::ClientInfo, filter: Some(filter), originator_id: None, license_data: LicenseData { encryption_data: None, credentials: LicenseCredentials { username: String::from("hostname"), hostname: String::new(), }, }, } } } impl SequenceFutureProperties<TlsStream<TcpStream>, SendDataContextTransport, (ironrdp::McsPdu, Vec<u8>)> for PostMcs { type Item = (PostMcsFutureTransport, PostMcsFutureTransport, FilterConfig); fn process_pdu(&mut self, (mcs_pdu, pdu_data): (McsPdu, BytesMut)) -> io::Result<Option<(McsPdu, Vec<u8>)>> { let filter = self.filter.as_ref().expect( "The filter must exist in the client's RDP Connection Sequence, and must be taken only in the Finished state", ); let (next_sequence_state, result) = match mcs_pdu { McsPdu::SendDataRequest(SendDataContext { initiator_id, channel_id, .. }) => { let (next_sequence_state, pdu, credentials) = process_send_data_request_pdu(pdu_data, self.sequence_state, filter, self.originator_id)?; if let Some(credentials) = credentials { self.license_data.credentials = credentials; } ( next_sequence_state, ( McsPdu::SendDataRequest(SendDataContext { pdu_length: pdu.len(), initiator_id, channel_id, }), pdu, ), ) } McsPdu::SendDataIndication(SendDataContext { initiator_id, channel_id, .. }) => { let (next_sequence_state, pdu, indication_data) = process_send_data_indication_pdu( pdu_data, self.sequence_state, filter, self.license_data.encryption_data.clone(), &self.license_data.credentials, )?; if let Some(originator_id) = indication_data.originator_id { self.originator_id = Some(originator_id); } if let Some(encryption_data) = indication_data.encryption_data { self.license_data.encryption_data = Some(encryption_data); } ( next_sequence_state, ( McsPdu::SendDataIndication(SendDataContext { pdu_length: pdu.len(), initiator_id, channel_id, }), pdu, ), ) } _ => { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got MCS PDU during RDP Connection Sequence: {}", mcs_pdu.as_short_name() ), )) } }; self.sequence_state = next_sequence_state; Ok(Some(result)) } fn return_item( &mut self, mut client: Option<PostMcsFutureTransport>, mut server: Option<PostMcsFutureTransport>, ) -> Self::Item { debug!("Successfully processed RDP Connection Sequence"); ( client.take().expect( "In RDP Connection Sequence, the client's stream must exist in a return_item method, and the method cannot be fired multiple times"), server.take().expect( "In RDP Connection Sequence, the server's stream must exist in a return_item method, and the method cannot be fired multiple times"), self.filter.take().expect( "In RDP Connection Sequence, the filter must exist in a return_item method, and the method cannot be fired multiple times"), ) } fn next_sender(&self) -> NextStream { match self.sequence_state { SequenceState::ClientInfo | SequenceState::ClientConfirmActive => NextStream::Client, SequenceState::ServerLicenseRequest | SequenceState::ServerUpgradeLicense | SequenceState::ServerChallenge | SequenceState::ServerDemandActive => NextStream::Server, SequenceState::Finished => panic!( "In RDP Connection Sequence, the future must not require a next sender in the Finished sequence state" ), } } fn next_receiver(&self) -> NextStream { match self.sequence_state { SequenceState::ServerLicenseRequest | SequenceState::ServerChallenge | SequenceState::ServerUpgradeLicense | SequenceState::Finished => NextStream::Server, SequenceState::ServerDemandActive | SequenceState::ClientConfirmActive => NextStream::Client, SequenceState::ClientInfo => { unreachable!("The future must not require a next receiver in the first sequence state (ClientInfo)") } } } fn sequence_finished(&self, future_state: FutureState) -> bool { future_state == FutureState::SendMessage && self.sequence_state == SequenceState::Finished } } fn process_send_data_request_pdu( pdu_data: BytesMut, sequence_state: SequenceState, filter_config: &FilterConfig, originator_id: Option<u16>, ) -> io::Result<(SequenceState, Vec<u8>, Option<LicenseCredentials>)> { match sequence_state { SequenceState::ClientInfo => { let mut client_info_pdu = ClientInfoPdu::from_buffer(pdu_data.as_ref())?; trace!("Got Client Info PDU: {:?}", client_info_pdu); client_info_pdu.filter(filter_config); trace!("Filtered Client Info PDU: {:?}", client_info_pdu); let mut client_info_pdu_buffer = Vec::with_capacity(client_info_pdu.buffer_length()); client_info_pdu.to_buffer(&mut client_info_pdu_buffer)?; Ok(( SequenceState::ServerLicenseRequest, client_info_pdu_buffer, Some(LicenseCredentials { username: client_info_pdu.client_info.credentials.username, hostname: client_info_pdu.client_info.credentials.domain.unwrap_or_default(), }), )) } SequenceState::ClientConfirmActive => { let mut share_control_header = ShareControlHeader::from_buffer(pdu_data.as_ref())?; let next_sequence_state = match (sequence_state, &mut share_control_header.share_control_pdu) { (SequenceState::ClientConfirmActive, ShareControlPdu::ClientConfirmActive(client_confirm_active)) => { if client_confirm_active.originator_id != originator_id.expect("Originator ID must be set during Server Demand Active PDU processing") { warn!( "Got invalid originator ID: {} != {}", client_confirm_active.originator_id, originator_id.unwrap() ); } client_confirm_active.pdu.filter(filter_config); trace!("Got Client Confirm Active PDU: {:?}", client_confirm_active); SequenceState::Finished } (_, share_control_pdu) => { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got invalid client's Share Control Header PDU: {:?}", share_control_pdu.as_short_name() ), )) } }; let mut share_control_header_buffer = Vec::with_capacity(share_control_header.buffer_length()); share_control_header.to_buffer(&mut share_control_header_buffer)?; Ok((next_sequence_state, share_control_header_buffer, None)) } state => Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got invalid sequence state ({:?}) in the client's RDP Connection Sequence", state ), )), } } pub struct IndicationData { originator_id: Option<u16>, encryption_data: Option<LicenseEncryptionData>, } fn process_send_data_indication_pdu( pdu_data: BytesMut, sequence_state: SequenceState, filter_config: &FilterConfig, encryption_data: Option<LicenseEncryptionData>, credentials: &LicenseCredentials, ) -> io::Result<(SequenceState, Vec<u8>, IndicationData)> { match sequence_state { SequenceState::ServerLicenseRequest => process_license_request(pdu_data.as_ref(), credentials), SequenceState::ServerChallenge => process_challenge(pdu_data.as_ref(), encryption_data, credentials), SequenceState::ServerUpgradeLicense => process_upgrade_license(pdu_data.as_ref(), encryption_data), SequenceState::ServerDemandActive => { let mut share_control_header = ShareControlHeader::from_buffer(pdu_data.as_ref())?; let next_sequence_state = match (sequence_state, &mut share_control_header.share_control_pdu) { (SequenceState::ServerDemandActive, ShareControlPdu::ServerDemandActive(server_demand_active)) => { server_demand_active.pdu.filter(filter_config); trace!("Got Server Demand Active PDU: {:?}", server_demand_active); SequenceState::ClientConfirmActive } (_, share_control_pdu) => { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got invalid server's Share Control Header PDU: {:?}", share_control_pdu.as_short_name() ), )) } }; let mut share_control_header_buffer = Vec::with_capacity(share_control_header.buffer_length()); share_control_header.to_buffer(&mut share_control_header_buffer)?; Ok(( next_sequence_state, share_control_header_buffer, IndicationData { originator_id: Some(share_control_header.pdu_source), encryption_data: None, }, )) } state => Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got invalid sequence state ({:?}) in the server's RDP Connection Sequence", state ), )), } } #[derive(Copy, Clone, Debug, PartialEq)] pub enum SequenceState { ClientInfo, ServerLicenseRequest, ServerChallenge, ServerUpgradeLicense, ServerDemandActive, ClientConfirmActive, Finished, }
mod licensing; use std::io; use bytes::BytesMut; use ironrdp::mcs::SendDataContext; use ironrdp::rdp::server_license::LicenseEncryptionData; use ironrdp::{ClientInfoPdu, McsPdu, PduParsing, ShareControlHeader, ShareControlPdu}; use slog_scope::{debug, trace, warn}; use tokio::net::TcpStream; use tokio_rustls::TlsStream; use tokio_util::codec::Framed; use super::{FutureState, NextStream, SequenceFutureProperties}; use crate::rdp::filter::{Filter, FilterConfig}; use crate::transport::mcs::SendDataContextTransport; use licensing::{process_challenge, process_license_request, process_upgrade_license, LicenseCredentials, LicenseData}; pub type PostMcsFutureTransport = Framed<TlsStream<TcpStream>, SendDataContextTransport>; pub struct PostMcs { sequence_state: SequenceState, filter: Option<FilterConfig>, originator_id: Option<u16>, license_data: LicenseData, } impl PostMcs { pub fn new(filter: FilterConfig) -> Self { Self { sequence_state: SequenceState::ClientInfo, filter: Some(filter), originator_id: None, license_data: LicenseData { encryption_data: None, credentials: LicenseCredentials { username: String::from("hostname"), hostname: String::new(), }, }, } } } impl SequenceFutureProperties<TlsStream<TcpStream>, SendDataContextTransport, (ironrdp::McsPdu, Vec<u8>)> for PostMcs { type Item = (PostMcsFutureTransport, PostMcsFutureTransport, FilterConfig); fn process_pdu(&mut self, (mcs_pdu, pdu_data): (McsPdu, BytesMut)) -> io::Result<Option<(McsPdu, Vec<u8>)>> { let filter = self.filter.as_ref().expect( "The filter must exist in the client's RDP Connection Sequence, and must be taken only in the Finished state", ); let (next_sequence_state, result) = match mcs_pdu { McsPdu::SendDataRequest(SendDataContext { initiator_id, channel_id, .. }) => { let (next_sequence_state, pdu, credentials) = process_send_data_request_pdu(pdu_data, self.sequence_state, filter, self.originator_id)?; if let Some(credentials) = credentials { self.license_data.credentials = credentials; } ( next_sequence_state, ( McsPdu::SendDataRequest(SendDataContext { pdu_length: pdu.len(), initiator_id, channel_id, }), pdu, ), ) } McsPdu::SendDataIndication(SendDataContext { initiator_id, channel_id, .. }) => { let (next_sequence_state, pdu, indication_data) = process_send_data_indication_pdu( pdu_data, self.sequence_state, filter, self.license_data.encryption_data.clone(), &self.license_data.credentials, )?; if let Some(originator_id) = indication_data.originator_id { self.originator_id = Some(originator_id); } if let Some(encryption_data) = indication_data.encryption_data { self.license_data.encryption_data = Some(encryption_data); } ( next_sequence_state, ( McsPdu::SendDataIndication(SendDataContext { pdu_length: pdu.len(), initiator_id, channel_id, }), pdu, ), ) } _ => { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got MCS PDU during RDP Connection Sequence: {}", mcs_pdu.as_short_name() ), )) } }; self.sequence_state = next_sequence_state; Ok(Some(result)) } fn return_item( &mut self, mut client: Option<PostMcsFutureTransport>, mut server: Option<PostMcsFutureTransport>, ) -> Self::Item { debug!("Successfully processed RDP Connection Sequence"); ( client.take().expect( "In RDP Connection Sequence, the client's stream must exist in a return_item method, and the method cannot be fired multiple times"), server.take().expect( "In RDP Connection Sequence, the server's stream must exist in a return_item method, and the method cannot be fired multiple times"), self.filter.take().expect( "In RDP Connection Sequence, the filter must exist in a return_item method, and the method cannot be fired multiple times"), ) } fn next_sender(&self) -> NextStream { match self.sequence_state { SequenceState::ClientInfo | SequenceState::ClientConfirmActive => NextStream::Client, SequenceState::ServerLicenseRequest | SequenceState::ServerUpgradeLicense | SequenceState::ServerChallenge | SequenceState::ServerDemandActiv
fn next_receiver(&self) -> NextStream { match self.sequence_state { SequenceState::ServerLicenseRequest | SequenceState::ServerChallenge | SequenceState::ServerUpgradeLicense | SequenceState::Finished => NextStream::Server, SequenceState::ServerDemandActive | SequenceState::ClientConfirmActive => NextStream::Client, SequenceState::ClientInfo => { unreachable!("The future must not require a next receiver in the first sequence state (ClientInfo)") } } } fn sequence_finished(&self, future_state: FutureState) -> bool { future_state == FutureState::SendMessage && self.sequence_state == SequenceState::Finished } } fn process_send_data_request_pdu( pdu_data: BytesMut, sequence_state: SequenceState, filter_config: &FilterConfig, originator_id: Option<u16>, ) -> io::Result<(SequenceState, Vec<u8>, Option<LicenseCredentials>)> { match sequence_state { SequenceState::ClientInfo => { let mut client_info_pdu = ClientInfoPdu::from_buffer(pdu_data.as_ref())?; trace!("Got Client Info PDU: {:?}", client_info_pdu); client_info_pdu.filter(filter_config); trace!("Filtered Client Info PDU: {:?}", client_info_pdu); let mut client_info_pdu_buffer = Vec::with_capacity(client_info_pdu.buffer_length()); client_info_pdu.to_buffer(&mut client_info_pdu_buffer)?; Ok(( SequenceState::ServerLicenseRequest, client_info_pdu_buffer, Some(LicenseCredentials { username: client_info_pdu.client_info.credentials.username, hostname: client_info_pdu.client_info.credentials.domain.unwrap_or_default(), }), )) } SequenceState::ClientConfirmActive => { let mut share_control_header = ShareControlHeader::from_buffer(pdu_data.as_ref())?; let next_sequence_state = match (sequence_state, &mut share_control_header.share_control_pdu) { (SequenceState::ClientConfirmActive, ShareControlPdu::ClientConfirmActive(client_confirm_active)) => { if client_confirm_active.originator_id != originator_id.expect("Originator ID must be set during Server Demand Active PDU processing") { warn!( "Got invalid originator ID: {} != {}", client_confirm_active.originator_id, originator_id.unwrap() ); } client_confirm_active.pdu.filter(filter_config); trace!("Got Client Confirm Active PDU: {:?}", client_confirm_active); SequenceState::Finished } (_, share_control_pdu) => { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got invalid client's Share Control Header PDU: {:?}", share_control_pdu.as_short_name() ), )) } }; let mut share_control_header_buffer = Vec::with_capacity(share_control_header.buffer_length()); share_control_header.to_buffer(&mut share_control_header_buffer)?; Ok((next_sequence_state, share_control_header_buffer, None)) } state => Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got invalid sequence state ({:?}) in the client's RDP Connection Sequence", state ), )), } } pub struct IndicationData { originator_id: Option<u16>, encryption_data: Option<LicenseEncryptionData>, } fn process_send_data_indication_pdu( pdu_data: BytesMut, sequence_state: SequenceState, filter_config: &FilterConfig, encryption_data: Option<LicenseEncryptionData>, credentials: &LicenseCredentials, ) -> io::Result<(SequenceState, Vec<u8>, IndicationData)> { match sequence_state { SequenceState::ServerLicenseRequest => process_license_request(pdu_data.as_ref(), credentials), SequenceState::ServerChallenge => process_challenge(pdu_data.as_ref(), encryption_data, credentials), SequenceState::ServerUpgradeLicense => process_upgrade_license(pdu_data.as_ref(), encryption_data), SequenceState::ServerDemandActive => { let mut share_control_header = ShareControlHeader::from_buffer(pdu_data.as_ref())?; let next_sequence_state = match (sequence_state, &mut share_control_header.share_control_pdu) { (SequenceState::ServerDemandActive, ShareControlPdu::ServerDemandActive(server_demand_active)) => { server_demand_active.pdu.filter(filter_config); trace!("Got Server Demand Active PDU: {:?}", server_demand_active); SequenceState::ClientConfirmActive } (_, share_control_pdu) => { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got invalid server's Share Control Header PDU: {:?}", share_control_pdu.as_short_name() ), )) } }; let mut share_control_header_buffer = Vec::with_capacity(share_control_header.buffer_length()); share_control_header.to_buffer(&mut share_control_header_buffer)?; Ok(( next_sequence_state, share_control_header_buffer, IndicationData { originator_id: Some(share_control_header.pdu_source), encryption_data: None, }, )) } state => Err(io::Error::new( io::ErrorKind::InvalidData, format!( "Got invalid sequence state ({:?}) in the server's RDP Connection Sequence", state ), )), } } #[derive(Copy, Clone, Debug, PartialEq)] pub enum SequenceState { ClientInfo, ServerLicenseRequest, ServerChallenge, ServerUpgradeLicense, ServerDemandActive, ClientConfirmActive, Finished, }
e => NextStream::Server, SequenceState::Finished => panic!( "In RDP Connection Sequence, the future must not require a next sender in the Finished sequence state" ), } }
function_block-function_prefixed
[ { "content": "pub fn connect_as_server(mut stream: impl io::Write + io::Read, host: String) -> io::Result<Uuid> {\n\n let message = JetMessage::JetAcceptReq(JetAcceptReq {\n\n version: JET_VERSION_V1 as u32,\n\n host,\n\n association: Uuid::nil(),\n\n candidate: Uuid::nil(),\n\n });\n\n write_jet_message(&mut stream, message)?;\n\n\n\n let buffer = read_bytes(&mut stream)?;\n\n if let JetMessage::JetAcceptRsp(response) =\n\n JetMessage::read_accept_response(&mut buffer.as_slice()).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?\n\n {\n\n assert_eq!(StatusCode::OK, response.status_code);\n\n assert_eq!(JET_VERSION_V1 as u32, response.version);\n\n assert!(!response.association.is_nil());\n\n\n\n Ok(response.association)\n\n } else {\n\n unreachable!()\n\n }\n\n}\n\n\n", "file_path": "benchmark/src/jet_proto.rs", "rank": 0, "score": 383517.42077023175 }, { "content": "pub fn connect_as_client(mut stream: impl io::Write + io::Read, host: String, association: Uuid) -> io::Result<()> {\n\n let message = JetMessage::JetConnectReq(JetConnectReq {\n\n version: JET_VERSION_V1 as u32,\n\n host,\n\n association,\n\n candidate: Uuid::nil(),\n\n });\n\n write_jet_message(&mut &mut stream, message)?;\n\n\n\n let buffer = read_bytes(&mut stream)?;\n\n if let JetMessage::JetConnectRsp(response) = JetMessage::read_connect_response(&mut buffer.as_slice())\n\n .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?\n\n {\n\n assert_eq!(StatusCode::OK, response.status_code);\n\n assert_eq!(JET_VERSION_V1 as u32, response.version);\n\n\n\n Ok(())\n\n } else {\n\n unreachable!()\n\n }\n\n}\n\n\n", "file_path": "benchmark/src/jet_proto.rs", "rank": 1, "score": 374691.31311634224 }, { "content": "fn map_dvc_pdu<F>(mut pdu: BytesMut, f: F) -> io::Result<(DvcCapabilitiesState, BytesMut)>\n\nwhere\n\n F: FnOnce(BytesMut) -> io::Result<(DvcCapabilitiesState, BytesMut)>,\n\n{\n\n let mut svc_header = vc::ChannelPduHeader::from_buffer(pdu.as_ref())?;\n\n pdu.advance(svc_header.buffer_length());\n\n\n\n if svc_header.total_length as usize != pdu.len() {\n\n return Err(io::Error::new(\n\n io::ErrorKind::InvalidData,\n\n format!(\n\n \"Received invalid VC header total length: {} != {}\",\n\n svc_header.total_length,\n\n pdu.len(),\n\n ),\n\n ));\n\n }\n\n\n\n let (next_state, dvc_pdu_buffer) = f(pdu)?;\n\n\n\n svc_header.total_length = dvc_pdu_buffer.len() as u32;\n\n\n\n let mut pdu = BytesMut::with_capacity(svc_header.buffer_length() + dvc_pdu_buffer.len());\n\n pdu.resize(svc_header.buffer_length() + dvc_pdu_buffer.len(), 0);\n\n svc_header.to_buffer(pdu.as_mut())?;\n\n (&mut pdu[svc_header.buffer_length()..]).clone_from_slice(&dvc_pdu_buffer);\n\n\n\n Ok((next_state, pdu))\n\n}\n\n\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/dvc_capabilities.rs", "rank": 2, "score": 360857.0008861022 }, { "content": "fn encode_and_write_send_data_context_pdu<T>(pdu: T, initiator_id: u16, channel_id: u16, mut stream: impl io::Write)\n\nwhere\n\n T: PduParsing,\n\n T::Error: fmt::Debug,\n\n{\n\n let mut pdu_buffer = Vec::with_capacity(pdu.buffer_length());\n\n pdu.to_buffer(&mut pdu_buffer)\n\n .expect(\"failed to encode Send Data Context PDU\");\n\n\n\n let send_data_context_pdu = SendDataContext {\n\n initiator_id,\n\n channel_id,\n\n pdu_length: pdu_buffer.len(),\n\n };\n\n\n\n write_x224_data_pdu(\n\n McsPdu::SendDataIndication(send_data_context_pdu),\n\n &mut stream,\n\n Some(pdu_buffer.as_slice()),\n\n );\n\n}\n\n\n", "file_path": "jet-proto/tests/rdp.rs", "rank": 3, "score": 334075.0577343245 }, { "content": "pub fn create_negotiation_request(username: String, mut request: Request) -> io::Result<Request> {\n\n request.nego_data = Some(NegoData::Cookie(username));\n\n Ok(request)\n\n}\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/negotiation.rs", "rank": 4, "score": 321789.68415010953 }, { "content": "fn write_x224_data_pdu<T>(pdu: T, mut stream: impl io::Write, extra_data: Option<&[u8]>)\n\nwhere\n\n T: PduParsing,\n\n T::Error: fmt::Debug,\n\n{\n\n let data_length = pdu.buffer_length() + extra_data.map(|v| v.len()).unwrap_or(0);\n\n\n\n Data::new(data_length)\n\n .to_buffer(&mut stream)\n\n .expect(\"failed to write X224 Data\");\n\n pdu.to_buffer(&mut stream).expect(\"failed to encode X224 Data\");\n\n if let Some(extra_data) = extra_data {\n\n stream\n\n .write_all(extra_data)\n\n .expect(\"failed to write extra data for X224 Data\");\n\n }\n\n}\n\n\n", "file_path": "jet-proto/tests/rdp.rs", "rank": 5, "score": 311025.6876528046 }, { "content": "pub fn decode_preconnection_pdu(buf: &mut BytesMut) -> Result<Option<PreconnectionPdu>, io::Error> {\n\n let mut parsing_buffer = buf.as_ref();\n\n match PreconnectionPdu::from_buffer_consume(&mut parsing_buffer) {\n\n Ok(preconnection_pdu) => {\n\n buf.split_at(preconnection_pdu.buffer_length());\n\n Ok(Some(preconnection_pdu))\n\n }\n\n Err(PreconnectionPduError::IoError(e)) if e.kind() == io::ErrorKind::UnexpectedEof => Ok(None),\n\n Err(e) => Err(io::Error::new(\n\n io::ErrorKind::InvalidData,\n\n format!(\"Failed to parse preconnection PDU: {}\", e),\n\n )),\n\n }\n\n}\n\n\n\n/// Returns the decoded preconnection PDU and leftover bytes\n\npub async fn read_preconnection_pdu(stream: &mut TcpStream) -> io::Result<(PreconnectionPdu, BytesMut)> {\n\n let mut buf = BytesMut::with_capacity(512);\n\n\n\n loop {\n", "file_path": "devolutions-gateway/src/preconnection_pdu.rs", "rank": 6, "score": 306089.59036623075 }, { "content": "fn write_dvc_pdu(mut pdu: Vec<u8>, mut tls_stream: &mut (impl io::Write + io::Read), drdynvc_channel_id: u16) {\n\n let channel_header = vc::ChannelPduHeader {\n\n total_length: pdu.len() as u32,\n\n flags: vc::ChannelControlFlags::FLAG_FIRST | vc::ChannelControlFlags::FLAG_LAST,\n\n };\n\n\n\n let mut channel_buffer = Vec::with_capacity(channel_header.buffer_length() + pdu.len());\n\n channel_header\n\n .to_buffer(&mut channel_buffer)\n\n .expect(\"failed to write channel header\");\n\n\n\n channel_buffer.append(&mut pdu);\n\n\n\n let send_data_context_pdu = SendDataContext {\n\n initiator_id: CHANNEL_INITIATOR_ID,\n\n channel_id: drdynvc_channel_id,\n\n pdu_length: channel_buffer.len(),\n\n };\n\n\n\n write_x224_data_pdu(\n\n McsPdu::SendDataIndication(send_data_context_pdu),\n\n &mut tls_stream,\n\n Some(channel_buffer.as_slice()),\n\n );\n\n}\n\n\n", "file_path": "jet-proto/tests/rdp.rs", "rank": 7, "score": 302602.4225199142 }, { "content": "fn read_stream_buffer(tls_stream: &mut impl io::Read) -> BytesMut {\n\n let mut buffer = BytesMut::with_capacity(1024);\n\n buffer.resize(1024, 0u8);\n\n loop {\n\n match tls_stream.read(&mut buffer) {\n\n Ok(n) => {\n\n buffer.truncate(n);\n\n\n\n return buffer;\n\n }\n\n Err(_) => thread::sleep(Duration::from_millis(10)),\n\n }\n\n }\n\n}\n\n\n", "file_path": "jet-proto/tests/rdp.rs", "rank": 8, "score": 302467.93649136496 }, { "content": "fn next_finalization_state(state: FinalizationState, share_data_pdu: &ShareDataPdu) -> io::Result<FinalizationState> {\n\n match (state, &share_data_pdu) {\n\n (FinalizationState::ClientSynchronize, ShareDataPdu::Synchronize(_)) => {\n\n Ok(FinalizationState::ServerSynchronize)\n\n }\n\n (FinalizationState::ServerSynchronize, ShareDataPdu::Synchronize(_)) => {\n\n Ok(FinalizationState::ClientControlCooperate)\n\n }\n\n (FinalizationState::ClientRequestControl, ShareDataPdu::Control(control_pdu))\n\n if control_pdu.action == ControlAction::RequestControl =>\n\n {\n\n Ok(FinalizationState::ServerGrantedControl)\n\n }\n\n (FinalizationState::ClientControlCooperate, ShareDataPdu::Control(control_pdu))\n\n if control_pdu.action == ControlAction::Cooperate =>\n\n {\n\n Ok(FinalizationState::ServerControlCooperate)\n\n }\n\n (FinalizationState::ServerControlCooperate, ShareDataPdu::Control(control_pdu))\n\n if control_pdu.action == ControlAction::Cooperate =>\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/finalization.rs", "rank": 9, "score": 292721.840843656 }, { "content": "fn read_bytes(mut stream: impl io::Read) -> io::Result<Vec<u8>> {\n\n let mut buffer = vec![0u8; 1024];\n\n\n\n match stream.read(&mut buffer) {\n\n Ok(0) => Err(io::Error::new(\n\n io::ErrorKind::ConnectionAborted,\n\n \"Failed to get any byte\",\n\n )),\n\n Ok(n) => {\n\n buffer.truncate(n);\n\n\n\n Ok(buffer)\n\n }\n\n Err(e) => Err(io::Error::new(\n\n io::ErrorKind::Other,\n\n format!(\"Failed to read bytes: {}\", e),\n\n )),\n\n }\n\n}\n", "file_path": "benchmark/src/jet_proto.rs", "rank": 10, "score": 290268.09483223053 }, { "content": "pub fn process_license_request(\n\n pdu: &[u8],\n\n credentials: &LicenseCredentials,\n\n) -> io::Result<(SequenceState, Vec<u8>, IndicationData)> {\n\n let initial_message = InitialServerLicenseMessage::from_buffer(pdu).map_err(|err| {\n\n io::Error::new(\n\n io::ErrorKind::InvalidData,\n\n format!(\n\n \"An error occured during reading Initial Server License Message: {:?}\",\n\n err\n\n ),\n\n )\n\n })?;\n\n\n\n debug!(\"Received Initial License Message PDU\");\n\n trace!(\"{:?}\", initial_message);\n\n\n\n match initial_message.message_type {\n\n InitialMessageType::LicenseRequest(license_request) => {\n\n let mut client_random = vec![0u8; RANDOM_NUMBER_SIZE];\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/post_mcs/licensing.rs", "rank": 11, "score": 284307.55547520396 }, { "content": "type ConnectToServerT = Pin<Box<dyn Future<Output = Result<TcpStream, io::Error>> + Send>>;\n", "file_path": "devolutions-gateway/src/rdp/connection_sequence_future.rs", "rank": 12, "score": 284067.762599851 }, { "content": "fn write_jet_message(mut stream: impl io::Write, message: JetMessage) -> io::Result<()> {\n\n let mut buffer = Vec::with_capacity(1024);\n\n message.write_to(&mut buffer)?;\n\n stream.write_all(&buffer)?;\n\n\n\n stream.flush()\n\n}\n\n\n", "file_path": "benchmark/src/jet_proto.rs", "rank": 13, "score": 283869.3040252269 }, { "content": "type FinalizationT = Pin<Box<SequenceFuture<Finalization, TlsStream<TcpStream>, RdpTransport, RdpPdu>>>;\n", "file_path": "devolutions-gateway/src/rdp/connection_sequence_future.rs", "rank": 14, "score": 257321.92800676767 }, { "content": "type McsT = Pin<Box<SequenceFuture<McsFuture, TlsStream<TcpStream>, McsTransport, ironrdp::McsPdu>>>;\n", "file_path": "devolutions-gateway/src/rdp/connection_sequence_future.rs", "rank": 16, "score": 255712.02710934466 }, { "content": "type McsInitialT = Pin<Box<SequenceFuture<McsInitialFuture, TlsStream<TcpStream>, DataTransport, BytesMut>>>;\n", "file_path": "devolutions-gateway/src/rdp/connection_sequence_future.rs", "rank": 17, "score": 254853.6110150239 }, { "content": "pub fn process_challenge(\n\n pdu: &[u8],\n\n encryption_data: Option<LicenseEncryptionData>,\n\n credentials: &LicenseCredentials,\n\n) -> io::Result<(SequenceState, Vec<u8>, IndicationData)> {\n\n let challenge = match ServerPlatformChallenge::from_buffer(pdu) {\n\n Err(ServerLicenseError::UnexpectedValidClientError(_)) => {\n\n warn!(\"The server has returned STATUS_VALID_CLIENT unexpectedly\");\n\n\n\n let valid_client = InitialServerLicenseMessage::new_status_valid_client_message();\n\n\n\n let mut valid_client_buffer = Vec::with_capacity(valid_client.buffer_length());\n\n valid_client.to_buffer(&mut valid_client_buffer).map_err(|err| {\n\n io::Error::new(\n\n io::ErrorKind::Other,\n\n format!(\"Received an error during writing Status Valid Client message: {}\", err),\n\n )\n\n })?;\n\n\n\n return Ok((\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/post_mcs/licensing.rs", "rank": 18, "score": 253803.81898857522 }, { "content": "pub fn process_upgrade_license(\n\n pdu: &[u8],\n\n encryption_data: Option<LicenseEncryptionData>,\n\n) -> io::Result<(SequenceState, Vec<u8>, IndicationData)> {\n\n let upgrade_license = match ServerUpgradeLicense::from_buffer(pdu) {\n\n Err(ServerLicenseError::UnexpectedValidClientError(_)) => {\n\n warn!(\"The server has returned STATUS_VALID_CLIENT unexpectedly\");\n\n\n\n let valid_client = InitialServerLicenseMessage::new_status_valid_client_message();\n\n\n\n let mut valid_client_buffer = Vec::with_capacity(valid_client.buffer_length());\n\n valid_client.to_buffer(&mut valid_client_buffer).map_err(|err| {\n\n io::Error::new(\n\n io::ErrorKind::Other,\n\n format!(\"Received an error during writing Status Valid Client message: {}\", err),\n\n )\n\n })?;\n\n\n\n return Ok((\n\n SequenceState::ServerDemandActive,\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/post_mcs/licensing.rs", "rank": 19, "score": 250219.04870944188 }, { "content": "pub fn create_tls_connector(socket: TcpStream) -> Connect<TcpStream> {\n\n let mut client_config = tokio_rustls::rustls::ClientConfig::default();\n\n client_config\n\n .dangerous()\n\n .set_certificate_verifier(Arc::new(danger_transport::NoCertificateVerification {}));\n\n let config_ref = Arc::new(client_config);\n\n let tls_connector = TlsConnector::from(config_ref);\n\n let dns_name = webpki::DNSNameRef::try_from_ascii_str(\"stub_string\").unwrap();\n\n tls_connector.connect(dns_name, socket)\n\n}\n", "file_path": "devolutions-gateway/src/utils.rs", "rank": 20, "score": 236349.92778056551 }, { "content": "type NegotiationWithServerT =\n\n Pin<Box<SequenceFuture<NegotiationWithServerFuture, TcpStream, NegotiationWithServerTransport, nego::Request>>>;\n", "file_path": "devolutions-gateway/src/rdp/connection_sequence_future.rs", "rank": 21, "score": 236098.1062727319 }, { "content": "type NegotiationWithClientT =\n\n Pin<Box<SequenceFuture<NegotiationWithClientFuture, TcpStream, NegotiationWithClientTransport, nego::Response>>>;\n", "file_path": "devolutions-gateway/src/rdp/connection_sequence_future.rs", "rank": 22, "score": 235639.91309592902 }, { "content": "fn read_x224_data_pdu<T>(buffer: &mut BytesMut) -> T\n\nwhere\n\n T: PduParsing,\n\n T::Error: fmt::Debug,\n\n{\n\n let data_pdu = Data::from_buffer(buffer.as_ref()).expect(\"failed to read X224 Data\");\n\n buffer.advance(data_pdu.buffer_length() - data_pdu.data_length);\n\n let pdu = T::from_buffer(&buffer[..data_pdu.data_length]).expect(\"failed to decode X224 Data\");\n\n buffer.advance(pdu.buffer_length());\n\n\n\n pdu\n\n}\n\n\n", "file_path": "jet-proto/tests/rdp.rs", "rank": 23, "score": 235271.35153375904 }, { "content": "pub fn get_tls_peer_pubkey<S>(stream: &tokio_rustls::TlsStream<S>) -> io::Result<Vec<u8>> {\n\n let der = get_der_cert_from_stream(&stream)?;\n\n get_pub_key_from_der(&der)\n\n}\n\n\n", "file_path": "devolutions-gateway/src/utils.rs", "rank": 24, "score": 226603.09940018534 }, { "content": "type EarlyClientUserAuthResultFuture =\n\n Box<dyn Future<Output = Result<EarlyUserAuthResultFutureTransport, io::Error>> + Send + 'static>;\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/nla.rs", "rank": 25, "score": 224439.77661665765 }, { "content": "type NlaWithServerT = Pin<Box<NlaWithServerFuture>>;\n", "file_path": "devolutions-gateway/src/rdp/connection_sequence_future.rs", "rank": 26, "score": 222920.05759277233 }, { "content": "type NlaWithClientT = Pin<Box<NlaWithClientFuture>>;\n", "file_path": "devolutions-gateway/src/rdp/connection_sequence_future.rs", "rank": 27, "score": 222376.36499790326 }, { "content": "type EarlyServerUserAuthResultFuture = Box<\n\n dyn Future<\n\n Output = (\n\n Option<Result<EarlyUserAuthResult, io::Error>>,\n\n EarlyUserAuthResultFutureTransport,\n\n ),\n\n > + Send\n\n + 'static,\n\n>;\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/nla.rs", "rank": 29, "score": 218985.79062288292 }, { "content": "pub fn configure_http_server(config: Arc<Config>, jet_associations: JetAssociationsMap) -> Result<(), String> {\n\n SaphirServer::builder()\n\n .configure_middlewares(|middlewares| {\n\n info!(\"Loading HTTP middlewares\");\n\n\n\n middlewares\n\n .apply(\n\n AuthMiddleware::new(config.clone()),\n\n vec![\"/\"],\n\n vec![\"/registry\", \"/health\"],\n\n )\n\n .apply(\n\n SogarAuthMiddleware::new(config.clone()),\n\n vec![\"/registry\"],\n\n vec![\"registry/oauth2/token\"],\n\n )\n\n .apply(LogMiddleware, vec![\"/\"], None)\n\n })\n\n .configure_router(|router| {\n\n info!(\"Loading HTTP controllers\");\n", "file_path": "devolutions-gateway/src/http/http_server.rs", "rank": 30, "score": 211011.9907156778 }, { "content": "type EarlyUserAuthResultFutureTransport = Framed<TlsStream<TcpStream>, EarlyUserAuthResultTransport>;\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/nla.rs", "rank": 31, "score": 210484.1962081158 }, { "content": "pub fn create_downgrade_dvc_capabilities_future(\n\n client_transport: Framed<TlsStream<TcpStream>, RdpTransport>,\n\n server_transport: Framed<TlsStream<TcpStream>, RdpTransport>,\n\n drdynvc_channel_id: u16,\n\n dvc_manager: DvcManager,\n\n) -> SequenceFuture<DowngradeDvcCapabilitiesFuture, TlsStream<TcpStream>, RdpTransport, RdpPdu> {\n\n SequenceFuture::with_get_state(\n\n DowngradeDvcCapabilitiesFuture::new(drdynvc_channel_id, dvc_manager),\n\n GetStateArgs {\n\n client: Some(client_transport),\n\n server: Some(server_transport),\n\n phantom_data: PhantomData,\n\n },\n\n )\n\n}\n\n\n\npub struct DowngradeDvcCapabilitiesFuture {\n\n sequence_state: SequenceState,\n\n drdynvc_channel_id: u16,\n\n dvc_manager: Option<DvcManager>,\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/dvc_capabilities.rs", "rank": 32, "score": 209051.69400544013 }, { "content": "pub fn exit(res: anyhow::Result<()>) -> ! {\n\n match res {\n\n Ok(()) => std::process::exit(0),\n\n Err(e) => {\n\n eprintln!(\"{:?}\", e);\n\n std::process::exit(1);\n\n }\n\n }\n\n}\n\n\n\nconst PIPE_FORMATS: &str = r#\"Pipe formats:\n\n `stdio` or `-`: Standard input output\n\n `cmd://<COMMAND>`: Spawn a new process with specified command using `cmd /C` on windows or `sh -c` otherwise\n\n `tcp://<ADDRESS>`: Plain TCP stream\n\n `tcp-listen://<BINDING ADDRESS>`: TCP listener\n\n `jet-tcp-connect://<ADDRESS>/<ASSOCIATION ID>/<CANDIDATE ID>`: TCP stream over JET protocol as client\n\n `jet-tcp-accept://<ADDRESS>/<ASSOCIATION ID>/<CANDIDATE ID>`: TCP stream over JET protocol as server\n\n `ws://<URL>`: WebSocket\n\n `wss://<URL>`: WebSocket Secure\n\n `ws-listen://<BINDING ADDRESS>`: WebSocket listener\"#;\n\n\n\n// forward\n\n\n\nconst FORWARD_SUBCOMMAND: &str = \"forward\";\n\n\n", "file_path": "jetsocat/src/main.rs", "rank": 33, "score": 204864.38070024253 }, { "content": "pub trait Filter {\n\n fn filter(&mut self, config: &FilterConfig);\n\n}\n\n\n\npub struct FilterConfig {\n\n server_response_protocol: nego::SecurityProtocol,\n\n version: gcc::RdpVersion,\n\n client_early_capability_flags: gcc::ClientEarlyCapabilityFlags,\n\n server_early_capability_flags: gcc::ServerEarlyCapabilityFlags,\n\n encryption_methods: gcc::EncryptionMethod,\n\n target_credentials: Credentials,\n\n}\n\n\n\nimpl FilterConfig {\n\n pub fn new(server_response_protocol: nego::SecurityProtocol, target_credentials: Credentials) -> Self {\n\n Self {\n\n server_response_protocol,\n\n version: gcc::RdpVersion::V5Plus,\n\n client_early_capability_flags: ClientEarlyCapabilityFlags::SUPPORT_DYN_VC_GFX_PROTOCOL,\n\n server_early_capability_flags: gcc::ServerEarlyCapabilityFlags::empty(),\n", "file_path": "devolutions-gateway/src/rdp/filter.rs", "rank": 34, "score": 204463.05514428765 }, { "content": "fn parse_tpkt_tpdu_message(mut tpkt_tpdu: &[u8]) -> Result<ParsedTpktPtdu, io::Error> {\n\n let data_pdu = Data::from_buffer(tpkt_tpdu)?;\n\n let expected_data_length = tpkt_tpdu.len() - (TPKT_HEADER_LENGTH + TPDU_DATA_HEADER_LENGTH);\n\n assert_eq!(expected_data_length, data_pdu.data_length);\n\n\n\n tpkt_tpdu = &tpkt_tpdu[TPKT_HEADER_LENGTH + TPDU_DATA_HEADER_LENGTH..];\n\n let mcs_pdu = McsPdu::from_buffer(tpkt_tpdu)?;\n\n\n\n match mcs_pdu {\n\n McsPdu::SendDataIndication(ref send_data_context) | McsPdu::SendDataRequest(ref send_data_context) => {\n\n Ok(ParsedTpktPtdu::VirtualChannel {\n\n id: send_data_context.channel_id,\n\n buffer: &tpkt_tpdu[tpkt_tpdu.len() - send_data_context.pdu_length..],\n\n })\n\n }\n\n McsPdu::DisconnectProviderUltimatum(reason) => Ok(ParsedTpktPtdu::DisconnectionRequest(reason)),\n\n pdu => Err(io::Error::new(\n\n io::ErrorKind::InvalidData,\n\n format!(\"Unexpected MCS PDU: {:?}\", pdu),\n\n )),\n\n }\n\n}\n\n\n", "file_path": "devolutions-gateway/src/interceptor/rdp.rs", "rank": 35, "score": 203679.44975599198 }, { "content": "pub trait JetStream: Stream {\n\n fn nb_bytes_read(self: Pin<&Self>) -> u64;\n\n fn set_packet_interceptor(self: Pin<&mut Self>, interceptor: Box<dyn PacketInterceptor>);\n\n}\n\n\n", "file_path": "devolutions-gateway/src/transport/mod.rs", "rank": 36, "score": 196784.4205484325 }, { "content": "type PostMcsT =\n\n Pin<Box<SequenceFuture<PostMcs, TlsStream<TcpStream>, SendDataContextTransport, (ironrdp::McsPdu, Vec<u8>)>>>;\n", "file_path": "devolutions-gateway/src/rdp/connection_sequence_future.rs", "rank": 37, "score": 195438.0416254679 }, { "content": "fn format_decorator(decorator: impl Decorator) -> FullFormat<impl Decorator> {\n\n FullFormat::new(decorator)\n\n .use_custom_timestamp(|output: &mut dyn io::Write| -> io::Result<()> {\n\n write!(output, \"{}\", Local::now().format(LOGGER_TIMESTAMP_FORMAT))\n\n })\n\n .build()\n\n}\n\n\n", "file_path": "devolutions-gateway/src/logger.rs", "rank": 38, "score": 192994.2181435732 }, { "content": "type FinalizationTransport = Framed<TlsStream<TcpStream>, RdpTransport>;\n\n\n\npub struct Finalization {\n\n sequence_state: SequenceState,\n\n}\n\n\n\nimpl Finalization {\n\n pub fn new() -> Self {\n\n Self {\n\n sequence_state: SequenceState::Finalization(FinalizationState::ClientSynchronize),\n\n }\n\n }\n\n}\n\n\n\nimpl SequenceFutureProperties<TlsStream<TcpStream>, RdpTransport, RdpPdu> for Finalization {\n\n type Item = (FinalizationTransport, FinalizationTransport);\n\n\n\n fn process_pdu(&mut self, rdp_pdu: RdpPdu) -> io::Result<Option<RdpPdu>> {\n\n let sequence_state = match self.sequence_state {\n\n SequenceState::Finalization(state)\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/finalization.rs", "rank": 39, "score": 192650.09611410552 }, { "content": "type NlaWithClientFutureT =\n\n Pin<Box<SequenceFuture<CredSspWithClientFuture, TlsStream<TcpStream>, TsRequestTransport, TsRequest>>>;\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/nla.rs", "rank": 40, "score": 192052.09547050434 }, { "content": "fn get_pub_key_from_pem_file(file: &str) -> io::Result<Vec<u8>> {\n\n let pem = &fs::read(file)?;\n\n let der = pem_to_der(pem).map_err(|_| {\n\n io::Error::new(\n\n io::ErrorKind::InvalidData,\n\n \"get_pub_key_from_pem_file: invalid pem certificate.\",\n\n )\n\n })?;\n\n let res = parse_x509_der(&der.1.contents[..]).map_err(|_| {\n\n io::Error::new(\n\n io::ErrorKind::InvalidData,\n\n \"get_pub_key_from_pem_file: invalid der certificate.\",\n\n )\n\n })?;\n\n let public_key = res.1.tbs_certificate.subject_pki.subject_public_key;\n\n Ok(public_key.data.to_vec())\n\n}\n\n\n", "file_path": "jet-proto/tests/rdp.rs", "rank": 41, "score": 191579.12677727864 }, { "content": "struct JetStreamImpl<T: AsyncRead> {\n\n stream: ReadHalf<T>,\n\n nb_bytes_read: Arc<AtomicU64>,\n\n packet_interceptor: Option<Box<dyn PacketInterceptor>>,\n\n peer_addr: Option<SocketAddr>,\n\n peer_addr_str: String,\n\n buffer: BipBufferWriter,\n\n}\n\n\n\nimpl<T: AsyncRead + Unpin> JetStreamImpl<T> {\n\n fn new(\n\n stream: ReadHalf<T>,\n\n nb_bytes_read: Arc<AtomicU64>,\n\n peer_addr: Option<SocketAddr>,\n\n buffer: BipBufferWriter,\n\n ) -> Self {\n\n Self {\n\n stream,\n\n nb_bytes_read,\n\n packet_interceptor: None,\n", "file_path": "devolutions-gateway/src/transport/mod.rs", "rank": 42, "score": 190306.543361414 }, { "content": "type CredSspWithServerFutureT =\n\n Pin<Box<SequenceFuture<CredSspWithServerFuture, TlsStream<TcpStream>, TsRequestTransport, TsRequest>>>;\n\n\n\npub enum NlaTransport {\n\n TsRequest(TsRequestFutureTransport),\n\n EarlyUserAuthResult(EarlyUserAuthResultFutureTransport),\n\n}\n\n\n\npub struct NlaWithClientFuture {\n\n state: NlaWithClientFutureState,\n\n client_response_protocol: nego::SecurityProtocol,\n\n tls_proxy_pubkey: Option<Vec<u8>>,\n\n identity: RdpIdentity,\n\n}\n\n\n\nimpl NlaWithClientFuture {\n\n pub fn new(\n\n client: TcpStream,\n\n client_response_protocol: nego::SecurityProtocol,\n\n tls_proxy_pubkey: Vec<u8>,\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/nla.rs", "rank": 43, "score": 189520.19353836737 }, { "content": "fn write_addr(mut addr_buf: &mut [u8], dest: &DestAddr) -> io::Result<usize> {\n\n let initial_len = addr_buf.len();\n\n match dest {\n\n DestAddr::Ip(SocketAddr::V4(addr)) => {\n\n addr_buf.write_all(&[1])?;\n\n addr_buf.write_all(&u32::from(*addr.ip()).to_be_bytes())?;\n\n addr_buf.write_all(&addr.port().to_be_bytes())?;\n\n }\n\n DestAddr::Ip(SocketAddr::V6(addr)) => {\n\n addr_buf.write_all(&[4])?;\n\n addr_buf.write_all(&addr.ip().octets())?;\n\n addr_buf.write_all(&addr.port().to_be_bytes())?;\n\n }\n\n DestAddr::Domain(domain, port) => {\n\n if let Ok(len) = u8::try_from(domain.len()) {\n\n addr_buf.write_all(&[3, len])?;\n\n } else {\n\n return Err(io::Error::new(io::ErrorKind::InvalidInput, \"domain name too long\"));\n\n }\n\n addr_buf.write_all(domain.as_bytes())?;\n", "file_path": "jetsocat/proxy/src/socks5.rs", "rank": 44, "score": 189276.41440633888 }, { "content": "pub fn get_pub_key_from_der(cert: &[u8]) -> io::Result<Vec<u8>> {\n\n let res = parse_x509_der(cert)\n\n .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, \"Utils: invalid der certificate.\"))?;\n\n let public_key = res.1.tbs_certificate.subject_pki.subject_public_key;\n\n\n\n Ok(public_key.data.to_vec())\n\n}\n\n\n", "file_path": "devolutions-gateway/src/utils.rs", "rank": 45, "score": 188819.78391772025 }, { "content": "type DvcCapabilitiesTransport = Framed<TlsStream<TcpStream>, RdpTransport>;\n\n\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/dvc_capabilities.rs", "rank": 46, "score": 188086.50219109762 }, { "content": "pub fn extract_association_claims(\n\n pdu: &PreconnectionPdu,\n\n config: &Config,\n\n) -> Result<JetAssociationTokenClaims, io::Error> {\n\n let payload = pdu\n\n .payload\n\n .as_deref()\n\n .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, \"Empty preconnection PDU\"))?;\n\n\n\n let is_encrypted = is_encrypted(payload);\n\n\n\n let jwe_token; // pre-declaration because we want longer lifetime\n\n let signed_jwt;\n\n\n\n if is_encrypted {\n\n let encrypted_jwt = payload;\n\n\n\n let delegation_key = config\n\n .delegation_private_key\n\n .as_ref()\n", "file_path": "devolutions-gateway/src/preconnection_pdu.rs", "rank": 47, "score": 185311.03474376007 }, { "content": "pub fn run<F: Future<Output = anyhow::Result<()>>>(log: Logger, f: F) -> anyhow::Result<()> {\n\n let rt = runtime::Builder::new_multi_thread()\n\n .enable_all()\n\n .build()\n\n .context(\"runtime build failed\")?;\n\n\n\n match rt.block_on(f) {\n\n Ok(()) => info!(log, \"Terminated successfully\"),\n\n Err(e) => {\n\n crit!(log, \"{:?}\", e);\n\n return Err(e);\n\n }\n\n }\n\n\n\n rt.shutdown_timeout(std::time::Duration::from_millis(100)); // just to be safe\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "jetsocat/src/main.rs", "rank": 48, "score": 184830.2244887109 }, { "content": "pub fn url_to_socket_addr(url: &Url) -> io::Result<SocketAddr> {\n\n use std::net::ToSocketAddrs;\n\n\n\n let host = url\n\n .host_str()\n\n .ok_or_else(|| io::Error::new(io::ErrorKind::Other, \"bad host in url\"))?;\n\n\n\n let port = url\n\n .port_or_known_default()\n\n .or_else(|| match url.scheme() {\n\n \"tcp\" => Some(8080),\n\n _ => None,\n\n })\n\n .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, \"bad or missing port in url\"))?;\n\n\n\n Ok((host, port).to_socket_addrs().unwrap().next().unwrap())\n\n}\n\n\n", "file_path": "devolutions-gateway/src/utils.rs", "rank": 49, "score": 183050.16198817457 }, { "content": "fn get_der_cert_from_stream<S>(stream: &tokio_rustls::TlsStream<S>) -> io::Result<Vec<u8>> {\n\n let (_, session) = stream.get_ref();\n\n let payload = session\n\n .get_peer_certificates()\n\n .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, \"Failed to get the peer certificate.\"))?;\n\n\n\n let cert = payload\n\n .first()\n\n .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, \"Payload does not contain any certificates\"))?;\n\n\n\n Ok(cert.as_ref().to_vec())\n\n}\n\n\n", "file_path": "devolutions-gateway/src/utils.rs", "rank": 50, "score": 182357.78692527174 }, { "content": "pub fn init(file_path: Option<&str>) -> io::Result<Logger> {\n\n let term_decorator = TermDecorator::new().build();\n\n let term_fmt = format_decorator(term_decorator);\n\n\n\n let drain_decorator = if let Some(file_path) = file_path {\n\n let outfile = OpenOptions::new().create(true).append(true).open(file_path)?;\n\n let file_decorator = PlainDecorator::new(outfile);\n\n let file_fmt = format_decorator(file_decorator);\n\n\n\n OrDrain::A(Duplicate(file_fmt, term_fmt).fuse())\n\n } else {\n\n OrDrain::B(term_fmt.fuse())\n\n };\n\n\n\n let env_drain = slog_envlogger::LogBuilder::new(drain_decorator)\n\n .filter(None, FilterLevel::Info)\n\n .parse(env::var(\"RUST_LOG\").unwrap_or_default().as_str())\n\n .build();\n\n\n\n let drain = Async::new(env_drain.fuse())\n", "file_path": "devolutions-gateway/src/logger.rs", "rank": 51, "score": 181730.55299500574 }, { "content": "type X224FutureTransport = Framed<TlsStream<TcpStream>, DataTransport>;\n\n\n\npub struct McsFuture {\n\n sequence_state: McsSequenceState,\n\n channels_to_join: StaticChannels,\n\n joined_channels: Option<StaticChannels>,\n\n}\n\n\n\nimpl McsFuture {\n\n pub fn new(channels_to_join: StaticChannels) -> Self {\n\n let joined_channels =\n\n StaticChannels::with_capacity_and_hasher(channels_to_join.len(), channels_to_join.hasher().clone());\n\n Self {\n\n sequence_state: McsSequenceState::ErectDomainRequest,\n\n channels_to_join,\n\n joined_channels: Some(joined_channels),\n\n }\n\n }\n\n}\n\n\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/mcs.rs", "rank": 52, "score": 179468.47119141574 }, { "content": "enum ConnectionSequenceFutureState {\n\n NegotiationWithClient(NegotiationWithClientT),\n\n NlaWithClient(NlaWithClientT),\n\n ConnectToServer(ConnectToServerT),\n\n NegotiationWithServer(NegotiationWithServerT),\n\n NlaWithServer(NlaWithServerT),\n\n McsInitial(McsInitialT),\n\n Mcs(McsT),\n\n PostMcs(PostMcsT),\n\n Finalization(FinalizationT),\n\n}\n\n\n", "file_path": "devolutions-gateway/src/rdp/connection_sequence_future.rs", "rank": 53, "score": 177710.40549246853 }, { "content": "fn auth_identity_to_credentials(auth_identity: sspi::AuthIdentity) -> ironrdp::rdp::Credentials {\n\n ironrdp::rdp::Credentials {\n\n username: auth_identity.username,\n\n password: auth_identity.password,\n\n domain: auth_identity.domain,\n\n }\n\n}\n\n\n", "file_path": "jet-proto/tests/rdp.rs", "rank": 54, "score": 177675.2736372257 }, { "content": "pub fn load_private_key(config: &CertificateConfig) -> io::Result<rustls::PrivateKey> {\n\n let mut pkcs8_keys = load_pkcs8_private_key(config)?;\n\n\n\n // prefer to load pkcs8 keys\n\n if !pkcs8_keys.is_empty() {\n\n Ok(pkcs8_keys.remove(0))\n\n } else {\n\n let mut rsa_keys = load_rsa_private_key(config)?;\n\n\n\n assert!(!rsa_keys.is_empty());\n\n Ok(rsa_keys.remove(0))\n\n }\n\n}\n\n\n", "file_path": "devolutions-gateway/src/utils.rs", "rank": 55, "score": 175677.22258936698 }, { "content": "struct RdpServer {\n\n routing_addr: &'static str,\n\n identities_proxy: IdentitiesProxy,\n\n}\n\n\n", "file_path": "jet-proto/tests/rdp.rs", "rank": 56, "score": 175372.64794953482 }, { "content": "fn write_request<S>(writer: &mut S, dest: &DestAddr) -> io::Result<()>\n\nwhere\n\n S: Write,\n\n{\n\n let host = match dest {\n\n DestAddr::Ip(addr) => addr.to_string(),\n\n DestAddr::Domain(domain, port) => {\n\n format!(\"{}:{}\", domain, port)\n\n }\n\n };\n\n\n\n writer.write_all(b\"CONNECT \")?;\n\n writer.write_all(host.as_bytes())?;\n\n writer.write_all(b\" HTTP/1.1\\r\\n\")?;\n\n\n\n writer.write_all(b\"Host: \")?;\n\n writer.write_all(host.as_bytes())?;\n\n writer.write_all(b\"\\r\\n\")?;\n\n\n\n writer.write_all(b\"Proxy-Connection: Keep-Alive\\r\\n\")?;\n", "file_path": "jetsocat/proxy/src/http.rs", "rank": 57, "score": 175139.71960094952 }, { "content": "type TsRequestFutureTransport = Framed<TlsStream<TcpStream>, TsRequestTransport>;\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/nla.rs", "rank": 58, "score": 174900.2024904326 }, { "content": "pub fn load_certs(config: &CertificateConfig) -> io::Result<Vec<rustls::Certificate>> {\n\n if let Some(filename) = &config.certificate_file {\n\n let certfile = fs::File::open(filename).unwrap_or_else(|_| panic!(\"cannot open certificate file {}\", filename));\n\n let mut reader = BufReader::new(certfile);\n\n\n\n rustls::internal::pemfile::certs(&mut reader)\n\n .map_err(|()| io::Error::new(io::ErrorKind::InvalidData, \"Failed to parse certificate\"))\n\n } else if let Some(data) = &config.certificate_data {\n\n load_certs_from_data(data)\n\n .map_err(|()| io::Error::new(io::ErrorKind::InvalidData, \"Failed to parse certificate data\"))\n\n } else {\n\n let certfile = include_bytes!(\"../cert/publicCert.pem\");\n\n let mut reader = BufReader::new(certfile.as_ref());\n\n\n\n rustls::internal::pemfile::certs(&mut reader)\n\n .map_err(|()| io::Error::new(io::ErrorKind::InvalidData, \"Failed to parse certificate\"))\n\n }\n\n}\n\n\n", "file_path": "devolutions-gateway/src/utils.rs", "rank": 59, "score": 174523.2914383387 }, { "content": "pub fn is_encrypted(token: &str) -> bool {\n\n let num_dots = token.chars().fold(0, |acc, c| if c == '.' { acc + 1 } else { acc });\n\n num_dots == 4\n\n}\n\n\n", "file_path": "devolutions-gateway/src/preconnection_pdu.rs", "rank": 60, "score": 172452.6475568068 }, { "content": "fn get_dvc_manager_with_got_create_request_pdu() -> DvcManager {\n\n let mut dvc_manager = DvcManager::with_allowed_channels(vec![CHANNEL_NAME.to_string()]);\n\n dvc_manager\n\n .process(PduSource::Server, DRDYNVC_WITH_CREATE_REQUEST_PACKET.as_ref())\n\n .unwrap();\n\n\n\n let channel = dvc_manager.pending_dynamic_channels.get(&CHANNEL_ID).unwrap();\n\n assert_eq!(CHANNEL_NAME, channel.name);\n\n\n\n assert!(dvc_manager.dynamic_channels.is_empty());\n\n\n\n dvc_manager\n\n}\n", "file_path": "devolutions-gateway/src/rdp/dvc_manager/tests.rs", "rank": 61, "score": 171890.09696947795 }, { "content": "type SendFuture<T, U> = Box<dyn Future<Output = Result<Framed<T, U>, io::Error>> + Send + 'static>;\n\n\n", "file_path": "devolutions-gateway/src/rdp/sequence_future.rs", "rank": 62, "score": 164396.32838505847 }, { "content": "fn resolve_rdp_routing_mode(claims: &JetAssociationTokenClaims) -> Result<RdpRoutingMode, io::Error> {\n\n const DEFAULT_ROUTING_HOST_SCHEME: &str = \"tcp://\";\n\n const DEFAULT_RDP_PORT: u16 = 3389;\n\n\n\n if !claims.jet_ap.is_rdp() {\n\n return Err(io::Error::new(\n\n io::ErrorKind::Other,\n\n format!(\n\n \"Expected RDP association, but found a different application protocol claim: {:?}\",\n\n claims.jet_ap\n\n ),\n\n ));\n\n }\n\n\n\n match &claims.jet_cm {\n\n ConnectionMode::Rdv => Ok(RdpRoutingMode::TcpRendezvous(claims.jet_aid)),\n\n ConnectionMode::Fwd { dst_hst, creds } => {\n\n let route_url = if dst_hst.starts_with(DEFAULT_ROUTING_HOST_SCHEME) {\n\n dst_hst.to_owned()\n\n } else {\n", "file_path": "devolutions-gateway/src/rdp.rs", "rank": 63, "score": 163987.60180206742 }, { "content": "pub fn create_context(config: Arc<Config>, logger: slog::Logger) -> Result<GatewayContext, &'static str> {\n\n let tcp_listeners: Vec<Url> = config\n\n .listeners\n\n .iter()\n\n .filter_map(|listener| {\n\n if listener.internal_url.scheme() == \"tcp\" {\n\n Some(listener.internal_url.clone())\n\n } else {\n\n None\n\n }\n\n })\n\n .collect();\n\n\n\n let websocket_listeners: Vec<Url> = config\n\n .listeners\n\n .iter()\n\n .filter_map(|listener| {\n\n if listener.internal_url.scheme() == \"ws\" || listener.internal_url.scheme() == \"wss\" {\n\n Some(listener.internal_url.clone())\n\n } else {\n", "file_path": "devolutions-gateway/src/service.rs", "rank": 64, "score": 161087.43169927402 }, { "content": "pub fn update_framed_codec<Io, OldCodec, NewCodec, OldDecodedType, NewDecodedType>(\n\n framed: Framed<Io, OldCodec>,\n\n codec: NewCodec,\n\n) -> Framed<Io, NewCodec>\n\nwhere\n\n Io: AsyncRead + AsyncWrite,\n\n OldCodec: Decoder + Encoder<OldDecodedType>,\n\n NewCodec: Decoder + Encoder<NewDecodedType>,\n\n{\n\n let FramedParts { io, read_buf, .. } = framed.into_parts();\n\n\n\n let mut new_parts = FramedParts::new(io, codec);\n\n new_parts.read_buf = read_buf;\n\n\n\n Framed::from_parts(new_parts)\n\n}\n\n\n", "file_path": "devolutions-gateway/src/utils.rs", "rank": 65, "score": 160513.21381177194 }, { "content": "fn read_dvc_pdu(\n\n check_dvc: impl Fn(BytesMut),\n\n mut tls_stream: &mut (impl io::Write + io::Read),\n\n drdynvc_channel_id: u16,\n\n) {\n\n let mut buffer = read_stream_buffer(&mut tls_stream);\n\n match read_x224_data_pdu::<McsPdu>(&mut buffer) {\n\n McsPdu::SendDataRequest(data_context) => {\n\n assert_eq!(CHANNEL_INITIATOR_ID, data_context.initiator_id);\n\n assert_eq!(drdynvc_channel_id, data_context.channel_id);\n\n\n\n let channel_header =\n\n vc::ChannelPduHeader::from_buffer(buffer.as_ref()).expect(\"failed to read channel header\");\n\n buffer.advance(channel_header.buffer_length());\n\n\n\n assert_eq!(channel_header.total_length, buffer.len() as u32);\n\n assert!(channel_header\n\n .flags\n\n .contains(vc::ChannelControlFlags::FLAG_FIRST | vc::ChannelControlFlags::FLAG_LAST));\n\n\n\n check_dvc(buffer);\n\n }\n\n pdu => panic!(\"Got unexpected MCS PDU: {:?}\", pdu),\n\n };\n\n}\n", "file_path": "jet-proto/tests/rdp.rs", "rank": 66, "score": 157738.87531832693 }, { "content": "enum NlaWithServerFutureState {\n\n Tls(Connect<TcpStream>),\n\n CredSsp(CredSspWithServerFutureT),\n\n EarlyUserAuthResult(Pin<EarlyServerUserAuthResultFuture>),\n\n}\n\n\n\nasync fn make_client_early_user_auth_future(\n\n mut transport: EarlyUserAuthResultFutureTransport,\n\n) -> Result<EarlyUserAuthResultFutureTransport, io::Error> {\n\n Pin::new(&mut transport).send(EarlyUserAuthResult::Success).await?;\n\n Ok(transport)\n\n}\n\n\n\nasync fn make_server_early_user_auth_future(\n\n transport: EarlyUserAuthResultFutureTransport,\n\n) -> (\n\n Option<Result<EarlyUserAuthResult, io::Error>>,\n\n EarlyUserAuthResultFutureTransport,\n\n) {\n\n transport.into_future().await\n\n}\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/nla.rs", "rank": 67, "score": 156640.31360968546 }, { "content": "enum NlaWithClientFutureState {\n\n Tls(Accept<TcpStream>),\n\n CredSsp(NlaWithClientFutureT),\n\n EarlyUserAuthResult(Pin<EarlyClientUserAuthResultFuture>),\n\n}\n\n\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/nla.rs", "rank": 68, "score": 156191.01394950677 }, { "content": "pub fn error_kind_to_reason_code(e: std::io::ErrorKind) -> ReasonCode {\n\n match e {\n\n std::io::ErrorKind::ConnectionRefused => ReasonCode::CONNECTION_REFUSED,\n\n _ => ReasonCode::GENERAL_FAILURE,\n\n }\n\n}\n", "file_path": "jetsocat/src/jmux/mod.rs", "rank": 69, "score": 156076.20952958317 }, { "content": "fn get_tpkt_tpdu_messages(mut data: &[u8]) -> (Vec<&[u8]>, usize) {\n\n let mut tpkt_tpdu_messages = Vec::new();\n\n let mut messages_len = 0;\n\n\n\n loop {\n\n match TpktHeader::from_buffer(data) {\n\n Ok(TpktHeader { length }) => {\n\n // TPKT&TPDU\n\n if data.len() >= length as usize {\n\n let (new_message, new_data) = data.split_at(length);\n\n data = new_data;\n\n messages_len += new_message.len();\n\n tpkt_tpdu_messages.push(new_message);\n\n } else {\n\n break;\n\n }\n\n }\n\n Err(NegotiationError::TpktVersionError) => {\n\n // Fast-Path, need to skip\n\n match FastPathHeader::from_buffer(data) {\n", "file_path": "devolutions-gateway/src/interceptor/rdp.rs", "rank": 70, "score": 155271.79289156685 }, { "content": "fn run_client() -> Child {\n\n let mut client_command = Command::new(IRONRDP_CLIENT_PATH);\n\n client_command\n\n .arg(JET_PROXY_SERVER_ADDR)\n\n .args(&[\"--security_protocol\", \"hybrid\"])\n\n .args(&[\"--username\", PROXY_CREDENTIALS.username.as_str()])\n\n .args(&[\"--password\", PROXY_CREDENTIALS.password.as_str()]);\n\n\n\n if let Some(ref domain) = PROXY_CREDENTIALS.domain {\n\n client_command.args(&[\"--domain\", domain]);\n\n }\n\n\n\n client_command.spawn().expect(\"failed to run IronRDP client\")\n\n}\n\n\n\n// NOTE: The following test is disabled by default as it requires specific environment with\n\n// ironrdp_client executable in PATH variable\n", "file_path": "jet-proto/tests/rdp.rs", "rank": 71, "score": 155222.90581528295 }, { "content": "fn encode_and_write_finalization_pdu(\n\n pdu: rdp::ShareDataPdu,\n\n initiator_id: u16,\n\n channel_id: u16,\n\n mut stream: impl io::Write,\n\n) {\n\n let share_data_header = rdp::ShareDataHeader {\n\n share_data_pdu: pdu,\n\n stream_priority: rdp::StreamPriority::Medium,\n\n compression_flags: rdp::CompressionFlags::empty(),\n\n compression_type: rdp::CompressionType::K8,\n\n };\n\n\n\n let share_control_header = rdp::ShareControlHeader {\n\n share_control_pdu: rdp::ShareControlPdu::Data(share_data_header),\n\n pdu_source: SERVER_PDU_SOURCE,\n\n share_id: SHARE_ID,\n\n };\n\n encode_and_write_send_data_context_pdu(share_control_header, initiator_id, channel_id, &mut stream);\n\n}\n\n\n", "file_path": "jet-proto/tests/rdp.rs", "rank": 72, "score": 155129.0450177032 }, { "content": "fn read_and_parse_finalization_pdu(\n\n mut buffer: &mut BytesMut,\n\n expected_initiator_id: u16,\n\n expected_channel_id: u16,\n\n) -> rdp::ShareDataPdu {\n\n let share_control_header = read_and_parse_send_data_context_pdu::<ShareControlHeader>(\n\n &mut buffer,\n\n expected_initiator_id,\n\n expected_channel_id,\n\n );\n\n if share_control_header.share_id != SHARE_ID {\n\n panic!(\n\n \"Got unexpected Share ID for Finalization PDU: {} != {}\",\n\n SHARE_ID, share_control_header.share_id\n\n );\n\n }\n\n\n\n if let rdp::ShareControlPdu::Data(rdp::ShareDataHeader {\n\n share_data_pdu,\n\n compression_flags,\n", "file_path": "jet-proto/tests/rdp.rs", "rank": 73, "score": 155129.0450177032 }, { "content": "pub trait JetSink<SinkItem>: Sink<SinkItem> {\n\n fn nb_bytes_written(self: Pin<&Self>) -> u64;\n\n fn finished(self: Pin<&mut Self>) -> bool;\n\n}\n\n\n", "file_path": "devolutions-gateway/src/transport/mod.rs", "rank": 74, "score": 153118.39705143636 }, { "content": "fn accept_tcp_stream(addr: &str) -> TcpStream {\n\n let listener_addr = addr.parse::<SocketAddr>().expect(\"failed to parse an addr\");\n\n let listener = TcpListener::bind(&listener_addr).expect(\"failed to bind to stream\");\n\n loop {\n\n match listener.accept() {\n\n Ok((stream, _addr)) => return stream,\n\n Err(_) => thread::sleep(Duration::from_millis(10)),\n\n }\n\n }\n\n}\n\n\n", "file_path": "jet-proto/tests/rdp.rs", "rank": 75, "score": 153103.4337410632 }, { "content": "pub fn parse_auth_header(auth_header: &str) -> Option<(AuthHeaderType, &str)> {\n\n let auth_vec = auth_header.trim().split(' ').collect::<Vec<&str>>();\n\n\n\n if auth_vec.len() >= 2 {\n\n match auth_vec[0].to_lowercase().as_ref() {\n\n \"bearer\" => Some((AuthHeaderType::Bearer, auth_vec[1])),\n\n \"signature\" => Some((AuthHeaderType::Signature, auth_header)),\n\n unexpected => {\n\n warn!(\"unexpected auth method: {}\", unexpected);\n\n None\n\n }\n\n }\n\n } else {\n\n warn!(\"invalid auth header: {}\", auth_header);\n\n None\n\n }\n\n}\n\n\n", "file_path": "devolutions-gateway/src/http/middlewares/auth.rs", "rank": 76, "score": 150717.59359558864 }, { "content": "struct JetSinkImpl<T: AsyncWrite> {\n\n stream: WriteHalf<T>,\n\n nb_bytes_written: Arc<AtomicU64>,\n\n bytes_to_write: usize,\n\n peer_addr_str: String,\n\n buffer: BipBufferReader,\n\n}\n\n\n\nimpl<T: AsyncWrite> JetSinkImpl<T> {\n\n fn new(\n\n stream: WriteHalf<T>,\n\n nb_bytes_written: Arc<AtomicU64>,\n\n peer_addr: Option<SocketAddr>,\n\n buffer: BipBufferReader,\n\n ) -> Self {\n\n Self {\n\n stream,\n\n nb_bytes_written,\n\n bytes_to_write: 0,\n\n peer_addr_str: peer_addr.map_or(\"Unknown\".to_string(), |addr| addr.to_string()),\n", "file_path": "devolutions-gateway/src/transport/mod.rs", "rank": 77, "score": 150497.82664660155 }, { "content": "pub trait SequenceFutureProperties<T, U, R>\n\nwhere\n\n T: AsyncRead + AsyncWrite + Send + Unpin + 'static,\n\n U: Decoder + Encoder<R> + Send + Unpin + 'static,\n\n R: 'static,\n\n{\n\n type Item;\n\n\n\n fn process_pdu(&mut self, pdu: <U as Decoder>::Item) -> io::Result<Option<R>>;\n\n fn return_item(&mut self, client: Option<Framed<T, U>>, server: Option<Framed<T, U>>) -> Self::Item;\n\n fn next_sender(&self) -> NextStream;\n\n fn next_receiver(&self) -> NextStream;\n\n fn sequence_finished(&self, future_state: FutureState) -> bool;\n\n}\n\n\n\npub struct SequenceFuture<F, T, U, R>\n\nwhere\n\n F: SequenceFutureProperties<T, U, R> + Send + Unpin,\n\n T: AsyncRead + AsyncWrite + Send + Unpin + 'static,\n\n U: Decoder + Encoder<R> + Send + Unpin + 'static,\n", "file_path": "devolutions-gateway/src/rdp/sequence_future.rs", "rank": 78, "score": 150415.29161495148 }, { "content": "#[test]\n\nfn parses_tpkt_channel_pdu() {\n\n let packet = TPKT_SERVER_MCS_DATA_INDICATION_DVC_CREATE_REQUEST_PACKET;\n\n\n\n match parse_tpkt_tpdu_message(packet.as_ref()).unwrap() {\n\n ParsedTpktPtdu::VirtualChannel { id, buffer } => {\n\n assert_eq!(DRDYNVC_CHANNEL_ID, id);\n\n assert_eq!(CHANNEL_DVC_CREATE_REQUEST_PACKET.as_ref(), buffer);\n\n }\n\n _ => panic!(\"Unexpected DisconnectionRequest\"),\n\n }\n\n}\n\n\n", "file_path": "devolutions-gateway/src/interceptor/rdp/tests.rs", "rank": 79, "score": 150219.34106083337 }, { "content": "#[test]\n\nfn does_not_parse_fast_path_pdu() {\n\n let packet = FASTPATH_PACKET;\n\n\n\n match parse_tpkt_tpdu_message(&packet) {\n\n Err(_) => (),\n\n res => panic!(\"Expected error, got: {:?}\", res),\n\n }\n\n}\n\n\n", "file_path": "devolutions-gateway/src/interceptor/rdp/tests.rs", "rank": 80, "score": 150219.34106083337 }, { "content": "#[test]\n\nfn reads_multiple_packets_after_incomplete_call() {\n\n let first_packet = TPKT_CLIENT_CONNECTION_REQUEST_PACKET;\n\n let second_packet = FASTPATH_PACKET;\n\n let third_packet = TPKT_CLIENT_CONNECTION_REQUEST_PACKET;\n\n let (first_packet_first_part, second_packet_second_part) = first_packet.split_at(3);\n\n let mut data = first_packet_first_part.to_vec();\n\n\n\n let (messages, data_length) = get_tpkt_tpdu_messages(&data);\n\n assert!(messages.is_empty());\n\n assert_eq!(0, data_length);\n\n\n\n data.extend_from_slice(second_packet_second_part);\n\n data.extend_from_slice(second_packet.as_ref());\n\n data.extend_from_slice(third_packet.as_ref());\n\n let (messages, data_length) = get_tpkt_tpdu_messages(&data);\n\n\n\n assert_eq!(2, messages.len());\n\n assert_eq!(first_packet.as_ref(), messages.first().unwrap().as_ref());\n\n assert_eq!(third_packet.as_ref(), messages.last().unwrap().as_ref());\n\n assert_eq!(data.len(), data_length);\n\n}\n\n\n", "file_path": "devolutions-gateway/src/interceptor/rdp/tests.rs", "rank": 81, "score": 148037.42908845257 }, { "content": "#[test]\n\nfn does_not_read_incomplete_packet_on_multiple_calls() {\n\n let mut data = TPKT_CLIENT_CONNECTION_REQUEST_PACKET.to_vec();\n\n data.truncate(3);\n\n\n\n let (messages, _) = get_tpkt_tpdu_messages(&data);\n\n assert!(messages.is_empty());\n\n\n\n let (messages, _) = get_tpkt_tpdu_messages(&data);\n\n assert!(messages.is_empty());\n\n}\n\n\n", "file_path": "devolutions-gateway/src/interceptor/rdp/tests.rs", "rank": 82, "score": 148037.42908845257 }, { "content": "#[test]\n\nfn does_not_parse_unsuitable_tpkt_mcs_pdu() {\n\n let packet = TPKT_CLIENT_MCS_ATTACH_USER_REQUEST_PACKET;\n\n\n\n match parse_tpkt_tpdu_message(packet.as_ref()) {\n\n Err(_) => (),\n\n res => panic!(\"Expected error, got: {:?}\", res),\n\n }\n\n}\n\n\n", "file_path": "devolutions-gateway/src/interceptor/rdp/tests.rs", "rank": 83, "score": 147907.43490515652 }, { "content": "pub fn run_proxy(\n\n proxy_addr: &str,\n\n websocket_url: Option<&str>,\n\n routing_url: Option<&str>,\n\n identities_file: Option<&str>,\n\n) -> KillOnDrop {\n\n let mut proxy_command = Command::new(bin());\n\n\n\n proxy_command\n\n .env(\"RUST_LOG\", \"DEBUG\")\n\n .args(&[\"--listener\", format!(\"tcp://{}\", proxy_addr).as_str()]);\n\n\n\n if let Some(websocket_url) = websocket_url {\n\n proxy_command.arg(\"-l\").arg(websocket_url);\n\n }\n\n\n\n if let Some(url) = routing_url {\n\n proxy_command.args(&[\"--routing-url\", url]);\n\n }\n\n\n", "file_path": "jet-proto/tests/common.rs", "rank": 84, "score": 147343.4985050004 }, { "content": "fn process_cred_ssp_phase_with_reply_needed<C>(\n\n ts_request: credssp::TsRequest,\n\n cred_ssp_context: &mut credssp::CredSspServer<C>,\n\n tls_stream: &mut (impl io::Write + io::Read),\n\n) where\n\n C: credssp::CredentialsProxy<AuthenticationData = sspi::AuthIdentity>,\n\n{\n\n let reply = cred_ssp_context.process(ts_request);\n\n match reply {\n\n Ok(credssp::ServerState::ReplyNeeded(ts_request)) => {\n\n let mut ts_request_buffer = Vec::with_capacity(ts_request.buffer_len() as usize);\n\n ts_request\n\n .encode_ts_request(&mut ts_request_buffer)\n\n .expect(\"failed to encode TSRequest\");\n\n\n\n tls_stream\n\n .write_all(&ts_request_buffer)\n\n .expect(\"failed to send CredSSP message\");\n\n }\n\n _ => panic!(\"the CredSSP server has returned unexpected result: {:?}\", reply),\n\n }\n\n}\n\n\n", "file_path": "jet-proto/tests/rdp.rs", "rank": 85, "score": 145912.67632609344 }, { "content": "fn read_and_parse_send_data_context_pdu<T>(\n\n mut buffer: &mut BytesMut,\n\n expected_initiator_id: u16,\n\n expected_channel_id: u16,\n\n) -> T\n\nwhere\n\n T: PduParsing,\n\n T::Error: fmt::Debug,\n\n{\n\n match read_x224_data_pdu::<McsPdu>(&mut buffer) {\n\n mcs::McsPdu::SendDataRequest(send_data_context) => {\n\n if send_data_context.initiator_id != expected_initiator_id {\n\n panic!(\n\n \"Unexpected Send Data Context PDU initiator ID: {} != {}\",\n\n expected_initiator_id, send_data_context.initiator_id\n\n );\n\n }\n\n if send_data_context.channel_id != expected_channel_id {\n\n panic!(\n\n \"Unexpected Send Data Context PDU channel ID: {} != {}\",\n", "file_path": "jet-proto/tests/rdp.rs", "rank": 86, "score": 145811.21732873647 }, { "content": "fn set_stream_option(stream: &TcpStream, logger: &Logger) {\n\n if let Err(e) = stream.set_nodelay(true) {\n\n slog_error!(logger, \"set_nodelay on TcpStream failed: {}\", e);\n\n }\n\n}\n\n\n\nasync fn start_tcp_server(\n\n url: Url,\n\n config: Arc<Config>,\n\n jet_associations: JetAssociationsMap,\n\n tls_acceptor: TlsAcceptor,\n\n tls_public_key: Vec<u8>,\n\n logger: Logger,\n\n) -> Result<(), String> {\n\n use futures::FutureExt as _;\n\n\n\n info!(\"Starting TCP jet server ({})...\", url);\n\n\n\n let socket_addr = url_to_socket_addr(&url).expect(\"invalid url\");\n\n\n", "file_path": "devolutions-gateway/src/service.rs", "rank": 87, "score": 145681.94522870303 }, { "content": "fn main() -> io::Result<()> {\n\n let opt = Opt::from_args();\n\n let (associations_sender, associations_receiver) = mpsc::channel();\n\n let barrier = Arc::new(Barrier::new(2));\n\n let barrier_s = barrier.clone();\n\n\n\n let opt_s = opt.clone();\n\n let server_handle = thread::Builder::new()\n\n .name(\"server\".to_string())\n\n .spawn(move || run_servers(opt_s, associations_sender, barrier_s))?;\n\n\n\n run_clients(opt, associations_receiver, barrier)?;\n\n\n\n server_handle.join().unwrap()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "benchmark/src/main.rs", "rank": 88, "score": 145446.89766187462 }, { "content": "fn handle_send_data_request(\n\n pdu: BytesMut,\n\n sequence_state: DvcCapabilitiesState,\n\n dvc_manager: &mut DvcManager,\n\n) -> io::Result<(DvcCapabilitiesState, BytesMut)> {\n\n let (next_state, dvc_pdu_buffer) = map_dvc_pdu(pdu, |mut dvc_data| {\n\n match (\n\n sequence_state,\n\n dvc::ClientPdu::from_buffer(dvc_data.as_ref(), dvc_data.len())?,\n\n ) {\n\n (\n\n DvcCapabilitiesState::ClientDvcCapabilitiesResponse,\n\n dvc::ClientPdu::CapabilitiesResponse(capabilities),\n\n ) => {\n\n debug!(\"Got client's DVC Capabilities Response PDU: {:?}\", capabilities);\n\n\n\n let caps_response_pdu = dvc::ClientPdu::CapabilitiesResponse(capabilities);\n\n\n\n dvc_data.resize(caps_response_pdu.buffer_length(), 0);\n\n caps_response_pdu.to_buffer(dvc_data.as_mut())?;\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/dvc_capabilities.rs", "rank": 89, "score": 144883.8307895901 }, { "content": "fn handle_send_data_indication(\n\n pdu: BytesMut,\n\n sequence_state: DvcCapabilitiesState,\n\n dvc_manager: &mut DvcManager,\n\n) -> io::Result<(DvcCapabilitiesState, BytesMut)> {\n\n let (next_state, dvc_pdu_buffer) = map_dvc_pdu(pdu, |mut dvc_data| {\n\n match (\n\n sequence_state,\n\n dvc::ServerPdu::from_buffer(dvc_data.as_ref(), dvc_data.len())?,\n\n ) {\n\n (DvcCapabilitiesState::ServerDvcCapabilitiesRequest, dvc::ServerPdu::CapabilitiesRequest(capabilities)) => {\n\n debug!(\"Got server's DVC Capabilities Request PDU: {:?}\", capabilities);\n\n\n\n let caps_request_pdu = dvc::ServerPdu::CapabilitiesRequest(capabilities);\n\n\n\n dvc_data.resize(caps_request_pdu.buffer_length(), 0);\n\n caps_request_pdu.to_buffer(dvc_data.as_mut())?;\n\n\n\n Ok((DvcCapabilitiesState::ClientDvcCapabilitiesResponse, dvc_data))\n\n }\n", "file_path": "devolutions-gateway/src/rdp/sequence_future/dvc_capabilities.rs", "rank": 90, "score": 144883.8307895901 }, { "content": "fn run_servers(opt: Opt, associations_sender: mpsc::Sender<Uuid>, barrier: Arc<Barrier>) -> io::Result<()> {\n\n let msg = vec![0; opt.server_block_size];\n\n let mut buf = vec![0; opt.client_block_size];\n\n let host = opt.connect_addr.ip().to_string();\n\n\n\n for _ in 0..opt.tests {\n\n let mut stream = TcpStream::connect(opt.connect_addr)?;\n\n let association = jet_proto::connect_as_server(&mut stream, host.clone())?;\n\n associations_sender\n\n .send(association)\n\n .expect(\"failed to send association\");\n\n barrier.wait();\n\n\n\n for _ in 0..opt.count {\n\n match opt.mode {\n\n Mode::Concurrent => {\n\n stream.write_all(&msg)?;\n\n stream.read_exact(&mut buf.as_mut())?;\n\n }\n\n _ => {\n", "file_path": "benchmark/src/main.rs", "rank": 91, "score": 143388.51753473637 }, { "content": "pub fn forward_action(c: &Context) {\n\n let res = ForwardArgs::parse(c).and_then(|args| {\n\n let log = setup_logger(args.common.logging);\n\n\n\n let cfg = jetsocat::ForwardCfg {\n\n pipe_a_mode: args.pipe_a_mode,\n\n pipe_b_mode: args.pipe_b_mode,\n\n repeat_count: args.repeat_count,\n\n proxy_cfg: args.common.proxy_cfg,\n\n };\n\n\n\n let forward_log = log.new(o!(\"action\" => \"forward\"));\n\n\n\n run(forward_log.clone(), jetsocat::forward(cfg, forward_log))\n\n });\n\n exit(res);\n\n}\n\n\n\n// jmux-proxy\n\n\n\nconst JMUX_PROXY_SUBCOMMAND: &str = \"jmux-proxy\";\n\n\n", "file_path": "jetsocat/src/main.rs", "rank": 92, "score": 139986.81869709265 }, { "content": "pub fn get_mask_value() -> u8 {\n\n unsafe {\n\n JET_MASK_INIT.call_once(|| {\n\n if let Ok(mask) = env::var(\"JET_MSG_MASK\") {\n\n let mask = mask.trim_start_matches(\"0x\");\n\n if let Ok(mask) = u8::from_str_radix(mask, 16) {\n\n JET_MSG_MASK = mask;\n\n }\n\n }\n\n });\n\n JET_MSG_MASK\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq)]\n\npub enum JetMessage {\n\n JetTestReq(JetTestReq),\n\n JetTestRsp(JetTestRsp),\n\n JetAcceptReq(JetAcceptReq),\n\n JetAcceptRsp(JetAcceptRsp),\n\n JetConnectReq(JetConnectReq),\n\n JetConnectRsp(JetConnectRsp),\n\n}\n\n\n", "file_path": "jet-proto/src/lib.rs", "rank": 93, "score": 139983.98929749284 }, { "content": "fn run_clients(opt: Opt, associations_receiver: mpsc::Receiver<Uuid>, barrier: Arc<Barrier>) -> std::io::Result<()> {\n\n let msg = vec![0; opt.client_block_size];\n\n let mut buf = vec![0; opt.server_block_size];\n\n let host = opt.connect_addr.ip().to_string();\n\n\n\n let total_time_ms: u128 = (0..opt.tests)\n\n .map(|i| {\n\n let mut stream = std::net::TcpStream::connect(opt.connect_addr).unwrap();\n\n let association = associations_receiver.recv().expect(\"failed to receive association\");\n\n jet_proto::connect_as_client(&mut stream, host.clone(), association).expect(\"failed to connect as client\");\n\n barrier.wait();\n\n\n\n let now = std::time::Instant::now();\n\n for _ in 0..opt.count {\n\n match opt.mode {\n\n Mode::Concurrent => {\n\n stream.write_all(&msg).unwrap();\n\n stream.read_exact(&mut buf.as_mut()).unwrap();\n\n }\n\n _ => {\n", "file_path": "benchmark/src/main.rs", "rank": 94, "score": 139740.74129659295 }, { "content": "fn process_req(req: &Request<Body>) -> Response<Body> {\n\n /*\n\n Source: https://gist.github.com/bluetech/192c74b9c4ae541747718ac4f4e20a14\n\n Author: Ran Benita<bluetech> (ran234@gmail.com)\n\n */\n\n\n\n fn convert_key(input: &[u8]) -> String {\n\n const WS_GUID: &[u8] = b\"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\";\n\n let mut digest = sha1::Sha1::new();\n\n digest.update(input);\n\n digest.update(WS_GUID);\n\n base64::encode(&digest.digest().bytes())\n\n }\n\n fn connection_has(value: &header::HeaderValue, needle: &str) -> bool {\n\n if let Ok(v) = value.to_str() {\n\n v.split(',').any(|s| s.trim().eq_ignore_ascii_case(needle))\n\n } else {\n\n false\n\n }\n\n }\n", "file_path": "devolutions-gateway/src/websocket_client.rs", "rank": 95, "score": 139009.17643233156 }, { "content": "pub fn jmux_proxy_action(c: &Context) {\n\n let res = JmuxProxyArgs::parse(c).and_then(|args| {\n\n let log = setup_logger(args.common.logging);\n\n\n\n let cfg = jetsocat::JmuxProxyCfg {\n\n pipe_mode: args.pipe_mode,\n\n proxy_cfg: args.common.proxy_cfg,\n\n listener_modes: args.listener_modes,\n\n };\n\n\n\n let jmux_proxy_log = log.new(o!(\"action\" => JMUX_PROXY_SUBCOMMAND));\n\n\n\n run(jmux_proxy_log.clone(), jetsocat::jmux_proxy(cfg, jmux_proxy_log))\n\n });\n\n exit(res);\n\n}\n\n\n\n// args parsing\n\n\n", "file_path": "jetsocat/src/main.rs", "rank": 96, "score": 138226.79353672714 }, { "content": "fn get_server_session(cert_path: &str, priv_key_path: &str) -> rustls::ServerSession {\n\n let certs = load_certs(cert_path);\n\n let priv_key = load_private_key(priv_key_path);\n\n\n\n let client_no_auth = rustls::NoClientAuth::new();\n\n let mut server_config = rustls::ServerConfig::new(client_no_auth);\n\n server_config.set_single_cert(certs, priv_key).unwrap();\n\n\n\n let config_ref = Arc::new(server_config);\n\n\n\n rustls::ServerSession::new(&config_ref)\n\n}\n\n\n\nimpl RdpServer {\n\n fn new(routing_addr: &'static str, identities_proxy: IdentitiesProxy) -> Self {\n\n Self {\n\n routing_addr,\n\n identities_proxy,\n\n }\n\n }\n", "file_path": "jet-proto/tests/rdp.rs", "rank": 97, "score": 137800.1807987687 }, { "content": "#[cfg(not(feature = \"detect-proxy\"))]\n\npub fn detect_proxy() -> Option<ProxyConfig> {\n\n None\n\n}\n", "file_path": "jetsocat/src/proxy.rs", "rank": 98, "score": 136537.85191255534 } ]
Rust
linkerd/app/outbound/src/target.rs
19h/linkerd2-proxy
20619fb1782216df515cd7927c764cfa58b6e46c
use linkerd_app_core::{ metrics, profiles, proxy::{ api_resolve::{ConcreteAddr, Metadata}, resolve::map_endpoint::MapEndpoint, }, svc::{self, stack::Param}, tls, transport, transport_header, Addr, Conditional, Error, }; use std::net::SocketAddr; #[derive(Copy, Clone)] pub struct EndpointFromMetadata; #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub struct Accept<P> { pub orig_dst: SocketAddr, pub protocol: P, } #[derive(Clone)] pub struct Logical<P> { pub orig_dst: SocketAddr, pub profile: Option<profiles::Receiver>, pub protocol: P, } #[derive(Clone, Debug)] pub struct Concrete<P> { pub resolve: ConcreteAddr, pub logical: Logical<P>, } #[derive(Clone, Debug)] pub struct Endpoint<P> { pub addr: SocketAddr, pub target_addr: SocketAddr, pub tls: tls::ConditionalClientTls, pub metadata: Metadata, pub logical: Logical<P>, } impl<P> Param<SocketAddr> for Accept<P> { fn param(&self) -> SocketAddr { self.orig_dst } } impl<P> Param<Addr> for Accept<P> { fn param(&self) -> Addr { self.orig_dst.into() } } impl<P> Param<transport::labels::Key> for Accept<P> { fn param(&self) -> transport::labels::Key { const NO_TLS: tls::ConditionalServerTls = Conditional::None(tls::NoServerTls::Loopback); transport::labels::Key::accept(transport::labels::Direction::Out, NO_TLS, self.orig_dst) } } impl<P> From<(Option<profiles::Receiver>, Accept<P>)> for Logical<P> { fn from( ( profile, Accept { orig_dst, protocol, .. }, ): (Option<profiles::Receiver>, Accept<P>), ) -> Self { Self { profile, orig_dst, protocol, } } } impl<P> Param<Option<profiles::Receiver>> for Logical<P> { fn param(&self) -> Option<profiles::Receiver> { self.profile.clone() } } impl<P> Param<SocketAddr> for Logical<P> { fn param(&self) -> SocketAddr { self.orig_dst } } impl<P> Param<profiles::LogicalAddr> for Logical<P> { fn param(&self) -> profiles::LogicalAddr { profiles::LogicalAddr(self.addr()) } } impl<P> Logical<P> { pub fn addr(&self) -> Addr { self.profile .as_ref() .and_then(|p| p.borrow().name.clone()) .map(|n| Addr::from((n, self.orig_dst.port()))) .unwrap_or_else(|| self.orig_dst.into()) } } impl<P: PartialEq> PartialEq<Logical<P>> for Logical<P> { fn eq(&self, other: &Logical<P>) -> bool { self.orig_dst == other.orig_dst && self.protocol == other.protocol } } impl<P: Eq> Eq for Logical<P> {} impl<P: std::hash::Hash> std::hash::Hash for Logical<P> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.orig_dst.hash(state); self.protocol.hash(state); } } impl<P: std::fmt::Debug> std::fmt::Debug for Logical<P> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Logical") .field("orig_dst", &self.orig_dst) .field("protocol", &self.protocol) .field( "profile", &format_args!( "{}", if self.profile.is_some() { "Some(..)" } else { "None" } ), ) .finish() } } impl<P> Logical<P> { pub fn or_endpoint( reason: tls::NoClientTls, ) -> impl Fn(Self) -> Result<svc::Either<Self, Endpoint<P>>, Error> + Copy { move |logical: Self| { let should_resolve = match logical.profile.as_ref() { Some(p) => { let p = p.borrow(); p.endpoint.is_none() && (p.name.is_some() || !p.targets.is_empty()) } None => false, }; if should_resolve { Ok(svc::Either::A(logical)) } else { Ok(svc::Either::B(Endpoint::from_logical(reason)(logical))) } } } } impl<P> From<(ConcreteAddr, Logical<P>)> for Concrete<P> { fn from((resolve, logical): (ConcreteAddr, Logical<P>)) -> Self { Self { resolve, logical } } } impl<P> Param<ConcreteAddr> for Concrete<P> { fn param(&self) -> ConcreteAddr { self.resolve.clone() } } impl<P> Endpoint<P> { pub fn from_logical(reason: tls::NoClientTls) -> impl (Fn(Logical<P>) -> Self) + Clone { move |logical| { let target_addr = logical.orig_dst; match logical .profile .as_ref() .and_then(|p| p.borrow().endpoint.clone()) { None => Self { addr: logical.param(), metadata: Metadata::default(), tls: Conditional::None(reason), logical, target_addr, }, Some((addr, metadata)) => Self { addr, tls: EndpointFromMetadata::client_tls(&metadata), metadata, logical, target_addr, }, } } } pub fn from_accept(reason: tls::NoClientTls) -> impl (Fn(Accept<P>) -> Self) + Clone { move |accept| Self::from_logical(reason)(Logical::from((None, accept))) } pub fn identity_disabled(mut self) -> Self { self.tls = Conditional::None(tls::NoClientTls::Disabled); self } } impl<P> Param<transport::ConnectAddr> for Endpoint<P> { fn param(&self) -> transport::ConnectAddr { transport::ConnectAddr(self.addr) } } impl<P> Param<tls::ConditionalClientTls> for Endpoint<P> { fn param(&self) -> tls::ConditionalClientTls { self.tls.clone() } } impl<P> Param<transport::labels::Key> for Endpoint<P> { fn param(&self) -> transport::labels::Key { transport::labels::Key::OutboundConnect(self.param()) } } impl<P> Param<metrics::OutboundEndpointLabels> for Endpoint<P> { fn param(&self) -> metrics::OutboundEndpointLabels { metrics::OutboundEndpointLabels { authority: Some(self.logical.addr().to_http_authority()), labels: metrics::prefix_labels("dst", self.metadata.labels().iter()), server_id: self.tls.clone(), target_addr: self.target_addr, } } } impl<P> Param<metrics::EndpointLabels> for Endpoint<P> { fn param(&self) -> metrics::EndpointLabels { Param::<metrics::OutboundEndpointLabels>::param(self).into() } } impl<P: std::hash::Hash> std::hash::Hash for Endpoint<P> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.addr.hash(state); self.tls.hash(state); self.logical.orig_dst.hash(state); self.logical.protocol.hash(state); } } impl EndpointFromMetadata { fn client_tls(metadata: &Metadata) -> tls::ConditionalClientTls { let use_transport_header = metadata.opaque_transport_port().is_some() || metadata.authority_override().is_some(); metadata .identity() .cloned() .map(move |server_id| { Conditional::Some(tls::ClientTls { server_id, alpn: if use_transport_header { Some(tls::client::AlpnProtocols(vec![ transport_header::PROTOCOL.into() ])) } else { None }, }) }) .unwrap_or(Conditional::None( tls::NoClientTls::NotProvidedByServiceDiscovery, )) } } impl<P: Clone + std::fmt::Debug> MapEndpoint<Concrete<P>, Metadata> for EndpointFromMetadata { type Out = Endpoint<P>; fn map_endpoint( &self, concrete: &Concrete<P>, addr: SocketAddr, metadata: Metadata, ) -> Self::Out { tracing::trace!(%addr, ?metadata, ?concrete, "Resolved endpoint"); Endpoint { addr, tls: Self::client_tls(&metadata), metadata, logical: concrete.logical.clone(), target_addr: concrete.logical.orig_dst, } } }
use linkerd_app_core::{ metrics, profiles, proxy::{ api_resolve::{ConcreteAddr, Metadata}, resolve::map_endpoint::MapEndpoint, }, svc::{self, stack::Param}, tls, transport, transport_header, Addr, Conditional, Error, }; use std::net::SocketAddr; #[derive(Copy, Clone)] pub struct EndpointFromMetadata; #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub struct Accept<P> { pub orig_dst: SocketAddr, pub protocol: P, } #[derive(Clone)] pub struct Logical<P> { pub orig_dst: SocketAddr, pub profile: Option<profiles::Receiver>, pub protocol: P, } #[derive(Clone, Debug)] pub struct Concrete<P> { pub resolve: ConcreteAddr, pub logical: Logical<P>, } #[derive(Clone, Debug)] pub struct Endpoint<P> { pub addr: SocketAddr, pub target_addr: SocketAddr, pub tls: tls::ConditionalClientTls, pub metadata: Metadata, pub logical: Logical<P>, } impl<P> Param<SocketAddr> for Accept<P> { fn param(&self) -> SocketAddr { self.orig_dst } } impl<P> Param<Addr> for Accept<P> { fn param(&self) -> Addr { self.orig_dst.into() } } impl<P> Param<transport::labels::Key> for Accept<P> { fn param(&self) -> transport::labels::Key { const NO_TLS: tls::ConditionalServerTls = Conditional::None(tls::NoServerTls::Loopback); transport::labels::Key::accept(transport::labels::Direction::Out, NO_TLS, self.orig_dst) } } impl<P> From<(Option<profiles::Receiver>, Accept<P>)> for Logical<P> { fn from( ( profile, Accept { orig_dst, protocol, .. }, ): (Option<profiles::Receiver>, Accept<P>), ) -> Self { Self { profile, orig_dst, protocol, } } } impl<P> Param<Option<profiles::Receiver>> for Logical<P> { fn param(&self) -> Option<profiles::Receiver> { self.profile.clone() } } impl<P> Param<SocketAddr> for Logical<P> { fn param(&self) -> SocketAddr { self.orig_dst } } impl<P> Param<profiles::LogicalAddr> for Logical<P> { fn param(&self) -> profiles::LogicalAddr { profiles::LogicalAddr(self.addr()) } } impl<P> Logical<P> { pub fn addr(&self) -> Addr { self.profile .as_ref() .and_then(|p| p.borrow().name.clone()) .map(|n| Addr::from((n, self.orig_dst.port()))) .unwrap_or_else(|| self.orig_dst.into()) } } impl<P: PartialEq> PartialEq<Logical<P>> for Logical<P> { fn eq(&self, other: &Logical<P>) -> bool { self.orig_dst == other.orig_dst && self.protocol == other.protocol } } impl<P: Eq> Eq for Logical<P> {} impl<P: std::hash::Hash> std::hash::Hash for Logical<P> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.orig_dst.hash(state); self.protocol.hash(state); } } impl<P: std::fmt::Debug> std::fmt::Debug for Logical<P> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Logical") .field("orig_dst", &self.orig_dst) .field("protocol", &self.protocol) .field( "profile", &format_args!( "{}", if self.profile.is_some() { "Some(..)" } else { "None" } ), ) .finish() } } impl<P> Logical<P> { pub fn or_endpoint( reason: tls::No
} impl<P> From<(ConcreteAddr, Logical<P>)> for Concrete<P> { fn from((resolve, logical): (ConcreteAddr, Logical<P>)) -> Self { Self { resolve, logical } } } impl<P> Param<ConcreteAddr> for Concrete<P> { fn param(&self) -> ConcreteAddr { self.resolve.clone() } } impl<P> Endpoint<P> { pub fn from_logical(reason: tls::NoClientTls) -> impl (Fn(Logical<P>) -> Self) + Clone { move |logical| { let target_addr = logical.orig_dst; match logical .profile .as_ref() .and_then(|p| p.borrow().endpoint.clone()) { None => Self { addr: logical.param(), metadata: Metadata::default(), tls: Conditional::None(reason), logical, target_addr, }, Some((addr, metadata)) => Self { addr, tls: EndpointFromMetadata::client_tls(&metadata), metadata, logical, target_addr, }, } } } pub fn from_accept(reason: tls::NoClientTls) -> impl (Fn(Accept<P>) -> Self) + Clone { move |accept| Self::from_logical(reason)(Logical::from((None, accept))) } pub fn identity_disabled(mut self) -> Self { self.tls = Conditional::None(tls::NoClientTls::Disabled); self } } impl<P> Param<transport::ConnectAddr> for Endpoint<P> { fn param(&self) -> transport::ConnectAddr { transport::ConnectAddr(self.addr) } } impl<P> Param<tls::ConditionalClientTls> for Endpoint<P> { fn param(&self) -> tls::ConditionalClientTls { self.tls.clone() } } impl<P> Param<transport::labels::Key> for Endpoint<P> { fn param(&self) -> transport::labels::Key { transport::labels::Key::OutboundConnect(self.param()) } } impl<P> Param<metrics::OutboundEndpointLabels> for Endpoint<P> { fn param(&self) -> metrics::OutboundEndpointLabels { metrics::OutboundEndpointLabels { authority: Some(self.logical.addr().to_http_authority()), labels: metrics::prefix_labels("dst", self.metadata.labels().iter()), server_id: self.tls.clone(), target_addr: self.target_addr, } } } impl<P> Param<metrics::EndpointLabels> for Endpoint<P> { fn param(&self) -> metrics::EndpointLabels { Param::<metrics::OutboundEndpointLabels>::param(self).into() } } impl<P: std::hash::Hash> std::hash::Hash for Endpoint<P> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.addr.hash(state); self.tls.hash(state); self.logical.orig_dst.hash(state); self.logical.protocol.hash(state); } } impl EndpointFromMetadata { fn client_tls(metadata: &Metadata) -> tls::ConditionalClientTls { let use_transport_header = metadata.opaque_transport_port().is_some() || metadata.authority_override().is_some(); metadata .identity() .cloned() .map(move |server_id| { Conditional::Some(tls::ClientTls { server_id, alpn: if use_transport_header { Some(tls::client::AlpnProtocols(vec![ transport_header::PROTOCOL.into() ])) } else { None }, }) }) .unwrap_or(Conditional::None( tls::NoClientTls::NotProvidedByServiceDiscovery, )) } } impl<P: Clone + std::fmt::Debug> MapEndpoint<Concrete<P>, Metadata> for EndpointFromMetadata { type Out = Endpoint<P>; fn map_endpoint( &self, concrete: &Concrete<P>, addr: SocketAddr, metadata: Metadata, ) -> Self::Out { tracing::trace!(%addr, ?metadata, ?concrete, "Resolved endpoint"); Endpoint { addr, tls: Self::client_tls(&metadata), metadata, logical: concrete.logical.clone(), target_addr: concrete.logical.orig_dst, } } }
ClientTls, ) -> impl Fn(Self) -> Result<svc::Either<Self, Endpoint<P>>, Error> + Copy { move |logical: Self| { let should_resolve = match logical.profile.as_ref() { Some(p) => { let p = p.borrow(); p.endpoint.is_none() && (p.name.is_some() || !p.targets.is_empty()) } None => false, }; if should_resolve { Ok(svc::Either::A(logical)) } else { Ok(svc::Either::B(Endpoint::from_logical(reason)(logical))) } } }
function_block-function_prefixed
[ { "content": "pub fn new<K: Eq + Hash + FmtLabels>(retain_idle: Duration) -> (Registry<K>, Report<K>) {\n\n let inner = Arc::new(Mutex::new(Inner::new()));\n\n let report = Report {\n\n metrics: inner.clone(),\n\n retain_idle,\n\n };\n\n (Registry(inner), report)\n\n}\n\n\n\n/// Implements `FmtMetrics` to render prometheus-formatted metrics for all transports.\n\n#[derive(Clone, Debug)]\n\npub struct Report<K: Eq + Hash + FmtLabels> {\n\n metrics: Arc<Mutex<Inner<K>>>,\n\n retain_idle: Duration,\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Registry<K: Eq + Hash + FmtLabels>(Arc<Mutex<Inner<K>>>);\n\n\n\n#[derive(Debug)]\n", "file_path": "linkerd/proxy/transport/src/metrics.rs", "rank": 0, "score": 329496.0506295838 }, { "content": "/// Construct a new labeled `SocketAddr `from a protobuf `WeightedAddr`.\n\npub fn to_addr_meta(\n\n pb: WeightedAddr,\n\n set_labels: &HashMap<String, String>,\n\n) -> Option<(SocketAddr, Metadata)> {\n\n let authority_override = pb.authority_override.and_then(to_authority);\n\n let addr = pb.addr.and_then(to_sock_addr)?;\n\n\n\n let meta = {\n\n let mut t = set_labels\n\n .iter()\n\n .chain(pb.metric_labels.iter())\n\n .collect::<Vec<(&String, &String)>>();\n\n t.sort_by(|(k0, _), (k1, _)| k0.cmp(k1));\n\n\n\n let mut m = IndexMap::with_capacity(t.len());\n\n for (k, v) in t.into_iter() {\n\n m.insert(k.clone(), v.clone());\n\n }\n\n\n\n m\n", "file_path": "linkerd/proxy/api-resolve/src/pb.rs", "rank": 1, "score": 282319.1353872691 }, { "content": "/// A mockable source for address info, i.e., for tests.\n\npub trait OrigDstAddr: Clone {\n\n fn orig_dst_addr(&self, socket: &TcpStream) -> Option<SocketAddr>;\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct BindTcp<O: OrigDstAddr = NoOrigDstAddr> {\n\n bind_addr: SocketAddr,\n\n keepalive: Option<Duration>,\n\n orig_dst_addr: O,\n\n}\n\n\n\npub type Connection = (Addrs, TcpStream);\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Addrs {\n\n local: SocketAddr,\n\n peer: SocketAddr,\n\n orig_dst: Option<SocketAddr>,\n\n}\n\n\n", "file_path": "linkerd/proxy/transport/src/listen.rs", "rank": 2, "score": 277893.78345761856 }, { "content": "pub fn is_discovery_rejected(err: &(dyn std::error::Error + 'static)) -> bool {\n\n if let Some(status) = err.downcast_ref::<tonic::Status>() {\n\n status.code() == tonic::Code::InvalidArgument\n\n } else if let Some(err) = err.source() {\n\n is_discovery_rejected(err)\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/core/src/lib.rs", "rank": 3, "score": 270831.6968008223 }, { "content": "pub fn layer<F, V>(f: F) -> Layer<FnLazy<F>, V>\n\nwhere\n\n F: Fn() -> V + Clone,\n\n V: Send + Sync + 'static,\n\n{\n\n Layer::new(FnLazy(f))\n\n}\n\n\n\n// === impl Layer ===\n\n\n\nimpl<L, V> Layer<L, V>\n\nwhere\n\n L: Lazy<V>,\n\n V: Send + Sync + 'static,\n\n{\n\n pub fn new(lazy: L) -> Self {\n\n Self {\n\n lazy,\n\n _marker: PhantomData,\n\n }\n", "file_path": "linkerd/proxy/http/src/insert.rs", "rank": 4, "score": 270269.1716013462 }, { "content": "fn measure_class<C: Hash + Eq>(\n\n lock: &Arc<Mutex<Metrics<C>>>,\n\n class: C,\n\n status: Option<http::StatusCode>,\n\n) {\n\n let now = Instant::now();\n\n let mut metrics = match lock.lock() {\n\n Ok(m) => m,\n\n Err(_) => return,\n\n };\n\n\n\n (*metrics).last_update = now;\n\n\n\n let status_metrics = metrics\n\n .by_status\n\n .entry(status)\n\n .or_insert_with(StatusMetrics::default);\n\n\n\n let class_metrics = status_metrics\n\n .by_class\n", "file_path": "linkerd/http-metrics/src/requests/service.rs", "rank": 5, "score": 259640.89930820762 }, { "content": "pub fn http_request_authority_addr<B>(req: &http::Request<B>) -> Result<Addr, addr::Error> {\n\n req.uri()\n\n .authority()\n\n .ok_or(addr::Error::InvalidHost)\n\n .and_then(|a| Addr::from_authority_and_default_port(a, DEFAULT_PORT))\n\n}\n\n\n", "file_path": "linkerd/app/core/src/lib.rs", "rank": 6, "score": 258217.3991207669 }, { "content": "pub fn http_request_host_addr<B>(req: &http::Request<B>) -> Result<Addr, addr::Error> {\n\n use crate::proxy::http::h1;\n\n\n\n h1::authority_from_host(req)\n\n .ok_or(addr::Error::InvalidHost)\n\n .and_then(|a| Addr::from_authority_and_default_port(&a, DEFAULT_PORT))\n\n}\n", "file_path": "linkerd/app/core/src/lib.rs", "rank": 7, "score": 258217.3991207669 }, { "content": "pub fn layer<P, R, N>(\n\n resolve: R,\n\n watchdog: Duration,\n\n) -> impl layer::Layer<N, Service = Stack<P, R, N>> + Clone\n\nwhere\n\n P: Copy + Send + std::fmt::Debug,\n\n R: Resolve<Concrete<P>, Endpoint = Metadata> + Clone,\n\n R::Resolution: Send,\n\n R::Future: Send,\n\n N: NewService<Endpoint<P>>,\n\n{\n\n const ENDPOINT_BUFFER_CAPACITY: usize = 1_000;\n\n\n\n let to_endpoint = EndpointFromMetadata;\n\n layer::mk(move |new_endpoint| {\n\n let endpoints = discover::resolve(\n\n new_endpoint,\n\n map_endpoint::Resolve::new(to_endpoint, resolve.clone()),\n\n );\n\n Buffer::new(ENDPOINT_BUFFER_CAPACITY, watchdog, endpoints)\n\n })\n\n}\n", "file_path": "linkerd/app/outbound/src/resolve.rs", "rank": 8, "score": 255947.56087307874 }, { "content": "pub fn client(addr: SocketAddr) -> Client {\n\n let api = pb::tap_client::TapClient::new(SyncSvc(client::http2(addr, \"localhost\")));\n\n Client { api }\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/tap.rs", "rank": 9, "score": 253231.15182179064 }, { "content": "pub fn http_request_l5d_override_dst_addr<B>(req: &http::Request<B>) -> Result<Addr, addr::Error> {\n\n proxy::http::authority_from_header(req, DST_OVERRIDE_HEADER)\n\n .ok_or_else(|| {\n\n tracing::trace!(\"{} not in request headers\", DST_OVERRIDE_HEADER);\n\n addr::Error::InvalidHost\n\n })\n\n .and_then(|a| Addr::from_authority_and_default_port(&a, DEFAULT_PORT))\n\n}\n\n\n", "file_path": "linkerd/app/core/src/lib.rs", "rank": 10, "score": 253197.63428083627 }, { "content": "pub fn client(addr: SocketAddr) -> TcpClient {\n\n TcpClient { addr }\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/tcp.rs", "rank": 11, "score": 250579.1121410553 }, { "content": "pub fn resolver() -> crate::resolver::Profiles {\n\n crate::resolver::Resolver::default()\n\n}\n\n\n", "file_path": "linkerd/app/test/src/profile.rs", "rank": 12, "score": 249399.2030988495 }, { "content": "pub fn layer<T, G, F, M>(\n\n get_profile: G,\n\n filter: F,\n\n) -> impl layer::Layer<M, Service = Service<F, G, M>> + Clone\n\nwhere\n\n F: Predicate<T> + Clone,\n\n G: GetProfile<F::Request> + Clone,\n\n{\n\n let get_profile = RecoverDefault::new(Filter::new(get_profile.into_service(), filter));\n\n layer::mk(move |inner| Discover {\n\n get_profile: get_profile.clone(),\n\n inner,\n\n })\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Discover<G, M> {\n\n get_profile: G,\n\n inner: M,\n\n}\n\n\n", "file_path": "linkerd/service-profiles/src/discover.rs", "rank": 13, "score": 247458.29175194804 }, { "content": "pub fn profiles() -> resolver::Profiles {\n\n profile::resolver()\n\n}\n\n\n", "file_path": "linkerd/app/test/src/lib.rs", "rank": 14, "score": 244172.05573014257 }, { "content": "pub fn destination_add(addr: SocketAddr) -> pb::Update {\n\n destination_add_hinted(addr, Hint::Unknown)\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 15, "score": 242091.67684323993 }, { "content": "pub fn tcp(addr: SocketAddr) -> tcp::TcpClient {\n\n tcp::client(addr)\n\n}\n\npub struct Client {\n\n addr: SocketAddr,\n\n run: Run,\n\n authority: String,\n\n /// This is a future that completes when the associated connection for\n\n /// this Client has been dropped.\n\n running: Running,\n\n tx: Sender,\n\n task: JoinHandle<()>,\n\n version: http::Version,\n\n tls: Option<TlsConfig>,\n\n}\n\n\n\npub struct Reconnect {\n\n addr: SocketAddr,\n\n authority: String,\n\n run: Run,\n", "file_path": "linkerd/app/integration/src/client.rs", "rank": 16, "score": 242091.67684323993 }, { "content": "pub fn layer<M, N: Clone, R>(\n\n new_route: N,\n\n) -> impl layer::Layer<M, Service = NewRouteRequest<M, N, R>> {\n\n // This is saved so that the same `Arc`s are used and cloned instead of\n\n // calling `Route::default()` every time.\n\n let default = Route::default();\n\n layer::mk(move |inner| NewRouteRequest {\n\n inner,\n\n new_route: new_route.clone(),\n\n default: default.clone(),\n\n _route: PhantomData,\n\n })\n\n}\n\n\n\npub struct NewRouteRequest<M, N, R> {\n\n inner: M,\n\n new_route: N,\n\n default: Route,\n\n _route: PhantomData<R>,\n\n}\n", "file_path": "linkerd/service-profiles/src/http/route_request.rs", "rank": 17, "score": 240246.39780329587 }, { "content": "#[derive(Debug, Default)]\n\nstruct Metrics {\n\n open_total: Counter,\n\n open_connections: Gauge,\n\n write_bytes_total: Counter,\n\n read_bytes_total: Counter,\n\n\n\n by_eos: Arc<Mutex<ByEos>>,\n\n}\n\n\n", "file_path": "linkerd/proxy/transport/src/metrics.rs", "rank": 18, "score": 235478.9511164009 }, { "content": "pub fn default_config(orig_dst: SocketAddr) -> Config {\n\n Config {\n\n allow_discovery: IpMatch::new(Some(IpNet::from_str(\"0.0.0.0/0\").unwrap())).into(),\n\n proxy: config::ProxyConfig {\n\n server: config::ServerConfig {\n\n bind: BindTcp::new(SocketAddr::new(LOCALHOST.into(), 0), None)\n\n .with_orig_dst_addr(orig_dst.into()),\n\n h2_settings: h2::Settings::default(),\n\n },\n\n connect: config::ConnectConfig {\n\n keepalive: None,\n\n timeout: Duration::from_secs(1),\n\n backoff: exp_backoff::ExponentialBackoff::new(\n\n Duration::from_millis(100),\n\n Duration::from_millis(500),\n\n 0.1,\n\n )\n\n .unwrap(),\n\n h1_settings: h1::PoolSettings {\n\n max_idle: 1,\n", "file_path": "linkerd/app/outbound/src/test_util.rs", "rank": 19, "score": 232978.68159551683 }, { "content": "pub fn default_config(orig_dst: SocketAddr) -> Config {\n\n let cluster_local = \"svc.cluster.local.\"\n\n .parse::<Suffix>()\n\n .expect(\"`svc.cluster.local.` suffix is definitely valid\");\n\n Config {\n\n allow_discovery: NameMatch::new(Some(cluster_local)),\n\n proxy: config::ProxyConfig {\n\n server: config::ServerConfig {\n\n bind: BindTcp::new(SocketAddr::new(LOCALHOST.into(), 0), None)\n\n .with_orig_dst_addr(orig_dst.into()),\n\n h2_settings: h2::Settings::default(),\n\n },\n\n connect: config::ConnectConfig {\n\n keepalive: None,\n\n timeout: Duration::from_secs(1),\n\n backoff: exp_backoff::ExponentialBackoff::new(\n\n Duration::from_millis(100),\n\n Duration::from_millis(500),\n\n 0.1,\n\n )\n", "file_path": "linkerd/app/inbound/src/test_util.rs", "rank": 20, "score": 232978.6815955168 }, { "content": "#[derive(Debug, Default)]\n\nstruct EosMetrics {\n\n close_total: Counter,\n\n connection_duration: Histogram<latency::Ms>,\n\n}\n\n\n\n/// Tracks the state of a single instance of `Io` throughout its lifetime.\n\n#[derive(Debug)]\n\npub struct Sensor {\n\n metrics: Option<Arc<Metrics>>,\n\n opened_at: Instant,\n\n}\n\n\n\npub type SensorIo<T> = io::SensorIo<T, Sensor>;\n\n\n\n/// Lazily builds instances of `Sensor`.\n", "file_path": "linkerd/proxy/transport/src/metrics.rs", "rank": 21, "score": 231026.22146785128 }, { "content": "fn should_teardown_connection(error: &(dyn std::error::Error + 'static)) -> bool {\n\n if error.is::<ResponseTimeout>() || error.is::<tower::timeout::error::Elapsed>() {\n\n false\n\n } else if let Some(e) = error.source() {\n\n should_teardown_connection(e)\n\n } else {\n\n true\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/core/src/errors.rs", "rank": 22, "score": 230789.2470118928 }, { "content": "#[pin_project]\n\nenum State<F, R: TryStream, B> {\n\n Disconnected {\n\n backoff: Option<B>,\n\n },\n\n Connecting {\n\n future: F,\n\n backoff: Option<B>,\n\n },\n\n\n\n Connected {\n\n #[pin]\n\n resolution: R,\n\n is_initial: bool,\n\n },\n\n\n\n Recover {\n\n error: Option<Error>,\n\n backoff: Option<B>,\n\n },\n\n\n", "file_path": "linkerd/proxy/resolve/src/recover.rs", "rank": 23, "score": 227063.87435072183 }, { "content": "#[derive(Clone)]\n\nstruct Target(SocketAddr, tls::ConditionalClientTls);\n\n\n", "file_path": "linkerd/tls/tests/tls_accept.rs", "rank": 24, "score": 226707.25587308133 }, { "content": "pub fn destination_add_hinted(addr: SocketAddr, hint: Hint) -> pb::Update {\n\n destination_add_labeled(addr, hint, HashMap::new(), HashMap::new())\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 25, "score": 224786.7073691078 }, { "content": "#[derive(Debug)]\n\nstruct ByEos {\n\n last_update: Instant,\n\n metrics: HashMap<Eos, EosMetrics>,\n\n}\n\n\n\n/// Describes a classtransport end.\n\n///\n\n/// An `EosMetrics` type exists for each unique `Key` and `Eos` pair.\n\n///\n\n/// Implements `FmtLabels`.\n", "file_path": "linkerd/proxy/transport/src/metrics.rs", "rank": 26, "score": 224193.74191123605 }, { "content": "pub fn destination_add_tls(addr: SocketAddr, local_id: &str) -> pb::Update {\n\n pb::Update {\n\n update: Some(pb::update::Update::Add(pb::WeightedAddrSet {\n\n addrs: vec![pb::WeightedAddr {\n\n addr: Some(net::TcpAddress {\n\n ip: Some(ip_conv(addr.ip())),\n\n port: u32::from(addr.port()),\n\n }),\n\n tls_identity: Some(pb::TlsIdentity {\n\n strategy: Some(pb::tls_identity::Strategy::DnsLikeIdentity(\n\n pb::tls_identity::DnsLikeIdentity {\n\n name: local_id.into(),\n\n },\n\n )),\n\n }),\n\n ..Default::default()\n\n }],\n\n ..Default::default()\n\n })),\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 27, "score": 222599.93758905173 }, { "content": "fn is_error<E: std::error::Error + 'static>(e: &(dyn std::error::Error + 'static)) -> bool {\n\n e.is::<E>() || e.source().map(is_error::<E>).unwrap_or(false)\n\n}\n\n\n\nimpl std::fmt::Display for SharedError {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n self.0.fmt(f)\n\n }\n\n}\n\n\n\nimpl std::error::Error for SharedError {\n\n fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n\n Some(&**self.0.as_ref())\n\n }\n\n}\n", "file_path": "linkerd/stack/src/fail_on_error.rs", "rank": 28, "score": 219128.8896352045 }, { "content": "pub fn new<T: Into<String>>(addr: SocketAddr, auth: T) -> Client {\n\n http2(addr, auth.into())\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/client.rs", "rank": 29, "score": 218559.4076028688 }, { "content": "pub fn http1<T: Into<String>>(addr: SocketAddr, auth: T) -> Client {\n\n Client::new(\n\n addr,\n\n auth.into(),\n\n Run::Http1 {\n\n absolute_uris: false,\n\n },\n\n None,\n\n )\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/client.rs", "rank": 30, "score": 218559.4076028688 }, { "content": "pub fn http2<T: Into<String>>(addr: SocketAddr, auth: T) -> Client {\n\n Client::new(addr, auth.into(), Run::Http2, None)\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/client.rs", "rank": 31, "score": 218559.4076028688 }, { "content": "#[derive(Clone, Debug)]\n\nstruct NewSensor(Arc<Metrics>);\n\n\n", "file_path": "linkerd/proxy/transport/src/metrics.rs", "rank": 32, "score": 218157.47235816933 }, { "content": "pub fn init_log_compat() -> Result<(), Error> {\n\n tracing_log::LogTracer::init().map_err(Error::from)\n\n}\n\n\n\n#[derive(Debug, Default)]\n\npub struct Settings {\n\n filter: Option<String>,\n\n format: Option<String>,\n\n test: bool,\n\n}\n\n\n\nimpl Settings {\n\n pub fn from_env() -> Self {\n\n let mut settings = Settings::default();\n\n if let Ok(filter) = env::var(ENV_LOG_LEVEL) {\n\n settings = settings.filter(filter);\n\n }\n\n if let Ok(format) = env::var(ENV_LOG_FORMAT) {\n\n settings = settings.format(format);\n\n }\n", "file_path": "linkerd/tracing/src/lib.rs", "rank": 33, "score": 217808.75594117027 }, { "content": "pub fn metric(name: impl Into<String>) -> MetricMatch {\n\n MetricMatch::new(name)\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/metrics.rs", "rank": 34, "score": 217333.7754165961 }, { "content": "pub fn prefix_labels<'i, I>(prefix: &str, mut labels_iter: I) -> Option<String>\n\nwhere\n\n I: Iterator<Item = (&'i String, &'i String)>,\n\n{\n\n let (k0, v0) = labels_iter.next()?;\n\n let mut out = format!(\"{}_{}=\\\"{}\\\"\", prefix, k0, v0);\n\n\n\n for (k, v) in labels_iter {\n\n write!(out, \",{}_{}=\\\"{}\\\"\", prefix, k, v).expect(\"label concat must succeed\");\n\n }\n\n Some(out)\n\n}\n\n\n\n// === impl Metrics ===\n\n\n\nimpl Metrics {\n\n pub fn new(retain_idle: Duration) -> (Self, impl FmtMetrics + Clone + Send + 'static) {\n\n let process = telemetry::process::Report::new(SystemTime::now());\n\n\n\n let build_info = telemetry::build_info::Report::new();\n", "file_path": "linkerd/app/core/src/metrics.rs", "rank": 35, "score": 216610.46686611575 }, { "content": "pub fn layer<C, R: Clone>(\n\n recover: R,\n\n) -> impl layer::Layer<C, Service = NewReconnect<C, R>> + Clone {\n\n layer::mk(move |connect| NewReconnect {\n\n connect,\n\n recover: recover.clone(),\n\n })\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct NewReconnect<C, R> {\n\n connect: C,\n\n recover: R,\n\n}\n\n\n\nimpl<C, R, T> NewService<T> for NewReconnect<C, R>\n\nwhere\n\n R: Recover + Clone,\n\n C: tower::Service<T> + Clone,\n\n{\n\n type Service = service::Service<T, R, C>;\n\n\n\n fn new_service(&mut self, target: T) -> Self::Service {\n\n service::Service::new(target, self.connect.clone(), self.recover.clone())\n\n }\n\n}\n", "file_path": "linkerd/reconnect/src/lib.rs", "rank": 36, "score": 216425.977026316 }, { "content": "pub fn client_with_auth<T: Into<String>>(addr: SocketAddr, auth: T) -> Client {\n\n let api = pb::tap_client::TapClient::new(SyncSvc(client::http2(addr, auth)));\n\n Client { api }\n\n}\n\n\n\npub struct Client {\n\n api: pb::tap_client::TapClient<SyncSvc>,\n\n}\n\n\n\nimpl Client {\n\n pub async fn observe(\n\n &mut self,\n\n req: ObserveBuilder,\n\n ) -> Pin<Box<dyn Stream<Item = Result<pb::TapEvent, tonic::Status>> + Send + Sync>> {\n\n let req = tonic::Request::new(req.0);\n\n match self.api.observe(req).await {\n\n Ok(rsp) => Box::pin(rsp.into_inner()),\n\n Err(e) => Box::pin(stream::once(async move { Err(e) })),\n\n }\n\n }\n", "file_path": "linkerd/app/integration/src/tap.rs", "rank": 37, "score": 216290.22475717927 }, { "content": "/// Initialize tracing and logging with the value of the `ENV_LOG`\n\n/// environment variable as the verbosity-level filter.\n\npub fn init() -> Result<Handle, Error> {\n\n let log_level = env::var(ENV_LOG_LEVEL).unwrap_or_else(|_| DEFAULT_LOG_LEVEL.to_string());\n\n if let \"OFF\" = log_level.to_uppercase().trim() {\n\n return Ok(Handle(Inner::Disabled));\n\n }\n\n\n\n let log_format = env::var(ENV_LOG_FORMAT).unwrap_or_else(|_| DEFAULT_LOG_FORMAT.to_string());\n\n let (dispatch, handle) = Settings::default()\n\n .filter(log_level)\n\n .format(log_format)\n\n .build();\n\n\n\n // Set up log compatibility.\n\n init_log_compat()?;\n\n // Set the default subscriber.\n\n tracing::dispatcher::set_global_default(dispatch)?;\n\n\n\n Ok(handle)\n\n}\n\n\n", "file_path": "linkerd/tracing/src/lib.rs", "rank": 38, "score": 215998.2937463765 }, { "content": "/// This sends `GET http://foo.com/ HTTP/1.1` instead of just `GET / HTTP/1.1`.\n\npub fn http1_absolute_uris<T: Into<String>>(addr: SocketAddr, auth: T) -> Client {\n\n Client::new(\n\n addr,\n\n auth.into(),\n\n Run::Http1 {\n\n absolute_uris: true,\n\n },\n\n None,\n\n )\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/client.rs", "rank": 39, "score": 214103.45497712318 }, { "content": "#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]\n\nstruct Eos(Option<Errno>);\n\n\n\n/// Holds metrics for a class of end-of-stream.\n", "file_path": "linkerd/proxy/transport/src/metrics.rs", "rank": 40, "score": 210454.23717651446 }, { "content": "pub fn mock_listening(a: SocketAddr) -> Listening {\n\n let (tx, _rx) = drain::channel();\n\n let conn_count = Arc::new(AtomicUsize::from(0));\n\n Listening {\n\n addr: a,\n\n drain: tx,\n\n conn_count,\n\n task: Some(tokio::spawn(async { Ok(()) })),\n\n }\n\n}\n\n\n\nimpl Listening {\n\n pub fn connections(&self) -> usize {\n\n self.conn_count.load(Ordering::Acquire)\n\n }\n\n\n\n /// Wait for the server task to join, and propagate panics.\n\n pub async fn join(mut self) {\n\n tracing::info!(addr = %self.addr, \"trying to shut down support server...\");\n\n tracing::debug!(\"draining...\");\n", "file_path": "linkerd/app/integration/src/server.rs", "rank": 41, "score": 210174.2987741392 }, { "content": "#[derive(Debug)]\n\nstruct State<E> {\n\n endpoints: Mutex<HashMap<Addr, E>>,\n\n // Keep unused_senders open if they're not going to be used.\n\n unused_senders: Mutex<Vec<Box<dyn std::any::Any + Send + Sync + 'static>>>,\n\n only: AtomicBool,\n\n}\n\n\n\npub type DstReceiver<E> = Streaming<mpsc::UnboundedReceiver<Result<Update<E>, Error>>>;\n\n\n\n#[derive(Debug)]\n\npub struct SendFailed(());\n\n\n\nimpl<E> Default for Resolver<E> {\n\n fn default() -> Self {\n\n Self {\n\n state: Arc::new(State {\n\n endpoints: Mutex::new(HashMap::new()),\n\n unused_senders: Mutex::new(Vec::new()),\n\n only: AtomicBool::new(true),\n\n }),\n", "file_path": "linkerd/app/test/src/resolver.rs", "rank": 42, "score": 209655.31641968095 }, { "content": "#[allow(clippy::clippy::too_many_arguments)]\n\npub fn stack<I, O, P, R>(\n\n Config { allow_discovery }: Config,\n\n inbound: Inbound<()>,\n\n outbound: Outbound<O>,\n\n profiles: P,\n\n resolve: R,\n\n) -> impl svc::NewService<\n\n GatewayConnection,\n\n Service = impl svc::Service<I, Response = (), Error = impl Into<Error>, Future = impl Send>\n\n + Send\n\n + 'static,\n\n> + Clone\n\n + Send\n\nwhere\n\n I: io::AsyncRead + io::AsyncWrite + io::PeerAddr + fmt::Debug + Send + Sync + Unpin + 'static,\n\n O: svc::Service<outbound::http::Endpoint, Error = io::Error>\n\n + svc::Service<outbound::tcp::Endpoint, Error = io::Error>,\n\n O: Clone + Send + Sync + Unpin + 'static,\n\n <O as svc::Service<outbound::http::Endpoint>>::Response:\n\n io::AsyncRead + io::AsyncWrite + tls::HasNegotiatedProtocol + Send + Unpin + 'static,\n", "file_path": "linkerd/app/gateway/src/lib.rs", "rank": 43, "score": 209028.3456511771 }, { "content": "pub fn new() -> Proxy {\n\n Proxy::default()\n\n}\n\n\n\n#[derive(Default)]\n\npub struct Proxy {\n\n controller: Option<controller::Listening>,\n\n identity: Option<controller::Listening>,\n\n\n\n /// Inbound/outbound addresses helpful for mocking connections that do not\n\n /// implement `server::Listener`.\n\n inbound: Option<SocketAddr>,\n\n outbound: Option<SocketAddr>,\n\n\n\n /// Inbound/outbound addresses for mocking connections that implement\n\n /// `server::Listener`.\n\n inbound_server: Option<server::Listening>,\n\n outbound_server: Option<server::Listening>,\n\n\n\n inbound_disable_ports_protocol_detection: Option<Vec<u16>>,\n", "file_path": "linkerd/app/integration/src/proxy.rs", "rank": 44, "score": 205943.56717611538 }, { "content": "/// Returns a `Receiver` that contains only the initial value, and closes when\n\n/// the receiver is dropped.\n\npub fn only(profile: Profile) -> Receiver {\n\n let (tx, rx) = channel(profile);\n\n tokio::spawn(async move { tx.closed().await });\n\n rx\n\n}\n\n\n", "file_path": "linkerd/app/test/src/profile.rs", "rank": 45, "score": 203142.60575778002 }, { "content": "pub fn http1_tls<T: Into<String>>(addr: SocketAddr, auth: T, tls: TlsConfig) -> Client {\n\n Client::new(\n\n addr,\n\n auth.into(),\n\n Run::Http1 {\n\n absolute_uris: false,\n\n },\n\n Some(tls),\n\n )\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/client.rs", "rank": 46, "score": 202790.3237624521 }, { "content": "pub fn http2_tls<T: Into<String>>(addr: SocketAddr, auth: T, tls: TlsConfig) -> Client {\n\n Client::new(addr, auth.into(), Run::Http2, Some(tls))\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/client.rs", "rank": 47, "score": 202790.3237624521 }, { "content": " pub trait Tap: Clone {\n\n type TapRequestPayload: TapPayload;\n\n type TapResponse: TapResponse<TapPayload = Self::TapResponsePayload>;\n\n type TapResponsePayload: TapPayload;\n\n\n\n /// Returns `true` as l\n\n fn can_tap_more(&self) -> bool;\n\n\n\n /// Initiate a tap, if it matches.\n\n ///\n\n /// If the tap cannot be initialized, for instance because the tap has\n\n /// completed or been canceled, then `None` is returned.\n\n fn tap<B: HttpBody, I: super::Inspect>(\n\n &mut self,\n\n req: &http::Request<B>,\n\n inspect: &I,\n\n ) -> Option<(Self::TapRequestPayload, Self::TapResponse)>;\n\n }\n\n\n", "file_path": "linkerd/proxy/tap/src/lib.rs", "rank": 48, "score": 199019.52748003116 }, { "content": "pub fn profile<I>(\n\n routes: I,\n\n retry_budget: Option<pb::RetryBudget>,\n\n dst_overrides: Vec<pb::WeightedDst>,\n\n fqn: impl Into<String>,\n\n) -> pb::DestinationProfile\n\nwhere\n\n I: IntoIterator,\n\n I::Item: Into<pb::Route>,\n\n{\n\n let routes = routes.into_iter().map(Into::into).collect();\n\n pb::DestinationProfile {\n\n routes,\n\n retry_budget,\n\n dst_overrides,\n\n fully_qualified_name: fqn.into(),\n\n ..Default::default()\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 49, "score": 198650.96150350195 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n let files = &[\"proto/header.proto\"];\n\n let dirs = &[\"proto\"];\n\n\n\n prost_build::compile_protos(files, dirs)?;\n\n\n\n // recompile protobufs only if any of the proto files changes.\n\n for file in files {\n\n println!(\"cargo:rerun-if-changed={}\", file);\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "linkerd/transport-header/build.rs", "rank": 50, "score": 198649.65206052907 }, { "content": "pub fn proxies() -> Stack<IdentityProxy> {\n\n Stack(IdentityProxy(()))\n\n}\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct IdentityProxy(());\n\n\n\nimpl<T> NewService<T> for IdentityProxy {\n\n type Service = ();\n\n fn new_service(&mut self, _: T) -> Self::Service {}\n\n}\n\n\n\n#[allow(dead_code)]\n\nimpl<L> Layers<L> {\n\n pub fn push<O>(self, outer: O) -> Layers<Pair<L, O>> {\n\n Layers(Pair::new(self.0, outer))\n\n }\n\n\n\n pub fn push_map_target<M>(self, map_target: M) -> Layers<Pair<L, stack::MapTargetLayer<M>>> {\n\n self.push(stack::MapTargetLayer::new(map_target))\n", "file_path": "linkerd/app/core/src/svc.rs", "rank": 51, "score": 196577.93369422155 }, { "content": "/// Returns a `Receiver` that contains only the default profile, and closes when\n\n/// the receiver is dropped.\n\npub fn only_default() -> Receiver {\n\n only(Profile::default())\n\n}\n\n\n", "file_path": "linkerd/app/test/src/profile.rs", "rank": 52, "score": 195282.8943083182 }, { "content": "pub fn labels() -> Labels {\n\n Labels::default()\n\n}\n\n\n\n#[derive(Eq, PartialEq)]\n\npub struct MatchErr(String);\n\n\n\nmacro_rules! match_err {\n\n ($($arg:tt)+) => {\n\n return Err(MatchErr(format!($($arg)+)));\n\n }\n\n}\n\n\n\nimpl MetricMatch {\n\n pub fn new(name: impl Into<String>) -> Self {\n\n Self {\n\n name: name.into(),\n\n labels: HashMap::new(),\n\n value: None,\n\n }\n", "file_path": "linkerd/app/integration/src/metrics.rs", "rank": 53, "score": 194944.6204582837 }, { "content": "pub fn with_name(name: &str) -> Profile {\n\n use std::str::FromStr;\n\n let name = dns::Name::from_str(name).expect(\"non-ascii characters in DNS name! 😢\");\n\n Profile {\n\n name: Some(name),\n\n ..Default::default()\n\n }\n\n}\n", "file_path": "linkerd/app/test/src/profile.rs", "rank": 54, "score": 194600.28344574678 }, { "content": "#[derive(Clone, Debug)]\n\nstruct AllowProfile(pub IpMatch);\n\n\n\n// === impl AllowProfile ===\n\n\n\nimpl svc::stack::Predicate<tcp::Accept> for AllowProfile {\n\n type Request = profiles::LogicalAddr;\n\n\n\n fn check(&mut self, a: tcp::Accept) -> Result<profiles::LogicalAddr, Error> {\n\n if self.0.matches(a.orig_dst.ip()) {\n\n Ok(profiles::LogicalAddr(a.orig_dst.into()))\n\n } else {\n\n Err(discovery_rejected().into())\n\n }\n\n }\n\n}\n", "file_path": "linkerd/app/outbound/src/discover.rs", "rank": 55, "score": 192403.70133763016 }, { "content": "pub trait Lazy<V>: Clone {\n\n fn value(&self) -> V;\n\n}\n\n\n\n/// Wraps an HTTP `Service` so that the `T -typed value` is cloned into\n\n/// each request's extensions.\n\n#[derive(Clone, Debug)]\n\npub struct Layer<L, V> {\n\n lazy: L,\n\n _marker: PhantomData<fn() -> V>,\n\n}\n\n\n\npub struct Insert<S, L, V> {\n\n inner: S,\n\n lazy: L,\n\n _marker: PhantomData<fn() -> V>,\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct FnLazy<F>(F);\n", "file_path": "linkerd/proxy/http/src/insert.rs", "rank": 56, "score": 192064.26705380934 }, { "content": "fn parse_bool(s: &str) -> Result<bool, ParseError> {\n\n s.parse().map_err(|_| ParseError::NotABool)\n\n}\n\n\n", "file_path": "linkerd/app/src/env.rs", "rank": 57, "score": 191862.66972933707 }, { "content": "fn parse_addr(s: &str) -> Result<Addr, ParseError> {\n\n Addr::from_str(s).map_err(|e| {\n\n error!(\"Not a valid address: {}\", s);\n\n ParseError::AddrError(e)\n\n })\n\n}\n\n\n", "file_path": "linkerd/app/src/env.rs", "rank": 58, "score": 191605.55872429165 }, { "content": "pub fn new() -> (Registry, Report) {\n\n let metrics = Metrics {\n\n streams: Counter::default(),\n\n requests: Counter::default(),\n\n spans: Counter::default(),\n\n };\n\n let shared = Arc::new(metrics);\n\n (Registry(shared.clone()), Report(shared))\n\n}\n\n\n\nimpl Registry {\n\n pub fn start_stream(&mut self) {\n\n self.0.streams.incr()\n\n }\n\n\n\n pub fn send(&mut self, spans: u64) {\n\n self.0.requests.incr();\n\n self.0.spans.add(spans);\n\n }\n\n}\n", "file_path": "linkerd/opencensus/src/metrics.rs", "rank": 59, "score": 191427.70903625205 }, { "content": "pub fn layer<N, S, Req>() -> impl layer::Layer<N, Service = NewSplit<N, S, Req>> + Clone {\n\n // This RNG doesn't need to be cryptographically secure. Small and fast is\n\n // preferable.\n\n layer::mk(move |inner| NewSplit {\n\n inner,\n\n _service: PhantomData,\n\n })\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct NewSplit<N, S, Req> {\n\n inner: N,\n\n _service: PhantomData<fn(Req) -> S>,\n\n}\n\n\n\npub enum Split<T, N, S, Req> {\n\n Default(S),\n\n Split(Box<Inner<T, N, S, Req>>),\n\n}\n\n\n", "file_path": "linkerd/service-profiles/src/split.rs", "rank": 60, "score": 190861.63280704242 }, { "content": "pub fn resolve<T, N, R>(endpoint: N, resolve: R) -> Stack<N, R, R::Endpoint>\n\nwhere\n\n R: Resolve<T>,\n\n{\n\n MakeEndpoint::new(endpoint, FromResolve::new(resolve))\n\n}\n", "file_path": "linkerd/proxy/discover/src/lib.rs", "rank": 61, "score": 189621.09409099823 }, { "content": "pub fn resolver<E>() -> resolver::Dst<E> {\n\n resolver::Resolver::default()\n\n}\n\n\n", "file_path": "linkerd/app/test/src/lib.rs", "rank": 62, "score": 189107.43056940625 }, { "content": "/// Produces a PeakEWMA balancer that uses connect latency (and pending\n\n/// connections) as its load metric.\n\npub fn layer<T, D>(\n\n default_rtt: Duration,\n\n decay: Duration,\n\n) -> impl tower::layer::Layer<D, Service = Balance<PeakEwmaDiscover<D, CompleteOnResponse>, T>> + Clone\n\nwhere\n\n D: Discover,\n\n D::Key: Hash,\n\n D::Service: tower::Service<T>,\n\n <D::Service as tower::Service<T>>::Error: Into<Error>,\n\n{\n\n layer::mk(move |discover| {\n\n let loaded =\n\n PeakEwmaDiscover::new(discover, default_rtt, decay, CompleteOnResponse::default());\n\n Balance::from_rng(loaded, &mut thread_rng()).expect(\"RNG must be valid\")\n\n })\n\n}\n", "file_path": "linkerd/proxy/tcp/src/balance.rs", "rank": 63, "score": 187637.07680799186 }, { "content": "pub fn layer<C, B>(\n\n h1_pool: h1::PoolSettings,\n\n h2_settings: h2::Settings,\n\n) -> impl layer::Layer<C, Service = MakeClient<C, B>> + Copy {\n\n layer::mk(move |connect: C| MakeClient {\n\n connect,\n\n h1_pool,\n\n h2_settings,\n\n _marker: PhantomData,\n\n })\n\n}\n\n\n\nimpl From<crate::Version> for Settings {\n\n fn from(v: crate::Version) -> Self {\n\n match v {\n\n crate::Version::Http1 => Self::Http1,\n\n crate::Version::H2 => Self::H2,\n\n }\n\n }\n\n}\n\n\n\n// === impl MakeClient ===\n\n\n", "file_path": "linkerd/proxy/http/src/client.rs", "rank": 64, "score": 187626.78985576687 }, { "content": "/// Returns if the request target is in `origin-form`.\n\n///\n\n/// This is `origin-form`: `example.com`\n\nfn is_origin_form(uri: &Uri) -> bool {\n\n uri.scheme().is_none() && uri.path_and_query().is_none()\n\n}\n\n\n\n/// Returns if the received request is definitely bad.\n\n///\n\n/// Just because a request parses doesn't mean it's correct. For examples:\n\n///\n\n/// - `GET example.com`\n\n/// - `CONNECT /just-a-path\n\npub(crate) fn is_bad_request<B>(req: &http::Request<B>) -> bool {\n\n if req.method() == http::Method::CONNECT {\n\n // CONNECT is only valid over HTTP/1.1\n\n if req.version() != http::Version::HTTP_11 {\n\n debug!(\"CONNECT request not valid for HTTP/1.0: {:?}\", req.uri());\n\n return true;\n\n }\n\n\n\n // CONNECT requests are only valid in authority-form.\n\n if !is_origin_form(req.uri()) {\n", "file_path": "linkerd/proxy/http/src/h1.rs", "rank": 65, "score": 187557.25644214748 }, { "content": "fn parse_socket_addr(s: &str) -> Result<SocketAddr, ParseError> {\n\n match parse_addr(s)? {\n\n Addr::Socket(a) => Ok(a),\n\n _ => {\n\n error!(\"Expected IP:PORT; found: {}\", s);\n\n Err(ParseError::HostIsNotAnIpAddress)\n\n }\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/src/env.rs", "rank": 66, "score": 186385.59303392243 }, { "content": "pub fn parse_control_addr<S: Strings>(\n\n strings: &S,\n\n base: &str,\n\n) -> Result<Option<ControlAddr>, EnvError> {\n\n let a_env = format!(\"{}_ADDR\", base);\n\n let a = parse(strings, &a_env, parse_addr);\n\n let n_env = format!(\"{}_NAME\", base);\n\n let n = parse(strings, &n_env, parse_identity);\n\n match (a?, n?) {\n\n (None, None) => Ok(None),\n\n (Some(ref addr), _) if addr.is_loopback() => Ok(Some(ControlAddr {\n\n addr: addr.clone(),\n\n identity: Conditional::None(tls::NoClientTls::Loopback),\n\n })),\n\n (Some(addr), Some(name)) => Ok(Some(ControlAddr {\n\n addr,\n\n identity: Conditional::Some(tls::ServerId(name).into()),\n\n })),\n\n (Some(_), None) => {\n\n error!(\"{} must be specified when {} is set\", n_env, a_env);\n\n Err(EnvError::InvalidEnvVar)\n\n }\n\n (None, Some(_)) => {\n\n error!(\"{} must be specified when {} is set\", a_env, n_env);\n\n Err(EnvError::InvalidEnvVar)\n\n }\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/src/env.rs", "rank": 67, "score": 185649.11416211177 }, { "content": "fn was_absolute_form(val: &[u8]) -> bool {\n\n val.len() >= \"HTTP/1.1; absolute-form\".len() && &val[10..23] == b\"absolute-form\"\n\n}\n", "file_path": "linkerd/proxy/http/src/orig_proto.rs", "rank": 68, "score": 184650.65643716403 }, { "content": "/// A middleware type that cannot exert backpressure.\n\n///\n\n/// Typically used to modify requests or responses.\n\npub trait Proxy<Req, S: tower::Service<Self::Request>> {\n\n /// The type of request sent to the inner `S`-typed service.\n\n type Request;\n\n\n\n /// The type of response returned to callers.\n\n type Response;\n\n\n\n /// The error type returned to callers.\n\n type Error: Into<Error>;\n\n\n\n /// The Future type returned to callers.\n\n type Future: Future<Output = Result<Self::Response, Self::Error>>;\n\n\n\n /// Usually invokes `S::call`, potentially modifying requests or responses.\n\n fn proxy(&self, inner: &mut S, req: Req) -> Self::Future;\n\n\n\n /// Wraps an `S` typed service with the proxy.\n\n fn wrap_service(self, inner: S) -> ProxyService<Self, S>\n\n where\n\n Self: Sized,\n", "file_path": "linkerd/stack/src/proxy.rs", "rank": 69, "score": 184164.14856180374 }, { "content": "pub fn destination_remove_none() -> pb::Update {\n\n pb::Update {\n\n update: Some(pb::update::Update::Remove(pb::AddrSet {\n\n addrs: Vec::new(),\n\n })),\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 70, "score": 182842.76650450245 }, { "content": "pub fn destination_add_none() -> pb::Update {\n\n pb::Update {\n\n update: Some(pb::update::Update::Add(pb::WeightedAddrSet {\n\n addrs: Vec::new(),\n\n ..Default::default()\n\n })),\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 71, "score": 182842.76650450245 }, { "content": "fn resolution(\n\n mut stream: tonic::Streaming<api::Update>,\n\n) -> impl Stream<Item = Result<resolve::Update<Metadata>, grpc::Status>> {\n\n try_stream! {\n\n while let Some(update) = stream.next().await {\n\n match update?.update {\n\n Some(api::update::Update::Add(api::WeightedAddrSet {\n\n addrs,\n\n metric_labels,\n\n })) => {\n\n let addr_metas = addrs\n\n .into_iter()\n\n .filter_map(|addr| pb::to_addr_meta(addr, &metric_labels))\n\n .collect::<Vec<_>>();\n\n if !addr_metas.is_empty() {\n\n debug!(endpoints = %addr_metas.len(), \"Add\");\n\n yield Update::Add(addr_metas);\n\n }\n\n }\n\n\n", "file_path": "linkerd/proxy/api-resolve/src/resolve.rs", "rank": 72, "score": 181982.51945595833 }, { "content": "pub fn new() -> (Registry, grpc::Server) {\n\n let registry = Registry::new();\n\n let server = grpc::Server::new(registry.clone());\n\n (registry, server)\n\n}\n\n\n", "file_path": "linkerd/proxy/tap/src/lib.rs", "rank": 73, "score": 181449.684785979 }, { "content": "pub fn parse_control_addr_disable_identity<S: Strings>(\n\n strings: &S,\n\n base: &str,\n\n) -> Result<Option<ControlAddr>, EnvError> {\n\n let a = parse(strings, &format!(\"{}_ADDR\", base), parse_addr)?;\n\n let identity = Conditional::None(tls::NoClientTls::Disabled);\n\n Ok(a.map(|addr| ControlAddr { addr, identity }))\n\n}\n\n\n", "file_path": "linkerd/app/src/env.rs", "rank": 74, "score": 179934.21872138884 }, { "content": "/// Like `read_vector` except the contents are ignored.\n\nfn skip_vector(input: &mut untrusted::Reader<'_>) -> Result<bool, untrusted::EndOfInput> {\n\n let r = read_vector(input, |input| {\n\n input.skip_to_end();\n\n Ok(Some(()))\n\n });\n\n r.map(|r| r.is_some())\n\n}\n\n\n", "file_path": "linkerd/tls/src/server/client_hello.rs", "rank": 75, "score": 179302.48966844456 }, { "content": "type DowngradeFuture<F, T> = future::MapOk<F, fn(T) -> T>;\n\n\n\nimpl<S, A, B> tower::Service<http::Request<A>> for Downgrade<S>\n\nwhere\n\n S: tower::Service<http::Request<A>, Response = http::Response<B>>,\n\n{\n\n type Response = S::Response;\n\n type Error = S::Error;\n\n type Future = DowngradeFuture<S::Future, S::Response>;\n\n\n\n fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {\n\n self.inner.poll_ready(cx)\n\n }\n\n\n\n fn call(&mut self, mut req: http::Request<A>) -> Self::Future {\n\n let mut upgrade_response = false;\n\n\n\n if req.version() == http::Version::HTTP_2 {\n\n if let Some(orig_proto) = req.headers_mut().remove(L5D_ORIG_PROTO) {\n\n debug!(\"translating HTTP2 to orig-proto: {:?}\", orig_proto);\n", "file_path": "linkerd/proxy/http/src/orig_proto.rs", "rank": 76, "score": 179295.5175050553 }, { "content": "fn header_value_from_request<B, K, F, T>(\n\n req: &http::Request<B>,\n\n header: K,\n\n try_from: F,\n\n) -> Option<T>\n\nwhere\n\n K: AsHeaderName,\n\n F: FnOnce(&str) -> Option<T>,\n\n{\n\n req.headers().get(header)?.to_str().ok().and_then(try_from)\n\n}\n", "file_path": "linkerd/proxy/http/src/lib.rs", "rank": 77, "score": 178527.5298147853 }, { "content": "#[derive(Debug, Clone)]\n\nstruct Inner {\n\n crt_key_watch: watch::Receiver<Option<CrtKey>>,\n\n refreshes: Arc<Counter>,\n\n}\n\n\n\nimpl FmtMetrics for Report {\n\n fn fmt_metrics(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n let this = match self.inner.as_ref() {\n\n Some(inner) => inner,\n\n None => return Ok(()),\n\n };\n\n\n\n if let Some(ref crt_key) = *(this.crt_key_watch.borrow()) {\n\n let dur = crt_key\n\n .expiry()\n\n .duration_since(UNIX_EPOCH)\n\n .map_err(|error| {\n\n tracing::warn!(%error, \"an identity would expire before the beginning of the UNIX epoch, something is probably wrong\");\n\n fmt::Error\n\n })?;\n", "file_path": "linkerd/proxy/identity/src/metrics.rs", "rank": 78, "score": 177284.95625384347 }, { "content": "pub fn trace_labels() -> HashMap<String, String> {\n\n let mut l = HashMap::new();\n\n l.insert(\"direction\".to_string(), \"outbound\".to_string());\n\n l\n\n}\n", "file_path": "linkerd/app/outbound/src/lib.rs", "rank": 79, "score": 176893.09673345464 }, { "content": "pub fn layer() -> respond::RespondLayer<NewRespond> {\n\n respond::RespondLayer::new(NewRespond(()))\n\n}\n\n\n\n#[derive(Clone, Default)]\n\npub struct Metrics(metrics::Registry<Label>);\n\n\n\npub type MetricsLayer = metrics::RecordErrorLayer<LabelError, Label>;\n\n\n\n/// Error metric labels.\n\n#[derive(Copy, Clone, Debug)]\n\npub struct LabelError(super::metrics::Direction);\n\n\n\npub type Label = (super::metrics::Direction, Reason);\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct HttpError {\n\n http: http::StatusCode,\n\n grpc: Code,\n\n message: &'static str,\n", "file_path": "linkerd/app/core/src/errors.rs", "rank": 80, "score": 176712.67751223448 }, { "content": "/// Resolves `T`-typed names/addresses as an infinite stream of `Update<Self::Endpoint>`.\n\npub trait Resolve<T> {\n\n type Endpoint;\n\n type Error: Into<Error>;\n\n type Resolution: Stream<Item = Result<Update<Self::Endpoint>, Self::Error>>;\n\n type Future: Future<Output = Result<Self::Resolution, Self::Error>>;\n\n\n\n fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;\n\n\n\n fn resolve(&mut self, target: T) -> Self::Future;\n\n\n\n fn into_service(self) -> ResolveService<Self>\n\n where\n\n Self: Sized,\n\n {\n\n ResolveService(self)\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct ResolveService<S>(S);\n", "file_path": "linkerd/proxy/core/src/resolve.rs", "rank": 81, "score": 176257.92727173146 }, { "content": "pub fn runtime() -> (ProxyRuntime, drain::Signal) {\n\n let (metrics, _) = metrics::Metrics::new(std::time::Duration::from_secs(10));\n\n let (drain_tx, drain) = drain::channel();\n\n let (tap, _) = tap::new();\n\n let runtime = ProxyRuntime {\n\n identity: None,\n\n metrics: metrics.outbound,\n\n tap,\n\n span_sink: None,\n\n drain,\n\n };\n\n (runtime, drain_tx)\n\n}\n", "file_path": "linkerd/app/inbound/src/test_util.rs", "rank": 82, "score": 175782.41960017395 }, { "content": "pub fn runtime() -> (ProxyRuntime, drain::Signal) {\n\n let (metrics, _) = metrics::Metrics::new(std::time::Duration::from_secs(10));\n\n let (drain_tx, drain) = drain::channel();\n\n let (tap, _) = tap::new();\n\n let runtime = ProxyRuntime {\n\n identity: None,\n\n metrics: metrics.outbound,\n\n tap,\n\n span_sink: None,\n\n drain,\n\n };\n\n (runtime, drain_tx)\n\n}\n", "file_path": "linkerd/app/outbound/src/test_util.rs", "rank": 83, "score": 175782.41960017395 }, { "content": "#[test]\n\nfn proxy_to_proxy_tls_works() {\n\n let server_tls = id::test_util::FOO_NS1.validate().unwrap();\n\n let client_tls = id::test_util::BAR_NS1.validate().unwrap();\n\n let server_id = tls::ServerId(server_tls.name().clone());\n\n let (client_result, server_result) = run_test(\n\n Conditional::Some((client_tls.clone(), server_id.clone())),\n\n |conn| write_then_read(conn, PING),\n\n Some(server_tls),\n\n |(_, conn)| read_then_write(conn, PING.len(), PONG),\n\n );\n\n assert_eq!(\n\n client_result.tls,\n\n Some(Conditional::Some(tls::ClientTls {\n\n server_id,\n\n alpn: None,\n\n }))\n\n );\n\n assert_eq!(&client_result.result.expect(\"pong\")[..], PONG);\n\n assert_eq!(\n\n server_result.tls,\n\n Some(Conditional::Some(tls::ServerTls::Established {\n\n client_id: Some(tls::ClientId(client_tls.name().clone())),\n\n negotiated_protocol: None,\n\n }))\n\n );\n\n assert_eq!(&server_result.result.expect(\"ping\")[..], PING);\n\n}\n\n\n", "file_path": "linkerd/tls/tests/tls_accept.rs", "rank": 84, "score": 175755.73369614052 }, { "content": "fn accept_json<B>(req: &http::Request<B>) -> bool {\n\n let json = http::header::HeaderValue::from_static(\"application/json\");\n\n req.uri().path().ends_with(\".json\")\n\n || req\n\n .headers()\n\n .get(http::header::ACCEPT)\n\n .iter()\n\n .any(|&value| value == json)\n\n}\n\n\n\nimpl Handle {\n\n fn render_json(&self) -> serde_json::Result<String> {\n\n serde_json::to_string(&self.tasks)\n\n }\n\n\n\n fn render_html(&self) -> String {\n\n let mut body = String::from(\n\n \"<html>\n\n <head><title>tasks</title></head>\n\n <body>\n", "file_path": "linkerd/tracing/src/tasks.rs", "rank": 85, "score": 174061.2370739853 }, { "content": "pub trait LabelError<E> {\n\n type Labels: FmtLabels + Hash + Eq;\n\n\n\n fn label_error(&self, error: &E) -> Self::Labels;\n\n}\n\n\n\n/// Produces layers and reports results.\n\n#[derive(Debug)]\n\npub struct Registry<K: Hash + Eq> {\n\n errors: Arc<Mutex<IndexMap<K, Counter>>>,\n\n}\n\n\n\nimpl<K: Hash + Eq> Registry<K> {\n\n pub fn layer<L>(&self, label: L) -> RecordErrorLayer<L, K> {\n\n RecordErrorLayer::new(label, self.errors.clone())\n\n }\n\n}\n\n\n\nimpl<K: Hash + Eq> Default for Registry<K> {\n\n fn default() -> Self {\n", "file_path": "linkerd/error-metrics/src/lib.rs", "rank": 86, "score": 173862.2289114693 }, { "content": "#[derive(Clone, Debug)]\n\nstruct SharedError(Arc<Error>);\n\n\n\nimpl<E, S> FailOnError<E, S> {\n\n pub fn new(inner: S) -> Self {\n\n Self {\n\n inner,\n\n error: Arc::new(RwLock::new(None)),\n\n _marker: std::marker::PhantomData,\n\n }\n\n }\n\n}\n\n\n\nimpl<E, S, Req> tower::Service<Req> for FailOnError<E, S>\n\nwhere\n\n S: tower::Service<Req>,\n\n S::Response: Send,\n\n S::Error: Into<Error> + Send,\n\n S::Future: Send + 'static,\n\n E: std::error::Error + 'static,\n\n{\n", "file_path": "linkerd/stack/src/fail_on_error.rs", "rank": 87, "score": 172442.02533630765 }, { "content": "struct Transported<I, R> {\n\n tls: Option<I>,\n\n\n\n /// The connection's result.\n\n result: Result<R, io::Error>,\n\n}\n\n\n", "file_path": "linkerd/tls/tests/tls_accept.rs", "rank": 88, "score": 170775.88639755448 }, { "content": "/// An error recovery strategy.\n\npub trait Recover<E: Into<Error> = Error> {\n\n type Backoff: Stream<Item = ()>;\n\n\n\n /// Given an E-typed error, determine if the error is recoverable.\n\n ///\n\n /// If it is, a backoff stream is returned. When the backoff becomes ready,\n\n /// it signals that the caller should retry its operation. If the backoff is\n\n /// polled agian, it is assumed that the operation failed and a new (possibly\n\n /// longer) backoff is initated.\n\n ///\n\n /// If the error is not recoverable, it is returned immediately.\n\n fn recover(&self, err: E) -> Result<Self::Backoff, E>;\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, Default)]\n\npub struct Immediately(());\n\n\n\n// === impl Recover ===\n\n\n\nimpl<E, B, F> Recover<E> for F\n", "file_path": "linkerd/error/src/recover.rs", "rank": 89, "score": 170286.59566220175 }, { "content": "#[test]\n\nfn proxy_to_proxy_tls_pass_through_when_identity_does_not_match() {\n\n let server_tls = id::test_util::FOO_NS1.validate().unwrap();\n\n\n\n // Misuse the client's identity instead of the server's identity. Any\n\n // identity other than `server_tls.server_identity` would work.\n\n let client_tls = id::test_util::BAR_NS1\n\n .validate()\n\n .expect(\"valid client cert\");\n\n let sni = id::test_util::BAR_NS1.crt().name().clone();\n\n\n\n let (client_result, server_result) = run_test(\n\n Conditional::Some((client_tls, tls::ServerId(sni.clone()))),\n\n |conn| write_then_read(conn, PING),\n\n Some(server_tls),\n\n |(_, conn)| read_then_write(conn, START_OF_TLS.len(), PONG),\n\n );\n\n\n\n // The server's connection will succeed with the TLS client hello passed\n\n // through, because the SNI doesn't match its identity.\n\n assert_eq!(client_result.tls, None);\n\n assert!(client_result.result.is_err());\n\n assert_eq!(\n\n server_result.tls,\n\n Some(Conditional::Some(tls::ServerTls::Passthru {\n\n sni: tls::ServerId(sni)\n\n }))\n\n );\n\n assert_eq!(&server_result.result.unwrap()[..], START_OF_TLS);\n\n}\n\n\n", "file_path": "linkerd/tls/tests/tls_accept.rs", "rank": 90, "score": 170137.37379092508 }, { "content": "// Generates a new span id, writes it to the request in the appropriate\n\n// propagation format and returns the generated span id.\n\npub fn increment_span_id<B>(request: &mut http::Request<B>, context: &TraceContext) -> Id {\n\n match context.propagation {\n\n Propagation::Grpc => increment_grpc_span_id(request, context),\n\n Propagation::Http => increment_http_span_id(request),\n\n }\n\n}\n\n\n", "file_path": "linkerd/trace-context/src/propagation.rs", "rank": 91, "score": 170054.31007474975 }, { "content": "fn stream_profile(mut rx: Receiver) -> Pin<Box<dyn Stream<Item = Profile> + Send + Sync>> {\n\n Box::pin(async_stream::stream! {\n\n loop {\n\n let val = rx.borrow().clone();\n\n yield val;\n\n // This is a loop with a return condition rather than a while loop,\n\n // because we want to yield the *first* value immediately, rather\n\n // than waiting for the profile to change again.\n\n if let Err(_) = rx.changed().await {\n\n tracing::trace!(\"profile sender dropped\");\n\n return;\n\n }\n\n }\n\n })\n\n}\n", "file_path": "linkerd/service-profiles/src/lib.rs", "rank": 92, "score": 168964.88110702846 }, { "content": "#[derive(Clone, Debug)]\n\nstruct SharedError(Arc<Error>);\n\n\n", "file_path": "linkerd/stack/src/result.rs", "rank": 93, "score": 168713.77392558075 }, { "content": "fn parse_grpc_trace_context_fields(buf: &mut Bytes) -> Option<TraceContext> {\n\n trace!(message = \"reading binary trace context\", ?buf);\n\n\n\n let _version = try_split_to(buf, 1).ok()?;\n\n\n\n let mut context = TraceContext {\n\n propagation: Propagation::Grpc,\n\n trace_id: Default::default(),\n\n parent_id: Default::default(),\n\n flags: Default::default(),\n\n };\n\n\n\n while !buf.is_empty() {\n\n match parse_grpc_trace_context_field(buf, &mut context) {\n\n Ok(()) => {}\n\n Err(ref e) if e.is::<UnknownFieldId>() => break,\n\n Err(e) => {\n\n warn!(\"error parsing {} header: {}\", GRPC_TRACE_HEADER, e);\n\n return None;\n\n }\n\n };\n\n }\n\n Some(context)\n\n}\n\n\n", "file_path": "linkerd/trace-context/src/propagation.rs", "rank": 94, "score": 166621.45483715256 }, { "content": "pub trait HasH2Reason {\n\n fn h2_reason(&self) -> Option<::h2::Reason>;\n\n}\n\n\n\nimpl<'a> HasH2Reason for &'a (dyn std::error::Error + 'static) {\n\n fn h2_reason(&self) -> Option<::h2::Reason> {\n\n if let Some(err) = self.downcast_ref::<::h2::Error>() {\n\n return err.h2_reason();\n\n }\n\n\n\n self.source().and_then(|e| e.h2_reason())\n\n }\n\n}\n\n\n\nimpl HasH2Reason for Error {\n\n fn h2_reason(&self) -> Option<::h2::Reason> {\n\n (&**self as &(dyn std::error::Error + 'static)).h2_reason()\n\n }\n\n}\n\n\n\nimpl HasH2Reason for ::h2::Error {\n\n fn h2_reason(&self) -> Option<::h2::Reason> {\n\n self.reason()\n\n }\n\n}\n\n\n", "file_path": "linkerd/proxy/http/src/lib.rs", "rank": 95, "score": 166618.04064687062 }, { "content": "#[derive(Debug)]\n\nstruct RefusedNotResolved(NameAddr);\n\n\n", "file_path": "linkerd/app/gateway/src/lib.rs", "rank": 96, "score": 166264.39540909854 }, { "content": "#[tracing::instrument]\n\nfn hello_server(http: hyper::server::conn::Http) -> impl Fn(ConnectAddr) -> Result<BoxedIo, Error> {\n\n move |endpoint| {\n\n let span = tracing::info_span!(\"hello_server\", ?endpoint);\n\n let _e = span.enter();\n\n tracing::info!(\"mock connecting\");\n\n let (client_io, server_io) = support::io::duplex(4096);\n\n let hello_svc = hyper::service::service_fn(|request: Request<Body>| async move {\n\n tracing::info!(?request);\n\n Ok::<_, Error>(Response::new(Body::from(\"Hello world!\")))\n\n });\n\n tokio::spawn(\n\n http.serve_connection(server_io, hello_svc)\n\n .in_current_span(),\n\n );\n\n Ok(BoxedIo::new(client_io))\n\n }\n\n}\n", "file_path": "linkerd/app/inbound/src/http/tests.rs", "rank": 97, "score": 164961.34734079504 }, { "content": "fn http_status(error: &(dyn std::error::Error + 'static)) -> StatusCode {\n\n if let Some(HttpError { http, .. }) = error.downcast_ref::<HttpError>() {\n\n *http\n\n } else if error.is::<ResponseTimeout>() {\n\n http::StatusCode::GATEWAY_TIMEOUT\n\n } else if error.is::<FailFastError>() || error.is::<tower::timeout::error::Elapsed>() {\n\n http::StatusCode::SERVICE_UNAVAILABLE\n\n } else if error.is::<IdentityRequired>() {\n\n http::StatusCode::FORBIDDEN\n\n } else if let Some(source) = error.source() {\n\n http_status(source)\n\n } else {\n\n http::StatusCode::BAD_GATEWAY\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/core/src/errors.rs", "rank": 98, "score": 163934.07557551796 }, { "content": "pub fn layer(metrics: HttpRouteRetry) -> NewRetryLayer<NewRetry> {\n\n NewRetryLayer::new(NewRetry::new(metrics))\n\n}\n\n\n", "file_path": "linkerd/app/core/src/retry.rs", "rank": 99, "score": 163542.2235505967 } ]
Rust
src/lib.rs
zklapow/sbus
9ca73cb0d58d7a13db3d48103de5fdb51e6d9154
#![no_std] mod taranis; pub use taranis::TaranisX7SBusPacket; use arraydeque::{ArrayDeque, Wrapping}; const SBUS_FLAG_BYTE_MASK: u8 = 0b11110000; const SBUS_HEADER_BYTE: u8 = 0x0F; const SBUS_FOOTER_BYTE: u8 = 0b00000000; const SBUS_PACKET_SIZE: usize = 25; #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Copy, Clone)] pub struct SBusPacket { channels: [u16; 16], d1: bool, d2: bool, failsafe: bool, frame_lost: bool, } pub struct SBusPacketParser { buffer: ArrayDeque<[u8; (SBUS_PACKET_SIZE * 2) as usize], Wrapping>, } impl SBusPacketParser { pub fn new() -> SBusPacketParser { SBusPacketParser { buffer: ArrayDeque::new(), } } pub fn push_bytes(&mut self, bytes: &[u8]) { bytes.iter().for_each(|b| { self.buffer.push_back(*b); }) } pub fn try_parse(&mut self) -> Option<SBusPacket> { if self.buffer.len() < SBUS_PACKET_SIZE { return None; } if *self.buffer.get(0).unwrap() != SBUS_HEADER_BYTE { while self.buffer.len() > 0 && *self.buffer.get(0).unwrap() != SBUS_HEADER_BYTE { let _ = self.buffer.pop_front().unwrap(); } return None; } else if *self.buffer.get(SBUS_PACKET_SIZE - 1).unwrap() == SBUS_FOOTER_BYTE && self.buffer.get(SBUS_PACKET_SIZE - 2).unwrap() & SBUS_FLAG_BYTE_MASK == 0 { let mut data_bytes: [u16; 23] = [0; 23]; for i in 0..23 { data_bytes[i] = self.buffer.pop_front().unwrap_or(0) as u16; } let mut channels: [u16; 16] = [0; 16]; channels[0] = (((data_bytes[1]) | (data_bytes[2] << 8)) as u16 & 0x07FF).into(); channels[1] = ((((data_bytes[2] >> 3) | (data_bytes[3] << 5)) as u16) & 0x07FF).into(); channels[2] = ((((data_bytes[3] >> 6) | (data_bytes[4] << 2) | (data_bytes[5] << 10)) as u16) & 0x07FF) .into(); channels[3] = ((((data_bytes[5] >> 1) | (data_bytes[6] << 7)) as u16) & 0x07FF).into(); channels[4] = ((((data_bytes[6] >> 4) | (data_bytes[7] << 4)) as u16) & 0x07FF).into(); channels[5] = ((((data_bytes[7] >> 7) | (data_bytes[8] << 1) | (data_bytes[9] << 9)) as u16) & 0x07FF) .into(); channels[6] = ((((data_bytes[9] >> 2) | (data_bytes[10] << 6)) as u16) & 0x07FF).into(); channels[7] = ((((data_bytes[10] >> 5) | (data_bytes[11] << 3)) as u16) & 0x07FF).into(); channels[8] = ((((data_bytes[12]) | (data_bytes[13] << 8)) as u16) & 0x07FF).into(); channels[9] = ((((data_bytes[13] >> 3) | (data_bytes[14] << 5)) as u16) & 0x07FF).into(); channels[10] = ((((data_bytes[14] >> 6) | (data_bytes[15] << 2) | (data_bytes[16] << 10)) as u16) & 0x07FF) .into(); channels[11] = ((((data_bytes[16] >> 1) | (data_bytes[17] << 7)) as u16) & 0x07FF).into(); channels[12] = ((((data_bytes[17] >> 4) | (data_bytes[18] << 4)) as u16) & 0x07FF).into(); channels[13] = ((((data_bytes[18] >> 7) | (data_bytes[19] << 1) | (data_bytes[20] << 9)) as u16) & 0x07FF) .into(); channels[14] = ((((data_bytes[20] >> 2) | (data_bytes[21] << 6)) as u16) & 0x07FF).into(); channels[15] = ((((data_bytes[21] >> 5) | (data_bytes[22] << 3)) as u16) & 0x07FF).into(); let flag_byte = self.buffer.pop_front().unwrap_or(0); return Some(SBusPacket { channels, d1: is_flag_set(flag_byte, 0), d2: is_flag_set(flag_byte, 1), frame_lost: is_flag_set(flag_byte, 2), failsafe: is_flag_set(flag_byte, 3), }); } else { while self.buffer.len() > 0 && *self.buffer.get(0).unwrap() != SBUS_HEADER_BYTE { self.buffer.pop_front(); } } return None; } } fn is_flag_set(flag_byte: u8, idx: u8) -> bool { flag_byte & 1 << idx == 1 }
#![no_std] mod taranis; pub use taranis::TaranisX7SBusPacket; use arraydeque::{ArrayDeque, Wrapping}; const SBUS_FLAG_BYTE_MASK: u8 = 0b11110000; const SBUS_HEADER_BYTE: u8 = 0x0F; const SBUS_FOOTER_BYTE: u8 = 0b00000000; const SBUS_PACKET_SIZE: usize = 25; #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Copy, Clone)] pub struct SBusPacket { channels: [u16; 16], d1: bool, d2: bool, failsafe: bool, frame_lost: bool, } pub struct SBusPacketParser { buffer: ArrayDeque<[u8; (SBUS_PACKET_SIZE * 2) as usize], Wrapping>, } impl SBusPacketParser { pub fn new() -> SBusPacketParser { SBusPacketParser { buffer: ArrayDeque::new(), } } pub fn push_bytes(&mut self, bytes: &[u8]) { bytes.iter().for_each(|b| { self.buffer.push_back(*b); }) } pub fn try_parse(&mut self) -> Option<SBusPacket> { if self.buffer.len() < SBUS_PACKET_SIZE { return None; } if *self.buffer.get(0).unwrap() != SBUS_HEADER_BYTE { while self.buffer.len() > 0 && *self.buffer.get(0).unwrap() != SBUS_HEADER_BYTE { let _ = self.buffer.pop_front().unwrap(); } return None; } else if *self.buffer.get(SBUS_PACKET_SIZE - 1).unwrap() == SBUS_FOOTER_BYTE && self.buffer.get(SBUS_PACKET_SIZE - 2).unwrap() & SBUS_FLAG_BYTE_MASK == 0 { let mut data_bytes: [u16; 23] = [0; 23]; for i in 0..23 { data_bytes[i] = self.buffer.pop_front().unwrap_or(0) as u16; } let mut channels: [u16; 16] = [0; 16]; channels[0] = (((data_bytes[1]) | (data_bytes[2] << 8)) as u16 & 0x07FF).into(); channels[1] = ((((data_bytes[2] >> 3) | (data_bytes[3] << 5)) as u16) & 0x07FF).into(); channels[2] = ((((data_bytes[3] >> 6) | (data_bytes[4] << 2) | (data_bytes[5] << 10)) as u16) & 0x07FF) .into(); channels[3] = ((((data_bytes[5] >> 1) | (data_bytes[6] << 7)) as u16) & 0x07FF).into(); channels[4] = ((((data_bytes[6] >> 4) | (data_bytes[7] << 4)) as u16) & 0x07FF).into(); channels[5] = ((((data_bytes[7] >> 7) | (data_bytes[8] << 1) | (data_bytes[9] << 9)) as u16) & 0x07FF) .into(); channels[6] = ((((data_bytes[9] >> 2) | (data_bytes[10] << 6)) as u16) & 0x07FF).into(); channels[7] = ((((data_bytes[10] >> 5) | (data_bytes[11] << 3)) as u16) & 0x07FF).into(); channels[8] = ((((data_bytes[12]) | (data_bytes[13] << 8)) as u16) & 0x07FF).into(); channels[9] = ((((data_bytes[13] >> 3) | (data_bytes[14] << 5)) as u16) & 0x07FF).into(); channels[10] = ((((data_bytes[14] >> 6) | (data_bytes[15] << 2) | (data_bytes[16] << 10)) as u16) & 0x07FF) .into(); channels[11] = ((((data_bytes[16] >> 1) | (data_bytes[17] << 7)) as u16) & 0x07FF).into(); channels[12] = ((((data_bytes[17] >> 4) | (data_bytes[18] << 4)) as u16) & 0x07FF).into(); channels[13] = ((((data_bytes[18] >> 7) | (data_bytes[19] << 1) | (data_bytes[20] << 9)) as u16) & 0x07FF) .into();
} fn is_flag_set(flag_byte: u8, idx: u8) -> bool { flag_byte & 1 << idx == 1 }
channels[14] = ((((data_bytes[20] >> 2) | (data_bytes[21] << 6)) as u16) & 0x07FF).into(); channels[15] = ((((data_bytes[21] >> 5) | (data_bytes[22] << 3)) as u16) & 0x07FF).into(); let flag_byte = self.buffer.pop_front().unwrap_or(0); return Some(SBusPacket { channels, d1: is_flag_set(flag_byte, 0), d2: is_flag_set(flag_byte, 1), frame_lost: is_flag_set(flag_byte, 2), failsafe: is_flag_set(flag_byte, 3), }); } else { while self.buffer.len() > 0 && *self.buffer.get(0).unwrap() != SBUS_HEADER_BYTE { self.buffer.pop_front(); } } return None; }
function_block-function_prefix_line
[ { "content": "use crate::SBusPacket;\n\n\n\nconst X7_MIN: u16 = 172;\n\nconst X7_MAX: u16 = 1811;\n\nconst X7_RANGE: f32 = (X7_MAX - X7_MIN) as f32;\n\n\n\n#[derive(Debug, Copy, Clone)]\n\npub struct TaranisX7SBusPacket {\n\n pub channels: [f32; 16],\n\n failsafe: bool,\n\n frame_lost: bool,\n\n}\n\n\n\nimpl TaranisX7SBusPacket {\n\n pub fn new(source: SBusPacket) -> TaranisX7SBusPacket {\n\n let mut mapped_channels: [f32; 16] = [0f32; 16];\n\n for i in 0..16 {\n\n mapped_channels[i] = TaranisX7SBusPacket::map(source.channels[i]);\n\n }\n\n\n", "file_path": "src/taranis.rs", "rank": 1, "score": 12111.838137925293 }, { "content": " return TaranisX7SBusPacket {\n\n channels: mapped_channels,\n\n failsafe: source.failsafe,\n\n frame_lost: source.frame_lost,\n\n };\n\n }\n\n\n\n fn map(v: u16) -> f32 {\n\n let offset = v - X7_MIN;\n\n\n\n return offset as f32 / X7_RANGE;\n\n }\n\n}\n", "file_path": "src/taranis.rs", "rank": 2, "score": 12107.3689183394 } ]
Rust
sdk/storage/src/file/share/mod.rs
elemount/azure-sdk-for-rust
ba0cc92ba5245f93ade4270aa54a897cc8f78d92
pub mod access_tier; pub mod requests; pub mod responses; use crate::parsing_xml::{cast_must, cast_optional, traverse}; use access_tier::AccessTier; use azure_core::headers::{ META_PREFIX, SHARE_NEXT_ALLOWED_QUOTA_DOWNGRADE_TIME, SHARE_PROVISIONED_EGRESS_MBPS, SHARE_PROVISIONED_INGRESS_MBPS, SHARE_PROVISIONED_IOPS, SHARE_QUOTA, STORAGE_ACCESS_TIER, }; use azure_core::incompletevector::IncompleteVector; use chrono::{DateTime, Utc}; use http::{header, HeaderMap}; use std::collections::HashMap; use std::str::FromStr; use xml::{Element, Xml}; #[derive(Debug, Clone)] pub struct Share { pub name: String, pub snapshot: Option<String>, pub version: Option<String>, pub deleted: bool, pub last_modified: DateTime<Utc>, pub e_tag: String, pub quota: u64, pub provisioned_iops: Option<u64>, pub provisioned_ingress_mbps: Option<u64>, pub provisioned_egress_mbps: Option<u64>, pub next_allowed_quota_downgrade_time: Option<DateTime<Utc>>, pub deleted_time: Option<DateTime<Utc>>, pub remaining_retention_days: Option<u64>, pub access_tier: AccessTier, pub metadata: HashMap<String, String>, } impl AsRef<str> for Share { fn as_ref(&self) -> &str { &self.name } } impl Share { pub fn new(name: &str) -> Share { Share { name: name.to_owned(), snapshot: None, version: None, deleted: false, last_modified: Utc::now(), e_tag: "".to_owned(), quota: 0, provisioned_iops: None, provisioned_ingress_mbps: None, provisioned_egress_mbps: None, next_allowed_quota_downgrade_time: None, deleted_time: None, remaining_retention_days: None, access_tier: AccessTier::TransactionOptimized, metadata: HashMap::new(), } } pub(crate) fn from_response<NAME>( name: NAME, headers: &HeaderMap, ) -> Result<Share, crate::Error> where NAME: Into<String>, { let last_modified = match headers.get(header::LAST_MODIFIED) { Some(last_modified) => last_modified.to_str()?, None => { static LM: header::HeaderName = header::LAST_MODIFIED; return Err(crate::Error::MissingHeaderError(LM.as_str().to_owned())); } }; let last_modified = DateTime::parse_from_rfc2822(last_modified)?; let last_modified = DateTime::from_utc(last_modified.naive_utc(), Utc); let e_tag = match headers.get(header::ETAG) { Some(e_tag) => e_tag.to_str()?.to_owned(), None => { return Err(crate::Error::MissingHeaderError( header::ETAG.as_str().to_owned(), )); } }; let access_tier = match headers.get(STORAGE_ACCESS_TIER) { Some(access_tier) => access_tier.to_str()?, None => { return Err(crate::Error::MissingHeaderError( STORAGE_ACCESS_TIER.to_owned(), )) } }; let access_tier = AccessTier::from_str(access_tier)?; let quota = match headers.get(SHARE_QUOTA) { Some(quota_str) => quota_str.to_str()?.parse::<u64>()?, None => { return Err(crate::Error::MissingHeaderError(SHARE_QUOTA.to_owned())); } }; let provisioned_iops = match headers.get(SHARE_PROVISIONED_IOPS) { Some(value) => Some(value.to_str()?.parse::<u64>()?), None => None, }; let provisioned_ingress_mbps = match headers.get(SHARE_PROVISIONED_INGRESS_MBPS) { Some(value) => Some(value.to_str()?.parse::<u64>()?), None => None, }; let provisioned_egress_mbps = match headers.get(SHARE_PROVISIONED_EGRESS_MBPS) { Some(value) => Some(value.to_str()?.parse::<u64>()?), None => None, }; let next_allowed_quota_downgrade_time = match headers.get(SHARE_NEXT_ALLOWED_QUOTA_DOWNGRADE_TIME) { Some(value) => Some(DateTime::from_utc( DateTime::parse_from_rfc2822(value.to_str()?)?.naive_utc(), Utc, )), None => None, }; let mut metadata: HashMap<String, String> = HashMap::new(); for (key, value) in headers { if key.as_str().starts_with(META_PREFIX) { metadata.insert(key.as_str().to_owned(), value.to_str()?.to_owned()); } } Ok(Share { name: name.into(), last_modified, e_tag, access_tier, quota, provisioned_iops, provisioned_ingress_mbps, provisioned_egress_mbps, next_allowed_quota_downgrade_time, metadata, snapshot: None, version: None, deleted: false, deleted_time: None, remaining_retention_days: None, }) } fn parse(elem: &Element) -> Result<Share, crate::Error> { let name = cast_must::<String>(elem, &["Name"])?; let snapshot = cast_optional::<String>(elem, &["Snapshot"])?; let version = cast_optional::<String>(elem, &["Version"])?; let deleted = match cast_optional::<bool>(elem, &["Deleted"])? { Some(deleted_status) => deleted_status, None => false, }; let last_modified = cast_must::<DateTime<Utc>>(elem, &["Properties", "Last-Modified"])?; let e_tag = cast_must::<String>(elem, &["Properties", "Etag"])?; let quota = cast_must::<u64>(elem, &["Properties", "Quota"])?; let deleted_time = cast_optional::<DateTime<Utc>>(elem, &["Properties", "DeletedTime"])?; let remaining_retention_days = cast_optional::<u64>(elem, &["Properties", "RemainingRetentionDays"])?; let access_tier = cast_must::<AccessTier>(elem, &["Properties", "AccessTier"])?; let metadata = { let mut hm = HashMap::new(); let metadata = traverse(elem, &["Metadata"], true)?; for m in metadata { for key in &m.children { let elem = match key { Xml::ElementNode(elem) => elem, _ => { return Err(crate::Error::UnexpectedXMLError(String::from( "Metadata should contain an ElementNode", ))); } }; let key = elem.name.to_owned(); if elem.children.is_empty() { return Err(crate::Error::UnexpectedXMLError(String::from( "Metadata node should not be empty", ))); } let content = { match elem.children[0] { Xml::CharacterNode(ref content) => content.to_owned(), _ => { return Err(crate::Error::UnexpectedXMLError(String::from( "Metadata node should contain a CharacterNode with metadata value", ))); } } }; hm.insert(key, content); } } hm }; Ok(Share { name, snapshot, version, deleted, last_modified, e_tag, quota, deleted_time, remaining_retention_days, access_tier, metadata, provisioned_iops: None, provisioned_ingress_mbps: None, provisioned_egress_mbps: None, next_allowed_quota_downgrade_time: None, }) } } pub(crate) fn incomplete_vector_from_share_response( body: &str, ) -> Result<IncompleteVector<Share>, crate::Error> { let elem: Element = body.parse()?; let mut v = Vec::new(); for share in traverse(&elem, &["Shares", "Share"], true)? { v.push(Share::parse(share)?); } let next_marker = match cast_optional::<String>(&elem, &["NextMarker"])? { Some(ref nm) if nm.is_empty() => None, Some(nm) => Some(nm.into()), None => None, }; Ok(IncompleteVector::new(next_marker, v)) }
pub mod access_tier; pub mod requests; pub mod responses; use crate::parsing_xml::{cast_must, cast_optional, traverse}; use access_tier::AccessTier; use azure_core::headers::{ META_PREFIX, SHARE_NEXT_ALLOWED_QUOTA_DOWNGRADE_TIME, SHARE_PROVISIONED_EGRESS_MBPS, SHARE_PROVISIONED_INGRESS_MBPS, SHARE_PROVISIONED_IOPS, SHARE_QUOTA, STORAGE_ACCESS_TIER, }; use azure_core::incompletevector::IncompleteVector; use chrono::{DateTime, Utc}; use http::{header, HeaderMap}; use std::collections::HashMap; use std::str::FromStr; use xml::{Element, Xml}; #[derive(Debug, Clone)] pub struct Share { pub name: String, pub snapshot: Option<String>, pub version: Option<String>, pub deleted: bool, pub last_modified: DateTime<Utc>, pub e_tag: String, pub quota: u64, pub provisioned_iops: Option<u64>, pub provisioned_ingress_mbps: Option<u64>, pub provisioned_egress_mbps: Option<u64>, pub next_allowed_quota_downgrade_time: Option<DateTime<Utc>>, pub deleted_time: Option<DateTime<Utc>>, pub remaining_retention_days: Option<u64>, pub access_tier: AccessTier, pub metadata: HashMap<String, String>, } impl AsRef<str> for Share { fn as_ref(&self) -> &str { &self.name } } impl Share { pub fn new(name: &str) -> Share { Share { name: name.to_owned(), snapshot: None, version: None, deleted: false, last_modified: Utc::now(), e_tag: "".to_owned(), quota: 0, provisioned_iops: None, provisioned_ingress_mbps: None, provisioned_egress_mbps: None, next_allowed_quota_downgrade_time: None, deleted_time: None, remaining_retention_days: None, access_tier: AccessTier::TransactionOptimized, metadata: HashMap::new(), } } pub(crate) fn from_response<NAME>( name: NAME, headers: &HeaderMap, ) -> Result<Share, crate::Error> where NAME: Into<String>, { let last_modified = match headers.get(header::LAST_MODIFIED) { Some(last_modified) => last_modified.to_str()?, None => { static LM: header::HeaderName = header::LAST_MODIFIED; return Err(crate::Error::MissingHeaderError(LM.as_str().to_owned())); } }; let last_modified = DateTime::parse_from_rfc2822(last_modified)?; let last_modified = DateTime::from_utc(last_modified.naive_utc(), Utc); let e_tag = match headers.get(header::ETAG) { Some(e_tag) => e_tag.to_str()?.to_owned(), None => { return Err(crate::Error::MissingHeaderError( header::ETAG.as_str().to_owned(), )); } }; let access_tier = match headers.get(STORAGE_ACCESS_TIER) { Some(access_tier) => access_tier.to_str()?, None => { return Err(crate::Error::MissingHeaderError( STORAGE_ACCESS_TIER.to_owned(), )) } }; let access_tier = AccessTier::from_str(access_tier)?; let quota = match headers.get(SHARE_QUOTA) { Some(quota_str) => quota_str.to_str()?.parse::<u64>()?, None => { return Err(crate::Error::MissingHeaderError(SHARE_QUOTA.to_owned())); } };
let provisioned_ingress_mbps = match headers.get(SHARE_PROVISIONED_INGRESS_MBPS) { Some(value) => Some(value.to_str()?.parse::<u64>()?), None => None, }; let provisioned_egress_mbps = match headers.get(SHARE_PROVISIONED_EGRESS_MBPS) { Some(value) => Some(value.to_str()?.parse::<u64>()?), None => None, }; let next_allowed_quota_downgrade_time = match headers.get(SHARE_NEXT_ALLOWED_QUOTA_DOWNGRADE_TIME) { Some(value) => Some(DateTime::from_utc( DateTime::parse_from_rfc2822(value.to_str()?)?.naive_utc(), Utc, )), None => None, }; let mut metadata: HashMap<String, String> = HashMap::new(); for (key, value) in headers { if key.as_str().starts_with(META_PREFIX) { metadata.insert(key.as_str().to_owned(), value.to_str()?.to_owned()); } } Ok(Share { name: name.into(), last_modified, e_tag, access_tier, quota, provisioned_iops, provisioned_ingress_mbps, provisioned_egress_mbps, next_allowed_quota_downgrade_time, metadata, snapshot: None, version: None, deleted: false, deleted_time: None, remaining_retention_days: None, }) } fn parse(elem: &Element) -> Result<Share, crate::Error> { let name = cast_must::<String>(elem, &["Name"])?; let snapshot = cast_optional::<String>(elem, &["Snapshot"])?; let version = cast_optional::<String>(elem, &["Version"])?; let deleted = match cast_optional::<bool>(elem, &["Deleted"])? { Some(deleted_status) => deleted_status, None => false, }; let last_modified = cast_must::<DateTime<Utc>>(elem, &["Properties", "Last-Modified"])?; let e_tag = cast_must::<String>(elem, &["Properties", "Etag"])?; let quota = cast_must::<u64>(elem, &["Properties", "Quota"])?; let deleted_time = cast_optional::<DateTime<Utc>>(elem, &["Properties", "DeletedTime"])?; let remaining_retention_days = cast_optional::<u64>(elem, &["Properties", "RemainingRetentionDays"])?; let access_tier = cast_must::<AccessTier>(elem, &["Properties", "AccessTier"])?; let metadata = { let mut hm = HashMap::new(); let metadata = traverse(elem, &["Metadata"], true)?; for m in metadata { for key in &m.children { let elem = match key { Xml::ElementNode(elem) => elem, _ => { return Err(crate::Error::UnexpectedXMLError(String::from( "Metadata should contain an ElementNode", ))); } }; let key = elem.name.to_owned(); if elem.children.is_empty() { return Err(crate::Error::UnexpectedXMLError(String::from( "Metadata node should not be empty", ))); } let content = { match elem.children[0] { Xml::CharacterNode(ref content) => content.to_owned(), _ => { return Err(crate::Error::UnexpectedXMLError(String::from( "Metadata node should contain a CharacterNode with metadata value", ))); } } }; hm.insert(key, content); } } hm }; Ok(Share { name, snapshot, version, deleted, last_modified, e_tag, quota, deleted_time, remaining_retention_days, access_tier, metadata, provisioned_iops: None, provisioned_ingress_mbps: None, provisioned_egress_mbps: None, next_allowed_quota_downgrade_time: None, }) } } pub(crate) fn incomplete_vector_from_share_response( body: &str, ) -> Result<IncompleteVector<Share>, crate::Error> { let elem: Element = body.parse()?; let mut v = Vec::new(); for share in traverse(&elem, &["Shares", "Share"], true)? { v.push(Share::parse(share)?); } let next_marker = match cast_optional::<String>(&elem, &["NextMarker"])? { Some(ref nm) if nm.is_empty() => None, Some(nm) => Some(nm.into()), None => None, }; Ok(IncompleteVector::new(next_marker, v)) }
let provisioned_iops = match headers.get(SHARE_PROVISIONED_IOPS) { Some(value) => Some(value.to_str()?.parse::<u64>()?), None => None, };
assignment_statement
[]
Rust
dora/src/gc/swiper/sweep.rs
dinfuehr/dora
bcfdac576b729e2bbb2422d0239426b884059b2c
use parking_lot::Mutex; use scoped_threadpool::Pool; use std::sync::Arc; use crate::driver::cmd::Args; use crate::gc::root::{get_rootset, Slot}; use crate::gc::swiper::card::CardTable; use crate::gc::swiper::controller::{self, HeapConfig, SharedHeapConfig}; use crate::gc::swiper::crossing::CrossingMap; use crate::gc::swiper::large::LargeSpace; use crate::gc::swiper::sweep::old::OldGen; use crate::gc::swiper::verify::VerifierPhase; use crate::gc::swiper::young::YoungGen; use crate::gc::swiper::{CollectionKind, CARD_SIZE_BITS, LARGE_OBJECT_SIZE}; use crate::gc::tlab; use crate::gc::{align_gen, formatted_size, GEN_SIZE}; use crate::gc::{Address, Collector, GcReason, Region}; use crate::mem; use crate::os::{self, MemoryPermission}; use crate::safepoint; use crate::vm::VM; mod old; mod sweep; pub struct SweepSwiper { heap: Region, reserved_area: Region, young: YoungGen, old: OldGen, large: LargeSpace, card_table: CardTable, crossing_map: CrossingMap, card_table_offset: usize, emit_write_barrier: bool, min_heap_size: usize, max_heap_size: usize, threadpool: Mutex<Pool>, config: SharedHeapConfig, } impl SweepSwiper { pub fn new(args: &Args) -> SweepSwiper { let max_heap_size = align_gen(args.max_heap_size()); let min_heap_size = align_gen(args.min_heap_size()); let mut config = HeapConfig::new(min_heap_size, max_heap_size); controller::init(&mut config, args); let card_size = mem::page_align((4 * max_heap_size) >> CARD_SIZE_BITS); let crossing_size = mem::page_align(max_heap_size >> CARD_SIZE_BITS); let reserve_size = max_heap_size * 4 + card_size + crossing_size; let reservation = os::reserve_align(reserve_size, GEN_SIZE, false); let heap_start = reservation.start; assert!(heap_start.is_gen_aligned()); let heap_end = heap_start.offset(4 * max_heap_size); let reserved_area = heap_start.region_start(reserve_size); let card_table_offset = heap_end.to_usize() - (heap_start.to_usize() >> CARD_SIZE_BITS); let card_start = heap_end; let card_end = card_start.offset(card_size); os::commit_at(card_start, card_size, MemoryPermission::ReadWrite); let crossing_start = card_end; let crossing_end = crossing_start.offset(crossing_size); os::commit_at(crossing_start, crossing_size, MemoryPermission::ReadWrite); let young_start = heap_start; let young_end = young_start.offset(max_heap_size); let young = Region::new(young_start, young_end); let old_start = young_end; let old_end = old_start.offset(max_heap_size); let eden_size = config.eden_size; let semi_size = config.semi_size; let large_start = old_end; let large_end = large_start.offset(2 * max_heap_size); let card_table = CardTable::new( card_start, card_end, Region::new(old_start, large_end), old_end, max_heap_size, ); let crossing_map = CrossingMap::new(crossing_start, crossing_end, max_heap_size); let young = YoungGen::new(young, eden_size, semi_size, args.flag_gc_verify); let config = Arc::new(Mutex::new(config)); let old = OldGen::new( old_start, old_end, crossing_map.clone(), card_table.clone(), config.clone(), ); let large = LargeSpace::new(large_start, large_end, config.clone()); if args.flag_gc_verbose { println!( "GC: heap info: {}, eden {}, semi {}, card {}, crossing {}", formatted_size(max_heap_size), formatted_size(eden_size), formatted_size(semi_size), formatted_size(card_size), formatted_size(crossing_size) ); } let nworkers = args.gc_workers(); let emit_write_barrier = !args.flag_disable_barrier; SweepSwiper { heap: Region::new(heap_start, heap_end), reserved_area, young, old, large, card_table, crossing_map, config, card_table_offset, emit_write_barrier, min_heap_size, max_heap_size, threadpool: Mutex::new(Pool::new(nworkers as u32)), } } } impl Collector for SweepSwiper { fn supports_tlab(&self) -> bool { true } fn alloc_tlab_area(&self, _vm: &VM, _size: usize) -> Option<Region> { unimplemented!() } fn alloc(&self, vm: &VM, size: usize, array_ref: bool) -> Address { if size < LARGE_OBJECT_SIZE { self.alloc_normal(vm, size, array_ref) } else { self.alloc_large(vm, size, array_ref) } } fn collect(&self, _vm: &VM, _reason: GcReason) { unimplemented!() } fn minor_collect(&self, _vm: &VM, _reason: GcReason) { unimplemented!() } fn needs_write_barrier(&self) -> bool { self.emit_write_barrier } fn card_table_offset(&self) -> usize { self.card_table_offset } fn dump_summary(&self, _runtime: f32) { unimplemented!() } fn verify_ref(&self, _vm: &VM, _reference: Address) { unimplemented!() } } impl SweepSwiper { fn perform_collection_and_choose(&self, vm: &VM, reason: GcReason) -> CollectionKind { let kind = controller::choose_collection_kind(&self.config, &vm.args, &self.young); self.perform_collection(vm, kind, reason) } fn perform_collection( &self, vm: &VM, kind: CollectionKind, mut reason: GcReason, ) -> CollectionKind { safepoint::stop_the_world(vm, |threads| { controller::start(&self.config, &self.young, &self.old, &self.large); tlab::make_iterable_all(vm, threads); let rootset = get_rootset(vm, threads); let kind = match kind { CollectionKind::Minor => { let promotion_failed = self.minor_collect(vm, reason, &rootset); if promotion_failed { reason = GcReason::PromotionFailure; self.full_collect(vm, reason, &rootset); CollectionKind::Full } else { CollectionKind::Minor } } CollectionKind::Full => { self.full_collect(vm, reason, &rootset); CollectionKind::Full } }; controller::stop( &self.config, kind, &self.young, &self.old, &self.large, &vm.args, reason, ); kind }) } fn minor_collect(&self, _vm: &VM, _reason: GcReason, _rootset: &[Slot]) -> bool { unimplemented!() } fn full_collect(&self, _vm: &VM, _reason: GcReason, _rootset: &[Slot]) { unimplemented!(); } fn verify( &self, _vm: &VM, _phase: VerifierPhase, _kind: CollectionKind, _name: &str, _rootset: &[Slot], _promotion_failed: bool, ) { unimplemented!(); } fn alloc_normal(&self, vm: &VM, size: usize, _array_ref: bool) -> Address { let ptr = self.young.bump_alloc(size); if !ptr.is_null() { return ptr; } self.perform_collection_and_choose(vm, GcReason::AllocationFailure); self.young.bump_alloc(size) } fn alloc_large(&self, vm: &VM, size: usize, _: bool) -> Address { let ptr = self.large.alloc(size); if !ptr.is_null() { return ptr; } self.perform_collection(vm, CollectionKind::Full, GcReason::AllocationFailure); self.large.alloc(size) } }
use parking_lot::Mutex; use scoped_threadpool::Pool; use std::sync::Arc; use crate::driver::cmd::Args; use crate::gc::root::{get_rootset, Slot}; use crate::gc::swiper::card::CardTable; use crate::gc::swiper::controller::{self, HeapConfig, SharedHeapConfig}; use crate::gc::swiper::crossing::CrossingMap; use crate::gc::swiper::large::LargeSpace; use crate::gc::swiper::sweep::old::OldGen; use crate::gc::swiper::verify::VerifierPhase; use crate::gc::swiper::young::YoungGen; use crate::gc::swiper::{CollectionKind, CARD_SIZE_BITS, LARGE_OBJECT_SIZE}; use crate::gc::tlab; use crate::gc::{align_gen, formatted_size, GEN_SIZE}; use crate::gc::{Address, Collector, GcReason, Region}; use crate::mem; use crate::os::{self, MemoryPermission}; use crate::safepoint; use crate::vm::VM; mod old; mod sweep; pub struct SweepSwiper { heap: Region, reserved_area: Region, young: YoungGen, old: OldGen, large: LargeSpace, card_table: CardTable, crossing_map: CrossingMap, card_table_offset: usize, emit_write_barrier: bool, min_heap_size: usize, max_heap_size: usize, threadpool: Mutex<Pool>, config: SharedHeapConfig, } impl SweepSwiper { pub fn new(args: &Args) -> SweepSwiper { let max_heap_size = align_gen(args.max_heap_size()); let min_heap_size = align_ge
} impl Collector for SweepSwiper { fn supports_tlab(&self) -> bool { true } fn alloc_tlab_area(&self, _vm: &VM, _size: usize) -> Option<Region> { unimplemented!() } fn alloc(&self, vm: &VM, size: usize, array_ref: bool) -> Address { if size < LARGE_OBJECT_SIZE { self.alloc_normal(vm, size, array_ref) } else { self.alloc_large(vm, size, array_ref) } } fn collect(&self, _vm: &VM, _reason: GcReason) { unimplemented!() } fn minor_collect(&self, _vm: &VM, _reason: GcReason) { unimplemented!() } fn needs_write_barrier(&self) -> bool { self.emit_write_barrier } fn card_table_offset(&self) -> usize { self.card_table_offset } fn dump_summary(&self, _runtime: f32) { unimplemented!() } fn verify_ref(&self, _vm: &VM, _reference: Address) { unimplemented!() } } impl SweepSwiper { fn perform_collection_and_choose(&self, vm: &VM, reason: GcReason) -> CollectionKind { let kind = controller::choose_collection_kind(&self.config, &vm.args, &self.young); self.perform_collection(vm, kind, reason) } fn perform_collection( &self, vm: &VM, kind: CollectionKind, mut reason: GcReason, ) -> CollectionKind { safepoint::stop_the_world(vm, |threads| { controller::start(&self.config, &self.young, &self.old, &self.large); tlab::make_iterable_all(vm, threads); let rootset = get_rootset(vm, threads); let kind = match kind { CollectionKind::Minor => { let promotion_failed = self.minor_collect(vm, reason, &rootset); if promotion_failed { reason = GcReason::PromotionFailure; self.full_collect(vm, reason, &rootset); CollectionKind::Full } else { CollectionKind::Minor } } CollectionKind::Full => { self.full_collect(vm, reason, &rootset); CollectionKind::Full } }; controller::stop( &self.config, kind, &self.young, &self.old, &self.large, &vm.args, reason, ); kind }) } fn minor_collect(&self, _vm: &VM, _reason: GcReason, _rootset: &[Slot]) -> bool { unimplemented!() } fn full_collect(&self, _vm: &VM, _reason: GcReason, _rootset: &[Slot]) { unimplemented!(); } fn verify( &self, _vm: &VM, _phase: VerifierPhase, _kind: CollectionKind, _name: &str, _rootset: &[Slot], _promotion_failed: bool, ) { unimplemented!(); } fn alloc_normal(&self, vm: &VM, size: usize, _array_ref: bool) -> Address { let ptr = self.young.bump_alloc(size); if !ptr.is_null() { return ptr; } self.perform_collection_and_choose(vm, GcReason::AllocationFailure); self.young.bump_alloc(size) } fn alloc_large(&self, vm: &VM, size: usize, _: bool) -> Address { let ptr = self.large.alloc(size); if !ptr.is_null() { return ptr; } self.perform_collection(vm, CollectionKind::Full, GcReason::AllocationFailure); self.large.alloc(size) } }
n(args.min_heap_size()); let mut config = HeapConfig::new(min_heap_size, max_heap_size); controller::init(&mut config, args); let card_size = mem::page_align((4 * max_heap_size) >> CARD_SIZE_BITS); let crossing_size = mem::page_align(max_heap_size >> CARD_SIZE_BITS); let reserve_size = max_heap_size * 4 + card_size + crossing_size; let reservation = os::reserve_align(reserve_size, GEN_SIZE, false); let heap_start = reservation.start; assert!(heap_start.is_gen_aligned()); let heap_end = heap_start.offset(4 * max_heap_size); let reserved_area = heap_start.region_start(reserve_size); let card_table_offset = heap_end.to_usize() - (heap_start.to_usize() >> CARD_SIZE_BITS); let card_start = heap_end; let card_end = card_start.offset(card_size); os::commit_at(card_start, card_size, MemoryPermission::ReadWrite); let crossing_start = card_end; let crossing_end = crossing_start.offset(crossing_size); os::commit_at(crossing_start, crossing_size, MemoryPermission::ReadWrite); let young_start = heap_start; let young_end = young_start.offset(max_heap_size); let young = Region::new(young_start, young_end); let old_start = young_end; let old_end = old_start.offset(max_heap_size); let eden_size = config.eden_size; let semi_size = config.semi_size; let large_start = old_end; let large_end = large_start.offset(2 * max_heap_size); let card_table = CardTable::new( card_start, card_end, Region::new(old_start, large_end), old_end, max_heap_size, ); let crossing_map = CrossingMap::new(crossing_start, crossing_end, max_heap_size); let young = YoungGen::new(young, eden_size, semi_size, args.flag_gc_verify); let config = Arc::new(Mutex::new(config)); let old = OldGen::new( old_start, old_end, crossing_map.clone(), card_table.clone(), config.clone(), ); let large = LargeSpace::new(large_start, large_end, config.clone()); if args.flag_gc_verbose { println!( "GC: heap info: {}, eden {}, semi {}, card {}, crossing {}", formatted_size(max_heap_size), formatted_size(eden_size), formatted_size(semi_size), formatted_size(card_size), formatted_size(crossing_size) ); } let nworkers = args.gc_workers(); let emit_write_barrier = !args.flag_disable_barrier; SweepSwiper { heap: Region::new(heap_start, heap_end), reserved_area, young, old, large, card_table, crossing_map, config, card_table_offset, emit_write_barrier, min_heap_size, max_heap_size, threadpool: Mutex::new(Pool::new(nworkers as u32)), } }
function_block-function_prefixed
[ { "content": "pub fn start(rootset: &[Slot], heap: Region, perm: Region, threadpool: &mut Pool) {\n\n let number_workers = threadpool.thread_count() as usize;\n\n let mut workers = Vec::with_capacity(number_workers);\n\n let mut stealers = Vec::with_capacity(number_workers);\n\n let injector = Injector::new();\n\n\n\n for _ in 0..number_workers {\n\n let w = Worker::new_lifo();\n\n let s = w.stealer();\n\n workers.push(w);\n\n stealers.push(s);\n\n }\n\n\n\n for root in rootset {\n\n let root_ptr = root.get();\n\n\n\n if heap.contains(root_ptr) {\n\n let root_obj = root_ptr.to_mut_obj();\n\n\n\n if !root_obj.header().is_marked_non_atomic() {\n", "file_path": "dora/src/gc/pmarking.rs", "rank": 0, "score": 445633.4186897788 }, { "content": "pub fn start(rootset: &[Slot], heap: Region, perm: Region) {\n\n let mut marking_stack: Vec<Address> = Vec::new();\n\n\n\n for root in rootset {\n\n let root_ptr = root.get();\n\n\n\n if heap.contains(root_ptr) {\n\n let root_obj = root_ptr.to_mut_obj();\n\n\n\n if !root_obj.header().is_marked_non_atomic() {\n\n marking_stack.push(root_ptr);\n\n root_obj.header_mut().mark_non_atomic();\n\n }\n\n } else {\n\n debug_assert!(root_ptr.is_null() || perm.contains(root_ptr));\n\n }\n\n }\n\n\n\n while marking_stack.len() > 0 {\n\n let object_addr = marking_stack.pop().expect(\"stack already empty\");\n", "file_path": "dora/src/gc/marking.rs", "rank": 1, "score": 407305.6830049029 }, { "content": "pub fn init(config: &mut HeapConfig, args: &Args) {\n\n assert!(config.min_heap_size <= config.max_heap_size);\n\n\n\n let young_size = if let Some(young_size) = args.young_size() {\n\n min(align_gen(young_size), config.max_heap_size - GEN_SIZE)\n\n } else if args.young_appel() {\n\n let max_heap_size = (config.max_heap_size as f64 * 0.9) as usize;\n\n align_gen(max_heap_size / 2)\n\n } else {\n\n unreachable!();\n\n };\n\n\n\n let young_size = max(young_size, GEN_SIZE);\n\n let (eden_size, semi_size) = calculate_young_size(args, young_size, 0);\n\n\n\n config.eden_size = eden_size;\n\n config.semi_size = semi_size;\n\n\n\n let max_old_limit = config.max_heap_size - young_size;\n\n let min_old_limit = if config.min_heap_size > young_size {\n", "file_path": "dora/src/gc/swiper/controller.rs", "rank": 2, "score": 379586.55194110994 }, { "content": "fn memory_size(young: &YoungGen, old: &dyn CommonOldGen, large: &LargeSpace) -> usize {\n\n let (eden_size, semi_size) = young.committed_size();\n\n let young_size = eden_size + semi_size;\n\n\n\n young_size + old.committed_size() + large.committed_size()\n\n}\n\n\n\npub struct HeapConfig {\n\n min_heap_size: usize,\n\n max_heap_size: usize,\n\n\n\n pub eden_size: usize,\n\n pub semi_size: usize,\n\n pub old_size: usize,\n\n pub old_limit: usize,\n\n\n\n gc_start: u64,\n\n gc_duration: f32,\n\n\n\n start_object_size: usize,\n", "file_path": "dora/src/gc/swiper/controller.rs", "rank": 3, "score": 359876.16268723767 }, { "content": "fn object_size(young: &YoungGen, old: &dyn CommonOldGen, large: &LargeSpace) -> usize {\n\n young.active_size() + old.active_size() + large.committed_size()\n\n}\n\n\n", "file_path": "dora/src/gc/swiper/controller.rs", "rank": 4, "score": 359876.1626872376 }, { "content": "/// returns true if given value is a multiple of a page size.\n\npub fn is_page_aligned(val: usize) -> bool {\n\n let align = os::page_size_bits();\n\n\n\n // we can use shifts here since we know that\n\n // page size is power of 2\n\n val == ((val >> align) << align)\n\n}\n\n\n", "file_path": "dora/src/mem.rs", "rank": 5, "score": 300156.86889879877 }, { "content": "/// returns true if given size is gen aligned\n\npub fn gen_aligned(size: usize) -> bool {\n\n (size & (GEN_SIZE - 1)) == 0\n\n}\n\n\n\n#[derive(Copy, Clone, PartialEq, Eq)]\n\npub enum GcReason {\n\n PromotionFailure,\n\n AllocationFailure,\n\n ForceCollect,\n\n ForceMinorCollect,\n\n Stress,\n\n StressMinor,\n\n}\n\n\n\nimpl GcReason {\n\n fn message(&self) -> &'static str {\n\n match self {\n\n GcReason::PromotionFailure => \"promo failure\",\n\n GcReason::AllocationFailure => \"alloc failure\",\n\n GcReason::ForceCollect => \"force collect\",\n", "file_path": "dora/src/gc.rs", "rank": 6, "score": 300156.86889879877 }, { "content": "/// returns 'true' if th given `value` is already aligned\n\n/// to `align`.\n\npub fn is_aligned(value: usize, align: usize) -> bool {\n\n align_usize(value, align) == value\n\n}\n\n\n", "file_path": "dora/src/mem.rs", "rank": 7, "score": 298227.16665233154 }, { "content": "fn forward_full(object: Address, heap: Region, perm: Region, large: Region) -> Option<Address> {\n\n if heap.contains(object) {\n\n let obj = object.to_mut_obj();\n\n\n\n if obj.header().is_marked_non_atomic() {\n\n if large.contains(object) {\n\n Some(object)\n\n } else {\n\n let new_address = obj.header().fwdptr_non_atomic();\n\n Some(new_address)\n\n }\n\n } else {\n\n None\n\n }\n\n } else {\n\n debug_assert!(perm.contains(object));\n\n Some(object)\n\n }\n\n}\n\n\n", "file_path": "dora/src/gc/swiper.rs", "rank": 8, "score": 289157.29008713854 }, { "content": "/// round the given value up to the nearest multiple of a generation\n\npub fn align_region(value: usize) -> usize {\n\n let align = REGION_SIZE_BITS;\n\n // we know that region size is power of 2, hence\n\n // we can use shifts instead of expensive division\n\n ((value + (1 << align) - 1) >> align) << align\n\n}\n\n\n\npub struct RegionSet {\n\n bits: FixedBitSet,\n\n}\n\n\n\nimpl RegionSet {\n\n fn new(regions: usize) -> RegionSet {\n\n RegionSet {\n\n bits: FixedBitSet::with_capacity(regions),\n\n }\n\n }\n\n\n\n fn clear(&mut self) {\n\n self.bits.clear();\n", "file_path": "dora/src/gc/region.rs", "rank": 9, "score": 286511.48456877534 }, { "content": "fn verify_marking_region(region: Region, heap: Region) {\n\n walk_region(region, |_obj, obj_address, _size| {\n\n verify_marking_object(obj_address, heap);\n\n });\n\n}\n\n\n", "file_path": "dora/src/gc/swiper/compact.rs", "rank": 10, "score": 284928.1320120931 }, { "content": "#[cfg(target_family = \"windows\")]\n\npub fn commit(size: usize, executable: bool) -> Address {\n\n debug_assert!(mem::is_page_aligned(size));\n\n\n\n use winapi::um::memoryapi::VirtualAlloc;\n\n use winapi::um::winnt::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PAGE_READWRITE};\n\n\n\n let prot = if executable {\n\n PAGE_EXECUTE_READWRITE\n\n } else {\n\n PAGE_READWRITE\n\n };\n\n\n\n let ptr = unsafe { VirtualAlloc(ptr::null_mut(), size, MEM_COMMIT | MEM_RESERVE, prot) };\n\n\n\n if ptr.is_null() {\n\n panic!(\"VirtualAlloc failed\");\n\n }\n\n\n\n Address::from_ptr(ptr)\n\n}\n\n\n", "file_path": "dora/src/os/allocator.rs", "rank": 11, "score": 281123.9238935322 }, { "content": "pub fn reserve_align(size: usize, align: usize, jitting: bool) -> Reservation {\n\n debug_assert!(mem::is_page_aligned(size));\n\n debug_assert!(mem::is_page_aligned(align));\n\n\n\n let align = if align == 0 { page_size() } else { align };\n\n let unaligned_size = size + align - page_size();\n\n\n\n let unaligned_start = reserve(unaligned_size, jitting);\n\n let aligned_start: Address = mem::align_usize(unaligned_start.to_usize(), align).into();\n\n\n\n let gap_start = aligned_start.offset_from(unaligned_start);\n\n let gap_end = unaligned_size - size - gap_start;\n\n\n\n if gap_start > 0 {\n\n uncommit(unaligned_start, gap_start);\n\n }\n\n\n\n if gap_end > 0 {\n\n uncommit(aligned_start.offset(size), gap_end);\n\n }\n", "file_path": "dora/src/os/allocator.rs", "rank": 12, "score": 275092.59559819126 }, { "content": "pub fn struct_accessible_from(vm: &VM, struct_id: StructId, namespace_id: NamespaceId) -> bool {\n\n let xstruct = vm.structs.idx(struct_id);\n\n let xstruct = xstruct.read();\n\n\n\n accessible_from(vm, xstruct.namespace_id, xstruct.is_pub, namespace_id)\n\n}\n\n\n", "file_path": "dora/src/vm/structs.rs", "rank": 13, "score": 274038.6612730156 }, { "content": "pub fn has_popcnt() -> bool {\n\n *HAS_POPCNT\n\n}\n\n\n", "file_path": "dora/src/cpu/x64.rs", "rank": 14, "score": 270801.2675686778 }, { "content": "pub fn supported() -> bool {\n\n false\n\n}\n\n\n", "file_path": "dora/src/disassembler/none.rs", "rank": 15, "score": 270801.2675686778 }, { "content": "pub fn has_lzcnt() -> bool {\n\n *HAS_LZCNT\n\n}\n\n\n", "file_path": "dora/src/cpu/x64.rs", "rank": 16, "score": 270801.2675686778 }, { "content": "pub fn has_round() -> bool {\n\n true\n\n}\n\n\n", "file_path": "dora/src/cpu/arm64.rs", "rank": 17, "score": 270801.2675686778 }, { "content": "pub fn has_lzcnt() -> bool {\n\n true\n\n}\n\n\n", "file_path": "dora/src/cpu/arm64.rs", "rank": 18, "score": 270801.2675686778 }, { "content": "pub fn supported() -> bool {\n\n true\n\n}\n\n\n", "file_path": "dora/src/disassembler/capstone.rs", "rank": 19, "score": 270801.2675686778 }, { "content": "pub fn has_round() -> bool {\n\n *HAS_ROUND\n\n}\n\n\n", "file_path": "dora/src/cpu/x64.rs", "rank": 20, "score": 270801.2675686778 }, { "content": "pub fn has_tzcnt() -> bool {\n\n *HAS_TZCNT\n\n}\n\n\n\nlazy_static! {\n\n// support for floating point rounding\n\nstatic ref HAS_ROUND: bool = is_x86_feature_detected!(\"sse4.1\");\n\nstatic ref HAS_POPCNT: bool = is_x86_feature_detected!(\"popcnt\");\n\nstatic ref HAS_LZCNT: bool = is_x86_feature_detected!(\"lzcnt\");\n\nstatic ref HAS_TZCNT: bool = is_x86_feature_detected!(\"bmi1\");\n\n}\n\n\n\n// first param offset to rbp is +16,\n\n// rbp+0 -> saved rbp\n\n// rbp+8 -> return address\n\npub static PARAM_OFFSET: i32 = 16;\n\n\n", "file_path": "dora/src/cpu/x64.rs", "rank": 21, "score": 270801.2675686778 }, { "content": "pub fn has_tzcnt() -> bool {\n\n true\n\n}\n\n\n\nimpl From<CondCode> for Cond {\n\n fn from(c: CondCode) -> Cond {\n\n match c {\n\n CondCode::Zero => Cond::EQ,\n\n CondCode::NonZero => Cond::NE,\n\n CondCode::Equal => Cond::EQ,\n\n CondCode::NotEqual => Cond::NE,\n\n CondCode::Greater => Cond::GT,\n\n CondCode::GreaterEq => Cond::GE,\n\n CondCode::Less => Cond::LT,\n\n CondCode::LessEq => Cond::LE,\n\n CondCode::UnsignedGreater => Cond::HI,\n\n CondCode::UnsignedGreaterEq => Cond::HS,\n\n CondCode::UnsignedLess => Cond::LO,\n\n CondCode::UnsignedLessEq => Cond::LS,\n\n }\n", "file_path": "dora/src/cpu/arm64.rs", "rank": 22, "score": 270801.2675686778 }, { "content": "pub fn has_popcnt() -> bool {\n\n true\n\n}\n\n\n", "file_path": "dora/src/cpu/arm64.rs", "rank": 23, "score": 270801.2675686778 }, { "content": "fn print(config: &HeapConfig, kind: CollectionKind, reason: GcReason) {\n\n match kind {\n\n CollectionKind::Minor => {\n\n println!(\n\n \"GC: {} ({}) {}/{} -> {}/{}; {:.2} ms; {} promoted; {} copied; {} garbage\",\n\n kind,\n\n reason,\n\n formatted_size(config.start_object_size),\n\n formatted_size(config.start_memory_size),\n\n formatted_size(config.end_object_size),\n\n formatted_size(config.end_memory_size),\n\n config.gc_duration,\n\n formatted_size(config.minor_promoted),\n\n formatted_size(config.minor_copied),\n\n formatted_size(config.minor_dead),\n\n );\n\n }\n\n\n\n CollectionKind::Full => {\n\n println!(\n", "file_path": "dora/src/gc/swiper/controller.rs", "rank": 24, "score": 270154.7273377528 }, { "content": "pub fn has_lse_atomics() -> bool {\n\n *HAS_LSE_ATOMICS\n\n}\n\n\n\nlazy_static! {\n\n static ref HAS_LSE_ATOMICS: bool = check_support_for_lse_atomics();\n\n}\n\n\n", "file_path": "dora/src/cpu/arm64.rs", "rank": 25, "score": 267422.76155855815 }, { "content": "pub fn initialize(tlab: Region) {\n\n current_thread().tld.tlab_initialize(tlab.start, tlab.end);\n\n}\n\n\n", "file_path": "dora/src/gc/tlab.rs", "rank": 26, "score": 260413.06440836898 }, { "content": "pub fn walk_region<F>(region: Region, mut fct: F)\n\nwhere\n\n F: FnMut(&mut Obj, Address, usize),\n\n{\n\n let mut scan = region.start;\n\n\n\n while scan < region.end {\n\n let object = scan.to_mut_obj();\n\n\n\n if object.header().vtblptr().is_null() {\n\n scan = scan.add_ptr(1);\n\n continue;\n\n }\n\n\n\n let object_size = object.size();\n\n fct(object, scan, object_size);\n\n scan = scan.offset(object_size);\n\n }\n\n}\n\n\n\nconst MIN_OBJECTS_TO_SKIP: usize = 4;\n\n\n", "file_path": "dora/src/gc/swiper.rs", "rank": 27, "score": 256167.53727445225 }, { "content": "fn determine_rootset(rootset: &mut Vec<Slot>, vm: &VM, fp: usize, pc: usize) -> bool {\n\n let code_map = vm.code_map.lock();\n\n let data = code_map.get(pc.into());\n\n\n\n match data {\n\n Some(CodeDescriptor::DoraFct(fct_id)) => {\n\n let jit_fct = vm.jit_fcts.idx(fct_id);\n\n\n\n let offset = pc - jit_fct.instruction_start().to_usize();\n\n let gcpoint = jit_fct\n\n .gcpoint_for_offset(offset as u32)\n\n .expect(\"no gcpoint\");\n\n\n\n for &offset in &gcpoint.offsets {\n\n let addr = (fp as isize + offset as isize) as usize;\n\n rootset.push(Slot::at(addr.into()));\n\n }\n\n\n\n true\n\n }\n", "file_path": "dora/src/gc/root.rs", "rank": 28, "score": 256026.8294653666 }, { "content": "/// returns true if value fits into i32 (signed 32bits).\n\npub fn fits_i32(value: i64) -> bool {\n\n i32::MIN as i64 <= value && value <= i32::MAX as i64\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_fits_u8() {\n\n assert_eq!(true, fits_u8(0));\n\n assert_eq!(true, fits_u8(255));\n\n assert_eq!(false, fits_u8(256));\n\n assert_eq!(false, fits_u8(-1));\n\n }\n\n\n\n #[test]\n\n fn test_fits_i32() {\n\n assert_eq!(true, fits_i32(0));\n\n assert_eq!(true, fits_i32(i32::MAX as i64));\n\n assert_eq!(true, fits_i32(i32::MIN as i64));\n\n assert_eq!(false, fits_i32(i32::MAX as i64 + 1));\n\n assert_eq!(false, fits_i32(i32::MIN as i64 - 1));\n\n }\n\n}\n", "file_path": "dora/src/mem.rs", "rank": 29, "score": 250306.65462113678 }, { "content": "/// returns true if value fits into u8 (unsigned 8bits).\n\npub fn fits_u8(value: i64) -> bool {\n\n 0 <= value && value <= 255\n\n}\n\n\n", "file_path": "dora/src/mem.rs", "rank": 30, "score": 250306.65462113678 }, { "content": "pub fn impl_matches(\n\n vm: &VM,\n\n check_ty: SourceType,\n\n check_type_param_defs: &[TypeParam],\n\n check_type_param_defs2: Option<&TypeParamDefinition>,\n\n impl_id: ImplId,\n\n) -> Option<SourceTypeArray> {\n\n let ximpl = vm.impls[impl_id].read();\n\n extension_matches_ty(\n\n vm,\n\n check_ty,\n\n check_type_param_defs,\n\n check_type_param_defs2,\n\n ximpl.ty.clone(),\n\n &ximpl.type_params,\n\n )\n\n}\n\n\n", "file_path": "dora/src/vm/impls.rs", "rank": 31, "score": 248115.57295857053 }, { "content": "pub fn should_file_be_parsed(path: &Path) -> bool {\n\n if !path.is_file() {\n\n return false;\n\n }\n\n\n\n let name = path.to_string_lossy();\n\n\n\n if !name.ends_with(\".dora\") {\n\n return false;\n\n }\n\n\n\n if name.ends_with(\"_x64.dora\") {\n\n cfg!(target_arch = \"x86_64\")\n\n } else if name.ends_with(\"_arm64.dora\") {\n\n cfg!(target_arch = \"aarch64\")\n\n } else {\n\n true\n\n }\n\n}\n\n\n", "file_path": "dora/src/semck/globaldef.rs", "rank": 32, "score": 247208.02514903684 }, { "content": "pub fn find_trait_impl(\n\n vm: &VM,\n\n fct_id: FctId,\n\n trait_id: TraitId,\n\n object_type: SourceType,\n\n) -> FctId {\n\n debug_assert!(!object_type.contains_type_param(vm));\n\n let impl_id = find_impl(vm, object_type, &[], trait_id)\n\n .expect(\"no impl found for generic trait method call\");\n\n\n\n let ximpl = vm.impls[impl_id].read();\n\n assert_eq!(ximpl.trait_id(), trait_id);\n\n\n\n ximpl\n\n .impl_for\n\n .get(&fct_id)\n\n .cloned()\n\n .expect(\"no impl method found for generic trait call\")\n\n}\n", "file_path": "dora/src/vm/impls.rs", "rank": 33, "score": 244992.482127171 }, { "content": "pub fn find_methods_in_struct(\n\n vm: &VM,\n\n object_type: SourceType,\n\n type_param_defs: &[TypeParam],\n\n type_param_defs2: Option<&TypeParamDefinition>,\n\n name: Name,\n\n is_static: bool,\n\n) -> Vec<Candidate> {\n\n let struct_id = if object_type.is_primitive() {\n\n object_type\n\n .primitive_struct_id(vm)\n\n .expect(\"primitive expected\")\n\n } else {\n\n object_type.struct_id().expect(\"struct expected\")\n\n };\n\n\n\n let xstruct = vm.structs.idx(struct_id);\n\n let xstruct = xstruct.read();\n\n\n\n for &extension_id in &xstruct.extensions {\n", "file_path": "dora/src/vm/structs.rs", "rank": 34, "score": 244851.22804100724 }, { "content": "pub fn struct_field_accessible_from(\n\n vm: &VM,\n\n struct_id: StructId,\n\n field_id: StructFieldId,\n\n namespace_id: NamespaceId,\n\n) -> bool {\n\n let xstruct = vm.structs.idx(struct_id);\n\n let xstruct = xstruct.read();\n\n\n\n let field = &xstruct.fields[field_id.to_usize()];\n\n\n\n accessible_from(\n\n vm,\n\n xstruct.namespace_id,\n\n xstruct.is_pub && field.is_pub,\n\n namespace_id,\n\n )\n\n}\n\n\n", "file_path": "dora/src/vm/structs.rs", "rank": 35, "score": 244851.22804100727 }, { "content": "pub fn check(vm: &mut VM) -> bool {\n\n // add user defined fcts and classes to vm\n\n // this check does not look into fct or class bodies\n\n if let Err(_) = globaldef::check(vm) {\n\n return false;\n\n }\n\n return_on_error!(vm);\n\n\n\n // add internal annotations early\n\n stdlib::resolve_internal_annotations(vm);\n\n\n\n // define internal classes\n\n stdlib::resolve_internal_classes(vm);\n\n\n\n // discover all enum variants\n\n enumck::check_variants(vm);\n\n\n\n // fill prelude with important types and functions\n\n stdlib::fill_prelude(vm);\n\n\n", "file_path": "dora/src/semck.rs", "rank": 36, "score": 244539.64075346699 }, { "content": "pub fn always_returns(s: &ast::Stmt) -> bool {\n\n returnck::returns_value(s).is_ok()\n\n}\n\n\n", "file_path": "dora/src/semck.rs", "rank": 37, "score": 244539.64075346693 }, { "content": "pub fn fits_ldst_unscaled(value: i32) -> bool {\n\n fits_i9(value)\n\n}\n\n\n\nconst FLOAT_TYPE_HALF: u32 = 0b11;\n\nconst FLOAT_TYPE_SINGLE: u32 = 0b00;\n\nconst FLOAT_TYPE_DOUBLE: u32 = 0b01;\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use byteorder::{LittleEndian, WriteBytesExt};\n\n\n\n macro_rules! assert_emit {\n\n (\n\n $($expr:expr),*;\n\n $name:ident\n\n (\n\n $($param:expr),*\n\n )\n", "file_path": "dora-asm/src/arm64.rs", "rank": 38, "score": 244236.4682307045 }, { "content": "pub fn fits_addsub_imm(value: u32) -> bool {\n\n fits_u12(value)\n\n}\n\n\n", "file_path": "dora-asm/src/arm64.rs", "rank": 39, "score": 244236.4682307045 }, { "content": "fn calculate_young_size(args: &Args, young_size: usize, min_semi_size: usize) -> (usize, usize) {\n\n let semi_ratio = args.flag_gc_semi_ratio.unwrap_or(INIT_SEMI_RATIO);\n\n let semi_size = if semi_ratio == 0 {\n\n 0\n\n } else {\n\n align_gen(young_size / semi_ratio)\n\n };\n\n\n\n let semi_size = max(semi_size, min_semi_size);\n\n let semi_size = max(semi_size, GEN_SIZE);\n\n let eden_size = young_size - semi_size;\n\n\n\n (eden_size, semi_size)\n\n}\n\n\n", "file_path": "dora/src/gc/swiper/controller.rs", "rank": 40, "score": 242785.2994049403 }, { "content": "pub fn expr_always_returns(e: &ast::Expr) -> bool {\n\n returnck::expr_returns_value(e).is_ok()\n\n}\n\n\n", "file_path": "dora/src/semck.rs", "rank": 41, "score": 241441.01128136698 }, { "content": "fn verify_marking_object(obj_address: Address, heap: Region) {\n\n let obj = obj_address.to_mut_obj();\n\n\n\n if obj.header().is_marked_non_atomic() {\n\n obj.visit_reference_fields(|field| {\n\n let object_addr = field.get();\n\n\n\n if heap.contains(object_addr) {\n\n assert!(object_addr.to_obj().header().is_marked_non_atomic());\n\n }\n\n });\n\n }\n\n}\n", "file_path": "dora/src/gc/swiper/compact.rs", "rank": 42, "score": 240104.43687337457 }, { "content": "#[inline(always)]\n\npub fn ptr_width_usize() -> usize {\n\n size_of::<*const u8>() as usize\n\n}\n\n\n", "file_path": "dora/src/mem.rs", "rank": 43, "score": 239430.59563205746 }, { "content": "pub fn find_impl(\n\n vm: &VM,\n\n check_ty: SourceType,\n\n check_type_param_defs: &[TypeParam],\n\n trait_id: TraitId,\n\n) -> Option<ImplId> {\n\n match check_ty {\n\n SourceType::Tuple(_)\n\n | SourceType::Unit\n\n | SourceType::Module(_)\n\n | SourceType::Trait(_, _)\n\n | SourceType::Lambda(_) => None,\n\n\n\n SourceType::Enum(enum_id, _) => {\n\n let xenum = vm.enums[enum_id].read();\n\n check_impls(\n\n vm,\n\n check_ty,\n\n check_type_param_defs,\n\n None,\n", "file_path": "dora/src/ty.rs", "rank": 44, "score": 239206.3040178119 }, { "content": "pub fn check_impls(\n\n vm: &VM,\n\n check_ty: SourceType,\n\n check_type_param_defs: &[TypeParam],\n\n check_type_param_defs2: Option<&TypeParamDefinition>,\n\n trait_id: TraitId,\n\n impls: &[ImplId],\n\n) -> Option<ImplId> {\n\n for &impl_id in impls {\n\n let ximpl = &vm.impls[impl_id];\n\n let ximpl = ximpl.read();\n\n\n\n if ximpl.trait_id != Some(trait_id) {\n\n continue;\n\n }\n\n\n\n if impl_matches(\n\n vm,\n\n check_ty.clone(),\n\n check_type_param_defs,\n", "file_path": "dora/src/ty.rs", "rank": 45, "score": 239206.3040178119 }, { "content": "pub fn walk_region_and_skip_garbage<F>(vm: &VM, region: Region, mut fct: F)\n\nwhere\n\n F: FnMut(&mut Obj, Address, usize) -> bool,\n\n{\n\n let mut scan = region.start;\n\n let mut garbage_start = Address::null();\n\n let mut garbage_objects = 0;\n\n\n\n while scan < region.end {\n\n let object = scan.to_mut_obj();\n\n\n\n if object.header().vtblptr().is_null() {\n\n scan = scan.add_ptr(1);\n\n continue;\n\n }\n\n\n\n let object_size = object.size();\n\n let marked = fct(object, scan, object_size);\n\n scan = scan.offset(object_size);\n\n\n", "file_path": "dora/src/gc/swiper.rs", "rank": 46, "score": 239086.2316561226 }, { "content": "pub fn check_struct(\n\n vm: &VM,\n\n fct: &Fct,\n\n struct_id: StructId,\n\n type_params: &SourceTypeArray,\n\n error: ErrorReporting,\n\n) -> bool {\n\n let xstruct = vm.structs.idx(struct_id);\n\n let xstruct = xstruct.read();\n\n\n\n let checker = TypeParamCheck {\n\n vm,\n\n caller_type_param_defs: &fct.type_params,\n\n callee_type_param_defs: &xstruct.type_params,\n\n error,\n\n };\n\n\n\n checker.check(type_params)\n\n}\n\n\n", "file_path": "dora/src/semck/typeparamck.rs", "rank": 47, "score": 235555.25665952876 }, { "content": "pub fn expr_block_always_returns(e: &ast::ExprBlockType) -> bool {\n\n returnck::expr_block_returns_value(e).is_ok()\n\n}\n\n\n", "file_path": "dora/src/semck.rs", "rank": 48, "score": 232877.52298828092 }, { "content": "pub fn walk_struct<V: Visitor>(v: &mut V, s: &Struct) {\n\n for f in &s.fields {\n\n v.visit_struct_field(f);\n\n }\n\n}\n\n\n", "file_path": "dora-parser/src/ast/visit.rs", "rank": 49, "score": 232602.64121845772 }, { "content": "fn forward_minor(object: Address, young: Region) -> Option<Address> {\n\n if young.contains(object) {\n\n let obj = object.to_mut_obj();\n\n\n\n if let Some(new_address) = obj.header().vtblptr_forwarded() {\n\n Some(new_address)\n\n } else {\n\n None\n\n }\n\n } else {\n\n Some(object)\n\n }\n\n}\n", "file_path": "dora/src/gc/swiper.rs", "rank": 50, "score": 231797.69956076017 }, { "content": "pub fn int_array_alloc_heap(vm: &VM, len: usize) -> Ref<Int32Array> {\n\n let size = Header::size() as usize // Object header\n\n + mem::ptr_width() as usize // length field\n\n + len * 4; // array content\n\n\n\n let size = mem::align_usize(size, mem::ptr_width() as usize);\n\n let ptr = vm.gc.alloc(vm, size, false);\n\n\n\n let clsid = vm.known.int_array(vm);\n\n let cls = vm.class_defs.idx(clsid);\n\n let vtable = cls.vtable.read();\n\n let vtable: &VTable = vtable.as_ref().unwrap();\n\n let mut handle: Ref<Int32Array> = ptr.into();\n\n handle\n\n .header_mut()\n\n .set_vtblptr(Address::from_ptr(vtable as *const VTable));\n\n handle.header_mut().clear_fwdptr();\n\n handle.length = len;\n\n\n\n handle\n\n}\n\n\n", "file_path": "dora/src/object.rs", "rank": 51, "score": 231795.5594298828 }, { "content": "#[cfg(not(target_os = \"macos\"))]\n\npub fn cacheline_sizes() -> (usize, usize) {\n\n let value: usize;\n\n\n\n unsafe {\n\n llvm_asm!(\"mrs $0, ctr_el0\": \"=r\"(value)::: \"volatile\");\n\n }\n\n\n\n let insn = 4 << (value & 0xF);\n\n let data = 4 << ((value >> 16) & 0xF);\n\n\n\n (insn, data)\n\n}\n\n\n", "file_path": "dora/src/cpu/arm64.rs", "rank": 52, "score": 231634.41021234533 }, { "content": "pub fn should_emit_debug(vm: &VM, fct: &Fct) -> bool {\n\n if let Some(ref dbg_names) = vm.args.flag_emit_debug {\n\n fct_pattern_match(vm, fct, dbg_names)\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "dora/src/compiler/codegen.rs", "rank": 53, "score": 230465.886816387 }, { "content": "pub fn should_emit_asm(vm: &VM, fct: &Fct) -> bool {\n\n if !disassembler::supported() {\n\n return false;\n\n }\n\n\n\n if let Some(ref dbg_names) = vm.args.flag_emit_asm {\n\n fct_pattern_match(vm, fct, dbg_names)\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "dora/src/compiler/codegen.rs", "rank": 54, "score": 230465.886816387 }, { "content": "pub fn should_emit_bytecode(vm: &VM, fct: &Fct) -> bool {\n\n if let Some(ref dbg_names) = vm.args.flag_emit_bytecode {\n\n fct_pattern_match(vm, fct, dbg_names)\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "dora/src/compiler/codegen.rs", "rank": 55, "score": 230465.886816387 }, { "content": "pub fn args_compatible_fct(\n\n vm: &VM,\n\n callee: &Fct,\n\n args: &[SourceType],\n\n type_params: &SourceTypeArray,\n\n self_ty: Option<SourceType>,\n\n) -> bool {\n\n let arg_types = callee.params_without_self();\n\n let variadic_arguments = callee.variadic_arguments;\n\n args_compatible(\n\n vm,\n\n arg_types,\n\n variadic_arguments,\n\n args,\n\n type_params,\n\n self_ty,\n\n )\n\n}\n\n\n", "file_path": "dora/src/semck/fctbodyck/body.rs", "rank": 56, "score": 228998.46722135888 }, { "content": "pub fn specialize_struct_id_params(\n\n vm: &VM,\n\n struct_id: StructId,\n\n type_params: SourceTypeArray,\n\n) -> StructDefId {\n\n let struc = vm.structs.idx(struct_id);\n\n let struc = struc.read();\n\n specialize_struct(vm, &*struc, type_params)\n\n}\n\n\n", "file_path": "dora/src/semck/specialize.rs", "rank": 57, "score": 228942.88579886948 }, { "content": "pub fn fits_movz(imm: u64, register_size: u32) -> bool {\n\n assert!(register_size == 32 || register_size == 64);\n\n\n\n count_empty_half_words(imm, register_size) >= (register_size / 16 - 1)\n\n}\n\n\n", "file_path": "dora-asm/src/arm64.rs", "rank": 58, "score": 227726.09947770293 }, { "content": "pub fn fits_movn(imm: u64, register_size: u32) -> bool {\n\n fits_movz(!imm, register_size)\n\n}\n\n\n", "file_path": "dora-asm/src/arm64.rs", "rank": 59, "score": 227726.09947770287 }, { "content": "/// round the given value up to the nearest multiple of a generation\n\npub fn align_gen(value: usize) -> usize {\n\n let align = GEN_ALIGNMENT_BITS;\n\n // we know that page size is power of 2, hence\n\n // we can use shifts instead of expensive division\n\n ((value + (1 << align) - 1) >> align) << align\n\n}\n\n\n", "file_path": "dora/src/gc.rs", "rank": 60, "score": 227413.6095189682 }, { "content": "/// round the given value up to the nearest multiple of a page\n\npub fn page_align(val: usize) -> usize {\n\n let align = os::page_size_bits();\n\n\n\n // we know that page size is power of 2, hence\n\n // we can use shifts instead of expensive division\n\n ((val + (1 << align) - 1) >> align) << align\n\n}\n\n\n", "file_path": "dora/src/mem.rs", "rank": 61, "score": 227413.6095189682 }, { "content": "pub fn align_gen_down(value: usize) -> usize {\n\n value & !(GEN_SIZE - 1)\n\n}\n\n\n", "file_path": "dora/src/gc.rs", "rank": 62, "score": 227413.6095189682 }, { "content": "pub fn calculate_size() -> usize {\n\n TLAB_SIZE\n\n}\n\n\n", "file_path": "dora/src/gc/tlab.rs", "rank": 63, "score": 226742.05586373163 }, { "content": "pub fn page_size() -> usize {\n\n let result = unsafe { PAGE_SIZE };\n\n\n\n if result != 0 {\n\n return result;\n\n }\n\n\n\n init_page_size();\n\n\n\n unsafe { PAGE_SIZE }\n\n}\n\n\n", "file_path": "dora/src/os/page.rs", "rank": 64, "score": 226742.05586373163 }, { "content": "pub fn walk_impl<V: Visitor>(v: &mut V, i: &Arc<Impl>) {\n\n for m in &i.methods {\n\n v.visit_method(m);\n\n }\n\n}\n\n\n", "file_path": "dora-parser/src/ast/visit.rs", "rank": 65, "score": 226597.93301637494 }, { "content": "/// rounds the given value `val` up to the nearest multiple\n\n/// of `align`.\n\npub fn align_usize(value: usize, align: usize) -> usize {\n\n if align == 0 {\n\n return value;\n\n }\n\n\n\n ((value + align - 1) / align) * align\n\n}\n\n\n", "file_path": "dora/src/mem.rs", "rank": 66, "score": 224543.6981193666 }, { "content": "pub fn page_size_bits() -> usize {\n\n let result = unsafe { PAGE_SIZE_BITS };\n\n\n\n if result != 0 {\n\n return result;\n\n }\n\n\n\n init_page_size();\n\n\n\n unsafe { PAGE_SIZE_BITS }\n\n}\n\n\n", "file_path": "dora/src/os/page.rs", "rank": 67, "score": 223506.8916886634 }, { "content": "struct HeapRegion {\n\n // Object area in region.\n\n area_start: Address,\n\n area_end: Address,\n\n\n\n // Separator between used & free bytes in region.\n\n top: AtomicUsize,\n\n\n\n // Current region state.\n\n state: AtomicRegionState,\n\n\n\n // Number of live bytes after marking.\n\n live_bytes: AtomicUsize,\n\n}\n\n\n\nimpl HeapRegion {\n\n fn area_size(&self) -> usize {\n\n self.area_end.to_usize() - self.area_start.to_usize()\n\n }\n\n}\n\n\n\nenumeration!(RegionState { Free, Used });\n\n\n", "file_path": "dora/src/gc/region.rs", "rank": 68, "score": 219242.52967141767 }, { "content": "fn argument_usize(arg: &str) -> Result<usize, String> {\n\n let idx = arg.find(\"=\").expect(\"missing =\");\n\n let (name, value) = arg.split_at(idx);\n\n let value = &value[1..];\n\n match value.parse::<usize>() {\n\n Ok(value) => Ok(value),\n\n Err(_) => Err(format!(\"{}: invalid value '{}'\", name, value)),\n\n }\n\n}\n\n\n", "file_path": "dora/src/driver/cmd.rs", "rank": 69, "score": 219017.34660750092 }, { "content": "pub fn get_rootset(vm: &VM, threads: &[Arc<DoraThread>]) -> Vec<Slot> {\n\n let mut rootset = Vec::new();\n\n\n\n determine_rootset_from_stack(&mut rootset, vm, threads);\n\n determine_rootset_from_handles(&mut rootset, threads);\n\n\n\n determine_rootset_from_globals(&mut rootset, vm);\n\n determine_rootset_from_wait_list(&mut rootset, vm);\n\n\n\n rootset\n\n}\n\n\n", "file_path": "dora/src/gc/root.rs", "rank": 70, "score": 214063.34982215057 }, { "content": "pub fn fct_pattern_match(vm: &VM, fct: &Fct, pattern: &str) -> bool {\n\n if pattern == \"all\" {\n\n return true;\n\n }\n\n\n\n let fct_name = fct.name_with_params(vm);\n\n\n\n for part in pattern.split(',') {\n\n if fct_name.contains(part) {\n\n return true;\n\n }\n\n }\n\n\n\n false\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq)]\n\npub enum AnyReg {\n\n Reg(Reg),\n\n FReg(FReg),\n", "file_path": "dora/src/compiler/codegen.rs", "rank": 71, "score": 213745.73324829945 }, { "content": "pub fn parse_arguments() -> Result<Args, String> {\n\n let cli_arguments: Vec<String> = std::env::args().collect();\n\n let mut args: Args = Default::default();\n\n let mut idx = 1;\n\n\n\n while idx < cli_arguments.len() {\n\n let arg = &cli_arguments[idx];\n\n\n\n if arg == \"test\" && idx == 1 {\n\n args.cmd_test = true;\n\n } else if arg == \"--version\" || arg == \"-v\" {\n\n args.flag_version = true;\n\n } else if arg == \"--check\" {\n\n args.flag_check = true;\n\n } else if arg == \"-h\" || arg == \"--help\" {\n\n args.flag_help = true;\n\n } else if arg == \"--emit-ast\" {\n\n args.flag_emit_ast = true;\n\n } else if arg.starts_with(\"--emit-asm=\") {\n\n args.flag_emit_asm = Some(argument_value(arg).into());\n", "file_path": "dora/src/driver/cmd.rs", "rank": 72, "score": 211392.74015554605 }, { "content": "pub fn specialize_struct_id(vm: &VM, struct_id: StructId) -> StructDefId {\n\n let struc = vm.structs.idx(struct_id);\n\n let struc = struc.read();\n\n specialize_struct(vm, &*struc, SourceTypeArray::empty())\n\n}\n\n\n", "file_path": "dora/src/semck/specialize.rs", "rank": 73, "score": 211045.84655775878 }, { "content": "pub fn check_super<'a>(vm: &VM, cls: &Class, error: ErrorReporting) -> bool {\n\n let object_type = cls.parent_class.clone().expect(\"parent_class missing\");\n\n\n\n let super_cls_id = object_type.cls_id().expect(\"no class\");\n\n let super_cls = vm.classes.idx(super_cls_id);\n\n let super_cls = super_cls.read();\n\n\n\n let checker = TypeParamCheck {\n\n vm,\n\n caller_type_param_defs: &cls.type_params,\n\n callee_type_param_defs: &super_cls.type_params,\n\n error,\n\n };\n\n\n\n let params = object_type.type_params(vm);\n\n\n\n checker.check(&params)\n\n}\n\n\n", "file_path": "dora/src/semck/typeparamck.rs", "rank": 74, "score": 209947.6998188412 }, { "content": "pub fn namespace_accessible_from(vm: &VM, target_id: NamespaceId, from_id: NamespaceId) -> bool {\n\n accessible_from(vm, target_id, true, from_id)\n\n}\n\n\n", "file_path": "dora/src/vm/namespaces.rs", "rank": 75, "score": 208955.11895395114 }, { "content": "#[cfg(target_family = \"unix\")]\n\nfn reserve(size: usize, jitting: bool) -> Address {\n\n debug_assert!(mem::is_page_aligned(size));\n\n\n\n let mut flags = libc::MAP_PRIVATE | libc::MAP_ANON;\n\n\n\n if jitting {\n\n flags |= map_jit_flag();\n\n }\n\n\n\n let ptr = unsafe {\n\n libc::mmap(ptr::null_mut(), size, libc::PROT_NONE, flags, -1, 0) as *mut libc::c_void\n\n };\n\n\n\n if ptr == libc::MAP_FAILED {\n\n panic!(\"reserving memory with mmap() failed\");\n\n }\n\n\n\n Address::from_ptr(ptr)\n\n}\n\n\n", "file_path": "dora/src/os/allocator.rs", "rank": 76, "score": 208355.58482573423 }, { "content": "#[cfg(target_family = \"windows\")]\n\nfn reserve(size: usize, _jitting: bool) -> Address {\n\n debug_assert!(mem::is_page_aligned(size));\n\n\n\n use winapi::um::memoryapi::VirtualAlloc;\n\n use winapi::um::winnt::{MEM_RESERVE, PAGE_NOACCESS};\n\n\n\n let ptr = unsafe { VirtualAlloc(ptr::null_mut(), size, MEM_RESERVE, PAGE_NOACCESS) };\n\n\n\n if ptr.is_null() {\n\n panic!(\"VirtualAlloc failed\");\n\n }\n\n\n\n Address::from_ptr(ptr)\n\n}\n\n\n", "file_path": "dora/src/os/allocator.rs", "rank": 77, "score": 208355.58482573426 }, { "content": "fn arg_allows(vm: &VM, def: SourceType, arg: SourceType, self_ty: Option<SourceType>) -> bool {\n\n match def {\n\n SourceType::Error | SourceType::Any => unreachable!(),\n\n SourceType::Unit\n\n | SourceType::Bool\n\n | SourceType::UInt8\n\n | SourceType::Char\n\n | SourceType::Struct(_, _)\n\n | SourceType::Int32\n\n | SourceType::Int64\n\n | SourceType::Float32\n\n | SourceType::Float64\n\n | SourceType::Enum(_, _)\n\n | SourceType::Trait(_, _) => def == arg,\n\n SourceType::Ptr => panic!(\"ptr should not occur in fct definition.\"),\n\n SourceType::This => {\n\n let real = self_ty.clone().expect(\"no Self type expected.\");\n\n arg_allows(vm, real, arg, self_ty)\n\n }\n\n\n", "file_path": "dora/src/semck/fctbodyck/body.rs", "rank": 78, "score": 208268.62428973592 }, { "content": "#[cfg(target_family = \"windows\")]\n\npub fn free(ptr: Address, size: usize) {\n\n debug_assert!(ptr.is_page_aligned());\n\n debug_assert!(mem::is_page_aligned(size));\n\n\n\n use winapi::um::memoryapi::VirtualFree;\n\n use winapi::um::winnt::MEM_RELEASE;\n\n\n\n let result = unsafe { VirtualFree(ptr.to_mut_ptr(), 0, MEM_RELEASE) };\n\n\n\n if result == 0 {\n\n panic!(\"VirtualFree failed\");\n\n }\n\n}\n\n\n\npub struct Reservation {\n\n pub start: Address,\n\n pub size: usize,\n\n\n\n pub unaligned_start: Address,\n\n pub unaligned_size: usize,\n", "file_path": "dora/src/os/allocator.rs", "rank": 79, "score": 207647.883796699 }, { "content": "pub fn allocate(size: usize) -> Option<Address> {\n\n assert!(size < TLAB_OBJECT_SIZE);\n\n\n\n let thread = current_thread();\n\n let tlab = thread.tld.tlab_region();\n\n\n\n if size <= tlab.size() {\n\n thread\n\n .tld\n\n .tlab_initialize(tlab.start.offset(size), tlab.end);\n\n Some(tlab.start)\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "dora/src/gc/tlab.rs", "rank": 80, "score": 207647.883796699 }, { "content": "#[cfg(target_family = \"windows\")]\n\npub fn discard(ptr: Address, size: usize) {\n\n debug_assert!(ptr.is_page_aligned());\n\n debug_assert!(mem::is_page_aligned(size));\n\n\n\n use winapi::um::memoryapi::VirtualFree;\n\n use winapi::um::winnt::MEM_DECOMMIT;\n\n\n\n let result = unsafe { VirtualFree(ptr.to_mut_ptr(), size, MEM_DECOMMIT) };\n\n\n\n if result == 0 {\n\n panic!(\"VirtualFree failed\");\n\n }\n\n}\n\n\n", "file_path": "dora/src/os/allocator.rs", "rank": 81, "score": 207647.883796699 }, { "content": "pub fn fct_accessible_from(vm: &VM, fct_id: FctId, namespace_id: NamespaceId) -> bool {\n\n let fct = vm.fcts.idx(fct_id);\n\n let fct = fct.read();\n\n\n\n accessible_from(vm, fct.namespace_id, fct.is_pub, namespace_id)\n\n}\n", "file_path": "dora/src/vm/functions.rs", "rank": 82, "score": 206688.6622983858 }, { "content": "pub fn global_accessible_from(vm: &VM, global_id: GlobalId, namespace_id: NamespaceId) -> bool {\n\n let global = vm.globals.idx(global_id);\n\n let global = global.read();\n\n\n\n accessible_from(vm, global.namespace_id, global.is_pub, namespace_id)\n\n}\n", "file_path": "dora/src/vm/globals.rs", "rank": 83, "score": 206688.6622983858 }, { "content": "pub fn method_accessible_from(vm: &VM, fct_id: FctId, namespace_id: NamespaceId) -> bool {\n\n let fct = vm.fcts.idx(fct_id);\n\n let fct = fct.read();\n\n\n\n let element_pub = match fct.parent {\n\n FctParent::Class(cls_id) => {\n\n let cls = vm.classes.idx(cls_id);\n\n let cls = cls.read();\n\n\n\n cls.is_pub && fct.is_pub\n\n }\n\n\n\n FctParent::Extension(_) => fct.is_pub,\n\n FctParent::Impl(_) | FctParent::Trait(_) => {\n\n // TODO: This should probably be limited\n\n return true;\n\n }\n\n\n\n FctParent::Module(module_id) => {\n\n let module = vm.modules.idx(module_id);\n", "file_path": "dora/src/vm/classes.rs", "rank": 84, "score": 206688.6622983858 }, { "content": "pub fn const_accessible_from(vm: &VM, const_id: ConstId, namespace_id: NamespaceId) -> bool {\n\n let xconst = vm.consts.idx(const_id);\n\n let xconst = xconst.read();\n\n\n\n accessible_from(vm, xconst.namespace_id, xconst.is_pub, namespace_id)\n\n}\n", "file_path": "dora/src/vm/consts.rs", "rank": 85, "score": 206688.6622983858 }, { "content": "pub fn enum_accessible_from(vm: &VM, enum_id: EnumId, namespace_id: NamespaceId) -> bool {\n\n let xenum = vm.enums[enum_id].read();\n\n\n\n accessible_from(vm, xenum.namespace_id, xenum.is_pub, namespace_id)\n\n}\n", "file_path": "dora/src/vm/enums.rs", "rank": 86, "score": 206688.6622983858 }, { "content": "pub fn namespace_contains(vm: &VM, parent_id: NamespaceId, child_id: NamespaceId) -> bool {\n\n if parent_id == child_id {\n\n return true;\n\n }\n\n\n\n let namespace = &vm.namespaces[child_id.to_usize()];\n\n namespace.parents.contains(&parent_id)\n\n}\n\n\n", "file_path": "dora/src/vm/namespaces.rs", "rank": 87, "score": 206688.6622983858 }, { "content": "pub fn module_accessible_from(vm: &VM, module_id: ModuleId, namespace_id: NamespaceId) -> bool {\n\n let module = vm.modules.idx(module_id);\n\n let module = module.read();\n\n\n\n accessible_from(vm, module.namespace_id, module.is_pub, namespace_id)\n\n}\n", "file_path": "dora/src/vm/modules.rs", "rank": 88, "score": 206688.6622983858 }, { "content": "pub fn class_accessible_from(vm: &VM, cls_id: ClassId, namespace_id: NamespaceId) -> bool {\n\n let cls = vm.classes.idx(cls_id);\n\n let cls = cls.read();\n\n\n\n accessible_from(vm, cls.namespace_id, cls.is_pub, namespace_id)\n\n}\n\n\n", "file_path": "dora/src/vm/classes.rs", "rank": 89, "score": 206688.6622983858 }, { "content": "pub fn trait_accessible_from(vm: &VM, trait_id: TraitId, namespace_id: NamespaceId) -> bool {\n\n let xtrait = vm.traits[trait_id].read();\n\n\n\n accessible_from(vm, xtrait.namespace_id, xtrait.is_pub, namespace_id)\n\n}\n", "file_path": "dora/src/vm/traits.rs", "rank": 90, "score": 206688.6622983858 }, { "content": "pub fn flush_icache(_: *const u8, _: usize) {\n\n // no flushing needed on x86_64, but emit compiler barrier\n\n compiler_fence(Ordering::SeqCst);\n\n}\n\n\n", "file_path": "dora/src/cpu/x64.rs", "rank": 91, "score": 204302.7659361628 }, { "content": "pub fn generate<'a>(vm: &'a VM, fct: NativeFct, dbg: bool) -> JitFctId {\n\n let fct_desc = fct.desc.clone();\n\n\n\n let ngen = NativeGen {\n\n vm,\n\n masm: MacroAssembler::new(),\n\n fct,\n\n dbg,\n\n };\n\n\n\n let jit_fct = ngen.generate();\n\n let jit_start = jit_fct.ptr_start();\n\n let jit_end = jit_fct.ptr_end();\n\n let jit_fct_id: JitFctId = vm.jit_fcts.push(JitFct::Compiled(jit_fct)).into();\n\n\n\n let code_desc = match fct_desc {\n\n NativeFctDescriptor::NativeStub(_) => CodeDescriptor::NativeStub(jit_fct_id),\n\n NativeFctDescriptor::TrapStub => CodeDescriptor::TrapStub,\n\n NativeFctDescriptor::VerifyStub => CodeDescriptor::VerifyStub,\n\n NativeFctDescriptor::AllocStub => CodeDescriptor::AllocStub,\n\n NativeFctDescriptor::GuardCheckStub => CodeDescriptor::GuardCheckStub,\n\n NativeFctDescriptor::SafepointStub => CodeDescriptor::SafepointStub,\n\n };\n\n\n\n vm.insert_code_map(jit_start, jit_end, code_desc);\n\n\n\n jit_fct_id\n\n}\n\n\n", "file_path": "dora/src/compiler/native_stub.rs", "rank": 92, "score": 201693.14294200105 }, { "content": "pub fn walk_struct_field<V: Visitor>(v: &mut V, f: &StructField) {\n\n v.visit_type(&f.data_type);\n\n}\n\n\n", "file_path": "dora-parser/src/ast/visit.rs", "rank": 93, "score": 198677.3657144853 }, { "content": "#[cfg(not(target_os = \"macos\"))]\n\npub fn flush_icache(start: *const u8, len: usize) {\n\n let start = start as usize;\n\n let end = start + len;\n\n\n\n let (icacheline_size, dcacheline_size) = cacheline_sizes();\n\n\n\n let istart = start & !(icacheline_size - 1);\n\n let dstart = start & !(dcacheline_size - 1);\n\n\n\n let mut ptr = dstart;\n\n\n\n while ptr < end {\n\n unsafe {\n\n llvm_asm!(\"dc civac, $0\":: \"r\"(ptr) : \"memory\" : \"volatile\");\n\n }\n\n\n\n ptr += dcacheline_size;\n\n }\n\n\n\n unsafe {\n", "file_path": "dora/src/cpu/arm64.rs", "rank": 94, "score": 198477.02460945558 }, { "content": "pub fn fill_region(vm: &VM, start: Address, end: Address) {\n\n if start == end {\n\n // nothing to do\n\n } else if end.offset_from(start) == mem::ptr_width_usize() {\n\n unsafe {\n\n *start.to_mut_ptr::<usize>() = 0;\n\n }\n\n } else if end.offset_from(start) == Header::size() as usize {\n\n // fill with object\n\n let cls_id = vm.known.obj(vm);\n\n let cls = vm.class_defs.idx(cls_id);\n\n let vtable = cls.vtable.read();\n\n let vtable: &VTable = vtable.as_ref().unwrap();\n\n\n\n unsafe {\n\n *start.to_mut_ptr::<usize>() = Address::from_ptr(vtable).to_usize();\n\n }\n\n } else {\n\n // fill with int array\n\n let cls_id = vm.known.int_array(vm);\n", "file_path": "dora/src/gc.rs", "rank": 95, "score": 195508.88404261044 }, { "content": " pub fn new(\n\n vm: &'a VM,\n\n young: &'a YoungGen,\n\n old: &'a OldGen,\n\n large: &'a LargeSpace,\n\n card_table: &'a CardTable,\n\n crossing_map: &'a CrossingMap,\n\n rootset: &'a [Slot],\n\n reason: GcReason,\n\n min_heap_size: usize,\n\n max_heap_size: usize,\n\n threadpool: &'a mut Pool,\n\n config: &'a SharedHeapConfig,\n\n ) -> ParallelMinorCollector<'a> {\n\n ParallelMinorCollector {\n\n vm,\n\n young,\n\n old,\n\n large,\n\n rootset,\n", "file_path": "dora/src/gc/swiper/pminor.rs", "rank": 96, "score": 52.4747635717452 }, { "content": " min_heap_size: usize,\n\n max_heap_size: usize,\n\n\n\n config: &'a SharedHeapConfig,\n\n phases: MinorCollectorPhases,\n\n}\n\n\n\nimpl<'a> MinorCollector<'a> {\n\n pub fn new(\n\n vm: &'a VM,\n\n young: &'a YoungGen,\n\n old: &'a OldGen,\n\n large: &'a LargeSpace,\n\n card_table: &'a CardTable,\n\n crossing_map: &'a CrossingMap,\n\n rootset: &'a [Slot],\n\n reason: GcReason,\n\n min_heap_size: usize,\n\n max_heap_size: usize,\n\n config: &'a SharedHeapConfig,\n", "file_path": "dora/src/gc/swiper/minor.rs", "rank": 98, "score": 52.3201436070598 }, { "content": "\n\n phases: FullCollectorPhases,\n\n}\n\n\n\nimpl<'a> FullCollector<'a> {\n\n pub fn new(\n\n vm: &'a VM,\n\n heap: Region,\n\n young: &'a YoungGen,\n\n old: &'a OldGen,\n\n large_space: &'a LargeSpace,\n\n card_table: &'a CardTable,\n\n crossing_map: &'a CrossingMap,\n\n perm_space: &'a Space,\n\n rootset: &'a [Slot],\n\n reason: GcReason,\n\n min_heap_size: usize,\n\n max_heap_size: usize,\n\n ) -> FullCollector<'a> {\n\n let old_total = old.total();\n", "file_path": "dora/src/gc/swiper/compact.rs", "rank": 99, "score": 50.48597481289009 } ]
Rust
src/p6/p6iv.rs
lukasl93/msp430fr5994
41eb5ada14476ab7b986f6b6f5c327d46e01b558
#[doc = "Reader of register P6IV"] pub type R = crate::R<u16, super::P6IV>; #[doc = "Writer for register P6IV"] pub type W = crate::W<u16, super::P6IV>; #[doc = "Register P6IV `reset()`'s with value 0"] impl crate::ResetValue for super::P6IV { type Type = u16; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "4:0\\] Port 6 interrupt vector value\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum P6IV_A { #[doc = "0: No interrupt pending"] NONE = 0, #[doc = "2: Interrupt Source: Port 6.0 interrupt; Interrupt Flag: P6IFG0; Interrupt Priority: Highest"] P6IFG0 = 2, #[doc = "4: Interrupt Source: Port 6.1 interrupt; Interrupt Flag: P6IFG1"] P6IFG1 = 4, #[doc = "6: Interrupt Source: Port 6.2 interrupt; Interrupt Flag: P6IFG2"] P6IFG2 = 6, #[doc = "8: Interrupt Source: Port 6.3 interrupt; Interrupt Flag: P6IFG3"] P6IFG3 = 8, #[doc = "10: Interrupt Source: Port 6.4 interrupt; Interrupt Flag: P6IFG4"] P6IFG4 = 10, #[doc = "12: Interrupt Source: Port 6.5 interrupt; Interrupt Flag: P6IFG5"] P6IFG5 = 12, #[doc = "14: Interrupt Source: Port 6.6 interrupt; Interrupt Flag: P6IFG6"] P6IFG6 = 14, #[doc = "16: Interrupt Source: Port 6.7 interrupt; Interrupt Flag: P6IFG7; Interrupt Priority: Lowest"] P6IFG7 = 16, } impl From<P6IV_A> for u8 { #[inline(always)] fn from(variant: P6IV_A) -> Self { variant as _ } } #[doc = "Reader of field `P6IV`"] pub type P6IV_R = crate::R<u8, P6IV_A>; impl P6IV_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, P6IV_A> { use crate::Variant::*; match self.bits { 0 => Val(P6IV_A::NONE), 2 => Val(P6IV_A::P6IFG0), 4 => Val(P6IV_A::P6IFG1), 6 => Val(P6IV_A::P6IFG2), 8 => Val(P6IV_A::P6IFG3), 10 => Val(P6IV_A::P6IFG4), 12 => Val(P6IV_A::P6IFG5), 14 => Val(P6IV_A::P6IFG6), 16 => Val(P6IV_A::P6IFG7), i => Res(i), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == P6IV_A::NONE } #[doc = "Checks if the value of the field is `P6IFG0`"] #[inline(always)] pub fn is_p6ifg0(&self) -> bool { *self == P6IV_A::P6IFG0 } #[doc = "Checks if the value of the field is `P6IFG1`"] #[inline(always)] pub fn is_p6ifg1(&self) -> bool { *self == P6IV_A::P6IFG1 } #[doc = "Checks if the value of the field is `P6IFG2`"] #[inline(always)] pub fn is_p6ifg2(&self) -> bool { *self == P6IV_A::P6IFG2 } #[doc = "Checks if the value of the field is `P6IFG3`"] #[inline(always)] pub fn is_p6ifg3(&self) -> bool { *self == P6IV_A::P6IFG3 } #[doc = "Checks if the value of the field is `P6IFG4`"] #[inline(always)] pub fn is_p6ifg4(&self) -> bool { *self == P6IV_A::P6IFG4 } #[doc = "Checks if the value of the field is `P6IFG5`"] #[inline(always)] pub fn is_p6ifg5(&self) -> bool { *self == P6IV_A::P6IFG5 } #[doc = "Checks if the value of the field is `P6IFG6`"] #[inline(always)] pub fn is_p6ifg6(&self) -> bool { *self == P6IV_A::P6IFG6 } #[doc = "Checks if the value of the field is `P6IFG7`"] #[inline(always)] pub fn is_p6ifg7(&self) -> bool { *self == P6IV_A::P6IFG7 } } #[doc = "Write proxy for field `P6IV`"] pub struct P6IV_W<'a> { w: &'a mut W, } impl<'a> P6IV_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: P6IV_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "No interrupt pending"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(P6IV_A::NONE) } #[doc = "Interrupt Source: Port 6.0 interrupt; Interrupt Flag: P6IFG0; Interrupt Priority: Highest"] #[inline(always)] pub fn p6ifg0(self) -> &'a mut W { self.variant(P6IV_A::P6IFG0) } #[doc = "Interrupt Source: Port 6.1 interrupt; Interrupt Flag: P6IFG1"] #[inline(always)] pub fn p6ifg1(self) -> &'a mut W { self.variant(P6IV_A::P6IFG1) } #[doc = "Interrupt Source: Port 6.2 interrupt; Interrupt Flag: P6IFG2"] #[inline(always)] pub fn p6ifg2(self) -> &'a mut W { self.variant(P6IV_A::P6IFG2) } #[doc = "Interrupt Source: Port 6.3 interrupt; Interrupt Flag: P6IFG3"] #[inline(always)] pub fn p6ifg3(self) -> &'a mut W { self.variant(P6IV_A::P6IFG3) } #[doc = "Interrupt Source: Port 6.4 interrupt; Interrupt Flag: P6IFG4"] #[inline(always)] pub fn p6ifg4(self) -> &'a mut W { self.variant(P6IV_A::P6IFG4) } #[doc = "Interrupt Source: Port 6.5 interrupt; Interrupt Flag: P6IFG5"] #[inline(always)] pub fn p6ifg5(self) -> &'a mut W { self.variant(P6IV_A::P6IFG5) } #[doc = "Interrupt Source: Port 6.6 interrupt; Interrupt Flag: P6IFG6"] #[inline(always)] pub fn p6ifg6(self) -> &'a mut W { self.variant(P6IV_A::P6IFG6) } #[doc = "Interrupt Source: Port 6.7 interrupt; Interrupt Flag: P6IFG7; Interrupt Priority: Lowest"] #[inline(always)] pub fn p6ifg7(self) -> &'a mut W { self.variant(P6IV_A::P6IFG7) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x1f) | ((value as u16) & 0x1f); self.w } } impl R { #[doc = "Bits 0:4 - 4:0\\] Port 6 interrupt vector value"] #[inline(always)] pub fn p6iv(&self) -> P6IV_R { P6IV_R::new((self.bits & 0x1f) as u8) } } impl W { #[doc = "Bits 0:4 - 4:0\\] Port 6 interrupt vector value"] #[inline(always)] pub fn p6iv(&mut self) -> P6IV_W { P6IV_W { w: self } } }
#[doc = "Reader of register P6IV"] pub type R = crate::R<u16, super::P6IV>; #[doc = "Writer for register P6IV"] pub type W = crate::W<u16, super::P6IV>; #[doc = "Register P6IV `reset()`'s with value 0"] impl crate::ResetValue for super::P6IV { type Type = u16; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "4:0\\] Port 6 interrupt vector value\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum P6IV_A { #[doc = "0: No interrupt pending"] NONE = 0, #[doc = "2: Interrupt Source: Port 6.0 interrupt; Interrupt Flag: P6IFG0; Interrupt Priority: Highest"] P6IFG0 = 2, #[doc = "4: Interrupt Source: Port 6.1 interrupt; Interrupt Flag: P6IFG1"] P6IFG1 = 4, #[doc = "6: Interrupt Source: Port 6.2 interrupt; Interrupt Flag: P6IFG2"] P6IFG2 = 6, #[doc = "8: Interrupt Source: Port 6.3 interrupt; Interrupt Flag: P6IFG3"] P6IFG3 = 8, #[doc = "10: Interrupt Source: Port 6.4 interrupt; Interrupt Flag: P6IFG4"] P6IFG4 = 10, #[doc = "12: Interrupt Source: Port 6.5 interrupt; Interrupt Flag: P6IFG5"] P6IFG5 = 12, #[doc = "14: Interrupt Source: Port 6.6 interrupt; Interrupt Flag: P6IFG6"] P6IFG6 = 14, #[doc = "16: Interrupt Source: Port 6.7 interrupt; Interrupt Flag: P6IFG7; Interrupt Priority: Lowest"] P6IFG7 = 16, } impl From<P6IV_A> for u8 { #[inline(always)] fn from(variant: P6IV_A) -> Self { variant as _ } } #[doc = "Reader of field `P6IV`"] pub type P6IV_R = crate::R<u8, P6IV_A>; impl P6IV_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, P6IV_A> { use crate::Variant::*; match self.bits { 0 => Val(P6IV_A::NONE), 2 => Val(P6IV_A::P6IFG0), 4 => Val(P6IV_A::P6IFG1), 6 => Val(P6IV_A::P6IFG2), 8 => Val(P6IV_A::P6IFG3), 10 => Val(P6IV_A::P6IFG4), 12 => Val(P6IV_A::P6IFG5), 14 => Val(P6IV_A::P6IFG6), 16 => Val(P6IV_A::P6IFG7), i => Res(i), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == P6IV_A::NONE } #[doc = "Checks if the value of the field is `P6IFG0`"] #[inline(always)] pub fn is_p6ifg0(&self) -> bool { *self == P6IV_A::P6IFG0 } #[doc = "Checks if the value of the field is `P6IFG1`"] #[inline(always)] pub fn is_p6ifg1(&self) -> bool { *self == P6IV_A::P6IFG1 } #[doc = "Checks if the value of the field is `P6IFG2`"] #[inline(always)] pub fn is_p6ifg2(&self) -> bool { *self == P6IV_A::P6IFG2 } #[doc = "Checks if the value of the field is `P6IFG3`"] #[inline(always)] pub fn is_p6ifg3(&self) -> bool { *self == P6IV_A::P6IFG3 } #[doc = "Checks if the value of the field is `P6IFG4`"] #[inline(always)] pub fn is_p6ifg4(&self) -> bool { *self == P6IV_A::P6IFG4 } #[doc = "Checks if the value of the field is `P6IFG5`"] #[inline(always)] pub fn is_p6ifg5(&self) -> bool { *self == P6IV_A::P6IFG5 } #[doc = "Checks if the value of the field is `P6IFG6`"] #[inline(always)] pub fn is_p6ifg6(&self) -> bool { *self == P6IV_A::P6IFG6 } #[doc = "Checks if the value of the field is `P6IFG7`"] #[inline(always)] pub fn is_p6ifg7(&self) -> bool { *self == P6IV_A::P6IFG7 } } #[doc = "Write proxy for field `P6IV`"] pub struct P6IV_W<'a> { w: &'a mut W, } impl<'a> P6IV_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: P6IV_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "No interrupt pending"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(P6IV_A::NONE) } #[doc = "Interrupt Source: Port 6.0 interrupt; Interrupt Flag: P6IFG0; Interrupt Priority: Highest"] #[inline(always)] pub fn p6ifg0(self) -> &'a mut W { self.variant(P6IV_A::P6IFG0) } #[doc = "Interrupt Source: Port 6.1 interrupt; Interrupt Flag: P6IFG1"] #[inline(always)] pub fn p6ifg1(self) -> &'a mut W { self.variant(P6IV_A::P6IFG1) } #[doc = "Interrupt Source: Port 6.2 interrupt; Interrupt Flag: P6IFG2"] #[inline(always)] pub fn p6ifg2(self) -> &'a mut W { self.variant(P6IV_A::P6IFG2) } #[doc = "Interrupt Source: Port 6.3 interrupt; Interrupt Flag: P6IFG3"] #[inline(always)] pub fn p6ifg3(self) -> &'a mut W { self.variant(P6IV_A::P6IFG3) } #[doc = "Interrupt Source: Port 6.4 interrupt; Interrupt Flag: P6IFG4"] #[inline(always)] pub fn p6ifg4(self) -> &'a mut W { self.variant(P6IV_A::P6IFG4)
IV_A::P6IFG7) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x1f) | ((value as u16) & 0x1f); self.w } } impl R { #[doc = "Bits 0:4 - 4:0\\] Port 6 interrupt vector value"] #[inline(always)] pub fn p6iv(&self) -> P6IV_R { P6IV_R::new((self.bits & 0x1f) as u8) } } impl W { #[doc = "Bits 0:4 - 4:0\\] Port 6 interrupt vector value"] #[inline(always)] pub fn p6iv(&mut self) -> P6IV_W { P6IV_W { w: self } } }
} #[doc = "Interrupt Source: Port 6.5 interrupt; Interrupt Flag: P6IFG5"] #[inline(always)] pub fn p6ifg5(self) -> &'a mut W { self.variant(P6IV_A::P6IFG5) } #[doc = "Interrupt Source: Port 6.6 interrupt; Interrupt Flag: P6IFG6"] #[inline(always)] pub fn p6ifg6(self) -> &'a mut W { self.variant(P6IV_A::P6IFG6) } #[doc = "Interrupt Source: Port 6.7 interrupt; Interrupt Flag: P6IFG7; Interrupt Priority: Lowest"] #[inline(always)] pub fn p6ifg7(self) -> &'a mut W { self.variant(P6
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Reset value of the register\"]\n\n fn reset_value() -> Self::Type;\n\n}\n\n#[doc = \"This structure provides volatile access to register\"]\n\npub struct Reg<U, REG> {\n\n register: vcell::VolatileCell<U>,\n\n _marker: marker::PhantomData<REG>,\n\n}\n\nunsafe impl<U: Send, REG> Send for Reg<U, REG> {}\n\nimpl<U, REG> Reg<U, REG>\n\nwhere\n\n Self: Readable,\n\n U: Copy,\n\n{\n\n #[doc = \"Reads the contents of `Readable` register\"]\n\n #[doc = \"\"]\n\n #[doc = \"You can read the contents of a register in such way:\"]\n", "file_path": "src/generic.rs", "rank": 0, "score": 168419.0529659847 }, { "content": "#[doc = \"This trait shows that register has `write`, `write_with_zero` and `reset` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Readable` can be also `modify`'ed\"]\n\npub trait Writable {}\n", "file_path": "src/generic.rs", "rank": 1, "score": 60810.64172948267 }, { "content": "#[doc = \"This trait shows that register has `read` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Writable` can be also `modify`'ed\"]\n\npub trait Readable {}\n", "file_path": "src/generic.rs", "rank": 2, "score": 60798.238326959654 }, { "content": "#[doc = \"Reader of register P4IV\"]\n\npub type R = crate::R<u16, super::P4IV>;\n\n#[doc = \"Writer for register P4IV\"]\n\npub type W = crate::W<u16, super::P4IV>;\n\n#[doc = \"Register P4IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::P4IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"4:0\\\\]\n\nPort 4 interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum P4IV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Port 4.0 interrupt; Interrupt Flag: P4IFG0; Interrupt Priority: Highest\"]\n", "file_path": "src/p4/p4iv.rs", "rank": 12, "score": 114.48931245338413 }, { "content": "#[doc = \"Reader of register P5IV\"]\n\npub type R = crate::R<u16, super::P5IV>;\n\n#[doc = \"Writer for register P5IV\"]\n\npub type W = crate::W<u16, super::P5IV>;\n\n#[doc = \"Register P5IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::P5IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"4:0\\\\]\n\nPort 5 interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum P5IV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Port 5.0 interrupt; Interrupt Flag: P5IFG0; Interrupt Priority: Highest\"]\n", "file_path": "src/p5/p5iv.rs", "rank": 13, "score": 114.48931245338413 }, { "content": "#[doc = \"Reader of register P2IV\"]\n\npub type R = crate::R<u16, super::P2IV>;\n\n#[doc = \"Writer for register P2IV\"]\n\npub type W = crate::W<u16, super::P2IV>;\n\n#[doc = \"Register P2IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::P2IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"4:0\\\\]\n\nPort 2 interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum P2IV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Port 2.0 interrupt; Interrupt Flag: P2IFG0; Interrupt Priority: Highest\"]\n", "file_path": "src/p2/p2iv.rs", "rank": 14, "score": 114.48931245338413 }, { "content": "#[doc = \"Reader of register P1IV\"]\n\npub type R = crate::R<u16, super::P1IV>;\n\n#[doc = \"Writer for register P1IV\"]\n\npub type W = crate::W<u16, super::P1IV>;\n\n#[doc = \"Register P1IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::P1IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"4:0\\\\]\n\nPort 1 interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum P1IV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Port 1.0 interrupt; Interrupt Flag: P1IFG0; Interrupt Priority: Highest\"]\n", "file_path": "src/p1/p1iv.rs", "rank": 15, "score": 114.48931245338414 }, { "content": "#[doc = \"Reader of register P7IV\"]\n\npub type R = crate::R<u16, super::P7IV>;\n\n#[doc = \"Writer for register P7IV\"]\n\npub type W = crate::W<u16, super::P7IV>;\n\n#[doc = \"Register P7IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::P7IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"4:0\\\\]\n\nPort 7 interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum P7IV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Port 7.0 interrupt; Interrupt Flag: P7IFG0; Interrupt Priority: Highest\"]\n", "file_path": "src/p7/p7iv.rs", "rank": 16, "score": 114.48931245338414 }, { "content": "#[doc = \"Reader of register P8IV\"]\n\npub type R = crate::R<u16, super::P8IV>;\n\n#[doc = \"Writer for register P8IV\"]\n\npub type W = crate::W<u16, super::P8IV>;\n\n#[doc = \"Register P8IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::P8IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"4:0\\\\]\n\nPort 8 interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum P8IV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Port 8.0 interrupt; Interrupt Flag: P8IFG0; Interrupt Priority: Highest\"]\n", "file_path": "src/p8/p8iv.rs", "rank": 17, "score": 114.48931245338414 }, { "content": "#[doc = \"Reader of register P3IV\"]\n\npub type R = crate::R<u16, super::P3IV>;\n\n#[doc = \"Writer for register P3IV\"]\n\npub type W = crate::W<u16, super::P3IV>;\n\n#[doc = \"Register P3IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::P3IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"4:0\\\\]\n\nPort 3 interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum P3IV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Port 3.0 interrupt; Interrupt Flag: P3IFG0; Interrupt Priority: Highest\"]\n", "file_path": "src/p3/p3iv.rs", "rank": 18, "score": 114.48931245338414 }, { "content": "#[doc = \"Reader of register ADC12IV\"]\n\npub type R = crate::R<u16, super::ADC12IV>;\n\n#[doc = \"Writer for register ADC12IV\"]\n\npub type W = crate::W<u16, super::ADC12IV>;\n\n#[doc = \"Register ADC12IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::ADC12IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\ninterrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum ADC12IV_A {\n\n #[doc = \"0: Interrupt Source: No interrupt pending, Interrupt Flag: None\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: ADC12MEMx overflow, Interrupt Flag: ADC12OVIFG, Interrupt Priority: Highest\"]\n", "file_path": "src/adc12_b/adc12iv.rs", "rank": 19, "score": 111.62240601889415 }, { "content": "#[doc = \"Reader of register DMAIV\"]\n\npub type R = crate::R<u16, super::DMAIV>;\n\n#[doc = \"Writer for register DMAIV\"]\n\npub type W = crate::W<u16, super::DMAIV>;\n\n#[doc = \"Register DMAIV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::DMAIV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\nDMA interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum DMAIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: DMA channel 0; Interrupt Flag: DMA0IFG; Interrupt Priority: Highest\"]\n", "file_path": "src/dma/dmaiv.rs", "rank": 20, "score": 108.89889211314706 }, { "content": "#[doc = \"Reader of register CEIV\"]\n\npub type R = crate::R<u16, super::CEIV>;\n\n#[doc = \"Writer for register CEIV\"]\n\npub type W = crate::W<u16, super::CEIV>;\n\n#[doc = \"Register CEIV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CEIV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\nComparator interrupt vector word register\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum CEIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: CEOUT interrupt; Interrupt Flag: CEIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/comp_e/ceiv.rs", "rank": 21, "score": 108.8424329347261 }, { "content": "#[doc = \"Reader of register UCB3IV\"]\n\npub type R = crate::R<u16, super::UCB3IV>;\n\n#[doc = \"Writer for register UCB3IV\"]\n\npub type W = crate::W<u16, super::UCB3IV>;\n\n#[doc = \"Register UCB3IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB3IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\neUSCI_B interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum UCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Arbitration lost; Interrupt Flag: UCALIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/e_usci_b3/ucb3iv.rs", "rank": 22, "score": 108.42243167913061 }, { "content": "#[doc = \"Reader of register UCB0IV\"]\n\npub type R = crate::R<u16, super::UCB0IV>;\n\n#[doc = \"Writer for register UCB0IV\"]\n\npub type W = crate::W<u16, super::UCB0IV>;\n\n#[doc = \"Register UCB0IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB0IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\neUSCI_B interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum UCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Arbitration lost; Interrupt Flag: UCALIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/e_usci_b0/ucb0iv.rs", "rank": 23, "score": 108.42243167913064 }, { "content": "#[doc = \"Reader of register UCA1IV\"]\n\npub type R = crate::R<u16, super::UCA1IV>;\n\n#[doc = \"Writer for register UCA1IV\"]\n\npub type W = crate::W<u16, super::UCA1IV>;\n\n#[doc = \"Register UCA1IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCA1IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\neUSCI_A interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum UCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Receive buffer full; Interrupt Flag: UCRXIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/e_usci_a1/uca1iv.rs", "rank": 24, "score": 108.42243167913064 }, { "content": "#[doc = \"Reader of register UCA0IV\"]\n\npub type R = crate::R<u16, super::UCA0IV>;\n\n#[doc = \"Writer for register UCA0IV\"]\n\npub type W = crate::W<u16, super::UCA0IV>;\n\n#[doc = \"Register UCA0IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCA0IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\neUSCI_A interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum UCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Receive buffer full; Interrupt Flag: UCRXIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/e_usci_a0/uca0iv.rs", "rank": 25, "score": 108.42243167913063 }, { "content": "#[doc = \"Reader of register UCB2IV\"]\n\npub type R = crate::R<u16, super::UCB2IV>;\n\n#[doc = \"Writer for register UCB2IV\"]\n\npub type W = crate::W<u16, super::UCB2IV>;\n\n#[doc = \"Register UCB2IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB2IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\neUSCI_B interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum UCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Arbitration lost; Interrupt Flag: UCALIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/e_usci_b2/ucb2iv.rs", "rank": 26, "score": 108.42243167913063 }, { "content": "#[doc = \"Reader of register UCA2IV\"]\n\npub type R = crate::R<u16, super::UCA2IV>;\n\n#[doc = \"Writer for register UCA2IV\"]\n\npub type W = crate::W<u16, super::UCA2IV>;\n\n#[doc = \"Register UCA2IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCA2IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\neUSCI_A interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum UCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Receive buffer full; Interrupt Flag: UCRXIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/e_usci_a2/uca2iv.rs", "rank": 27, "score": 108.42243167913064 }, { "content": "#[doc = \"Reader of register UCB1IV\"]\n\npub type R = crate::R<u16, super::UCB1IV>;\n\n#[doc = \"Writer for register UCB1IV\"]\n\npub type W = crate::W<u16, super::UCB1IV>;\n\n#[doc = \"Register UCB1IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB1IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\neUSCI_B interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum UCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Arbitration lost; Interrupt Flag: UCALIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/e_usci_b1/ucb1iv.rs", "rank": 28, "score": 108.42243167913063 }, { "content": "#[doc = \"Reader of register UCA3IV\"]\n\npub type R = crate::R<u16, super::UCA3IV>;\n\n#[doc = \"Writer for register UCA3IV\"]\n\npub type W = crate::W<u16, super::UCA3IV>;\n\n#[doc = \"Register UCA3IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCA3IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\neUSCI_A interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum UCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Receive buffer full; Interrupt Flag: UCRXIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/e_usci_a3/uca3iv.rs", "rank": 29, "score": 108.42243167913061 }, { "content": "#[doc = \"Reader of register TA3IV\"]\n\npub type R = crate::R<u16, super::TA3IV>;\n\n#[doc = \"Writer for register TA3IV\"]\n\npub type W = crate::W<u16, super::TA3IV>;\n\n#[doc = \"Register TA3IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA3IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\nTimerA interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum TAIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Capture/compare 1; Interrupt Flag: TAxCCR1 CCIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/ta3/ta3iv.rs", "rank": 30, "score": 107.4834593689576 }, { "content": "#[doc = \"Reader of register TA4IV\"]\n\npub type R = crate::R<u16, super::TA4IV>;\n\n#[doc = \"Writer for register TA4IV\"]\n\npub type W = crate::W<u16, super::TA4IV>;\n\n#[doc = \"Register TA4IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA4IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\nTimerA interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum TAIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Capture/compare 1; Interrupt Flag: TAxCCR1 CCIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/ta4/ta4iv.rs", "rank": 31, "score": 107.48345936895758 }, { "content": "#[doc = \"Reader of register TA1IV\"]\n\npub type R = crate::R<u16, super::TA1IV>;\n\n#[doc = \"Writer for register TA1IV\"]\n\npub type W = crate::W<u16, super::TA1IV>;\n\n#[doc = \"Register TA1IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA1IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\nTimerA interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum TAIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Capture/compare 1; Interrupt Flag: TAxCCR1 CCIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/ta1/ta1iv.rs", "rank": 32, "score": 107.48345936895758 }, { "content": "#[doc = \"Reader of register RTCIV\"]\n\npub type R = crate::R<u16, super::RTCIV>;\n\n#[doc = \"Writer for register RTCIV\"]\n\npub type W = crate::W<u16, super::RTCIV>;\n\n#[doc = \"Register RTCIV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RTCIV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\nReal-time clock interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum RTCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: RTC oscillator failure; Interrupt Flag: RTCOFIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/rtc_c/rtciv.rs", "rank": 33, "score": 107.4834593689576 }, { "content": "#[doc = \"Reader of register TA2IV\"]\n\npub type R = crate::R<u16, super::TA2IV>;\n\n#[doc = \"Writer for register TA2IV\"]\n\npub type W = crate::W<u16, super::TA2IV>;\n\n#[doc = \"Register TA2IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA2IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\nTimerA interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum TAIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Capture/compare 1; Interrupt Flag: TAxCCR1 CCIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/ta2/ta2iv.rs", "rank": 34, "score": 107.48345936895758 }, { "content": "#[doc = \"Reader of register TA0IV\"]\n\npub type R = crate::R<u16, super::TA0IV>;\n\n#[doc = \"Writer for register TA0IV\"]\n\npub type W = crate::W<u16, super::TA0IV>;\n\n#[doc = \"Register TA0IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA0IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\nTimerA interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum TAIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Capture/compare 1; Interrupt Flag: TAxCCR1 CCIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/ta0/ta0iv.rs", "rank": 35, "score": 107.48345936895757 }, { "content": "#[doc = \"Reader of register TB0IV\"]\n\npub type R = crate::R<u16, super::TB0IV>;\n\n#[doc = \"Writer for register TB0IV\"]\n\npub type W = crate::W<u16, super::TB0IV>;\n\n#[doc = \"Register TB0IV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TB0IV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\nTimer_B interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum TBIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Capture/compare 1; Interrupt Flag: TBxCCR1 CCIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/tb0/tb0iv.rs", "rank": 36, "score": 107.02080196504829 }, { "content": "#[doc = \"Reader of register UCA1IV_SPI\"]\n\npub type R = crate::R<u16, super::UCA1IV_SPI>;\n\n#[doc = \"Writer for register UCA1IV_SPI\"]\n\npub type W = crate::W<u16, super::UCA1IV_SPI>;\n\n#[doc = \"Register UCA1IV_SPI `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCA1IV_SPI {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\neUSCI_A interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum UCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Data received; Interrupt Flag: UCRXIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/e_usci_a1/uca1iv_spi.rs", "rank": 37, "score": 106.10879256768368 }, { "content": "#[doc = \"Reader of register UCA3IV_SPI\"]\n\npub type R = crate::R<u16, super::UCA3IV_SPI>;\n\n#[doc = \"Writer for register UCA3IV_SPI\"]\n\npub type W = crate::W<u16, super::UCA3IV_SPI>;\n\n#[doc = \"Register UCA3IV_SPI `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCA3IV_SPI {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\neUSCI_A interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum UCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Data received; Interrupt Flag: UCRXIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/e_usci_a3/uca3iv_spi.rs", "rank": 38, "score": 106.10879256768371 }, { "content": "#[doc = \"Reader of register UCA0IV_SPI\"]\n\npub type R = crate::R<u16, super::UCA0IV_SPI>;\n\n#[doc = \"Writer for register UCA0IV_SPI\"]\n\npub type W = crate::W<u16, super::UCA0IV_SPI>;\n\n#[doc = \"Register UCA0IV_SPI `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCA0IV_SPI {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\neUSCI_A interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum UCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Data received; Interrupt Flag: UCRXIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/e_usci_a0/uca0iv_spi.rs", "rank": 39, "score": 106.1087925676837 }, { "content": "#[doc = \"Reader of register UCA2IV_SPI\"]\n\npub type R = crate::R<u16, super::UCA2IV_SPI>;\n\n#[doc = \"Writer for register UCA2IV_SPI\"]\n\npub type W = crate::W<u16, super::UCA2IV_SPI>;\n\n#[doc = \"Register UCA2IV_SPI `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCA2IV_SPI {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\neUSCI_A interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum UCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Data received; Interrupt Flag: UCRXIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/e_usci_a2/uca2iv_spi.rs", "rank": 40, "score": 106.1087925676837 }, { "content": "#[doc = \"Reader of register UCB1IV_SPI\"]\n\npub type R = crate::R<u16, super::UCB1IV_SPI>;\n\n#[doc = \"Writer for register UCB1IV_SPI\"]\n\npub type W = crate::W<u16, super::UCB1IV_SPI>;\n\n#[doc = \"Register UCB1IV_SPI `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB1IV_SPI {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\neUSCI_B interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum UCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Data received; Interrupt Flag: UCRXIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/e_usci_b1/ucb1iv_spi.rs", "rank": 41, "score": 105.65930424910044 }, { "content": "#[doc = \"Reader of register UCB2IV_SPI\"]\n\npub type R = crate::R<u16, super::UCB2IV_SPI>;\n\n#[doc = \"Writer for register UCB2IV_SPI\"]\n\npub type W = crate::W<u16, super::UCB2IV_SPI>;\n\n#[doc = \"Register UCB2IV_SPI `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB2IV_SPI {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\neUSCI_B interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum UCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Data received; Interrupt Flag: UCRXIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/e_usci_b2/ucb2iv_spi.rs", "rank": 42, "score": 105.65930424910044 }, { "content": "#[doc = \"Reader of register UCB0IV_SPI\"]\n\npub type R = crate::R<u16, super::UCB0IV_SPI>;\n\n#[doc = \"Writer for register UCB0IV_SPI\"]\n\npub type W = crate::W<u16, super::UCB0IV_SPI>;\n\n#[doc = \"Register UCB0IV_SPI `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB0IV_SPI {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\neUSCI_B interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum UCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Data received; Interrupt Flag: UCRXIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/e_usci_b0/ucb0iv_spi.rs", "rank": 43, "score": 105.65930424910044 }, { "content": "#[doc = \"Reader of register UCB3IV_SPI\"]\n\npub type R = crate::R<u16, super::UCB3IV_SPI>;\n\n#[doc = \"Writer for register UCB3IV_SPI\"]\n\npub type W = crate::W<u16, super::UCB3IV_SPI>;\n\n#[doc = \"Register UCB3IV_SPI `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB3IV_SPI {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\neUSCI_B interrupt vector value\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum UCIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Interrupt Source: Data received; Interrupt Flag: UCRXIFG; Interrupt Priority: Highest\"]\n", "file_path": "src/e_usci_b3/ucb3iv_spi.rs", "rank": 44, "score": 105.65930424910044 }, { "content": "#[doc = \"Reader of register GCCTL1\"]\n\npub type R = crate::R<u16, super::GCCTL1>;\n\n#[doc = \"Writer for register GCCTL1\"]\n\npub type W = crate::W<u16, super::GCCTL1>;\n\n#[doc = \"Register GCCTL1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::GCCTL1 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"4:4\\\\]\n\nWrite Protection Detection flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum WPIFG_A {\n\n #[doc = \"0: No interrupt pending.\"]\n\n WPIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending. Can be cleared by writing '0' or by reading SYSSNIV when it is the highest pending interrupt.\"]\n\n WPIFG_1 = 1,\n", "file_path": "src/frctl_a/gcctl1.rs", "rank": 45, "score": 98.57749391154785 }, { "content": "#[doc = \"Reader of register LEAIV\"]\n\npub type R = crate::R<u32, super::LEAIV>;\n\n#[doc = \"Writer for register LEAIV\"]\n\npub type W = crate::W<u32, super::LEAIV>;\n\n#[doc = \"Register LEAIV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::LEAIV {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"7:0\\\\]\n\nLEA interrupt vector. This is a generated value that can be used as address offset for fast interrupt service routine handling. Reading this register clears the highest pending LEA interrupt (displaying this register with an IDE does not affect its content). Writing to this register clears al pending interrupt flags.This value is always aligned to a 20 bit address offset boundary\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum LEAIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: LEA command overflow\"]\n", "file_path": "src/lea/leaiv.rs", "rank": 46, "score": 97.16842715767271 }, { "content": "#[doc = \"Reader of register SYSRSTIV\"]\n\npub type R = crate::R<u16, super::SYSRSTIV>;\n\n#[doc = \"Writer for register SYSRSTIV\"]\n\npub type W = crate::W<u16, super::SYSRSTIV>;\n\n#[doc = \"Register SYSRSTIV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SYSRSTIV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\nReset interrupt vector\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum SYSRSTIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Brownout\"]\n", "file_path": "src/sys/sysrstiv.rs", "rank": 47, "score": 94.46309405883753 }, { "content": "#[doc = \"Reader of register SYSSNIV\"]\n\npub type R = crate::R<u16, super::SYSSNIV>;\n\n#[doc = \"Writer for register SYSSNIV\"]\n\npub type W = crate::W<u16, super::SYSSNIV>;\n\n#[doc = \"Register SYSSNIV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SYSSNIV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\nSystem NMI vector\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum SYSSNIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: Reserved\"]\n", "file_path": "src/sys/syssniv.rs", "rank": 48, "score": 92.674390747103 }, { "content": "#[doc = \"Reader of register SYSUNIV\"]\n\npub type R = crate::R<u16, super::SYSUNIV>;\n\n#[doc = \"Writer for register SYSUNIV\"]\n\npub type W = crate::W<u16, super::SYSUNIV>;\n\n#[doc = \"Register SYSUNIV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SYSUNIV {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"15:0\\\\]\n\nUser NMI vector\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u16)]\n\npub enum SYSUNIV_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n NONE = 0,\n\n #[doc = \"2: NMIIFG NMI pin\"]\n", "file_path": "src/sys/sysuniv.rs", "rank": 49, "score": 91.81860401542019 }, { "content": "#[doc = \"Reader of register TA1CTL\"]\n\npub type R = crate::R<u16, super::TA1CTL>;\n\n#[doc = \"Writer for register TA1CTL\"]\n\npub type W = crate::W<u16, super::TA1CTL>;\n\n#[doc = \"Register TA1CTL `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA1CTL {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nTimerA interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum TAIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n TAIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n TAIFG_1 = 1,\n", "file_path": "src/ta1/ta1ctl.rs", "rank": 50, "score": 91.44544413251205 }, { "content": "#[doc = \"Reader of register UCA0IFG\"]\n\npub type R = crate::R<u16, super::UCA0IFG>;\n\n#[doc = \"Writer for register UCA0IFG\"]\n\npub type W = crate::W<u16, super::UCA0IFG>;\n\n#[doc = \"Register UCA0IFG `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCA0IFG {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nReceive interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum UCRXIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n UCRXIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n UCRXIFG_1 = 1,\n", "file_path": "src/e_usci_a0/uca0ifg.rs", "rank": 51, "score": 91.44544413251202 }, { "content": "#[doc = \"Reader of register ADC12IFGR1\"]\n\npub type R = crate::R<u16, super::ADC12IFGR1>;\n\n#[doc = \"Writer for register ADC12IFGR1\"]\n\npub type W = crate::W<u16, super::ADC12IFGR1>;\n\n#[doc = \"Register ADC12IFGR1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::ADC12IFGR1 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nADC12MEM16 interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum ADC12IFG16_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n ADC12IFG16_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n ADC12IFG16_1 = 1,\n", "file_path": "src/adc12_b/adc12ifgr1.rs", "rank": 52, "score": 91.44544413251204 }, { "content": "#[doc = \"Reader of register ADC12IFGR0\"]\n\npub type R = crate::R<u16, super::ADC12IFGR0>;\n\n#[doc = \"Writer for register ADC12IFGR0\"]\n\npub type W = crate::W<u16, super::ADC12IFGR0>;\n\n#[doc = \"Register ADC12IFGR0 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::ADC12IFGR0 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nADC12MEM0 interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum ADC12IFG0_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n ADC12IFG0_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n ADC12IFG0_1 = 1,\n", "file_path": "src/adc12_b/adc12ifgr0.rs", "rank": 53, "score": 91.44544413251201 }, { "content": "#[doc = \"Reader of register TA4CTL\"]\n\npub type R = crate::R<u16, super::TA4CTL>;\n\n#[doc = \"Writer for register TA4CTL\"]\n\npub type W = crate::W<u16, super::TA4CTL>;\n\n#[doc = \"Register TA4CTL `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA4CTL {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nTimerA interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum TAIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n TAIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n TAIFG_1 = 1,\n", "file_path": "src/ta4/ta4ctl.rs", "rank": 54, "score": 91.44544413251205 }, { "content": "#[doc = \"Reader of register TA3CTL\"]\n\npub type R = crate::R<u16, super::TA3CTL>;\n\n#[doc = \"Writer for register TA3CTL\"]\n\npub type W = crate::W<u16, super::TA3CTL>;\n\n#[doc = \"Register TA3CTL `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA3CTL {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nTimerA interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum TAIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n TAIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n TAIFG_1 = 1,\n", "file_path": "src/ta3/ta3ctl.rs", "rank": 55, "score": 91.44544413251204 }, { "content": "#[doc = \"Reader of register UCA1IFG\"]\n\npub type R = crate::R<u16, super::UCA1IFG>;\n\n#[doc = \"Writer for register UCA1IFG\"]\n\npub type W = crate::W<u16, super::UCA1IFG>;\n\n#[doc = \"Register UCA1IFG `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCA1IFG {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nReceive interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum UCRXIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n UCRXIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n UCRXIFG_1 = 1,\n", "file_path": "src/e_usci_a1/uca1ifg.rs", "rank": 56, "score": 91.44544413251202 }, { "content": "#[doc = \"Reader of register UCA3IFG\"]\n\npub type R = crate::R<u16, super::UCA3IFG>;\n\n#[doc = \"Writer for register UCA3IFG\"]\n\npub type W = crate::W<u16, super::UCA3IFG>;\n\n#[doc = \"Register UCA3IFG `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCA3IFG {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nReceive interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum UCRXIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n UCRXIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n UCRXIFG_1 = 1,\n", "file_path": "src/e_usci_a3/uca3ifg.rs", "rank": 57, "score": 91.44544413251202 }, { "content": "#[doc = \"Reader of register UCA2IFG\"]\n\npub type R = crate::R<u16, super::UCA2IFG>;\n\n#[doc = \"Writer for register UCA2IFG\"]\n\npub type W = crate::W<u16, super::UCA2IFG>;\n\n#[doc = \"Register UCA2IFG `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCA2IFG {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nReceive interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum UCRXIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n UCRXIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n UCRXIFG_1 = 1,\n", "file_path": "src/e_usci_a2/uca2ifg.rs", "rank": 58, "score": 91.44544413251204 }, { "content": "#[doc = \"Reader of register TA0CTL\"]\n\npub type R = crate::R<u16, super::TA0CTL>;\n\n#[doc = \"Writer for register TA0CTL\"]\n\npub type W = crate::W<u16, super::TA0CTL>;\n\n#[doc = \"Register TA0CTL `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA0CTL {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nTimerA interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum TAIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n TAIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n TAIFG_1 = 1,\n", "file_path": "src/ta0/ta0ctl.rs", "rank": 59, "score": 91.44544413251202 }, { "content": "#[doc = \"Reader of register TA2CTL\"]\n\npub type R = crate::R<u16, super::TA2CTL>;\n\n#[doc = \"Writer for register TA2CTL\"]\n\npub type W = crate::W<u16, super::TA2CTL>;\n\n#[doc = \"Register TA2CTL `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA2CTL {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nTimerA interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum TAIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n TAIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n TAIFG_1 = 1,\n", "file_path": "src/ta2/ta2ctl.rs", "rank": 60, "score": 91.44544413251204 }, { "content": "#[doc = \"Reader of register TB0CCTL1\"]\n\npub type R = crate::R<u16, super::TB0CCTL1>;\n\n#[doc = \"Writer for register TB0CCTL1\"]\n\npub type W = crate::W<u16, super::TB0CCTL1>;\n\n#[doc = \"Register TB0CCTL1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TB0CCTL1 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/tb0/tb0cctl1.rs", "rank": 61, "score": 91.05001350073597 }, { "content": "#[doc = \"Reader of register TA3CCTL0\"]\n\npub type R = crate::R<u16, super::TA3CCTL0>;\n\n#[doc = \"Writer for register TA3CCTL0\"]\n\npub type W = crate::W<u16, super::TA3CCTL0>;\n\n#[doc = \"Register TA3CCTL0 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA3CCTL0 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/ta3/ta3cctl0.rs", "rank": 62, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TB0CCTL3\"]\n\npub type R = crate::R<u16, super::TB0CCTL3>;\n\n#[doc = \"Writer for register TB0CCTL3\"]\n\npub type W = crate::W<u16, super::TB0CCTL3>;\n\n#[doc = \"Register TB0CCTL3 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TB0CCTL3 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/tb0/tb0cctl3.rs", "rank": 63, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TA1CCTL0\"]\n\npub type R = crate::R<u16, super::TA1CCTL0>;\n\n#[doc = \"Writer for register TA1CCTL0\"]\n\npub type W = crate::W<u16, super::TA1CCTL0>;\n\n#[doc = \"Register TA1CCTL0 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA1CCTL0 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/ta1/ta1cctl0.rs", "rank": 64, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TA0CCTL1\"]\n\npub type R = crate::R<u16, super::TA0CCTL1>;\n\n#[doc = \"Writer for register TA0CCTL1\"]\n\npub type W = crate::W<u16, super::TA0CCTL1>;\n\n#[doc = \"Register TA0CCTL1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA0CCTL1 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/ta0/ta0cctl1.rs", "rank": 65, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TB0CCTL6\"]\n\npub type R = crate::R<u16, super::TB0CCTL6>;\n\n#[doc = \"Writer for register TB0CCTL6\"]\n\npub type W = crate::W<u16, super::TB0CCTL6>;\n\n#[doc = \"Register TB0CCTL6 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TB0CCTL6 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/tb0/tb0cctl6.rs", "rank": 66, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TA2CCTL1\"]\n\npub type R = crate::R<u16, super::TA2CCTL1>;\n\n#[doc = \"Writer for register TA2CCTL1\"]\n\npub type W = crate::W<u16, super::TA2CCTL1>;\n\n#[doc = \"Register TA2CCTL1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA2CCTL1 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/ta2/ta2cctl1.rs", "rank": 67, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TA0CCTL0\"]\n\npub type R = crate::R<u16, super::TA0CCTL0>;\n\n#[doc = \"Writer for register TA0CCTL0\"]\n\npub type W = crate::W<u16, super::TA0CCTL0>;\n\n#[doc = \"Register TA0CCTL0 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA0CCTL0 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/ta0/ta0cctl0.rs", "rank": 68, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TB0CCTL2\"]\n\npub type R = crate::R<u16, super::TB0CCTL2>;\n\n#[doc = \"Writer for register TB0CCTL2\"]\n\npub type W = crate::W<u16, super::TB0CCTL2>;\n\n#[doc = \"Register TB0CCTL2 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TB0CCTL2 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/tb0/tb0cctl2.rs", "rank": 69, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register CEINT\"]\n\npub type R = crate::R<u16, super::CEINT>;\n\n#[doc = \"Writer for register CEINT\"]\n\npub type W = crate::W<u16, super::CEINT>;\n\n#[doc = \"Register CEINT `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CEINT {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nComparator output interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CEIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CEIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CEIFG_1 = 1,\n", "file_path": "src/comp_e/ceint.rs", "rank": 70, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TA1CCTL1\"]\n\npub type R = crate::R<u16, super::TA1CCTL1>;\n\n#[doc = \"Writer for register TA1CCTL1\"]\n\npub type W = crate::W<u16, super::TA1CCTL1>;\n\n#[doc = \"Register TA1CCTL1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA1CCTL1 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/ta1/ta1cctl1.rs", "rank": 71, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TA4CCTL0\"]\n\npub type R = crate::R<u16, super::TA4CCTL0>;\n\n#[doc = \"Writer for register TA4CCTL0\"]\n\npub type W = crate::W<u16, super::TA4CCTL0>;\n\n#[doc = \"Register TA4CCTL0 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA4CCTL0 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/ta4/ta4cctl0.rs", "rank": 72, "score": 91.05001350073593 }, { "content": "#[doc = \"Reader of register SFRIFG1\"]\n\npub type R = crate::R<u16, super::SFRIFG1>;\n\n#[doc = \"Writer for register SFRIFG1\"]\n\npub type W = crate::W<u16, super::SFRIFG1>;\n\n#[doc = \"Register SFRIFG1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SFRIFG1 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"1:1\\\\]\n\nOscillator fault interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum OFIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n OFIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n OFIFG_1 = 1,\n", "file_path": "src/sfr/sfrifg1.rs", "rank": 73, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TB0CTL\"]\n\npub type R = crate::R<u16, super::TB0CTL>;\n\n#[doc = \"Writer for register TB0CTL\"]\n\npub type W = crate::W<u16, super::TB0CTL>;\n\n#[doc = \"Register TB0CTL `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TB0CTL {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nTimerB interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum TBIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n TBIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n TBIFG_1 = 1,\n", "file_path": "src/tb0/tb0ctl.rs", "rank": 74, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TA4CCTL2\"]\n\npub type R = crate::R<u16, super::TA4CCTL2>;\n\n#[doc = \"Writer for register TA4CCTL2\"]\n\npub type W = crate::W<u16, super::TA4CCTL2>;\n\n#[doc = \"Register TA4CCTL2 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA4CCTL2 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/ta4/ta4cctl2.rs", "rank": 75, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TB0CCTL4\"]\n\npub type R = crate::R<u16, super::TB0CCTL4>;\n\n#[doc = \"Writer for register TB0CCTL4\"]\n\npub type W = crate::W<u16, super::TB0CCTL4>;\n\n#[doc = \"Register TB0CCTL4 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TB0CCTL4 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/tb0/tb0cctl4.rs", "rank": 76, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TA4CCTL1\"]\n\npub type R = crate::R<u16, super::TA4CCTL1>;\n\n#[doc = \"Writer for register TA4CCTL1\"]\n\npub type W = crate::W<u16, super::TA4CCTL1>;\n\n#[doc = \"Register TA4CCTL1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA4CCTL1 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/ta4/ta4cctl1.rs", "rank": 77, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TA3CCTL1\"]\n\npub type R = crate::R<u16, super::TA3CCTL1>;\n\n#[doc = \"Writer for register TA3CCTL1\"]\n\npub type W = crate::W<u16, super::TA3CCTL1>;\n\n#[doc = \"Register TA3CCTL1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA3CCTL1 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/ta3/ta3cctl1.rs", "rank": 78, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TA1CCTL2\"]\n\npub type R = crate::R<u16, super::TA1CCTL2>;\n\n#[doc = \"Writer for register TA1CCTL2\"]\n\npub type W = crate::W<u16, super::TA1CCTL2>;\n\n#[doc = \"Register TA1CCTL2 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA1CCTL2 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/ta1/ta1cctl2.rs", "rank": 79, "score": 91.05001350073591 }, { "content": "#[doc = \"Reader of register TA0CCTL2\"]\n\npub type R = crate::R<u16, super::TA0CCTL2>;\n\n#[doc = \"Writer for register TA0CCTL2\"]\n\npub type W = crate::W<u16, super::TA0CCTL2>;\n\n#[doc = \"Register TA0CCTL2 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA0CCTL2 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/ta0/ta0cctl2.rs", "rank": 80, "score": 91.05001350073596 }, { "content": "#[doc = \"Reader of register TB0CCTL0\"]\n\npub type R = crate::R<u16, super::TB0CCTL0>;\n\n#[doc = \"Writer for register TB0CCTL0\"]\n\npub type W = crate::W<u16, super::TB0CCTL0>;\n\n#[doc = \"Register TB0CCTL0 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TB0CCTL0 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/tb0/tb0cctl0.rs", "rank": 81, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TB0CCTL5\"]\n\npub type R = crate::R<u16, super::TB0CCTL5>;\n\n#[doc = \"Writer for register TB0CCTL5\"]\n\npub type W = crate::W<u16, super::TB0CCTL5>;\n\n#[doc = \"Register TB0CCTL5 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TB0CCTL5 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/tb0/tb0cctl5.rs", "rank": 82, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register TA2CCTL0\"]\n\npub type R = crate::R<u16, super::TA2CCTL0>;\n\n#[doc = \"Writer for register TA2CCTL0\"]\n\npub type W = crate::W<u16, super::TA2CCTL0>;\n\n#[doc = \"Register TA2CCTL0 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TA2CCTL0 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nCapture/compare interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CCIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n CCIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n CCIFG_1 = 1,\n", "file_path": "src/ta2/ta2cctl0.rs", "rank": 83, "score": 91.05001350073594 }, { "content": "#[doc = \"Reader of register UCB3IFG\"]\n\npub type R = crate::R<u16, super::UCB3IFG>;\n\n#[doc = \"Writer for register UCB3IFG\"]\n\npub type W = crate::W<u16, super::UCB3IFG>;\n\n#[doc = \"Register UCB3IFG `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB3IFG {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\neUSCI_B receive interrupt flag 0\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum UCRXIFG0_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n UCRXIFG0_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n UCRXIFG0_1 = 1,\n", "file_path": "src/e_usci_b3/ucb3ifg.rs", "rank": 84, "score": 90.65835992924391 }, { "content": "#[doc = \"Reader of register UCB2IFG\"]\n\npub type R = crate::R<u16, super::UCB2IFG>;\n\n#[doc = \"Writer for register UCB2IFG\"]\n\npub type W = crate::W<u16, super::UCB2IFG>;\n\n#[doc = \"Register UCB2IFG `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB2IFG {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\neUSCI_B receive interrupt flag 0\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum UCRXIFG0_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n UCRXIFG0_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n UCRXIFG0_1 = 1,\n", "file_path": "src/e_usci_b2/ucb2ifg.rs", "rank": 85, "score": 90.6583599292439 }, { "content": "#[doc = \"Reader of register UCB1IFG\"]\n\npub type R = crate::R<u16, super::UCB1IFG>;\n\n#[doc = \"Writer for register UCB1IFG\"]\n\npub type W = crate::W<u16, super::UCB1IFG>;\n\n#[doc = \"Register UCB1IFG `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB1IFG {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\neUSCI_B receive interrupt flag 0\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum UCRXIFG0_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n UCRXIFG0_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n UCRXIFG0_1 = 1,\n", "file_path": "src/e_usci_b1/ucb1ifg.rs", "rank": 86, "score": 90.6583599292439 }, { "content": "#[doc = \"Reader of register UCB0IFG\"]\n\npub type R = crate::R<u16, super::UCB0IFG>;\n\n#[doc = \"Writer for register UCB0IFG\"]\n\npub type W = crate::W<u16, super::UCB0IFG>;\n\n#[doc = \"Register UCB0IFG `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB0IFG {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\neUSCI_B receive interrupt flag 0\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum UCRXIFG0_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n UCRXIFG0_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n UCRXIFG0_1 = 1,\n", "file_path": "src/e_usci_b0/ucb0ifg.rs", "rank": 87, "score": 90.65835992924391 }, { "content": "#[doc = \"Reader of register ADC12IFGR2\"]\n\npub type R = crate::R<u16, super::ADC12IFGR2>;\n\n#[doc = \"Writer for register ADC12IFGR2\"]\n\npub type W = crate::W<u16, super::ADC12IFGR2>;\n\n#[doc = \"Register ADC12IFGR2 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::ADC12IFGR2 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"1:1\\\\]\n\nInterrupt flag for ADC12MEMx between ADC12HI and ADC12LO\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum ADC12INIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n ADC12INIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n ADC12INIFG_1 = 1,\n", "file_path": "src/adc12_b/adc12ifgr2.rs", "rank": 88, "score": 90.27042488838008 }, { "content": "#[doc = \"Reader of register MPUCTL1\"]\n\npub type R = crate::R<u16, super::MPUCTL1>;\n\n#[doc = \"Writer for register MPUCTL1\"]\n\npub type W = crate::W<u16, super::MPUCTL1>;\n\n#[doc = \"Register MPUCTL1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::MPUCTL1 {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nMain Memory Segment 1 Violation Interrupt Flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum MPUSEG1IFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n MPUSEG1IFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n MPUSEG1IFG_1 = 1,\n", "file_path": "src/mpu/mpuctl1.rs", "rank": 89, "score": 90.27042488838009 }, { "content": "#[doc = \"Reader of register UCA3IFG_SPI\"]\n\npub type R = crate::R<u16, super::UCA3IFG_SPI>;\n\n#[doc = \"Writer for register UCA3IFG_SPI\"]\n\npub type W = crate::W<u16, super::UCA3IFG_SPI>;\n\n#[doc = \"Register UCA3IFG_SPI `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCA3IFG_SPI {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nReceive interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum UCRXIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n UCRXIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n UCRXIFG_1 = 1,\n", "file_path": "src/e_usci_a3/uca3ifg_spi.rs", "rank": 90, "score": 89.12836459005916 }, { "content": "#[doc = \"Reader of register UCA1IFG_SPI\"]\n\npub type R = crate::R<u16, super::UCA1IFG_SPI>;\n\n#[doc = \"Writer for register UCA1IFG_SPI\"]\n\npub type W = crate::W<u16, super::UCA1IFG_SPI>;\n\n#[doc = \"Register UCA1IFG_SPI `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCA1IFG_SPI {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nReceive interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum UCRXIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n UCRXIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n UCRXIFG_1 = 1,\n", "file_path": "src/e_usci_a1/uca1ifg_spi.rs", "rank": 91, "score": 89.12836459005918 }, { "content": "#[doc = \"Reader of register UCB2IFG_SPI\"]\n\npub type R = crate::R<u16, super::UCB2IFG_SPI>;\n\n#[doc = \"Writer for register UCB2IFG_SPI\"]\n\npub type W = crate::W<u16, super::UCB2IFG_SPI>;\n\n#[doc = \"Register UCB2IFG_SPI `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB2IFG_SPI {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nReceive interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum UCRXIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n UCRXIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n UCRXIFG_1 = 1,\n", "file_path": "src/e_usci_b2/ucb2ifg_spi.rs", "rank": 92, "score": 89.12836459005919 }, { "content": "#[doc = \"Reader of register UCA0IFG_SPI\"]\n\npub type R = crate::R<u16, super::UCA0IFG_SPI>;\n\n#[doc = \"Writer for register UCA0IFG_SPI\"]\n\npub type W = crate::W<u16, super::UCA0IFG_SPI>;\n\n#[doc = \"Register UCA0IFG_SPI `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCA0IFG_SPI {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nReceive interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum UCRXIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n UCRXIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n UCRXIFG_1 = 1,\n", "file_path": "src/e_usci_a0/uca0ifg_spi.rs", "rank": 93, "score": 89.12836459005915 }, { "content": "#[doc = \"Reader of register UCB3IFG_SPI\"]\n\npub type R = crate::R<u16, super::UCB3IFG_SPI>;\n\n#[doc = \"Writer for register UCB3IFG_SPI\"]\n\npub type W = crate::W<u16, super::UCB3IFG_SPI>;\n\n#[doc = \"Register UCB3IFG_SPI `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB3IFG_SPI {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nReceive interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum UCRXIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n UCRXIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n UCRXIFG_1 = 1,\n", "file_path": "src/e_usci_b3/ucb3ifg_spi.rs", "rank": 94, "score": 89.12836459005916 }, { "content": "#[doc = \"Reader of register UCB1IFG_SPI\"]\n\npub type R = crate::R<u16, super::UCB1IFG_SPI>;\n\n#[doc = \"Writer for register UCB1IFG_SPI\"]\n\npub type W = crate::W<u16, super::UCB1IFG_SPI>;\n\n#[doc = \"Register UCB1IFG_SPI `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB1IFG_SPI {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nReceive interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum UCRXIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n UCRXIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n UCRXIFG_1 = 1,\n", "file_path": "src/e_usci_b1/ucb1ifg_spi.rs", "rank": 95, "score": 89.12836459005918 }, { "content": "#[doc = \"Reader of register UCB0IFG_SPI\"]\n\npub type R = crate::R<u16, super::UCB0IFG_SPI>;\n\n#[doc = \"Writer for register UCB0IFG_SPI\"]\n\npub type W = crate::W<u16, super::UCB0IFG_SPI>;\n\n#[doc = \"Register UCB0IFG_SPI `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB0IFG_SPI {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nReceive interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum UCRXIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n UCRXIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n UCRXIFG_1 = 1,\n", "file_path": "src/e_usci_b0/ucb0ifg_spi.rs", "rank": 96, "score": 89.12836459005918 }, { "content": "#[doc = \"Reader of register UCA2IFG_SPI\"]\n\npub type R = crate::R<u16, super::UCA2IFG_SPI>;\n\n#[doc = \"Writer for register UCA2IFG_SPI\"]\n\npub type W = crate::W<u16, super::UCA2IFG_SPI>;\n\n#[doc = \"Register UCA2IFG_SPI `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCA2IFG_SPI {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"0:0\\\\]\n\nReceive interrupt flag\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum UCRXIFG_A {\n\n #[doc = \"0: No interrupt pending\"]\n\n UCRXIFG_0 = 0,\n\n #[doc = \"1: Interrupt pending\"]\n\n UCRXIFG_1 = 1,\n", "file_path": "src/e_usci_a2/uca2ifg_spi.rs", "rank": 97, "score": 89.12836459005916 }, { "content": "#[doc = \"Reader of register UCB1TXBUF\"]\n\npub type R = crate::R<u16, super::UCB1TXBUF>;\n\n#[doc = \"Writer for register UCB1TXBUF\"]\n\npub type W = crate::W<u16, super::UCB1TXBUF>;\n\n#[doc = \"Register UCB1TXBUF `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB1TXBUF {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `UCTXBUF`\"]\n\npub type UCTXBUF_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `UCTXBUF`\"]\n\npub struct UCTXBUF_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> UCTXBUF_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/e_usci_b1/ucb1txbuf.rs", "rank": 98, "score": 87.90127345720441 }, { "content": "#[doc = \"Reader of register UCB0TBCNT\"]\n\npub type R = crate::R<u16, super::UCB0TBCNT>;\n\n#[doc = \"Writer for register UCB0TBCNT\"]\n\npub type W = crate::W<u16, super::UCB0TBCNT>;\n\n#[doc = \"Register UCB0TBCNT `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::UCB0TBCNT {\n\n type Type = u16;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `UCTBCNT`\"]\n\npub type UCTBCNT_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `UCTBCNT`\"]\n\npub struct UCTBCNT_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> UCTBCNT_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/e_usci_b0/ucb0tbcnt.rs", "rank": 99, "score": 87.9012734572044 } ]
Rust
src/osm_io/o5m/varint.rs
Vadeen/vadeen_osm
80aa4f862ed7a9ee135e7e818a332a7650511976
use crate::osm_io::error::{Error, ErrorKind, Result}; use std::io::{Read, Write}; #[derive(Debug)] pub struct VarInt { bytes: Vec<u8>, } impl VarInt { pub fn new(bytes: Vec<u8>) -> Self { VarInt { bytes } } pub fn create_bytes<T: Into<VarInt>>(value: T) -> Vec<u8> { let varint: VarInt = value.into(); varint.into_bytes() } pub fn into_bytes(self) -> Vec<u8> { self.bytes } } pub trait ReadVarInt: Read { fn read_varint(&mut self) -> Result<VarInt> { let mut bytes = Vec::new(); for i in 0..10 { if i == 9 { return Err(Error::new( ErrorKind::ParseError, Some("Varint overflow, read 9 bytes.".to_owned()), )); } let mut buf = [0u8; 1]; self.read_exact(&mut buf)?; let byte = buf[0]; bytes.push(byte); if byte & 0x80 == 0 { break; } } Ok(VarInt { bytes }) } } impl<R: Read + ?Sized> ReadVarInt for R {} pub trait WriteVarInt: Write { fn write_varint<T: Into<VarInt>>(&mut self, i: T) -> Result<()> { let varint: VarInt = i.into(); self.write_all(&varint.bytes)?; Ok(()) } } impl<W: Write + ?Sized> WriteVarInt for W {} impl From<VarInt> for i64 { fn from(mut vi: VarInt) -> Self { let (first, rest) = vi.bytes.split_first().unwrap(); let byte = *first as u64; let negative = (byte & 0x01) != 0x00; let mut value = (byte & 0x7E) >> 1; if (byte & 0x80) != 0x00 { vi.bytes = rest.to_vec(); value |= (Into::<u64>::into(vi)) << 6; } let value = value as i64; if negative { -value - 1 } else { value } } } impl From<VarInt> for u64 { fn from(vi: VarInt) -> Self { let mut value = 0; for (n, _) in vi.bytes.iter().enumerate() { let byte = vi.bytes[n] as u64; value |= (byte & 0x7F) << (7 * (n as u64)); if byte & 0x80 == 0 { break; } } value } } impl From<u32> for VarInt { fn from(value: u32) -> Self { VarInt::from(value as u64) } } impl From<u64> for VarInt { fn from(mut value: u64) -> Self { let mut bytes = Vec::new(); while value > 0x7F { bytes.push(((value & 0x7F) | 0x80) as u8); value >>= 7; } if value > 0 { bytes.push(value as u8); } VarInt::new(bytes) } } impl From<i32> for VarInt { fn from(value: i32) -> Self { VarInt::from(value as i64) } } impl From<i64> for VarInt { fn from(mut value: i64) -> Self { let mut sign_bit = 0x00; if value < 0 { sign_bit = 0x01; value = -value - 1; } let value = value as u64; let least_significant = (((value << 1) & 0x7F) | sign_bit) as u8; let mut bytes = Vec::new(); if value > 0x3F { bytes.push(least_significant | 0x80); let mut rest = Self::from((value >> 6) as u64); bytes.append(&mut rest.bytes); } else { bytes.push(least_significant); } VarInt::new(bytes) } } #[cfg(test)] mod test_from_bytes { use crate::osm_io::o5m::varint::ReadVarInt; use crate::osm_io::o5m::varint::VarInt; #[test] fn max_one_byte_uvarint() { let varint = VarInt::new(vec![0x7F]); assert_eq!(Into::<u64>::into(varint), 127); } #[test] fn read_two_bytes_uvarint() { let data = vec![0xC3, 0x02]; let varint = data.as_slice().read_varint().unwrap(); assert_eq!(Into::<u64>::into(varint), 323); } #[test] fn three_byte_uvarint() { let varint = VarInt::new(vec![0x80, 0x80, 0x01]); assert_eq!(Into::<u64>::into(varint), 16384); } #[test] fn read_one_byte_positive_varint() { let data = vec![0x08]; let varint = data.as_slice().read_varint().unwrap(); assert_eq!(Into::<i64>::into(varint), 4); } #[test] fn one_byte_negative_varint() { let varint = VarInt::new(vec![0x03]); assert_eq!(Into::<i64>::into(varint), -2); } #[test] fn read_four_byte_positive_varint() { let data = vec![0x94, 0xfe, 0xd2, 0x05]; let varint = data.as_slice().read_varint().unwrap(); assert_eq!(Into::<i64>::into(varint), 5922698); } #[test] fn two_byte_negative_varint() { let varint = VarInt::new(vec![0x81, 0x01]); assert_eq!(Into::<i64>::into(varint), -65); } #[test] fn too_many_bytes() { let data = vec![0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]; let error = data.as_slice().read_varint().unwrap_err(); assert_eq!(error.to_string(), "Varint overflow, read 9 bytes.") } } #[cfg(test)] mod test_to_bytes { use crate::osm_io::o5m::varint::VarInt; #[test] fn one_byte_uvarint() { let varint = VarInt::from(5 as u64); assert_eq!(varint.bytes, vec![0x05]); } #[test] fn max_one_byte_uvarint() { let varint = VarInt::from(127 as u64); assert_eq!(varint.bytes, vec![0x7F]); } #[test] fn two_byte_uvarint() { let varint = VarInt::from(323 as u64); assert_eq!(varint.bytes, vec![0xC3, 0x02]); } #[test] fn three_byte_uvarint() { let varint = VarInt::from(16384 as u64); assert_eq!(varint.bytes, vec![0x80, 0x80, 0x01]); } #[test] fn one_byte_positive_varint() { let varint = VarInt::from(4 as i64); assert_eq!(varint.bytes, vec![0x08]); } #[test] fn one_byte_negative_varint() { let varint = VarInt::from(-3 as i64); assert_eq!(varint.bytes, vec![0x05]); } #[test] fn two_byte_positive_varint() { let varint = VarInt::from(64 as i64); assert_eq!(varint.bytes, vec![0x80, 0x01]); } #[test] fn two_byte_negative_varint() { let varint = VarInt::from(-65 as i64); assert_eq!(varint.bytes, vec![0x81, 0x01]); } }
use crate::osm_io::error::{Error, ErrorKind, Result}; use std::io::{Read, Write}; #[derive(Debug)] pub struct VarInt { bytes: Vec<u8>, } impl VarInt { pub fn new(bytes: Vec<u8>) -> Self { VarInt { bytes } } pub fn create_bytes<T: Into<VarInt>>(value: T) -> Vec<u8> { let varint: VarInt = value.into(); varint.into_bytes() } pub fn into_bytes(self) -> Vec<u8> { self.bytes } } pub trait ReadVarInt: Read { fn read_varint(&mut self) -> Result<VarInt> { let mut bytes = Vec::new(); for i in 0..10 { if i == 9 { return
; } let mut buf = [0u8; 1]; self.read_exact(&mut buf)?; let byte = buf[0]; bytes.push(byte); if byte & 0x80 == 0 { break; } } Ok(VarInt { bytes }) } } impl<R: Read + ?Sized> ReadVarInt for R {} pub trait WriteVarInt: Write { fn write_varint<T: Into<VarInt>>(&mut self, i: T) -> Result<()> { let varint: VarInt = i.into(); self.write_all(&varint.bytes)?; Ok(()) } } impl<W: Write + ?Sized> WriteVarInt for W {} impl From<VarInt> for i64 { fn from(mut vi: VarInt) -> Self { let (first, rest) = vi.bytes.split_first().unwrap(); let byte = *first as u64; let negative = (byte & 0x01) != 0x00; let mut value = (byte & 0x7E) >> 1; if (byte & 0x80) != 0x00 { vi.bytes = rest.to_vec(); value |= (Into::<u64>::into(vi)) << 6; } let value = value as i64; if negative { -value - 1 } else { value } } } impl From<VarInt> for u64 { fn from(vi: VarInt) -> Self { let mut value = 0; for (n, _) in vi.bytes.iter().enumerate() { let byte = vi.bytes[n] as u64; value |= (byte & 0x7F) << (7 * (n as u64)); if byte & 0x80 == 0 { break; } } value } } impl From<u32> for VarInt { fn from(value: u32) -> Self { VarInt::from(value as u64) } } impl From<u64> for VarInt { fn from(mut value: u64) -> Self { let mut bytes = Vec::new(); while value > 0x7F { bytes.push(((value & 0x7F) | 0x80) as u8); value >>= 7; } if value > 0 { bytes.push(value as u8); } VarInt::new(bytes) } } impl From<i32> for VarInt { fn from(value: i32) -> Self { VarInt::from(value as i64) } } impl From<i64> for VarInt { fn from(mut value: i64) -> Self { let mut sign_bit = 0x00; if value < 0 { sign_bit = 0x01; value = -value - 1; } let value = value as u64; let least_significant = (((value << 1) & 0x7F) | sign_bit) as u8; let mut bytes = Vec::new(); if value > 0x3F { bytes.push(least_significant | 0x80); let mut rest = Self::from((value >> 6) as u64); bytes.append(&mut rest.bytes); } else { bytes.push(least_significant); } VarInt::new(bytes) } } #[cfg(test)] mod test_from_bytes { use crate::osm_io::o5m::varint::ReadVarInt; use crate::osm_io::o5m::varint::VarInt; #[test] fn max_one_byte_uvarint() { let varint = VarInt::new(vec![0x7F]); assert_eq!(Into::<u64>::into(varint), 127); } #[test] fn read_two_bytes_uvarint() { let data = vec![0xC3, 0x02]; let varint = data.as_slice().read_varint().unwrap(); assert_eq!(Into::<u64>::into(varint), 323); } #[test] fn three_byte_uvarint() { let varint = VarInt::new(vec![0x80, 0x80, 0x01]); assert_eq!(Into::<u64>::into(varint), 16384); } #[test] fn read_one_byte_positive_varint() { let data = vec![0x08]; let varint = data.as_slice().read_varint().unwrap(); assert_eq!(Into::<i64>::into(varint), 4); } #[test] fn one_byte_negative_varint() { let varint = VarInt::new(vec![0x03]); assert_eq!(Into::<i64>::into(varint), -2); } #[test] fn read_four_byte_positive_varint() { let data = vec![0x94, 0xfe, 0xd2, 0x05]; let varint = data.as_slice().read_varint().unwrap(); assert_eq!(Into::<i64>::into(varint), 5922698); } #[test] fn two_byte_negative_varint() { let varint = VarInt::new(vec![0x81, 0x01]); assert_eq!(Into::<i64>::into(varint), -65); } #[test] fn too_many_bytes() { let data = vec![0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]; let error = data.as_slice().read_varint().unwrap_err(); assert_eq!(error.to_string(), "Varint overflow, read 9 bytes.") } } #[cfg(test)] mod test_to_bytes { use crate::osm_io::o5m::varint::VarInt; #[test] fn one_byte_uvarint() { let varint = VarInt::from(5 as u64); assert_eq!(varint.bytes, vec![0x05]); } #[test] fn max_one_byte_uvarint() { let varint = VarInt::from(127 as u64); assert_eq!(varint.bytes, vec![0x7F]); } #[test] fn two_byte_uvarint() { let varint = VarInt::from(323 as u64); assert_eq!(varint.bytes, vec![0xC3, 0x02]); } #[test] fn three_byte_uvarint() { let varint = VarInt::from(16384 as u64); assert_eq!(varint.bytes, vec![0x80, 0x80, 0x01]); } #[test] fn one_byte_positive_varint() { let varint = VarInt::from(4 as i64); assert_eq!(varint.bytes, vec![0x08]); } #[test] fn one_byte_negative_varint() { let varint = VarInt::from(-3 as i64); assert_eq!(varint.bytes, vec![0x05]); } #[test] fn two_byte_positive_varint() { let varint = VarInt::from(64 as i64); assert_eq!(varint.bytes, vec![0x80, 0x01]); } #[test] fn two_byte_negative_varint() { let varint = VarInt::from(-65 as i64); assert_eq!(varint.bytes, vec![0x81, 0x01]); } }
Err(Error::new( ErrorKind::ParseError, Some("Varint overflow, read 9 bytes.".to_owned()), ))
call_expression
[ { "content": "/// Writer for the osm formats.\n\npub trait OsmWrite<W: Write> {\n\n fn write(&mut self, osm: &Osm) -> std::result::Result<(), Error>;\n\n\n\n fn into_inner(self: Box<Self>) -> W;\n\n}\n\n\n", "file_path": "src/osm_io.rs", "rank": 2, "score": 124140.17316385586 }, { "content": "/// Convenience function for easily reading osm files.\n\n/// Format is determined from file ending.\n\n///\n\n/// # Example\n\n/// ```rust,no_run\n\n/// # use vadeen_osm::osm_io::error::Result;\n\n/// # use vadeen_osm::osm_io::read;\n\n/// # fn main() -> Result<()> {\n\n/// // Read xml map.\n\n/// let osm = read(\"map.osm\")?;\n\n///\n\n/// // Read o5m map.\n\n/// let osm = read(\"map.o5m\")?;\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n\npub fn read<P: AsRef<Path>>(path: P) -> Result<Osm> {\n\n let format = path.as_ref().try_into()?;\n\n let file = File::open(path)?;\n\n let mut reader = create_reader(BufReader::new(file), format);\n\n reader.read()\n\n}\n\n\n", "file_path": "src/osm_io.rs", "rank": 3, "score": 118168.84067467635 }, { "content": "/// Convenience function for easily writing osm files.\n\n/// Format is determined from file ending.\n\n///\n\n/// # Example\n\n/// ```rust,no_run\n\n/// # use vadeen_osm::OsmBuilder;\n\n/// # use vadeen_osm::osm_io::error::Result;\n\n/// # use vadeen_osm::osm_io::write;\n\n/// # fn main() -> Result<()> {\n\n/// let osm = OsmBuilder::default().build();\n\n///\n\n/// // Write xml map.\n\n/// write(\"map.osm\", &osm)?;\n\n///\n\n/// // Write o5m map.\n\n/// write(\"map.o5m\", &osm)?;\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n\npub fn write<P: AsRef<Path>>(path: P, osm: &Osm) -> Result<()> {\n\n let format = path.as_ref().try_into()?;\n\n let file = File::create(path)?;\n\n let mut writer = create_writer(file, format);\n\n writer.write(&osm)\n\n}\n\n\n", "file_path": "src/osm_io.rs", "rank": 4, "score": 112947.01402776227 }, { "content": "/// Reader for the osm formats.\n\npub trait OsmRead {\n\n fn read(&mut self) -> std::result::Result<Osm, Error>;\n\n}\n\n\n", "file_path": "src/osm_io.rs", "rank": 5, "score": 112748.39850157395 }, { "content": "/// Creates an `OsmWriter` appropriate to the provided `FileFormat`.\n\n///\n\n/// # Example\n\n/// Write map to map.o5m\n\n/// ```rust,no_run\n\n/// # use vadeen_osm::{Osm, OsmBuilder};\n\n/// # use vadeen_osm::osm_io::{create_writer, FileFormat, create_reader};\n\n/// # use vadeen_osm::osm_io::error::Result;\n\n/// # use std::fs::File;\n\n/// # use std::path::Path;\n\n/// # use std::convert::TryInto;\n\n/// # use std::io::BufReader;\n\n/// # fn main() -> Result<()> {\n\n/// let builder = OsmBuilder::default();\n\n/// // builder.add_polygon(..); etc...\n\n/// let osm = builder.build();\n\n///\n\n/// // Write to file.\n\n/// let output = File::create(\"map.o5m\")?;\n\n/// let mut writer = create_writer(output, FileFormat::O5m);\n\n/// writer.write(&osm);\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n\npub fn create_writer<'a, W: Write + 'a>(\n\n writer: W,\n\n format: FileFormat,\n\n) -> Box<dyn OsmWrite<W> + 'a> {\n\n match format {\n\n FileFormat::O5m => Box::new(O5mWriter::new(writer)),\n\n FileFormat::Xml => Box::new(XmlWriter::new(writer)),\n\n }\n\n}\n\n\n\nimpl FileFormat {\n\n pub fn from(s: &str) -> Option<Self> {\n\n match s {\n\n \"osm\" => Some(FileFormat::Xml),\n\n \"o5m\" => Some(FileFormat::O5m),\n\n _ => None,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/osm_io.rs", "rank": 6, "score": 105306.95857946598 }, { "content": "/// Creates an `OsmReader` appropriate to the provided `FileFormat`.\n\n///\n\n/// # Example\n\n/// Read map from map.osm\n\n/// ```rust,no_run\n\n/// # use std::path::Path;\n\n/// # use std::convert::TryInto;\n\n/// # use std::fs::File;\n\n/// # use vadeen_osm::osm_io::create_reader;\n\n/// # use vadeen_osm::osm_io::error::Result;\n\n/// # use std::io::BufReader;\n\n/// # fn main() -> Result<()> {\n\n/// let path = Path::new(\"map.osm\");\n\n/// let file = File::open(path)?;\n\n///\n\n/// // Get format from path. This can also be specified as FileFormat::Xml.\n\n/// let format = path.try_into()?;\n\n///\n\n/// // Read from file.\n\n/// let mut reader = create_reader(BufReader::new(file), format);\n\n/// let osm = reader.read()?;\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n\npub fn create_reader<'a, R: BufRead + 'a>(\n\n reader: R,\n\n format: FileFormat,\n\n) -> Box<dyn OsmRead + 'a> {\n\n match format {\n\n FileFormat::Xml => Box::new(XmlReader::new(reader)),\n\n FileFormat::O5m => Box::new(O5mReader::new(reader)),\n\n }\n\n}\n\n\n", "file_path": "src/osm_io.rs", "rank": 7, "score": 89433.27718099588 }, { "content": "#[test]\n\nfn read_write_osm_file() {\n\n let path = Path::new(\"./tests/test_data/generated.osm\");\n\n let format = path.try_into().unwrap();\n\n let mut file = File::open(path).unwrap();\n\n let mut input = Vec::new();\n\n file.read_to_end(&mut input).unwrap();\n\n\n\n // Read data\n\n let mut reader = create_reader(BufReader::new(&input[..]), format);\n\n let osm = reader.read().unwrap();\n\n\n\n // Write data\n\n let output = Vec::new();\n\n let mut writer = create_writer(output, format);\n\n writer.write(&osm).unwrap();\n\n\n\n assert_eq!(input, writer.into_inner());\n\n}\n", "file_path": "tests/xml_io.rs", "rank": 8, "score": 89277.04034713641 }, { "content": "fn main() -> Result<()> {\n\n // Create a builder.\n\n let mut builder = OsmBuilder::default();\n\n\n\n // Add a polygon to the map.\n\n builder.add_polygon(\n\n vec![\n\n vec![\n\n // Outer polygon\n\n MyCoordinate::new(66.29, -3.177),\n\n MyCoordinate::new(66.29, -0.9422),\n\n MyCoordinate::new(64.43, -0.9422),\n\n MyCoordinate::new(64.43, -3.177),\n\n MyCoordinate::new(66.29, -3.177),\n\n ],\n\n // Add inner polygons here.\n\n ],\n\n vec![MyTag::new(\"natural\", \"water\")],\n\n );\n\n\n\n // Build into Osm structure.\n\n let osm = builder.build();\n\n\n\n // Write to file in the xml format.\n\n write(\"example_map.osm\", &osm)?;\n\n Ok(())\n\n}\n", "file_path": "examples/custom_data.rs", "rank": 9, "score": 85171.8404441364 }, { "content": "fn main() -> Result<()> {\n\n // Create a builder.\n\n let mut builder = OsmBuilder::default();\n\n\n\n // Add a polygon to the map.\n\n builder.add_polygon(\n\n vec![\n\n vec![\n\n // Outer polygon\n\n (66.29, -3.177),\n\n (66.29, -0.9422),\n\n (64.43, -0.9422),\n\n (64.43, -3.177),\n\n (66.29, -3.177),\n\n ],\n\n vec![\n\n // One inner polygon\n\n (66.0, -2.25),\n\n (65.7, -2.5),\n\n (65.7, -2.0),\n", "file_path": "examples/osm_builder.rs", "rank": 10, "score": 85171.8404441364 }, { "content": "fn parse_node(event: &BytesStart) -> Result<Node> {\n\n let attributes = Attributes::from(event.attributes());\n\n Ok(Node {\n\n id: attributes.get_parse(\"id\")?,\n\n coordinate: attributes.create_coordinate()?,\n\n meta: attributes.create_meta()?,\n\n })\n\n}\n\n\n", "file_path": "src/osm_io/xml/reader.rs", "rank": 11, "score": 83359.90435999438 }, { "content": "fn parse_relation(event: &BytesStart) -> Result<Relation> {\n\n let attributes = Attributes::from(event.attributes());\n\n Ok(Relation {\n\n id: attributes.get_parse(\"id\")?,\n\n members: vec![],\n\n meta: attributes.create_meta()?,\n\n })\n\n}\n\n\n", "file_path": "src/osm_io/xml/reader.rs", "rank": 12, "score": 83359.90435999438 }, { "content": "fn parse_boundary(event: &BytesStart) -> Result<Boundary> {\n\n let attributes = Attributes::from(event.attributes());\n\n Ok(attributes.create_boundary()?)\n\n}\n\n\n", "file_path": "src/osm_io/xml/reader.rs", "rank": 13, "score": 83359.90435999438 }, { "content": "fn parse_way(event: &BytesStart) -> Result<Way> {\n\n let attributes = Attributes::from(event.attributes());\n\n Ok(Way {\n\n id: attributes.get_parse(\"id\")?,\n\n refs: vec![],\n\n meta: attributes.create_meta()?,\n\n })\n\n}\n\n\n", "file_path": "src/osm_io/xml/reader.rs", "rank": 14, "score": 83359.90435999438 }, { "content": "fn create_tags(events: &[BytesStart]) -> Result<Vec<Tag>> {\n\n let mut tags = Vec::new();\n\n for e in events.iter().filter(|e| e.name() == b\"tag\") {\n\n tags.push(Attributes::from(e.attributes()).create_tag()?);\n\n }\n\n Ok(tags)\n\n}\n\n\n", "file_path": "src/osm_io/xml/reader.rs", "rank": 15, "score": 79427.1286867097 }, { "content": "/// Add the meta attributes to an element.\n\nfn add_meta_attributes(elem: &mut BytesStart, meta: &Meta) {\n\n let version = meta.version;\n\n elem.push_attribute((\"version\", version.unwrap_or(1).to_string().as_ref()));\n\n\n\n if let Some(author) = &meta.author {\n\n let dt = Utc.timestamp(author.created, 0);\n\n let time_str = dt.format(\"%Y-%m-%dT%H:%M:%S%.fZ\").to_string();\n\n elem.extend_attributes(vec![\n\n (\"uid\", author.uid.to_string().as_ref()),\n\n (\"user\", author.user.as_ref()),\n\n (\"changeset\", author.change_set.to_string().as_ref()),\n\n (\"timestamp\", time_str.as_ref()),\n\n ]);\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::io::Cursor;\n\n\n", "file_path": "src/osm_io/xml/writer.rs", "rank": 16, "score": 78672.2335715408 }, { "content": "fn create_way_refs(events: &[BytesStart]) -> Result<Vec<i64>> {\n\n let mut refs = Vec::new();\n\n for e in events.iter().filter(|e| e.name() == b\"nd\") {\n\n refs.push(Attributes::from(e.attributes()).get_parse(\"ref\")?);\n\n }\n\n Ok(refs)\n\n}\n\n\n", "file_path": "src/osm_io/xml/reader.rs", "rank": 17, "score": 77457.43258626443 }, { "content": "/// Add relation member attributes to an element.\n\nfn add_member_attributes(elem: &mut BytesStart, mem: &RelationMember) {\n\n let (mem_type, mem_ref, mem_role) = match mem {\n\n RelationMember::Node(mem_ref, role) => (\"node\", mem_ref, role),\n\n RelationMember::Way(mem_ref, role) => (\"way\", mem_ref, role),\n\n RelationMember::Relation(mem_ref, role) => (\"relation\", mem_ref, role),\n\n };\n\n\n\n elem.extend_attributes(vec![\n\n (\"type\", mem_type),\n\n (\"ref\", mem_ref.to_string().as_ref()),\n\n (\"role\", mem_role),\n\n ]);\n\n}\n\n\n", "file_path": "src/osm_io/xml/writer.rs", "rank": 18, "score": 76829.29528992662 }, { "content": "fn create_relation_members(events: &[BytesStart]) -> Result<Vec<RelationMember>> {\n\n let mut members = Vec::new();\n\n for e in events.iter().filter(|e| e.name() == b\"member\") {\n\n members.push(Attributes::from(e.attributes()).create_relation_member()?);\n\n }\n\n Ok(members)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::geo::{Boundary, Coordinate};\n\n use crate::osm_io::error::ErrorKind;\n\n use crate::osm_io::xml::XmlReader;\n\n use crate::osm_io::OsmRead;\n\n use crate::{AuthorInformation, Meta, Node, Relation, RelationMember, Way};\n\n\n\n #[test]\n\n fn read_boundary() {\n\n let xml = r#\"<bounds minlat=\"58.24\" minlon=\"15.16\" maxlat=\"62.18\" maxlon=\"17.34\"/>\"#;\n\n let mut reader = XmlReader::new(xml.as_bytes());\n", "file_path": "src/osm_io/xml/reader.rs", "rank": 19, "score": 75619.39532988379 }, { "content": "#[test]\n\nfn write_o5m_file() {\n\n let path = Path::new(\"./tests/test_data/generated.osm\");\n\n let format = path.try_into().unwrap();\n\n let mut file = File::open(path).unwrap();\n\n let mut input = Vec::new();\n\n file.read_to_end(&mut input).unwrap();\n\n\n\n // Read xml\n\n let mut reader = create_reader(BufReader::new(&input[..]), format);\n\n let osm = reader.read().unwrap();\n\n\n\n // Read expected output\n\n let mut file = File::open(\"./tests/test_data/generated.o5m\").unwrap();\n\n let mut expected_output = Vec::new();\n\n file.read_to_end(&mut expected_output).unwrap();\n\n\n\n // Write o5m\n\n let output = Vec::new();\n\n let mut writer = create_writer(output, FileFormat::O5m);\n\n writer.write(&osm).unwrap();\n\n\n\n assert_eq!(writer.into_inner(), expected_output);\n\n}\n", "file_path": "tests/o5m_io.rs", "rank": 20, "score": 67279.24526740104 }, { "content": "#[test]\n\nfn read_o5m_file() {\n\n let osm = read(\"./tests/test_data/real_map.o5m\").unwrap();\n\n\n\n let boundary = osm.boundary.as_ref().unwrap();\n\n assert_eq!(boundary.min, (60.6750500, 17.1362500).into());\n\n assert_eq!(boundary.max, (60.6763100, 17.1389800).into());\n\n\n\n // Assert a node.\n\n {\n\n let node = osm.nodes.iter().find(|r| r.id == 60686436).unwrap();\n\n assert_eq!(node.id, 60686436);\n\n assert_eq!(node.coordinate, Coordinate::new(60.6763366, 17.1421725));\n\n assert_eq!(node.meta.tags, []);\n\n\n\n let author = node.meta.author.as_ref().unwrap();\n\n assert_eq!(Some(3), node.meta.version);\n\n assert_eq!(\"Dalkvist\", author.user);\n\n assert_eq!(12140, author.uid);\n\n assert_eq!(7035827, author.change_set);\n\n assert_eq!(1295564363, author.created);\n", "file_path": "tests/o5m_io.rs", "rank": 21, "score": 67234.45667971786 }, { "content": "#[test]\n\nfn read_osm_file() {\n\n let osm = read(\"./tests/test_data/real_map.osm\").unwrap();\n\n\n\n let boundary = osm.boundary.as_ref().unwrap();\n\n assert_eq!(boundary.min, (60.6750500, 17.1362500).into());\n\n assert_eq!(boundary.max, (60.6763100, 17.1389800).into());\n\n\n\n // Assert a node.\n\n {\n\n let node = osm.nodes.iter().find(|r| r.id == 60686436).unwrap();\n\n assert_eq!(node.id, 60686436);\n\n assert_eq!(node.coordinate, Coordinate::new(60.6763366, 17.1421725));\n\n assert_eq!(node.meta.tags, []);\n\n\n\n let author = node.meta.author.as_ref().unwrap();\n\n assert_eq!(Some(3), node.meta.version);\n\n assert_eq!(\"Dalkvist\", author.user);\n\n assert_eq!(12140, author.uid);\n\n assert_eq!(7035827, author.change_set);\n\n assert_eq!(1295564363, author.created);\n", "file_path": "tests/xml_io.rs", "rank": 22, "score": 67234.45667971786 }, { "content": "/// Low level decoding from binary to data types.\n\n/// Keeps state of string references and delta values.\n\nstruct O5mDecoder<R: BufRead> {\n\n inner: Take<R>,\n\n string_table: StringReferenceTable,\n\n delta: DeltaState,\n\n limit: u64,\n\n position: u64,\n\n}\n\n\n\nimpl<R: BufRead> O5mReader<R> {\n\n pub fn new(inner: R) -> Self {\n\n O5mReader {\n\n decoder: O5mDecoder::new(inner),\n\n }\n\n }\n\n\n\n /// Get the current position in the file.\n\n fn position(&self) -> u64 {\n\n self.decoder.position()\n\n }\n\n\n", "file_path": "src/osm_io/o5m/reader.rs", "rank": 23, "score": 59015.98591821174 }, { "content": "struct MyTag {\n\n key: String,\n\n value: String,\n\n}\n\n\n", "file_path": "examples/custom_data.rs", "rank": 24, "score": 48300.29276814206 }, { "content": "struct MyCoordinate {\n\n lat: f64,\n\n lon: f64,\n\n}\n\n\n\nimpl MyTag {\n\n fn new(key: &str, value: &str) -> Self {\n\n MyTag {\n\n key: key.to_owned(),\n\n value: value.to_owned(),\n\n }\n\n }\n\n}\n\n\n\nimpl MyCoordinate {\n\n fn new(lat: f64, lon: f64) -> Self {\n\n MyCoordinate { lat, lon }\n\n }\n\n}\n\n\n", "file_path": "examples/custom_data.rs", "rank": 25, "score": 48300.29276814206 }, { "content": "fn main() {\n\n let mut osm = Osm::default();\n\n\n\n // Add a node\n\n osm.add_node(Node {\n\n id: 1,\n\n coordinate: (66.29, -3.177).into(),\n\n meta: Meta {\n\n tags: vec![(\"key\", \"value\").into()],\n\n version: Some(3),\n\n author: Some(AuthorInformation {\n\n created: 12345678,\n\n change_set: 1,\n\n uid: 1234,\n\n user: \"Username\".to_string(),\n\n }),\n\n },\n\n });\n\n\n\n // Add a way with no tags or nothing.\n", "file_path": "examples/no_builder.rs", "rank": 26, "score": 45976.15275505994 }, { "content": "#[derive(Debug)]\n\nstruct DeltaValue {\n\n state: i64,\n\n}\n\n\n", "file_path": "src/osm_io/o5m.rs", "rank": 27, "score": 45605.483465042154 }, { "content": "#[derive(Debug)]\n\nstruct DeltaState {\n\n time: DeltaValue,\n\n id: DeltaValue,\n\n lat: DeltaValue,\n\n lon: DeltaValue,\n\n change_set: DeltaValue,\n\n way_ref: DeltaValue,\n\n rel_node_ref: DeltaValue,\n\n rel_way_ref: DeltaValue,\n\n rel_rel_ref: DeltaValue,\n\n}\n\n\n\nimpl StringReferenceTable {\n\n pub fn new() -> Self {\n\n StringReferenceTable {\n\n table: VecDeque::with_capacity(15000),\n\n }\n\n }\n\n\n\n pub fn clear(&mut self) {\n", "file_path": "src/osm_io/o5m.rs", "rank": 28, "score": 45605.483465042154 }, { "content": "#[derive(Debug)]\n\nstruct O5mEncoder {\n\n string_table: StringReferenceTable,\n\n delta: DeltaState,\n\n}\n\n\n\nimpl<W: Write> O5mWriter<W> {\n\n pub fn new(writer: W) -> O5mWriter<W> {\n\n O5mWriter {\n\n inner: writer,\n\n encoder: O5mEncoder::new(),\n\n }\n\n }\n\n\n\n /// See: https://wiki.openstreetmap.org/wiki/O5m#Reset\n\n fn reset(&mut self) -> io::Result<()> {\n\n self.inner.write_all(&[O5M_RESET])?;\n\n self.encoder.reset();\n\n Ok(())\n\n }\n\n\n", "file_path": "src/osm_io/o5m/writer.rs", "rank": 29, "score": 44442.47618770211 }, { "content": "#[derive(Debug)]\n\nstruct StringReferenceTable {\n\n table: VecDeque<Vec<u8>>,\n\n}\n\n\n\n/// Represents a delta value, i.e. a value that is relative to it's last value.\n", "file_path": "src/osm_io/o5m.rs", "rank": 30, "score": 44442.47618770211 }, { "content": "/// See: https://wiki.openstreetmap.org/wiki/O5m#cite_note-1\n\nfn member_type(member: &RelationMember) -> &str {\n\n match member {\n\n RelationMember::Node(_, _) => \"0\",\n\n RelationMember::Way(_, _) => \"1\",\n\n RelationMember::Relation(_, _) => \"2\",\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::{AuthorInformation, Meta, Relation, RelationMember, Way};\n\n\n\n #[test]\n\n fn string_pair_bytes() {\n\n let mut encoder = O5mEncoder::new();\n\n let bytes = encoder.string_pair_to_bytes(\"oneway\", \"yes\");\n\n let expected: Vec<u8> = vec![\n\n 0x00, 0x6f, 0x6e, 0x65, 0x77, 0x61, 0x79, 0x00, 0x79, 0x65, 0x73, 0x00,\n\n ];\n", "file_path": "src/osm_io/o5m/writer.rs", "rank": 31, "score": 32526.919598836655 }, { "content": "## Custom data\n\nThe builder can handle all kind of data as long as it has implemented the correct `Into` traits.\n\n\n\nFor example if you have a custom tag type `MyTag` and a custom coordinate type `MyCoordinate` you can use them\n\nseamlessly with the builder as long as you implement the appropriate `Into<Tag>` and `Into<Coordinate>`.\n\n```rust\n\n// Your custom tag.\n\nstruct MyTag {\n\n key: String,\n\n value: String,\n\n}\n\n\n\n// Your custom coordinate type.\n\nstruct MyCoordinate {\n\n lat: f64,\n\n lon: f64,\n\n}\n\n\n\n// All you have to do is to implement the Into traits.\n\nimpl Into<Coordinate> for MyCoordinate {\n\n fn into(self) -> Coordinate {\n\n Coordinate::new(self.lat, self.lon)\n\n }\n\n}\n\n\n\nimpl Into<Tag> for MyTag {\n\n fn into(self) -> Tag {\n\n Tag {\n\n key: self.key,\n\n value: self.value,\n\n }\n\n }\n\n}\n\n\n\n// Then you can use them with the builder:\n\nlet mut builder = OsmBuilder::default();\n\n\n\n// Add a polygon to the map.\n\nbuilder.add_polygon(\n\n vec![\n\n vec![\n\n // Outer polygon\n\n MyCoordinate::new(66.29, -3.177),\n\n MyCoordinate::new(66.29, -0.9422),\n\n MyCoordinate::new(64.43, -0.9422),\n\n MyCoordinate::new(64.43, -3.177),\n\n MyCoordinate::new(66.29, -3.177),\n\n ],\n\n // Add inner polygons here.\n\n ],\n\n vec![MyTag::new(\"natural\", \"water\")],\n\n);\n\n\n\n// Build into Osm structure.\n\nlet osm = builder.build();\n\n\n\n// Write to file in the xml format.\n\nwrite(\"example_map.osm\", &osm)?;\n\n```\n\n\n", "file_path": "README.md", "rank": 44, "score": 17.097058428845248 }, { "content": " fn read_delta_coordinate(&mut self) -> Result<Coordinate> {\n\n let lon = self.read_delta(Lon)? as i32;\n\n let lat = self.read_delta(Lat)? as i32;\n\n Ok(Coordinate { lat, lon })\n\n }\n\n\n\n /// Wrapper for easy reading i64 varint.\n\n fn read_varint(&mut self) -> Result<i64> {\n\n Ok(self.inner.read_varint()?.into())\n\n }\n\n\n\n /// Wrapper for easy reading u64 varint.\n\n fn read_uvarint(&mut self) -> Result<u64> {\n\n Ok(self.inner.read_varint()?.into())\n\n }\n\n\n\n /// Read one single byte.\n\n fn read_u8(&mut self) -> Result<u8> {\n\n let mut bytes = [0u8; 1];\n\n self.inner.read_exact(&mut bytes)?;\n", "file_path": "src/osm_io/o5m/reader.rs", "rank": 45, "score": 17.062055627105124 }, { "content": " }\n\n }\n\n\n\n /// Read real string pairs. I.e. data that is actually a pair of 2 strings, not single strings\n\n /// or a user which consists of one int and a string.\n\n fn read_string_pair(&mut self) -> Result<(String, String)> {\n\n let reference: u64 = self.inner.read_varint()?.into();\n\n if reference != 0 {\n\n let bytes = self.string_table.get(reference)?;\n\n Ok(Self::bytes_to_string_pair(bytes))\n\n } else {\n\n let bytes = self.read_string_bytes(2)?;\n\n Ok(Self::bytes_to_string_pair(&bytes))\n\n }\n\n }\n\n\n\n /// Read strings that do not come in pairs.\n\n fn read_string(&mut self) -> Result<String> {\n\n let reference = self.read_uvarint()?;\n\n let value = if reference == 0 {\n", "file_path": "src/osm_io/o5m/reader.rs", "rank": 46, "score": 16.9089293160937 }, { "content": " /// See: https://wiki.openstreetmap.org/wiki/O5m#Bounding_Box\n\n fn write_bounding_box(&mut self, boundary: &Boundary) -> Result<()> {\n\n let mut bytes = Vec::new();\n\n bytes.write_varint(boundary.min.lon)?;\n\n bytes.write_varint(boundary.min.lat)?;\n\n bytes.write_varint(boundary.max.lon)?;\n\n bytes.write_varint(boundary.max.lat)?;\n\n\n\n self.inner.write_all(&[O5M_BOUNDING_BOX])?;\n\n self.inner.write_varint(bytes.len() as u64)?;\n\n self.inner.write_all(&bytes)?;\n\n Ok(())\n\n }\n\n\n\n /// See: https://wiki.openstreetmap.org/wiki/O5m#Node\n\n fn write_node(&mut self, node: &Node) -> Result<()> {\n\n let mut bytes = Vec::new();\n\n self.encoder.write_node(&mut bytes, node)?;\n\n\n\n self.inner.write_all(&[O5M_NODE])?;\n", "file_path": "src/osm_io/o5m/writer.rs", "rank": 47, "score": 16.453802829538844 }, { "content": " self.inner.write_varint(bytes.len() as u64)?;\n\n self.inner.write_all(&bytes)?;\n\n Ok(())\n\n }\n\n\n\n /// See: https://wiki.openstreetmap.org/wiki/O5m#Way\n\n fn write_way(&mut self, way: &Way) -> Result<()> {\n\n let mut bytes = Vec::new();\n\n self.encoder.write_way(&mut bytes, way)?;\n\n\n\n self.inner.write_all(&[O5M_WAY])?;\n\n self.inner.write_varint(bytes.len() as u64)?;\n\n self.inner.write_all(&bytes)?;\n\n Ok(())\n\n }\n\n\n\n /// See: https://wiki.openstreetmap.org/wiki/O5m#Relation\n\n fn write_relation(&mut self, rel: &Relation) -> Result<()> {\n\n let mut bytes = Vec::new();\n\n self.encoder.write_relation(&mut bytes, rel)?;\n", "file_path": "src/osm_io/o5m/writer.rs", "rank": 48, "score": 16.106877412647727 }, { "content": " }\n\n\n\n /// Converts a relation into a byte vector that can be written to file.\n\n /// See: https://wiki.openstreetmap.org/wiki/O5m#Relation\n\n pub fn write_relation<W: Write>(&mut self, writer: &mut W, rel: &Relation) -> Result<()> {\n\n let mut mem_bytes = Vec::new();\n\n self.write_rel_members(&mut mem_bytes, &rel.members)?;\n\n\n\n writer.write_varint(self.delta.encode(Id, rel.id))?;\n\n self.write_meta(writer, &rel.meta)?;\n\n writer.write_varint(mem_bytes.len() as u64)?;\n\n writer.write_all(&mem_bytes)?;\n\n\n\n for tag in &rel.meta.tags {\n\n self.write_tag(writer, &tag)?;\n\n }\n\n\n\n Ok(())\n\n }\n\n\n", "file_path": "src/osm_io/o5m/writer.rs", "rank": 49, "score": 15.928480816037197 }, { "content": " }\n\n Ok(())\n\n }\n\n\n\n /// Write tag as string pair to `writer`.\n\n fn write_tag<W: Write>(&mut self, writer: &mut W, tag: &Tag) -> Result<()> {\n\n let bytes = self.string_pair_to_bytes(&tag.key, &tag.value);\n\n writer.write_all(&bytes)?;\n\n Ok(())\n\n }\n\n\n\n /// Converts a user to a byte vector that can be written to file.\n\n /// See: https://wiki.openstreetmap.org/wiki/O5m#Strings\n\n fn write_user<W: Write>(&mut self, writer: &mut W, uid: u64, username: &str) -> Result<()> {\n\n let mut bytes = Vec::new();\n\n bytes.push(0);\n\n bytes.write_varint(uid)?;\n\n\n\n bytes.push(0);\n\n for byte in username.bytes() {\n", "file_path": "src/osm_io/o5m/writer.rs", "rank": 50, "score": 15.101087457380599 }, { "content": " let delta_coordinate = self.delta_coordinate(node.coordinate);\n\n\n\n writer.write_varint(delta_id)?;\n\n self.write_meta(writer, &node.meta)?;\n\n writer.write_varint(delta_coordinate.lon)?;\n\n writer.write_varint(delta_coordinate.lat)?;\n\n\n\n for tag in &node.meta.tags {\n\n self.write_tag(writer, &tag)?;\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n /// Converts a way into a byte vector that can be written to file.\n\n /// See: https://wiki.openstreetmap.org/wiki/O5m#Way\n\n pub fn write_way<W: Write>(&mut self, writer: &mut W, way: &Way) -> Result<()> {\n\n let delta_id = self.delta.encode(Id, way.id);\n\n let mut ref_bytes = Vec::new();\n\n self.write_way_refs(&mut ref_bytes, &way.refs)?;\n", "file_path": "src/osm_io/o5m/writer.rs", "rank": 51, "score": 15.063934248444385 }, { "content": "\n\n self.inner.write_all(&[O5M_RELATION])?;\n\n self.inner.write_varint(bytes.len() as u64)?;\n\n self.inner.write_all(&bytes)?;\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<W: Write> OsmWrite<W> for O5mWriter<W> {\n\n fn write(&mut self, osm: &Osm) -> std::result::Result<(), Error> {\n\n self.reset()?;\n\n self.inner.write_all(&[O5M_HEADER])?;\n\n self.inner.write_all(O5M_HEADER_DATA)?;\n\n\n\n if let Some(boundary) = &osm.boundary {\n\n self.write_bounding_box(&boundary)?;\n\n }\n\n\n\n self.reset()?;\n\n for node in &osm.nodes {\n", "file_path": "src/osm_io/o5m/writer.rs", "rank": 52, "score": 14.935961651087293 }, { "content": "}\n\n\n\nimpl O5mEncoder {\n\n pub fn new() -> Self {\n\n O5mEncoder {\n\n string_table: StringReferenceTable::new(),\n\n delta: DeltaState::new(),\n\n }\n\n }\n\n\n\n /// Resets string reference table and all deltas.\n\n pub fn reset(&mut self) {\n\n self.string_table.clear();\n\n self.delta = DeltaState::new();\n\n }\n\n\n\n /// Converts a node into a byte vector that can be written to file.\n\n /// See: https://wiki.openstreetmap.org/wiki/O5m#Node\n\n pub fn write_node<W: Write>(&mut self, writer: &mut W, node: &Node) -> Result<()> {\n\n let delta_id = self.delta.encode(Id, node.id);\n", "file_path": "src/osm_io/o5m/writer.rs", "rank": 53, "score": 14.836307831421191 }, { "content": "\n\n writer.write_varint(delta_id)?;\n\n self.write_meta(writer, &way.meta)?;\n\n writer.write_varint(ref_bytes.len() as u64)?;\n\n writer.write_all(&ref_bytes)?;\n\n\n\n for tag in &way.meta.tags {\n\n self.write_tag(writer, &tag)?;\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n /// Converts way references to bytes.\n\n fn write_way_refs<W: Write>(&mut self, writer: &mut W, refs: &[i64]) -> Result<()> {\n\n for i in refs {\n\n let delta = self.delta.encode(WayRef, *i);\n\n writer.write_varint(delta)?;\n\n }\n\n Ok(())\n", "file_path": "src/osm_io/o5m/writer.rs", "rank": 54, "score": 14.656219550272478 }, { "content": " /// Writes relation members to `writers`.\n\n fn write_rel_members<W: Write>(\n\n &mut self,\n\n writer: &mut W,\n\n members: &[RelationMember],\n\n ) -> Result<()> {\n\n for m in members {\n\n let mem_type = member_type(m);\n\n let mem_role = m.role();\n\n let delta = self.delta_rel_member(m);\n\n\n\n let mut mem_bytes = Vec::new();\n\n mem_bytes.write_all(&[0x00])?;\n\n mem_bytes.write_all(&mem_type.as_bytes())?;\n\n mem_bytes.write_all(&mem_role.as_bytes())?;\n\n mem_bytes.write_all(&[0x00])?;\n\n\n\n writer.write_varint(delta)?;\n\n writer.write_all(&self.string_table.reference(mem_bytes))?;\n\n }\n", "file_path": "src/osm_io/o5m/writer.rs", "rank": 55, "score": 14.212812152018973 }, { "content": "use super::super::chrono::{TimeZone, Utc};\n\nuse super::quick_xml::events::{BytesDecl, BytesEnd, BytesStart, Event};\n\nuse super::quick_xml::Writer;\n\nuse crate::geo::Boundary;\n\nuse crate::osm_io::error::{Error, Result};\n\nuse crate::osm_io::OsmWrite;\n\nuse crate::{Meta, Node, Osm, Relation, RelationMember, Tag, Way};\n\nuse std::io::Write;\n\n\n\nconst OSM_VERSION: &str = \"0.6\";\n\nconst OSM_GENERATOR: &str = \"Vadeen OSM\";\n\nconst XML_VERSION: &[u8] = b\"1.0\";\n\nconst XML_ENCODING: &[u8] = b\"UTF-8\";\n\n\n\n/// A writer for the xml format.\n\npub struct XmlWriter<W: Write> {\n\n writer: Writer<W>,\n\n}\n\n\n\nimpl<W: Write> XmlWriter<W> {\n", "file_path": "src/osm_io/xml/writer.rs", "rank": 56, "score": 13.74864055428311 }, { "content": " Ok(self.decoder.read_u8()?)\n\n }\n\n\n\n /// Skip a whole data set. Used when data set is unknown.\n\n fn skip_dataset(&mut self, block_type: u8) -> Result<()> {\n\n if block_type >= 0xF0 {\n\n self.decoder.read_limit()?;\n\n self.decoder.skip_all()?;\n\n }\n\n Ok(())\n\n }\n\n\n\n /// See: https://wiki.openstreetmap.org/wiki/O5m#Bounding_Box\n\n fn read_boundary(&mut self) -> Result<Boundary> {\n\n self.decoder.read_limit()?;\n\n let min_lon = self.decoder.read_varint()? as i32;\n\n let min_lat = self.decoder.read_varint()? as i32;\n\n let max_lon = self.decoder.read_varint()? as i32;\n\n let max_lat = self.decoder.read_varint()? as i32;\n\n Ok(Boundary {\n", "file_path": "src/osm_io/o5m/reader.rs", "rank": 57, "score": 13.440132438178935 }, { "content": " }\n\n\n\n /// Read uid and user. Uid is encoded as a varint, but the bytes are treated as a string pair,\n\n /// i.e. appears in the string reference table.\n\n fn read_user(&mut self) -> Result<(u64, String)> {\n\n let reference = self.read_uvarint()?;\n\n if reference != 0 {\n\n let bytes = self.string_table.get(reference)?;\n\n Ok(Self::bytes_to_user(bytes))\n\n } else {\n\n let bytes = self.read_string_bytes(2)?;\n\n Ok(Self::bytes_to_user(&bytes))\n\n }\n\n }\n\n\n\n /// Turns bytes into uid and username.\n\n fn bytes_to_user(bytes: &[u8]) -> (u64, String) {\n\n let (uid_bytes, user_bytes) = Self::split_string_bytes(&bytes);\n\n let uid: u64 = VarInt::new(Vec::from(uid_bytes)).into();\n\n let user = String::from_utf8_lossy(&user_bytes).into_owned();\n", "file_path": "src/osm_io/o5m/reader.rs", "rank": 58, "score": 13.233910938405664 }, { "content": " }\n\n\n\n self.string_table.push(&data);\n\n Ok(data)\n\n }\n\n\n\n /// Read a delta value.\n\n fn read_delta(&mut self, delta: Delta) -> Result<i64> {\n\n let val = self.read_varint()?;\n\n Ok(self.delta.decode(delta, val))\n\n }\n\n\n\n /// Calls callback until end of file is reached.\n\n /// This function assumes that the callback is consuming data on the provided reader (self),\n\n /// otherwise this will loop in infinity.\n\n fn read_until_eof<T>(&mut self, f: fn(&mut Self) -> Result<T>) -> Result<Vec<T>> {\n\n let mut vec = Vec::new();\n\n loop {\n\n match f(self) {\n\n Ok(r) => vec.push(r),\n", "file_path": "src/osm_io/o5m/reader.rs", "rank": 59, "score": 13.229058423905922 }, { "content": "//! Base module for reading and writing osm xml data.\n\n//! See: https://wiki.openstreetmap.org/wiki/OSM_XML\n\n\n\nextern crate quick_xml;\n\n\n\nmod reader;\n\nmod writer;\n\n\n\npub use self::reader::*;\n\npub use self::writer::*;\n\nuse crate::osm_io::error::Error;\n\nuse crate::osm_io::error::ErrorKind::ParseError;\n\n\n\nimpl From<quick_xml::Error> for Error {\n\n fn from(e: quick_xml::Error) -> Self {\n\n Error::new(ParseError, Some(e.to_string()))\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/osm_io/xml.rs", "rank": 60, "score": 13.188648005762529 }, { "content": "//!\n\n//! Read from arbitrary reader and write to arbitrary writer:\n\n//! ```rust,no_run\n\n//! # use std::path::Path;\n\n//! # use std::convert::TryInto;\n\n//! # use std::fs::File;\n\n//! # use vadeen_osm::osm_io::{create_reader, create_writer, FileFormat};\n\n//! # use vadeen_osm::osm_io::error::Result;\n\n//! # use std::io::BufReader;\n\n//! # fn main() -> Result<()> {\n\n//! // Read from file in this example, you can read from anything that implements the Read trait.\n\n//! let path = Path::new(\"map.osm\");\n\n//! let input = File::open(path)?;\n\n//!\n\n//! // Get format from path. This can also be specified as FileFormat::Xml or any other FileFormat.\n\n//! let format = path.try_into()?;\n\n//!\n\n//! // Create reader and read.\n\n//! let mut reader = create_reader(BufReader::new(input), format);\n\n//! let osm = reader.read()?;\n", "file_path": "src/osm_io.rs", "rank": 61, "score": 13.032357141980029 }, { "content": " ParseError,\n\n Some(format!(\n\n \"The 'type' attribute contains invalid data '{}'.\",\n\n t\n\n )),\n\n )),\n\n }\n\n }\n\n}\n\n\n\nimpl<R: BufRead> XmlReader<R> {\n\n pub fn new(inner: R) -> XmlReader<R> {\n\n XmlReader {\n\n reader: Reader::from_reader(inner),\n\n line: 1,\n\n }\n\n }\n\n\n\n /// Parse next xml element. Returns false if end of file was reached.\n\n fn parse_event(&mut self, osm: &mut Osm) -> Result<bool> {\n", "file_path": "src/osm_io/xml/reader.rs", "rank": 62, "score": 13.026229339403459 }, { "content": " self.repr.source()\n\n }\n\n}\n\n\n\nimpl Display for Error {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {\n\n match &self.message {\n\n Some(message) => write!(f, \"{}\", message),\n\n None => self.repr.fmt(f),\n\n }\n\n }\n\n}\n\n\n\n/// Errors can not really be compared. This is to allow the results to be compared when they are Ok.\n\nimpl PartialEq for Error {\n\n fn eq(&self, _other: &Self) -> bool {\n\n false\n\n }\n\n}\n\n\n\nimpl From<io::Error> for Error {\n\n fn from(e: io::Error) -> Self {\n\n Error {\n\n repr: Simple(IO(e)),\n\n message: None,\n\n }\n\n }\n\n}\n", "file_path": "src/osm_io/error.rs", "rank": 63, "score": 13.013881211286925 }, { "content": "use crate::osm_io::error::ErrorKind::IO;\n\nuse crate::osm_io::error::Repr::Simple;\n\nuse std::fmt::{Display, Formatter};\n\nuse std::io;\n\n\n\npub type Result<T> = std::result::Result<T, Error>;\n\n\n\n/// Represents errors that may occur when reading or writing osm.\n\n#[derive(Debug)]\n\npub struct Error {\n\n repr: Repr,\n\n message: Option<String>,\n\n}\n\n\n\n/// It will make it possible to change internals without breaking change.\n\n#[derive(Debug)]\n", "file_path": "src/osm_io/error.rs", "rank": 64, "score": 12.901412130711119 }, { "content": "//! IO functionality for OSM maps.\n\n//!\n\n//! Reading to and from files are easiest done with the [`read`] and [`write`] functions.\n\n//!\n\n//! Readers and writers are easies created with the [`create_reader`] and [`create_writer`]\n\n//! functions.\n\n//!\n\n//! Error handling is defined in the [`error`] module.\n\n//!\n\n//! # Examples\n\n//! Read from .osm file and write to .o5m file:\n\n//! ```rust,no_run\n\n//! use vadeen_osm::osm_io::{read, write};\n\n//! # use vadeen_osm::osm_io::error::Result;\n\n//! # fn main() -> Result<()> {\n\n//! let osm = read(\"map.osm\")?;\n\n//! write(\"map.o5m\", &osm)?;\n\n//! # Ok(())\n\n//! # }\n\n//! ```\n", "file_path": "src/osm_io.rs", "rank": 65, "score": 12.27104422434735 }, { "content": " Ok(())\n\n }\n\n\n\n /// Writes meta to `writer`. It's positioned directly after the id of the element.\n\n pub fn write_meta<W: Write>(&mut self, writer: &mut W, meta: &Meta) -> Result<()> {\n\n if let Some(version) = meta.version {\n\n writer.write_varint(version)?;\n\n\n\n if let Some(author) = meta.author.as_ref() {\n\n let delta_time = self.delta.encode(Time, author.created);\n\n let delta_change_set = self.delta.encode(ChangeSet, author.change_set as i64);\n\n\n\n writer.write_varint(delta_time)?;\n\n writer.write_varint(delta_change_set)?;\n\n self.write_user(writer, author.uid, &author.user)?;\n\n } else {\n\n writer.write_all(&[0x00])?; // No author info.\n\n }\n\n } else {\n\n writer.write_all(&[0x00])?; // No version, no timestamp and no author info.\n", "file_path": "src/osm_io/o5m/writer.rs", "rank": 66, "score": 11.972928120574224 }, { "content": " fn split_string_bytes(bytes: &[u8]) -> (&[u8], &[u8]) {\n\n let div = bytes.iter().position(|b| b == &0u8).unwrap();\n\n (&bytes[0..div], &bytes[(div + 1)..])\n\n }\n\n\n\n /// Reads string bytes from stream. A string can consist of 1 or more parts. Each part is\n\n /// divided by a zero byte. String pairs have 2 parts. Uid and and username have one part since\n\n /// they are not divided by a zero byte.\n\n fn read_string_bytes(&mut self, parts: u8) -> Result<Vec<u8>> {\n\n let mut data = Vec::new();\n\n let mut count = 0;\n\n loop {\n\n let b = self.read_u8()?;\n\n if b == 0 {\n\n count += 1;\n\n if count == parts {\n\n break;\n\n }\n\n }\n\n data.push(b);\n", "file_path": "src/osm_io/o5m/reader.rs", "rank": 67, "score": 11.460638912774737 }, { "content": " Err(e) => {\n\n if let ErrorKind::IO(err) = e.kind() {\n\n if err.kind() == std::io::ErrorKind::UnexpectedEof {\n\n break;\n\n }\n\n }\n\n return Err(e);\n\n }\n\n }\n\n }\n\n Ok(vec)\n\n }\n\n}\n\n\n\nimpl<R: BufRead> OsmRead for O5mReader<R> {\n\n fn read(&mut self) -> std::result::Result<Osm, Error> {\n\n let mut osm = Osm::default();\n\n\n\n loop {\n\n match self.parse_next(&mut osm) {\n", "file_path": "src/osm_io/o5m/reader.rs", "rank": 68, "score": 11.39108865057568 }, { "content": " }\n\n}\n\n\n\nimpl<W: Write> OsmWrite<W> for XmlWriter<W> {\n\n fn write(&mut self, osm: &Osm) -> std::result::Result<(), Error> {\n\n self.write_start()?;\n\n\n\n if let Some(boundary) = &osm.boundary {\n\n self.write_bounds(boundary)?;\n\n }\n\n\n\n for node in &osm.nodes {\n\n self.write_node(node)?;\n\n }\n\n\n\n for way in &osm.ways {\n\n self.write_way(way)?;\n\n }\n\n\n\n for rel in &osm.relations {\n", "file_path": "src/osm_io/xml/writer.rs", "rank": 69, "score": 11.327016813661812 }, { "content": " pub fn new(inner: W) -> XmlWriter<W> {\n\n XmlWriter {\n\n writer: Writer::new(inner),\n\n }\n\n }\n\n\n\n /// Write the start tags: Xml header and <osm>-tag.\n\n fn write_start(&mut self) -> Result<()> {\n\n self.writer.write_event(Event::Decl(BytesDecl::new(\n\n XML_VERSION,\n\n Some(XML_ENCODING),\n\n None,\n\n )))?;\n\n self.writer.write(b\"\\n\")?;\n\n\n\n let elem = BytesStart::owned_name(b\"osm\".to_vec())\n\n .with_attributes(vec![(\"version\", OSM_VERSION), (\"generator\", OSM_GENERATOR)]);\n\n self.writer.write_event(Event::Start(elem))?;\n\n self.writer.write(b\"\\n\")?;\n\n Ok(())\n", "file_path": "src/osm_io/xml/writer.rs", "rank": 70, "score": 11.2491029756916 }, { "content": " // Pop the oldest one off if we are at the limit.\n\n if self.table.len() == MAX_STRING_TABLE_SIZE {\n\n self.table.pop_back();\n\n }\n\n\n\n self.table.push_front(bytes.to_vec());\n\n }\n\n}\n\n\n\nimpl DeltaValue {\n\n pub fn new() -> Self {\n\n DeltaValue { state: 0 }\n\n }\n\n\n\n /// Calculate delta and update state.\n\n pub fn delta(&mut self, id: i64) -> i64 {\n\n let delta = id - self.state;\n\n self.state = id;\n\n delta\n\n }\n", "file_path": "src/osm_io/o5m.rs", "rank": 71, "score": 11.14949186942703 }, { "content": " self.writer.write(b\"\\n\")?;\n\n\n\n self.write_tags(&node.meta.tags)?;\n\n\n\n self.writer.write(b\"\\t\")?;\n\n self.writer\n\n .write_event(Event::End(BytesEnd::owned(b\"node\".to_vec())))?;\n\n }\n\n self.writer.write(b\"\\n\")?;\n\n Ok(())\n\n }\n\n\n\n /// See: https://wiki.openstreetmap.org/wiki/Way\n\n fn write_way(&mut self, way: &Way) -> Result<()> {\n\n let mut elem = BytesStart::owned_name(b\"way\".to_vec());\n\n elem.push_attribute((\"id\", way.id.to_string().as_ref()));\n\n\n\n add_meta_attributes(&mut elem, &way.meta);\n\n\n\n self.writer.write(b\"\\t\")?;\n", "file_path": "src/osm_io/xml/writer.rs", "rank": 72, "score": 11.088815044810218 }, { "content": " /// See: https://wiki.openstreetmap.org/wiki/Relation\n\n fn write_relation(&mut self, rel: &Relation) -> Result<()> {\n\n let mut elem = BytesStart::owned_name(b\"relation\".to_vec());\n\n elem.push_attribute((\"id\", rel.id.to_string().as_ref()));\n\n\n\n add_meta_attributes(&mut elem, &rel.meta);\n\n\n\n self.writer.write(b\"\\t\")?;\n\n self.writer.write_event(Event::Start(elem))?;\n\n self.writer.write(b\"\\n\")?;\n\n\n\n for m in &rel.members {\n\n let mut mem = BytesStart::owned_name(b\"member\".to_vec());\n\n add_member_attributes(&mut mem, m);\n\n\n\n self.writer.write(b\"\\t\\t\")?;\n\n self.writer.write_event(Event::Empty(mem))?;\n\n self.writer.write(b\"\\n\")?;\n\n }\n\n\n", "file_path": "src/osm_io/xml/writer.rs", "rank": 73, "score": 11.0153801614205 }, { "content": " }\n\n\n\n fn next_id(&mut self) -> i64 {\n\n self.osm.max_id += 1;\n\n self.osm.max_id\n\n }\n\n}\n\n\n\nimpl Default for OsmBuilder {\n\n fn default() -> Self {\n\n OsmBuilder {\n\n osm: Osm::default(),\n\n }\n\n }\n\n}\n\n\n\nimpl Osm {\n\n /// Add a node to the map, the boundary is expanded to include the node.\n\n pub fn add_node(&mut self, node: Node) {\n\n if let Some(boundary) = &mut self.boundary {\n", "file_path": "src/lib.rs", "rank": 74, "score": 10.732226590826713 }, { "content": " }\n\n\n\n /// Write end of osm: </osm>.\n\n fn write_end(&mut self) -> Result<()> {\n\n let elem = BytesEnd::owned(b\"osm\".to_vec());\n\n self.writer.write_event(Event::End(elem))?;\n\n Ok(())\n\n }\n\n\n\n /// Optional bounds box tag.\n\n fn write_bounds(&mut self, bounds: &Boundary) -> Result<()> {\n\n let elem = BytesStart::owned_name(b\"bounds\".to_vec()).with_attributes(vec![\n\n (\"minlat\", bounds.min.lat().to_string().as_ref()),\n\n (\"minlon\", bounds.min.lon().to_string().as_ref()),\n\n (\"maxlat\", bounds.max.lat().to_string().as_ref()),\n\n (\"maxlon\", bounds.max.lon().to_string().as_ref()),\n\n ]);\n\n\n\n self.writer.write(b\"\\t\")?;\n\n self.writer.write_event(Event::Empty(elem))?;\n", "file_path": "src/osm_io/xml/writer.rs", "rank": 75, "score": 10.665724983823779 }, { "content": " /// Reads relation members until `size` is consumed.\n\n fn read_relation_members(&mut self, size: u64) -> Result<Vec<RelationMember>> {\n\n let limit = self.inner.limit();\n\n self.set_limit(size);\n\n let members = self.read_until_eof(|r| Ok(r.read_relation_member()?))?;\n\n self.set_limit(limit - size);\n\n Ok(members)\n\n }\n\n\n\n /// Read a single relation member.\n\n fn read_relation_member(&mut self) -> Result<RelationMember> {\n\n let id = self.read_varint()?;\n\n let s = self.read_string()?;\n\n\n\n if !s.is_char_boundary(1) || s.len() < 2 {\n\n return Err(Error::new(\n\n ErrorKind::ParseError,\n\n Some(\"Corrupt relation member reference data.\".to_owned()),\n\n ));\n\n }\n", "file_path": "src/osm_io/o5m/reader.rs", "rank": 76, "score": 10.381722789366327 }, { "content": "use super::super::chrono::{DateTime, Utc};\n\nuse super::quick_xml::Reader;\n\nuse crate::geo::{Boundary, Coordinate};\n\nuse crate::osm_io::error::ErrorKind::ParseError;\n\nuse crate::osm_io::error::{Error, Result};\n\nuse crate::osm_io::OsmRead;\n\nuse crate::{AuthorInformation, Meta, Node, Osm, Relation, RelationMember, Tag, Way};\n\nuse quick_xml::events::{BytesStart, Event};\n\nuse std::collections::HashMap;\n\nuse std::io::BufRead;\n\nuse std::str::FromStr;\n\n\n\n/// A reader for the xml format.\n\npub struct XmlReader<R: BufRead> {\n\n reader: Reader<R>,\n\n line: u32,\n\n}\n\n\n\n/// Abstract representation of the attributes of an XML element.\n\n/// The attributes of each xml different element contains all information to create that OSM\n", "file_path": "src/osm_io/xml/reader.rs", "rank": 77, "score": 10.33126846166087 }, { "content": "//!\n\n//! // ... do som stuff with the map.\n\n//!\n\n//! // Write to a Vec in this example, you can write to anything that implements the Write trait.\n\n//! let output = Vec::new();\n\n//!\n\n//! // Create writer and write.\n\n//! let mut writer = create_writer(output, FileFormat::O5m);\n\n//! writer.write(&osm);\n\n//! # Ok(())\n\n//! # }\n\n//! ```\n\n//!\n\n//! [`create_reader`]: fn.create_reader.html\n\n//! [`create_writer`]: fn.create_writer.html\n\n//! [`read`]: fn.read.html\n\n//! [`write`]: fn.write.html\n\n//! [`FileFormat`]: enum.FileFormat.html\n\n//! [`error`]: error/index.html\n\nextern crate chrono;\n", "file_path": "src/osm_io.rs", "rank": 78, "score": 10.057657289087242 }, { "content": "use super::varint::ReadVarInt;\n\nuse super::varint::VarInt;\n\nuse super::*;\n\nuse crate::geo::{Boundary, Coordinate};\n\nuse crate::osm_io::error::Result;\n\nuse crate::osm_io::error::{Error, ErrorKind};\n\nuse crate::osm_io::o5m::Delta::*;\n\nuse crate::osm_io::OsmRead;\n\nuse crate::{AuthorInformation, Meta, Node, Osm, Relation, RelationMember, Tag, Way};\n\nuse std::io::{BufRead, Read, Take};\n\n\n\n/// A reader for the o5m format.\n\npub struct O5mReader<R: BufRead> {\n\n decoder: O5mDecoder<R>,\n\n}\n\n\n\n/// Low level decoding from binary to data types.\n\n/// Keeps state of string references and delta values.\n", "file_path": "src/osm_io/o5m/reader.rs", "rank": 79, "score": 10.053300190413136 }, { "content": "impl TryFrom<&str> for FileFormat {\n\n type Error = Error;\n\n\n\n fn try_from(value: &str) -> std::result::Result<Self, Self::Error> {\n\n if let Some(format) = FileFormat::from(&value) {\n\n Ok(format)\n\n } else {\n\n Err(Error::new(\n\n ErrorKind::InvalidFileFormat,\n\n Some(format!(\"'{}' is not a valid osm file format.\", value)),\n\n ))\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<&String> for FileFormat {\n\n type Error = Error;\n\n\n\n fn try_from(value: &String) -> std::result::Result<Self, Self::Error> {\n\n (value[..]).try_into()\n", "file_path": "src/osm_io.rs", "rank": 80, "score": 9.990662027761257 }, { "content": " let mut buf = Vec::new();\n\n match self.reader.read_event(&mut buf)? {\n\n Event::Start(ref event) => self.parse_element(osm, event)?,\n\n Event::Empty(ref event) => self.parse_empty_element(osm, event)?,\n\n Event::Eof => return Ok(false),\n\n _ => { /* Ignore all other events. */ }\n\n }\n\n\n\n self.line += buf.iter().filter(|b| **b == b'\\n').count() as u32;\n\n Ok(true)\n\n }\n\n\n\n /// Read until and end element, or end of file is reached.\n\n /// Only empty elements are returned, the rest is ignored. This limitation since OSM only use\n\n /// empty element in a nested context within the <osm> tag.\n\n ///\n\n /// TODO Corruption if nested elements are encountered:\n\n /// This should return error if non empty element is encountered. The end of the nested element\n\n /// will terminate this read and possibly corrupt the flow.\n\n fn read_element_content(&mut self, mut buf: &mut Vec<u8>) -> Result<Vec<BytesStart>> {\n", "file_path": "src/osm_io/xml/reader.rs", "rank": 81, "score": 9.949345643187435 }, { "content": " }\n\n\n\n /// Sets limit of the reader by reading the limit from the stream.\n\n fn read_limit(&mut self) -> Result<()> {\n\n self.set_limit(9);\n\n let len = self.read_uvarint()?;\n\n self.set_limit(len);\n\n Ok(())\n\n }\n\n\n\n /// Skip until limit or end of file is reached.\n\n fn skip_all(&mut self) -> Result<()> {\n\n let _ = self.read_until_eof(|r| {\n\n r.read_u8()?;\n\n Ok(())\n\n })?;\n\n Ok(())\n\n }\n\n\n\n /// Read coordinate and delta decode values.\n", "file_path": "src/osm_io/o5m/reader.rs", "rank": 82, "score": 9.922341572896652 }, { "content": "impl ErrorKind {\n\n fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n\n match self {\n\n IO(e) => Some(e),\n\n _ => None,\n\n }\n\n }\n\n}\n\n\n\nimpl Display for ErrorKind {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {\n\n match self {\n\n ErrorKind::InvalidFileFormat => write!(f, \"File format not recognized.\")?,\n\n ErrorKind::ParseError => write!(f, \"Unknown parse error occurred.\")?,\n\n IO(io_error) => match io_error.kind() {\n\n io::ErrorKind::UnexpectedEof => write!(f, \"Unexpected end of file.\")?,\n\n _ => write!(f, \"IO error: {}\", io_error)?,\n\n },\n\n };\n\n Ok(())\n", "file_path": "src/osm_io/error.rs", "rank": 83, "score": 9.854955943422091 }, { "content": " self.write_tags(&rel.meta.tags)?;\n\n\n\n self.writer.write(b\"\\t\")?;\n\n self.writer\n\n .write_event(Event::End(BytesEnd::owned(b\"relation\".to_vec())))?;\n\n self.writer.write(b\"\\n\")?;\n\n Ok(())\n\n }\n\n\n\n /// See: https://wiki.openstreetmap.org/wiki/Tags\n\n fn write_tags(&mut self, tags: &[Tag]) -> Result<()> {\n\n for tag in tags {\n\n let tag_elem = BytesStart::owned_name(b\"tag\".to_vec())\n\n .with_attributes(vec![(\"k\", tag.key.as_ref()), (\"v\", tag.value.as_ref())]);\n\n\n\n self.writer.write(b\"\\t\\t\")?;\n\n self.writer.write_event(Event::Empty(tag_elem))?;\n\n self.writer.write(b\"\\n\")?;\n\n }\n\n Ok(())\n", "file_path": "src/osm_io/xml/writer.rs", "rank": 84, "score": 9.774202718899355 }, { "content": "\n\nimpl Boundary {\n\n pub fn new<C: Into<Coordinate>>(min: C, max: C) -> Boundary {\n\n Boundary {\n\n min: min.into(),\n\n max: max.into(),\n\n freeze: false,\n\n }\n\n }\n\n\n\n /// Same as `default()` but inverted so min contains max and max contains min.\n\n /// Used when a boundary are intended to be expanded by coordinates.\n\n pub fn inverted() -> Self {\n\n Boundary {\n\n min: (90.0, 180.0).into(),\n\n max: (-90.0, -180.0).into(),\n\n freeze: false,\n\n }\n\n }\n\n\n", "file_path": "src/geo.rs", "rank": 85, "score": 9.667576383706013 }, { "content": "use vadeen_osm::osm_io::error::Result;\n\nuse vadeen_osm::osm_io::write;\n\nuse vadeen_osm::OsmBuilder;\n\n\n", "file_path": "examples/osm_builder.rs", "rank": 86, "score": 9.655777408199395 }, { "content": " self.writer.write(b\"\\n\")?;\n\n Ok(())\n\n }\n\n\n\n /// See: https://wiki.openstreetmap.org/wiki/Node\n\n fn write_node(&mut self, node: &Node) -> Result<()> {\n\n let mut elem = BytesStart::owned_name(b\"node\".to_vec()).with_attributes(vec![\n\n (\"id\", node.id.to_string().as_ref()),\n\n (\"lat\", node.coordinate.lat().to_string().as_ref()),\n\n (\"lon\", node.coordinate.lon().to_string().as_ref()),\n\n ]);\n\n\n\n add_meta_attributes(&mut elem, &node.meta);\n\n\n\n if node.meta.tags.is_empty() {\n\n self.writer.write(b\"\\t\")?;\n\n self.writer.write_event(Event::Empty(elem))?;\n\n } else {\n\n self.writer.write(b\"\\t\")?;\n\n self.writer.write_event(Event::Start(elem))?;\n", "file_path": "src/osm_io/xml/writer.rs", "rank": 87, "score": 9.563368968013181 }, { "content": " Ok(bytes[0])\n\n }\n\n\n\n /// Read author information. Uid, user and change set.\n\n fn read_author_info(&mut self) -> Result<Option<AuthorInformation>> {\n\n let created = self.read_delta(Time)?;\n\n\n\n // If there is no time, there is no author information.\n\n if created == 0 {\n\n return Ok(None);\n\n }\n\n\n\n let change_set = self.read_delta(ChangeSet)? as u64;\n\n let (uid, user) = self.read_user()?;\n\n Ok(Some(AuthorInformation {\n\n created,\n\n change_set,\n\n uid,\n\n user,\n\n }))\n", "file_path": "src/osm_io/o5m/reader.rs", "rank": 88, "score": 9.55724723338462 }, { "content": "use vadeen_osm::osm_io::error::Result;\n\nuse vadeen_osm::osm_io::write;\n\nuse vadeen_osm::{OsmBuilder, Tag};\n\nuse vadeen_osm::geo::Coordinate;\n\n\n", "file_path": "examples/custom_data.rs", "rank": 89, "score": 9.276348878152241 }, { "content": "\n\npub mod error;\n\nmod o5m;\n\nmod xml;\n\n\n\nuse self::error::*;\n\nuse self::o5m::O5mWriter;\n\nuse self::xml::XmlWriter;\n\nuse crate::osm_io::o5m::O5mReader;\n\nuse crate::osm_io::xml::XmlReader;\n\nuse crate::Osm;\n\nuse std::convert::{TryFrom, TryInto};\n\nuse std::fs::File;\n\nuse std::io::{BufRead, BufReader, Write};\n\nuse std::path::Path;\n\n\n\n/// Represent a osm file format.\n\n///\n\n/// See OSM documentation over [`file formats`].\n\n///\n", "file_path": "src/osm_io.rs", "rank": 90, "score": 9.259014721013518 }, { "content": " way.refs = create_way_refs(&event_content)?;\n\n way.meta.tags = create_tags(&event_content)?;\n\n osm.add_way(way);\n\n }\n\n b\"relation\" => {\n\n let mut relation = parse_relation(&event)?;\n\n relation.members = create_relation_members(&event_content)?;\n\n relation.meta.tags = create_tags(&event_content)?;\n\n osm.add_relation(relation);\n\n }\n\n _ => { /* Ignore unknown elements. */ }\n\n }\n\n\n\n self.line += buf.iter().filter(|b| **b == b'\\n').count() as u32;\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<R: BufRead> OsmRead for XmlReader<R> {\n\n fn read(&mut self) -> std::result::Result<Osm, Error> {\n", "file_path": "src/osm_io/xml/reader.rs", "rank": 91, "score": 9.249132127068465 }, { "content": " /// See: https://wiki.openstreetmap.org/wiki/O5m#Relation\n\n fn read_relation(&mut self) -> Result<Relation> {\n\n self.decoder.read_limit()?;\n\n\n\n let mut relation = Relation::default();\n\n relation.id = self.decoder.read_delta(Id)?;\n\n relation.meta = self.read_meta()?;\n\n\n\n let ref_size = self.decoder.read_uvarint()?;\n\n relation.members = self.decoder.read_relation_members(ref_size)?;\n\n relation.meta.tags = self.decoder.read_tags()?;\n\n\n\n Ok(relation)\n\n }\n\n\n\n /// Meta is common data part of every element.\n\n fn read_meta(&mut self) -> Result<Meta> {\n\n let mut meta = Meta::default();\n\n let version = self.decoder.read_uvarint()? as u32;\n\n meta.version = if version == 0 { None } else { Some(version) };\n", "file_path": "src/osm_io/o5m/reader.rs", "rank": 92, "score": 9.16934672694445 }, { "content": "use std::io;\n\nuse std::io::Write;\n\n\n\nuse super::*;\n\nuse crate::geo::{Boundary, Coordinate};\n\nuse crate::osm_io::error::Error;\n\nuse crate::osm_io::o5m::varint::WriteVarInt;\n\nuse crate::osm_io::o5m::Delta::{\n\n ChangeSet, Id, Lat, Lon, RelNodeRef, RelRelRef, RelWayRef, Time, WayRef,\n\n};\n\nuse crate::osm_io::OsmWrite;\n\nuse crate::{Meta, Node, Osm, Relation, RelationMember, Tag, Way};\n\n\n\n/// A writer for the o5m binary format.\n\n#[derive(Debug)]\n\npub struct O5mWriter<W> {\n\n inner: W,\n\n encoder: O5mEncoder,\n\n}\n\n\n\n/// Encodes data into bytes according the o5m specification. Keeps track of string references and\n\n/// delta values.\n\n#[derive(Debug)]\n", "file_path": "src/osm_io/o5m/writer.rs", "rank": 93, "score": 9.021188095117097 }, { "content": " message,\n\n }\n\n }\n\n\n\n pub fn message(&self) -> Option<&String> {\n\n self.message.as_ref()\n\n }\n\n\n\n pub fn set_message(&mut self, message: String) {\n\n self.message = Some(message);\n\n }\n\n\n\n /// Returns reference to error kind.\n\n pub fn kind(&self) -> &ErrorKind {\n\n match &self.repr {\n\n Simple(e) => &e,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/osm_io/error.rs", "rank": 94, "score": 8.87366250693298 }, { "content": " (uid, user)\n\n }\n\n\n\n /// Read tags. There is no size or delimiter for tags, so they are read until there is no more\n\n /// data to read in the current limit.\n\n fn read_tags(&mut self) -> Result<Vec<Tag>> {\n\n let pairs = self.read_until_eof(|r| Ok(r.read_string_pair()?))?;\n\n let tags = pairs.into_iter().map(|s| s.into()).collect();\n\n Ok(tags)\n\n }\n\n\n\n /// Reads way references until `size` is consumed.\n\n fn read_way_references(&mut self, size: u64) -> Result<Vec<i64>> {\n\n let limit = self.inner.limit();\n\n self.set_limit(size);\n\n let refs = self.read_until_eof(|r| Ok(r.read_delta(WayRef)?))?;\n\n self.set_limit(limit - size);\n\n Ok(refs)\n\n }\n\n\n", "file_path": "src/osm_io/o5m/reader.rs", "rank": 95, "score": 8.836705035155813 }, { "content": " lon: int_lon,\n\n }\n\n }\n\n\n\n pub fn lat(self) -> f64 {\n\n self.lat as f64 / COORD_PRECISION\n\n }\n\n\n\n pub fn lon(self) -> f64 {\n\n self.lon as f64 / COORD_PRECISION\n\n }\n\n}\n\n\n\nimpl Sub for Coordinate {\n\n type Output = Coordinate;\n\n\n\n fn sub(self, rhs: Self) -> Self::Output {\n\n Coordinate {\n\n lon: self.lon - rhs.lon,\n\n lat: self.lat - rhs.lat,\n", "file_path": "src/geo.rs", "rank": 96, "score": 8.604019062964234 }, { "content": " /// returned. If not the string will be pushed to the table and returned untouched.\n\n fn reference(&mut self, bytes: Vec<u8>) -> Vec<u8> {\n\n if bytes.len() > MAX_STRING_REFERENCE_LENGTH {\n\n return bytes;\n\n }\n\n\n\n if let Some(pos) = self.table.iter().position(|b| b == &bytes) {\n\n VarInt::create_bytes((pos + 1) as u64)\n\n } else {\n\n self.push(&bytes);\n\n bytes\n\n }\n\n }\n\n\n\n /// Push string to table. The string is only added if it do not exceed 250 bytes in length.\n\n pub fn push(&mut self, bytes: &[u8]) {\n\n if bytes.len() > MAX_STRING_REFERENCE_LENGTH {\n\n return;\n\n }\n\n\n", "file_path": "src/osm_io/o5m.rs", "rank": 97, "score": 8.59480895363724 }, { "content": " self.writer.write_event(Event::Start(elem))?;\n\n self.writer.write(b\"\\n\")?;\n\n\n\n for r in &way.refs {\n\n let mut nd = BytesStart::owned_name(b\"nd\".to_vec());\n\n nd.push_attribute((\"ref\", r.to_string().as_ref()));\n\n self.writer.write(b\"\\t\\t\")?;\n\n self.writer.write_event(Event::Empty(nd))?;\n\n self.writer.write(b\"\\n\")?;\n\n }\n\n\n\n self.write_tags(&way.meta.tags)?;\n\n\n\n self.writer.write(b\"\\t\")?;\n\n self.writer\n\n .write_event(Event::End(BytesEnd::owned(b\"way\".to_vec())))?;\n\n self.writer.write(b\"\\n\")?;\n\n Ok(())\n\n }\n\n\n", "file_path": "src/osm_io/xml/writer.rs", "rank": 98, "score": 8.579164209657696 }, { "content": "//! This crate contains implementation to read and write [`Open Street Maps`].\n\n//!\n\n//! The [`Osm`] struct is an abstract representation of an OSM map. You can build your map with this\n\n//! struct by adding nodes, ways and relations. Use the [`OsmBuilder`] if you are working with\n\n//! non OSM data, it lets you work with polygons, poly lines and points instead.\n\n//!\n\n//! The [`osm_io`] module contains io functionality for reading and writing multiple OSM formats.\n\n//! Currently osm and o5m is supported.\n\n//!\n\n//! The [`geo`] module contains some more general geographic abstractions used by this crate.\n\n//!\n\n//! [`Open Street Maps`]: https://wiki.openstreetmap.org/wiki/Main_Page\n\n//! [`Osm`]: struct.Osm.html\n\n//! [`OsmBuilder`]: struct.OsmBuilder.html\n\n//! [`osm_io`]: osm_io/index.html\n\n//! [`geo`]: geo/index.html\n\nmod element;\n\npub mod geo;\n\npub mod osm_io;\n\n\n", "file_path": "src/lib.rs", "rank": 99, "score": 8.549216316113212 } ]
Rust
src/nerve/github/response.rs
ustwo/github-issues
cc51621f3794d1172bb8bc333eb6be31f6736b61
use std::fmt; use hyper; use hyper::Client; use hyper::client::Response as HyperResponse; use hyper::header::{Headers, Accept, Authorization, Connection, UserAgent, qitem}; use regex::Regex; use rustc_serialize::json; use std::io::Read; use std::process; use say; use github; header! { (XRateLimitRemaining, "X-RateLimit-Remaining") => [u32] } header! { (Link, "Link") => [String] } #[derive(Debug)] pub struct Response { pub content: String, pub ratelimit: u32, } impl From<HyperResponse> for Response { fn from(mut res: HyperResponse) -> Self { let mut body = String::new(); res.read_to_string(&mut body).unwrap(); Response { content: body , ratelimit: ratelimit(&res.headers) } } } pub struct Page { pub content: String, pub next: Option<String>, pub ratelimit: u32, } impl Page { pub fn new(url: &str, token: &str) -> Page { let mut res = get_page(url.to_string(), token); let mut body = String::new(); res.read_to_string(&mut body).unwrap(); Page {content: body, next: next_url(link(&res.headers)), ratelimit: ratelimit(&res.headers)} } pub fn warn(&self) { if self.next.is_none() { println!("{} {} {}", say::warn(), self.ratelimit, "Remaining requests"); } } } impl fmt::Display for Page { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{{next: {:?}, ratelimit: {}}}", self.next, self.ratelimit) } } fn get_page(url: String, token: &str) -> HyperResponse { println!("{} {} {}", say::info(), "Fetching", url); let client = Client::new(); let res = client.get(&*url.clone()) .header(UserAgent(format!("nerve/{}", env!("CARGO_PKG_VERSION")))) .header(Authorization(format!("token {}", token))) .header(Accept(vec![qitem(github::mime())])) .header(Connection::close()) .send().unwrap_or_else(|_| process::exit(1)); match res.status { hyper::Ok => {} _ => { println!("{} {}", say::error(), "Unable to parse the response from Github"); process::exit(1) } } res } pub fn ratelimit(headers: &Headers) -> u32 { match headers.get() { Some(&XRateLimitRemaining(x)) => x, None => 0 } } pub fn warn_ratelimit(ratelimit: u32) { println!("{} {} {}", say::warn(), ratelimit, "Remaining requests"); } pub fn link(headers: &Headers) -> String { match headers.get() { Some(&Link(ref x)) => x.to_string(), None => "".to_string() } } fn next_url(link: String) -> Option<String> { let re = Regex::new(r"<([^;]+)>;\s*rel=.next.").unwrap(); match re.captures(&link) { None => None, Some(cs) => cs.at(1).as_ref().map(|x| x.to_string()) } } #[derive(Debug, RustcDecodable, RustcEncodable)] pub struct ResponseError { pub message: String, pub errors: Vec<ErrorResource>, } impl ResponseError { pub fn from_str(data: &str) -> Result<ResponseError, json::DecoderError> { json::decode(data) } } impl fmt::Display for ResponseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let error = self.errors.first().unwrap(); write!(f, "the field '{}' {}", error.field, "has an invalid value.") } } #[derive(Debug, RustcDecodable, RustcEncodable)] pub struct ErrorResource { pub code: String, pub resource: String, pub field: String, }
use std::fmt; use hyper; use hyper::Client; use hyper::client::Response as HyperResponse; use hyper::header::{Headers, Accept, Authorization, Connection, UserAgent, qitem}; use regex::Regex; use rustc_serialize::json; use std::io::Read; use std::process; use say; use github; header! { (XRateLimitRemaining, "X-RateLimit-Remaining") => [u32] } header! { (Link, "Link") => [String] } #[derive(Debug)] pub struct Response { pub content: String, pub ratelimit: u32, } impl From<HyperResponse> for Response { fn from(mut res: HyperResponse) -> Self { let mut body = String::new(); res.read_to_string(&mut body).unwrap(); Response { content: body , ratelimit: ratelimit(&res.headers) } } } pub struct Page { pub content: String, pub next: Option<String>, pub ratelimit: u32, } impl Page { pub fn new(url: &str, token: &str) -> Page { let mut res = get_page(url.to_string(), token); let mut body = String::new(); res.read_to_string(&mut body).unwrap(); Page {content: body, next: next_url(link(&res.headers)), ratelimit: ratelimit(&res.headers)} } pub fn warn(&self) { if self.next.is_none() { println!("{} {} {}", say::warn(), self.ratelimit, "Remaining requests"); } } } impl fmt::Display for Page { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{{next: {:?}, ratelimit: {}}}", self.next, self.ratelimit) } } fn get_page(url: String, token: &str) -> HyperResponse { println!("{} {} {}", say::info(), "Fetching", url); let client = Client::new(); let res = client.get(&*url.clone()) .header(UserAgent(format!("nerve/{}", env!("CARGO_PKG_VERSION")))) .header(Authorization(format!("token {}", token))) .header(Accept(vec![qitem(github::mime())])) .header(Connection::close()) .send().unwrap_or_else(|_| process::exit(1)); match res.status { hyper::Ok => {} _ => { println!("{} {}", say::error(), "Unable to parse the response from Github"); process::exit(1) } } res } pub fn ratelimit(headers: &Headers) ->
} impl ResponseError { pub fn from_str(data: &str) -> Result<ResponseError, json::DecoderError> { json::decode(data) } } impl fmt::Display for ResponseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let error = self.errors.first().unwrap(); write!(f, "the field '{}' {}", error.field, "has an invalid value.") } } #[derive(Debug, RustcDecodable, RustcEncodable)] pub struct ErrorResource { pub code: String, pub resource: String, pub field: String, }
u32 { match headers.get() { Some(&XRateLimitRemaining(x)) => x, None => 0 } } pub fn warn_ratelimit(ratelimit: u32) { println!("{} {} {}", say::warn(), ratelimit, "Remaining requests"); } pub fn link(headers: &Headers) -> String { match headers.get() { Some(&Link(ref x)) => x.to_string(), None => "".to_string() } } fn next_url(link: String) -> Option<String> { let re = Regex::new(r"<([^;]+)>;\s*rel=.next.").unwrap(); match re.captures(&link) { None => None, Some(cs) => cs.at(1).as_ref().map(|x| x.to_string()) } } #[derive(Debug, RustcDecodable, RustcEncodable)] pub struct ResponseError { pub message: String, pub errors: Vec<ErrorResource>,
random
[ { "content": "pub fn create(url: &str, token: &str, issue: &NewIssue) -> Result<Response, ResponseError> {\n\n let client = Client::new();\n\n let body = json::encode(issue).unwrap();\n\n\n\n let res = client.post(&*url.clone())\n\n .body(&body)\n\n .header(UserAgent(format!(\"nerve/{}\", env!(\"CARGO_PKG_VERSION\"))))\n\n .header(Authorization(format!(\"token {}\", token)))\n\n .header(Accept(vec![qitem(mime())]))\n\n .header(Connection::close())\n\n .send().unwrap_or_else(|_| process::exit(1));\n\n\n\n match res.status {\n\n hyper::Ok => {}\n\n StatusCode::Created => {}\n\n StatusCode::UnprocessableEntity => {\n\n let body: Response = From::from(res);\n\n let err = ResponseError::from_str(&body.content).unwrap();\n\n\n\n return Err(err);\n\n }\n\n e => {\n\n println!(\"{} {}\", say::error(), e);\n\n process::exit(1)\n\n }\n\n }\n\n\n\n Ok(From::from(res))\n\n}\n", "file_path": "src/nerve/github/issues.rs", "rank": 5, "score": 156865.58209416608 }, { "content": "pub fn highlight(text: &str) -> String {\n\n White.bold().paint(text).to_string()\n\n}\n\n\n", "file_path": "src/nerve/say.rs", "rank": 6, "score": 151631.02661769206 }, { "content": "pub fn red(text: &str) -> String {\n\n Red.bold().paint(text).to_string()\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn simple_info() {\n\n assert_eq!(info(), \"\\u{1b}[32mInfo:\\u{1b}[0m\");\n\n }\n\n #[test]\n\n fn format_info() {\n\n assert_eq!(format!(\"{} {}\", info(), \"foo\"), \"\\u{1b}[32mInfo:\\u{1b}[0m foo\");\n\n }\n\n}\n", "file_path": "src/nerve/say.rs", "rank": 7, "score": 151631.02661769206 }, { "content": "pub fn yellow(text: &str) -> String {\n\n Yellow.paint(text).to_string()\n\n}\n\n\n", "file_path": "src/nerve/say.rs", "rank": 8, "score": 151631.02661769206 }, { "content": "pub fn info() -> String {\n\n Green.paint(\"Info:\").to_string()\n\n}\n\n\n", "file_path": "src/nerve/say.rs", "rank": 9, "score": 126708.9776232137 }, { "content": "pub fn error() -> String {\n\n Red.paint(\"Error:\").to_string()\n\n}\n\n\n", "file_path": "src/nerve/say.rs", "rank": 10, "score": 126708.9776232137 }, { "content": "pub fn warn() -> String {\n\n Yellow.paint(\"Warning:\").to_string()\n\n}\n\n\n", "file_path": "src/nerve/say.rs", "rank": 11, "score": 126708.9776232137 }, { "content": "pub fn run(repopath: String,\n\n oauth_token: String,\n\n labels: Vec<String>,\n\n state: String,\n\n format: OutputFormat,\n\n output_file: String) {\n\n\n\n let labels_pair = if labels.is_empty() { \"\".to_owned() }\n\n else { format!(\"&labels={}\", labels.join(\",\")) };\n\n let url = format!(\"https://api.github.com/repos/{repopath}/issues?filter=all&state={state}{labels_pair}\",\n\n repopath = repopath,\n\n state = state,\n\n labels_pair = labels_pair);\n\n\n\n let page = Page::new(&url, &oauth_token);\n\n let mut issues = issues_from_json(&page.content).unwrap();\n\n let mut next_url = page.next.clone();\n\n\n\n page.warn();\n\n\n", "file_path": "src/nerve/cmd/fetch.rs", "rank": 12, "score": 117929.10424832157 }, { "content": "pub fn run(repopath: String, oauth_token: String, filename: String) {\n\n let href = format!(\"https://github.com/{}/issues/\", repopath);\n\n let existing_issues = fetch_open_issues(&repopath, &oauth_token);\n\n let title_list = extract_titles(existing_issues);\n\n\n\n let records = csv::Reader::from_file(filename).unwrap();\n\n let issues: NewIssues = NewIssues::from(records);\n\n\n\n\n\n for (i, new_issue) in issues.into_iter().enumerate() {\n\n let similars = filter_by_similar(&new_issue.title, &title_list, 0.6);\n\n\n\n if !similars.is_empty() {\n\n println!(\"#{} {}\", i, say::highlight(&new_issue.title));\n\n\n\n for (num, title) in similars {\n\n println!(\" {}{} {}\", href, say::red(&num.to_string()), say::yellow(&title));\n\n }\n\n }\n\n\n\n }\n\n}\n\n\n\n\n", "file_path": "src/nerve/cmd/check.rs", "rank": 13, "score": 116277.94781357914 }, { "content": "fn fetch_open_issues(repopath: &str, oauth_token: &str) -> Issues {\n\n let url = format!(\"https://api.github.com/repos/{repopath}/issues?filter=all&state=open\",\n\n repopath = repopath);\n\n\n\n let page = Page::new(&url, &oauth_token);\n\n\n\n let mut issues: Issues = issues_from_json(&page.content).unwrap();\n\n let mut next_url = page.next.clone();\n\n\n\n page.warn();\n\n\n\n while let Some(url) = next_url {\n\n let page = Page::new(&url, &oauth_token);\n\n issues.extend(issues_from_json(&page.content).unwrap());\n\n next_url = page.next.clone();\n\n\n\n page.warn();\n\n }\n\n\n\n issues\n\n}\n", "file_path": "src/nerve/cmd/check.rs", "rank": 14, "score": 104504.09993752923 }, { "content": "// CSV lib does not cast Vec<String> so this is a workaround.\n\npub fn split(s: String) -> Vec<String> {\n\n let s = s.trim();\n\n\n\n if s.is_empty() {\n\n vec![]\n\n } else {\n\n s.split(\",\").map(|s| From::from(s.trim())).collect()\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn empty_string() {\n\n let expected: Vec<String> = vec![];\n\n assert_eq!(split(\"\".to_string()), expected);\n\n }\n\n\n", "file_path": "src/nerve/format.rs", "rank": 15, "score": 104452.08086102502 }, { "content": "type Record = (String, String, String, String, Option<u32>);\n\n\n\nimpl From<Record> for NewIssue {\n\n fn from(record: Record) -> Self {\n\n let (title, body, labels, assignees, milestone):\n\n (String, String, String, String, Option<u32>) = record;\n\n\n\n NewIssue { assignees : split(assignees)\n\n , body : body\n\n , labels : split(labels)\n\n , title : title\n\n , milestone : milestone\n\n }\n\n }\n\n}\n\n\n\npub struct NewIssues(Vec<NewIssue>);\n\n\n\n\n\nimpl NewIssues {\n", "file_path": "src/nerve/github/entities.rs", "rank": 16, "score": 103164.64747886968 }, { "content": "pub fn is_repopath(value: String) -> Result<(), String> {\n\n if value.split(\"/\").collect::<Vec<&str>>().len() != 2 {\n\n return Err(String::from(\"<repopath> must have the form <owner>/<repo>. e.g. ustwo/github-issues\"));\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn valid_repopath() {\n\n assert!(is_repopath(\"foo/bar\".to_owned()).is_ok());\n\n }\n\n\n\n #[test]\n\n fn invalid_repopath() {\n\n assert!(is_repopath(\"foo_bar\".to_owned()).is_err());\n\n assert!(is_repopath(\"foo/bar/baz\".to_owned()).is_err());\n\n }\n\n\n\n}\n", "file_path": "src/nerve/validators.rs", "rank": 17, "score": 102487.27232406828 }, { "content": "pub fn run(repopath: String,\n\n oauth_token: String,\n\n filename: String) {\n\n\n\n let records = csv::Reader::from_file(filename).unwrap();\n\n let issues: NewIssues = NewIssues::from(records);\n\n\n\n let url = format!(\"https://api.github.com/repos/{repopath}/issues\",\n\n repopath = repopath);\n\n\n\n\n\n for new_issue in issues {\n\n let res = issues::create(&url, &oauth_token, &new_issue);\n\n\n\n match res {\n\n Ok(r) => {\n\n let issue = Issue::from_str(&r.content).unwrap();\n\n\n\n println!(\"{} {} {} {}\", say::info(), \"Created issue number\",\n\n issue.number,\n", "file_path": "src/nerve/cmd/upload.rs", "rank": 18, "score": 97328.49160730033 }, { "content": "pub fn issues_from_json(data: &str) -> Result<Issues, json::DecoderError> {\n\n json::decode(data)\n\n}\n\n\n\n\n\npub type Labels = Vec<Label>;\n\n\n\n#[derive(Debug, RustcDecodable, RustcEncodable)]\n\npub struct Label {\n\n pub name: String,\n\n}\n\n\n\n#[derive(Debug, RustcDecodable, RustcEncodable)]\n\npub struct User {\n\n pub login: String,\n\n}\n", "file_path": "src/nerve/github/entities.rs", "rank": 19, "score": 96581.429477078 }, { "content": "pub fn run(output: Option<&str>) {\n\n let template = r#\"title,body,labels,assignees,milestone_id\n\n\"A nice title\",\"A descriptive body\",\"in_backlog,feature\",arnau,1\"#;\n\n\n\n match output {\n\n Some(filepath) => {\n\n let mut f = File::create(filepath).unwrap();\n\n let _ = f.write_all(template.as_bytes());\n\n }\n\n None => println!(\"{}\", template),\n\n }\n\n}\n", "file_path": "src/nerve/cmd/template.rs", "rank": 20, "score": 95255.75477856869 }, { "content": "/// Checks if two strings are similar given a threshold from 0 to 1 where 0\n\n/// is different and 1 is equal.\n\n///\n\n/// Note that the current implementation uses the [Jaro distance](http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance).\n\n///\n\n/// ```\n\n/// use nerve::checker::similar;\n\n///\n\n/// match similar(\"foo\", \"bar\", 0.5) {\n\n/// Ok((s, distance)) => assert!(distance >= 0.5),\n\n/// Err((s, distance)) => assert!(distance < 0.5),\n\n/// }\n\n/// ```\n\npub fn similar<'a>(a: &str, b: &'a str, threshold: f64) -> DistanceResult<'a> {\n\n let distance = jaro(a, b);\n\n let res = (b, distance.clone());\n\n\n\n if distance >= threshold {\n\n Ok(res)\n\n } else {\n\n Err(res)\n\n }\n\n}\n\n\n\n\n", "file_path": "src/nerve/checker.rs", "rank": 21, "score": 92619.28090500209 }, { "content": "fn extract_titles<'a>(issues: Issues) -> Vec<(u32, String)> {\n\n issues.into_iter()\n\n .map(|issue| (issue.number, issue.title.unwrap_or(\"\".to_string())))\n\n .collect()\n\n}\n\n\n", "file_path": "src/nerve/cmd/check.rs", "rank": 22, "score": 89801.59725610426 }, { "content": "/// Checks if a string has any similars in a set of strings for the given\n\n/// threshold. Check `similar()` for implementation details.\n\npub fn similar_to_any<'a>(a: &'a str, v: &'a [IssueField], threshold: f64)\n\n -> Vec<(u32, DistanceResult<'a>)> {\n\n v.iter()\n\n .map(|&(id, ref b)| (id, similar(a, b, threshold)))\n\n .collect()\n\n}\n\n\n\n\n", "file_path": "src/nerve/checker.rs", "rank": 23, "score": 83173.46832267754 }, { "content": "/// Hyper Mime for application/vnd.github.v3+json\n\npub fn mime() -> mime::Mime {\n\n mime::Mime(mime::TopLevel::Application,\n\n mime::SubLevel::Ext(\"vnd.github.v3+json\".to_owned()),\n\n vec![(mime::Attr::Charset, mime::Value::Utf8)])\n\n}\n", "file_path": "src/nerve/github/mod.rs", "rank": 24, "score": 81684.15707153187 }, { "content": "type IssueField = (u32, String);\n\n\n", "file_path": "src/nerve/checker.rs", "rank": 25, "score": 77258.83311211789 }, { "content": "fn write_json(issues: Issues, output_file: String) {\n\n let mut f = File::create(output_file).unwrap();\n\n let string: String = json::encode(&issues).unwrap();\n\n let _ = f.write_all(string.as_bytes());\n\n}\n\n\n", "file_path": "src/nerve/cmd/fetch.rs", "rank": 26, "score": 76884.33420974825 }, { "content": "fn write_csv(issues: Issues, output_file: String) {\n\n let mut wtr = csv::Writer::from_file(output_file).unwrap();\n\n\n\n let headers = (\"number\",\n\n \"title\",\n\n \"state\",\n\n \"created_at\",\n\n \"closed_at\",\n\n \"assignee\",\n\n \"user\",\n\n \"labels\",\n\n \"body\");\n\n let _ = wtr.encode(headers);\n\n\n\n for issue in issues {\n\n let labels = issue.labels.iter()\n\n .map(|x| x.name.clone())\n\n .collect::<Vec<String>>()\n\n .join(\",\");\n\n let user = issue.user;\n", "file_path": "src/nerve/cmd/fetch.rs", "rank": 27, "score": 76884.33420974825 }, { "content": "/// Filters a list of strings based on how similar are to an initial string\n\n/// for the given threshold. Check `similar()` for implementation details.\n\npub fn filter_by_similar(input: &str, references: &[IssueField], threshold: f64) -> Vec<IssueField> {\n\n let xs = similar_to_any(input, references, threshold);\n\n\n\n xs.iter()\n\n .filter_map(|&(id, x)| {\n\n match x {\n\n Err(_) => None,\n\n Ok((s, _)) => Some((id, s.to_string()))\n\n }\n\n })\n\n .collect()\n\n}\n\n\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n", "file_path": "src/nerve/checker.rs", "rank": 28, "score": 75303.24710290585 }, { "content": "type FieldDistance<'a> = (&'a str, Distance);\n", "file_path": "src/nerve/checker.rs", "rank": 29, "score": 36796.4393463508 }, { "content": "fn main() {\n\n env_logger::init().unwrap();\n\n let matches = cli().get_matches();\n\n\n\n match matches.subcommand() {\n\n (\"fetch\", Some(sub_matches)) => {\n\n let labels: Vec<String> = values_t!(sub_matches, \"label\", String).unwrap_or(vec![]);\n\n let state = sub_matches.value_of(\"state\").unwrap_or(\"all\").to_owned();\n\n let repopath = sub_matches.value_of(\"repopath\").unwrap().to_owned();\n\n let oauth_token = sub_matches.value_of(\"oauth-token\").unwrap().to_owned();\n\n let format = value_t!(sub_matches, \"format\", OutputFormat).unwrap_or_else(|e| e.exit());\n\n let output = matches.value_of(\"output\").unwrap().to_owned();\n\n\n\n cmd::fetch::run(repopath,\n\n oauth_token,\n\n labels,\n\n state,\n\n format,\n\n output);\n\n\n", "file_path": "src/main.rs", "rank": 30, "score": 35463.64926864268 }, { "content": "fn cli() -> App<'static, 'static> {\n\n let upload_about = \"Upload issues from a CSV file. If the first line is\n\ndetected to be a header it will be ignored. The fields are identified and\n\nconsumed in order:\n\n\n\n1. `title`\n\n2. `body`\n\n3. `labels`\n\n4. `assignees`\n\n5. `milestone_id`\";\n\n\n\n\n\n App::new(\"github-issues\")\n\n .version(env!(\"CARGO_PKG_VERSION\"))\n\n .author(\"Arnau Siches <arnau@ustwo.com>\")\n\n .about(\"Github issues consumer.\")\n\n .subcommand(SubCommand::with_name(\"completions\")\n\n .about(\"Generates completion scripts for your shell\")\n\n .arg(Arg::with_name(\"SHELL\")\n\n .required(true)\n", "file_path": "src/main.rs", "rank": 31, "score": 30405.86613632374 }, { "content": "use ansi_term::Colour::{Green, Yellow, Red, White};\n\n\n", "file_path": "src/nerve/say.rs", "rank": 32, "score": 25174.405657223626 }, { "content": " while let Some(url) = next_url {\n\n let page = Page::new(&url, &oauth_token);\n\n issues.extend(issues_from_json(&page.content).unwrap());\n\n next_url = page.next.clone();\n\n\n\n page.warn();\n\n }\n\n\n\n println!(\"{} {}\", say::highlight(\"Total issues collected:\"), issues.len());\n\n\n\n\n\n match format {\n\n OutputFormat::CSV => write_csv(issues, output_file),\n\n OutputFormat::JSON => write_json(issues, output_file),\n\n }\n\n}\n\n\n\n\n", "file_path": "src/nerve/cmd/fetch.rs", "rank": 33, "score": 24116.73139707679 }, { "content": "//! Fetch command\n\n//!\n\n//! It fetches issues and serialises them based on the defined output format.\n\n//! Currently csv or json.\n\n\n\nuse csv;\n\nuse rustc_serialize::json;\n\nuse std::fs::File;\n\nuse std::io::prelude::*;\n\n\n\nuse say;\n\nuse format::OutputFormat;\n\nuse github::entities::{Issues, issues_from_json};\n\nuse github::response::Page;\n\n\n\n\n", "file_path": "src/nerve/cmd/fetch.rs", "rank": 34, "score": 24112.061061848864 }, { "content": " let assignee = issue.assignee;\n\n\n\n let row = (issue.number,\n\n issue.title,\n\n issue.state,\n\n issue.created_at,\n\n issue.closed_at,\n\n assignee,\n\n user,\n\n labels,\n\n issue.body);\n\n\n\n let _ = wtr.encode(row);\n\n }\n\n}\n", "file_path": "src/nerve/cmd/fetch.rs", "rank": 35, "score": 24104.312086333608 }, { "content": "# Github Issues CLI\n\n\n\n⚠️ No longer maintained ⚠️\n\n\n\nThe current version allows you to fetch or upload Github issues. `fetch` lets\n\nyou store the retrieved issues in CSV or JSON. `upload` lets you create\n\nmultiple issues from a CSV.\n\n\n\n\n\n## In short\n\n\n\n### Fetch issues\n\n\n\nGet all issues from `ustwo/ustwo.com-frontend` labelled as `in_backlog` or\n\n`bug` and store them as CSV in `ustwo.csv`.\n\n\n\n```sh\n\ngithub-issues fetch ustwo/ustwo.com-frontend \\\n\n --oauth-token=$GITHUB_TOKEN \\\n\n --format=csv \\\n\n --output=usweb.csv \\\n\n --label=in_backlog \\\n\n --label=bug\n\n```\n\n\n\n\n\n### Upload issues\n\n\n\nCreate a file `myissues.csv` with the following format:\n\n\n\n```csv\n\ntitle,body,labels,assignees,milestone_id\n\n\"A nice title\",\"A descriptive body\",\"in_backlog,feature\",arnau,1\n\n\"Another issue\",\"foo bar\",\"chore\",,\n\n```\n\n\n\nAnd run\n\n\n\n```sh\n\ngithub-issues upload ustwo/ustwo.com-frontend \\\n\n --oauth-token=$GITHUB_TOKEN \\\n\n --input=myissues.csv\n\n```\n\n\n\nThe order of the fields is fixed: `title`, `body`, `labels`, `assignees`,\n\n`milestone_id`. And `title` is the only required field so the minimum record\n\npossible is:\n\n\n\n```csv\n\nA title,,,,\n\nAnother title,,,,\n\n```\n\n\n\nAs you can see, the header line is optional. The fields are identified and\n\nconsumed in order:\n\n\n\n1. `title`\n\n2. `body`\n\n3. `labels`\n\n4. `assignees`\n\n5. `milestone_id`\n\n\n\n\n\nNote: Github allows you to create labels by just setting them in a new Issue\n\nbut it will fail if you reference a non-existing milestone id.\n\n\n\nThe output in the screen will be showing the progress like this:\n\n\n\n```\n\nInfo: Created issue number 18 A nice title\n\nInfo: Created issue number 19 Another issue\n\n```\n\n\n\nAnd it will reflect an error like:\n\n\n\n```\n\nError: Couldn't create an issue for 'Foo bar' because the field 'milestone' has an invalid value.\n\n```\n\n\n\n\n", "file_path": "README.md", "rank": 36, "score": 22699.649778781844 }, { "content": "# Changelog\n\n\n\n## next\n\n\n\n* Add JSON output format.\n\n\n\n## 0.2.0\n\n\n\n* Change `--csv` to `--format=csv`.\n\n* Improve help messages.\n\n* Improve error message for bad repopath patterns.\n\n* Add state flag for the fetch command.\n\n* Add colors to standard output.\n\n* Clean unnecessary params when querying Github.\n\n\n\n## 0.1.1\n\n\n\n* Add verbose flag.\n\n* Add fetch command.\n", "file_path": "CHANGELOG.md", "rank": 37, "score": 22696.933793339882 }, { "content": "# Contributing\n\n\n\nFirst of all, thanks for taking the time to submit a pull request!\n\n\n\nThese are the few notes and guidelines to keep things coherent.\n\n\n\n\n\n## Overview\n\n\n\n1. Check you have all [requirements](#requirements) in place.\n\n2. Create your [_feature_ branch](#feature-branch).\n\n3. [Install](#install) the project dependencies for development.\n\n4. [Test](#test).\n\n5. Push your branch and submit a [Pull Request](https://github.com/ustwo/github-issues/compare/).\n\n6. Add a description of your proposed changes and why they are needed.\n\n\n\nWe will review the changes as soon as possible.\n\n\n\n\n\n## Requirements\n\n\n\n* [Fork the project](http://github.com/ustwo/github-issues/fork) and clone.\n\n* Rust +1.12\n\n\n\n\n\n## Install\n\n\n\nThis project uses `cargo` to manage dependencies so making a build will fetch\n\nanything required.\n\n\n\n```sh\n\ncargo build\n\n```\n\n\n\nIf you are on Mac OSX you should probably use a custom `OPENSSL_INCLUDE_DIR`.\n\nFor example, mine is installed in `/usr/local/opt/openssl/include`.\n\n\n\n```sh\n\nOPENSSL_INCLUDE_DIR=/usr/local/openssl/include cargo build\n\n```\n\n\n\n\n\n## Feature Branch\n\n\n\n```sh\n\ngit checkout -b features/feature-name\n\n```\n\n\n\n\n\n## Test\n\n\n\n```sh\n\ncargo test\n\n```\n", "file_path": "CONTRIBUTING.md", "rank": 38, "score": 22696.85615369952 }, { "content": "## Check for duplicates\n\n\n\nIf you want to check if any record in the CSV you are about to upload is a\n\npossible duplicate to an existing issue you can pass the flag `--check` to\n\nthe `upload` command. This flag makes the command noop so even if there are\n\nno duplicates detected you'll have to run the `upload` command without the\n\nflag in order to create new issues.\n\n\n\nThe current duplicate detection is quite naive. It only checks if the title\n\nof the issue is similar to another one. So short names have more chances to\n\nbe false positives.\n\n\n\n\n\n## Install\n\n\n\nThe preferred way to install `github-issues` is via Hombrew:\n\n\n\n```sh\n\nbrew install ustwo/tools/github-issues\n\n```\n\n\n\nAlternatively, grab a [release](https://github.com/ustwo/github-issues/releases)\n\nand place it in your `$PATH`.\n\n\n\n\n\n## Contributing\n\n\n\nCheck our [contributing guidelines](./CONTRIBUTING.md)\n\n\n\n\n\n## Maintainers\n\n\n\n* [Arnau Siches](mailto:arnau@ustwo.com) (@arnau)\n\n\n\n\n\n## Contact\n\n\n\nopen.source@ustwo.com\n\n\n\n\n\n## License\n\n\n\nThis is a proof of concept with no guarantee of active maintenance.\n\n\n\nLicensed under [MIT](./LICENSE).\n", "file_path": "README.md", "rank": 39, "score": 22693.75734917292 }, { "content": "# Contributor Code of Conduct\n\n\n\nAs contributors and maintainers of this project, and in the interest of\n\nfostering an open and welcoming community, we pledge to respect all people who\n\ncontribute through reporting issues, posting feature requests, updating\n\ndocumentation, submitting pull requests or patches, and other activities.\n\n\n\nWe are committed to making participation in this project a harassment-free\n\nexperience for everyone, regardless of level of experience, gender, gender\n\nidentity and expression, sexual orientation, disability, personal appearance,\n\nbody size, race, ethnicity, age, religion, or nationality.\n\n\n\nExamples of unacceptable behavior by participants include:\n\n\n\n* The use of sexualized language or imagery\n\n* Personal attacks\n\n* Trolling or insulting/derogatory comments\n\n* Public or private harassment\n\n* Publishing other's private information, such as physical or electronic\n\n addresses, without explicit permission\n\n* Other unethical or unprofessional conduct\n\n\n\nProject maintainers have the right and responsibility to remove, edit, or\n\nreject comments, commits, code, wiki edits, issues, and other contributions\n\nthat are not aligned to this Code of Conduct, or to ban temporarily or\n\npermanently any contributor for other behaviors that they deem inappropriate,\n\nthreatening, offensive, or harmful.\n\n\n\nBy adopting this Code of Conduct, project maintainers commit themselves to\n\nfairly and consistently applying these principles to every aspect of managing\n\nthis project. Project maintainers who do not follow or enforce the Code of\n\nConduct may be permanently removed from the project team.\n\n\n\nThis Code of Conduct applies both within project spaces and in public spaces\n", "file_path": "CODE_OF_CONDUCT.md", "rank": 41, "score": 22211.640702970388 }, { "content": "when an individual is representing the project or its community.\n\n\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\n\nreported by contacting a project maintainer at open.source+code.of.conduct@ustwo.com. All\n\ncomplaints will be reviewed and investigated and will result in a response that\n\nis deemed necessary and appropriate to the circumstances. Maintainers are\n\nobligated to maintain confidentiality with regard to the reporter of an\n\nincident.\n\n\n\n\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage],\n\nversion 1.3.0, available at\n\n[http://contributor-covenant.org/version/1/3/0/][version]\n\n\n\n[homepage]: http://contributor-covenant.org\n\n[version]: http://contributor-covenant.org/version/1/3/0/\n", "file_path": "CODE_OF_CONDUCT.md", "rank": 44, "score": 22209.338282118464 }, { "content": "use hyper::Client;\n\nuse hyper::status::StatusCode;\n\nuse hyper::header::{ Accept, Authorization, Connection, UserAgent, qitem };\n\nuse hyper;\n\nuse rustc_serialize::json;\n\nuse std::process;\n\n\n\nuse say;\n\nuse github::mime;\n\nuse github::entities::{ NewIssue };\n\nuse github::response::{ Response, ResponseError };\n\n\n", "file_path": "src/nerve/github/issues.rs", "rank": 45, "score": 22205.746526459923 }, { "content": "// Github entities represented as structs.\n\nuse std::io;\n\nuse csv;\n\nuse rustc_serialize::json;\n\n\n\nuse format::split;\n\n\n\n/// An Issue-to-be. It doesn't have number, state or any timestamp because\n\n/// it is not yet created.\n\n///\n\n/// The flow is then:\n\n///\n\n/// create(NewIssue) -> Issue\n\n#[derive(Debug, RustcDecodable, RustcEncodable)]\n\npub struct NewIssue {\n\n pub assignees: Vec<String>,\n\n pub body: String,\n\n pub labels: Vec<String>,\n\n pub title: String,\n\n pub milestone: Option<u32>,\n\n}\n\n\n", "file_path": "src/nerve/github/entities.rs", "rank": 47, "score": 22198.715255868436 }, { "content": " pub closed_at: Option<String>,\n\n pub labels: Labels,\n\n pub number: u32,\n\n // pub id: u32,\n\n pub state: Option<String>,\n\n pub title: Option<String>,\n\n pub user: Option<User>,\n\n}\n\n\n\nimpl Issue {\n\n pub fn from_str(data: &str) -> Result<Issue, json::DecoderError> {\n\n json::decode(data)\n\n }\n\n}\n\n\n\n\n\npub type Issues = Vec<Issue>;\n\n\n", "file_path": "src/nerve/github/entities.rs", "rank": 48, "score": 22198.59450222954 }, { "content": "use hyper::mime;\n\n\n\npub mod entities;\n\npub mod response;\n\npub mod issues;\n\n\n\n\n\n/// Hyper Mime for application/vnd.github.v3+json\n", "file_path": "src/nerve/github/mod.rs", "rank": 49, "score": 22196.749103947514 }, { "content": " let mut issues: NewIssues = NewIssues::new();\n\n\n\n for record in records.decode::<Record>() {\n\n issues.push(NewIssue::from(record.unwrap()));\n\n }\n\n\n\n issues\n\n }\n\n}\n\n\n\n\n\n/// A partial representation of a Github Issue. The represented fields are the\n\n/// only ones transported to the final CSV/Json output. Might be interesting\n\n/// to add some more bits like the milestone.\n\n#[derive(Debug, RustcDecodable, RustcEncodable)]\n\npub struct Issue {\n\n pub assignee: Option<User>,\n\n // pub assignees: Vec<User>,\n\n pub body: Option<String>,\n\n pub created_at: Option<String>,\n", "file_path": "src/nerve/github/entities.rs", "rank": 50, "score": 22195.348357087725 }, { "content": " fn new() -> Self {\n\n NewIssues(Vec::new())\n\n }\n\n\n\n fn push(&mut self, elem: NewIssue) {\n\n self.0.push(elem);\n\n }\n\n}\n\n\n\nimpl IntoIterator for NewIssues {\n\n type Item = NewIssue;\n\n type IntoIter = ::std::vec::IntoIter<NewIssue>;\n\n\n\n fn into_iter(self) -> Self::IntoIter {\n\n self.0.into_iter()\n\n }\n\n}\n\n\n\nimpl <T: io::Read>From<csv::Reader<T>> for NewIssues {\n\n fn from(mut records: csv::Reader<T>) -> Self {\n", "file_path": "src/nerve/github/entities.rs", "rank": 52, "score": 22194.204218576302 }, { "content": "use std::str::FromStr;\n\n\n\npub enum OutputFormat {\n\n CSV,\n\n JSON,\n\n}\n\n\n\nimpl FromStr for OutputFormat {\n\n type Err = &'static str;\n\n\n\n fn from_str(value: &str) -> Result<Self, Self::Err> {\n\n match value {\n\n \"csv\" => Ok(OutputFormat::CSV),\n\n \"json\" => Ok(OutputFormat::JSON),\n\n _ => Err(\"Unexpected output format\")\n\n }\n\n }\n\n}\n\n\n\n\n\n// CSV lib does not cast Vec<String> so this is a workaround.\n", "file_path": "src/nerve/format.rs", "rank": 53, "score": 11.53151425842824 }, { "content": "//! Check command\n\n//!\n\n//! It checks if any records in a CSV already exist as issues in Github.\n\n\n\nuse csv;\n\n\n\nuse say;\n\nuse checker::filter_by_similar;\n\nuse github::entities::{Issues, NewIssues, issues_from_json};\n\nuse github::response::Page;\n\n\n", "file_path": "src/nerve/cmd/check.rs", "rank": 54, "score": 8.509315571769463 }, { "content": "#[macro_use] extern crate hyper;\n\n#[macro_use] extern crate log;\n\nextern crate ansi_term;\n\nextern crate csv;\n\nextern crate env_logger;\n\nextern crate regex;\n\nextern crate rustc_serialize;\n\nextern crate strsim;\n\n\n\n\n\npub mod cmd;\n\npub mod format;\n\npub mod checker;\n\npub mod github;\n\npub mod say;\n\npub mod validators;\n", "file_path": "src/nerve/lib.rs", "rank": 55, "score": 8.373255754144967 }, { "content": " },\n\n\n\n (\"completions\", Some(sub_matches)) => {\n\n let shell = sub_matches.value_of(\"SHELL\").unwrap();\n\n\n\n cli().gen_completions_to(\"github-issues\",\n\n shell.parse::<Shell>().unwrap(),\n\n &mut io::stdout());\n\n },\n\n\n\n // (_, _) => unimplemented!(), // for brevity\n\n (_, _) => {\n\n cli().print_help().unwrap();\n\n println!(\"\");\n\n },\n\n }\n\n}\n", "file_path": "src/main.rs", "rank": 56, "score": 7.351998598992016 }, { "content": "//! Upload command\n\n//!\n\n//! It uploads issues from a CSV.\n\nuse csv;\n\n\n\nuse say;\n\nuse github::issues;\n\nuse github::entities::{Issue, NewIssues};\n\n\n\n\n", "file_path": "src/nerve/cmd/upload.rs", "rank": 57, "score": 7.143390887940351 }, { "content": " issue.title.unwrap_or(\"missing title\".to_string()));\n\n }\n\n\n\n Err(e) => {\n\n println!(\"{} {} {} {} {}\", say::error(),\n\n \"Couldn't create an issue for\", new_issue.title,\n\n \"because\", e);\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/nerve/cmd/upload.rs", "rank": 58, "score": 6.015489353217537 }, { "content": "pub mod fetch;\n\npub mod template;\n\npub mod upload;\n\npub mod check;\n", "file_path": "src/nerve/cmd/mod.rs", "rank": 59, "score": 5.314529039995106 }, { "content": " },\n\n\n\n (\"upload-template\", Some(sub_matches)) => {\n\n cmd::template::run(sub_matches.value_of(\"output\"));\n\n },\n\n\n\n (\"upload\", Some(sub_matches)) => {\n\n let repopath = sub_matches.value_of(\"repopath\").unwrap().to_owned();\n\n let oauth_token = sub_matches.value_of(\"oauth-token\").unwrap().to_owned();\n\n let input_file = sub_matches.value_of(\"input\").unwrap().to_owned();\n\n\n\n if sub_matches.is_present(\"check\") {\n\n cmd::check::run(repopath,\n\n oauth_token,\n\n input_file);\n\n } else {\n\n cmd::upload::run(repopath,\n\n oauth_token,\n\n input_file);\n\n }\n", "file_path": "src/main.rs", "rank": 60, "score": 5.3141169738486305 }, { "content": " .arg(Arg::with_name(\"input\")\n\n .help(\"Read input from <file>\")\n\n .long(\"input\")\n\n .value_name(\"file\")\n\n .required(true))\n\n .arg(Arg::with_name(\"check\")\n\n .help(\"Check if any records in the provided CSV have potential collisions in existing Issues. This flag makes the command noop.\")\n\n .long(\"check\")))\n\n .subcommand(SubCommand::with_name(\"fetch\")\n\n .about(\"Fetch issues from Github.\")\n\n .arg(Arg::with_name(\"repopath\")\n\n .help(\"Repo path (e.g. ustwo/mastermind)\")\n\n .index(1)\n\n .validator(is_repopath)\n\n .required(true))\n\n .arg(Arg::with_name(\"oauth-token\")\n\n .help(\"Github OAuth authorisation token\")\n\n .long(\"oauth-token\")\n\n .value_name(\"oauth_token\")\n\n .required(true))\n", "file_path": "src/main.rs", "rank": 61, "score": 5.305655414119623 }, { "content": "//! This module implements string similarity keeping track of the id/number of\n\n//! the original Issue.\n\n\n\nuse strsim::jaro;\n\n\n", "file_path": "src/nerve/checker.rs", "rank": 62, "score": 4.08885301883702 }, { "content": " .possible_values(&[\"bash\", \"fish\", \"zsh\"])\n\n .help(\"The shell to generate the script for\")))\n\n .subcommand(SubCommand::with_name(\"upload-template\")\n\n .about(\"Generates a CSV example as an easy start for the upload command.\")\n\n .arg(Arg::with_name(\"output\")\n\n .help(\"Write output to <file>\")\n\n .long(\"output\")\n\n .value_name(\"file\")))\n\n .subcommand(SubCommand::with_name(\"upload\")\n\n .about(upload_about)\n\n .arg(Arg::with_name(\"repopath\")\n\n .help(\"Repo path (e.g. ustwo/mastermind)\")\n\n .index(1)\n\n .validator(is_repopath)\n\n .required(true))\n\n .arg(Arg::with_name(\"oauth-token\")\n\n .help(\"Github OAuth authorisation token\")\n\n .long(\"oauth-token\")\n\n .value_name(\"oauth_token\")\n\n .required(true))\n", "file_path": "src/main.rs", "rank": 63, "score": 3.1719533505146997 }, { "content": " #[test]\n\n fn string_with_spaces() {\n\n let expected: Vec<String> = vec![];\n\n assert_eq!(split(\" \".to_string()), expected);\n\n }\n\n\n\n #[test]\n\n fn string_with_one_item() {\n\n let expected: Vec<String> = vec![String::from(\"one\")];\n\n assert_eq!(split(\"one\".to_string()), expected);\n\n }\n\n\n\n #[test]\n\n fn string_with_multiple_item() {\n\n let expected: Vec<String> = vec![ String::from(\"one\")\n\n , String::from(\"two\")\n\n , String::from(\"three\") ];\n\n assert_eq!(split(\"one,two, three\".to_string()), expected);\n\n }\n\n\n\n}\n", "file_path": "src/nerve/format.rs", "rank": 64, "score": 2.9781998569731263 }, { "content": "#[macro_use] extern crate clap;\n\n#[macro_use] extern crate log;\n\nextern crate env_logger;\n\n\n\nextern crate nerve;\n\n\n\nuse std::io;\n\nuse clap::{Arg, App, SubCommand, Shell};\n\n\n\n\n\nuse nerve::cmd;\n\nuse nerve::format::{OutputFormat};\n\nuse nerve::validators::{is_repopath};\n\n\n", "file_path": "src/main.rs", "rank": 65, "score": 2.8256565401204767 }, { "content": "//! Upload template command\n\n//!\n\n//! It returns a dummy CSV\n\n\n\nuse std::fs::File;\n\nuse std::io::prelude::*;\n\n\n\n\n", "file_path": "src/nerve/cmd/template.rs", "rank": 66, "score": 2.5414566275487123 }, { "content": "\n\n assert!(similar_to_any(actual, &expected, 0.6).iter()\n\n .any(|&(_, x)| x.is_err()));\n\n }\n\n\n\n #[test]\n\n fn similar_to_all() {\n\n let expected = vec![(1, \"iOS Secret Keeping\".to_string())];\n\n assert_eq!(filter_by_similar(\"RFC: iOS Secret Keeping\", &expected, 0.6),\n\n vec![(1, \"iOS Secret Keeping\".to_string())]);\n\n }\n\n\n\n #[test]\n\n fn similar_to_some() {\n\n let expected = vec![ (1, \"iOS Secret Keeping\".to_string())\n\n , (2, \"Developer certificate of origin\".to_string())\n\n ];\n\n assert_eq!(filter_by_similar(\"RFC: iOS Secret Keeping\", &expected, 0.6),\n\n vec![(1, \"iOS Secret Keeping\".to_string())]);\n\n }\n\n\n\n}\n", "file_path": "src/nerve/checker.rs", "rank": 67, "score": 2.438954220249145 }, { "content": " fn similar_test() {\n\n assert!(similar(\"RFC: iOS Secret Keeping\", \"iOS Secret Keeping\", 0.6).is_ok());\n\n assert!(similar(\"RFC: iOS Secret Keeping\", \"Developer certificate of origin\", 0.6).is_err());\n\n }\n\n\n\n #[test]\n\n fn similar_to_all_test() {\n\n let expected = vec![(1, \"iOS Secret Keeping\".to_string())];\n\n let actual = \"RFC: iOS Secret Keeping\";\n\n\n\n assert!(similar_to_any(actual, &expected, 0.6).iter()\n\n .all(|&(_, x)| x.is_ok()));\n\n }\n\n\n\n #[test]\n\n fn is_different_to_some_test() {\n\n let expected = vec![ (1, \"iOS Secret Keeping\".to_string())\n\n , (2, \"Developer certificate of origin\".to_string())\n\n ];\n\n let actual = \"RFC: iOS Secret Keeping\";\n", "file_path": "src/nerve/checker.rs", "rank": 68, "score": 1.9777353921325334 }, { "content": " .arg(Arg::with_name(\"format\")\n\n .help(\"Output format\")\n\n .long(\"format\")\n\n .value_name(\"format\")\n\n .possible_values(&[\"csv\", \"json\"])\n\n .required(true))\n\n .arg(Arg::with_name(\"output\")\n\n .help(\"Write output to <file>\")\n\n .long(\"output\")\n\n .value_name(\"file\")\n\n .required(true))\n\n .arg(Arg::with_name(\"state\")\n\n .help(\"Issue state. Defaults to \\\"all\\\"\")\n\n .long(\"state\")\n\n .value_name(\"state\")\n\n .possible_values(&[\"all\", \"open\", \"closed\"]))\n\n .arg(Arg::with_name(\"label\")\n\n .help(\"Github label to filter with\")\n\n .long(\"label\")\n\n .value_name(\"label\")\n\n .multiple(true)))\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 69, "score": 1.0158327185895906 } ]
Rust
src/tools/clippy/clippy_lints/src/size_of_in_element_count.rs
ohno418/rust
395a09c3dafe0c7838c9ca41d2b47bb5e79a5b6d
use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_hir::BinOpKind; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, Ty, TypeAndMut}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::sym; declare_clippy_lint! { #[clippy::version = "1.50.0"] pub SIZE_OF_IN_ELEMENT_COUNT, correctness, "using `size_of::<T>` or `size_of_val::<T>` where a count of elements of `T` is expected" } declare_lint_pass!(SizeOfInElementCount => [SIZE_OF_IN_ELEMENT_COUNT]); fn get_size_of_ty<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, inverted: bool) -> Option<Ty<'tcx>> { match expr.kind { ExprKind::Call(count_func, _func_args) => { if_chain! { if !inverted; if let ExprKind::Path(ref count_func_qpath) = count_func.kind; if let Some(def_id) = cx.qpath_res(count_func_qpath, count_func.hir_id).opt_def_id(); if matches!(cx.tcx.get_diagnostic_name(def_id), Some(sym::mem_size_of | sym::mem_size_of_val)); then { cx.typeck_results().node_substs(count_func.hir_id).types().next() } else { None } } }, ExprKind::Binary(op, left, right) if BinOpKind::Mul == op.node => { get_size_of_ty(cx, left, inverted).or_else(|| get_size_of_ty(cx, right, inverted)) }, ExprKind::Binary(op, left, right) if BinOpKind::Div == op.node => { get_size_of_ty(cx, left, inverted).or_else(|| get_size_of_ty(cx, right, !inverted)) }, ExprKind::Cast(expr, _) => get_size_of_ty(cx, expr, inverted), _ => None, } } fn get_pointee_ty_and_count_expr<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ) -> Option<(Ty<'tcx>, &'tcx Expr<'tcx>)> { const FUNCTIONS: [&[&str]; 8] = [ &paths::PTR_COPY_NONOVERLAPPING, &paths::PTR_COPY, &paths::PTR_WRITE_BYTES, &paths::PTR_SWAP_NONOVERLAPPING, &paths::PTR_SLICE_FROM_RAW_PARTS, &paths::PTR_SLICE_FROM_RAW_PARTS_MUT, &paths::SLICE_FROM_RAW_PARTS, &paths::SLICE_FROM_RAW_PARTS_MUT, ]; const METHODS: [&str; 11] = [ "write_bytes", "copy_to", "copy_from", "copy_to_nonoverlapping", "copy_from_nonoverlapping", "add", "wrapping_add", "sub", "wrapping_sub", "offset", "wrapping_offset", ]; if_chain! { if let ExprKind::Call(func, [.., count]) = expr.kind; if let ExprKind::Path(ref func_qpath) = func.kind; if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id(); if FUNCTIONS.iter().any(|func_path| match_def_path(cx, def_id, func_path)); if let Some(pointee_ty) = cx.typeck_results().node_substs(func.hir_id).types().next(); then { return Some((pointee_ty, count)); } }; if_chain! { if let ExprKind::MethodCall(method_path, [ptr_self, .., count], _) = expr.kind; let method_ident = method_path.ident.as_str(); if METHODS.iter().any(|m| *m == &*method_ident); if let ty::RawPtr(TypeAndMut { ty: pointee_ty, .. }) = cx.typeck_results().expr_ty(ptr_self).kind(); then { return Some((*pointee_ty, count)); } }; None } impl<'tcx> LateLintPass<'tcx> for SizeOfInElementCount { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { const HELP_MSG: &str = "use a count of elements instead of a count of bytes\ , it already gets multiplied by the size of the type"; const LINT_MSG: &str = "found a count of bytes \ instead of a count of elements of `T`"; if_chain! { if let Some((pointee_ty, count_expr)) = get_pointee_ty_and_count_expr(cx, expr); if let Some(ty_used_for_size_of) = get_size_of_ty(cx, count_expr, false); if pointee_ty == ty_used_for_size_of; then { span_lint_and_help( cx, SIZE_OF_IN_ELEMENT_COUNT, count_expr.span, LINT_MSG, None, HELP_MSG ); } }; } }
use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_hir::BinOpKind; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, Ty, TypeAndMut}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::sym; declare_clippy_lint! { #[clippy::version = "1.50.0"] pub SIZE_OF_IN_ELEMENT_COUNT, correctness, "using `size_of::<T>` or `size_of_val::<T>` where a count of elements of `T` is expected" } declare_lint_pass!(SizeOfInElementCount => [SIZE_OF_IN_ELEMENT_COUNT]); fn get_size_of_ty<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, inverted: bool) -> Option<Ty<'tcx>> { match expr.kind { ExprKind::Call(count_func, _func_args) => { if_chain! { if !inverted; if let ExprKind::Path(ref count_func_qpath) = count_func.kind; if let Some(def_id) = cx.qpath_res(count_func_qpath, count_func.hir_id).opt_def_id(); if matches!(cx.tcx.get_diagnostic_name(def_id), Some(sym::mem_size_of | sym::mem_size_of_val)); then { cx.typeck_results().node_substs(count_func.hir_id).types().next() } else { None } } }, ExprKind::Binary(op, left, right) if BinOpKind::Mul == op.node => { get_size_of_ty(cx, left, inverted).or_else(|| get_size_of_ty(cx, right, inverted)) }, ExprKind::Binary(op, left, right) if BinOpKind::Div == op.node => { get_size_of_ty(cx, left, inverted).or_else(|| get_size_of_ty(cx, right, !inverted)) }, ExprKind::Cast(expr, _) => get_size_of_ty(cx, expr, inverted), _ => None, } }
impl<'tcx> LateLintPass<'tcx> for SizeOfInElementCount { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { const HELP_MSG: &str = "use a count of elements instead of a count of bytes\ , it already gets multiplied by the size of the type"; const LINT_MSG: &str = "found a count of bytes \ instead of a count of elements of `T`"; if_chain! { if let Some((pointee_ty, count_expr)) = get_pointee_ty_and_count_expr(cx, expr); if let Some(ty_used_for_size_of) = get_size_of_ty(cx, count_expr, false); if pointee_ty == ty_used_for_size_of; then { span_lint_and_help( cx, SIZE_OF_IN_ELEMENT_COUNT, count_expr.span, LINT_MSG, None, HELP_MSG ); } }; } }
fn get_pointee_ty_and_count_expr<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ) -> Option<(Ty<'tcx>, &'tcx Expr<'tcx>)> { const FUNCTIONS: [&[&str]; 8] = [ &paths::PTR_COPY_NONOVERLAPPING, &paths::PTR_COPY, &paths::PTR_WRITE_BYTES, &paths::PTR_SWAP_NONOVERLAPPING, &paths::PTR_SLICE_FROM_RAW_PARTS, &paths::PTR_SLICE_FROM_RAW_PARTS_MUT, &paths::SLICE_FROM_RAW_PARTS, &paths::SLICE_FROM_RAW_PARTS_MUT, ]; const METHODS: [&str; 11] = [ "write_bytes", "copy_to", "copy_from", "copy_to_nonoverlapping", "copy_from_nonoverlapping", "add", "wrapping_add", "sub", "wrapping_sub", "offset", "wrapping_offset", ]; if_chain! { if let ExprKind::Call(func, [.., count]) = expr.kind; if let ExprKind::Path(ref func_qpath) = func.kind; if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id(); if FUNCTIONS.iter().any(|func_path| match_def_path(cx, def_id, func_path)); if let Some(pointee_ty) = cx.typeck_results().node_substs(func.hir_id).types().next(); then { return Some((pointee_ty, count)); } }; if_chain! { if let ExprKind::MethodCall(method_path, [ptr_self, .., count], _) = expr.kind; let method_ident = method_path.ident.as_str(); if METHODS.iter().any(|m| *m == &*method_ident); if let ty::RawPtr(TypeAndMut { ty: pointee_ty, .. }) = cx.typeck_results().expr_ty(ptr_self).kind(); then { return Some((*pointee_ty, count)); } }; None }
function_block-full_function
[]
Rust
tarpc/examples/pubsub.rs
tikue/tarpc
90bc7f741d8fc837ac436a5ac39cca13245fe558
use anyhow::anyhow; use futures::{ channel::oneshot, future::{self, AbortHandle}, prelude::*, }; use log::info; use publisher::Publisher as _; use std::{ collections::HashMap, io, net::SocketAddr, sync::{Arc, Mutex, RwLock}, }; use subscriber::Subscriber as _; use tarpc::{ client, context, serde_transport::tcp, server::{self, Channel}, }; use tokio::net::ToSocketAddrs; use tokio_serde::formats::Json; pub mod subscriber { #[tarpc::service] pub trait Subscriber { async fn topics() -> Vec<String>; async fn receive(topic: String, message: String); } } pub mod publisher { #[tarpc::service] pub trait Publisher { async fn publish(topic: String, message: String); } } #[derive(Clone, Debug)] struct Subscriber { local_addr: SocketAddr, topics: Vec<String>, } #[tarpc::server] impl subscriber::Subscriber for Subscriber { async fn topics(self, _: context::Context) -> Vec<String> { self.topics.clone() } async fn receive(self, _: context::Context, topic: String, message: String) { info!( "[{}] received message on topic '{}': {}", self.local_addr, topic, message ); } } struct SubscriberHandle(AbortHandle); impl Drop for SubscriberHandle { fn drop(&mut self) { self.0.abort(); } } impl Subscriber { async fn connect( publisher_addr: impl ToSocketAddrs, topics: Vec<String>, ) -> anyhow::Result<SubscriberHandle> { let publisher = tcp::connect(publisher_addr, Json::default).await?; let local_addr = publisher.local_addr()?; let mut handler = server::BaseChannel::with_defaults(publisher).requests(); let subscriber = Subscriber { local_addr, topics }; match handler.next().await { Some(init_topics) => init_topics?.execute(subscriber.clone().serve()).await, None => { return Err(anyhow!( "[{}] Server never initialized the subscriber.", local_addr )) } }; let (handler, abort_handle) = future::abortable(handler.execute(subscriber.serve())); tokio::spawn(async move { match handler.await { Ok(()) | Err(future::Aborted) => info!("[{}] subscriber shutdown.", local_addr), } }); Ok(SubscriberHandle(abort_handle)) } } #[derive(Debug)] struct Subscription { subscriber: subscriber::SubscriberClient, topics: Vec<String>, } #[derive(Clone, Debug)] struct Publisher { clients: Arc<Mutex<HashMap<SocketAddr, Subscription>>>, subscriptions: Arc<RwLock<HashMap<String, HashMap<SocketAddr, subscriber::SubscriberClient>>>>, } struct PublisherAddrs { publisher: SocketAddr, subscriptions: SocketAddr, } impl Publisher { async fn start(self) -> io::Result<PublisherAddrs> { let mut connecting_publishers = tcp::listen("localhost:0", Json::default).await?; let publisher_addrs = PublisherAddrs { publisher: connecting_publishers.local_addr(), subscriptions: self.clone().start_subscription_manager().await?, }; info!("[{}] listening for publishers.", publisher_addrs.publisher); tokio::spawn(async move { let publisher = connecting_publishers.next().await.unwrap().unwrap(); info!("[{}] publisher connected.", publisher.peer_addr().unwrap()); server::BaseChannel::with_defaults(publisher) .execute(self.serve()) .await }); Ok(publisher_addrs) } async fn start_subscription_manager(mut self) -> io::Result<SocketAddr> { let mut connecting_subscribers = tcp::listen("localhost:0", Json::default) .await? .filter_map(|r| future::ready(r.ok())); let new_subscriber_addr = connecting_subscribers.get_ref().local_addr(); info!("[{}] listening for subscribers.", new_subscriber_addr); tokio::spawn(async move { while let Some(conn) = connecting_subscribers.next().await { let subscriber_addr = conn.peer_addr().unwrap(); let tarpc::client::NewClient { client: subscriber, dispatch, } = subscriber::SubscriberClient::new(client::Config::default(), conn); let (ready_tx, ready) = oneshot::channel(); self.clone() .start_subscriber_gc(subscriber_addr, dispatch, ready); self.initialize_subscription(subscriber_addr, subscriber) .await; ready_tx.send(()).unwrap(); } }); Ok(new_subscriber_addr) } async fn initialize_subscription( &mut self, subscriber_addr: SocketAddr, subscriber: subscriber::SubscriberClient, ) { if let Ok(topics) = subscriber.topics(context::current()).await { self.clients.lock().unwrap().insert( subscriber_addr, Subscription { subscriber: subscriber.clone(), topics: topics.clone(), }, ); info!("[{}] subscribed to topics: {:?}", subscriber_addr, topics); let mut subscriptions = self.subscriptions.write().unwrap(); for topic in topics { subscriptions .entry(topic) .or_insert_with(HashMap::new) .insert(subscriber_addr, subscriber.clone()); } } } fn start_subscriber_gc( self, subscriber_addr: SocketAddr, client_dispatch: impl Future<Output = anyhow::Result<()>> + Send + 'static, subscriber_ready: oneshot::Receiver<()>, ) { tokio::spawn(async move { if let Err(e) = client_dispatch.await { info!( "[{}] subscriber connection broken: {:?}", subscriber_addr, e ) } let _ = subscriber_ready.await; if let Some(subscription) = self.clients.lock().unwrap().remove(&subscriber_addr) { info!( "[{} unsubscribing from topics: {:?}", subscriber_addr, subscription.topics ); let mut subscriptions = self.subscriptions.write().unwrap(); for topic in subscription.topics { let subscribers = subscriptions.get_mut(&topic).unwrap(); subscribers.remove(&subscriber_addr); if subscribers.is_empty() { subscriptions.remove(&topic); } } } }); } } #[tarpc::server] impl publisher::Publisher for Publisher { async fn publish(self, _: context::Context, topic: String, message: String) { info!("received message to publish."); let mut subscribers = match self.subscriptions.read().unwrap().get(&topic) { None => return, Some(subscriptions) => subscriptions.clone(), }; let mut publications = Vec::new(); for client in subscribers.values_mut() { publications.push(client.receive(context::current(), topic.clone(), message.clone())); } for response in future::join_all(publications).await { if let Err(e) = response { info!("failed to broadcast to subscriber: {}", e); } } } } #[tokio::main] async fn main() -> anyhow::Result<()> { env_logger::init(); let clients = Arc::new(Mutex::new(HashMap::new())); let addrs = Publisher { clients, subscriptions: Arc::new(RwLock::new(HashMap::new())), } .start() .await?; let _subscriber0 = Subscriber::connect( addrs.subscriptions, vec!["calculus".into(), "cool shorts".into()], ) .await?; let _subscriber1 = Subscriber::connect( addrs.subscriptions, vec!["cool shorts".into(), "history".into()], ) .await?; let publisher = publisher::PublisherClient::new( client::Config::default(), tcp::connect(addrs.publisher, Json::default).await?, ) .spawn()?; publisher .publish(context::current(), "calculus".into(), "sqrt(2)".into()) .await?; publisher .publish( context::current(), "cool shorts".into(), "hello to all".into(), ) .await?; publisher .publish(context::current(), "history".into(), "napoleon".to_string()) .await?; drop(_subscriber0); publisher .publish( context::current(), "cool shorts".into(), "hello to who?".into(), ) .await?; info!("done."); Ok(()) }
use anyhow::anyhow; use futures::{ channel::oneshot, future::{self, AbortHandle}, prelude::*, }; use log::info; use publisher::Publisher as _; use std::{ collections::HashMap, io, net::SocketAddr, sync::{Arc, Mutex, RwLock}, }; use subscriber::Subscriber as _; use tarpc::{ client, context, serde_transport::tcp, server::{self, Channel}, }; use tokio::net::ToSocketAddrs; use tokio_serde::formats::Json; pub mod subscriber { #[tarpc::service] pub trait Subscriber { async fn topics() -> Vec<String>; async fn receive(topic: String, message: String); } } pub mod publisher { #[tarpc::service] pub trait Publisher { async fn publish(topic: String, message: String); } } #[derive(Clone, Debug)] struct Subscriber { local_addr: SocketAddr, topics: Vec<String>, } #[tarpc::server] impl subscriber::Subscriber for Subscriber { async fn topics(self, _: context::Context) -> Vec<String> { self.topics.clone() } async fn receive(self, _: context::Context, topic: String, message: String) { info!( "[{}] received message on topic '{}': {}", self.local_addr, topic, message ); } } struct SubscriberHandle(AbortHandle); impl Drop for SubscriberHandle { fn drop(&mut self) { self.0.abort(); } } impl Subscriber { async fn connect( publisher_addr: impl ToSocketAddrs, topics: Vec<String>, ) -> anyhow::Result<SubscriberHandle> { let publisher = tcp::connect(publisher_addr, Json::default).await?; let local_addr = publisher.local_addr()?; let mut handler = server::BaseChannel::with_defaults(publisher).requests(); let subscriber = Subscriber { local_addr, topics }; match handler.next().await { Some(init_topics) => init_topics?.execute(subscriber.clone().serve()).await, None => { return Err(anyhow!( "[{}] Server never initialized the subscriber.", local_addr )) } }; let (handler, abort_handle) = future::abortable(handler.execute(subscriber.serve())); tokio::spawn(async move { match handler.await { Ok(()) | Err(future::Aborted) => info!("[{}] subscriber shutdown.", local_addr), } }); Ok(SubscriberHandle(abort_handle)) } } #[derive(Debug)] struct Subscription { subscriber: subscriber::SubscriberClient, topics: Vec<String>, } #[derive(Clone, Debug)] struct Publisher { clients: Arc<Mutex<HashMap<SocketAddr, Subscription>>>, subscriptions: Arc<RwLock<HashMap<String, HashMap<SocketAddr, subscriber::SubscriberClient>>>>, } struct PublisherAddrs { publisher: SocketAddr, subscriptions: SocketAddr, } impl Publisher { async fn start(self) -> io::Result<PublisherAddrs> { let mut connecting_publishers = tcp::listen("localhost:0", Json::default).await?; let publisher_addrs = PublisherAddrs { publisher: connecting_publishers.local_addr(), subscriptions: self.clone().start_subscription_manager().await?, }; info!("[{}] listening for publishers.", publisher_addrs.publisher); tokio::spawn(async move { let publisher = connecting_publishers.next().await.unwrap().unwrap(); info!("[{}] publisher connected.", publisher.peer_addr().unwrap()); server::BaseChannel::with_defaults(publisher) .execute(self.serve()) .await }); Ok(publisher_addrs) } async fn start_subscription_manager(mut self) -> io::Result<SocketAddr> { let mut connecting_subscribers = tcp::listen("localhost:0", Json::default) .await? .filter_map(|r| future::ready(r.ok())); let new_subscriber_addr = connecting_subscribers.get_ref().local_addr(); info!("[{}] listening for subscribers.", new_subscriber_addr); tokio::spawn(async move { while let Some(conn) = connecting_subscribers.next().await { let subscriber_addr = conn.peer_addr().unwrap(); let tarpc::client::NewClient { client: subscriber, dispatch, } = subscriber::SubscriberClient::new(client::Config::default(), conn); let (ready_tx, ready) = oneshot::channel(); self.clone() .start_subscriber_gc(subscriber_addr, dispatch, ready); self.initialize_subscription(subscriber_addr, subscriber) .await; ready_tx.send(()).unwrap(); } }); Ok(new_subscriber_addr) } async fn initialize_subscription( &mut self, subscriber_addr: SocketAddr, subscriber: subscriber::SubscriberClient, ) {
} fn start_subscriber_gc( self, subscriber_addr: SocketAddr, client_dispatch: impl Future<Output = anyhow::Result<()>> + Send + 'static, subscriber_ready: oneshot::Receiver<()>, ) { tokio::spawn(async move { if let Err(e) = client_dispatch.await { info!( "[{}] subscriber connection broken: {:?}", subscriber_addr, e ) } let _ = subscriber_ready.await; if let Some(subscription) = self.clients.lock().unwrap().remove(&subscriber_addr) { info!( "[{} unsubscribing from topics: {:?}", subscriber_addr, subscription.topics ); let mut subscriptions = self.subscriptions.write().unwrap(); for topic in subscription.topics { let subscribers = subscriptions.get_mut(&topic).unwrap(); subscribers.remove(&subscriber_addr); if subscribers.is_empty() { subscriptions.remove(&topic); } } } }); } } #[tarpc::server] impl publisher::Publisher for Publisher { async fn publish(self, _: context::Context, topic: String, message: String) { info!("received message to publish."); let mut subscribers = match self.subscriptions.read().unwrap().get(&topic) { None => return, Some(subscriptions) => subscriptions.clone(), }; let mut publications = Vec::new(); for client in subscribers.values_mut() { publications.push(client.receive(context::current(), topic.clone(), message.clone())); } for response in future::join_all(publications).await { if let Err(e) = response { info!("failed to broadcast to subscriber: {}", e); } } } } #[tokio::main] async fn main() -> anyhow::Result<()> { env_logger::init(); let clients = Arc::new(Mutex::new(HashMap::new())); let addrs = Publisher { clients, subscriptions: Arc::new(RwLock::new(HashMap::new())), } .start() .await?; let _subscriber0 = Subscriber::connect( addrs.subscriptions, vec!["calculus".into(), "cool shorts".into()], ) .await?; let _subscriber1 = Subscriber::connect( addrs.subscriptions, vec!["cool shorts".into(), "history".into()], ) .await?; let publisher = publisher::PublisherClient::new( client::Config::default(), tcp::connect(addrs.publisher, Json::default).await?, ) .spawn()?; publisher .publish(context::current(), "calculus".into(), "sqrt(2)".into()) .await?; publisher .publish( context::current(), "cool shorts".into(), "hello to all".into(), ) .await?; publisher .publish(context::current(), "history".into(), "napoleon".to_string()) .await?; drop(_subscriber0); publisher .publish( context::current(), "cool shorts".into(), "hello to who?".into(), ) .await?; info!("done."); Ok(()) }
if let Ok(topics) = subscriber.topics(context::current()).await { self.clients.lock().unwrap().insert( subscriber_addr, Subscription { subscriber: subscriber.clone(), topics: topics.clone(), }, ); info!("[{}] subscribed to topics: {:?}", subscriber_addr, topics); let mut subscriptions = self.subscriptions.write().unwrap(); for topic in topics { subscriptions .entry(topic) .or_insert_with(HashMap::new) .insert(subscriber_addr, subscriber.clone()); } }
if_condition
[ { "content": "/// The server end of an open connection with a client, streaming in requests from, and sinking\n\n/// responses to, the client.\n\n///\n\n/// The ways to use a Channel, in order of simplest to most complex, is:\n\n/// 1. [`Channel::execute`] - Requires the `tokio1` feature. This method is best for those who\n\n/// do not have specific scheduling needs and whose services are `Send + 'static`.\n\n/// 2. [`Channel::requests`] - This method is best for those who need direct access to individual\n\n/// requests, or are not using `tokio`, or want control over [futures](Future) scheduling.\n\n/// [`Requests`] is a stream of [`InFlightRequests`](InFlightRequest), each which has an\n\n/// [`execute`](InFlightRequest::execute) method. If using `execute`, request processing will\n\n/// automatically cease when either the request deadline is reached or when a corresponding\n\n/// cancellation message is received by the Channel.\n\n/// 3. [`Sink::start_send`] - A user is free to manually send responses to requests produced by a\n\n/// Channel using [`Sink::start_send`] in lieu of the previous methods. If not using one of the\n\n/// previous execute methods, then nothing will automatically cancel requests or set up the\n\n/// request context. However, the Channel will still clean up resources upon deadline expiration\n\n/// or cancellation. In the case that the Channel cleans up resources related to a request\n\n/// before the response is sent, the response can still be sent into the Channel later on.\n\n/// Because there is no guarantee that a cancellation message will ever be received for a\n\n/// request, or that requests come with reasonably short deadlines, services should strive to\n\n/// clean up Channel resources by sending a response for every request.\n\npub trait Channel\n\nwhere\n\n Self: Transport<Response<<Self as Channel>::Resp>, Request<<Self as Channel>::Req>>,\n\n{\n\n /// Type of request item.\n\n type Req;\n\n\n\n /// Type of response sink item.\n\n type Resp;\n\n\n\n /// Configuration of the channel.\n\n fn config(&self) -> &Config;\n\n\n\n /// Returns the number of in-flight requests over this channel.\n\n fn in_flight_requests(&self) -> usize;\n\n\n\n /// Caps the number of concurrent requests to `limit`.\n\n fn max_concurrent_requests(self, limit: usize) -> Throttler<Self>\n\n where\n\n Self: Sized,\n", "file_path": "tarpc/src/server.rs", "rank": 0, "score": 227995.58616703883 }, { "content": "pub fn cx() -> Context<'static> {\n\n Context::from_waker(&noop_waker_ref())\n\n}\n", "file_path": "tarpc/src/server/testing.rs", "rank": 1, "score": 198143.09463720248 }, { "content": "/// Returns the context for the current request, or a default Context if no request is active.\n\npub fn current() -> Context {\n\n Context::current()\n\n}\n\n\n\nimpl Context {\n\n /// Returns a Context containing a new root trace context and a default deadline.\n\n pub fn new_root() -> Self {\n\n Self {\n\n deadline: ten_seconds_from_now(),\n\n trace_context: trace::Context::new_root(),\n\n }\n\n }\n\n\n\n /// Returns the context for the current request, or a default Context if no request is active.\n\n pub fn current() -> Self {\n\n CURRENT_CONTEXT\n\n .try_with(Self::clone)\n\n .unwrap_or_else(|_| Self::new_root())\n\n }\n\n\n", "file_path": "tarpc/src/context.rs", "rank": 2, "score": 193343.6834943873 }, { "content": "fn convert_send_err_to_io(e: futures::channel::mpsc::SendError) -> io::Error {\n\n if e.is_disconnected() {\n\n io::Error::from(io::ErrorKind::NotConnected)\n\n } else if e.is_full() {\n\n io::Error::from(io::ErrorKind::WouldBlock)\n\n } else {\n\n io::Error::new(io::ErrorKind::Other, e)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(feature = \"tokio1\")]\n\nmod tests {\n\n use crate::{\n\n client, context,\n\n server::{BaseChannel, Incoming},\n\n transport,\n\n };\n\n use assert_matches::assert_matches;\n\n use futures::{prelude::*, stream};\n", "file_path": "tarpc/src/transport/channel.rs", "rank": 3, "score": 179876.44112979106 }, { "content": " #[tarpc::service]\n\n pub trait Add {\n\n /// Add two ints together.\n\n async fn add(x: i32, y: i32) -> i32;\n\n }\n\n}\n\n\n\npub mod double {\n", "file_path": "tarpc/examples/server_calling_server.rs", "rank": 6, "score": 169597.38987925093 }, { "content": " #[tarpc::service]\n\n pub trait Double {\n\n /// 2 * x\n\n async fn double(x: i32) -> Result<i32, String>;\n\n }\n\n}\n\n\n", "file_path": "tarpc/examples/server_calling_server.rs", "rank": 7, "score": 169597.38987925093 }, { "content": "#[test]\n\nfn channel_filter_poll_listener() {\n\n use assert_matches::assert_matches;\n\n use pin_utils::pin_mut;\n\n\n\n #[derive(Debug)]\n\n struct TestChannel {\n\n key: &'static str,\n\n }\n\n let (new_channels, listener) = futures::channel::mpsc::unbounded();\n\n let filter = ChannelFilter::new(listener, 2, |chan: &TestChannel| chan.key);\n\n pin_mut!(filter);\n\n\n\n new_channels\n\n .unbounded_send(TestChannel { key: \"key\" })\n\n .unwrap();\n\n let channel1 =\n\n assert_matches!(filter.as_mut().poll_listener(&mut ctx()), Poll::Ready(Some(Ok(c))) => c);\n\n assert_eq!(Arc::strong_count(&channel1.tracker), 1);\n\n\n\n new_channels\n", "file_path": "tarpc/src/server/filter.rs", "rank": 8, "score": 163445.76129461548 }, { "content": "pub trait PollExt {\n\n fn is_done(&self) -> bool;\n\n}\n\n\n\nimpl<T> PollExt for Poll<Option<T>> {\n\n fn is_done(&self) -> bool {\n\n matches!(self, Poll::Ready(None))\n\n }\n\n}\n\n\n", "file_path": "tarpc/src/server/testing.rs", "rank": 9, "score": 160463.5769376198 }, { "content": "/// Equivalent to a `FnOnce(Req) -> impl Future<Output = Resp>`.\n\npub trait Serve<Req> {\n\n /// Type of response.\n\n type Resp;\n\n\n\n /// Type of response future.\n\n type Fut: Future<Output = Self::Resp>;\n\n\n\n /// Responds to a single request.\n\n fn serve(self, ctx: context::Context, req: Req) -> Self::Fut;\n\n}\n\n\n\nimpl<Req, Resp, Fut, F> Serve<Req> for F\n\nwhere\n\n F: FnOnce(context::Context, Req) -> Fut,\n\n Fut: Future<Output = Resp>,\n\n{\n\n type Resp = Resp;\n\n type Fut = Fut;\n\n\n\n fn serve(self, ctx: context::Context, req: Req) -> Self::Fut {\n\n self(ctx, req)\n\n }\n\n}\n\n\n", "file_path": "tarpc/src/server.rs", "rank": 10, "score": 160451.39417740947 }, { "content": "/// An extension trait for [streams](Stream) of [`Channels`](Channel).\n\npub trait Incoming<C>\n\nwhere\n\n Self: Sized + Stream<Item = C>,\n\n C: Channel,\n\n{\n\n /// Enforces channel per-key limits.\n\n fn max_channels_per_key<K, KF>(self, n: u32, keymaker: KF) -> filter::ChannelFilter<Self, K, KF>\n\n where\n\n K: fmt::Display + Eq + Hash + Clone + Unpin,\n\n KF: Fn(&C) -> K,\n\n {\n\n ChannelFilter::new(self, n, keymaker)\n\n }\n\n\n\n /// Caps the number of concurrent requests per channel.\n\n fn max_concurrent_requests_per_channel(self, n: usize) -> ThrottlerStream<Self> {\n\n ThrottlerStream::new(self, n)\n\n }\n\n\n\n /// [Executes](Channel::execute) each incoming channel. Each channel will be handled\n", "file_path": "tarpc/src/server.rs", "rank": 11, "score": 160448.01947194108 }, { "content": "#[cfg(test)]\n\nfn ctx() -> Context<'static> {\n\n use futures::task::*;\n\n\n\n Context::from_waker(&noop_waker_ref())\n\n}\n\n\n", "file_path": "tarpc/src/server/filter.rs", "rank": 12, "score": 155863.15742530633 }, { "content": "/// Returns a channel and dispatcher that manages the lifecycle of requests initiated by the\n\n/// channel.\n\npub fn new<Req, Resp, C>(\n\n config: Config,\n\n transport: C,\n\n) -> NewClient<Channel<Req, Resp>, RequestDispatch<Req, Resp, C>>\n\nwhere\n\n C: Transport<ClientMessage<Req>, Response<Resp>>,\n\n{\n\n let (to_dispatch, pending_requests) = mpsc::channel(config.pending_request_buffer);\n\n let (cancellation, canceled_requests) = cancellations();\n\n let canceled_requests = canceled_requests;\n\n\n\n NewClient {\n\n client: Channel {\n\n to_dispatch,\n\n cancellation,\n\n next_request_id: Arc::new(AtomicUsize::new(0)),\n\n },\n\n dispatch: RequestDispatch {\n\n config,\n\n canceled_requests,\n", "file_path": "tarpc/src/client.rs", "rank": 13, "score": 145770.3718576871 }, { "content": "struct HelloServer;\n\n\n\n#[tarpc::server]\n\nimpl World for HelloServer {\n\n fn hello(name: String) -> String {\n\n format!(\"Hello, {}!\", name)\n\n }\n\n}\n\n\n", "file_path": "tarpc/tests/compile_fail/tarpc_server_missing_async.rs", "rank": 14, "score": 145687.2557887809 }, { "content": "/// Returns two unbounded channel peers. Each [`Stream`] yields items sent through the other's\n\n/// [`Sink`].\n\npub fn unbounded<SinkItem, Item>() -> (\n\n UnboundedChannel<SinkItem, Item>,\n\n UnboundedChannel<Item, SinkItem>,\n\n) {\n\n let (tx1, rx2) = mpsc::unbounded_channel();\n\n let (tx2, rx1) = mpsc::unbounded_channel();\n\n (\n\n UnboundedChannel { tx: tx1, rx: rx1 },\n\n UnboundedChannel { tx: tx2, rx: rx2 },\n\n )\n\n}\n\n\n\n/// A bi-directional channel backed by an [`UnboundedSender`](mpsc::UnboundedSender)\n\n/// and [`UnboundedReceiver`](mpsc::UnboundedReceiver).\n\n#[derive(Debug)]\n\npub struct UnboundedChannel<Item, SinkItem> {\n\n rx: mpsc::UnboundedReceiver<Item>,\n\n tx: mpsc::UnboundedSender<SinkItem>,\n\n}\n\n\n", "file_path": "tarpc/src/transport/channel.rs", "rank": 15, "score": 145429.43543227483 }, { "content": "/// Returns two channel peers with buffer equal to `capacity`. Each [`Stream`] yields items sent\n\n/// through the other's [`Sink`].\n\npub fn bounded<SinkItem, Item>(\n\n capacity: usize,\n\n) -> (Channel<SinkItem, Item>, Channel<Item, SinkItem>) {\n\n let (tx1, rx2) = futures::channel::mpsc::channel(capacity);\n\n let (tx2, rx1) = futures::channel::mpsc::channel(capacity);\n\n (Channel { tx: tx1, rx: rx1 }, Channel { tx: tx2, rx: rx2 })\n\n}\n\n\n\n/// A bi-directional channel backed by a [`Sender`](futures::channel::mpsc::Sender)\n\n/// and [`Receiver`](futures::channel::mpsc::Receiver).\n\n#[pin_project]\n\n#[derive(Debug)]\n\npub struct Channel<Item, SinkItem> {\n\n #[pin]\n\n rx: futures::channel::mpsc::Receiver<Item>,\n\n #[pin]\n\n tx: futures::channel::mpsc::Sender<SinkItem>,\n\n}\n\n\n\nimpl<Item, SinkItem> Stream for Channel<Item, SinkItem> {\n", "file_path": "tarpc/src/transport/channel.rs", "rank": 16, "score": 145429.25574010925 }, { "content": "#[derive(Clone)]\n\nstruct Server;\n\n\n\nimpl Service for Server {\n\n type AddFut = Ready<i32>;\n\n\n\n fn add(self, _: context::Context, x: i32, y: i32) -> Self::AddFut {\n\n ready(x + y)\n\n }\n\n\n\n type HeyFut = Ready<String>;\n\n\n\n fn hey(self, _: context::Context, name: String) -> Self::HeyFut {\n\n ready(format!(\"Hey, {}.\", name))\n\n }\n\n}\n\n\n\n#[tokio::test]\n\nasync fn sequential() -> io::Result<()> {\n\n let _ = env_logger::try_init();\n\n\n", "file_path": "tarpc/tests/service_functional.rs", "rank": 17, "score": 143411.44077834906 }, { "content": "#[derive(Debug)]\n\nstruct DispatchResponse<Resp> {\n\n response: oneshot::Receiver<Response<Resp>>,\n\n ctx: context::Context,\n\n cancellation: Option<RequestCancellation>,\n\n request_id: u64,\n\n}\n\n\n\nimpl<Resp> Future for DispatchResponse<Resp> {\n\n type Output = io::Result<Resp>;\n\n\n\n fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<Resp>> {\n\n let resp = ready!(self.response.poll_unpin(cx));\n\n self.cancellation.take();\n\n Poll::Ready(match resp {\n\n Ok(resp) => Ok(resp.message?),\n\n Err(oneshot::error::RecvError { .. }) => {\n\n // The oneshot is Canceled when the dispatch task ends. In that case,\n\n // there's nothing listening on the other side, so there's no point in\n\n // propagating cancellation.\n\n Err(io::Error::from(io::ErrorKind::ConnectionReset))\n", "file_path": "tarpc/src/client.rs", "rank": 18, "score": 143241.55532363948 }, { "content": "#[allow(clippy::trivially_copy_pass_by_ref)] // Exact fn signature required by serde derive\n\npub fn serialize_io_error_kind_as_u32<S>(\n\n kind: &io::ErrorKind,\n\n serializer: S,\n\n) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n use std::io::ErrorKind::*;\n\n match *kind {\n\n NotFound => 0,\n\n PermissionDenied => 1,\n\n ConnectionRefused => 2,\n\n ConnectionReset => 3,\n\n ConnectionAborted => 4,\n\n NotConnected => 5,\n\n AddrInUse => 6,\n\n AddrNotAvailable => 7,\n\n BrokenPipe => 8,\n\n AlreadyExists => 9,\n\n WouldBlock => 10,\n", "file_path": "tarpc/src/util/serde.rs", "rank": 19, "score": 142286.8886779323 }, { "content": "#[test]\n\nfn tracker_drop() {\n\n use assert_matches::assert_matches;\n\n\n\n let (tx, mut rx) = mpsc::unbounded_channel();\n\n Tracker {\n\n key: Some(1),\n\n dropped_keys: tx,\n\n };\n\n assert_matches!(rx.poll_recv(&mut ctx()), Poll::Ready(Some(1)));\n\n}\n\n\n", "file_path": "tarpc/src/server/filter.rs", "rank": 20, "score": 141710.01048787593 }, { "content": "#[test]\n\nfn channel_filter_increment_channels_for_key() {\n\n use assert_matches::assert_matches;\n\n use pin_utils::pin_mut;\n\n\n\n struct TestChannel {\n\n key: &'static str,\n\n }\n\n let (_, listener) = futures::channel::mpsc::unbounded();\n\n let filter = ChannelFilter::new(listener, 2, |chan: &TestChannel| chan.key);\n\n pin_mut!(filter);\n\n let tracker1 = filter.as_mut().increment_channels_for_key(\"key\").unwrap();\n\n assert_eq!(Arc::strong_count(&tracker1), 1);\n\n let tracker2 = filter.as_mut().increment_channels_for_key(\"key\").unwrap();\n\n assert_eq!(Arc::strong_count(&tracker1), 2);\n\n assert_matches!(filter.increment_channels_for_key(\"key\"), Err(\"key\"));\n\n drop(tracker2);\n\n assert_eq!(Arc::strong_count(&tracker1), 1);\n\n}\n\n\n", "file_path": "tarpc/src/server/filter.rs", "rank": 21, "score": 139707.44994533772 }, { "content": "#[test]\n\nfn channel_filter_handle_new_channel() {\n\n use assert_matches::assert_matches;\n\n use pin_utils::pin_mut;\n\n\n\n #[derive(Debug)]\n\n struct TestChannel {\n\n key: &'static str,\n\n }\n\n let (_, listener) = futures::channel::mpsc::unbounded();\n\n let filter = ChannelFilter::new(listener, 2, |chan: &TestChannel| chan.key);\n\n pin_mut!(filter);\n\n let channel1 = filter\n\n .as_mut()\n\n .handle_new_channel(TestChannel { key: \"key\" })\n\n .unwrap();\n\n assert_eq!(Arc::strong_count(&channel1.tracker), 1);\n\n\n\n let channel2 = filter\n\n .as_mut()\n\n .handle_new_channel(TestChannel { key: \"key\" })\n", "file_path": "tarpc/src/server/filter.rs", "rank": 22, "score": 139707.44994533772 }, { "content": "#[test]\n\nfn channel_filter_poll_closed_channels() {\n\n use assert_matches::assert_matches;\n\n use pin_utils::pin_mut;\n\n\n\n #[derive(Debug)]\n\n struct TestChannel {\n\n key: &'static str,\n\n }\n\n let (new_channels, listener) = futures::channel::mpsc::unbounded();\n\n let filter = ChannelFilter::new(listener, 2, |chan: &TestChannel| chan.key);\n\n pin_mut!(filter);\n\n\n\n new_channels\n\n .unbounded_send(TestChannel { key: \"key\" })\n\n .unwrap();\n\n let channel =\n\n assert_matches!(filter.as_mut().poll_listener(&mut ctx()), Poll::Ready(Some(Ok(c))) => c);\n\n assert_eq!(filter.key_counts.len(), 1);\n\n\n\n drop(channel);\n\n assert_matches!(\n\n filter.as_mut().poll_closed_channels(&mut ctx()),\n\n Poll::Ready(())\n\n );\n\n assert!(filter.key_counts.is_empty());\n\n}\n\n\n", "file_path": "tarpc/src/server/filter.rs", "rank": 23, "score": 139707.44994533772 }, { "content": "#[tarpc::service(derive_serde = false)]\n\ntrait World {\n\n async fn hello(name: String) -> String;\n\n}\n\n\n", "file_path": "tarpc/tests/compile_fail/tarpc_server_missing_async.rs", "rank": 24, "score": 139103.1128866477 }, { "content": "/// Extension trait for [SystemTimes](SystemTime) in the future, i.e. deadlines.\n\npub trait TimeUntil {\n\n /// How much time from now until this time is reached.\n\n fn time_until(&self) -> Duration;\n\n}\n\n\n\nimpl TimeUntil for SystemTime {\n\n fn time_until(&self) -> Duration {\n\n self.duration_since(SystemTime::now()).unwrap_or_default()\n\n }\n\n}\n\n\n", "file_path": "tarpc/src/util.rs", "rank": 25, "score": 138050.07948095835 }, { "content": "#[tarpc::service]\n\npub trait World {\n\n async fn hello(name: String) -> String;\n\n}\n\n\n", "file_path": "tarpc/examples/compression.rs", "rank": 26, "score": 138046.3415581197 }, { "content": "#[tarpc::service]\n\npub trait World {\n\n async fn hello(name: String) -> String;\n\n}\n\n\n\n/// This is the type that implements the generated World trait. It is the business logic\n\n/// and is used to start the server.\n", "file_path": "tarpc/examples/readme.rs", "rank": 27, "score": 138046.3415581197 }, { "content": "/// Collection compaction; configurable `shrink_to_fit`.\n\npub trait Compact {\n\n /// Compacts space if the ratio of length : capacity is less than `usage_ratio_threshold`.\n\n fn compact(&mut self, usage_ratio_threshold: f64);\n\n}\n\n\n\nimpl<K, V, H> Compact for HashMap<K, V, H>\n\nwhere\n\n K: Eq + Hash,\n\n H: BuildHasher,\n\n{\n\n fn compact(&mut self, usage_ratio_threshold: f64) {\n\n if self.capacity() > 1000 {\n\n let usage_ratio = self.len() as f64 / self.capacity() as f64;\n\n if usage_ratio < usage_ratio_threshold {\n\n self.shrink_to_fit();\n\n }\n\n }\n\n }\n\n}\n", "file_path": "tarpc/src/util.rs", "rank": 28, "score": 138042.0810574889 }, { "content": "#[test]\n\nfn tracked_channel_stream() {\n\n use assert_matches::assert_matches;\n\n use pin_utils::pin_mut;\n\n\n\n let (chan_tx, chan) = futures::channel::mpsc::unbounded();\n\n let (dropped_keys, _) = mpsc::unbounded_channel();\n\n let channel = TrackedChannel {\n\n inner: chan,\n\n tracker: Arc::new(Tracker {\n\n key: Some(1),\n\n dropped_keys,\n\n }),\n\n };\n\n\n\n chan_tx.unbounded_send(\"test\").unwrap();\n\n pin_mut!(channel);\n\n assert_matches!(channel.poll_next(&mut ctx()), Poll::Ready(Some(\"test\")));\n\n}\n\n\n", "file_path": "tarpc/src/server/filter.rs", "rank": 29, "score": 137267.0618073314 }, { "content": "#[test]\n\nfn tracked_channel_sink() {\n\n use assert_matches::assert_matches;\n\n use pin_utils::pin_mut;\n\n\n\n let (chan, mut chan_rx) = futures::channel::mpsc::unbounded();\n\n let (dropped_keys, _) = mpsc::unbounded_channel();\n\n let channel = TrackedChannel {\n\n inner: chan,\n\n tracker: Arc::new(Tracker {\n\n key: Some(1),\n\n dropped_keys,\n\n }),\n\n };\n\n\n\n pin_mut!(channel);\n\n assert_matches!(channel.as_mut().poll_ready(&mut ctx()), Poll::Ready(Ok(())));\n\n assert_matches!(channel.as_mut().start_send(\"test\"), Ok(()));\n\n assert_matches!(channel.as_mut().poll_flush(&mut ctx()), Poll::Ready(Ok(())));\n\n assert_matches!(chan_rx.try_next(), Ok(Some(\"test\")));\n\n}\n\n\n", "file_path": "tarpc/src/server/filter.rs", "rank": 30, "score": 137267.0618073314 }, { "content": "#[test]\n\nfn channel_filter_stream() {\n\n use assert_matches::assert_matches;\n\n use pin_utils::pin_mut;\n\n\n\n #[derive(Debug)]\n\n struct TestChannel {\n\n key: &'static str,\n\n }\n\n let (new_channels, listener) = futures::channel::mpsc::unbounded();\n\n let filter = ChannelFilter::new(listener, 2, |chan: &TestChannel| chan.key);\n\n pin_mut!(filter);\n\n\n\n new_channels\n\n .unbounded_send(TestChannel { key: \"key\" })\n\n .unwrap();\n\n let channel = assert_matches!(filter.as_mut().poll_next(&mut ctx()), Poll::Ready(Some(c)) => c);\n\n assert_eq!(filter.key_counts.len(), 1);\n\n\n\n drop(channel);\n\n assert_matches!(filter.as_mut().poll_next(&mut ctx()), Poll::Pending);\n\n assert!(filter.key_counts.is_empty());\n\n}\n", "file_path": "tarpc/src/server/filter.rs", "rank": 31, "score": 137267.0618073314 }, { "content": "fn main() {}\n", "file_path": "tarpc/tests/compile_fail/tarpc_server_missing_async.rs", "rank": 32, "score": 137117.9648700765 }, { "content": "#[derive(Debug)]\n\nstruct DispatchRequest<Req, Resp> {\n\n pub ctx: context::Context,\n\n pub request_id: u64,\n\n pub request: Req,\n\n pub response_completion: oneshot::Sender<Response<Resp>>,\n\n}\n\n\n\n/// Sends request cancellation signals.\n", "file_path": "tarpc/src/client.rs", "rank": 33, "score": 136811.81868943633 }, { "content": "/// Deserializes [`io::ErrorKind`] from a `u32`.\n\npub fn deserialize_io_error_kind_from_u32<'de, D>(\n\n deserializer: D,\n\n) -> Result<io::ErrorKind, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n use std::io::ErrorKind::*;\n\n Ok(match u32::deserialize(deserializer)? {\n\n 0 => NotFound,\n\n 1 => PermissionDenied,\n\n 2 => ConnectionRefused,\n\n 3 => ConnectionReset,\n\n 4 => ConnectionAborted,\n\n 5 => NotConnected,\n\n 6 => AddrInUse,\n\n 7 => AddrNotAvailable,\n\n 8 => BrokenPipe,\n\n 9 => AlreadyExists,\n\n 10 => WouldBlock,\n\n 11 => InvalidInput,\n\n 12 => InvalidData,\n\n 13 => TimedOut,\n\n 14 => WriteZero,\n\n 15 => Interrupted,\n\n 16 => Other,\n\n 17 => UnexpectedEof,\n\n _ => Other,\n\n })\n\n}\n", "file_path": "tarpc/src/util/serde.rs", "rank": 34, "score": 135798.88173990758 }, { "content": "#[tarpc::service]\n\npub trait ColorProtocol {\n\n async fn get_opposite_color(color: TestData) -> TestData;\n\n}\n\n\n", "file_path": "tarpc/tests/dataservice.rs", "rank": 35, "score": 134671.60164592694 }, { "content": " pub trait Sealed {}\n\n\n\n impl<Item, SinkItem, Codec> Sealed for Transport<TcpStream, Item, SinkItem, Codec> {}\n\n }\n\n\n\n impl<Item, SinkItem, Codec> Transport<TcpStream, Item, SinkItem, Codec> {\n\n /// Returns the peer address of the underlying TcpStream.\n\n pub fn peer_addr(&self) -> io::Result<SocketAddr> {\n\n self.inner.get_ref().get_ref().peer_addr()\n\n }\n\n /// Returns the local address of the underlying TcpStream.\n\n pub fn local_addr(&self) -> io::Result<SocketAddr> {\n\n self.inner.get_ref().get_ref().local_addr()\n\n }\n\n }\n\n\n\n /// A connection Future that also exposes the length-delimited framing config.\n\n #[pin_project]\n\n pub struct Connect<T, Item, SinkItem, CodecFn> {\n\n #[pin]\n", "file_path": "tarpc/src/serde_transport.rs", "rank": 36, "score": 134667.34114529617 }, { "content": "fn deserialize<D>(message: ByteBuf) -> io::Result<D>\n\nwhere\n\n for<'a> D: Deserialize<'a>,\n\n{\n\n bincode::deserialize(message.as_ref()).map_err(|e| io::Error::new(io::ErrorKind::Other, e))\n\n}\n\n\n", "file_path": "tarpc/examples/compression.rs", "rank": 37, "score": 132572.26436193025 }, { "content": "#[tarpc::service]\n\npub trait PingService {\n\n async fn ping();\n\n}\n\n\n", "file_path": "tarpc/examples/custom_transport.rs", "rank": 38, "score": 131539.62209548292 }, { "content": "#[derive(Debug)]\n\nstruct CanceledRequests(mpsc::UnboundedReceiver<u64>);\n\n\n", "file_path": "tarpc/src/client.rs", "rank": 39, "score": 127323.86051201519 }, { "content": "#[test]\n\nfn context_scope() {\n\n let ctx = Context::new_root();\n\n let mut ctx_copy = Box::pin(ctx.scope(async { current() }));\n\n assert_matches!(ctx_copy.poll_unpin(&mut noop_context()),\n\n Poll::Ready(Context {\n\n deadline,\n\n trace_context: trace::Context { trace_id, span_id, parent_id },\n\n }) if deadline == ctx.deadline\n\n && trace_id == ctx.trace_context.trace_id\n\n && span_id == ctx.trace_context.span_id\n\n && parent_id == ctx.trace_context.parent_id);\n\n}\n", "file_path": "tarpc/src/context.rs", "rank": 40, "score": 124030.34090750723 }, { "content": "/// Transforms an async function into a sync one, returning a type declaration\n\n/// for the return type (a future).\n\nfn transform_method(method: &mut ImplItemMethod) -> ImplItemType {\n\n method.sig.asyncness = None;\n\n\n\n // get either the return type or ().\n\n let ret = match &method.sig.output {\n\n ReturnType::Default => quote!(()),\n\n ReturnType::Type(_, ret) => quote!(#ret),\n\n };\n\n\n\n let fut_name = associated_type_for_rpc(method);\n\n let fut_name_ident = Ident::new(&fut_name, method.sig.ident.span());\n\n\n\n // generate the updated return signature.\n\n method.sig.output = parse_quote! {\n\n -> ::core::pin::Pin<Box<\n\n dyn ::core::future::Future<Output = #ret> + ::core::marker::Send\n\n >>\n\n };\n\n\n\n // transform the body of the method into Box::pin(async move { body }).\n", "file_path": "plugins/src/lib.rs", "rank": 41, "score": 123427.63762563837 }, { "content": "#[derive(Clone)]\n\nstruct DoubleServer {\n\n add_client: add::AddClient,\n\n}\n\n\n\n#[tarpc::server]\n\nimpl DoubleService for DoubleServer {\n\n async fn double(self, _: context::Context, x: i32) -> Result<i32, String> {\n\n let ctx = context::current();\n\n log::info!(\"DoubleService {:#?}\", ctx);\n\n self.add_client\n\n .add(ctx, x, x)\n\n .await\n\n .map_err(|e| e.to_string())\n\n }\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> io::Result<()> {\n\n env_logger::init();\n\n\n", "file_path": "tarpc/examples/server_calling_server.rs", "rank": 42, "score": 122474.39216156339 }, { "content": "#[derive(Clone)]\n\nstruct AddServer;\n\n\n\n#[tarpc::server]\n\nimpl AddService for AddServer {\n\n async fn add(self, _: context::Context, x: i32, y: i32) -> i32 {\n\n log::info!(\"AddService {:#?}\", context::current());\n\n x + y\n\n }\n\n}\n\n\n", "file_path": "tarpc/examples/server_calling_server.rs", "rank": 43, "score": 122474.39216156339 }, { "content": "#[proc_macro_attribute]\n\npub fn server(_attr: TokenStream, input: TokenStream) -> TokenStream {\n\n let mut item = syn::parse_macro_input!(input as ItemImpl);\n\n let span = item.span();\n\n\n\n // the generated type declarations\n\n let mut types: Vec<ImplItemType> = Vec::new();\n\n let mut expected_non_async_types: Vec<(&ImplItemMethod, String)> = Vec::new();\n\n let mut found_non_async_types: Vec<&ImplItemType> = Vec::new();\n\n\n\n for inner in &mut item.items {\n\n match inner {\n\n ImplItem::Method(method) => {\n\n if method.sig.asyncness.is_some() {\n\n // if this function is declared async, transform it into a regular function\n\n let typedecl = transform_method(method);\n\n types.push(typedecl);\n\n } else {\n\n // If it's not async, keep track of all required associated types for better\n\n // error reporting.\n\n expected_non_async_types.push((method, associated_type_for_rpc(method)));\n", "file_path": "plugins/src/lib.rs", "rank": 44, "score": 122188.6292494087 }, { "content": "/// generate an identifier consisting of the method name to CamelCase with\n\n/// Fut appended to it.\n\nfn associated_type_for_rpc(method: &ImplItemMethod) -> String {\n\n snake_to_camel(&method.sig.ident.unraw().to_string()) + \"Fut\"\n\n}\n\n\n", "file_path": "plugins/src/lib.rs", "rank": 48, "score": 120895.96079267046 }, { "content": "#[test]\n\nfn context_current_has_no_parent() {\n\n let ctx = current();\n\n assert_matches!(ctx.trace_context.parent_id, None);\n\n}\n\n\n", "file_path": "tarpc/src/context.rs", "rank": 49, "score": 120876.0149817528 }, { "content": "#[test]\n\nfn context_root_has_no_parent() {\n\n let ctx = Context::new_root();\n\n assert_matches!(ctx.trace_context.parent_id, None);\n\n}\n\n\n", "file_path": "tarpc/src/context.rs", "rank": 50, "score": 120876.0149817528 }, { "content": " /// A bidirectional stream ([`Sink`] + [`Stream`]) of messages.\n\n pub trait Transport<SinkItem, Item>:\n\n Stream<Item = io::Result<Item>> + Sink<SinkItem, Error = io::Error>\n\n {\n\n }\n\n\n\n impl<T, SinkItem, Item> Transport<SinkItem, Item> for T where\n\n T: Stream<Item = io::Result<Item>> + Sink<SinkItem, Error = io::Error> + ?Sized\n\n {\n\n }\n\n}\n", "file_path": "tarpc/src/transport.rs", "rank": 51, "score": 120846.26504537229 }, { "content": "#[derive(Clone)]\n\nstruct HelloServer(SocketAddr);\n\n\n\n#[tarpc::server]\n\nimpl World for HelloServer {\n\n async fn hello(self, _: context::Context, name: String) -> String {\n\n format!(\"Hello, {}! You are connected from {:?}.\", name, self.0)\n\n }\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> io::Result<()> {\n\n env_logger::init();\n\n\n\n let flags = App::new(\"Hello Server\")\n\n .version(\"0.1\")\n\n .author(\"Tim <tikue@google.com>\")\n\n .about(\"Say hello!\")\n\n .arg(\n\n Arg::with_name(\"port\")\n\n .short(\"p\")\n", "file_path": "example-service/src/server.rs", "rank": 53, "score": 116526.55183589668 }, { "content": " trait PollTest {\n\n type T;\n\n fn unwrap(self) -> Poll<Self::T>;\n\n fn ready(self) -> Self::T;\n\n }\n\n\n\n impl<T, E> PollTest for Poll<Option<Result<T, E>>>\n\n where\n\n E: ::std::fmt::Display,\n\n {\n\n type T = Option<T>;\n\n\n\n fn unwrap(self) -> Poll<Option<T>> {\n\n match self {\n\n Poll::Ready(Some(Ok(t))) => Poll::Ready(Some(t)),\n\n Poll::Ready(None) => Poll::Ready(None),\n\n Poll::Ready(Some(Err(e))) => panic!(\"{}\", e.to_string()),\n\n Poll::Pending => Poll::Pending,\n\n }\n\n }\n", "file_path": "tarpc/src/client.rs", "rank": 54, "score": 116337.41401727652 }, { "content": "#[derive(Clone, Debug)]\n\nstruct HelloServer;\n\n\n\n#[tarpc::server]\n\nimpl World for HelloServer {\n\n async fn hello(self, _: context::Context, name: String) -> String {\n\n format!(\"Hey, {}!\", name)\n\n }\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> anyhow::Result<()> {\n\n let mut incoming = tcp::listen(\"localhost:0\", Bincode::default).await?;\n\n let addr = incoming.local_addr();\n\n tokio::spawn(async move {\n\n let transport = incoming.next().await.unwrap().unwrap();\n\n BaseChannel::with_defaults(add_compression(transport))\n\n .execute(HelloServer.serve())\n\n .await;\n\n });\n\n\n\n let transport = tcp::connect(addr, Bincode::default).await?;\n\n let client = WorldClient::new(client::Config::default(), add_compression(transport)).spawn()?;\n\n\n\n println!(\n\n \"{}\",\n\n client.hello(context::current(), \"friend\".into()).await?\n\n );\n\n Ok(())\n\n}\n", "file_path": "tarpc/examples/compression.rs", "rank": 55, "score": 115243.60485982671 }, { "content": "#[derive(Clone)]\n\nstruct ColorServer;\n\n\n\n#[tarpc::server]\n\nimpl ColorProtocol for ColorServer {\n\n async fn get_opposite_color(self, _: context::Context, color: TestData) -> TestData {\n\n match color {\n\n TestData::White => TestData::Black,\n\n TestData::Black => TestData::White,\n\n }\n\n }\n\n}\n\n\n\n#[tokio::test]\n\nasync fn test_call() -> io::Result<()> {\n\n let transport = tarpc::serde_transport::tcp::listen(\"localhost:56797\", Json::default).await?;\n\n let addr = transport.local_addr();\n\n tokio::spawn(\n\n transport\n\n .take(1)\n\n .filter_map(|r| async { r.ok() })\n", "file_path": "tarpc/tests/dataservice.rs", "rank": 56, "score": 115239.32681474811 }, { "content": "#[derive(Clone)]\n\nstruct HelloServer;\n\n\n\nimpl World for HelloServer {\n\n // Each defined rpc generates two items in the trait, a fn that serves the RPC, and\n\n // an associated type representing the future output by the fn.\n\n\n\n type HelloFut = Ready<String>;\n\n\n\n fn hello(self, _: context::Context, name: String) -> Self::HelloFut {\n\n future::ready(format!(\"Hello, {}!\", name))\n\n }\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> io::Result<()> {\n\n let (client_transport, server_transport) = tarpc::transport::channel::unbounded();\n\n\n\n let server = server::BaseChannel::with_defaults(server_transport);\n\n tokio::spawn(server.execute(HelloServer.serve()));\n\n\n", "file_path": "tarpc/examples/readme.rs", "rank": 57, "score": 115239.32681474811 }, { "content": "#[tarpc::service]\n\ntrait World {\n\n async fn new();\n\n}\n\n\n", "file_path": "tarpc/tests/compile_fail/tarpc_service_fn_new.rs", "rank": 58, "score": 111461.83285764877 }, { "content": "#[tarpc::service]\n\ntrait World {\n\n async fn serve();\n\n}\n\n\n", "file_path": "tarpc/tests/compile_fail/tarpc_service_fn_serve.rs", "rank": 59, "score": 111461.83285764877 }, { "content": "#[tarpc::service]\n\npub trait World {\n\n /// Returns a greeting for name.\n\n async fn hello(name: String) -> String;\n\n}\n", "file_path": "example-service/src/lib.rs", "rank": 60, "score": 111445.21331283834 }, { "content": "#[derive(Debug)]\n\nstruct Tracker<K> {\n\n key: Option<K>,\n\n dropped_keys: mpsc::UnboundedSender<K>,\n\n}\n\n\n\nimpl<K> Drop for Tracker<K> {\n\n fn drop(&mut self) {\n\n // Don't care if the listener is dropped.\n\n let _ = self.dropped_keys.send(self.key.take().unwrap());\n\n }\n\n}\n\n\n\nimpl<C, K> Stream for TrackedChannel<C, K>\n\nwhere\n\n C: Stream,\n\n{\n\n type Item = <C as Stream>::Item;\n\n\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {\n\n self.inner_pin_mut().poll_next(cx)\n", "file_path": "tarpc/src/server/filter.rs", "rank": 61, "score": 109331.56056746558 }, { "content": "/// Data needed to clean up a single in-flight request.\n\nstruct RequestData {\n\n /// Aborts the response handler for the associated request.\n\n abort_handle: AbortHandle,\n\n /// The key to remove the timer for the request's deadline.\n\n deadline_key: delay_queue::Key,\n\n}\n\n\n\n/// An error returned when a request attempted to start with the same ID as a request already\n\n/// in flight.\n\n#[derive(Debug)]\n\npub struct AlreadyExistsError;\n\n\n\nimpl InFlightRequests {\n\n /// Returns the number of in-flight requests.\n\n pub fn len(&self) -> usize {\n\n self.request_data.len()\n\n }\n\n\n\n /// Starts a request, unless a request with the same ID is already in flight.\n\n pub fn start_request(\n", "file_path": "tarpc/src/server/in_flight_requests.rs", "rank": 62, "score": 108870.56288025889 }, { "content": " #[tarpc::service]\n\n trait r#trait {\n\n async fn r#await(r#struct: r#yield, r#enum: i32) -> (r#yield, i32);\n\n async fn r#fn(r#impl: r#yield) -> r#yield;\n\n async fn r#async();\n\n }\n\n\n\n #[tarpc::server]\n\n impl r#trait for () {\n\n async fn r#await(\n\n self,\n\n _: context::Context,\n\n r#struct: r#yield,\n\n r#enum: i32,\n\n ) -> (r#yield, i32) {\n\n (r#struct, r#enum)\n\n }\n\n\n\n async fn r#fn(self, _: context::Context, r#impl: r#yield) -> r#yield {\n\n r#impl\n\n }\n\n\n\n async fn r#async(self, _: context::Context) {}\n\n }\n\n}\n\n\n", "file_path": "plugins/tests/server.rs", "rank": 64, "score": 106669.56894951472 }, { "content": "/// Constructs a new transport from a framed transport and a serialization codec.\n\npub fn new<S, Item, SinkItem, Codec>(\n\n framed_io: Framed<S, LengthDelimitedCodec>,\n\n codec: Codec,\n\n) -> Transport<S, Item, SinkItem, Codec>\n\nwhere\n\n S: AsyncWrite + AsyncRead,\n\n Item: for<'de> Deserialize<'de>,\n\n SinkItem: Serialize,\n\n Codec: Serializer<SinkItem> + Deserializer<Item>,\n\n{\n\n Transport {\n\n inner: SerdeFramed::new(framed_io, codec),\n\n }\n\n}\n\n\n\nimpl<S, Item, SinkItem, Codec> From<(S, Codec)> for Transport<S, Item, SinkItem, Codec>\n\nwhere\n\n S: AsyncWrite + AsyncRead,\n\n Item: for<'de> Deserialize<'de>,\n\n SinkItem: Serialize,\n", "file_path": "tarpc/src/serde_transport.rs", "rank": 65, "score": 106234.00784386157 }, { "content": "#[derive(Debug)]\n\nstruct RequestData<Resp> {\n\n ctx: context::Context,\n\n response_completion: oneshot::Sender<Response<Resp>>,\n\n /// The key to remove the timer for the request's deadline.\n\n deadline_key: delay_queue::Key,\n\n}\n\n\n\n/// An error returned when an attempt is made to insert a request with an ID that is already in\n\n/// use.\n\n#[derive(Debug)]\n\npub struct AlreadyExistsError;\n\n\n\nimpl<Resp> InFlightRequests<Resp> {\n\n /// Returns the number of in-flight requests.\n\n pub fn len(&self) -> usize {\n\n self.request_data.len()\n\n }\n\n\n\n /// Returns true iff there are no requests in flight.\n\n pub fn is_empty(&self) -> bool {\n", "file_path": "tarpc/src/client/in_flight_requests.rs", "rank": 66, "score": 104891.66862314966 }, { "content": "fn serialize<T: Serialize>(t: T) -> io::Result<ByteBuf> {\n\n bincode::serialize(&t)\n\n .map(ByteBuf::from)\n\n .map_err(|e| io::Error::new(io::ErrorKind::Other, e))\n\n}\n\n\n", "file_path": "tarpc/examples/compression.rs", "rank": 67, "score": 103352.40589936315 }, { "content": "fn ten_seconds_from_now() -> SystemTime {\n\n SystemTime::now() + Duration::from_secs(10)\n\n}\n\n\n", "file_path": "tarpc/src/context.rs", "rank": 68, "score": 102896.82107261667 }, { "content": "/// Returns a channel to send request cancellation messages.\n\nfn cancellations() -> (RequestCancellation, CanceledRequests) {\n\n // Unbounded because messages are sent in the drop fn. This is fine, because it's still\n\n // bounded by the number of in-flight requests. Additionally, each request has a clone\n\n // of the sender, so the bounded channel would have the same behavior,\n\n // since it guarantees a slot.\n\n let (tx, rx) = mpsc::unbounded_channel();\n\n (RequestCancellation(tx), CanceledRequests(rx))\n\n}\n\n\n\nimpl RequestCancellation {\n\n /// Cancels the request with ID `request_id`.\n\n fn cancel(&mut self, request_id: u64) {\n\n let _ = self.0.send(request_id);\n\n }\n\n}\n\n\n\nimpl CanceledRequests {\n\n fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Option<u64>> {\n\n self.0.poll_recv(cx)\n\n }\n", "file_path": "tarpc/src/client.rs", "rank": 69, "score": 100601.3632632732 }, { "content": "#[derive(Debug, Clone)]\n\nstruct RequestCancellation(mpsc::UnboundedSender<u64>);\n\n\n\n/// A stream of IDs of requests that have been canceled.\n", "file_path": "tarpc/src/client.rs", "rank": 70, "score": 98242.24653700621 }, { "content": "fn snake_to_camel(ident_str: &str) -> String {\n\n let mut camel_ty = String::with_capacity(ident_str.len());\n\n\n\n let mut last_char_was_underscore = true;\n\n for c in ident_str.chars() {\n\n match c {\n\n '_' => last_char_was_underscore = true,\n\n c if last_char_was_underscore => {\n\n camel_ty.extend(c.to_uppercase());\n\n last_char_was_underscore = false;\n\n }\n\n c => camel_ty.extend(c.to_lowercase()),\n\n }\n\n }\n\n\n\n camel_ty.shrink_to_fit();\n\n camel_ty\n\n}\n\n\n", "file_path": "plugins/src/lib.rs", "rank": 71, "score": 97269.36374060196 }, { "content": "#[tarpc::service]\n\ntrait Foo {\n\n async fn two_part(s: String, i: i32) -> (String, i32);\n\n async fn bar(s: String) -> String;\n\n async fn baz();\n\n}\n\n\n", "file_path": "plugins/tests/server.rs", "rank": 72, "score": 93157.43366625678 }, { "content": " #[tarpc::service]\n\n trait Syntax {\n\n #[deny(warnings)]\n\n #[allow(non_snake_case)]\n\n async fn TestCamelCaseDoesntConflict();\n\n async fn hello() -> String;\n\n #[doc = \"attr\"]\n\n async fn attr(s: String) -> String;\n\n async fn no_args_no_return();\n\n async fn no_args() -> ();\n\n async fn one_arg(one: String) -> i32;\n\n async fn two_args_no_return(one: String, two: u64);\n\n async fn two_args(one: String, two: u64) -> String;\n\n async fn no_args_ret_error() -> i32;\n\n async fn one_arg_ret_error(one: String) -> String;\n\n async fn no_arg_implicit_return_error();\n\n #[doc = \"attr\"]\n\n async fn one_arg_implicit_return_error(one: String);\n\n }\n\n\n\n #[tarpc::server]\n", "file_path": "plugins/tests/server.rs", "rank": 73, "score": 93157.43366625678 }, { "content": "#[test]\n\nfn syntax() {\n", "file_path": "plugins/tests/server.rs", "rank": 74, "score": 91111.96659126236 }, { "content": "fn main() {}\n", "file_path": "tarpc/tests/compile_fail/tarpc_service_fn_serve.rs", "rank": 75, "score": 90925.51308515827 }, { "content": "fn main() {}\n", "file_path": "tarpc/tests/compile_fail/tarpc_service_fn_new.rs", "rank": 76, "score": 90925.51308515827 }, { "content": "#[test]\n\nfn att_service_trait() {\n\n use futures::future::{ready, Ready};\n\n\n", "file_path": "plugins/tests/service.rs", "rank": 77, "score": 88036.5358356543 }, { "content": "#[tarpc::service(derive_serde = false)]\n", "file_path": "tarpc/tests/compile_fail/tarpc_server_missing_async.rs", "rank": 78, "score": 86755.2291791032 }, { "content": "#[allow(non_camel_case_types)]\n\n#[test]\n\nfn raw_idents_work() {\n\n type r#yield = String;\n\n\n", "file_path": "plugins/tests/server.rs", "rank": 79, "score": 86147.03816615039 }, { "content": "#[test]\n\nfn type_generation_works() {\n\n #[tarpc::server]\n\n impl Foo for () {\n\n async fn two_part(self, _: context::Context, s: String, i: i32) -> (String, i32) {\n\n (s, i)\n\n }\n\n\n\n async fn bar(self, _: context::Context, s: String) -> String {\n\n s\n\n }\n\n\n\n async fn baz(self, _: context::Context) {}\n\n }\n\n\n\n // the assert_type_eq macro can only be used once per block.\n\n {\n\n assert_type_eq!(\n\n <() as Foo>::TwoPartFut,\n\n Pin<Box<dyn Future<Output = (String, i32)> + Send>>\n\n );\n", "file_path": "plugins/tests/server.rs", "rank": 80, "score": 86147.03816615039 }, { "content": "#[derive(Clone)]\n\nstruct Service;\n\n\n\nimpl PingService for Service {\n\n type PingFut = future::Ready<()>;\n\n\n\n fn ping(self, _: Context) -> Self::PingFut {\n\n future::ready(())\n\n }\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> std::io::Result<()> {\n\n let bind_addr = \"/tmp/tarpc_on_unix_example.sock\";\n\n\n\n let _ = std::fs::remove_file(bind_addr);\n\n\n\n let listener = UnixListener::bind(bind_addr).unwrap();\n\n let codec_builder = LengthDelimitedCodec::builder();\n\n tokio::spawn(async move {\n\n loop {\n", "file_path": "tarpc/examples/custom_transport.rs", "rank": 81, "score": 84068.87971144466 }, { "content": " #[tarpc::service]\n\n trait Counter {\n\n async fn count() -> u32;\n\n }\n\n\n\n struct CountService(u32);\n\n\n\n impl Counter for &mut CountService {\n\n type CountFut = futures::future::Ready<u32>;\n\n\n\n fn count(self, _: context::Context) -> Self::CountFut {\n\n self.0 += 1;\n\n futures::future::ready(self.0)\n\n }\n\n }\n\n\n\n let (tx, rx) = channel::unbounded();\n\n tokio::spawn(async {\n\n let mut requests = BaseChannel::with_defaults(rx).requests();\n\n let mut counter = CountService(0);\n\n\n", "file_path": "tarpc/tests/service_functional.rs", "rank": 82, "score": 83520.94743990808 }, { "content": "#[tarpc_plugins::service]\n\ntrait Service {\n\n async fn add(x: i32, y: i32) -> i32;\n\n async fn hey(name: String) -> String;\n\n}\n\n\n", "file_path": "tarpc/tests/service_functional.rs", "rank": 83, "score": 83520.89138609493 }, { "content": " #[tarpc_plugins::service]\n\n trait Loop {\n\n async fn r#loop();\n\n }\n\n\n\n #[derive(Clone)]\n\n struct LoopServer;\n\n\n\n #[derive(Debug)]\n\n struct AllHandlersComplete;\n\n\n\n #[tarpc::server]\n\n impl Loop for LoopServer {\n\n async fn r#loop(self, _: context::Context) {\n\n loop {\n\n futures::pending!();\n\n }\n\n }\n\n }\n\n\n\n let _ = env_logger::try_init();\n", "file_path": "tarpc/tests/service_functional.rs", "rank": 84, "score": 83520.89138609493 }, { "content": "#[tarpc::service]\n\ntrait World {\n\n async fn pat((a, b): (u8, u32));\n\n}\n\n\n", "file_path": "tarpc/tests/compile_fail/tarpc_service_arg_pat.rs", "rank": 85, "score": 83074.01673614724 }, { "content": "#[test]\n\nfn ui() {\n\n let t = trybuild::TestCases::new();\n\n t.compile_fail(\"tests/compile_fail/*.rs\");\n\n}\n", "file_path": "tarpc/tests/compile_fail.rs", "rank": 86, "score": 81489.37646349276 }, { "content": "#[proc_macro_attribute]\n\npub fn service(attr: TokenStream, input: TokenStream) -> TokenStream {\n\n let derive_serde = parse_macro_input!(attr as DeriveSerde);\n\n let unit_type: &Type = &parse_quote!(());\n\n let Service {\n\n ref attrs,\n\n ref vis,\n\n ref ident,\n\n ref rpcs,\n\n } = parse_macro_input!(input as Service);\n\n\n\n let camel_case_fn_names: &Vec<_> = &rpcs\n\n .iter()\n\n .map(|rpc| snake_to_camel(&rpc.ident.unraw().to_string()))\n\n .collect();\n\n let args: &[&[PatType]] = &rpcs.iter().map(|rpc| &*rpc.args).collect::<Vec<_>>();\n\n let response_fut_name = &format!(\"{}ResponseFut\", ident.unraw());\n\n let derive_serialize = if derive_serde.0 {\n\n Some(\n\n quote! {#[derive(tarpc::serde::Serialize, tarpc::serde::Deserialize)]\n\n #[serde(crate = \"tarpc::serde\")]},\n", "file_path": "plugins/src/lib.rs", "rank": 87, "score": 81317.61092339054 }, { "content": "fn main() {}\n", "file_path": "tarpc/tests/compile_fail/tarpc_service_arg_pat.rs", "rank": 88, "score": 81088.70486956327 }, { "content": "#[proc_macro_attribute]\n\npub fn derive_serde(_attr: TokenStream, item: TokenStream) -> TokenStream {\n\n let mut gen: proc_macro2::TokenStream = quote! {\n\n #[derive(tarpc::serde::Serialize, tarpc::serde::Deserialize)]\n\n #[serde(crate = \"tarpc::serde\")]\n\n };\n\n gen.extend(proc_macro2::TokenStream::from(item));\n\n proc_macro::TokenStream::from(gen)\n\n}\n\n\n\n/// Generates:\n\n/// - service trait\n\n/// - serve fn\n\n/// - client stub struct\n\n/// - new_stub client factory fn\n\n/// - Request and Response enums\n\n/// - ResponseFut Future\n", "file_path": "plugins/src/lib.rs", "rank": 89, "score": 79870.42529187795 }, { "content": "fn add_compression<In, Out>(\n\n transport: impl Stream<Item = io::Result<CompressedMessage<In>>>\n\n + Sink<CompressedMessage<Out>, Error = io::Error>,\n\n) -> impl Stream<Item = io::Result<In>> + Sink<Out, Error = io::Error>\n\nwhere\n\n Out: Serialize,\n\n for<'a> In: Deserialize<'a>,\n\n{\n\n transport.with(compress).and_then(decompress)\n\n}\n\n\n", "file_path": "tarpc/examples/compression.rs", "rank": 90, "score": 77115.00436266 }, { "content": " #[tarpc::service]\n\n trait r#trait {\n\n async fn r#await(r#struct: r#yield, r#enum: i32) -> (r#yield, i32);\n\n async fn r#fn(r#impl: r#yield) -> r#yield;\n\n async fn r#async();\n\n }\n\n\n\n impl r#trait for () {\n\n type AwaitFut = Ready<(r#yield, i32)>;\n\n fn r#await(self, _: context::Context, r#struct: r#yield, r#enum: i32) -> Self::AwaitFut {\n\n ready((r#struct, r#enum))\n\n }\n\n\n\n type FnFut = Ready<r#yield>;\n\n fn r#fn(self, _: context::Context, r#impl: r#yield) -> Self::FnFut {\n\n ready(r#impl)\n\n }\n\n\n\n type AsyncFut = Ready<()>;\n\n fn r#async(self, _: context::Context) -> Self::AsyncFut {\n\n ready(())\n\n }\n\n }\n\n}\n\n\n", "file_path": "plugins/tests/service.rs", "rank": 91, "score": 74242.40381671343 }, { "content": "// Copyright 2018 Google LLC\n\n//\n\n// Use of this source code is governed by an MIT-style\n\n// license that can be found in the LICENSE file or at\n\n// https://opensource.org/licenses/MIT.\n\n\n\nuse crate::{add::Add as AddService, double::Double as DoubleService};\n\nuse futures::{future, prelude::*};\n\nuse std::io;\n\nuse tarpc::{\n\n client, context,\n\n server::{BaseChannel, Incoming},\n\n};\n\nuse tokio_serde::formats::Json;\n\n\n\npub mod add {\n\n #[tarpc::service]\n", "file_path": "tarpc/examples/server_calling_server.rs", "rank": 92, "score": 64108.87477255124 }, { "content": " let add_listener = tarpc::serde_transport::tcp::listen(\"localhost:0\", Json::default)\n\n .await?\n\n .filter_map(|r| future::ready(r.ok()));\n\n let addr = add_listener.get_ref().local_addr();\n\n let add_server = add_listener\n\n .map(BaseChannel::with_defaults)\n\n .take(1)\n\n .execute(AddServer.serve());\n\n tokio::spawn(add_server);\n\n\n\n let to_add_server = tarpc::serde_transport::tcp::connect(addr, Json::default).await?;\n\n let add_client = add::AddClient::new(client::Config::default(), to_add_server).spawn()?;\n\n\n\n let double_listener = tarpc::serde_transport::tcp::listen(\"localhost:0\", Json::default)\n\n .await?\n\n .filter_map(|r| future::ready(r.ok()));\n\n let addr = double_listener.get_ref().local_addr();\n\n let double_server = double_listener\n\n .map(BaseChannel::with_defaults)\n\n .take(1)\n", "file_path": "tarpc/examples/server_calling_server.rs", "rank": 93, "score": 64107.00969376718 }, { "content": " .execute(DoubleServer { add_client }.serve());\n\n tokio::spawn(double_server);\n\n\n\n let to_double_server = tarpc::serde_transport::tcp::connect(addr, Json::default).await?;\n\n let double_client =\n\n double::DoubleClient::new(client::Config::default(), to_double_server).spawn()?;\n\n\n\n let ctx = context::current();\n\n log::info!(\"Client {:#?}\", ctx);\n\n for i in 1..=5 {\n\n eprintln!(\"{:?}\", double_client.double(ctx, i).await?);\n\n }\n\n Ok(())\n\n}\n", "file_path": "tarpc/examples/server_calling_server.rs", "rank": 94, "score": 64100.723763821195 }, { "content": " /// Returns the ID of the request-scoped trace.\n\n pub fn trace_id(&self) -> &TraceId {\n\n &self.trace_context.trace_id\n\n }\n\n\n\n /// Run a future with this context as the current context.\n\n pub async fn scope<F>(self, f: F) -> F::Output\n\n where\n\n F: std::future::Future,\n\n {\n\n CURRENT_CONTEXT.scope(self, f).await\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nuse {\n\n assert_matches::assert_matches, futures::prelude::*, futures_test::task::noop_context,\n\n std::task::Poll,\n\n};\n\n\n", "file_path": "tarpc/src/context.rs", "rank": 95, "score": 62169.200948490754 }, { "content": "// Copyright 2018 Google LLC\n\n//\n\n// Use of this source code is governed by an MIT-style\n\n// license that can be found in the LICENSE file or at\n\n// https://opensource.org/licenses/MIT.\n\n\n\n//! Provides a request context that carries a deadline and trace context. This context is sent from\n\n//! client to server and is used by the server to enforce response deadlines.\n\n\n\nuse crate::trace::{self, TraceId};\n\nuse static_assertions::assert_impl_all;\n\nuse std::time::{Duration, SystemTime};\n\n\n\n/// A request context that carries request-scoped information like deadlines and trace information.\n\n/// It is sent from client to server and is used by the server to enforce response deadlines.\n\n///\n\n/// The context should not be stored directly in a server implementation, because the context will\n\n/// be different for each request in scope.\n\n#[derive(Clone, Copy, Debug)]\n\n#[non_exhaustive]\n", "file_path": "tarpc/src/context.rs", "rank": 96, "score": 62158.11508463917 }, { "content": "#[cfg_attr(feature = \"serde1\", derive(serde::Serialize, serde::Deserialize))]\n\npub struct Context {\n\n /// When the client expects the request to be complete by. The server should cancel the request\n\n /// if it is not complete by this time.\n\n #[cfg_attr(feature = \"serde1\", serde(default = \"ten_seconds_from_now\"))]\n\n pub deadline: SystemTime,\n\n /// Uniquely identifies requests originating from the same source.\n\n /// When a service handles a request by making requests itself, those requests should\n\n /// include the same `trace_id` as that included on the original request. This way,\n\n /// users can trace related actions across a distributed system.\n\n pub trace_context: trace::Context,\n\n}\n\n\n\nassert_impl_all!(Context: Send, Sync);\n\n\n\ntokio::task_local! {\n\n static CURRENT_CONTEXT: Context;\n\n}\n\n\n", "file_path": "tarpc/src/context.rs", "rank": 97, "score": 62150.72007973545 }, { "content": " #[tokio::test]\n\n async fn stage_request_response_closed_skipped() {\n\n let (mut dispatch, mut channel, _server_channel) = set_up();\n\n let dispatch = Pin::new(&mut dispatch);\n\n let cx = &mut Context::from_waker(&noop_waker_ref());\n\n\n\n // Test that a request future that's closed its receiver but not yet canceled its request --\n\n // i.e. still in `drop fn` -- will cause the request to not be added to the in-flight request\n\n // map.\n\n let mut resp = send_request(&mut channel, \"hi\").await;\n\n resp.response.close();\n\n\n\n assert!(dispatch.poll_next_request(cx).is_pending());\n\n }\n\n\n\n fn set_up() -> (\n\n RequestDispatch<String, String, UnboundedChannel<Response<String>, ClientMessage<String>>>,\n\n Channel<String, String>,\n\n UnboundedChannel<ClientMessage<String>, Response<String>>,\n\n ) {\n", "file_path": "tarpc/src/client.rs", "rank": 98, "score": 61769.973121298484 }, { "content": "\n\n // Regression test for https://github.com/google/tarpc/issues/220\n\n #[tokio::test]\n\n async fn stage_request_channel_dropped_doesnt_panic() {\n\n let (mut dispatch, mut channel, mut server_channel) = set_up();\n\n let mut dispatch = Pin::new(&mut dispatch);\n\n let cx = &mut Context::from_waker(&noop_waker_ref());\n\n\n\n let _ = send_request(&mut channel, \"hi\").await;\n\n drop(channel);\n\n\n\n assert!(dispatch.as_mut().poll(cx).is_ready());\n\n send_response(\n\n &mut server_channel,\n\n Response {\n\n request_id: 0,\n\n message: Ok(\"hello\".into()),\n\n },\n\n )\n\n .await;\n", "file_path": "tarpc/src/client.rs", "rank": 99, "score": 61769.5683368084 } ]
Rust
src/parsers.rs
hoodie/sdp-nom
c0ffeea95aeed252ba1af2b8a04c570a0e75c942
#![allow(dead_code)] use nom::{ branch::alt, bytes::complete::{tag, take_while, take_while1}, character::{ complete::{multispace0, space1}, is_digit, }, combinator::{complete, map, map_res, opt}, error::ParseError, multi::many0, sequence::{delimited, preceded, separated_pair, terminated}, IResult, Parser, }; use std::{borrow::Cow, net::IpAddr}; #[cfg(test)] pub fn create_test_vec(strs: &[&str]) -> Vec<Cow<'static, str>> { strs.iter().map(|&s| Cow::from(s.to_owned())).collect() } pub fn is_not_space(c: char) -> bool { c != ' ' } pub fn is_alphabetic(chr: u8) -> bool { (0x41..=0x5A).contains(&chr) || (0x61..=0x7A).contains(&chr) } pub fn is_alphanumeric(chr: char) -> bool { is_alphabetic(chr as u8) || is_digit(chr as u8) } pub fn is_numeric(chr: char) -> bool { is_digit(chr as u8) } pub fn ws<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( f: F, ) -> impl Parser<&'a str, O, E> { delimited(multispace0, f, multispace0) } pub fn wsf<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { delimited(multispace0, f, multispace0) } pub fn cowify<'a, E: ParseError<&'a str>, F: Parser<&'a str, &'a str, E>>( f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, Cow<'a, str>, E> { map(f, Cow::from) } pub fn a_line<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { line("a=", f) } pub fn attribute<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( attribute_kind: &'a str, f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { line( "a=", map(separated_pair(tag(attribute_kind), tag(":"), f), |(_, x)| x), ) } pub fn attribute_p<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( p: F, f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { line("a=", map(separated_pair(p, tag(":"), f), |(_, x)| x)) } pub fn line<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( prefix: &'a str, f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { complete(preceded(tag(prefix), f)) } pub fn read_number(input: &str) -> IResult<&str, u32> { map_res( take_while1(|c: char| -> bool { c != ' ' && c != ':' && c != '/' }), |i: &str| i.parse::<u32>(), )(input) } pub fn read_big_number(input: &str) -> IResult<&str, u64> { map_res( take_while1(|c: char| -> bool { c != ' ' && c != ':' && c != '/' }), |i: &str| (i).parse::<u64>(), )(input) } pub fn read_everything(input: &str) -> IResult<&str, &str> { take_while(|c| c != '\n')(input) } pub fn read_string0(input: &str) -> IResult<&str, &str> { take_while(is_not_space)(input) } pub fn read_string(input: &str) -> IResult<&str, &str> { take_while1(is_not_space)(input) } pub fn read_non_colon_string(input: &str) -> IResult<&str, &str> { take_while1(|c: char| -> bool { c != ' ' && c != ':' })(input) } pub fn read_non_slash_string(input: &str) -> IResult<&str, &str> { take_while1(|c: char| -> bool { c != ' ' && c != '/' })(input) } pub fn slash_separated_strings(input: &str) -> IResult<&str, Vec<&str>> { many0(terminated(read_non_slash_string, opt(tag("/"))))(input) } pub fn slash_separated_cow_strings(input: &str) -> IResult<&str, Vec<Cow<'_, str>>> { many0(terminated(cowify(read_non_slash_string), opt(tag("/"))))(input) } pub fn space_separated_cow_strings(input: &str) -> IResult<&str, Vec<Cow<'_, str>>> { many0(terminated(cowify(read_string), multispace0))(input) } pub fn space_separated_strings(input: &str) -> IResult<&str, Vec<&str>> { many0(terminated(read_string, multispace0))(input) } pub fn read_addr(input: &str) -> IResult<&str, IpAddr> { map_res(take_while1(|c| c != ' ' && c != '/'), str::parse)(input) } #[derive(Clone, PartialEq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr( feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "camelCase") )] #[non_exhaustive] pub enum IpVer { Ip4, Ip6, } pub fn read_ipver(input: &str) -> IResult<&str, IpVer> { alt(( map(tag("IP4"), |_| IpVer::Ip4), map(tag("IP6"), |_| IpVer::Ip6), ))(input) } pub fn read_as_strings(input: &str) -> IResult<&str, Vec<&str>> { many0(terminated(read_string, opt(space1)))(input) } pub fn read_as_cow_strings(input: &str) -> IResult<&str, Vec<Cow<'_, str>>> { many0(terminated(cowify(read_string), opt(space1)))(input) } pub fn read_as_numbers(input: &str) -> IResult<&str, Vec<u32>> { many0(terminated(read_number, opt(space1)))(input) }
#![allow(dead_code)] use nom::{ branch::alt, bytes::complete::{tag, take_while, take_while1}, character::{ complete::{multispace0, space1}, is_digit, }, combinator::{complete, map, map_res, opt}, error::ParseError, multi::many0, sequence::{delimited, preceded, separated_pair, terminated}, IResult, Parser, }; use std::{borrow::Cow, net::IpAddr}; #[cfg(test)] pub fn create_test_vec(strs: &[&str]) -> Vec<Cow<'static, str>> { strs.iter().map(|&s| Cow::from(s.to_owned())).collect() } pub fn is_not_space(c: char) -> bool { c != ' ' } pub fn is_alphabetic(chr: u8) -> bool { (0x41..=0x5A).contains(&chr) || (0x61..=0x7A).contains(&chr) } pub fn is_alphanumeric(chr: char) -> bool { is_alphabetic(chr as u8) || is_digit(chr as u8) } pub fn is_numeric(chr: char) -> bool { is_digit(chr as u8) } pub fn ws<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( f: F, ) -> impl Parser<&'a str, O, E> { delimited(multispace0, f, multispace0) } pub fn wsf<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { delimited(multispace0, f, multispace0) } pub fn cowify<'a, E: ParseError<&'a str>, F: Parser<&'a str, &'a str, E>>( f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, Cow<'a, str>, E> { map(f, Cow::from) } pub fn a_line<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { line("a=", f) } pub fn attribute<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( attribute_kind: &'a str, f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { line( "a=", map(separated_pair(tag(attribute_kind), tag(":"), f), |(_, x)| x), ) } pub fn attribute_p<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( p: F, f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { line("a=", map(separated_pair(p, tag(":"), f), |(_, x)| x)) } pub fn line<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( prefix: &'a str, f: F, ) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> { complete(preceded(tag(prefix), f)) } pub fn read_number(input: &str) -> IResult<&str, u32> { map_res( take_while1(|c: char| -> bool { c != ' ' && c != ':' && c != '/' }), |i: &str| i.parse::<u32>(), )(input) } pub fn read_big_number(input: &str) -> IResult<&str, u64> {
(input) } pub fn read_everything(input: &str) -> IResult<&str, &str> { take_while(|c| c != '\n')(input) } pub fn read_string0(input: &str) -> IResult<&str, &str> { take_while(is_not_space)(input) } pub fn read_string(input: &str) -> IResult<&str, &str> { take_while1(is_not_space)(input) } pub fn read_non_colon_string(input: &str) -> IResult<&str, &str> { take_while1(|c: char| -> bool { c != ' ' && c != ':' })(input) } pub fn read_non_slash_string(input: &str) -> IResult<&str, &str> { take_while1(|c: char| -> bool { c != ' ' && c != '/' })(input) } pub fn slash_separated_strings(input: &str) -> IResult<&str, Vec<&str>> { many0(terminated(read_non_slash_string, opt(tag("/"))))(input) } pub fn slash_separated_cow_strings(input: &str) -> IResult<&str, Vec<Cow<'_, str>>> { many0(terminated(cowify(read_non_slash_string), opt(tag("/"))))(input) } pub fn space_separated_cow_strings(input: &str) -> IResult<&str, Vec<Cow<'_, str>>> { many0(terminated(cowify(read_string), multispace0))(input) } pub fn space_separated_strings(input: &str) -> IResult<&str, Vec<&str>> { many0(terminated(read_string, multispace0))(input) } pub fn read_addr(input: &str) -> IResult<&str, IpAddr> { map_res(take_while1(|c| c != ' ' && c != '/'), str::parse)(input) } #[derive(Clone, PartialEq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr( feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "camelCase") )] #[non_exhaustive] pub enum IpVer { Ip4, Ip6, } pub fn read_ipver(input: &str) -> IResult<&str, IpVer> { alt(( map(tag("IP4"), |_| IpVer::Ip4), map(tag("IP6"), |_| IpVer::Ip6), ))(input) } pub fn read_as_strings(input: &str) -> IResult<&str, Vec<&str>> { many0(terminated(read_string, opt(space1)))(input) } pub fn read_as_cow_strings(input: &str) -> IResult<&str, Vec<Cow<'_, str>>> { many0(terminated(cowify(read_string), opt(space1)))(input) } pub fn read_as_numbers(input: &str) -> IResult<&str, Vec<u32>> { many0(terminated(read_number, opt(space1)))(input) }
map_res( take_while1(|c: char| -> bool { c != ' ' && c != ':' && c != '/' }), |i: &str| (i).parse::<u64>(), )
call_expression
[ { "content": "pub fn rtpmap_line(input: &str) -> IResult<&str, RtpMap> {\n\n attribute(\n\n \"rtpmap\",\n\n map(\n\n tuple((\n\n read_number, // payload_typ\n\n preceded(multispace1, cowify(read_non_slash_string)), // encoding_name\n\n opt(preceded(tag(\"/\"), read_number)), // clock_rate\n\n opt(preceded(\n\n tag(\"/\"),\n\n read_number, // encoding\n\n )),\n\n )),\n\n |(payload, encoding_name, clock_rate, encoding)| RtpMap {\n\n payload,\n\n encoding_name,\n\n clock_rate,\n\n encoding,\n\n },\n\n ),\n\n )(input)\n\n}\n\n\n", "file_path": "src/attributes/rtpmap.rs", "rank": 11, "score": 222191.38112813156 }, { "content": "pub fn session_line(input: &str) -> IResult<&str, SessionLine> {\n\n alt((\n\n // two levels of `alt` because it's not implemented for such large tuples\n\n map(version_line, SessionLine::Version),\n\n map(name_line, SessionLine::Name),\n\n map(description_line, SessionLine::Description),\n\n map(bandwidth_line, SessionLine::BandWidth),\n\n map(uri_line, SessionLine::Uri),\n\n map(timing_line, SessionLine::Timing),\n\n map(phone_number_line, SessionLine::PhoneNumber),\n\n map(email_address_line, SessionLine::EmailAddress),\n\n map(origin_line, SessionLine::Origin),\n\n map(connection_line, SessionLine::Connection),\n\n map(media_line, SessionLine::Media),\n\n ))(input)\n\n}\n\n\n\npub mod connection;\n\npub mod media;\n\npub mod origin;\n", "file_path": "src/lines.rs", "rank": 12, "score": 218325.93929694104 }, { "content": "pub fn sdp_line(input: &str) -> IResult<&str, SdpLine> {\n\n alt((\n\n map(session_line, SdpLine::Session),\n\n map(attribute_line, SdpLine::Attribute),\n\n map(cowify(lines::comment::comment_line), SdpLine::Comment),\n\n ))(input)\n\n}\n", "file_path": "src/sdp_line.rs", "rank": 16, "score": 214579.04825133723 }, { "content": "pub fn attribute_line(input: &str) -> IResult<&str, AttributeLine> {\n\n alt((\n\n alt((\n\n map(mid::mid_line, AttributeLine::Mid),\n\n map(msid::msid_semantic_line, AttributeLine::MsidSemantic),\n\n map(msid::msid_line, AttributeLine::Msid),\n\n map(bundle::bundle_group_line, AttributeLine::BundleGroup),\n\n map(ice::ice_parameter_line, AttributeLine::Ice),\n\n map(ssrc::ssrc_line, AttributeLine::Ssrc),\n\n map(ssrc::ssrc_group_line, AttributeLine::SsrcGroup),\n\n map(rtpmap::rtpmap_line, AttributeLine::RtpMap),\n\n map(rtpmap::read_p_time, AttributeLine::PTime),\n\n map(fingerprint_line, AttributeLine::Fingerprint),\n\n )),\n\n alt((\n\n map(candidate::candidate_line, AttributeLine::Candidate),\n\n map(direction::direction_line, AttributeLine::Direction),\n\n map(extmap::extmap_line, AttributeLine::Extmap),\n\n map(dtls::setup_role_line, AttributeLine::SetupRole),\n\n map(rtp_attribute_line, AttributeLine::Rtp),\n", "file_path": "src/attributes.rs", "rank": 17, "score": 213263.55345675215 }, { "content": "pub fn origin_line(input: &str) -> IResult<&str, Origin> {\n\n line(\"o=\", origin)(input)\n\n}\n\n\n", "file_path": "src/lines/origin.rs", "rank": 18, "score": 213263.55345675215 }, { "content": "/// Connection \"c=IN IP4 10.23.42.137\"\n\n///\n\npub fn connection_line(input: &str) -> IResult<&str, Connection> {\n\n line(\n\n \"c=\",\n\n preceded(\n\n wsf(tag(\"IN\")),\n\n map(\n\n tuple((\n\n wsf(read_ipver), // ip_ver\n\n read_addr, // addr\n\n opt(preceded(tag(\"/\"), read_number)),\n\n )),\n\n |(ip_ver, addr, mask)| (Connection { ip_ver, addr, mask }),\n\n ),\n\n ),\n\n )(input)\n\n}\n\n\n", "file_path": "src/lines/connection.rs", "rank": 19, "score": 213263.55345675218 }, { "content": "pub fn media_line(input: &str) -> IResult<&str, Media> {\n\n line(\n\n \"m=\",\n\n wsf(map(\n\n tuple((\n\n wsf(cowify(read_string)), // type\n\n wsf(read_number), // port\n\n wsf(slash_separated_cow_strings), // protocol\n\n wsf(read_as_cow_strings), // payloads\n\n )),\n\n |(r#type, port, protocol, payloads)| Media {\n\n r#type,\n\n port,\n\n protocol,\n\n payloads,\n\n },\n\n )),\n\n )(input)\n\n}\n\n\n", "file_path": "src/lines/media.rs", "rank": 20, "score": 213263.55345675215 }, { "content": "pub fn origin(input: &str) -> IResult<&str, Origin> {\n\n map(\n\n tuple((\n\n wsf(cowify(read_string)), // user_name\n\n wsf(read_big_number), // session_id\n\n wsf(read_number), // session_version\n\n wsf(cowify(read_string)), // net_type\n\n wsf(read_ipver), // ip_ver\n\n wsf(read_addr), // addr\n\n )),\n\n |(user_name, session_id, session_version, net_type, ip_ver, addr)| Origin {\n\n user_name,\n\n session_id,\n\n session_version,\n\n net_type,\n\n ip_ver,\n\n addr,\n\n },\n\n )(input)\n\n}\n\n\n", "file_path": "src/lines/origin.rs", "rank": 27, "score": 208162.44779266446 }, { "content": "pub fn extmap_line(input: &str) -> IResult<&str, Extmap> {\n\n attribute(\"extmap\", read_extmap)(input)\n\n}\n\n\n", "file_path": "src/attributes/extmap.rs", "rank": 32, "score": 204091.95448767452 }, { "content": "/// \"a=Candidate\"\n\npub fn candidate_line(input: &str) -> IResult<&str, Candidate> {\n\n attribute(\"candidate\", candidate)(input)\n\n}\n\n\n\n#[cfg(test)]\n\n#[rustfmt::skip]\n\nmod tests {\n\n use std::net::Ipv4Addr;\n\n\n\n use crate::{assert_line, assert_line_print};\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn parses_candidate_line() {\n\n assert_line_print!(candidate_line, \"a=candidate:3348148302 1 udp 2113937151 192.0.2.1 56500 typ host\");\n\n assert_line_print!(candidate_line, \"a=candidate:3348148302 1 tcp 2113937151 192.0.2.1 56500 typ srflx\");\n\n assert_line_print!(candidate_line, \"a=candidate:3348148302 2 tcp 2113937151 192.0.2.1 56500 typ srflx\");\n\n assert_line!(candidate_line, \"a=candidate:1 1 TCP 2128609279 10.0.1.1 9 typ host tcptype active\", Candidate {\n\n foundation: 1, component: CandidateComponent::Rtp, protocol: CandidateProtocol::Tcp, priority: 2128609279, addr: Ipv4Addr::new(10,0,1,1).into(), port: 9,\n", "file_path": "src/attributes/candidate.rs", "rank": 33, "score": 204091.95448767452 }, { "content": "/// ssrc\n\npub fn ssrc_line(input: &str) -> IResult<&str, Ssrc> {\n\n attribute(\n\n \"ssrc\",\n\n map(\n\n tuple((\n\n wsf(read_big_number), // id\n\n preceded(\n\n multispace0,\n\n separated_pair(\n\n cowify(read_non_colon_string),\n\n tag(\":\"),\n\n cowify(wsf(is_not(\"\\n\"))),\n\n ),\n\n ),\n\n )),\n\n |(id, (attribute, value))| Ssrc {\n\n id,\n\n attribute,\n\n value,\n\n },\n\n ),\n\n )(input)\n\n}\n\n\n", "file_path": "src/attributes/ssrc.rs", "rank": 34, "score": 204091.95448767452 }, { "content": "pub fn read_p_time(input: &str) -> IResult<&str, PTime> {\n\n alt((\n\n attribute(\"ptime\", map(read_number, PTime::PTime)),\n\n attribute(\"minptime\", map(read_number, PTime::MinPTime)),\n\n attribute(\"maxptime\", map(read_number, PTime::MaxPTime)),\n\n ))(input)\n\n}\n\n\n", "file_path": "src/attributes/rtpmap.rs", "rank": 38, "score": 201250.5241885804 }, { "content": "pub fn rtcpfb_attribute_line(input: &str) -> IResult<&str, Fb> {\n\n attribute(\"rtcp-fb\", rtcpfb_attribute)(input)\n\n}\n\n\n", "file_path": "src/attributes/rtcp.rs", "rank": 39, "score": 200290.7159301468 }, { "content": "pub fn rtcp_attribute_line(input: &str) -> IResult<&str, Rtcp> {\n\n attribute(\"rtcp\", rtcp_attribute)(input)\n\n}\n\n\n", "file_path": "src/attributes/rtcp.rs", "rank": 40, "score": 200290.71593014678 }, { "content": "pub fn setup_role_line(input: &str) -> IResult<&str, SetupRole> {\n\n attribute(\"setup\", read_setup_role)(input)\n\n}\n\n\n", "file_path": "src/attributes/dtls.rs", "rank": 41, "score": 196732.52231764697 }, { "content": "pub fn ice_parameter_line(input: &str) -> IResult<&str, IceParameter> {\n\n alt((\n\n attribute(\"ice-ufrag\", map(cowify(read_string), IceParameter::Ufrag)),\n\n attribute(\"ice-pwd\", map(cowify(read_string), IceParameter::Pwd)),\n\n attribute(\n\n \"ice-options\",\n\n map(cowify(read_string), IceParameter::Options),\n\n ),\n\n a_line(map(tag(\"ice-mismatch\"), |_| IceParameter::Mismatch)),\n\n a_line(map(tag(\"ice-lite\"), |_| IceParameter::Lite)),\n\n ))(input)\n\n}\n\n\n", "file_path": "src/attributes/ice.rs", "rank": 42, "score": 196732.52231764697 }, { "content": "pub fn ssrc_group_line(input: &str) -> IResult<&str, SsrcGroup> {\n\n attribute(\"ssrc-group\", ssrc_group)(input)\n\n}\n\n\n", "file_path": "src/attributes/ssrc.rs", "rank": 43, "score": 196732.52231764697 }, { "content": "pub fn sdp_lines(sdp: &str) -> impl Iterator<Item = SdpLine<'_>> {\n\n sdp.lines().filter_map(|line| match sdp_line(line) {\n\n Ok((_, parsed)) => Some(parsed),\n\n Err(_) => None,\n\n })\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 44, "score": 190427.54680571117 }, { "content": "pub fn sdp_lines_all(sdp: &str) -> impl Iterator<Item = Result<(&str, SdpLine<'_>), String>> {\n\n sdp.lines()\n\n .map(|l| nom::Finish::finish(sdp_line(l)).map_err(|e| e.to_string()))\n\n}\n", "file_path": "src/lib.rs", "rank": 45, "score": 186423.04477204257 }, { "content": "pub fn candidate(input: &str) -> IResult<&str, Candidate> {\n\n map(\n\n tuple((\n\n wsf(read_number), // foundation\n\n // component:\n\n wsf(alt((\n\n map(tag(\"1\"), |_| CandidateComponent::Rtp),\n\n map(tag(\"2\"), |_| CandidateComponent::Rtcp),\n\n ))),\n\n // protocol:\n\n wsf(alt((\n\n map(alt((tag(\"UDP\"), tag(\"udp\"))), |_| CandidateProtocol::Udp),\n\n map(alt((tag(\"TCP\"), tag(\"tcp\"))), |_| CandidateProtocol::Tcp),\n\n map(alt((tag(\"DCCP\"), tag(\"dccp\"))), |_| CandidateProtocol::Dccp),\n\n ))),\n\n wsf(read_number), // priority\n\n wsf(read_addr), // addr\n\n wsf(read_number), // port\n\n preceded(\n\n tag(\"typ\"),\n", "file_path": "src/attributes/candidate.rs", "rank": 46, "score": 185642.33478150662 }, { "content": "pub fn ssrc_group(input: &str) -> IResult<&str, SsrcGroup> {\n\n map(\n\n tuple((\n\n alt((\n\n // semantic\n\n map(tag(\"FID\"), |_| SsrcSemantic::FID),\n\n map(tag(\"FEC\"), |_| SsrcSemantic::FEC),\n\n )),\n\n wsf(read_as_numbers), // ids\n\n )),\n\n |(semantic, ids)| SsrcGroup { semantic, ids },\n\n )(input)\n\n}\n\n\n", "file_path": "src/attributes/ssrc.rs", "rank": 47, "score": 179349.85899059562 }, { "content": "pub fn read_net_type(input: &str) -> IResult<&str, NetType> {\n\n map(tag(\"IN\"), |_| NetType::IN)(input)\n\n}\n\n\n\n/// Rtcp\n\n///\n\n///<https://tools.ietf.org/html/rfc3605>\n\n/// `a=rtcp:65179 IN IP4 10.23.34.567`\n\n#[derive(Clone, PartialEq)]\n\n#[cfg_attr(feature = \"debug\", derive(Debug))]\n\n#[cfg_attr(\n\n feature = \"serde\",\n\n derive(serde::Serialize, serde::Deserialize),\n\n serde(rename_all = \"camelCase\")\n\n)]\n\npub struct Rtcp {\n\n pub port: u32,\n\n pub net_type: NetType,\n\n pub ip_ver: IpVer,\n\n pub addr: IpAddr,\n\n}\n\n\n", "file_path": "src/attributes/rtcp.rs", "rank": 48, "score": 176501.04639180607 }, { "content": "pub fn print_leftover(input: &str, rest: &str) {\n\n println!(\"INPUT: {:?}\\nLEFT: {:?}\", input, rest);\n\n}\n\n\n", "file_path": "src/assert.rs", "rank": 49, "score": 174039.03651500703 }, { "content": "/// a=extmap:<value>[\"/\"<direction>] <URI> <extensionattributes>\n\nfn read_extmap(input: &str) -> IResult<&str, Extmap> {\n\n map(\n\n tuple((\n\n wsf(read_number), // <value>\n\n wsf(opt(preceded(tag(\"/\"), read_direction))), // [\"/\"<direction>]\n\n wsf(cowify(read_string)), // <uri>\n\n wsf(read_as_cow_strings), // <extensionattributes>\n\n )),\n\n |(value, direction, uri, attributes)| Extmap {\n\n value,\n\n direction,\n\n uri,\n\n attributes,\n\n },\n\n )(input)\n\n}\n\n\n", "file_path": "src/attributes/extmap.rs", "rank": 50, "score": 148596.73548277374 }, { "content": "fn rtcp_attribute(input: &str) -> IResult<&str, Rtcp> {\n\n map(\n\n tuple((\n\n wsf(read_number), // port\n\n wsf(read_net_type), // net_type\n\n wsf(read_ipver), // ip_ver\n\n wsf(read_addr), // addr\n\n )),\n\n |(port, net_type, ip_ver, addr)| Rtcp {\n\n port,\n\n net_type,\n\n ip_ver,\n\n addr,\n\n },\n\n )(input)\n\n}\n\n\n", "file_path": "src/attributes/rtcp.rs", "rank": 51, "score": 148596.73548277374 }, { "content": "fn rtcpfb_attribute(input: &str) -> IResult<&str, Fb> {\n\n map(\n\n tuple((\n\n read_number, // payload\n\n wsf(read_val), // val\n\n )),\n\n |(payload, val)| Fb { payload, val },\n\n )(input)\n\n}\n\n\n", "file_path": "src/attributes/rtcp.rs", "rank": 52, "score": 148596.73548277374 }, { "content": "fn read_param(input: &str) -> IResult<&str, FbParam> {\n\n alt((\n\n map(preceded(tag(\"app\"), wsf(cowify(read_string))), FbParam::App),\n\n map(\n\n tuple((wsf(cowify(read_string)), wsf(cowify(read_string)))),\n\n |(token, value)| FbParam::Pair(token, value),\n\n ),\n\n map(wsf(cowify(read_string)), FbParam::Single),\n\n ))(input)\n\n}\n\n\n\n#[derive(Clone, IntoOwned, PartialEq)]\n\n#[cfg_attr(feature = \"debug\", derive(Debug))]\n\n#[cfg_attr(\n\n feature = \"serde\",\n\n derive(serde::Serialize, serde::Deserialize),\n\n serde(rename_all = \"camelCase\")\n\n)]\n\n#[non_exhaustive]\n\npub enum FbAckParam<'a> {\n\n Rpsi,\n\n Sli(Option<Cow<'a, str>>),\n\n App(Cow<'a, str>),\n\n Other(Cow<'a, str>, Option<Cow<'a, str>>),\n\n}\n\n\n", "file_path": "src/attributes/rtcp.rs", "rank": 53, "score": 146167.19594996143 }, { "content": "fn read_val(input: &str) -> IResult<&str, FbVal> {\n\n alt((\n\n map(preceded(tag(\"ack\"), wsf(read_ack_param)), FbVal::Ack),\n\n map(preceded(tag(\"nack\"), wsf(read_nack_param)), FbVal::Nack),\n\n map(preceded(tag(\"trr-int\"), wsf(read_number)), FbVal::TrrInt),\n\n map(\n\n tuple((wsf(cowify(read_string)), opt(wsf(read_param)))),\n\n |(id, param)| FbVal::RtcpFbId { id, param },\n\n ),\n\n ))(input)\n\n}\n\n\n", "file_path": "src/attributes/rtcp.rs", "rank": 54, "score": 146167.19594996143 }, { "content": "pub fn print_result<T: fmt::Debug>(input: &str, rest: &str, result: &T) {\n\n println!(\n\n \"INPUT: {:?}\\nLEFT: {:?}\\nRESULT: {:#?}\",\n\n input, rest, result\n\n );\n\n}\n\n\n", "file_path": "src/assert.rs", "rank": 55, "score": 144441.09067525226 }, { "content": "fn read_setup_role(input: &str) -> IResult<&str, SetupRole> {\n\n alt((\n\n map(tag(\"active\"), |_| SetupRole::Active),\n\n map(tag(\"passive\"), |_| SetupRole::Passive),\n\n map(tag(\"actpass\"), |_| SetupRole::ActPass),\n\n ))(input)\n\n}\n\n\n", "file_path": "src/attributes/dtls.rs", "rank": 56, "score": 143891.83686606528 }, { "content": "fn read_ack_param(input: &str) -> IResult<&str, FbAckParam> {\n\n alt((\n\n map(tag(\"rpsi\"), |_| FbAckParam::Rpsi),\n\n map(\n\n preceded(tag(\"app\"), wsf(cowify(read_string))),\n\n FbAckParam::App,\n\n ),\n\n map(\n\n preceded(tag(\"sli\"), opt(wsf(cowify(read_string)))),\n\n FbAckParam::Sli,\n\n ),\n\n map(\n\n tuple((wsf(cowify(read_string)), wsf(cowify(read_string)))),\n\n |(token, value)| FbAckParam::Other(token, Some(value)),\n\n ),\n\n ))(input)\n\n}\n\n\n", "file_path": "src/attributes/rtcp.rs", "rank": 57, "score": 141756.14301060484 }, { "content": "fn read_nack_param(input: &str) -> IResult<&str, FbNackParam> {\n\n alt((\n\n map(tag(\"rpsi\"), |_| FbNackParam::Rpsi),\n\n map(\n\n preceded(tag(\"app\"), wsf(cowify(read_string))),\n\n FbNackParam::App,\n\n ),\n\n map(\n\n tuple((wsf(cowify(read_string)), wsf(cowify(read_string)))),\n\n |(token, value)| FbNackParam::Other(token, value),\n\n ),\n\n ))(input)\n\n}\n\n\n", "file_path": "src/attributes/rtcp.rs", "rank": 58, "score": 141756.14301060484 }, { "content": "type ParseError<'a> = nom::Err<nom::error::Error<&'a str>>;\n\n\n", "file_path": "src/session.rs", "rank": 60, "score": 98222.7128360232 }, { "content": "fn with_all_fixtures<F>(\n\n sub_folders: &[impl AsRef<Path>],\n\n f: F,\n\n) -> Result<(), Box<dyn std::error::Error>>\n\nwhere\n\n F: Fn(&Path), // -> Result<(), Box<dyn std::error::Error>>,\n\n{\n\n for sub_folder in sub_folders {\n\n let fixture_path = dbg!(PathBuf::from(env::var(\"CARGO_MANIFEST_DIR\").unwrap())\n\n .join(\"fixtures\")\n\n .join(sub_folder));\n\n\n\n for path in fs::read_dir(fixture_path)?\n\n .filter_map(|entry| entry.ok())\n\n .filter(|entry| entry.path().extension().and_then(OsStr::to_str) == Some(\"sdp\"))\n\n .map(|entry| entry.path())\n\n {\n\n f(&path);\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/parse_fixtures.rs", "rank": 61, "score": 94009.92364899072 }, { "content": "#[test]\n\nfn test_connection_line() {\n\n assert_line!(\n\n connection_line,\n\n \"c=IN IP6 fe80::5a55:caff:fe1a:e187\",\n\n Connection {\n\n ip_ver: IpVer::Ip6,\n\n addr: \"fe80::5a55:caff:fe1a:e187\".parse().unwrap(),\n\n mask: None,\n\n },\n\n print\n\n );\n\n assert_line!(\n\n connection_line,\n\n \"c=IN IP4 10.23.42.137/32\",\n\n Connection {\n\n ip_ver: IpVer::Ip4,\n\n addr: IpAddr::V4(Ipv4Addr::new(10, 23, 42, 137)),\n\n mask: Some(32),\n\n },\n\n print\n", "file_path": "src/lines/connection.rs", "rank": 62, "score": 72411.69329334723 }, { "content": "#[test]\n\nfn seldom_lines() {\n\n let seldom_lines = [\n\n \"i=foobar\",\n\n \"e=email@example.com\",\n\n \"p=0118 999 881 999 119 7253\",\n\n ];\n\n for (i, line) in seldom_lines.iter().enumerate() {\n\n print!(\"{}.\", i);\n\n assert_line!(line);\n\n }\n\n}\n", "file_path": "src/tests.rs", "rank": 63, "score": 68529.40460146386 }, { "content": "#[cfg(all(feature = \"udisplay\", not(feature = \"display\")))]\n\npub fn ufmt_to_string<U: ufmt::uDisplay>(stuff: &U) -> String {\n\n let mut output = String::new();\n\n ufmt::uwrite!(output, \"{}\", stuff).unwrap();\n\n output\n\n}\n", "file_path": "src/session.rs", "rank": 64, "score": 67011.41262008427 }, { "content": "#[test]\n\nfn test_mline() {\n\n assert_line!(\n\n media_line,\n\n \"m=video 51744 RTP/AVP 126 97 98 34 31\",\n\n Media {\n\n r#type: \"video\".into(),\n\n port: 51744,\n\n protocol: create_test_vec(&[\"RTP\", \"AVP\"]),\n\n payloads: create_test_vec(&[\"126\", \"97\", \"98\", \"34\", \"31\"]),\n\n },\n\n print\n\n );\n\n assert_line!(\n\n media_line,\n\n \"m=audio 9 UDP/TLS/RTP/SAVPF 111 103 104 9 0 8 106 105 13 110 112 113 126\",\n\n Media {\n\n r#type: \"audio\".into(),\n\n port: 9,\n\n protocol: create_test_vec(&[\"UDP\", \"TLS\", \"RTP\", \"SAVPF\"]),\n\n payloads: create_test_vec(&[\n", "file_path": "src/lines/media.rs", "rank": 65, "score": 65885.46945331462 }, { "content": "#[test]\n\nfn test_attribute_line() {\n\n assert_line_print!(attribute_line, \"a=bundle-only\");\n\n assert_line_print!(attribute_line, \"a=end-of-candidates\");\n\n assert_line_print!(attribute_line, \"a=extmap-allowed-mixed\");\n\n}\n\n\n\npub mod generic {\n\n use super::*;\n\n\n\n pub fn key_val_attribute_line(input: &str) -> IResult<&str, (Cow<'_, str>, Cow<'_, str>)> {\n\n a_line(map(\n\n separated_pair(\n\n cowify(read_non_colon_string),\n\n tag(\":\"),\n\n cowify(is_not(\"\\n\")),\n\n ),\n\n |(key, val)| (key, val),\n\n ))(input)\n\n }\n\n\n", "file_path": "src/attributes.rs", "rank": 66, "score": 65885.46945331462 }, { "content": "#[test]\n\nfn parses_candidates() {\n\n assert_line!(\n\n origin_line,\n\n \"o=test 4962303333179871722 1 IN IP4 0.0.0.0\",\n\n Origin {\n\n user_name: \"test\".into(),\n\n session_id: 4962303333179871722,\n\n session_version: 1,\n\n net_type: \"IN\".into(),\n\n ip_ver: IpVer::Ip4,\n\n addr: \"0.0.0.0\".parse().unwrap(),\n\n },\n\n print\n\n );\n\n assert_line_print!(origin_line, \"o=- 4962303333179871722 1 IN IP4 0.0.0.0\");\n\n}\n", "file_path": "src/lines/origin.rs", "rank": 67, "score": 65885.46945331462 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn test_rtcpfb_line() {\n\n assert_line_print!(rtcpfb_attribute_line, \"a=rtcp-fb:98 trr-int 100\");\n\n assert_line_print!(rtcpfb_attribute_line, \"a=rtcp-fb:98 ack sli\");\n\n assert_line_print!(rtcpfb_attribute_line, \"a=rtcp-fb:98 ack sli 5432\");\n\n assert_line!(rtcpfb_attribute_line, \"a=rtcp-fb:98 nack rpsi\", Fb {payload: 98, val: FbVal::Nack(FbNackParam::Rpsi)}, print);\n\n\n\n assert_line!(rtcpfb_attribute_line, \"a=rtcp-fb:96 goog-remb\", Fb {payload: 96, val: FbVal::RtcpFbId{id: \"goog-remb\".into(), param: None}}, print);\n\n assert_line!(rtcpfb_attribute_line, \"a=rtcp-fb:96 transport-cc\", Fb {payload: 96, val: FbVal::RtcpFbId{id: \"transport-cc\".into(), param: None}}, print);\n\n assert_line!(\n\n rtcpfb_attribute_line,\n\n \"a=rtcp-fb:96 ccm fir\",\n\n Fb {\n\n payload: 96,\n\n val: FbVal::RtcpFbId{\n\n id: \"ccm\".into(),\n\n param: Some(FbParam::Single(\"fir\".into()))\n\n }\n\n }, print\n\n );\n\n}\n", "file_path": "src/attributes/rtcp.rs", "rank": 68, "score": 63476.34308226822 }, { "content": "#[test]\n\nfn test_rtpmap_line() {\n\n assert_line!(\n\n rtpmap_line,\n\n \"a=rtpmap:96 VP8/90000\",\n\n RtpMap {\n\n payload: 96,\n\n encoding_name: \"VP8\".into(),\n\n clock_rate: Some(90000),\n\n encoding: None,\n\n },\n\n print\n\n );\n\n assert_line!(\n\n rtpmap_line,\n\n \"a=rtpmap:97 rtx/90000\",\n\n RtpMap {\n\n payload: 97,\n\n encoding_name: \"rtx\".into(),\n\n clock_rate: Some(90000),\n\n encoding: None,\n", "file_path": "src/attributes/rtpmap.rs", "rank": 69, "score": 63476.34308226822 }, { "content": "#[test]\n\nfn test_extmap_line() {\n\n assert_line!(extmap_line, \"a=extmap:1/sendonly URI-toffset\");\n\n assert_line!(extmap_line, \"a=extmap:2 urn:ietf:params:rtp-hdrext:toffset\");\n\n assert_line!(\n\n extmap_line,\n\n \"a=extmap:3 urn:ietf:params:rtp-hdrext:encrypt urn:ietf:params:rtp-hdrext:smpte-tc 25@600/24\"\n\n );\n\n assert_line!(\n\n extmap_line,\n\n \"a=extmap:4/recvonly urn:ietf:params:rtp-hdrext:encrypt URI-gps-string\"\n\n );\n\n assert_line!(\n\n extmap_line,\n\n \"a=extmap:2/sendrecv http://example.com/082005/ext.htm#xmeta short\"\n\n );\n\n}\n", "file_path": "src/attributes/extmap.rs", "rank": 70, "score": 63476.34308226822 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn test_ssrc_line() {\n\n assert_line!(\n\n ssrc_line,\n\n \"a=ssrc:1366781084 cname:EocUG1f0fcg/yvY7\",\n\n Ssrc { id: 1366781084, attribute: \"cname\".into(), value: \"EocUG1f0fcg/yvY7\".into() },\n\n print\n\n );\n\n assert_line!(\n\n ssrc_line,\n\n \"a=ssrc: 1366781084 cname: EocUG1f0fcg/yvY7\",\n\n Ssrc { id: 1366781084, attribute: \"cname\".into(), value: \"EocUG1f0fcg/yvY7\".into() }\n\n );\n\n assert_line!(ssrc_line, \"a=ssrc:3570614608 cname:4TOk42mSjXCkVIa6\");\n\n assert_line!(ssrc_line, \"a=ssrc:3570614608 msid:lgsCFqt9kN2fVKw5wg3NKqGdATQoltEwOdMS 35429d94-5637-4686-9ecd-7d0622261ce8\");\n\n assert_line!(ssrc_line, \"a=ssrc:3570614608 mslabel:lgsCFqt9kN2fVKw5wg3NKqGdATQoltEwOdMS\");\n\n assert_line!(ssrc_line, \"a=ssrc:3570614608 label:35429d94-5637-4686-9ecd-7d0622261ce8\");\n\n assert_line!(ssrc_line, \"a=ssrc:2231627014 cname:4TOk42mSjXCkVIa6\");\n\n assert_line!(ssrc_line, \"a=ssrc:2231627014 msid:lgsCFqt9kN2fVKw5wg3NKqGdATQoltEwOdMS daed9400-d0dd-4db3-b949-422499e96e2d\");\n\n assert_line!(ssrc_line, \"a=ssrc:2231627014 mslabel:lgsCFqt9kN2fVKw5wg3NKqGdATQoltEwOdMS\");\n\n assert_line!(ssrc_line, \"a=ssrc:2231627014 label:daed9400-d0dd-4db3-b949-422499e96e2d\");\n", "file_path": "src/attributes/ssrc.rs", "rank": 71, "score": 63476.34308226822 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn test_ssrc_group_line() {\n\n assert_line_print!(ssrc_group_line, \"a=ssrc-group:FID 2231627014 632943048\");\n\n}\n", "file_path": "src/attributes/ssrc.rs", "rank": 72, "score": 61272.075262498525 }, { "content": "#[test]\n\nfn test_setup_role_line() {\n\n assert_line!(setup_role_line, \"a=setup:active\", SetupRole::Active, print);\n\n assert_line!(\n\n setup_role_line,\n\n \"a=setup:actpass\",\n\n SetupRole::ActPass,\n\n print\n\n );\n\n assert_line!(\n\n setup_role_line,\n\n \"a=setup:passive\",\n\n SetupRole::Passive,\n\n print\n\n );\n\n}\n", "file_path": "src/attributes/dtls.rs", "rank": 73, "score": 61272.075262498525 }, { "content": "#[test]\n\nfn test_rtcp_attribute_line() {\n\n assert_line_print!(rtcp_attribute_line, \"a=rtcp:65179 IN IP4 10.23.34.255\");\n\n assert_line_print!(rtcp_attribute_line, \"a=rtcp:65179 IN IP4 ::1\");\n\n}\n\n\n\n// ///////////////////////\n\n\n\n/// RtcpFeedback\n\n///\n\n/// This one is fun to parse\n\n///<https://tools.ietf.org/html/rfc6642>\n\n///<https://tools.ietf.org/html/rfc4585#section-4.2>\n\n///<https://datatracker.ietf.org/doc/draft-ietf-mmusic-sdp-mux-attributes/16/?include_text=1>\n\n/// eg `a=rtcp-fb:98 trr-int 100`\n\n#[derive(Clone, IntoOwned, PartialEq)]\n\n#[cfg_attr(feature = \"debug\", derive(Debug))]\n\n#[cfg_attr(\n\n feature = \"serde\",\n\n derive(serde::Serialize, serde::Deserialize),\n\n serde(rename_all = \"camelCase\")\n", "file_path": "src/attributes/rtcp.rs", "rank": 74, "score": 61272.075262498525 }, { "content": "fn sort_certain_lines(mut session: Session) -> Session {\n\n session.media.iter_mut().for_each(|media| {\n\n media.fmtp.sort_by_key(|a| a.payload);\n\n });\n\n session\n\n}\n\n\n", "file_path": "tests/parse_fixtures.rs", "rank": 75, "score": 52884.961660562265 }, { "content": "fn main() {\n\n let input = read_from_args().unwrap();\n\n let session = Session::read_str(&input);\n\n eprintln!(\"parsed\\n{:#?}\", session);\n\n\n\n let reserialized = session.to_string();\n\n eprintln!(\"reserialized\\n{}\", reserialized);\n\n let reparsed = Session::read_str(&reserialized);\n\n\n\n pretty_assertions::assert_eq!(session, reparsed);\n\n let parsed_lines = sdp_lines_all(&input)\n\n .map(|res| {\n\n let (remainder, line) = res.unwrap();\n\n if !remainder.is_empty() {\n\n eprintln!(\"🙈 remainder {:?}\", remainder);\n\n }\n\n line\n\n })\n\n .collect::<Vec<_>>();\n\n // eprintln!(\"parsed\\n{:#?}\", session);\n", "file_path": "examples/reparse.rs", "rank": 76, "score": 40848.22174874116 }, { "content": "#[test]\n\nfn anatomy() {\n\n //! every exaple from<https://webrtchacks.com/sdp-anatomy/>\n\n\n\n let anatomy_examples = [\n\n // Global Lines\n\n \"o=- 4611731400430051336 2 IN IP4 127.0.0.1\",\n\n \"s=-\",\n\n \"t=0 0\",\n\n \"a=group:BUNDLE 0 1\",\n\n \"a=msid-semantic: WMS lgsCFqt9kN2fVKw5wg3NKqGdATQoltEwOdMS\",\n\n \"m=audio 58779 UDP/TLS/RTP/SAVPF 111 103 104 9 0 8 106 105 13 126\",\n\n \"c=IN IP4 217.130.243.155\",\n\n \"a=rtcp:51472 IN IP4 217.130.243.155\",\n\n\n\n // Audio Lines\n\n \"a=candidate:1467250027 1 udp 2122260223 192.168.0.196 46243 typ host generation 0\",\n\n \"a=candidate:1467250027 2 udp 2122260222 192.168.0.196 56280 typ host generation 0\",\n\n \"a=candidate:435653019 1 tcp 1845501695 192.168.0.196 0 typ host tcptype active generation 0\",\n\n \"a=candidate:435653019 2 tcp 1845501695 192.168.0.196 0 typ host tcptype active generation 0\",\n\n \"a=candidate:1853887674 1 udp 1518280447 47.61.61.61 36768 typ srflx raddr 192.168.0.196 rport 36768 generation 0\",\n", "file_path": "src/tests.rs", "rank": 77, "score": 40848.22174874116 }, { "content": "fn main() {\n\n let mut err_count = 1;\n\n if let Some(arg) = std::env::args().nth(1) {\n\n if let Ok(content) = std::fs::read_to_string(arg) {\n\n err_count = 0;\n\n for line in content.lines() {\n\n if let Err(e) = sdp_line(line) {\n\n println!(\"{:#}\", line);\n\n println!(\"{}\\n\", e);\n\n err_count += 1;\n\n }\n\n }\n\n }\n\n }\n\n println!(\"{} errors\", err_count);\n\n std::process::exit(err_count);\n\n}\n", "file_path": "examples/incomplete.rs", "rank": 78, "score": 40848.22174874116 }, { "content": "fn main() {\n\n let content = read_from_args().unwrap();\n\n for line in sdp_lines(&content) {\n\n cfg_if::cfg_if! {\n\n if #[cfg(feature = \"serde\")] {\n\n println!(\"{}\", serde_json::to_string_pretty(&line).unwrap());\n\n } else {\n\n println!(\"{}\", ufmt_to_string(&line));\n\n }\n\n }\n\n }\n\n}\n", "file_path": "examples/iter.rs", "rank": 79, "score": 40848.22174874116 }, { "content": "fn main() {\n\n let session = read_from_args().unwrap();\n\n\n\n cfg_if::cfg_if! {\n\n if #[cfg(feature = \"serde\")] {\n\n println!(\"{}\", serde_json::to_string_pretty(&session).unwrap());\n\n } else {\n\n println!(\"{:#?}\", session);\n\n // print!(\"{}\", session.to_string());\n\n }\n\n }\n\n}\n", "file_path": "examples/session.rs", "rank": 80, "score": 40848.22174874116 }, { "content": "fn main() {\n\n let session = read_from_args().unwrap();\n\n\n\n let value = serde_json::to_value(&session)\n\n .map(|mut v| {\n\n filter_undefineds(&mut v);\n\n v\n\n })\n\n .and_then(|value| serde_json::to_string_pretty(&value))\n\n .unwrap();\n\n println!(\"{}\", value);\n\n}\n", "file_path": "examples/json_filtered.rs", "rank": 81, "score": 39424.431294159454 }, { "content": "fn main() {\n\n cfg_if::cfg_if! {\n\n if #[cfg(feature = \"msg_pack\")] {\n\n use pretty_assertions::assert_eq;\n\n use sdp_nom::Session;\n\n let (session, content) = read_from_args().unwrap();\n\n\n\n let packed = rmp_serde::to_vec(&session).unwrap();\n\n\n\n let text_size = content.as_bytes().len() as u32;\n\n let pack_size = packed.len() as u32;\n\n\n\n println!(\"text size: {:?}B\", text_size);\n\n println!(\"packed size: {:?}B\", pack_size);\n\n println!(\n\n \"ratio: {:?}B\",\n\n f64::from(pack_size) / f64::from(text_size)\n\n );\n\n\n\n let new_session: Session = rmp_serde::from_read_ref(&packed).unwrap();\n\n assert_eq!(session, new_session);\n\n assert_eq!(content, new_session.to_string());\n\n } else {\n\n panic!(\"please use --feature \\\"msg_pack\\\"\")\n\n }\n\n }\n\n}\n", "file_path": "examples/message_pack.rs", "rank": 82, "score": 39424.431294159454 }, { "content": "fn main() {\n\n let mut err_count = 0;\n\n if let Some(arg) = std::env::args().nth(1) {\n\n if let Ok(content) = std::fs::read_to_string(arg) {\n\n for line in content.lines() {\n\n match sdp_line(line) {\n\n Ok(parsed) => {\n\n println!(\"\\n👌 {:#} -> {:?}\", line, parsed.0);\n\n println!(\"{:#?}\", parsed.1);\n\n }\n\n Err(e) => {\n\n println!(\"\\n🥵 {:#}\", line);\n\n println!(\"{}\", e);\n\n err_count += 1;\n\n }\n\n }\n\n }\n\n }\n\n } else {\n\n println!(\"no input! please pass a file path as first parameter\");\n\n }\n\n println!(\"{} errors\", err_count);\n\n std::process::exit(err_count);\n\n}\n", "file_path": "examples/pretty_print.rs", "rank": 83, "score": 39424.431294159454 }, { "content": "#[test]\n\nfn test_extmap() {\n\n assert_line!(\n\n read_extmap,\n\n \"1/sendonly URI-toffset\",\n\n Extmap {\n\n value: 1,\n\n direction: Some(Direction::SendOnly),\n\n uri: \"URI-toffset\".into(),\n\n attributes: vec![]\n\n }\n\n );\n\n assert_line!(\n\n read_extmap,\n\n \"2 urn:ietf:params:rtp-hdrext:toffset\",\n\n Extmap {\n\n value: 2,\n\n direction: None,\n\n uri: \"urn:ietf:params:rtp-hdrext:toffset\".into(),\n\n attributes: vec![]\n\n }\n", "file_path": "src/attributes/extmap.rs", "rank": 84, "score": 38132.96398435681 }, { "content": "#[test]\n\n#[cfg(feature = \"udisplay\")]\n\nfn parse_fixtures_reparsable() {\n\n with_all_fixtures(&[\"reparsable\", \"mozilla\"], |path| {\n\n let fixture = std::fs::read_to_string(&path).unwrap();\n\n let session = sort_certain_lines(Session::read_str(&fixture));\n\n eprintln!(\"parsed\\n{:#?}\", session);\n\n\n\n let reserialized = session.to_string();\n\n eprintln!(\"reserialized\\n{}\", reserialized);\n\n let reparsed = sort_certain_lines(Session::read_str(&reserialized));\n\n\n\n eprintln!(\"fixture: {:?}\", path.display());\n\n pretty_assertions::assert_eq!(session, reparsed);\n\n })\n\n .unwrap();\n\n}\n\n\n", "file_path": "tests/parse_fixtures.rs", "rank": 85, "score": 36956.19232429251 }, { "content": "fn main() {\n\n let mut session = read_from_args().unwrap();\n\n session.media = session\n\n .media\n\n .into_iter()\n\n .map(|mut media| {\n\n media.candidates = media\n\n .candidates\n\n .into_iter()\n\n .filter(|c| c.protocol == CandidateProtocol::Tcp)\n\n .collect();\n\n media\n\n })\n\n .collect();\n\n\n\n cfg_if::cfg_if! {\n\n if #[cfg(feature = \"serde\")] {\n\n println!(\"{}\", serde_json::to_string_pretty(&session).unwrap());\n\n } else {\n\n // println!(\"{:#?}\", session);\n\n print!(\"{}\", session.to_string());\n\n }\n\n }\n\n}\n", "file_path": "examples/remove_direct_tcp_candidates.rs", "rank": 86, "score": 36956.19232429251 }, { "content": "#[test]\n\nfn test_ice_parameters() {\n\n assert_line!(\n\n ice_parameter_line,\n\n \"a=ice-ufrag:Oyef7uvBlwafI3hT\",\n\n IceParameter::Ufrag(\"Oyef7uvBlwafI3hT\".into()),\n\n print\n\n );\n\n assert_line!(\n\n ice_parameter_line,\n\n \"a=ice-pwd:T0teqPLNQQOf+5W+ls+P2p16\",\n\n IceParameter::Pwd(\"T0teqPLNQQOf+5W+ls+P2p16\".into()),\n\n print\n\n );\n\n assert_line!(\n\n ice_parameter_line,\n\n \"a=ice-ufrag:x+m/\",\n\n IceParameter::Ufrag(\"x+m/\".into()),\n\n print\n\n );\n\n assert_line!(\n", "file_path": "src/attributes/ice.rs", "rank": 87, "score": 36956.19232429251 }, { "content": "#[test]\n\nfn test_setup_role() {\n\n assert_line!(read_setup_role, \"active\", SetupRole::Active);\n\n assert_line!(read_setup_role, \"passive\", SetupRole::Passive);\n\n}\n\n\n", "file_path": "src/attributes/dtls.rs", "rank": 88, "score": 36956.19232429251 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn test_read_val() {\n\n assert_line!(read_val, \"trr-int 100\", FbVal::TrrInt(100), print);\n\n assert_line!(read_val, \"ack sli\", FbVal::Ack(FbAckParam::Sli(None)), print);\n\n assert_line!(read_val, \"ack sli 5432\", FbVal::Ack(FbAckParam::Sli(Some(\"5432\".into()))), print);\n\n assert_line!(read_val, \"nack rpsi\", FbVal::Nack(FbNackParam::Rpsi), print);\n\n assert_line!(read_val, \"goog-remb\", FbVal:: RtcpFbId{id: \"goog-remb\".into(), param: None}, print);\n\n assert_line!(read_val, \"ccm\", FbVal:: RtcpFbId{id: \"ccm\".into(), param: None}, print);\n\n assert_line!(read_val, \"ccm fir\", FbVal:: RtcpFbId{id: \"ccm\".into(), param: Some(FbParam::Single(\"fir\".into()))}, print);\n\n assert_line!(read_val, \"fb foo bar\", FbVal:: RtcpFbId{id: \"fb\".into(), param: Some(FbParam::Pair(\"foo\".into(), \"bar\".into()))}, print);\n\n}\n\n\n", "file_path": "src/attributes/rtcp.rs", "rank": 89, "score": 36956.19232429251 }, { "content": "#[test]\n\nfn test_read_p_time() {\n\n assert_line!(read_p_time, \"a=ptime:1\", PTime::PTime(1), print);\n\n assert_line!(read_p_time, \"a=minptime:20\", PTime::MinPTime(20), print);\n\n assert_line!(read_p_time, \"a=maxptime:120\", PTime::MaxPTime(120), print);\n\n}\n\n\n\n/// RtpMap\n\n/// `a=rtpmap:<payload type> <encoding name>/<clock rate> [/<encoding` parameters>]\n\n///<https://tools.ietf.org/html/rfc4566#section-6>\n\n#[derive(Clone, IntoOwned, PartialEq)]\n\n#[cfg_attr(feature = \"debug\", derive(Debug))]\n\n#[cfg_attr(\n\n feature = \"serde\",\n\n derive(serde::Serialize, serde::Deserialize),\n\n serde(rename_all = \"camelCase\")\n\n)]\n\npub struct RtpMap<'a> {\n\n pub payload: u32,\n\n pub encoding_name: Cow<'a, str>,\n\n pub clock_rate: Option<u32>,\n\n pub encoding: Option<u32>,\n\n}\n\n\n", "file_path": "src/attributes/rtpmap.rs", "rank": 90, "score": 36956.19232429251 }, { "content": "fn write_ln_option<W>(\n\n f: &mut Formatter<'_, W>,\n\n content: &Option<impl ufmt::uDisplay>,\n\n) -> Result<(), W::Error>\n\nwhere\n\n W: uWrite + ?Sized,\n\n{\n\n if let Some(ref x) = content {\n\n uwriteln!(f, \"{}\", x)?;\n\n }\n\n Ok(())\n\n}\n\n\n\nimpl ufmt::uDisplay for MediaSection<'_> {\n\n fn fmt<W>(&self, f: &mut Formatter<'_, W>) -> Result<(), W::Error>\n\n where\n\n W: uWrite + ?Sized,\n\n {\n\n uwriteln!(f, \"{}\", self.media())?;\n\n\n", "file_path": "src/udisplay.rs", "rank": 91, "score": 36112.482763562046 }, { "content": "fn main() {\n\n let content = read_from_args().unwrap();\n\n for line in sdp_lines(&content).filter(|line| {\n\n line.as_attribute()\n\n .and_then(|a| a.as_candidate())\n\n .map(|candidate| candidate.protocol != CandidateProtocol::Tcp)\n\n .unwrap_or(true)\n\n }) {\n\n cfg_if::cfg_if! {\n\n if #[cfg(feature = \"serde\")] {\n\n println!(\"{}\", serde_json::to_string_pretty(&line).unwrap());\n\n } else {\n\n println!(\"{}\", ufmt_to_string(&line));\n\n }\n\n }\n\n }\n\n}\n", "file_path": "examples/remove_direct_tcp_candidates_iter.rs", "rank": 92, "score": 35879.48670491481 }, { "content": "#[test]\n\n#[cfg(feature = \"udisplay\")]\n\nfn parse_fixtures_order_preserving() {\n\n with_all_fixtures(&[\"order_preserving\"], |path| {\n\n let fixture = std::fs::read_to_string(&path).unwrap();\n\n let session = Session::read_str(&fixture);\n\n eprintln!(\"parsed\\n{:#?}\", session);\n\n\n\n let reserialized = session.to_string();\n\n eprintln!(\"reserialized\\n{}\", reserialized);\n\n let reparsed = Session::read_str(&reserialized);\n\n\n\n eprintln!(\"fixture: {:?}\", path.display());\n\n pretty_assertions::assert_eq!(fixture, reserialized);\n\n pretty_assertions::assert_eq!(session, reparsed);\n\n })\n\n .unwrap();\n\n}\n\n\n", "file_path": "tests/parse_fixtures.rs", "rank": 93, "score": 35879.48670491481 }, { "content": "#[test]\n\n#[cfg(feature = \"udisplay\")]\n\nfn parse_fixtures_sdp_transform() {\n\n with_all_fixtures(&[\"sdp_transform\"], |path| {\n\n let fixture = std::fs::read_to_string(&path).unwrap();\n\n let session = Session::read_str(&fixture);\n\n eprintln!(\"parsed\\n{:#?}\", session);\n\n\n\n let reserialized = session.to_string();\n\n eprintln!(\"reserialized\\n{}\", reserialized);\n\n let reparsed = Session::read_str(&reserialized);\n\n\n\n eprintln!(\"fixture: {:?}\", path.display());\n\n pretty_assertions::assert_eq!(session, reparsed);\n\n })\n\n .unwrap();\n\n}\n\n\n", "file_path": "tests/parse_fixtures.rs", "rank": 94, "score": 35879.48670491481 }, { "content": "#[test]\n\nfn test_rtcpfb_ack_param() {\n\n assert_line!(read_ack_param, \"sli\", FbAckParam::Sli(None));\n\n assert_line!(\n\n read_ack_param,\n\n \"sli 5432\",\n\n FbAckParam::Sli(Some(\"5432\".into()))\n\n );\n\n}\n\n\n\n#[derive(Clone, IntoOwned, PartialEq)]\n\n#[cfg_attr(feature = \"debug\", derive(Debug))]\n\n#[cfg_attr(\n\n feature = \"serde\",\n\n derive(serde::Serialize, serde::Deserialize),\n\n serde(rename_all = \"camelCase\")\n\n)]\n\n#[non_exhaustive]\n\npub enum FbNackParam<'a> {\n\n Pli,\n\n Sli,\n\n Rpsi,\n\n App(Cow<'a, str>),\n\n Other(Cow<'a, str>, Cow<'a, str>),\n\n}\n\n\n", "file_path": "src/attributes/rtcp.rs", "rank": 95, "score": 35879.48670491481 }, { "content": "fn read_from_args() -> Option<String> {\n\n if let Some(arg) = std::env::args().nth(1) {\n\n if let Ok(content) = std::fs::read_to_string(arg) {\n\n Some(content)\n\n } else {\n\n None\n\n }\n\n } else {\n\n println!(\"no input! please pass a file path as first parameter\");\n\n None\n\n }\n\n}\n\n\n", "file_path": "examples/iter.rs", "rank": 96, "score": 35382.88861425811 }, { "content": "fn read_from_args() -> Option<String> {\n\n if let Some(arg) = std::env::args().nth(1) {\n\n std::fs::read_to_string(arg).ok()\n\n } else {\n\n println!(\"no input! please pass a file path as first parameter\");\n\n None\n\n }\n\n}\n\n\n", "file_path": "examples/reparse.rs", "rank": 97, "score": 35382.88861425811 }, { "content": "#[test]\n\n#[cfg(feature = \"udisplay\")]\n\nfn parse_fixtures_sdp_transform_lazy() {\n\n with_all_fixtures(&[\"sdp_transform\"], |path| {\n\n let fixture = std::fs::read_to_string(&path).unwrap();\n\n let parsed_lines = sdp_lines_all(&fixture)\n\n .map(|res| {\n\n eprintln!(\"fixture: {:?}\", path.display());\n\n let (remainder, line) = res.unwrap();\n\n if !remainder.is_empty() {\n\n eprintln!(\"🙈 remainder {:?}\", remainder);\n\n }\n\n line\n\n })\n\n .collect::<Vec<_>>();\n\n // eprintln!(\"parsed\\n{:#?}\", session);\n\n\n\n let reserialized_lines = parsed_lines\n\n .iter()\n\n .map(ToString::to_string)\n\n .collect::<String>();\n\n // eprintln!(\"reserialized\\n{}\", reserialized);\n\n let reparsed_lines = sdp_lines(&reserialized_lines).collect::<Vec<_>>();\n\n\n\n eprintln!(\"fixture: {:?}\", path.display());\n\n pretty_assertions::assert_eq!(parsed_lines, reparsed_lines);\n\n })\n\n .unwrap();\n\n}\n", "file_path": "tests/parse_fixtures.rs", "rank": 98, "score": 34890.6040862452 }, { "content": "fn read_from_args() -> Option<Session<'static>> {\n\n if let Some(arg) = std::env::args().nth(1) {\n\n if let Ok(content) = std::fs::read_to_string(arg) {\n\n Some(Session::read_str(&content).into_owned())\n\n } else {\n\n None\n\n }\n\n } else {\n\n println!(\"no input! please pass a file path as first parameter\");\n\n None\n\n }\n\n}\n\n\n", "file_path": "examples/session.rs", "rank": 99, "score": 33669.01886565359 } ]
Rust
lib/codegen/src/ir/types.rs
gmorenz/cretonne
bcf6a058841bde1f773e5a30bdaff71224d0b99a
use std::default::Default; use std::fmt::{self, Debug, Display, Formatter}; #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct Type(u8); pub const VOID: Type = Type(0); const LANE_BASE: u8 = 0x70; const VECTOR_BASE: u8 = LANE_BASE + 16; include!(concat!(env!("OUT_DIR"), "/types.rs")); impl Type { pub fn lane_type(self) -> Type { if self.0 < VECTOR_BASE { self } else { Type(LANE_BASE | (self.0 & 0x0f)) } } pub fn log2_lane_bits(self) -> u8 { match self.lane_type() { B1 => 0, B8 | I8 => 3, B16 | I16 => 4, B32 | I32 | F32 => 5, B64 | I64 | F64 => 6, _ => 0, } } pub fn lane_bits(self) -> u8 { match self.lane_type() { B1 => 1, B8 | I8 => 8, B16 | I16 => 16, B32 | I32 | F32 => 32, B64 | I64 | F64 => 64, _ => 0, } } pub fn int(bits: u16) -> Option<Type> { match bits { 8 => Some(I8), 16 => Some(I16), 32 => Some(I32), 64 => Some(I64), _ => None, } } fn replace_lanes(self, lane: Type) -> Type { debug_assert!(lane.is_lane() && !self.is_special()); Type((lane.0 & 0x0f) | (self.0 & 0xf0)) } pub fn as_bool_pedantic(self) -> Type { self.replace_lanes(match self.lane_type() { B8 | I8 => B8, B16 | I16 => B16, B32 | I32 | F32 => B32, B64 | I64 | F64 => B64, _ => B1, }) } pub fn as_bool(self) -> Type { if !self.is_vector() { B1 } else { self.as_bool_pedantic() } } pub fn half_width(self) -> Option<Type> { Some(self.replace_lanes(match self.lane_type() { I16 => I8, I32 => I16, I64 => I32, F64 => F32, B16 => B8, B32 => B16, B64 => B32, _ => return None, })) } pub fn double_width(self) -> Option<Type> { Some(self.replace_lanes(match self.lane_type() { I8 => I16, I16 => I32, I32 => I64, F32 => F64, B8 => B16, B16 => B32, B32 => B64, _ => return None, })) } pub fn is_void(self) -> bool { self == VOID } pub fn is_special(self) -> bool { self.0 < LANE_BASE } pub fn is_lane(self) -> bool { LANE_BASE <= self.0 && self.0 < VECTOR_BASE } pub fn is_vector(self) -> bool { self.0 >= VECTOR_BASE } pub fn is_bool(self) -> bool { match self { B1 | B8 | B16 | B32 | B64 => true, _ => false, } } pub fn is_int(self) -> bool { match self { I8 | I16 | I32 | I64 => true, _ => false, } } pub fn is_float(self) -> bool { match self { F32 | F64 => true, _ => false, } } pub fn is_flags(self) -> bool { match self { IFLAGS | FFLAGS => true, _ => false, } } pub fn log2_lane_count(self) -> u8 { self.0.saturating_sub(LANE_BASE) >> 4 } pub fn lane_count(self) -> u16 { 1 << self.log2_lane_count() } pub fn bits(self) -> u16 { u16::from(self.lane_bits()) * self.lane_count() } pub fn bytes(self) -> u32 { (u32::from(self.bits()) + 7) / 8 } pub fn by(self, n: u16) -> Option<Type> { if self.lane_bits() == 0 || !n.is_power_of_two() { return None; } let log2_lanes: u32 = n.trailing_zeros(); let new_type = u32::from(self.0) + (log2_lanes << 4); if new_type < 0x100 { Some(Type(new_type as u8)) } else { None } } pub fn half_vector(self) -> Option<Type> { if self.is_vector() { Some(Type(self.0 - 0x10)) } else { None } } pub fn index(self) -> usize { usize::from(self.0) } pub fn wider_or_equal(self, other: Type) -> bool { self.lane_count() == other.lane_count() && self.lane_bits() >= other.lane_bits() } } impl Display for Type { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.is_bool() { write!(f, "b{}", self.lane_bits()) } else if self.is_int() { write!(f, "i{}", self.lane_bits()) } else if self.is_float() { write!(f, "f{}", self.lane_bits()) } else if self.is_vector() { write!(f, "{}x{}", self.lane_type(), self.lane_count()) } else { f.write_str(match *self { VOID => "void", IFLAGS => "iflags", FFLAGS => "fflags", _ => panic!("Invalid Type(0x{:x})", self.0), }) } } } impl Debug for Type { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.is_bool() { write!(f, "types::B{}", self.lane_bits()) } else if self.is_int() { write!(f, "types::I{}", self.lane_bits()) } else if self.is_float() { write!(f, "types::F{}", self.lane_bits()) } else if self.is_vector() { write!(f, "{:?}X{}", self.lane_type(), self.lane_count()) } else { match *self { VOID => write!(f, "types::VOID"), IFLAGS => write!(f, "types::IFLAGS"), FFLAGS => write!(f, "types::FFLAGS"), _ => write!(f, "Type(0x{:x})", self.0), } } } } impl Default for Type { fn default() -> Self { VOID } } #[cfg(test)] mod tests { use super::*; use std::string::ToString; #[test] fn basic_scalars() { assert_eq!(VOID, VOID.lane_type()); assert_eq!(0, VOID.bits()); assert_eq!(IFLAGS, IFLAGS.lane_type()); assert_eq!(0, IFLAGS.bits()); assert_eq!(FFLAGS, FFLAGS.lane_type()); assert_eq!(0, FFLAGS.bits()); assert_eq!(B1, B1.lane_type()); assert_eq!(B8, B8.lane_type()); assert_eq!(B16, B16.lane_type()); assert_eq!(B32, B32.lane_type()); assert_eq!(B64, B64.lane_type()); assert_eq!(I8, I8.lane_type()); assert_eq!(I16, I16.lane_type()); assert_eq!(I32, I32.lane_type()); assert_eq!(I64, I64.lane_type()); assert_eq!(F32, F32.lane_type()); assert_eq!(F64, F64.lane_type()); assert_eq!(VOID.lane_bits(), 0); assert_eq!(IFLAGS.lane_bits(), 0); assert_eq!(FFLAGS.lane_bits(), 0); assert_eq!(B1.lane_bits(), 1); assert_eq!(B8.lane_bits(), 8); assert_eq!(B16.lane_bits(), 16); assert_eq!(B32.lane_bits(), 32); assert_eq!(B64.lane_bits(), 64); assert_eq!(I8.lane_bits(), 8); assert_eq!(I16.lane_bits(), 16); assert_eq!(I32.lane_bits(), 32); assert_eq!(I64.lane_bits(), 64); assert_eq!(F32.lane_bits(), 32); assert_eq!(F64.lane_bits(), 64); } #[test] fn typevar_functions() { assert_eq!(VOID.half_width(), None); assert_eq!(IFLAGS.half_width(), None); assert_eq!(FFLAGS.half_width(), None); assert_eq!(B1.half_width(), None); assert_eq!(B8.half_width(), None); assert_eq!(B16.half_width(), Some(B8)); assert_eq!(B32.half_width(), Some(B16)); assert_eq!(B64.half_width(), Some(B32)); assert_eq!(I8.half_width(), None); assert_eq!(I16.half_width(), Some(I8)); assert_eq!(I32.half_width(), Some(I16)); assert_eq!(I32X4.half_width(), Some(I16X4)); assert_eq!(I64.half_width(), Some(I32)); assert_eq!(F32.half_width(), None); assert_eq!(F64.half_width(), Some(F32)); assert_eq!(VOID.double_width(), None); assert_eq!(IFLAGS.double_width(), None); assert_eq!(FFLAGS.double_width(), None); assert_eq!(B1.double_width(), None); assert_eq!(B8.double_width(), Some(B16)); assert_eq!(B16.double_width(), Some(B32)); assert_eq!(B32.double_width(), Some(B64)); assert_eq!(B64.double_width(), None); assert_eq!(I8.double_width(), Some(I16)); assert_eq!(I16.double_width(), Some(I32)); assert_eq!(I32.double_width(), Some(I64)); assert_eq!(I32X4.double_width(), Some(I64X4)); assert_eq!(I64.double_width(), None); assert_eq!(F32.double_width(), Some(F64)); assert_eq!(F64.double_width(), None); } #[test] fn vectors() { let big = F64.by(256).unwrap(); assert_eq!(big.lane_bits(), 64); assert_eq!(big.lane_count(), 256); assert_eq!(big.bits(), 64 * 256); assert_eq!(big.half_vector().unwrap().to_string(), "f64x128"); assert_eq!(B1.by(2).unwrap().half_vector().unwrap().to_string(), "b1"); assert_eq!(I32.half_vector(), None); assert_eq!(VOID.half_vector(), None); assert_eq!(I32.by(4), Some(I32X4)); assert_eq!(F64.by(8), Some(F64X8)); } #[test] fn format_scalars() { assert_eq!(VOID.to_string(), "void"); assert_eq!(IFLAGS.to_string(), "iflags"); assert_eq!(FFLAGS.to_string(), "fflags"); assert_eq!(B1.to_string(), "b1"); assert_eq!(B8.to_string(), "b8"); assert_eq!(B16.to_string(), "b16"); assert_eq!(B32.to_string(), "b32"); assert_eq!(B64.to_string(), "b64"); assert_eq!(I8.to_string(), "i8"); assert_eq!(I16.to_string(), "i16"); assert_eq!(I32.to_string(), "i32"); assert_eq!(I64.to_string(), "i64"); assert_eq!(F32.to_string(), "f32"); assert_eq!(F64.to_string(), "f64"); } #[test] fn format_vectors() { assert_eq!(B1.by(8).unwrap().to_string(), "b1x8"); assert_eq!(B8.by(1).unwrap().to_string(), "b8"); assert_eq!(B16.by(256).unwrap().to_string(), "b16x256"); assert_eq!(B32.by(4).unwrap().by(2).unwrap().to_string(), "b32x8"); assert_eq!(B64.by(8).unwrap().to_string(), "b64x8"); assert_eq!(I8.by(64).unwrap().to_string(), "i8x64"); assert_eq!(F64.by(2).unwrap().to_string(), "f64x2"); assert_eq!(I8.by(3), None); assert_eq!(I8.by(512), None); assert_eq!(VOID.by(4), None); } #[test] fn as_bool() { assert_eq!(I32X4.as_bool(), B32X4); assert_eq!(I32.as_bool(), B1); assert_eq!(I32X4.as_bool_pedantic(), B32X4); assert_eq!(I32.as_bool_pedantic(), B32); } }
use std::default::Default; use std::fmt::{self, Debug, Display, Formatter}; #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct Type(u8); pub const VOID: Type = Type(0); const LANE_BASE: u8 = 0x70; const VECTOR_BASE: u8 = LANE_BASE + 16; include!(concat!(env!("OUT_DIR"), "/types.rs")); impl Type { pub fn lane_type(self) -> Typ
pub fn log2_lane_bits(self) -> u8 { match self.lane_type() { B1 => 0, B8 | I8 => 3, B16 | I16 => 4, B32 | I32 | F32 => 5, B64 | I64 | F64 => 6, _ => 0, } } pub fn lane_bits(self) -> u8 { match self.lane_type() { B1 => 1, B8 | I8 => 8, B16 | I16 => 16, B32 | I32 | F32 => 32, B64 | I64 | F64 => 64, _ => 0, } } pub fn int(bits: u16) -> Option<Type> { match bits { 8 => Some(I8), 16 => Some(I16), 32 => Some(I32), 64 => Some(I64), _ => None, } } fn replace_lanes(self, lane: Type) -> Type { debug_assert!(lane.is_lane() && !self.is_special()); Type((lane.0 & 0x0f) | (self.0 & 0xf0)) } pub fn as_bool_pedantic(self) -> Type { self.replace_lanes(match self.lane_type() { B8 | I8 => B8, B16 | I16 => B16, B32 | I32 | F32 => B32, B64 | I64 | F64 => B64, _ => B1, }) } pub fn as_bool(self) -> Type { if !self.is_vector() { B1 } else { self.as_bool_pedantic() } } pub fn half_width(self) -> Option<Type> { Some(self.replace_lanes(match self.lane_type() { I16 => I8, I32 => I16, I64 => I32, F64 => F32, B16 => B8, B32 => B16, B64 => B32, _ => return None, })) } pub fn double_width(self) -> Option<Type> { Some(self.replace_lanes(match self.lane_type() { I8 => I16, I16 => I32, I32 => I64, F32 => F64, B8 => B16, B16 => B32, B32 => B64, _ => return None, })) } pub fn is_void(self) -> bool { self == VOID } pub fn is_special(self) -> bool { self.0 < LANE_BASE } pub fn is_lane(self) -> bool { LANE_BASE <= self.0 && self.0 < VECTOR_BASE } pub fn is_vector(self) -> bool { self.0 >= VECTOR_BASE } pub fn is_bool(self) -> bool { match self { B1 | B8 | B16 | B32 | B64 => true, _ => false, } } pub fn is_int(self) -> bool { match self { I8 | I16 | I32 | I64 => true, _ => false, } } pub fn is_float(self) -> bool { match self { F32 | F64 => true, _ => false, } } pub fn is_flags(self) -> bool { match self { IFLAGS | FFLAGS => true, _ => false, } } pub fn log2_lane_count(self) -> u8 { self.0.saturating_sub(LANE_BASE) >> 4 } pub fn lane_count(self) -> u16 { 1 << self.log2_lane_count() } pub fn bits(self) -> u16 { u16::from(self.lane_bits()) * self.lane_count() } pub fn bytes(self) -> u32 { (u32::from(self.bits()) + 7) / 8 } pub fn by(self, n: u16) -> Option<Type> { if self.lane_bits() == 0 || !n.is_power_of_two() { return None; } let log2_lanes: u32 = n.trailing_zeros(); let new_type = u32::from(self.0) + (log2_lanes << 4); if new_type < 0x100 { Some(Type(new_type as u8)) } else { None } } pub fn half_vector(self) -> Option<Type> { if self.is_vector() { Some(Type(self.0 - 0x10)) } else { None } } pub fn index(self) -> usize { usize::from(self.0) } pub fn wider_or_equal(self, other: Type) -> bool { self.lane_count() == other.lane_count() && self.lane_bits() >= other.lane_bits() } } impl Display for Type { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.is_bool() { write!(f, "b{}", self.lane_bits()) } else if self.is_int() { write!(f, "i{}", self.lane_bits()) } else if self.is_float() { write!(f, "f{}", self.lane_bits()) } else if self.is_vector() { write!(f, "{}x{}", self.lane_type(), self.lane_count()) } else { f.write_str(match *self { VOID => "void", IFLAGS => "iflags", FFLAGS => "fflags", _ => panic!("Invalid Type(0x{:x})", self.0), }) } } } impl Debug for Type { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.is_bool() { write!(f, "types::B{}", self.lane_bits()) } else if self.is_int() { write!(f, "types::I{}", self.lane_bits()) } else if self.is_float() { write!(f, "types::F{}", self.lane_bits()) } else if self.is_vector() { write!(f, "{:?}X{}", self.lane_type(), self.lane_count()) } else { match *self { VOID => write!(f, "types::VOID"), IFLAGS => write!(f, "types::IFLAGS"), FFLAGS => write!(f, "types::FFLAGS"), _ => write!(f, "Type(0x{:x})", self.0), } } } } impl Default for Type { fn default() -> Self { VOID } } #[cfg(test)] mod tests { use super::*; use std::string::ToString; #[test] fn basic_scalars() { assert_eq!(VOID, VOID.lane_type()); assert_eq!(0, VOID.bits()); assert_eq!(IFLAGS, IFLAGS.lane_type()); assert_eq!(0, IFLAGS.bits()); assert_eq!(FFLAGS, FFLAGS.lane_type()); assert_eq!(0, FFLAGS.bits()); assert_eq!(B1, B1.lane_type()); assert_eq!(B8, B8.lane_type()); assert_eq!(B16, B16.lane_type()); assert_eq!(B32, B32.lane_type()); assert_eq!(B64, B64.lane_type()); assert_eq!(I8, I8.lane_type()); assert_eq!(I16, I16.lane_type()); assert_eq!(I32, I32.lane_type()); assert_eq!(I64, I64.lane_type()); assert_eq!(F32, F32.lane_type()); assert_eq!(F64, F64.lane_type()); assert_eq!(VOID.lane_bits(), 0); assert_eq!(IFLAGS.lane_bits(), 0); assert_eq!(FFLAGS.lane_bits(), 0); assert_eq!(B1.lane_bits(), 1); assert_eq!(B8.lane_bits(), 8); assert_eq!(B16.lane_bits(), 16); assert_eq!(B32.lane_bits(), 32); assert_eq!(B64.lane_bits(), 64); assert_eq!(I8.lane_bits(), 8); assert_eq!(I16.lane_bits(), 16); assert_eq!(I32.lane_bits(), 32); assert_eq!(I64.lane_bits(), 64); assert_eq!(F32.lane_bits(), 32); assert_eq!(F64.lane_bits(), 64); } #[test] fn typevar_functions() { assert_eq!(VOID.half_width(), None); assert_eq!(IFLAGS.half_width(), None); assert_eq!(FFLAGS.half_width(), None); assert_eq!(B1.half_width(), None); assert_eq!(B8.half_width(), None); assert_eq!(B16.half_width(), Some(B8)); assert_eq!(B32.half_width(), Some(B16)); assert_eq!(B64.half_width(), Some(B32)); assert_eq!(I8.half_width(), None); assert_eq!(I16.half_width(), Some(I8)); assert_eq!(I32.half_width(), Some(I16)); assert_eq!(I32X4.half_width(), Some(I16X4)); assert_eq!(I64.half_width(), Some(I32)); assert_eq!(F32.half_width(), None); assert_eq!(F64.half_width(), Some(F32)); assert_eq!(VOID.double_width(), None); assert_eq!(IFLAGS.double_width(), None); assert_eq!(FFLAGS.double_width(), None); assert_eq!(B1.double_width(), None); assert_eq!(B8.double_width(), Some(B16)); assert_eq!(B16.double_width(), Some(B32)); assert_eq!(B32.double_width(), Some(B64)); assert_eq!(B64.double_width(), None); assert_eq!(I8.double_width(), Some(I16)); assert_eq!(I16.double_width(), Some(I32)); assert_eq!(I32.double_width(), Some(I64)); assert_eq!(I32X4.double_width(), Some(I64X4)); assert_eq!(I64.double_width(), None); assert_eq!(F32.double_width(), Some(F64)); assert_eq!(F64.double_width(), None); } #[test] fn vectors() { let big = F64.by(256).unwrap(); assert_eq!(big.lane_bits(), 64); assert_eq!(big.lane_count(), 256); assert_eq!(big.bits(), 64 * 256); assert_eq!(big.half_vector().unwrap().to_string(), "f64x128"); assert_eq!(B1.by(2).unwrap().half_vector().unwrap().to_string(), "b1"); assert_eq!(I32.half_vector(), None); assert_eq!(VOID.half_vector(), None); assert_eq!(I32.by(4), Some(I32X4)); assert_eq!(F64.by(8), Some(F64X8)); } #[test] fn format_scalars() { assert_eq!(VOID.to_string(), "void"); assert_eq!(IFLAGS.to_string(), "iflags"); assert_eq!(FFLAGS.to_string(), "fflags"); assert_eq!(B1.to_string(), "b1"); assert_eq!(B8.to_string(), "b8"); assert_eq!(B16.to_string(), "b16"); assert_eq!(B32.to_string(), "b32"); assert_eq!(B64.to_string(), "b64"); assert_eq!(I8.to_string(), "i8"); assert_eq!(I16.to_string(), "i16"); assert_eq!(I32.to_string(), "i32"); assert_eq!(I64.to_string(), "i64"); assert_eq!(F32.to_string(), "f32"); assert_eq!(F64.to_string(), "f64"); } #[test] fn format_vectors() { assert_eq!(B1.by(8).unwrap().to_string(), "b1x8"); assert_eq!(B8.by(1).unwrap().to_string(), "b8"); assert_eq!(B16.by(256).unwrap().to_string(), "b16x256"); assert_eq!(B32.by(4).unwrap().by(2).unwrap().to_string(), "b32x8"); assert_eq!(B64.by(8).unwrap().to_string(), "b64x8"); assert_eq!(I8.by(64).unwrap().to_string(), "i8x64"); assert_eq!(F64.by(2).unwrap().to_string(), "f64x2"); assert_eq!(I8.by(3), None); assert_eq!(I8.by(512), None); assert_eq!(VOID.by(4), None); } #[test] fn as_bool() { assert_eq!(I32X4.as_bool(), B32X4); assert_eq!(I32.as_bool(), B1); assert_eq!(I32X4.as_bool_pedantic(), B32X4); assert_eq!(I32.as_bool_pedantic(), B32); } }
e { if self.0 < VECTOR_BASE { self } else { Type(LANE_BASE | (self.0 & 0x0f)) } }
function_block-function_prefixed
[ { "content": "/// Look for `key` in `table`.\n\n///\n\n/// The provided `hash` value must have been computed from `key` using the same hash function that\n\n/// was used to construct the table.\n\n///\n\n/// Returns `Ok(idx)` with the table index containing the found entry, or `Err(idx)` with the empty\n\n/// sentinel entry if no entry could be found.\n\npub fn probe<K: Copy + Eq, T: Table<K> + ?Sized>(\n\n table: &T,\n\n key: K,\n\n hash: usize,\n\n) -> Result<usize, usize> {\n\n debug_assert!(table.len().is_power_of_two());\n\n let mask = table.len() - 1;\n\n\n\n let mut idx = hash;\n\n let mut step = 0;\n\n\n\n loop {\n\n idx &= mask;\n\n\n\n match table.key(idx) {\n\n None => return Err(idx),\n\n Some(k) if k == key => return Ok(idx),\n\n _ => {}\n\n }\n\n\n\n // Quadratic probing.\n\n step += 1;\n\n // When `table.len()` is a power of two, it can be proven that `idx` will visit all\n\n // entries. This means that this loop will always terminate if the hash table has even\n\n // one unused entry.\n\n debug_assert!(step < table.len());\n\n idx += step;\n\n }\n\n}\n\n\n", "file_path": "lib/codegen/src/constant_hash.rs", "rank": 0, "score": 218302.523497148 }, { "content": "/// Helper function translating wasmparser types to Cretonne types when possible.\n\npub fn type_to_type(ty: &wasmparser::Type) -> Result<ir::Type, ()> {\n\n match *ty {\n\n wasmparser::Type::I32 => Ok(ir::types::I32),\n\n wasmparser::Type::I64 => Ok(ir::types::I64),\n\n wasmparser::Type::F32 => Ok(ir::types::F32),\n\n wasmparser::Type::F64 => Ok(ir::types::F64),\n\n _ => Err(()),\n\n }\n\n}\n\n\n", "file_path": "lib/wasm/src/translation_utils.rs", "rank": 1, "score": 217788.556076516 }, { "content": "/// Get register class for a type appearing in a legalized signature.\n\npub fn regclass_for_abi_type(ty: Type) -> RegClass {\n\n if ty.is_float() { FPR } else { GPR }\n\n}\n\n\n", "file_path": "lib/codegen/src/isa/riscv/abi.rs", "rank": 2, "score": 211663.27817793126 }, { "content": "fn lookup_with_dlsym(name: &str) -> *const u8 {\n\n let c_str = CString::new(name).unwrap();\n\n let c_str_ptr = c_str.as_ptr();\n\n let sym = unsafe { libc::dlsym(libc::RTLD_DEFAULT, c_str_ptr) };\n\n if sym.is_null() {\n\n panic!(\"can't resolve symbol {}\", name);\n\n }\n\n sym as *const u8\n\n}\n\n\n", "file_path": "lib/simplejit/src/backend.rs", "rank": 3, "score": 210582.94317965565 }, { "content": "/// Get register class for a type appearing in a legalized signature.\n\npub fn regclass_for_abi_type(ty: ir::Type) -> RegClass {\n\n if ty.is_int() || ty.is_bool() {\n\n GPR\n\n } else {\n\n FPR\n\n }\n\n}\n\n\n", "file_path": "lib/codegen/src/isa/x86/abi.rs", "rank": 4, "score": 202797.10603482346 }, { "content": "/// Get register class for a type appearing in a legalized signature.\n\npub fn regclass_for_abi_type(ty: ir::Type) -> RegClass {\n\n if ty.is_int() {\n\n GPR\n\n } else {\n\n match ty.bits() {\n\n 32 => S,\n\n 64 => D,\n\n 128 => Q,\n\n _ => panic!(\"Unexpected {} ABI type for arm32\", ty),\n\n }\n\n }\n\n}\n\n\n", "file_path": "lib/codegen/src/isa/arm32/abi.rs", "rank": 5, "score": 202797.10603482346 }, { "content": "/// Get register class for a type appearing in a legalized signature.\n\npub fn regclass_for_abi_type(ty: ir::Type) -> RegClass {\n\n if ty.is_int() { GPR } else { FPR }\n\n}\n\n\n", "file_path": "lib/codegen/src/isa/arm64/abi.rs", "rank": 6, "score": 202797.10603482346 }, { "content": "/// A primitive hash function for matching opcodes.\n\n/// Must match `lib/codegen/meta/constant_hash.py`.\n\npub fn simple_hash(s: &str) -> usize {\n\n let mut h: u32 = 5381;\n\n for c in s.chars() {\n\n h = (h ^ c as u32).wrapping_add(h.rotate_right(6));\n\n }\n\n h as usize\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::simple_hash;\n\n\n\n #[test]\n\n fn basic() {\n\n // c.f. `meta/constant_hash.py` tests.\n\n assert_eq!(simple_hash(\"Hello\"), 0x2fa70c01);\n\n assert_eq!(simple_hash(\"world\"), 0x5b0c31d5);\n\n }\n\n}\n", "file_path": "lib/codegen/src/constant_hash.rs", "rank": 7, "score": 196827.9083729714 }, { "content": "/// Translate a `wasmparser` type into its `Cretonne` equivalent, when possible\n\npub fn num_return_values(ty: wasmparser::Type) -> usize {\n\n match ty {\n\n wasmparser::Type::EmptyBlockType => 0,\n\n wasmparser::Type::I32 |\n\n wasmparser::Type::F32 |\n\n wasmparser::Type::I64 |\n\n wasmparser::Type::F64 => 1,\n\n _ => panic!(\"unsupported return value type\"),\n\n }\n\n}\n", "file_path": "lib/wasm/src/translation_utils.rs", "rank": 8, "score": 194503.39176952047 }, { "content": "#[allow(dead_code)]\n\npub fn is_signed_int<T: Into<i64>>(x: T, wd: u8, sc: u8) -> bool {\n\n let s = x.into();\n\n s == (s >> sc << (64 - wd + sc) >> (64 - wd))\n\n}\n\n\n\n/// Check that `x` can be represented as a `wd`-bit unsigned integer with `sc` low zero bits.\n", "file_path": "lib/codegen/src/predicates.rs", "rank": 9, "score": 189850.26701097895 }, { "content": "#[allow(dead_code)]\n\npub fn is_unsigned_int<T: Into<i64>>(x: T, wd: u8, sc: u8) -> bool {\n\n let u = x.into() as u64;\n\n // Bit-mask of the permitted bits.\n\n let m = (1 << wd) - (1 << sc);\n\n u == (u & m)\n\n}\n\n\n", "file_path": "lib/codegen/src/predicates.rs", "rank": 10, "score": 189850.26701097895 }, { "content": "/// Determine the right action to take when passing a `have` value type to a call signature where\n\n/// the next argument is `arg` which has a different value type.\n\n///\n\n/// The signature legalization process in `legalize_args` above can replace a single argument value\n\n/// with multiple arguments of smaller types. It can also change the type of an integer argument to\n\n/// a larger integer type, requiring the smaller value to be sign- or zero-extended.\n\n///\n\n/// The legalizer needs to repair the values at all ABI boundaries:\n\n///\n\n/// - Incoming function arguments to the entry EBB.\n\n/// - Function arguments passed to a call.\n\n/// - Return values from a call.\n\n/// - Return values passed to a return instruction.\n\n///\n\n/// The `legalize_abi_value` function helps the legalizer with the process. When the legalizer\n\n/// needs to pass a pre-legalized `have` argument, but the ABI argument `arg` has a different value\n\n/// type, `legalize_abi_value(have, arg)` tells the legalizer how to create the needed value type\n\n/// for the argument.\n\n///\n\n/// It may be necessary to call `legalize_abi_value` more than once for a given argument before the\n\n/// desired argument type appears. This will happen when a vector or integer type needs to be split\n\n/// more than once, for example.\n\npub fn legalize_abi_value(have: Type, arg: &AbiParam) -> ValueConversion {\n\n let have_bits = have.bits();\n\n let arg_bits = arg.value_type.bits();\n\n\n\n match have_bits.cmp(&arg_bits) {\n\n // We have fewer bits than the ABI argument.\n\n Ordering::Less => {\n\n debug_assert!(\n\n have.is_int() && arg.value_type.is_int(),\n\n \"Can only extend integer values\"\n\n );\n\n match arg.extension {\n\n ArgumentExtension::Uext => ValueConversion::Uext(arg.value_type),\n\n ArgumentExtension::Sext => ValueConversion::Sext(arg.value_type),\n\n _ => panic!(\"No argument extension specified\"),\n\n }\n\n }\n\n // We have the same number of bits as the argument.\n\n Ordering::Equal => {\n\n // This must be an integer vector that is split and then extended.\n", "file_path": "lib/codegen/src/abi.rs", "rank": 11, "score": 186387.3288573107 }, { "content": "/// Trait that must be implemented by the entries in a constant hash table.\n\npub trait Table<K: Copy + Eq> {\n\n /// Get the number of entries in this table which must be a power of two.\n\n fn len(&self) -> usize;\n\n\n\n /// Get the key corresponding to the entry at `idx`, or `None` if the entry is empty.\n\n /// The `idx` must be in range.\n\n fn key(&self, idx: usize) -> Option<K>;\n\n}\n\n\n", "file_path": "lib/codegen/src/constant_hash.rs", "rank": 12, "score": 184981.06245916156 }, { "content": "/// Format a floating point number in a way that is reasonably human-readable, and that can be\n\n/// converted back to binary without any rounding issues. The hexadecimal formatting of normal and\n\n/// subnormal numbers is compatible with C99 and the `printf \"%a\"` format specifier. The NaN and Inf\n\n/// formats are not supported by C99.\n\n///\n\n/// The encoding parameters are:\n\n///\n\n/// w - exponent field width in bits\n\n/// t - trailing significand field width in bits\n\n///\n\nfn format_float(bits: u64, w: u8, t: u8, f: &mut Formatter) -> fmt::Result {\n\n debug_assert!(w > 0 && w <= 16, \"Invalid exponent range\");\n\n debug_assert!(1 + w + t <= 64, \"Too large IEEE format for u64\");\n\n debug_assert!((t + w + 1).is_power_of_two(), \"Unexpected IEEE format size\");\n\n\n\n let max_e_bits = (1u64 << w) - 1;\n\n let t_bits = bits & ((1u64 << t) - 1); // Trailing significand.\n\n let e_bits = (bits >> t) & max_e_bits; // Biased exponent.\n\n let sign_bit = (bits >> (w + t)) & 1;\n\n\n\n let bias: i32 = (1 << (w - 1)) - 1;\n\n let e = e_bits as i32 - bias; // Unbiased exponent.\n\n let emin = 1 - bias; // Minimum exponent.\n\n\n\n // How many hexadecimal digits are needed for the trailing significand?\n\n let digits = (t + 3) / 4;\n\n // Trailing significand left-aligned in `digits` hexadecimal digits.\n\n let left_t_bits = t_bits << (4 * digits - t);\n\n\n\n // All formats share the leading sign.\n", "file_path": "lib/codegen/src/ir/immediates.rs", "rank": 13, "score": 174055.85020704393 }, { "content": "pub fn run(\n\n files: Vec<String>,\n\n flag_print: bool,\n\n flag_set: &[String],\n\n flag_isa: &str,\n\n) -> Result<(), String> {\n\n let parsed = parse_sets_and_isa(flag_set, flag_isa)?;\n\n\n\n for filename in files {\n\n let path = Path::new(&filename);\n\n let name = String::from(path.as_os_str().to_string_lossy());\n\n handle_module(flag_print, &path.to_path_buf(), &name, parsed.as_fisa())?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/compile.rs", "rank": 14, "score": 173198.79739438015 }, { "content": "pub fn run(\n\n files: Vec<String>,\n\n flag_verbose: bool,\n\n flag_just_decode: bool,\n\n flag_check_translation: bool,\n\n flag_print: bool,\n\n flag_set: &[String],\n\n flag_isa: &str,\n\n flag_print_size: bool,\n\n) -> Result<(), String> {\n\n let parsed = parse_sets_and_isa(flag_set, flag_isa)?;\n\n\n\n for filename in files {\n\n let path = Path::new(&filename);\n\n let name = String::from(path.as_os_str().to_string_lossy());\n\n handle_module(\n\n flag_verbose,\n\n flag_just_decode,\n\n flag_check_translation,\n\n flag_print,\n\n flag_print_size,\n\n &path.to_path_buf(),\n\n &name,\n\n parsed.as_fisa(),\n\n )?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/wasm.rs", "rank": 15, "score": 173198.79739438015 }, { "content": "/// Read an entire file into a vector of bytes.\n\npub fn read_to_end<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {\n\n let mut file = File::open(path)?;\n\n let mut buffer = Vec::new();\n\n file.read_to_end(&mut buffer)?;\n\n Ok(buffer)\n\n}\n\n\n\n/// Like `FlagsOrIsa`, but holds ownership.\n\npub enum OwnedFlagsOrIsa {\n\n Flags(settings::Flags),\n\n Isa(Box<TargetIsa>),\n\n}\n\n\n\nimpl OwnedFlagsOrIsa {\n\n /// Produce a FlagsOrIsa reference.\n\n pub fn as_fisa(&self) -> FlagsOrIsa {\n\n match *self {\n\n OwnedFlagsOrIsa::Flags(ref flags) => FlagsOrIsa::from(flags),\n\n OwnedFlagsOrIsa::Isa(ref isa) => FlagsOrIsa::from(&**isa),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 16, "score": 171236.15015510772 }, { "content": "/// Performs the LICM pass by detecting loops within the CFG and moving\n\n/// loop-invariant instructions out of them.\n\n/// Changes the CFG and domtree in-place during the operation.\n\npub fn do_licm(\n\n func: &mut Function,\n\n cfg: &mut ControlFlowGraph,\n\n domtree: &mut DominatorTree,\n\n loop_analysis: &mut LoopAnalysis,\n\n) {\n\n let _tt = timing::licm();\n\n debug_assert!(cfg.is_valid());\n\n debug_assert!(domtree.is_valid());\n\n debug_assert!(loop_analysis.is_valid());\n\n\n\n for lp in loop_analysis.loops() {\n\n // For each loop that we want to optimize we determine the set of loop-invariant\n\n // instructions\n\n let invariant_insts = remove_loop_invariant_instructions(lp, func, cfg, loop_analysis);\n\n // Then we create the loop's pre-header and fill it with the invariant instructions\n\n // Then we remove the invariant instructions from the loop body\n\n if !invariant_insts.is_empty() {\n\n // If the loop has a natural pre-header we use it, otherwise we create it.\n\n let mut pos;\n", "file_path": "lib/codegen/src/licm.rs", "rank": 17, "score": 167628.36803084222 }, { "content": "/// Lists are allocated in sizes that are powers of two, starting from 4.\n\n/// Each power of two is assigned a size class number, so the size is `4 << SizeClass`.\n\ntype SizeClass = u8;\n\n\n", "file_path": "lib/entity/src/list.rs", "rank": 18, "score": 167002.4919985858 }, { "content": "/// Split `value` into halves using the `vsplit` semantics. Do this by reusing existing values if\n\n/// possible.\n\npub fn vsplit(\n\n func: &mut ir::Function,\n\n cfg: &ControlFlowGraph,\n\n pos: CursorPosition,\n\n srcloc: ir::SourceLoc,\n\n value: Value,\n\n) -> (Value, Value) {\n\n split_any(func, cfg, pos, srcloc, value, Opcode::Vconcat)\n\n}\n\n\n", "file_path": "lib/codegen/src/legalizer/split.rs", "rank": 19, "score": 165068.29863181832 }, { "content": "/// Split `value` into two values using the `isplit` semantics. Do this by reusing existing values\n\n/// if possible.\n\npub fn isplit(\n\n func: &mut ir::Function,\n\n cfg: &ControlFlowGraph,\n\n pos: CursorPosition,\n\n srcloc: ir::SourceLoc,\n\n value: Value,\n\n) -> (Value, Value) {\n\n split_any(func, cfg, pos, srcloc, value, Opcode::Iconcat)\n\n}\n\n\n", "file_path": "lib/codegen/src/legalizer/split.rs", "rank": 20, "score": 165068.24181228242 }, { "content": "/// Write the operands of `inst` to `w` with a prepended space.\n\npub fn write_operands(\n\n w: &mut Write,\n\n dfg: &DataFlowGraph,\n\n isa: Option<&TargetIsa>,\n\n inst: Inst,\n\n) -> Result {\n\n let pool = &dfg.value_lists;\n\n use ir::instructions::InstructionData::*;\n\n match dfg[inst] {\n\n Unary { arg, .. } => write!(w, \" {}\", arg),\n\n UnaryImm { imm, .. } => write!(w, \" {}\", imm),\n\n UnaryIeee32 { imm, .. } => write!(w, \" {}\", imm),\n\n UnaryIeee64 { imm, .. } => write!(w, \" {}\", imm),\n\n UnaryBool { imm, .. } => write!(w, \" {}\", imm),\n\n UnaryGlobalVar { global_var, .. } => write!(w, \" {}\", global_var),\n\n Binary { args, .. } => write!(w, \" {}, {}\", args[0], args[1]),\n\n BinaryImm { arg, imm, .. } => write!(w, \" {}, {}\", arg, imm),\n\n Ternary { args, .. } => write!(w, \" {}, {}, {}\", args[0], args[1], args[2]),\n\n MultiAry { ref args, .. } => {\n\n if args.is_empty() {\n", "file_path": "lib/codegen/src/write.rs", "rank": 21, "score": 165063.01348643197 }, { "content": "/// Verify that CPU flags are used correctly.\n\n///\n\n/// The value types `iflags` and `fflags` represent CPU flags which usually live in a\n\n/// special-purpose register, so they can't be used as freely as other value types that can live in\n\n/// any register.\n\n///\n\n/// We verify the following conditions:\n\n///\n\n/// - At most one flags value can be live at a time.\n\n/// - A flags value can not be live across an instruction that clobbers the flags.\n\n///\n\n///\n\npub fn verify_flags(\n\n func: &ir::Function,\n\n cfg: &ControlFlowGraph,\n\n isa: Option<&isa::TargetIsa>,\n\n) -> Result {\n\n let _tt = timing::verify_flags();\n\n let mut verifier = FlagsVerifier {\n\n func,\n\n cfg,\n\n encinfo: isa.map(|isa| isa.encoding_info()),\n\n livein: EntityMap::new(),\n\n };\n\n verifier.check()\n\n}\n\n\n", "file_path": "lib/codegen/src/verifier/flags.rs", "rank": 22, "score": 162639.7043143134 }, { "content": "/// Verify value locations for `func`.\n\n///\n\n/// After register allocation, every value must be assigned to a location - either a register or a\n\n/// stack slot. These locations must be compatible with the constraints described by the\n\n/// instruction encoding recipes.\n\n///\n\n/// Values can be temporarily diverted to a different location by using the `regmove`, `regspill`,\n\n/// and `regfill` instructions, but only inside an EBB.\n\n///\n\n/// If a liveness analysis is provided, it is used to verify that there are no active register\n\n/// diversions across control flow edges.\n\npub fn verify_locations(\n\n isa: &isa::TargetIsa,\n\n func: &ir::Function,\n\n liveness: Option<&Liveness>,\n\n) -> Result {\n\n let _tt = timing::verify_locations();\n\n let verifier = LocationVerifier {\n\n isa,\n\n func,\n\n reginfo: isa.register_info(),\n\n encinfo: isa.encoding_info(),\n\n liveness,\n\n };\n\n verifier.check_constraints()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "lib/codegen/src/verifier/locations.rs", "rank": 23, "score": 162634.2376968001 }, { "content": "/// Verify liveness information for `func`.\n\n///\n\n/// The provided control flow graph is assumed to be sound.\n\n///\n\n/// - All values in the program must have a live range.\n\n/// - The live range def point must match where the value is defined.\n\n/// - The live range must reach all uses.\n\n/// - When a live range is live-in to an EBB, it must be live at all the predecessors.\n\n/// - The live range affinity must be compatible with encoding constraints.\n\n///\n\n/// We don't verify that live ranges are minimal. This would require recomputing live ranges for\n\n/// all values.\n\npub fn verify_liveness(\n\n isa: &TargetIsa,\n\n func: &Function,\n\n cfg: &ControlFlowGraph,\n\n liveness: &Liveness,\n\n) -> Result {\n\n let _tt = timing::verify_liveness();\n\n let verifier = LivenessVerifier {\n\n isa,\n\n func,\n\n cfg,\n\n liveness,\n\n };\n\n verifier.check_ebbs()?;\n\n verifier.check_insts()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "lib/codegen/src/verifier/liveness.rs", "rank": 24, "score": 162632.8296852783 }, { "content": "/// Expand a `call` instruction.\n\npub fn expand_call(\n\n inst: ir::Inst,\n\n func: &mut ir::Function,\n\n _cfg: &mut ControlFlowGraph,\n\n isa: &TargetIsa,\n\n) {\n\n // Unpack the instruction.\n\n let (func_ref, old_args) = match func.dfg[inst] {\n\n ir::InstructionData::Call {\n\n opcode,\n\n ref args,\n\n func_ref,\n\n } => {\n\n debug_assert_eq!(opcode, ir::Opcode::Call);\n\n (func_ref, args.clone())\n\n }\n\n _ => panic!(\"Wanted call: {}\", func.dfg.display_inst(inst, None)),\n\n };\n\n\n\n let ptr_ty = if isa.flags().is_64bit() {\n", "file_path": "lib/codegen/src/legalizer/call.rs", "rank": 25, "score": 162629.20087599877 }, { "content": "/// Verify conventional SSA form for `func`.\n\n///\n\n/// Conventional SSA form is represented in Cretonne with the help of virtual registers:\n\n///\n\n/// - Two values are said to be *PHI-related* if one is an EBB argument and the other is passed as\n\n/// a branch argument in a location that matches the first value.\n\n/// - PHI-related values must belong to the same virtual register.\n\n/// - Two values in the same virtual register must not have overlapping live ranges.\n\n///\n\n/// Additionally, we verify this property of virtual registers:\n\n///\n\n/// - The values in a virtual register are topologically ordered w.r.t. dominance.\n\n///\n\n/// We don't verify that virtual registers are minimal. Minimal CSSA is not required.\n\npub fn verify_cssa(\n\n func: &Function,\n\n cfg: &ControlFlowGraph,\n\n domtree: &DominatorTree,\n\n liveness: &Liveness,\n\n virtregs: &VirtRegs,\n\n) -> Result {\n\n let _tt = timing::verify_cssa();\n\n\n\n let mut preorder = DominatorTreePreorder::new();\n\n preorder.compute(domtree, &func.layout);\n\n\n\n let verifier = CssaVerifier {\n\n func,\n\n cfg,\n\n domtree,\n\n virtregs,\n\n liveness,\n\n preorder,\n\n };\n\n verifier.check_virtregs()?;\n\n verifier.check_cssa()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "lib/codegen/src/verifier/cssa.rs", "rank": 26, "score": 162629.20087599877 }, { "content": "pub fn write_ebb_header(\n\n w: &mut Write,\n\n func: &Function,\n\n isa: Option<&TargetIsa>,\n\n ebb: Ebb,\n\n indent: usize,\n\n) -> Result {\n\n // Write out the basic block header, outdented:\n\n //\n\n // ebb1:\n\n // ebb1(v1: i32):\n\n // ebb10(v4: f64, v5: b1):\n\n //\n\n\n\n // The `indent` is the instruction indentation. EBB headers are 4 spaces out from that.\n\n write!(w, \"{1:0$}{2}\", indent - 4, \"\", ebb)?;\n\n\n\n let regs = isa.map(TargetIsa::register_info);\n\n let regs = regs.as_ref();\n\n\n", "file_path": "lib/codegen/src/write.rs", "rank": 27, "score": 162629.20087599877 }, { "content": "#[allow(dead_code)]\n\npub fn is_equal<T: Eq + Copy, O: Into<T> + Copy>(x: T, y: O) -> bool {\n\n x == y.into()\n\n}\n\n\n\n/// Check that `x` can be represented as a `wd`-bit signed integer with `sc` low zero bits.\n", "file_path": "lib/codegen/src/predicates.rs", "rank": 28, "score": 161150.3809811989 }, { "content": "/// Reads the Type Section of the wasm module and returns the corresponding function signatures.\n\npub fn parse_function_signatures(\n\n parser: &mut Parser,\n\n environ: &mut ModuleEnvironment,\n\n) -> Result<(), SectionParsingError> {\n\n loop {\n\n match *parser.read() {\n\n ParserState::EndSection => break,\n\n ParserState::TypeSectionEntry(FuncType {\n\n form: wasmparser::Type::Func,\n\n ref params,\n\n ref returns,\n\n }) => {\n\n let mut sig = Signature::new(CallConv::SystemV);\n\n sig.params.extend(params.iter().map(|ty| {\n\n let cret_arg: ir::Type = type_to_type(ty).expect(\n\n \"only numeric types are supported in function signatures\",\n\n );\n\n AbiParam::new(cret_arg)\n\n }));\n\n sig.returns.extend(returns.iter().map(|ty| {\n", "file_path": "lib/wasm/src/sections_translator.rs", "rank": 29, "score": 160322.51857994156 }, { "content": "/// Expand the stack check instruction.\n\npub fn expand_stack_check(\n\n inst: ir::Inst,\n\n func: &mut ir::Function,\n\n _cfg: &mut ControlFlowGraph,\n\n isa: &TargetIsa,\n\n) {\n\n use ir::condcodes::IntCC;\n\n\n\n let gv = match func.dfg[inst] {\n\n ir::InstructionData::UnaryGlobalVar { global_var, .. } => global_var,\n\n _ => panic!(\"Want stack_check: {}\", func.dfg.display_inst(inst, isa)),\n\n };\n\n let ptr_ty = if isa.flags().is_64bit() {\n\n ir::types::I64\n\n } else {\n\n ir::types::I32\n\n };\n\n\n\n let mut pos = FuncCursor::new(func).at_inst(inst);\n\n pos.use_srcloc(inst);\n", "file_path": "lib/codegen/src/legalizer/mod.rs", "rank": 30, "score": 160317.06562999648 }, { "content": "/// Expand a `global_addr` instruction according to the definition of the global variable.\n\npub fn expand_global_addr(\n\n inst: ir::Inst,\n\n func: &mut ir::Function,\n\n _cfg: &mut ControlFlowGraph,\n\n _isa: &TargetIsa,\n\n) {\n\n // Unpack the instruction.\n\n let gv = match func.dfg[inst] {\n\n ir::InstructionData::UnaryGlobalVar { opcode, global_var } => {\n\n debug_assert_eq!(opcode, ir::Opcode::GlobalAddr);\n\n global_var\n\n }\n\n _ => panic!(\"Wanted global_addr: {}\", func.dfg.display_inst(inst, None)),\n\n };\n\n\n\n match func.global_vars[gv] {\n\n ir::GlobalVarData::VMContext { offset } => vmctx_addr(inst, func, offset.into()),\n\n ir::GlobalVarData::Deref { base, offset } => deref_addr(inst, func, base, offset.into()),\n\n ir::GlobalVarData::Sym { .. } => globalsym(inst, func, gv),\n\n }\n\n}\n\n\n", "file_path": "lib/codegen/src/legalizer/globalvar.rs", "rank": 31, "score": 160317.06562999648 }, { "content": "/// Retrieves the size and maximum fields of memories from the memory section\n\npub fn parse_global_section(\n\n parser: &mut Parser,\n\n environ: &mut ModuleEnvironment,\n\n) -> Result<(), SectionParsingError> {\n\n loop {\n\n let (content_type, mutability) = match *parser.read() {\n\n ParserState::BeginGlobalSectionEntry(ref ty) => (ty.content_type, ty.mutable),\n\n ParserState::EndSection => break,\n\n ref s => return Err(SectionParsingError::WrongSectionContent(format!(\"{:?}\", s))),\n\n };\n\n match *parser.read() {\n\n ParserState::BeginInitExpressionBody => (),\n\n ref s => return Err(SectionParsingError::WrongSectionContent(format!(\"{:?}\", s))),\n\n }\n\n let initializer = match *parser.read() {\n\n ParserState::InitExpressionOperator(Operator::I32Const { value }) => {\n\n GlobalInit::I32Const(value)\n\n }\n\n ParserState::InitExpressionOperator(Operator::I64Const { value }) => {\n\n GlobalInit::I64Const(value)\n", "file_path": "lib/wasm/src/sections_translator.rs", "rank": 32, "score": 160317.06562999648 }, { "content": "/// Expand a `heap_addr` instruction according to the definition of the heap.\n\npub fn expand_heap_addr(\n\n inst: ir::Inst,\n\n func: &mut ir::Function,\n\n cfg: &mut ControlFlowGraph,\n\n _isa: &TargetIsa,\n\n) {\n\n // Unpack the instruction.\n\n let (heap, offset, size) = match func.dfg[inst] {\n\n ir::InstructionData::HeapAddr {\n\n opcode,\n\n heap,\n\n arg,\n\n imm,\n\n } => {\n\n debug_assert_eq!(opcode, ir::Opcode::HeapAddr);\n\n (heap, arg, imm.into())\n\n }\n\n _ => panic!(\"Wanted heap_addr: {}\", func.dfg.display_inst(inst, None)),\n\n };\n\n\n\n match func.heaps[heap].style {\n\n ir::HeapStyle::Dynamic { bound_gv } => {\n\n dynamic_addr(inst, heap, offset, size, bound_gv, func)\n\n }\n\n ir::HeapStyle::Static { bound } => {\n\n static_addr(inst, heap, offset, size, bound.into(), func, cfg)\n\n }\n\n }\n\n}\n\n\n", "file_path": "lib/codegen/src/legalizer/heap.rs", "rank": 33, "score": 160317.06562999648 }, { "content": "/// Legalize `sig`.\n\npub fn legalize_signature(\n\n _sig: &mut ir::Signature,\n\n _flags: &shared_settings::Flags,\n\n _current: bool,\n\n) {\n\n unimplemented!()\n\n}\n\n\n", "file_path": "lib/codegen/src/isa/arm64/abi.rs", "rank": 34, "score": 160317.06562999648 }, { "content": "/// Legalize `sig`.\n\npub fn legalize_signature(\n\n _sig: &mut ir::Signature,\n\n _flags: &shared_settings::Flags,\n\n _current: bool,\n\n) {\n\n unimplemented!()\n\n}\n\n\n", "file_path": "lib/codegen/src/isa/arm32/abi.rs", "rank": 35, "score": 160317.06562999648 }, { "content": "/// Eliminate unreachable code.\n\n///\n\n/// This pass deletes whole EBBs that can't be reached from the entry block. It does not delete\n\n/// individual instructions whose results are unused.\n\n///\n\n/// The reachability analysis is performed by the dominator tree analysis.\n\npub fn eliminate_unreachable_code(\n\n func: &mut ir::Function,\n\n cfg: &mut ControlFlowGraph,\n\n domtree: &DominatorTree,\n\n) {\n\n let _tt = timing::unreachable_code();\n\n let mut pos = FuncCursor::new(func);\n\n while let Some(ebb) = pos.next_ebb() {\n\n if domtree.is_reachable(ebb) {\n\n continue;\n\n }\n\n\n\n dbg!(\"Eliminating unreachable {}\", ebb);\n\n // Move the cursor out of the way and make sure the next lop iteration goes to the right\n\n // EBB.\n\n pos.prev_ebb();\n\n\n\n // Remove all instructions from `ebb`.\n\n while let Some(inst) = pos.func.layout.first_inst(ebb) {\n\n dbg!(\" - {}\", pos.func.dfg.display_inst(inst, None));\n", "file_path": "lib/codegen/src/unreachable_code.rs", "rank": 36, "score": 160317.06562999648 }, { "content": "/// Pretty-print a verifier error.\n\npub fn pretty_verifier_error(\n\n func: &ir::Function,\n\n isa: Option<&TargetIsa>,\n\n err: &verifier::Error,\n\n) -> String {\n\n let mut msg = err.to_string();\n\n match err.location {\n\n ir::entities::AnyEntity::Inst(inst) => {\n\n write!(msg, \"\\n{}: {}\\n\\n\", inst, func.dfg.display_inst(inst, isa)).unwrap()\n\n }\n\n _ => msg.push('\\n'),\n\n }\n\n write!(msg, \"{}\", func.display(isa)).unwrap();\n\n msg\n\n}\n\n\n", "file_path": "lib/codegen/src/print_errors.rs", "rank": 37, "score": 160317.06562999648 }, { "content": "/// Retrieves the tables from the table section\n\npub fn parse_elements_section(\n\n parser: &mut Parser,\n\n environ: &mut ModuleEnvironment,\n\n) -> Result<(), SectionParsingError> {\n\n loop {\n\n let table_index = match *parser.read() {\n\n ParserState::BeginElementSectionEntry(table_index) => table_index as TableIndex,\n\n ParserState::EndSection => break,\n\n ref s => return Err(SectionParsingError::WrongSectionContent(format!(\"{:?}\", s))),\n\n };\n\n match *parser.read() {\n\n ParserState::BeginInitExpressionBody => (),\n\n ref s => return Err(SectionParsingError::WrongSectionContent(format!(\"{:?}\", s))),\n\n };\n\n let (base, offset) = match *parser.read() {\n\n ParserState::InitExpressionOperator(Operator::I32Const { value }) => {\n\n (None, value as u32 as usize)\n\n }\n\n ParserState::InitExpressionOperator(Operator::GetGlobal { global_index }) => {\n\n match environ.get_global(global_index as GlobalIndex).initializer {\n", "file_path": "lib/wasm/src/sections_translator.rs", "rank": 38, "score": 160317.06562999648 }, { "content": "/// Legalize `sig` for RISC-V.\n\npub fn legalize_signature(\n\n sig: &mut ir::Signature,\n\n flags: &shared_settings::Flags,\n\n isa_flags: &settings::Flags,\n\n current: bool,\n\n) {\n\n let bits = if flags.is_64bit() { 64 } else { 32 };\n\n\n\n let mut args = Args::new(bits, isa_flags.enable_e());\n\n legalize_args(&mut sig.params, &mut args);\n\n\n\n let mut rets = Args::new(bits, isa_flags.enable_e());\n\n legalize_args(&mut sig.returns, &mut rets);\n\n\n\n if current {\n\n let ptr = Type::int(bits).unwrap();\n\n\n\n // Add the link register as an argument and return value.\n\n //\n\n // The `jalr` instruction implementing a return can technically accept the return address\n\n // in any register, but a micro-architecture with a return address predictor will only\n\n // recognize it as a return if the address is in `x1`.\n\n let link = AbiParam::special_reg(ptr, ArgumentPurpose::Link, GPR.unit(1));\n\n sig.params.push(link);\n\n sig.returns.push(link);\n\n }\n\n}\n\n\n", "file_path": "lib/codegen/src/isa/riscv/abi.rs", "rank": 39, "score": 160317.06562999648 }, { "content": "/// Retrieves the correspondences between functions and signatures from the function section\n\npub fn parse_function_section(\n\n parser: &mut Parser,\n\n environ: &mut ModuleEnvironment,\n\n) -> Result<(), SectionParsingError> {\n\n loop {\n\n match *parser.read() {\n\n ParserState::FunctionSectionEntry(sigindex) => {\n\n environ.declare_func_type(sigindex as SignatureIndex);\n\n }\n\n ParserState::EndSection => break,\n\n ref s => return Err(SectionParsingError::WrongSectionContent(format!(\"{:?}\", s))),\n\n };\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "lib/wasm/src/sections_translator.rs", "rank": 40, "score": 160317.06562999648 }, { "content": "/// Retrieves the size and maximum fields of memories from the memory section\n\npub fn parse_memory_section(\n\n parser: &mut Parser,\n\n environ: &mut ModuleEnvironment,\n\n) -> Result<(), SectionParsingError> {\n\n loop {\n\n match *parser.read() {\n\n ParserState::MemorySectionEntry(ref ty) => {\n\n environ.declare_memory(Memory {\n\n pages_count: ty.limits.initial as usize,\n\n maximum: ty.limits.maximum.map(|x| x as usize),\n\n shared: ty.shared,\n\n });\n\n }\n\n ParserState::EndSection => break,\n\n ref s => return Err(SectionParsingError::WrongSectionContent(format!(\"{:?}\", s))),\n\n };\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "lib/wasm/src/sections_translator.rs", "rank": 41, "score": 160317.06562999648 }, { "content": "/// Retrieves the tables from the table section\n\npub fn parse_table_section(\n\n parser: &mut Parser,\n\n environ: &mut ModuleEnvironment,\n\n) -> Result<(), SectionParsingError> {\n\n loop {\n\n match *parser.read() {\n\n ParserState::TableSectionEntry(ref table) => {\n\n environ.declare_table(Table {\n\n ty: match type_to_type(&table.element_type) {\n\n Ok(t) => TableElementType::Val(t),\n\n Err(()) => TableElementType::Func(),\n\n },\n\n size: table.limits.initial as usize,\n\n maximum: table.limits.maximum.map(|x| x as usize),\n\n })\n\n }\n\n ParserState::EndSection => break,\n\n ref s => return Err(SectionParsingError::WrongSectionContent(format!(\"{:?}\", s))),\n\n };\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "lib/wasm/src/sections_translator.rs", "rank": 42, "score": 160317.06562999648 }, { "content": "/// Retrieves the start function index from the start section\n\npub fn parse_start_section(\n\n parser: &mut Parser,\n\n environ: &mut ModuleEnvironment,\n\n) -> Result<(), SectionParsingError> {\n\n loop {\n\n match *parser.read() {\n\n ParserState::StartSectionEntry(index) => {\n\n environ.declare_start_func(index as FunctionIndex);\n\n }\n\n ParserState::EndSection => break,\n\n ref s => return Err(SectionParsingError::WrongSectionContent(format!(\"{:?}\", s))),\n\n };\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "lib/wasm/src/sections_translator.rs", "rank": 43, "score": 160317.06562999648 }, { "content": "pub fn spiderwasm_prologue_epilogue(\n\n func: &mut ir::Function,\n\n isa: &TargetIsa,\n\n) -> result::CtonResult {\n\n // Spiderwasm on 32-bit x86 always aligns its stack pointer to 16 bytes.\n\n let stack_align = 16;\n\n let word_size = if isa.flags().is_64bit() { 8 } else { 4 };\n\n let bytes = StackSize::from(isa.flags().spiderwasm_prologue_words()) * word_size;\n\n\n\n let mut ss = ir::StackSlotData::new(ir::StackSlotKind::IncomingArg, bytes);\n\n ss.offset = Some(-(bytes as StackOffset));\n\n func.stack_slots.push(ss);\n\n\n\n layout_stack(&mut func.stack_slots, stack_align)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "lib/codegen/src/isa/x86/abi.rs", "rank": 44, "score": 158117.70547355097 }, { "content": "#[inline]\n\npub fn enabled() -> bool {\n\n if cfg!(debug_assertions) {\n\n match STATE.load(atomic::Ordering::Relaxed) {\n\n 0 => initialize(),\n\n s => s > 0,\n\n }\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "lib/codegen/src/dbg.rs", "rank": 45, "score": 157492.92472803488 }, { "content": "/// Types that have a reserved value which can't be created any other way.\n\npub trait ReservedValue: Eq {\n\n /// Create an instance of the reserved value.\n\n fn reserved_value() -> Self;\n\n}\n\n\n\n/// Packed representation of `Option<T>`.\n\n#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]\n\npub struct PackedOption<T: ReservedValue>(T);\n\n\n\nimpl<T: ReservedValue> PackedOption<T> {\n\n /// Returns `true` if the packed option is a `None` value.\n\n pub fn is_none(&self) -> bool {\n\n self.0 == T::reserved_value()\n\n }\n\n\n\n /// Returns `true` if the packed option is a `Some` value.\n\n pub fn is_some(&self) -> bool {\n\n !self.is_none()\n\n }\n\n\n", "file_path": "lib/entity/src/packed_option.rs", "rank": 46, "score": 154164.1475842729 }, { "content": "/// Translate a sequence of bytes forming a valid Wasm binary into a list of valid Cretonne IR\n\n/// [`Function`](../codegen/ir/function/struct.Function.html).\n\n/// Returns the functions and also the mappings for imported functions and signature between the\n\n/// indexes in the wasm module and the indexes inside each functions.\n\npub fn translate_module<'data>(\n\n data: &'data [u8],\n\n environ: &mut ModuleEnvironment<'data>,\n\n) -> Result<(), String> {\n\n let _tt = timing::wasm_translate_module();\n\n let mut parser = Parser::new(data);\n\n match *parser.read() {\n\n ParserState::BeginWasm { .. } => {}\n\n ParserState::Error(BinaryReaderError { message, offset }) => {\n\n return Err(format!(\"at offset {}: {}\", offset, message));\n\n }\n\n ref s => panic!(\"modules should begin properly: {:?}\", s),\n\n }\n\n let mut next_input = ParserInput::Default;\n\n loop {\n\n match *parser.read_with_input(next_input) {\n\n ParserState::BeginSection { code: SectionCode::Type, .. } => {\n\n match parse_function_signatures(&mut parser, environ) {\n\n Ok(()) => (),\n\n Err(SectionParsingError::WrongSectionContent(s)) => {\n", "file_path": "lib/wasm/src/module_translator.rs", "rank": 47, "score": 152751.44630006782 }, { "content": "type BitSet8 = BitSet<u8>;\n", "file_path": "lib/codegen/src/ir/instructions.rs", "rank": 48, "score": 152295.53200682986 }, { "content": "/// Retrieves the imports from the imports section of the binary.\n\npub fn parse_import_section<'data>(\n\n parser: &mut Parser<'data>,\n\n environ: &mut ModuleEnvironment<'data>,\n\n) -> Result<(), SectionParsingError> {\n\n loop {\n\n match *parser.read() {\n\n ParserState::ImportSectionEntry {\n\n ty: ImportSectionEntryType::Function(sig),\n\n module,\n\n field,\n\n } => {\n\n // The input has already been validated, so we should be able to\n\n // assume valid UTF-8 and use `from_utf8_unchecked` if performance\n\n // becomes a concern here.\n\n let module_name = from_utf8(module).unwrap();\n\n let field_name = from_utf8(field).unwrap();\n\n environ.declare_func_import(sig as SignatureIndex, module_name, field_name);\n\n }\n\n ParserState::ImportSectionEntry {\n\n ty: ImportSectionEntryType::Memory(MemoryType {\n", "file_path": "lib/wasm/src/sections_translator.rs", "rank": 49, "score": 150547.61671515388 }, { "content": "pub fn parse_data_section<'data>(\n\n parser: &mut Parser<'data>,\n\n environ: &mut ModuleEnvironment<'data>,\n\n) -> Result<(), SectionParsingError> {\n\n loop {\n\n let memory_index = match *parser.read() {\n\n ParserState::BeginDataSectionEntry(memory_index) => memory_index,\n\n ParserState::EndSection => break,\n\n ref s => return Err(SectionParsingError::WrongSectionContent(format!(\"{:?}\", s))),\n\n };\n\n match *parser.read() {\n\n ParserState::BeginInitExpressionBody => (),\n\n ref s => return Err(SectionParsingError::WrongSectionContent(format!(\"{:?}\", s))),\n\n };\n\n let (base, offset) = match *parser.read() {\n\n ParserState::InitExpressionOperator(Operator::I32Const { value }) => {\n\n (None, value as u32 as usize)\n\n }\n\n ParserState::InitExpressionOperator(Operator::GetGlobal { global_index }) => {\n\n match environ.get_global(global_index as GlobalIndex).initializer {\n", "file_path": "lib/wasm/src/sections_translator.rs", "rank": 50, "score": 150547.61671515388 }, { "content": "/// Retrieves the names of the functions from the export section\n\npub fn parse_export_section<'data>(\n\n parser: &mut Parser<'data>,\n\n environ: &mut ModuleEnvironment<'data>,\n\n) -> Result<(), SectionParsingError> {\n\n loop {\n\n match *parser.read() {\n\n ParserState::ExportSectionEntry {\n\n field,\n\n ref kind,\n\n index,\n\n } => {\n\n // The input has already been validated, so we should be able to\n\n // assume valid UTF-8 and use `from_utf8_unchecked` if performance\n\n // becomes a concern here.\n\n let name = from_utf8(field).unwrap();\n\n let func_index = index as FunctionIndex;\n\n match *kind {\n\n ExternalKind::Function => environ.declare_func_export(func_index, name),\n\n ExternalKind::Table => environ.declare_table_export(func_index, name),\n\n ExternalKind::Memory => environ.declare_memory_export(func_index, name),\n\n ExternalKind::Global => environ.declare_global_export(func_index, name),\n\n }\n\n }\n\n ParserState::EndSection => break,\n\n ref s => return Err(SectionParsingError::WrongSectionContent(format!(\"{:?}\", s))),\n\n };\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "lib/wasm/src/sections_translator.rs", "rank": 51, "score": 150547.61671515388 }, { "content": "/// Get an ISA builder for creating x86 targets.\n\npub fn isa_builder() -> IsaBuilder {\n\n IsaBuilder {\n\n setup: settings::builder(),\n\n constructor: isa_constructor,\n\n }\n\n}\n\n\n", "file_path": "lib/codegen/src/isa/x86/mod.rs", "rank": 52, "score": 148452.97712106747 }, { "content": "/// Get an ISA builder for creating ARM64 targets.\n\npub fn isa_builder() -> IsaBuilder {\n\n IsaBuilder {\n\n setup: settings::builder(),\n\n constructor: isa_constructor,\n\n }\n\n}\n\n\n", "file_path": "lib/codegen/src/isa/arm64/mod.rs", "rank": 53, "score": 148452.97712106747 }, { "content": "/// Get an ISA builder for creating RISC-V targets.\n\npub fn isa_builder() -> IsaBuilder {\n\n IsaBuilder {\n\n setup: settings::builder(),\n\n constructor: isa_constructor,\n\n }\n\n}\n\n\n", "file_path": "lib/codegen/src/isa/riscv/mod.rs", "rank": 54, "score": 148452.97712106747 }, { "content": "/// Get an ISA builder for creating ARM32 targets.\n\npub fn isa_builder() -> IsaBuilder {\n\n IsaBuilder {\n\n setup: settings::builder(),\n\n constructor: isa_constructor,\n\n }\n\n}\n\n\n", "file_path": "lib/codegen/src/isa/arm32/mod.rs", "rank": 55, "score": 148452.97712106747 }, { "content": "/// A type wrapping a small integer index should implement `EntityRef` so it can be used as the key\n\n/// of an `EntityMap` or `SparseMap`.\n\npub trait EntityRef: Copy + Eq {\n\n /// Create a new entity reference from a small integer.\n\n /// This should crash if the requested index is not representable.\n\n fn new(usize) -> Self;\n\n\n\n /// Get the index that was used to create this entity reference.\n\n fn index(self) -> usize;\n\n}\n\n\n\n/// Macro which provides the common implementation of a 32-bit entity reference.\n\n#[macro_export]\n\nmacro_rules! entity_impl {\n\n // Basic traits.\n\n ($entity:ident) => {\n\n impl $crate::EntityRef for $entity {\n\n fn new(index: usize) -> Self {\n\n debug_assert!(index < ($crate::__core::u32::MAX as usize));\n\n $entity(index as u32)\n\n }\n\n\n", "file_path": "lib/entity/src/lib.rs", "rank": 56, "score": 147982.30841352552 }, { "content": "/// Methods that are specialized to a target ISA. Implies a Display trait that shows the\n\n/// shared flags, as well as any isa-specific flags.\n\npub trait TargetIsa: fmt::Display {\n\n /// Get the name of this ISA.\n\n fn name(&self) -> &'static str;\n\n\n\n /// Get the ISA-independent flags that were used to make this trait object.\n\n fn flags(&self) -> &settings::Flags;\n\n\n\n /// Does the CPU implement scalar comparisons using a CPU flags register?\n\n fn uses_cpu_flags(&self) -> bool {\n\n false\n\n }\n\n\n\n /// Get a data structure describing the registers in this ISA.\n\n fn register_info(&self) -> RegInfo;\n\n\n\n /// Returns an iterartor over legal encodings for the instruction.\n\n fn legal_encodings<'a>(\n\n &'a self,\n\n func: &'a ir::Function,\n\n inst: &'a ir::InstructionData,\n", "file_path": "lib/codegen/src/isa/mod.rs", "rank": 57, "score": 145791.91956741136 }, { "content": "pub fn run(files: &[String]) -> CommandResult {\n\n for (i, f) in files.into_iter().enumerate() {\n\n if i != 0 {\n\n println!();\n\n }\n\n cat_one(f)?\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/cat.rs", "rank": 58, "score": 143951.08890206902 }, { "content": "// Create a single-register REX prefix, setting the B bit to bit 3 of the register.\n\n// This is used for instructions that encode a register in the low 3 bits of the opcode and for\n\n// instructions that use the ModR/M `reg` field for something else.\n\nfn rex1(reg_b: RegUnit) -> u8 {\n\n let b = ((reg_b >> 3) & 1) as u8;\n\n BASE_REX | b\n\n}\n\n\n", "file_path": "lib/codegen/src/isa/x86/binemit.rs", "rank": 59, "score": 142894.43745190848 }, { "content": "/// Get the spill slot size to use for `ty`.\n\nfn spill_size(ty: Type) -> StackSize {\n\n cmp::max(MIN_SPILL_SLOT_SIZE, ty.bytes())\n\n}\n\n\n\n/// The kind of a stack slot.\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\n\npub enum StackSlotKind {\n\n /// A spill slot. This is a stack slot created by the register allocator.\n\n SpillSlot,\n\n\n\n /// An explicit stack slot. This is a chunk of stack memory for use by the `stack_load`\n\n /// and `stack_store` instructions.\n\n ExplicitSlot,\n\n\n\n /// An incoming function argument.\n\n ///\n\n /// If the current function has more arguments than fits in registers, the remaining arguments\n\n /// are passed on the stack by the caller. These incoming arguments are represented as SSA\n\n /// values assigned to incoming stack slots.\n\n IncomingArg,\n", "file_path": "lib/codegen/src/ir/stackslot.rs", "rank": 60, "score": 142743.05650903884 }, { "content": "/// The main pre-opt pass.\n\npub fn do_preopt(func: &mut Function) {\n\n let _tt = timing::preopt();\n\n let mut pos = FuncCursor::new(func);\n\n while let Some(_ebb) = pos.next_ebb() {\n\n while let Some(inst) = pos.next_inst() {\n\n // Apply basic simplifications.\n\n simplify(&mut pos, inst);\n\n\n\n //-- BEGIN -- division by constants ----------------\n\n\n\n let mb_dri = get_div_info(inst, &pos.func.dfg);\n\n if let Some(divrem_info) = mb_dri {\n\n do_divrem_transformation(&divrem_info, &mut pos, inst);\n\n continue;\n\n }\n\n\n\n //-- END -- division by constants ------------------\n\n }\n\n }\n\n}\n", "file_path": "lib/codegen/src/preopt.rs", "rank": 61, "score": 141638.95365606673 }, { "content": "pub fn run(files: &[String]) -> CommandResult {\n\n for (i, f) in files.into_iter().enumerate() {\n\n if i != 0 {\n\n println!();\n\n }\n\n print_cfg(f)?\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/print_cfg.rs", "rank": 62, "score": 141638.95365606673 }, { "content": "// Should `inst` be printed with a type suffix?\n\n//\n\n// Polymorphic instructions may need a suffix indicating the value of the controlling type variable\n\n// if it can't be trivially inferred.\n\n//\n\nfn type_suffix(func: &Function, inst: Inst) -> Option<Type> {\n\n let inst_data = &func.dfg[inst];\n\n let constraints = inst_data.opcode().constraints();\n\n\n\n if !constraints.is_polymorphic() {\n\n return None;\n\n }\n\n\n\n // If the controlling type variable can be inferred from the type of the designated value input\n\n // operand, we don't need the type suffix.\n\n if constraints.use_typevar_operand() {\n\n let ctrl_var = inst_data.typevar_operand(&func.dfg.value_lists).unwrap();\n\n let def_ebb = match func.dfg.value_def(ctrl_var) {\n\n ValueDef::Result(instr, _) => func.layout.inst_ebb(instr),\n\n ValueDef::Param(ebb, _) => Some(ebb),\n\n };\n\n if def_ebb.is_some() && def_ebb == func.layout.inst_ebb(inst) {\n\n return None;\n\n }\n\n }\n\n\n\n let rtype = func.dfg.ctrl_typevar(inst);\n\n assert!(\n\n !rtype.is_void(),\n\n \"Polymorphic instruction must produce a result\"\n\n );\n\n Some(rtype)\n\n}\n\n\n", "file_path": "lib/codegen/src/write.rs", "rank": 63, "score": 141230.3259013029 }, { "content": "/// Load `path` and run the test in it.\n\n///\n\n/// If running this test causes a panic, it will propagate as normal.\n\npub fn run(path: &Path) -> TestResult {\n\n let _tt = timing::process_file();\n\n dbg!(\"---\\nFile: {}\", path.to_string_lossy());\n\n let started = time::Instant::now();\n\n let buffer = read_to_string(path).map_err(|e| e.to_string())?;\n\n let testfile = parse_test(&buffer).map_err(|e| e.to_string())?;\n\n if testfile.functions.is_empty() {\n\n return Err(\"no functions found\".to_string());\n\n }\n\n\n\n // Parse the test commands.\n\n let mut tests = testfile\n\n .commands\n\n .iter()\n\n .map(new_subtest)\n\n .collect::<Result<Vec<_>>>()?;\n\n\n\n // Flags to use for those tests that don't need an ISA.\n\n // This is the cumulative effect of all the `set` commands in the file.\n\n let flags = match testfile.isa_spec {\n", "file_path": "lib/filetests/src/runone.rs", "rank": 64, "score": 139439.5934996212 }, { "content": "/// Parse a float using the same format as `format_float` above.\n\n///\n\n/// The encoding parameters are:\n\n///\n\n/// w - exponent field width in bits\n\n/// t - trailing significand field width in bits\n\n///\n\nfn parse_float(s: &str, w: u8, t: u8) -> Result<u64, &'static str> {\n\n debug_assert!(w > 0 && w <= 16, \"Invalid exponent range\");\n\n debug_assert!(1 + w + t <= 64, \"Too large IEEE format for u64\");\n\n debug_assert!((t + w + 1).is_power_of_two(), \"Unexpected IEEE format size\");\n\n\n\n let (sign_bit, s2) = if s.starts_with('-') {\n\n (1u64 << (t + w), &s[1..])\n\n } else if s.starts_with('+') {\n\n (0, &s[1..])\n\n } else {\n\n (0, s)\n\n };\n\n\n\n if !s2.starts_with(\"0x\") {\n\n let max_e_bits = ((1u64 << w) - 1) << t;\n\n let quiet_bit = 1u64 << (t - 1);\n\n\n\n // The only decimal encoding allowed is 0.\n\n if s2 == \"0.0\" {\n\n return Ok(sign_bit);\n", "file_path": "lib/codegen/src/ir/immediates.rs", "rank": 65, "score": 138350.80784632787 }, { "content": "/// Two-level hash table lookup and iterator construction.\n\n///\n\n/// Given the controlling type variable and instruction opcode, find the corresponding encoding\n\n/// list.\n\n///\n\n/// Returns an iterator that produces legal encodings for `inst`.\n\npub fn lookup_enclist<'a, OffT1, OffT2>(\n\n ctrl_typevar: Type,\n\n inst: &'a InstructionData,\n\n func: &'a Function,\n\n level1_table: &'static [Level1Entry<OffT1>],\n\n level2_table: &'static [Level2Entry<OffT2>],\n\n enclist: &'static [EncListEntry],\n\n legalize_actions: &'static [Legalize],\n\n recipe_preds: &'static [RecipePredicate],\n\n inst_preds: &'static [InstPredicate],\n\n isa_preds: PredicateView<'a>,\n\n) -> Encodings<'a>\n\nwhere\n\n OffT1: Into<u32> + Copy,\n\n OffT2: Into<u32> + Copy,\n\n{\n\n let (offset, legalize) = match probe(level1_table, ctrl_typevar, ctrl_typevar.index()) {\n\n Err(l1idx) => {\n\n // No level 1 entry found for the type.\n\n // We have a sentinel entry with the default legalization code.\n", "file_path": "lib/codegen/src/isa/enc_tables.rs", "rank": 66, "score": 137354.47500649694 }, { "content": "pub fn magicS32(d: i32) -> MS32 {\n\n debug_assert_ne!(d, -1);\n\n debug_assert_ne!(d, 0);\n\n debug_assert_ne!(d, 1);\n\n let two31: u32 = 0x80000000u32;\n\n let mut p: i32 = 31;\n\n let ad: u32 = i32::wrapping_abs(d) as u32;\n\n let t: u32 = two31 + ((d as u32) >> 31);\n\n let anc: u32 = u32::wrapping_sub(t - 1, t % ad);\n\n let mut q1: u32 = two31 / anc;\n\n let mut r1: u32 = two31 - q1 * anc;\n\n let mut q2: u32 = two31 / ad;\n\n let mut r2: u32 = two31 - q2 * ad;\n\n loop {\n\n p = p + 1;\n\n q1 = 2 * q1;\n\n r1 = 2 * r1;\n\n if r1 >= anc {\n\n q1 = q1 + 1;\n\n r1 = r1 - anc;\n", "file_path": "lib/codegen/src/divconst_magic_numbers.rs", "rank": 67, "score": 137344.9539055348 }, { "content": "pub fn magicS64(d: i64) -> MS64 {\n\n debug_assert_ne!(d, -1);\n\n debug_assert_ne!(d, 0);\n\n debug_assert_ne!(d, 1);\n\n let two63: u64 = 0x8000000000000000u64;\n\n let mut p: i32 = 63;\n\n let ad: u64 = i64::wrapping_abs(d) as u64;\n\n let t: u64 = two63 + ((d as u64) >> 63);\n\n let anc: u64 = u64::wrapping_sub(t - 1, t % ad);\n\n let mut q1: u64 = two63 / anc;\n\n let mut r1: u64 = two63 - q1 * anc;\n\n let mut q2: u64 = two63 / ad;\n\n let mut r2: u64 = two63 - q2 * ad;\n\n loop {\n\n p = p + 1;\n\n q1 = 2 * q1;\n\n r1 = 2 * r1;\n\n if r1 >= anc {\n\n q1 = q1 + 1;\n\n r1 = r1 - anc;\n", "file_path": "lib/codegen/src/divconst_magic_numbers.rs", "rank": 68, "score": 137344.9539055348 }, { "content": "pub fn magicU32(d: u32) -> MU32 {\n\n debug_assert_ne!(d, 0);\n\n debug_assert_ne!(d, 1); // d==1 generates out of range shifts.\n\n\n\n let mut do_add: bool = false;\n\n let mut p: i32 = 31;\n\n let nc: u32 = 0xFFFFFFFFu32 - u32::wrapping_neg(d) % d;\n\n let mut q1: u32 = 0x80000000u32 / nc;\n\n let mut r1: u32 = 0x80000000u32 - q1 * nc;\n\n let mut q2: u32 = 0x7FFFFFFFu32 / d;\n\n let mut r2: u32 = 0x7FFFFFFFu32 - q2 * d;\n\n loop {\n\n p = p + 1;\n\n if r1 >= nc - r1 {\n\n q1 = u32::wrapping_add(u32::wrapping_mul(2, q1), 1);\n\n r1 = u32::wrapping_sub(u32::wrapping_mul(2, r1), nc);\n\n } else {\n\n q1 = 2 * q1;\n\n r1 = 2 * r1;\n\n }\n", "file_path": "lib/codegen/src/divconst_magic_numbers.rs", "rank": 69, "score": 137344.9539055348 }, { "content": "pub fn magicU64(d: u64) -> MU64 {\n\n debug_assert_ne!(d, 0);\n\n debug_assert_ne!(d, 1); // d==1 generates out of range shifts.\n\n\n\n let mut do_add: bool = false;\n\n let mut p: i32 = 63;\n\n let nc: u64 = 0xFFFFFFFFFFFFFFFFu64 - u64::wrapping_neg(d) % d;\n\n let mut q1: u64 = 0x8000000000000000u64 / nc;\n\n let mut r1: u64 = 0x8000000000000000u64 - q1 * nc;\n\n let mut q2: u64 = 0x7FFFFFFFFFFFFFFFu64 / d;\n\n let mut r2: u64 = 0x7FFFFFFFFFFFFFFFu64 - q2 * d;\n\n loop {\n\n p = p + 1;\n\n if r1 >= nc - r1 {\n\n q1 = u64::wrapping_add(u64::wrapping_mul(2, q1), 1);\n\n r1 = u64::wrapping_sub(u64::wrapping_mul(2, r1), nc);\n\n } else {\n\n q1 = 2 * q1;\n\n r1 = 2 * r1;\n\n }\n", "file_path": "lib/codegen/src/divconst_magic_numbers.rs", "rank": 70, "score": 137344.9539055348 }, { "content": "#[derive(Clone, Copy)]\n\nstruct RegUse {\n\n value: Value,\n\n opidx: u16,\n\n\n\n // Register class required by the use.\n\n rci: RegClassIndex,\n\n\n\n // A use with a fixed register constraint.\n\n fixed: bool,\n\n\n\n // A register use of a spilled value.\n\n spilled: bool,\n\n\n\n // A use with a tied register constraint *and* the used value is not killed.\n\n tied: bool,\n\n}\n\n\n\nimpl RegUse {\n\n fn new(value: Value, idx: usize, rci: RegClassIndex) -> RegUse {\n\n RegUse {\n", "file_path": "lib/codegen/src/regalloc/spilling.rs", "rank": 71, "score": 136080.79237281202 }, { "content": "/// Translates wasm operators into Cretonne IR instructions. Returns `true` if it inserted\n\n/// a return.\n\npub fn translate_operator<FE: FuncEnvironment + ?Sized>(\n\n op: Operator,\n\n builder: &mut FunctionBuilder<Variable>,\n\n state: &mut TranslationState,\n\n environ: &mut FE,\n\n) {\n\n if !state.reachable {\n\n return translate_unreachable_operator(&op, builder, state);\n\n }\n\n\n\n // This big match treats all Wasm code operators.\n\n match op {\n\n /********************************** Locals ****************************************\n\n * `get_local` and `set_local` are treated as non-SSA variables and will completely\n\n * disappear in the Cretonne Code\n\n ***********************************************************************************/\n\n Operator::GetLocal { local_index } => {\n\n state.push1(builder.use_var(Variable::with_u32(local_index)))\n\n }\n\n Operator::SetLocal { local_index } => {\n", "file_path": "lib/wasm/src/code_translator.rs", "rank": 72, "score": 135347.7295289714 }, { "content": "/// Extend the live range for `value` so it reaches `to` which must live in `ebb`.\n\nfn extend_to_use(\n\n lr: &mut LiveRange,\n\n ebb: Ebb,\n\n to: Inst,\n\n worklist: &mut Vec<Ebb>,\n\n func: &Function,\n\n cfg: &ControlFlowGraph,\n\n forest: &mut LiveRangeForest,\n\n) {\n\n // This is our scratch working space, and we'll leave it empty when we return.\n\n debug_assert!(worklist.is_empty());\n\n\n\n // Extend the range locally in `ebb`.\n\n // If there already was a live interval in that block, we're done.\n\n if lr.extend_in_ebb(ebb, to, &func.layout, forest) {\n\n worklist.push(ebb);\n\n }\n\n\n\n // The work list contains those EBBs where we have learned that the value needs to be\n\n // live-in.\n", "file_path": "lib/codegen/src/regalloc/liveness.rs", "rank": 73, "score": 134738.69475987944 }, { "content": "/// Build a filechecker using the directives in the file preamble and the function's comments.\n\npub fn build_filechecker(context: &Context) -> Result<Checker> {\n\n let mut builder = CheckerBuilder::new();\n\n // Preamble comments apply to all functions.\n\n for comment in context.preamble_comments {\n\n builder.directive(comment.text).map_err(|e| {\n\n format!(\"filecheck: {}\", e)\n\n })?;\n\n }\n\n for comment in &context.details.comments {\n\n builder.directive(comment.text).map_err(|e| {\n\n format!(\"filecheck: {}\", e)\n\n })?;\n\n }\n\n Ok(builder.finish())\n\n}\n", "file_path": "lib/filetests/src/subtest.rs", "rank": 74, "score": 133154.89381108692 }, { "content": "pub fn ref_slice<T>(s: &T) -> &[T] {\n\n unsafe { slice::from_raw_parts(s, 1) }\n\n}\n\n\n", "file_path": "lib/codegen/src/ref_slice.rs", "rank": 75, "score": 133149.49123934738 }, { "content": "pub fn run(files: &[String], verbose: bool) -> CommandResult {\n\n if files.is_empty() {\n\n return Err(\"No check files\".to_string());\n\n }\n\n let checker = read_checkfile(&files[0])?;\n\n if checker.is_empty() {\n\n return Err(format!(\"{}: no filecheck directives found\", files[0]));\n\n }\n\n\n\n // Print out the directives under --verbose.\n\n if verbose {\n\n println!(\"{}\", checker);\n\n }\n\n\n\n let mut buffer = String::new();\n\n io::stdin().read_to_string(&mut buffer).map_err(|e| {\n\n format!(\"stdin: {}\", e)\n\n })?;\n\n\n\n if verbose {\n", "file_path": "src/rsfilecheck.rs", "rank": 76, "score": 131681.24937981414 }, { "content": "/// Parse the entire `text` as a test case file.\n\n///\n\n/// The returned `TestFile` contains direct references to substrings of `text`.\n\npub fn parse_test(text: &str) -> Result<TestFile> {\n\n let _tt = timing::parse_text();\n\n let mut parser = Parser::new(text);\n\n // Gather the preamble comments.\n\n parser.start_gathering_comments();\n\n\n\n let commands = parser.parse_test_commands();\n\n let isa_spec = parser.parse_isa_specs()?;\n\n\n\n parser.token();\n\n parser.claim_gathered_comments(AnyEntity::Function);\n\n\n\n let preamble_comments = parser.take_comments();\n\n let functions = parser.parse_function_list(isa_spec.unique_isa())?;\n\n\n\n Ok(TestFile {\n\n commands,\n\n isa_spec,\n\n preamble_comments,\n\n functions,\n", "file_path": "lib/reader/src/parser.rs", "rank": 77, "score": 131152.266862784 }, { "content": "#[cold]\n\npub fn bad_encoding(func: &Function, inst: Inst) -> ! {\n\n panic!(\n\n \"Bad encoding {} for {}\",\n\n func.encodings[inst],\n\n func.dfg.display_inst(inst, None)\n\n );\n\n}\n\n\n", "file_path": "lib/codegen/src/binemit/mod.rs", "rank": 78, "score": 131152.266862784 }, { "content": "/// Verify `func` after checking the integrity of associated context data structures `cfg` and\n\n/// `domtree`.\n\npub fn verify_context<'a, FOI: Into<FlagsOrIsa<'a>>>(\n\n func: &Function,\n\n cfg: &ControlFlowGraph,\n\n domtree: &DominatorTree,\n\n fisa: FOI,\n\n) -> Result {\n\n let _tt = timing::verifier();\n\n let verifier = Verifier::new(func, fisa.into());\n\n if cfg.is_valid() {\n\n verifier.cfg_integrity(cfg)?;\n\n }\n\n if domtree.is_valid() {\n\n verifier.domtree_integrity(domtree)?;\n\n }\n\n verifier.run()\n\n}\n\n\n", "file_path": "lib/codegen/src/verifier/mod.rs", "rank": 79, "score": 129586.6097857277 }, { "content": "// Create a dual-register REX prefix, setting:\n\n//\n\n// REX.B = bit 3 of r/m register, or SIB base register when a SIB byte is present.\n\n// REX.R = bit 3 of reg register.\n\nfn rex2(rm: RegUnit, reg: RegUnit) -> u8 {\n\n let b = ((rm >> 3) & 1) as u8;\n\n let r = ((reg >> 3) & 1) as u8;\n\n BASE_REX | b | (r << 2)\n\n}\n\n\n", "file_path": "lib/codegen/src/isa/x86/binemit.rs", "rank": 80, "score": 127886.86908152008 }, { "content": "/// Run filecheck on `text`, using directives extracted from `context`.\n\npub fn run_filecheck(text: &str, context: &Context) -> Result<()> {\n\n let checker = build_filechecker(context)?;\n\n if checker.check(text, NO_VARIABLES).map_err(|e| {\n\n format!(\"filecheck: {}\", e)\n\n })?\n\n {\n\n Ok(())\n\n } else {\n\n // Filecheck mismatch. Emit an explanation as output.\n\n let (_, explain) = checker.explain(text, NO_VARIABLES).map_err(|e| {\n\n format!(\"explain: {}\", e)\n\n })?;\n\n Err(format!(\"filecheck failed:\\n{}{}\", checker, explain))\n\n }\n\n}\n\n\n", "file_path": "lib/filetests/src/subtest.rs", "rank": 81, "score": 127594.84867281294 }, { "content": "/// Translate from a Cretonne `Reloc` to a raw object-file-format-specific\n\n/// relocation code.\n\npub fn raw_relocation(reloc: Reloc, format: Format) -> u32 {\n\n match format {\n\n Format::ELF => {\n\n use goblin::elf;\n\n match reloc {\n\n Reloc::Abs4 => elf::reloc::R_X86_64_32,\n\n Reloc::Abs8 => elf::reloc::R_X86_64_64,\n\n Reloc::X86PCRel4 => elf::reloc::R_X86_64_PC32,\n\n // TODO: Get Cretonne to tell us when we can use\n\n // R_X86_64_GOTPCRELX/R_X86_64_REX_GOTPCRELX.\n\n Reloc::X86GOTPCRel4 => elf::reloc::R_X86_64_GOTPCREL,\n\n Reloc::X86PLTRel4 => elf::reloc::R_X86_64_PLT32,\n\n _ => unimplemented!(),\n\n }\n\n }\n\n Format::MachO => unimplemented!(),\n\n }\n\n}\n", "file_path": "lib/faerie/src/container.rs", "rank": 82, "score": 127589.3854091643 }, { "content": "/// Main entry point for `cton-util test`.\n\n///\n\n/// Take a list of filenames which can be either `.cton` files or directories.\n\n///\n\n/// Files are interpreted as test cases and executed immediately.\n\n///\n\n/// Directories are scanned recursively for test cases ending in `.cton`. These test cases are\n\n/// executed on background threads.\n\n///\n\npub fn run(verbose: bool, files: &[String]) -> TestResult {\n\n let mut runner = TestRunner::new(verbose);\n\n\n\n for path in files.iter().map(Path::new) {\n\n if path.is_file() {\n\n runner.push_test(path);\n\n } else {\n\n runner.push_dir(path);\n\n }\n\n }\n\n\n\n runner.start_threads();\n\n runner.run()\n\n}\n\n\n", "file_path": "lib/filetests/src/lib.rs", "rank": 83, "score": 127589.3854091643 }, { "content": "pub fn do_postopt(func: &mut Function, isa: &TargetIsa) {\n\n let _tt = timing::postopt();\n\n let mut pos = EncCursor::new(func, isa);\n\n while let Some(_ebb) = pos.next_ebb() {\n\n let mut last_flags_clobber = None;\n\n while let Some(inst) = pos.next_inst() {\n\n if isa.uses_cpu_flags() {\n\n // Optimize instructions to make use of flags.\n\n optimize_cpu_flags(&mut pos, inst, last_flags_clobber, isa);\n\n\n\n // Track the most recent seen instruction that clobbers the flags.\n\n if let Some(constraints) =\n\n isa.encoding_info().operand_constraints(\n\n pos.func.encodings[inst],\n\n )\n\n {\n\n if constraints.clobbers_flags {\n\n last_flags_clobber = Some(inst)\n\n }\n\n }\n\n }\n\n }\n\n }\n\n}\n", "file_path": "lib/codegen/src/postopt.rs", "rank": 84, "score": 127589.3854091643 }, { "content": "/// Parse the entire `text` into a list of functions.\n\n///\n\n/// Any test commands or ISA declarations are ignored.\n\npub fn parse_functions(text: &str) -> Result<Vec<Function>> {\n\n let _tt = timing::parse_text();\n\n parse_test(text).map(|file| {\n\n file.functions.into_iter().map(|(func, _)| func).collect()\n\n })\n\n}\n\n\n", "file_path": "lib/reader/src/parser.rs", "rank": 85, "score": 127589.3854091643 }, { "content": "/// Get the set of allocatable registers for `func`.\n\npub fn allocatable_registers(_func: &ir::Function) -> RegisterSet {\n\n unimplemented!()\n\n}\n", "file_path": "lib/codegen/src/isa/arm32/abi.rs", "rank": 86, "score": 127424.08888818166 }, { "content": "/// Get the set of allocatable registers for `func`.\n\npub fn allocatable_registers(_func: &ir::Function) -> RegisterSet {\n\n unimplemented!()\n\n}\n", "file_path": "lib/codegen/src/isa/arm64/abi.rs", "rank": 87, "score": 127424.08888818166 }, { "content": "fn parse_enum_value(value: &str, choices: &[&str]) -> Result<u8> {\n\n match choices.iter().position(|&tag| tag == value) {\n\n Some(idx) => Ok(idx as u8),\n\n None => Err(Error::BadValue),\n\n }\n\n}\n\n\n\nimpl Configurable for Builder {\n\n fn enable(&mut self, name: &str) -> Result<()> {\n\n use self::detail::Detail;\n\n let (offset, detail) = self.lookup(name)?;\n\n match detail {\n\n Detail::Bool { bit } => {\n\n self.set_bit(offset, bit, true);\n\n Ok(())\n\n }\n\n Detail::Preset => {\n\n self.apply_preset(&self.template.presets[offset..]);\n\n Ok(())\n\n }\n", "file_path": "lib/codegen/src/settings.rs", "rank": 88, "score": 126128.3772838176 }, { "content": "/// Emit instructions to produce a zero value in the given type.\n\nfn emit_zero(ty: Type, mut cur: FuncCursor) -> Value {\n\n if ty.is_int() {\n\n cur.ins().iconst(ty, 0)\n\n } else if ty.is_bool() {\n\n cur.ins().bconst(ty, false)\n\n } else if ty == F32 {\n\n cur.ins().f32const(Ieee32::with_bits(0))\n\n } else if ty == F64 {\n\n cur.ins().f64const(Ieee64::with_bits(0))\n\n } else if ty.is_vector() {\n\n let scalar_ty = ty.lane_type();\n\n if scalar_ty.is_int() {\n\n cur.ins().iconst(ty, 0)\n\n } else if scalar_ty.is_bool() {\n\n cur.ins().bconst(ty, false)\n\n } else if scalar_ty == F32 {\n\n let scalar = cur.ins().f32const(Ieee32::with_bits(0));\n\n cur.ins().splat(ty, scalar)\n\n } else if scalar_ty == F64 {\n\n let scalar = cur.ins().f64const(Ieee64::with_bits(0));\n", "file_path": "lib/frontend/src/ssa.rs", "rank": 89, "score": 125987.19818891541 }, { "content": "/// Write a line with the given format arguments.\n\n///\n\n/// This is for use by the `dbg!` macro.\n\npub fn writeln_with_format_args(args: fmt::Arguments) -> io::Result<()> {\n\n WRITER.with(|rc| {\n\n let mut w = rc.borrow_mut();\n\n writeln!(*w, \"{}\", args)?;\n\n w.flush()\n\n })\n\n}\n\n\n", "file_path": "lib/codegen/src/dbg.rs", "rank": 90, "score": 125688.33753346713 }, { "content": "/// Look for a supported ISA with the given `name`.\n\n/// Return a builder that can create a corresponding `TargetIsa`.\n\npub fn lookup(name: &str) -> Result<Builder, LookupError> {\n\n match name {\n\n \"riscv\" => isa_builder!(riscv, build_riscv),\n\n \"x86\" => isa_builder!(x86, build_x86),\n\n \"arm32\" => isa_builder!(arm32, build_arm32),\n\n \"arm64\" => isa_builder!(arm64, build_arm64),\n\n _ => Err(LookupError::Unknown),\n\n }\n\n}\n\n\n\n/// Describes reason for target lookup failure\n\n#[derive(PartialEq, Eq, Copy, Clone, Debug)]\n\npub enum LookupError {\n\n /// Unknown Target\n\n Unknown,\n\n\n\n /// Target known but not built and thus not supported\n\n Unsupported,\n\n}\n\n\n", "file_path": "lib/codegen/src/isa/mod.rs", "rank": 91, "score": 125682.93496172759 }, { "content": "/// Pre-parse a supposed entity name by splitting it into two parts: A head of lowercase ASCII\n\n/// letters and numeric tail.\n\npub fn split_entity_name(name: &str) -> Option<(&str, u32)> {\n\n let (head, tail) = name.split_at(name.len() - trailing_digits(name));\n\n if tail.len() > 1 && tail.starts_with('0') {\n\n None\n\n } else {\n\n tail.parse().ok().map(|n| (head, n))\n\n }\n\n}\n\n\n\n/// Lexical analysis.\n\n///\n\n/// A `Lexer` reads text from a `&str` and provides a sequence of tokens.\n\n///\n\n/// Also keep track of a line number for error reporting.\n\n///\n\npub struct Lexer<'a> {\n\n // Complete source being processed.\n\n source: &'a str,\n\n\n\n // Iterator into `source`.\n", "file_path": "lib/reader/src/lexer.rs", "rank": 92, "score": 125682.93496172759 }, { "content": "/// Displayable slice of values.\n\nstruct DisplayValues<'a>(&'a [Value]);\n\n\n\nimpl<'a> fmt::Display for DisplayValues<'a> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> Result {\n\n for (i, val) in self.0.iter().enumerate() {\n\n if i == 0 {\n\n write!(f, \"{}\", val)?;\n\n } else {\n\n write!(f, \", {}\", val)?;\n\n }\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use ir::types;\n\n use ir::{ExternalName, Function, StackSlotData, StackSlotKind};\n\n use std::string::ToString;\n", "file_path": "lib/codegen/src/write.rs", "rank": 93, "score": 124248.15533097697 }, { "content": "/// Legalize all the function signatures in `func`.\n\n///\n\n/// This changes all signatures to be ABI-compliant with full `ArgumentLoc` annotations. It doesn't\n\n/// change the entry block arguments, calls, or return instructions, so this can leave the function\n\n/// in a state with type discrepancies.\n\npub fn legalize_signatures(func: &mut Function, isa: &TargetIsa) {\n\n isa.legalize_signature(&mut func.signature, true);\n\n func.signature.compute_argument_bytes();\n\n for sig_data in func.dfg.signatures.values_mut() {\n\n isa.legalize_signature(sig_data, false);\n\n sig_data.compute_argument_bytes();\n\n }\n\n\n\n if let Some(entry) = func.layout.entry_block() {\n\n legalize_entry_params(func, entry);\n\n spill_entry_params(func, entry);\n\n }\n\n}\n\n\n", "file_path": "lib/codegen/src/legalizer/boundary.rs", "rank": 94, "score": 123865.80217965292 }, { "content": "pub fn subtest(parsed: &TestCommand) -> Result<Box<SubTest>> {\n\n assert_eq!(parsed.command, \"dce\");\n\n if !parsed.options.is_empty() {\n\n Err(format!(\"No options allowed on {}\", parsed))\n\n } else {\n\n Ok(Box::new(TestDCE))\n\n }\n\n}\n\n\n\nimpl SubTest for TestDCE {\n\n fn name(&self) -> Cow<str> {\n\n Cow::from(\"dce\")\n\n }\n\n\n\n fn is_mutating(&self) -> bool {\n\n true\n\n }\n\n\n\n fn run(&self, func: Cow<Function>, context: &Context) -> Result<()> {\n\n // Create a compilation context, and drop in the function.\n", "file_path": "lib/filetests/src/test_dce.rs", "rank": 95, "score": 123861.20743456199 }, { "content": "pub fn subtest(parsed: &TestCommand) -> Result<Box<SubTest>> {\n\n assert_eq!(parsed.command, \"legalizer\");\n\n if !parsed.options.is_empty() {\n\n Err(format!(\"No options allowed on {}\", parsed))\n\n } else {\n\n Ok(Box::new(TestLegalizer))\n\n }\n\n}\n\n\n\nimpl SubTest for TestLegalizer {\n\n fn name(&self) -> Cow<str> {\n\n Cow::from(\"legalizer\")\n\n }\n\n\n\n fn is_mutating(&self) -> bool {\n\n true\n\n }\n\n\n\n fn needs_isa(&self) -> bool {\n\n true\n", "file_path": "lib/filetests/src/test_legalizer.rs", "rank": 96, "score": 123861.20743456199 }, { "content": "pub fn subtest(parsed: &TestCommand) -> Result<Box<SubTest>> {\n\n assert_eq!(parsed.command, \"licm\");\n\n if !parsed.options.is_empty() {\n\n Err(format!(\"No options allowed on {}\", parsed))\n\n } else {\n\n Ok(Box::new(TestLICM))\n\n }\n\n}\n\n\n\nimpl SubTest for TestLICM {\n\n fn name(&self) -> Cow<str> {\n\n Cow::from(\"licm\")\n\n }\n\n\n\n fn is_mutating(&self) -> bool {\n\n true\n\n }\n\n\n\n fn run(&self, func: Cow<Function>, context: &Context) -> Result<()> {\n\n // Create a compilation context, and drop in the function.\n", "file_path": "lib/filetests/src/test_licm.rs", "rank": 97, "score": 123861.20743456199 }, { "content": "pub fn subtest(parsed: &TestCommand) -> Result<Box<SubTest>> {\n\n assert_eq!(parsed.command, \"postopt\");\n\n if !parsed.options.is_empty() {\n\n Err(format!(\"No options allowed on {}\", parsed))\n\n } else {\n\n Ok(Box::new(TestPostopt))\n\n }\n\n}\n\n\n\nimpl SubTest for TestPostopt {\n\n fn name(&self) -> Cow<str> {\n\n Cow::from(\"postopt\")\n\n }\n\n\n\n fn is_mutating(&self) -> bool {\n\n true\n\n }\n\n\n\n fn run(&self, func: Cow<Function>, context: &Context) -> Result<()> {\n\n // Create a compilation context, and drop in the function.\n", "file_path": "lib/filetests/src/test_postopt.rs", "rank": 98, "score": 123861.20743456199 }, { "content": "pub fn subtest(parsed: &TestCommand) -> Result<Box<SubTest>> {\n\n assert_eq!(parsed.command, \"domtree\");\n\n if !parsed.options.is_empty() {\n\n Err(format!(\"No options allowed on {}\", parsed))\n\n } else {\n\n Ok(Box::new(TestDomtree))\n\n }\n\n}\n\n\n\nimpl SubTest for TestDomtree {\n\n fn name(&self) -> Cow<str> {\n\n Cow::from(\"domtree\")\n\n }\n\n\n\n // Extract our own dominator tree from\n\n fn run(&self, func: Cow<Function>, context: &Context) -> Result<()> {\n\n let func = func.borrow();\n\n let cfg = ControlFlowGraph::with_function(func);\n\n let domtree = DominatorTree::with_function(func, &cfg);\n\n\n", "file_path": "lib/filetests/src/test_domtree.rs", "rank": 99, "score": 123861.20743456199 } ]
Rust
src/command/mod.rs
rwjblue/notion
05b6b795a732602b7301e6b08a4353caa712c191
mod config; mod current; mod deactivate; mod fetch; mod help; mod install; mod shim; mod use_; mod version; pub(crate) use self::config::Config; pub(crate) use self::current::Current; pub(crate) use self::deactivate::Deactivate; pub(crate) use self::fetch::Fetch; pub(crate) use self::help::Help; pub(crate) use self::install::Install; pub(crate) use self::shim::Shim; pub(crate) use self::use_::Use; pub(crate) use self::version::Version; use docopt::Docopt; use serde::de::DeserializeOwned; use notion_core::session::Session; use notion_fail::{FailExt, Fallible}; use {CliParseError, DocoptExt, Notion}; use std::fmt::{self, Display}; use std::str::FromStr; #[derive(Debug, Deserialize, Clone, Copy)] pub(crate) enum CommandName { Fetch, Install, Use, Config, Current, Deactivate, Shim, Help, Version, } impl Display for CommandName { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!( fmt, "{}", match *self { CommandName::Fetch => "fetch", CommandName::Install => "install", CommandName::Use => "use", CommandName::Config => "config", CommandName::Deactivate => "deactivate", CommandName::Current => "current", CommandName::Shim => "shim", CommandName::Help => "help", CommandName::Version => "version", } ) } } impl FromStr for CommandName { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match s { "fetch" => CommandName::Fetch, "install" => CommandName::Install, "use" => CommandName::Use, "config" => CommandName::Config, "current" => CommandName::Current, "deactivate" => CommandName::Deactivate, "shim" => CommandName::Shim, "help" => CommandName::Help, "version" => CommandName::Version, _ => { throw!(()); } }) } } pub(crate) trait Command: Sized { type Args: DeserializeOwned; const USAGE: &'static str; fn help() -> Self; fn parse(notion: Notion, args: Self::Args) -> Fallible<Self>; fn run(self, session: &mut Session) -> Fallible<()>; fn go(notion: Notion, session: &mut Session) -> Fallible<()> { let argv = notion.full_argv(); let args = Docopt::new(Self::USAGE).and_then(|d| d.argv(argv).deserialize()); match args { Ok(args) => Self::parse(notion, args)?.run(session), Err(err) => { if err.is_help() { Self::help().run(session) } else { throw!(err.with_context(CliParseError::from_docopt)); } } } } }
mod config; mod current; mod deactivate; mod fetch; mod help; mod install; mod shim; mod use_; mod version; pub(crate) use self::config::Config; pub(crate) use self::current::Current; pub(crate) use self::deactivate::Deactivate; pub(crate) use self::fetch::Fetch; pub(crate) use self::help::Help; pub(crate) use self::install::Install; pub(crate) use self::shim::Shim; pub(crate) use self::use_::Use; pub(crate) use self::version::Version; use docopt::Docopt; use serde::de::DeserializeOwned; use notion_core::session::Session; use notion_fail::{FailExt, Fallible}; use {CliParseError, DocoptExt, Notion}; use std::fmt::{self, Display}; use std::str::FromStr; #[derive(Debug, Deserialize, Clone, Copy)] pub(crate) enum CommandName { Fetch, Install, Use, Config, Current, Deactivate, Shim, Help, Version, } impl Display for CommandName { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!( fmt, "{}", match *self { CommandName::Fetch => "fetch", CommandName::Install => "install", CommandName::Use => "use", CommandName::Config => "config", CommandName::Deactivate => "deactivate", CommandName::Current => "current", CommandName::Shim => "shim", CommandName::Help => "help", CommandName::Version => "version", } ) } } impl FromStr for CommandName { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match s { "fetch" => CommandName::Fetch, "install" => CommandName::Install, "use" => CommandName::Use, "config" => CommandName::Config, "current" => CommandName::Current, "deactivate" => CommandName::Deactivate, "shim" => CommandName::Shim, "help" => CommandName::Help, "version" => CommandName::Version, _ => { throw!(()); } }) } } pub(crate) trait Command: Sized { type Args: DeserializeOwned; const USAGE: &'static str; fn help() -> Self; fn parse(notion: Notion, args: Self::Args) -> Fallible<Self>; fn run(self, session: &mut Session) -> Fallible<()>; fn go(notion: Notion, session: &mut Session) -> Fallible<()> { let argv = notion.full_argv(); let args = Docopt::new(Self::USAGE).and_then(|d| d.argv(argv).deserialize()); match args { Ok(args) => Self::parse(notion, args)?.run(session), Err(err) => { if err.is_help() { Self::help().run(session) }
}
else { throw!(err.with_context(CliParseError::from_docopt)); } } } }
function_block-function_prefix_line
[]
Rust
token-lending/program/tests/borrow_obligation_liquidity.rs
panoptesDev/panoptis-program-library
fe410cc1081742ebdf09f22ad21eb8cc511f9918
#![cfg(feature = "test-bpf")] mod helpers; use helpers::*; use solana_program_test::*; use solana_sdk::{ instruction::InstructionError, pubkey::Pubkey, signature::{Keypair, Signer}, transaction::{Transaction, TransactionError}, }; use spl_token_lending::{ error::LendingError, instruction::{borrow_obligation_liquidity, refresh_obligation}, math::Decimal, processor::process_instruction, state::{FeeCalculation, INITIAL_COLLATERAL_RATIO}, }; use std::u64; #[tokio::test] async fn test_borrow_usdc_fixed_amount() { let mut test = ProgramTest::new( "spl_token_lending", spl_token_lending::id(), processor!(process_instruction), ); test.set_bpf_compute_max_units(60_000); const USDC_TOTAL_BORROW_FRACTIONAL: u64 = 1_000 * FRACTIONAL_TO_USDC; const FEE_AMOUNT: u64 = 100; const HOST_FEE_AMOUNT: u64 = 20; const PANO_DEPOSIT_AMOUNT_LAMPORTS: u64 = 100 * LAMPORTS_TO_PANO * INITIAL_COLLATERAL_RATIO; const USDC_BORROW_AMOUNT_FRACTIONAL: u64 = USDC_TOTAL_BORROW_FRACTIONAL - FEE_AMOUNT; const PANO_RESERVE_COLLATERAL_LAMPORTS: u64 = 2 * PANO_DEPOSIT_AMOUNT_LAMPORTS; const USDC_RESERVE_LIQUIDITY_FRACTIONAL: u64 = 2 * USDC_TOTAL_BORROW_FRACTIONAL; let user_accounts_owner = Keypair::new(); let lending_market = add_lending_market(&mut test); let mut reserve_config = TEST_RESERVE_CONFIG; reserve_config.loan_to_value_ratio = 50; let sol_oracle = add_sol_oracle(&mut test); let sol_test_reserve = add_reserve( &mut test, &lending_market, &sol_oracle, &user_accounts_owner, AddReserveArgs { collateral_amount: PANO_RESERVE_COLLATERAL_LAMPORTS, liquidity_mint_pubkey: spl_token::native_mint::id(), liquidity_mint_decimals: 9, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let usdc_mint = add_usdc_mint(&mut test); let usdc_oracle = add_usdc_oracle(&mut test); let usdc_test_reserve = add_reserve( &mut test, &lending_market, &usdc_oracle, &user_accounts_owner, AddReserveArgs { liquidity_amount: USDC_RESERVE_LIQUIDITY_FRACTIONAL, liquidity_mint_pubkey: usdc_mint.pubkey, liquidity_mint_decimals: usdc_mint.decimals, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let test_obligation = add_obligation( &mut test, &lending_market, &user_accounts_owner, AddObligationArgs { deposits: &[(&sol_test_reserve, PANO_DEPOSIT_AMOUNT_LAMPORTS)], ..AddObligationArgs::default() }, ); let (mut banks_client, payer, recent_blockhash) = test.start().await; let initial_liquidity_supply = get_token_balance(&mut banks_client, usdc_test_reserve.liquidity_supply_pubkey).await; let mut transaction = Transaction::new_with_payer( &[ refresh_obligation( spl_token_lending::id(), test_obligation.pubkey, vec![sol_test_reserve.pubkey], ), borrow_obligation_liquidity( spl_token_lending::id(), USDC_BORROW_AMOUNT_FRACTIONAL, usdc_test_reserve.liquidity_supply_pubkey, usdc_test_reserve.user_liquidity_pubkey, usdc_test_reserve.pubkey, usdc_test_reserve.liquidity_fee_receiver_pubkey, test_obligation.pubkey, lending_market.pubkey, test_obligation.owner, Some(usdc_test_reserve.liquidity_host_pubkey), ), ], Some(&payer.pubkey()), ); transaction.sign(&[&payer, &user_accounts_owner], recent_blockhash); assert!(banks_client.process_transaction(transaction).await.is_ok()); let usdc_reserve = usdc_test_reserve.get_state(&mut banks_client).await; let obligation = test_obligation.get_state(&mut banks_client).await; let (total_fee, host_fee) = usdc_reserve .config .fees .calculate_borrow_fees( USDC_BORROW_AMOUNT_FRACTIONAL.into(), FeeCalculation::Exclusive, ) .unwrap(); assert_eq!(total_fee, FEE_AMOUNT); assert_eq!(host_fee, HOST_FEE_AMOUNT); let borrow_amount = get_token_balance(&mut banks_client, usdc_test_reserve.user_liquidity_pubkey).await; assert_eq!(borrow_amount, USDC_BORROW_AMOUNT_FRACTIONAL); let liquidity = &obligation.borrows[0]; assert_eq!( liquidity.borrowed_amount_wads, Decimal::from(USDC_TOTAL_BORROW_FRACTIONAL) ); assert_eq!( usdc_reserve.liquidity.borrowed_amount_wads, liquidity.borrowed_amount_wads ); let liquidity_supply = get_token_balance(&mut banks_client, usdc_test_reserve.liquidity_supply_pubkey).await; assert_eq!( liquidity_supply, initial_liquidity_supply - USDC_TOTAL_BORROW_FRACTIONAL ); let fee_balance = get_token_balance( &mut banks_client, usdc_test_reserve.liquidity_fee_receiver_pubkey, ) .await; assert_eq!(fee_balance, FEE_AMOUNT - HOST_FEE_AMOUNT); let host_fee_balance = get_token_balance(&mut banks_client, usdc_test_reserve.liquidity_host_pubkey).await; assert_eq!(host_fee_balance, HOST_FEE_AMOUNT); } #[tokio::test] async fn test_borrow_sol_max_amount() { let mut test = ProgramTest::new( "spl_token_lending", spl_token_lending::id(), processor!(process_instruction), ); test.set_bpf_compute_max_units(60_000); const FEE_AMOUNT: u64 = 5000; const HOST_FEE_AMOUNT: u64 = 1000; const USDC_DEPOSIT_AMOUNT_FRACTIONAL: u64 = 2_000 * FRACTIONAL_TO_USDC * INITIAL_COLLATERAL_RATIO; const PANO_BORROW_AMOUNT_LAMPORTS: u64 = 50 * LAMPORTS_TO_PANO; const USDC_RESERVE_COLLATERAL_FRACTIONAL: u64 = 2 * USDC_DEPOSIT_AMOUNT_FRACTIONAL; const PANO_RESERVE_LIQUIDITY_LAMPORTS: u64 = 2 * PANO_BORROW_AMOUNT_LAMPORTS; let user_accounts_owner = Keypair::new(); let lending_market = add_lending_market(&mut test); let mut reserve_config = TEST_RESERVE_CONFIG; reserve_config.loan_to_value_ratio = 50; let usdc_mint = add_usdc_mint(&mut test); let usdc_oracle = add_usdc_oracle(&mut test); let usdc_test_reserve = add_reserve( &mut test, &lending_market, &usdc_oracle, &user_accounts_owner, AddReserveArgs { liquidity_amount: USDC_RESERVE_COLLATERAL_FRACTIONAL, liquidity_mint_pubkey: usdc_mint.pubkey, liquidity_mint_decimals: usdc_mint.decimals, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let sol_oracle = add_sol_oracle(&mut test); let sol_test_reserve = add_reserve( &mut test, &lending_market, &sol_oracle, &user_accounts_owner, AddReserveArgs { liquidity_amount: PANO_RESERVE_LIQUIDITY_LAMPORTS, liquidity_mint_pubkey: spl_token::native_mint::id(), liquidity_mint_decimals: 9, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let test_obligation = add_obligation( &mut test, &lending_market, &user_accounts_owner, AddObligationArgs { deposits: &[(&usdc_test_reserve, USDC_DEPOSIT_AMOUNT_FRACTIONAL)], ..AddObligationArgs::default() }, ); let (mut banks_client, payer, recent_blockhash) = test.start().await; let initial_liquidity_supply = get_token_balance(&mut banks_client, sol_test_reserve.liquidity_supply_pubkey).await; let mut transaction = Transaction::new_with_payer( &[ refresh_obligation( spl_token_lending::id(), test_obligation.pubkey, vec![usdc_test_reserve.pubkey], ), borrow_obligation_liquidity( spl_token_lending::id(), u64::MAX, sol_test_reserve.liquidity_supply_pubkey, sol_test_reserve.user_liquidity_pubkey, sol_test_reserve.pubkey, sol_test_reserve.liquidity_fee_receiver_pubkey, test_obligation.pubkey, lending_market.pubkey, test_obligation.owner, Some(sol_test_reserve.liquidity_host_pubkey), ), ], Some(&payer.pubkey()), ); transaction.sign(&[&payer, &user_accounts_owner], recent_blockhash); assert!(banks_client.process_transaction(transaction).await.is_ok()); let sol_reserve = sol_test_reserve.get_state(&mut banks_client).await; let obligation = test_obligation.get_state(&mut banks_client).await; let (total_fee, host_fee) = sol_reserve .config .fees .calculate_borrow_fees(PANO_BORROW_AMOUNT_LAMPORTS.into(), FeeCalculation::Inclusive) .unwrap(); assert_eq!(total_fee, FEE_AMOUNT); assert_eq!(host_fee, HOST_FEE_AMOUNT); let borrow_amount = get_token_balance(&mut banks_client, sol_test_reserve.user_liquidity_pubkey).await; assert_eq!(borrow_amount, PANO_BORROW_AMOUNT_LAMPORTS - FEE_AMOUNT); let liquidity = &obligation.borrows[0]; assert_eq!( liquidity.borrowed_amount_wads, Decimal::from(PANO_BORROW_AMOUNT_LAMPORTS) ); let liquidity_supply = get_token_balance(&mut banks_client, sol_test_reserve.liquidity_supply_pubkey).await; assert_eq!( liquidity_supply, initial_liquidity_supply - PANO_BORROW_AMOUNT_LAMPORTS ); let fee_balance = get_token_balance( &mut banks_client, sol_test_reserve.liquidity_fee_receiver_pubkey, ) .await; assert_eq!(fee_balance, FEE_AMOUNT - HOST_FEE_AMOUNT); let host_fee_balance = get_token_balance(&mut banks_client, sol_test_reserve.liquidity_host_pubkey).await; assert_eq!(host_fee_balance, HOST_FEE_AMOUNT); } #[tokio::test] async fn test_borrow_too_large() { let mut test = ProgramTest::new( "spl_token_lending", spl_token_lending::id(), processor!(process_instruction), ); const PANO_DEPOSIT_AMOUNT_LAMPORTS: u64 = 100 * LAMPORTS_TO_PANO * INITIAL_COLLATERAL_RATIO; const USDC_BORROW_AMOUNT_FRACTIONAL: u64 = 1_000 * FRACTIONAL_TO_USDC + 1; const PANO_RESERVE_COLLATERAL_LAMPORTS: u64 = 2 * PANO_DEPOSIT_AMOUNT_LAMPORTS; const USDC_RESERVE_LIQUIDITY_FRACTIONAL: u64 = 2 * USDC_BORROW_AMOUNT_FRACTIONAL; let user_accounts_owner = Keypair::new(); let lending_market = add_lending_market(&mut test); let mut reserve_config = TEST_RESERVE_CONFIG; reserve_config.loan_to_value_ratio = 50; let sol_oracle = add_sol_oracle(&mut test); let sol_test_reserve = add_reserve( &mut test, &lending_market, &sol_oracle, &user_accounts_owner, AddReserveArgs { collateral_amount: PANO_RESERVE_COLLATERAL_LAMPORTS, liquidity_mint_pubkey: spl_token::native_mint::id(), liquidity_mint_decimals: 9, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let usdc_mint = add_usdc_mint(&mut test); let usdc_oracle = add_usdc_oracle(&mut test); let usdc_test_reserve = add_reserve( &mut test, &lending_market, &usdc_oracle, &user_accounts_owner, AddReserveArgs { liquidity_amount: USDC_RESERVE_LIQUIDITY_FRACTIONAL, liquidity_mint_pubkey: usdc_mint.pubkey, liquidity_mint_decimals: usdc_mint.decimals, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let test_obligation = add_obligation( &mut test, &lending_market, &user_accounts_owner, AddObligationArgs { deposits: &[(&sol_test_reserve, PANO_DEPOSIT_AMOUNT_LAMPORTS)], ..AddObligationArgs::default() }, ); let (mut banks_client, payer, recent_blockhash) = test.start().await; let mut transaction = Transaction::new_with_payer( &[ refresh_obligation( spl_token_lending::id(), test_obligation.pubkey, vec![sol_test_reserve.pubkey], ), borrow_obligation_liquidity( spl_token_lending::id(), USDC_BORROW_AMOUNT_FRACTIONAL, usdc_test_reserve.liquidity_supply_pubkey, usdc_test_reserve.user_liquidity_pubkey, usdc_test_reserve.pubkey, usdc_test_reserve.liquidity_fee_receiver_pubkey, test_obligation.pubkey, lending_market.pubkey, test_obligation.owner, Some(usdc_test_reserve.liquidity_host_pubkey), ), ], Some(&payer.pubkey()), ); transaction.sign(&[&payer, &user_accounts_owner], recent_blockhash); assert_eq!( banks_client .process_transaction(transaction) .await .unwrap_err() .unwrap(), TransactionError::InstructionError( 1, InstructionError::Custom(LendingError::BorrowTooLarge as u32) ) ); }
#![cfg(feature = "test-bpf")] mod helpers; use helpers::*; use solana_program_test::*; use solana_sdk::{ instruction::InstructionError, pubkey::Pubkey, signature::{Keypair, Signer}, transaction::{Transaction, TransactionError}, }; use spl_token_lending::{ error::LendingError, instruction::{borrow_obligation_liquidity, refresh_obligation}, math::Decimal, processor::process_instruction, state::{FeeCalculation, INITIAL_COLLATERAL_RATIO}, }; use std::u64; #[tokio::test] async fn test_borrow_usdc_fixed_amount() { let mut test = ProgramTest::new( "spl_token_lending", spl_token_lending::id(), processor!(process_instruction), ); test.set_bpf_compute_max_units(60_000); const USDC_TOTAL_BORROW_FRACTIONAL: u64 = 1_000 * FRACTIONAL_TO_USDC; const FEE_AMOUNT: u64 = 100; const HOST_FEE_AMOUNT: u64 = 20; const PANO_DEPOSIT_AMOUNT_LAMPORTS: u64 = 100 * LAMPORTS_TO_PANO * INITIAL_COLLATERAL_RATIO; const USDC_BORROW_AMOUNT_FRACTIONAL: u64 = USDC_TOTAL_BORROW_FRACTIONAL - FEE_AMOUNT; const PANO_RESERVE_COLLATERAL_LAMPORTS: u64 = 2 * PANO_DEPOSIT_AMOUNT_LAMPORTS; const USDC_RESERVE_LIQUIDITY_FRACTIONAL: u64 = 2 * USDC_TOTAL_BORROW_FRACTIONAL; let user_accounts_owner = Keypair::new(); let lending_market = add_lending_market(&mut test); let mut reserve_config = TEST_RESERVE_CONFIG; reserve_config.loan_to_value_ratio = 50; let sol_oracle = add_sol_oracle(&mut test); let sol_test_reserve = add_reserve( &mut test, &lending_market, &sol_oracle, &user_accounts_owner, AddReserveArgs { collateral_amount: PANO_RESERVE_COLLATERAL_LAMPORTS, liquidity_mint_pubkey: spl_token::native_mint::id(), liquidity_mint_decimals: 9, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let usdc_mint = add_usdc_mint(&mut test); let usdc_oracle = add_usdc_oracle(&mut test); let usdc_test_reserve = add_reserve( &mut test, &lending_market, &usdc_oracle, &user_accounts_owner, AddReserveArgs { liquidity_amount: USDC_RESERVE_LIQUIDITY_FRACTIONAL, liquidity_mint_pubkey: usdc_mint.pubkey, liquidity_mint_decimals: usdc_mint.decimals, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let test_obligation = add_obligation( &mut test, &lending_market, &user_accounts_owner, AddObligationArgs { deposits: &[(&sol_test_reserve, PANO_DEPOSIT_AMOUNT_LAMPORTS)], ..AddObligationArgs::default() }, ); let (mut banks_client, payer, recent_blockhash) = test.start().await; let initial_liquidity_supply = get_token_balance(&mut banks_client, usdc_test_reserve.liquidity_supply_pubkey).await; let mut transaction = Transaction::new_with_payer( &[ refresh_obligation( spl_token_lending::id(), test_obligation.pubkey, vec![sol_test_reserve.pubkey], ), borrow_obligation_liquidity( spl_token_lending::id(), USDC_BORROW_AMOUNT_FRACTIONAL, usdc_test_reserve.liquidity_supply_pubkey, usdc_test_reserve.user_liquidity_pubkey, usdc_test_reserve.pubkey, usdc_test_reserve.liquidity_fee_receiver_pubkey, test_obligation.pubkey, lending_market.pubkey, test_obligation.owner, Some(usdc_test_reserve.liquidity_host_pubkey), ), ], Some(&payer.pubkey()), ); transaction.sign(&[&payer, &user_accounts_owner], recent_blockhash); assert!(banks_client.process_transaction(transaction).await.is_ok()); let usdc_reserve = usdc_test_reserve.get_state(&mut banks_client).await; let obligation = test_obligation.get_state(&mut banks_client).await; let (total_fee, host_fee) = usdc_reserve .config .fees .calculate_borrow_fees( USDC_BORROW_AMOUNT_FRACTIONAL.into(), FeeCalculation::Exclusive, ) .unwrap(); assert_eq!(total_fee, FEE_AMOUNT); assert_eq!(host_fee, HOST_FEE_AMOUNT); let borrow_amount = get_token_balance(&mut banks_client, usdc_test_reserve.user_liquidity_pubkey).await; assert_eq!(borrow_amount, USDC_BORROW_AMOUNT_FRACTIONAL); let liquidity = &obligation.borrows[0]; assert_eq!( liquidity.borrowed_amount_wads, Decimal::from(USDC_TOTAL_BORROW_FRACTIONAL) ); assert_eq!( usdc_reserve.liquidity.borrowed_amount_wads, liquidity.borrowed_amount_wads ); let liquidity_supply = get_token_balance(&mut banks_client, usdc_test_reserve.liquidity_supply_pubkey).await; assert_eq!( liquidity_supply, initial_liquidity_supply - USDC_TOTAL_BORROW_FRACTIONAL ); let fee_balance = get_token_balance( &mut banks_client, usdc_test_reserve.liquidity_fee_receiver_pubkey, ) .await; assert_eq!(fee_balance, FEE_AMOUNT - HOST_FEE_AMOUNT); let host_fee_balance = get_token_balance(&mut banks_client, usdc_test_reserve.liquidity_host_pubkey).await; assert_eq!(host_fee_balance, HOST_FEE_AMOUNT); } #[tokio::test] async fn test_borrow_sol_max_amount() {
test.set_bpf_compute_max_units(60_000); const FEE_AMOUNT: u64 = 5000; const HOST_FEE_AMOUNT: u64 = 1000; const USDC_DEPOSIT_AMOUNT_FRACTIONAL: u64 = 2_000 * FRACTIONAL_TO_USDC * INITIAL_COLLATERAL_RATIO; const PANO_BORROW_AMOUNT_LAMPORTS: u64 = 50 * LAMPORTS_TO_PANO; const USDC_RESERVE_COLLATERAL_FRACTIONAL: u64 = 2 * USDC_DEPOSIT_AMOUNT_FRACTIONAL; const PANO_RESERVE_LIQUIDITY_LAMPORTS: u64 = 2 * PANO_BORROW_AMOUNT_LAMPORTS; let user_accounts_owner = Keypair::new(); let lending_market = add_lending_market(&mut test); let mut reserve_config = TEST_RESERVE_CONFIG; reserve_config.loan_to_value_ratio = 50; let usdc_mint = add_usdc_mint(&mut test); let usdc_oracle = add_usdc_oracle(&mut test); let usdc_test_reserve = add_reserve( &mut test, &lending_market, &usdc_oracle, &user_accounts_owner, AddReserveArgs { liquidity_amount: USDC_RESERVE_COLLATERAL_FRACTIONAL, liquidity_mint_pubkey: usdc_mint.pubkey, liquidity_mint_decimals: usdc_mint.decimals, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let sol_oracle = add_sol_oracle(&mut test); let sol_test_reserve = add_reserve( &mut test, &lending_market, &sol_oracle, &user_accounts_owner, AddReserveArgs { liquidity_amount: PANO_RESERVE_LIQUIDITY_LAMPORTS, liquidity_mint_pubkey: spl_token::native_mint::id(), liquidity_mint_decimals: 9, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let test_obligation = add_obligation( &mut test, &lending_market, &user_accounts_owner, AddObligationArgs { deposits: &[(&usdc_test_reserve, USDC_DEPOSIT_AMOUNT_FRACTIONAL)], ..AddObligationArgs::default() }, ); let (mut banks_client, payer, recent_blockhash) = test.start().await; let initial_liquidity_supply = get_token_balance(&mut banks_client, sol_test_reserve.liquidity_supply_pubkey).await; let mut transaction = Transaction::new_with_payer( &[ refresh_obligation( spl_token_lending::id(), test_obligation.pubkey, vec![usdc_test_reserve.pubkey], ), borrow_obligation_liquidity( spl_token_lending::id(), u64::MAX, sol_test_reserve.liquidity_supply_pubkey, sol_test_reserve.user_liquidity_pubkey, sol_test_reserve.pubkey, sol_test_reserve.liquidity_fee_receiver_pubkey, test_obligation.pubkey, lending_market.pubkey, test_obligation.owner, Some(sol_test_reserve.liquidity_host_pubkey), ), ], Some(&payer.pubkey()), ); transaction.sign(&[&payer, &user_accounts_owner], recent_blockhash); assert!(banks_client.process_transaction(transaction).await.is_ok()); let sol_reserve = sol_test_reserve.get_state(&mut banks_client).await; let obligation = test_obligation.get_state(&mut banks_client).await; let (total_fee, host_fee) = sol_reserve .config .fees .calculate_borrow_fees(PANO_BORROW_AMOUNT_LAMPORTS.into(), FeeCalculation::Inclusive) .unwrap(); assert_eq!(total_fee, FEE_AMOUNT); assert_eq!(host_fee, HOST_FEE_AMOUNT); let borrow_amount = get_token_balance(&mut banks_client, sol_test_reserve.user_liquidity_pubkey).await; assert_eq!(borrow_amount, PANO_BORROW_AMOUNT_LAMPORTS - FEE_AMOUNT); let liquidity = &obligation.borrows[0]; assert_eq!( liquidity.borrowed_amount_wads, Decimal::from(PANO_BORROW_AMOUNT_LAMPORTS) ); let liquidity_supply = get_token_balance(&mut banks_client, sol_test_reserve.liquidity_supply_pubkey).await; assert_eq!( liquidity_supply, initial_liquidity_supply - PANO_BORROW_AMOUNT_LAMPORTS ); let fee_balance = get_token_balance( &mut banks_client, sol_test_reserve.liquidity_fee_receiver_pubkey, ) .await; assert_eq!(fee_balance, FEE_AMOUNT - HOST_FEE_AMOUNT); let host_fee_balance = get_token_balance(&mut banks_client, sol_test_reserve.liquidity_host_pubkey).await; assert_eq!(host_fee_balance, HOST_FEE_AMOUNT); } #[tokio::test] async fn test_borrow_too_large() { let mut test = ProgramTest::new( "spl_token_lending", spl_token_lending::id(), processor!(process_instruction), ); const PANO_DEPOSIT_AMOUNT_LAMPORTS: u64 = 100 * LAMPORTS_TO_PANO * INITIAL_COLLATERAL_RATIO; const USDC_BORROW_AMOUNT_FRACTIONAL: u64 = 1_000 * FRACTIONAL_TO_USDC + 1; const PANO_RESERVE_COLLATERAL_LAMPORTS: u64 = 2 * PANO_DEPOSIT_AMOUNT_LAMPORTS; const USDC_RESERVE_LIQUIDITY_FRACTIONAL: u64 = 2 * USDC_BORROW_AMOUNT_FRACTIONAL; let user_accounts_owner = Keypair::new(); let lending_market = add_lending_market(&mut test); let mut reserve_config = TEST_RESERVE_CONFIG; reserve_config.loan_to_value_ratio = 50; let sol_oracle = add_sol_oracle(&mut test); let sol_test_reserve = add_reserve( &mut test, &lending_market, &sol_oracle, &user_accounts_owner, AddReserveArgs { collateral_amount: PANO_RESERVE_COLLATERAL_LAMPORTS, liquidity_mint_pubkey: spl_token::native_mint::id(), liquidity_mint_decimals: 9, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let usdc_mint = add_usdc_mint(&mut test); let usdc_oracle = add_usdc_oracle(&mut test); let usdc_test_reserve = add_reserve( &mut test, &lending_market, &usdc_oracle, &user_accounts_owner, AddReserveArgs { liquidity_amount: USDC_RESERVE_LIQUIDITY_FRACTIONAL, liquidity_mint_pubkey: usdc_mint.pubkey, liquidity_mint_decimals: usdc_mint.decimals, config: reserve_config, mark_fresh: true, ..AddReserveArgs::default() }, ); let test_obligation = add_obligation( &mut test, &lending_market, &user_accounts_owner, AddObligationArgs { deposits: &[(&sol_test_reserve, PANO_DEPOSIT_AMOUNT_LAMPORTS)], ..AddObligationArgs::default() }, ); let (mut banks_client, payer, recent_blockhash) = test.start().await; let mut transaction = Transaction::new_with_payer( &[ refresh_obligation( spl_token_lending::id(), test_obligation.pubkey, vec![sol_test_reserve.pubkey], ), borrow_obligation_liquidity( spl_token_lending::id(), USDC_BORROW_AMOUNT_FRACTIONAL, usdc_test_reserve.liquidity_supply_pubkey, usdc_test_reserve.user_liquidity_pubkey, usdc_test_reserve.pubkey, usdc_test_reserve.liquidity_fee_receiver_pubkey, test_obligation.pubkey, lending_market.pubkey, test_obligation.owner, Some(usdc_test_reserve.liquidity_host_pubkey), ), ], Some(&payer.pubkey()), ); transaction.sign(&[&payer, &user_accounts_owner], recent_blockhash); assert_eq!( banks_client .process_transaction(transaction) .await .unwrap_err() .unwrap(), TransactionError::InstructionError( 1, InstructionError::Custom(LendingError::BorrowTooLarge as u32) ) ); }
let mut test = ProgramTest::new( "spl_token_lending", spl_token_lending::id(), processor!(process_instruction), );
assignment_statement
[ { "content": "fn check_fee_payer_balance(config: &Config, required_balance: u64) -> Result<(), Error> {\n\n let balance = config.rpc_client.get_balance(&config.fee_payer)?;\n\n if balance < required_balance {\n\n Err(format!(\n\n \"Fee payer, {}, has insufficient balance: {} required, {} available\",\n\n config.fee_payer,\n\n lamports_to_sol(required_balance),\n\n lamports_to_sol(balance)\n\n )\n\n .into())\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "token/cli/src/main.rs", "rank": 0, "score": 298573.1699227292 }, { "content": "pub fn add_usdc_oracle(test: &mut ProgramTest) -> TestOracle {\n\n add_oracle(\n\n test,\n\n // Mock with SRM since Pyth doesn't have USDC yet\n\n Pubkey::from_str(SRM_PYTH_PRODUCT).unwrap(),\n\n Pubkey::from_str(SRM_PYTH_PRICE).unwrap(),\n\n // Set USDC price to $1\n\n Decimal::from(1u64),\n\n )\n\n}\n\n\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 1, "score": 296596.72769772523 }, { "content": "pub fn add_usdc_mint(test: &mut ProgramTest) -> TestMint {\n\n let authority = Keypair::new();\n\n let pubkey = Pubkey::from_str(USDC_MINT).unwrap();\n\n let decimals = 6;\n\n test.add_packable_account(\n\n pubkey,\n\n u32::MAX as u64,\n\n &Mint {\n\n is_initialized: true,\n\n mint_authority: COption::Some(authority.pubkey()),\n\n decimals,\n\n ..Mint::default()\n\n },\n\n &spl_token::id(),\n\n );\n\n TestMint {\n\n pubkey,\n\n authority,\n\n decimals,\n\n }\n\n}\n\n\n\npub struct TestOracle {\n\n pub product_pubkey: Pubkey,\n\n pub price_pubkey: Pubkey,\n\n pub price: Decimal,\n\n}\n\n\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 2, "score": 296596.72769772523 }, { "content": "pub fn add_sol_oracle(test: &mut ProgramTest) -> TestOracle {\n\n add_oracle(\n\n test,\n\n Pubkey::from_str(PANO_PYTH_PRODUCT).unwrap(),\n\n Pubkey::from_str(PANO_PYTH_PRICE).unwrap(),\n\n // Set PANO price to $20\n\n Decimal::from(20u64),\n\n )\n\n}\n\n\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 3, "score": 296596.72769772523 }, { "content": "fn check_fee_payer_balance(config: &Config, required_balance: u64) -> Result<(), Error> {\n\n let balance = config.rpc_client.get_balance(&config.fee_payer.pubkey())?;\n\n if balance < required_balance {\n\n Err(format!(\n\n \"Fee payer, {}, has insufficient balance: {} required, {} available\",\n\n config.fee_payer.pubkey(),\n\n lamports_to_sol(required_balance),\n\n lamports_to_sol(balance)\n\n )\n\n .into())\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "token-lending/cli/src/main.rs", "rank": 4, "score": 294378.59589417087 }, { "content": "fn check_fee_payer_balance(config: &Config, required_balance: u64) -> Result<(), Error> {\n\n let balance = config.rpc_client.get_balance(&config.fee_payer.pubkey())?;\n\n if balance < required_balance {\n\n Err(format!(\n\n \"Fee payer, {}, has insufficient balance: {} required, {} available\",\n\n config.fee_payer.pubkey(),\n\n Sol(required_balance),\n\n Sol(balance)\n\n )\n\n .into())\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "stake-pool/cli/src/main.rs", "rank": 5, "score": 294378.59589417087 }, { "content": "pub fn add_lending_market(test: &mut ProgramTest) -> TestLendingMarket {\n\n let lending_market_pubkey = Pubkey::new_unique();\n\n let (lending_market_authority, bump_seed) =\n\n Pubkey::find_program_address(&[lending_market_pubkey.as_ref()], &spl_token_lending::id());\n\n\n\n let lending_market_owner =\n\n read_keypair_file(\"tests/fixtures/lending_market_owner.json\").unwrap();\n\n let oracle_program_id = read_keypair_file(\"tests/fixtures/oracle_program_id.json\")\n\n .unwrap()\n\n .pubkey();\n\n\n\n test.add_packable_account(\n\n lending_market_pubkey,\n\n u32::MAX as u64,\n\n &LendingMarket::new(InitLendingMarketParams {\n\n bump_seed,\n\n owner: lending_market_owner.pubkey(),\n\n quote_currency: QUOTE_CURRENCY,\n\n token_program_id: spl_token::id(),\n\n oracle_program_id,\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 6, "score": 292787.97172707255 }, { "content": "pub fn add_obligation(\n\n test: &mut ProgramTest,\n\n lending_market: &TestLendingMarket,\n\n user_accounts_owner: &Keypair,\n\n args: AddObligationArgs,\n\n) -> TestObligation {\n\n let AddObligationArgs {\n\n deposits,\n\n borrows,\n\n mark_fresh,\n\n slots_elapsed,\n\n } = args;\n\n\n\n let obligation_keypair = Keypair::new();\n\n let obligation_pubkey = obligation_keypair.pubkey();\n\n\n\n let (obligation_deposits, test_deposits) = deposits\n\n .iter()\n\n .map(|(deposit_reserve, collateral_amount)| {\n\n let mut collateral = ObligationCollateral::new(deposit_reserve.pubkey);\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 7, "score": 269192.43414324 }, { "content": "pub fn program_test() -> ProgramTest {\n\n ProgramTest::new(\n\n \"spl_stake_pool\",\n\n id(),\n\n processor!(processor::Processor::process),\n\n )\n\n}\n\n\n\npub async fn get_account(banks_client: &mut BanksClient, pubkey: &Pubkey) -> Account {\n\n banks_client\n\n .get_account(*pubkey)\n\n .await\n\n .expect(\"account not found\")\n\n .expect(\"account empty\")\n\n}\n\n\n\npub async fn create_mint(\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n recent_blockhash: &Hash,\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 8, "score": 228657.61583259248 }, { "content": "fn command_set_fee(config: &Config, stake_pool_address: &Pubkey, new_fee: Fee) -> CommandResult {\n\n let mut signers = vec![config.fee_payer.as_ref(), config.manager.as_ref()];\n\n unique_signers!(signers);\n\n let transaction = checked_transaction_with_signers(\n\n config,\n\n &[spl_stake_pool::instruction::set_fee(\n\n &spl_stake_pool::id(),\n\n stake_pool_address,\n\n &config.manager.pubkey(),\n\n new_fee,\n\n )],\n\n &signers,\n\n )?;\n\n send_transaction(config, transaction)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "stake-pool/cli/src/main.rs", "rank": 9, "score": 222666.98712799413 }, { "content": "pub fn add_reserve(\n\n test: &mut ProgramTest,\n\n lending_market: &TestLendingMarket,\n\n oracle: &TestOracle,\n\n user_accounts_owner: &Keypair,\n\n args: AddReserveArgs,\n\n) -> TestReserve {\n\n let AddReserveArgs {\n\n name,\n\n config,\n\n liquidity_amount,\n\n liquidity_mint_pubkey,\n\n liquidity_mint_decimals,\n\n user_liquidity_amount,\n\n borrow_amount,\n\n initial_borrow_rate,\n\n collateral_amount,\n\n mark_fresh,\n\n slots_elapsed,\n\n } = args;\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 10, "score": 221575.3836607206 }, { "content": "pub fn add_oracle(\n\n test: &mut ProgramTest,\n\n product_pubkey: Pubkey,\n\n price_pubkey: Pubkey,\n\n price: Decimal,\n\n) -> TestOracle {\n\n let oracle_program_id = read_keypair_file(\"tests/fixtures/oracle_program_id.json\").unwrap();\n\n\n\n // Add Pyth product account\n\n test.add_account_with_file_data(\n\n product_pubkey,\n\n u32::MAX as u64,\n\n oracle_program_id.pubkey(),\n\n &format!(\"{}.bin\", product_pubkey.to_string()),\n\n );\n\n\n\n // Add Pyth price account after setting the price\n\n let filename = &format!(\"{}.bin\", price_pubkey.to_string());\n\n let mut pyth_price_data = read_file(find_file(filename).unwrap_or_else(|| {\n\n panic!(\"Unable to locate {}\", filename);\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 11, "score": 221575.3836607206 }, { "content": "pub fn add_account_for_program(\n\n test: &mut ProgramTest,\n\n program_derived_account: &Pubkey,\n\n amount: u64,\n\n mint_pubkey: &Pubkey,\n\n) -> Pubkey {\n\n let program_owned_token_account = Keypair::new();\n\n test.add_packable_account(\n\n program_owned_token_account.pubkey(),\n\n u32::MAX as u64,\n\n &Token {\n\n mint: *mint_pubkey,\n\n owner: *program_derived_account,\n\n amount,\n\n state: AccountState::Initialized,\n\n is_native: COption::None,\n\n ..Token::default()\n\n },\n\n &spl_token::id(),\n\n );\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 12, "score": 217165.52033353638 }, { "content": "fn pack_coption_u64(src: &COption<u64>, dst: &mut [u8; 12]) {\n\n let (tag, body) = mut_array_refs![dst, 4, 8];\n\n match src {\n\n COption::Some(amount) => {\n\n *tag = [1, 0, 0, 0];\n\n *body = amount.to_le_bytes();\n\n }\n\n COption::None => {\n\n *tag = [0; 4];\n\n }\n\n }\n\n}\n", "file_path": "token/program/src/state.rs", "rank": 13, "score": 201392.49587930652 }, { "content": "fn validate_fraction(numerator: u64, denominator: u64) -> Result<(), SwapError> {\n\n if denominator == 0 && numerator == 0 {\n\n Ok(())\n\n } else if numerator >= denominator {\n\n Err(SwapError::InvalidFee)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl Fees {\n\n /// Calculate the withdraw fee in pool tokens\n\n pub fn owner_withdraw_fee(&self, pool_tokens: u128) -> Option<u128> {\n\n calculate_fee(\n\n pool_tokens,\n\n u128::try_from(self.owner_withdraw_fee_numerator).ok()?,\n\n u128::try_from(self.owner_withdraw_fee_denominator).ok()?,\n\n )\n\n }\n\n\n", "file_path": "token-swap/program/src/curve/fees.rs", "rank": 14, "score": 193122.75112247438 }, { "content": "#[allow(non_snake_case)]\n\npub fn NopOverride<T>(_: &mut T) {}\n", "file_path": "governance/program/tests/program_test/tools.rs", "rank": 15, "score": 190681.34683059863 }, { "content": "#[inline(never)] // avoid stack frame limit\n\nfn process_liquidate_obligation(\n\n program_id: &Pubkey,\n\n liquidity_amount: u64,\n\n accounts: &[AccountInfo],\n\n) -> ProgramResult {\n\n if liquidity_amount == 0 {\n\n msg!(\"Liquidity amount provided cannot be zero\");\n\n return Err(LendingError::InvalidAmount.into());\n\n }\n\n\n\n let account_info_iter = &mut accounts.iter();\n\n let source_liquidity_info = next_account_info(account_info_iter)?;\n\n let destination_collateral_info = next_account_info(account_info_iter)?;\n\n let repay_reserve_info = next_account_info(account_info_iter)?;\n\n let repay_reserve_liquidity_supply_info = next_account_info(account_info_iter)?;\n\n let withdraw_reserve_info = next_account_info(account_info_iter)?;\n\n let withdraw_reserve_collateral_supply_info = next_account_info(account_info_iter)?;\n\n let obligation_info = next_account_info(account_info_iter)?;\n\n let lending_market_info = next_account_info(account_info_iter)?;\n\n let lending_market_authority_info = next_account_info(account_info_iter)?;\n", "file_path": "token-lending/program/src/processor.rs", "rank": 16, "score": 184043.8804435461 }, { "content": "fn checked_transaction_with_signers<T: Signers>(\n\n config: &Config,\n\n instructions: &[Instruction],\n\n signers: &T,\n\n) -> Result<Transaction, Error> {\n\n let (recent_blockhash, fee_calculator) = config.rpc_client.get_recent_blockhash()?;\n\n let transaction = Transaction::new_signed_with_payer(\n\n instructions,\n\n Some(&config.fee_payer.pubkey()),\n\n signers,\n\n recent_blockhash,\n\n );\n\n\n\n check_fee_payer_balance(config, fee_calculator.calculate_fee(transaction.message()))?;\n\n Ok(transaction)\n\n}\n\n\n", "file_path": "stake-pool/cli/src/main.rs", "rank": 17, "score": 182625.16132502805 }, { "content": "fn process_deposit_reserve_liquidity(\n\n program_id: &Pubkey,\n\n liquidity_amount: u64,\n\n accounts: &[AccountInfo],\n\n) -> ProgramResult {\n\n if liquidity_amount == 0 {\n\n msg!(\"Liquidity amount provided cannot be zero\");\n\n return Err(LendingError::InvalidAmount.into());\n\n }\n\n\n\n let account_info_iter = &mut accounts.iter();\n\n let source_liquidity_info = next_account_info(account_info_iter)?;\n\n let destination_collateral_info = next_account_info(account_info_iter)?;\n\n let reserve_info = next_account_info(account_info_iter)?;\n\n let reserve_liquidity_supply_info = next_account_info(account_info_iter)?;\n\n let reserve_collateral_mint_info = next_account_info(account_info_iter)?;\n\n let lending_market_info = next_account_info(account_info_iter)?;\n\n let lending_market_authority_info = next_account_info(account_info_iter)?;\n\n let user_transfer_authority_info = next_account_info(account_info_iter)?;\n\n let clock = &Clock::from_account_info(next_account_info(account_info_iter)?)?;\n", "file_path": "token-lending/program/src/processor.rs", "rank": 18, "score": 180631.17476131232 }, { "content": "#[inline(never)] // avoid stack frame limit\n\nfn process_borrow_obligation_liquidity(\n\n program_id: &Pubkey,\n\n liquidity_amount: u64,\n\n accounts: &[AccountInfo],\n\n) -> ProgramResult {\n\n if liquidity_amount == 0 {\n\n msg!(\"Liquidity amount provided cannot be zero\");\n\n return Err(LendingError::InvalidAmount.into());\n\n }\n\n\n\n let account_info_iter = &mut accounts.iter();\n\n let source_liquidity_info = next_account_info(account_info_iter)?;\n\n let destination_liquidity_info = next_account_info(account_info_iter)?;\n\n let borrow_reserve_info = next_account_info(account_info_iter)?;\n\n let borrow_reserve_liquidity_fee_receiver_info = next_account_info(account_info_iter)?;\n\n let obligation_info = next_account_info(account_info_iter)?;\n\n let lending_market_info = next_account_info(account_info_iter)?;\n\n let lending_market_authority_info = next_account_info(account_info_iter)?;\n\n let obligation_owner_info = next_account_info(account_info_iter)?;\n\n let clock = &Clock::from_account_info(next_account_info(account_info_iter)?)?;\n", "file_path": "token-lending/program/src/processor.rs", "rank": 19, "score": 180539.76378724384 }, { "content": "#[inline(never)] // avoid stack frame limit\n\nfn process_repay_obligation_liquidity(\n\n program_id: &Pubkey,\n\n liquidity_amount: u64,\n\n accounts: &[AccountInfo],\n\n) -> ProgramResult {\n\n if liquidity_amount == 0 {\n\n msg!(\"Liquidity amount provided cannot be zero\");\n\n return Err(LendingError::InvalidAmount.into());\n\n }\n\n\n\n let account_info_iter = &mut accounts.iter();\n\n let source_liquidity_info = next_account_info(account_info_iter)?;\n\n let destination_liquidity_info = next_account_info(account_info_iter)?;\n\n let repay_reserve_info = next_account_info(account_info_iter)?;\n\n let obligation_info = next_account_info(account_info_iter)?;\n\n let lending_market_info = next_account_info(account_info_iter)?;\n\n let user_transfer_authority_info = next_account_info(account_info_iter)?;\n\n let clock = &Clock::from_account_info(next_account_info(account_info_iter)?)?;\n\n let token_program_id = next_account_info(account_info_iter)?;\n\n\n", "file_path": "token-lending/program/src/processor.rs", "rank": 20, "score": 180539.76378724384 }, { "content": "#[inline(never)] // avoid stack frame limit\n\nfn process_deposit_obligation_collateral(\n\n program_id: &Pubkey,\n\n collateral_amount: u64,\n\n accounts: &[AccountInfo],\n\n) -> ProgramResult {\n\n if collateral_amount == 0 {\n\n msg!(\"Collateral amount provided cannot be zero\");\n\n return Err(LendingError::InvalidAmount.into());\n\n }\n\n\n\n let account_info_iter = &mut accounts.iter();\n\n let source_collateral_info = next_account_info(account_info_iter)?;\n\n let destination_collateral_info = next_account_info(account_info_iter)?;\n\n let deposit_reserve_info = next_account_info(account_info_iter)?;\n\n let obligation_info = next_account_info(account_info_iter)?;\n\n let lending_market_info = next_account_info(account_info_iter)?;\n\n let lending_market_authority_info = next_account_info(account_info_iter)?;\n\n let obligation_owner_info = next_account_info(account_info_iter)?;\n\n let user_transfer_authority_info = next_account_info(account_info_iter)?;\n\n let clock = &Clock::from_account_info(next_account_info(account_info_iter)?)?;\n", "file_path": "token-lending/program/src/processor.rs", "rank": 21, "score": 180500.15207705807 }, { "content": "#[inline(never)]\n\nfn u64_divide(dividend: u64, divisor: u64) -> u64 {\n\n dividend / divisor\n\n}\n\n\n\n/// f32_multiply\n", "file_path": "libraries/math/src/processor.rs", "rank": 22, "score": 179883.2551837993 }, { "content": "#[inline(never)]\n\nfn u64_multiply(multiplicand: u64, multiplier: u64) -> u64 {\n\n multiplicand * multiplier\n\n}\n\n\n\n/// u64_divide\n", "file_path": "libraries/math/src/processor.rs", "rank": 23, "score": 179883.2551837993 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn liquidate_obligation(\n\n program_id: Pubkey,\n\n liquidity_amount: u64,\n\n source_liquidity_pubkey: Pubkey,\n\n destination_collateral_pubkey: Pubkey,\n\n repay_reserve_pubkey: Pubkey,\n\n repay_reserve_liquidity_supply_pubkey: Pubkey,\n\n withdraw_reserve_pubkey: Pubkey,\n\n withdraw_reserve_collateral_supply_pubkey: Pubkey,\n\n obligation_pubkey: Pubkey,\n\n lending_market_pubkey: Pubkey,\n\n user_transfer_authority_pubkey: Pubkey,\n\n) -> Instruction {\n\n let (lending_market_authority_pubkey, _bump_seed) = Pubkey::find_program_address(\n\n &[&lending_market_pubkey.to_bytes()[..PUBKEY_BYTES]],\n\n &program_id,\n\n );\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n", "file_path": "token-lending/program/src/instruction.rs", "rank": 24, "score": 179402.24993830014 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn deposit_reserve_liquidity(\n\n program_id: Pubkey,\n\n liquidity_amount: u64,\n\n source_liquidity_pubkey: Pubkey,\n\n destination_collateral_pubkey: Pubkey,\n\n reserve_pubkey: Pubkey,\n\n reserve_liquidity_supply_pubkey: Pubkey,\n\n reserve_collateral_mint_pubkey: Pubkey,\n\n lending_market_pubkey: Pubkey,\n\n user_transfer_authority_pubkey: Pubkey,\n\n) -> Instruction {\n\n let (lending_market_authority_pubkey, _bump_seed) = Pubkey::find_program_address(\n\n &[&lending_market_pubkey.to_bytes()[..PUBKEY_BYTES]],\n\n &program_id,\n\n );\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n\n AccountMeta::new(source_liquidity_pubkey, false),\n\n AccountMeta::new(destination_collateral_pubkey, false),\n", "file_path": "token-lending/program/src/instruction.rs", "rank": 25, "score": 175989.54425606635 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn repay_obligation_liquidity(\n\n program_id: Pubkey,\n\n liquidity_amount: u64,\n\n source_liquidity_pubkey: Pubkey,\n\n destination_liquidity_pubkey: Pubkey,\n\n repay_reserve_pubkey: Pubkey,\n\n obligation_pubkey: Pubkey,\n\n lending_market_pubkey: Pubkey,\n\n user_transfer_authority_pubkey: Pubkey,\n\n) -> Instruction {\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n\n AccountMeta::new(source_liquidity_pubkey, false),\n\n AccountMeta::new(destination_liquidity_pubkey, false),\n\n AccountMeta::new(repay_reserve_pubkey, false),\n\n AccountMeta::new(obligation_pubkey, false),\n\n AccountMeta::new_readonly(lending_market_pubkey, false),\n\n AccountMeta::new_readonly(user_transfer_authority_pubkey, true),\n\n AccountMeta::new_readonly(sysvar::clock::id(), false),\n\n AccountMeta::new_readonly(spl_token::id(), false),\n\n ],\n\n data: LendingInstruction::RepayObligationLiquidity { liquidity_amount }.pack(),\n\n }\n\n}\n\n\n\n/// Creates a `LiquidateObligation` instruction\n", "file_path": "token-lending/program/src/instruction.rs", "rank": 26, "score": 175898.13328199787 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn borrow_obligation_liquidity(\n\n program_id: Pubkey,\n\n liquidity_amount: u64,\n\n source_liquidity_pubkey: Pubkey,\n\n destination_liquidity_pubkey: Pubkey,\n\n borrow_reserve_pubkey: Pubkey,\n\n borrow_reserve_liquidity_fee_receiver_pubkey: Pubkey,\n\n obligation_pubkey: Pubkey,\n\n lending_market_pubkey: Pubkey,\n\n obligation_owner_pubkey: Pubkey,\n\n host_fee_receiver_pubkey: Option<Pubkey>,\n\n) -> Instruction {\n\n let (lending_market_authority_pubkey, _bump_seed) = Pubkey::find_program_address(\n\n &[&lending_market_pubkey.to_bytes()[..PUBKEY_BYTES]],\n\n &program_id,\n\n );\n\n let mut accounts = vec![\n\n AccountMeta::new(source_liquidity_pubkey, false),\n\n AccountMeta::new(destination_liquidity_pubkey, false),\n\n AccountMeta::new(borrow_reserve_pubkey, false),\n", "file_path": "token-lending/program/src/instruction.rs", "rank": 27, "score": 175898.13328199787 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn deposit_obligation_collateral(\n\n program_id: Pubkey,\n\n collateral_amount: u64,\n\n source_collateral_pubkey: Pubkey,\n\n destination_collateral_pubkey: Pubkey,\n\n deposit_reserve_pubkey: Pubkey,\n\n obligation_pubkey: Pubkey,\n\n lending_market_pubkey: Pubkey,\n\n obligation_owner_pubkey: Pubkey,\n\n user_transfer_authority_pubkey: Pubkey,\n\n) -> Instruction {\n\n let (lending_market_authority_pubkey, _bump_seed) = Pubkey::find_program_address(\n\n &[&lending_market_pubkey.to_bytes()[..PUBKEY_BYTES]],\n\n &program_id,\n\n );\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n\n AccountMeta::new(source_collateral_pubkey, false),\n\n AccountMeta::new(destination_collateral_pubkey, false),\n", "file_path": "token-lending/program/src/instruction.rs", "rank": 28, "score": 175858.5215718121 }, { "content": "// Helpers\n\nfn pack_decimal(decimal: Decimal, dst: &mut [u8; 16]) {\n\n *dst = decimal\n\n .to_scaled_val()\n\n .expect(\"Decimal cannot be packed\")\n\n .to_le_bytes();\n\n}\n\n\n", "file_path": "token-lending/program/src/state/mod.rs", "rank": 29, "score": 172644.41812176394 }, { "content": "fn pack_bool(boolean: bool, dst: &mut [u8; 1]) {\n\n *dst = (boolean as u8).to_le_bytes()\n\n}\n\n\n", "file_path": "token-lending/program/src/state/mod.rs", "rank": 30, "score": 172638.0823495953 }, { "content": "/// Creates instructions required to deposit into a stake pool, given a stake\n\n/// account owned by the user.\n\npub fn deposit(\n\n program_id: &Pubkey,\n\n stake_pool: &Pubkey,\n\n validator_list_storage: &Pubkey,\n\n stake_pool_withdraw_authority: &Pubkey,\n\n deposit_stake_address: &Pubkey,\n\n deposit_stake_withdraw_authority: &Pubkey,\n\n validator_stake_account: &Pubkey,\n\n reserve_stake_account: &Pubkey,\n\n pool_tokens_to: &Pubkey,\n\n pool_mint: &Pubkey,\n\n token_program_id: &Pubkey,\n\n) -> Vec<Instruction> {\n\n let stake_pool_deposit_authority =\n\n find_deposit_authority_program_address(program_id, stake_pool).0;\n\n let accounts = vec![\n\n AccountMeta::new(*stake_pool, false),\n\n AccountMeta::new(*validator_list_storage, false),\n\n AccountMeta::new_readonly(stake_pool_deposit_authority, false),\n\n AccountMeta::new_readonly(*stake_pool_withdraw_authority, false),\n", "file_path": "stake-pool/program/src/instruction.rs", "rank": 31, "score": 168321.3621736373 }, { "content": "pub fn process_instruction(\n\n program_id: &Pubkey,\n\n accounts: &[AccountInfo],\n\n instruction_data: &[u8],\n\n) -> ProgramResult {\n\n Processor::process(program_id, accounts, instruction_data)\n\n}\n\n\n\npub struct Processor;\n\nimpl Processor {\n\n pub fn process(\n\n program_id: &Pubkey,\n\n accounts: &[AccountInfo],\n\n instruction_data: &[u8],\n\n ) -> ProgramResult {\n\n let instruction = FlashLoanReceiverInstruction::unpack(instruction_data)?;\n\n\n\n match instruction {\n\n FlashLoanReceiverInstruction::ReceiveFlashLoan { amount } => {\n\n msg!(\"Instruction: Receive Flash Loan\");\n", "file_path": "token-lending/program/tests/helpers/flash_loan_receiver.rs", "rank": 32, "score": 167605.0681990452 }, { "content": "/// Create a `RecordInstruction::Write` instruction\n\npub fn write(record_account: &Pubkey, signer: &Pubkey, offset: u64, data: Vec<u8>) -> Instruction {\n\n Instruction::new_with_borsh(\n\n id(),\n\n &RecordInstruction::Write { offset, data },\n\n vec![\n\n AccountMeta::new(*record_account, false),\n\n AccountMeta::new_readonly(*signer, true),\n\n ],\n\n )\n\n}\n\n\n", "file_path": "record/program/src/instruction.rs", "rank": 33, "score": 166515.99833653396 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn deposit(\n\n program_id: &Pubkey,\n\n pool: &Pubkey,\n\n authority: &Pubkey,\n\n user_transfer_authority: &Pubkey,\n\n user_token_account: &Pubkey,\n\n pool_deposit_token_account: &Pubkey,\n\n token_pass_mint: &Pubkey,\n\n token_fail_mint: &Pubkey,\n\n token_pass_destination_account: &Pubkey,\n\n token_fail_destination_account: &Pubkey,\n\n token_program_id: &Pubkey,\n\n amount: u64,\n\n) -> Result<Instruction, ProgramError> {\n\n let init_data = PoolInstruction::Deposit(amount);\n\n let data = init_data.try_to_vec()?;\n\n\n\n let accounts = vec![\n\n AccountMeta::new_readonly(*pool, false),\n\n AccountMeta::new_readonly(*authority, false),\n", "file_path": "binary-oracle-pair/program/src/instruction.rs", "rank": 34, "score": 165865.2121607008 }, { "content": "/// A more efficient `copy_from_slice` implementation.\n\nfn fast_copy(mut src: &[u8], mut dst: &mut [u8]) {\n\n while src.len() >= 8 {\n\n #[allow(clippy::ptr_offset_with_cast)]\n\n let (src_word, src_rem) = array_refs![src, 8; ..;];\n\n #[allow(clippy::ptr_offset_with_cast)]\n\n let (dst_word, dst_rem) = mut_array_refs![dst, 8; ..;];\n\n *dst_word = *src_word;\n\n src = src_rem;\n\n dst = dst_rem;\n\n }\n\n unsafe {\n\n std::ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), src.len());\n\n }\n\n}\n\n\n\n/// Deserializes only the particular input parameters that the shared memory\n\n/// program uses. For more information about the format of the serialized input\n\n/// parameters see `solana_sdk::entrypoint::deserialize`\n\nunsafe fn deserialize_input_parameters<'a>(\n\n input: *mut u8,\n", "file_path": "shared-memory/program/src/lib.rs", "rank": 35, "score": 164130.44730520918 }, { "content": "/// Create PreciseSquareRoot instruction\n\npub fn u64_divide(dividend: u64, divisor: u64) -> Instruction {\n\n Instruction {\n\n program_id: id(),\n\n accounts: vec![],\n\n data: MathInstruction::U64Divide { dividend, divisor }\n\n .try_to_vec()\n\n .unwrap(),\n\n }\n\n}\n\n\n", "file_path": "libraries/math/src/instruction.rs", "rank": 36, "score": 163297.34467321256 }, { "content": "/// Create PreciseSquareRoot instruction\n\npub fn u64_multiply(multiplicand: u64, multiplier: u64) -> Instruction {\n\n Instruction {\n\n program_id: id(),\n\n accounts: vec![],\n\n data: MathInstruction::U64Multiply {\n\n multiplicand,\n\n multiplier,\n\n }\n\n .try_to_vec()\n\n .unwrap(),\n\n }\n\n}\n\n\n", "file_path": "libraries/math/src/instruction.rs", "rank": 37, "score": 163297.34467321256 }, { "content": "fn command_supply(config: &Config, address: Pubkey) -> CommandResult {\n\n let supply = config.rpc_client.get_token_supply(&address)?;\n\n let cli_token_amount = CliTokenAmount { amount: supply };\n\n println!(\n\n \"{}\",\n\n config.output_format.formatted_string(&cli_token_amount)\n\n );\n\n\n\n Ok(None)\n\n}\n\n\n", "file_path": "token/cli/src/main.rs", "rank": 38, "score": 160404.727789085 }, { "content": "fn command_gc(config: &Config, owner: Pubkey) -> CommandResult {\n\n println_display(config, \"Fetching token accounts\".to_string());\n\n let accounts = config\n\n .rpc_client\n\n .get_token_accounts_by_owner(&owner, TokenAccountsFilter::ProgramId(spl_token::id()))?;\n\n if accounts.is_empty() {\n\n println_display(config, \"Nothing to do\".to_string());\n\n return Ok(None);\n\n }\n\n\n\n let minimum_balance_for_rent_exemption = if !config.sign_only {\n\n config\n\n .rpc_client\n\n .get_minimum_balance_for_rent_exemption(Account::LEN)?\n\n } else {\n\n 0\n\n };\n\n\n\n let mut accounts_by_token = HashMap::new();\n\n\n", "file_path": "token/cli/src/main.rs", "rank": 39, "score": 160404.727789085 }, { "content": "fn command_multisig(config: &Config, address: Pubkey) -> CommandResult {\n\n let multisig = get_multisig(config, &address)?;\n\n let n = multisig.n as usize;\n\n assert!(n <= multisig.signers.len());\n\n let cli_multisig = CliMultisig {\n\n address: address.to_string(),\n\n m: multisig.m,\n\n n: multisig.n,\n\n signers: multisig\n\n .signers\n\n .iter()\n\n .enumerate()\n\n .filter_map(|(i, signer)| {\n\n if i < n {\n\n Some(signer.to_string())\n\n } else {\n\n None\n\n }\n\n })\n\n .collect(),\n\n };\n\n println!(\"{}\", config.output_format.formatted_string(&cli_multisig));\n\n Ok(None)\n\n}\n\n\n", "file_path": "token/cli/src/main.rs", "rank": 40, "score": 160404.727789085 }, { "content": "fn command_balance(config: &Config, address: Pubkey) -> CommandResult {\n\n let balance = config\n\n .rpc_client\n\n .get_token_account_balance(&address)\n\n .map_err(|_| format!(\"Could not find token account {}\", address))?;\n\n let cli_token_amount = CliTokenAmount { amount: balance };\n\n println!(\n\n \"{}\",\n\n config.output_format.formatted_string(&cli_token_amount)\n\n );\n\n\n\n Ok(None)\n\n}\n\n\n", "file_path": "token/cli/src/main.rs", "rank": 41, "score": 160404.727789085 }, { "content": "pub fn map_transaction_error(transport_error: TransportError) -> ProgramError {\n\n match transport_error {\n\n TransportError::TransactionError(TransactionError::InstructionError(\n\n _,\n\n InstructionError::Custom(error_index),\n\n )) => ProgramError::Custom(error_index),\n\n TransportError::TransactionError(TransactionError::InstructionError(\n\n _,\n\n instruction_error,\n\n )) => ProgramError::try_from(instruction_error).unwrap_or_else(|ie| match ie {\n\n InstructionError::IncorrectAuthority => {\n\n ProgramInstructionError::IncorrectAuthority.into()\n\n }\n\n InstructionError::PrivilegeEscalation => {\n\n ProgramInstructionError::PrivilegeEscalation.into()\n\n }\n\n _ => panic!(\"TEST-INSTRUCTION-ERROR {:?}\", ie),\n\n }),\n\n\n\n _ => panic!(\"TEST-TRANSPORT-ERROR: {:?}\", transport_error),\n\n }\n\n}\n\n\n", "file_path": "governance/program/tests/program_test/tools.rs", "rank": 42, "score": 158626.80809210538 }, { "content": "fn command_account_info(config: &Config, address: Pubkey) -> CommandResult {\n\n let account = config\n\n .rpc_client\n\n .get_token_account(&address)\n\n .map_err(|_| format!(\"Could not find token account {}\", address))?\n\n .unwrap();\n\n let mint = Pubkey::from_str(&account.mint).unwrap();\n\n let owner = Pubkey::from_str(&account.owner).unwrap();\n\n let is_associated = get_associated_token_address(&owner, &mint) == address;\n\n let cli_token_account = CliTokenAccount {\n\n address: address.to_string(),\n\n is_associated,\n\n account,\n\n };\n\n println!(\n\n \"{}\",\n\n config.output_format.formatted_string(&cli_token_account)\n\n );\n\n Ok(None)\n\n}\n\n\n", "file_path": "token/cli/src/main.rs", "rank": 43, "score": 158598.96437412992 }, { "content": "fn validate_mint(config: &Config, token: Pubkey) -> Result<(), Error> {\n\n let mint = config.rpc_client.get_account(&token);\n\n if mint.is_err() || Mint::unpack(&mint.unwrap().data).is_err() {\n\n return Err(format!(\"Invalid mint account {:?}\", token).into());\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "token/cli/src/main.rs", "rank": 44, "score": 156628.73543969932 }, { "content": "/// Create SquareRoot instruction\n\npub fn sqrt_u64(radicand: u64) -> Instruction {\n\n Instruction {\n\n program_id: id(),\n\n accounts: vec![],\n\n data: MathInstruction::SquareRootU64 { radicand }\n\n .try_to_vec()\n\n .unwrap(),\n\n }\n\n}\n\n\n", "file_path": "libraries/math/src/instruction.rs", "rank": 45, "score": 156334.26914781626 }, { "content": "fn command_list(config: &Config, stake_pool_address: &Pubkey) -> CommandResult {\n\n let stake_pool = get_stake_pool(&config.rpc_client, stake_pool_address)?;\n\n let validator_list = get_validator_list(&config.rpc_client, &stake_pool.validator_list)?;\n\n let pool_mint = get_token_mint(&config.rpc_client, &stake_pool.pool_mint)?;\n\n let epoch_info = config.rpc_client.get_epoch_info()?;\n\n let pool_withdraw_authority =\n\n find_withdraw_authority_program_address(&spl_stake_pool::id(), stake_pool_address).0;\n\n\n\n if config.verbose {\n\n println!(\"Stake Pool Info\");\n\n println!(\"===============\");\n\n println!(\"Stake Pool: {}\", stake_pool_address);\n\n println!(\"Validator List: {}\", stake_pool.validator_list);\n\n println!(\"Manager: {}\", stake_pool.manager);\n\n println!(\"Staker: {}\", stake_pool.staker);\n\n println!(\"Depositor: {}\", stake_pool.deposit_authority);\n\n println!(\"Withdraw Authority: {}\", pool_withdraw_authority);\n\n println!(\"Pool Token Mint: {}\", stake_pool.pool_mint);\n\n println!(\"Fee Account: {}\", stake_pool.manager_fee_account);\n\n } else {\n", "file_path": "stake-pool/cli/src/main.rs", "rank": 46, "score": 155179.55474766053 }, { "content": "fn new_throwaway_signer() -> (Box<dyn Signer>, Pubkey) {\n\n let keypair = Keypair::new();\n\n let pubkey = keypair.pubkey();\n\n (Box::new(keypair) as Box<dyn Signer>, pubkey)\n\n}\n\n\n", "file_path": "token/cli/src/main.rs", "rank": 47, "score": 154477.8596517808 }, { "content": "#![cfg(feature = \"test-bpf\")]\n\n\n\nmod helpers;\n\n\n\nuse helpers::*;\n\nuse solana_program_test::*;\n\nuse solana_sdk::{\n\n pubkey::Pubkey,\n\n signature::{Keypair, Signer},\n\n transaction::Transaction,\n\n};\n\nuse spl_token::instruction::approve;\n\nuse spl_token_lending::{\n\n instruction::{liquidate_obligation, refresh_obligation},\n\n processor::process_instruction,\n\n state::INITIAL_COLLATERAL_RATIO,\n\n};\n\n\n\n#[tokio::test]\n\nasync fn test_success() {\n", "file_path": "token-lending/program/tests/liquidate_obligation.rs", "rank": 48, "score": 152211.6858904161 }, { "content": " mark_fresh: true,\n\n ..AddReserveArgs::default()\n\n },\n\n );\n\n\n\n let test_obligation = add_obligation(\n\n &mut test,\n\n &lending_market,\n\n &user_accounts_owner,\n\n AddObligationArgs {\n\n deposits: &[(&sol_test_reserve, PANO_DEPOSIT_AMOUNT_LAMPORTS)],\n\n borrows: &[(&usdc_test_reserve, USDC_BORROW_AMOUNT_FRACTIONAL)],\n\n ..AddObligationArgs::default()\n\n },\n\n );\n\n\n\n let (mut banks_client, payer, recent_blockhash) = test.start().await;\n\n\n\n let initial_user_liquidity_balance =\n\n get_token_balance(&mut banks_client, usdc_test_reserve.user_liquidity_pubkey).await;\n", "file_path": "token-lending/program/tests/liquidate_obligation.rs", "rank": 49, "score": 152205.88280464584 }, { "content": " let initial_liquidity_supply_balance =\n\n get_token_balance(&mut banks_client, usdc_test_reserve.liquidity_supply_pubkey).await;\n\n let initial_user_collateral_balance =\n\n get_token_balance(&mut banks_client, sol_test_reserve.user_collateral_pubkey).await;\n\n let initial_collateral_supply_balance =\n\n get_token_balance(&mut banks_client, sol_test_reserve.collateral_supply_pubkey).await;\n\n\n\n let mut transaction = Transaction::new_with_payer(\n\n &[\n\n approve(\n\n &spl_token::id(),\n\n &usdc_test_reserve.user_liquidity_pubkey,\n\n &user_transfer_authority.pubkey(),\n\n &user_accounts_owner.pubkey(),\n\n &[],\n\n USDC_LIQUIDATION_AMOUNT_FRACTIONAL,\n\n )\n\n .unwrap(),\n\n refresh_obligation(\n\n spl_token_lending::id(),\n", "file_path": "token-lending/program/tests/liquidate_obligation.rs", "rank": 50, "score": 152202.3270593134 }, { "content": " let user_collateral_balance =\n\n get_token_balance(&mut banks_client, sol_test_reserve.user_collateral_pubkey).await;\n\n assert_eq!(\n\n user_collateral_balance,\n\n initial_user_collateral_balance + PANO_LIQUIDATION_AMOUNT_LAMPORTS\n\n );\n\n\n\n let collateral_supply_balance =\n\n get_token_balance(&mut banks_client, sol_test_reserve.collateral_supply_pubkey).await;\n\n assert_eq!(\n\n collateral_supply_balance,\n\n initial_collateral_supply_balance - PANO_LIQUIDATION_AMOUNT_LAMPORTS\n\n );\n\n\n\n let obligation = test_obligation.get_state(&mut banks_client).await;\n\n assert_eq!(\n\n obligation.deposits[0].deposited_amount,\n\n PANO_DEPOSIT_AMOUNT_LAMPORTS - PANO_LIQUIDATION_AMOUNT_LAMPORTS\n\n );\n\n assert_eq!(\n\n obligation.borrows[0].borrowed_amount_wads,\n\n (USDC_BORROW_AMOUNT_FRACTIONAL - USDC_LIQUIDATION_AMOUNT_FRACTIONAL).into()\n\n )\n\n}\n", "file_path": "token-lending/program/tests/liquidate_obligation.rs", "rank": 51, "score": 152197.3379995685 }, { "content": " transaction.sign(\n\n &[&payer, &user_accounts_owner, &user_transfer_authority],\n\n recent_blockhash,\n\n );\n\n assert!(banks_client.process_transaction(transaction).await.is_ok());\n\n\n\n let user_liquidity_balance =\n\n get_token_balance(&mut banks_client, usdc_test_reserve.user_liquidity_pubkey).await;\n\n assert_eq!(\n\n user_liquidity_balance,\n\n initial_user_liquidity_balance - USDC_LIQUIDATION_AMOUNT_FRACTIONAL\n\n );\n\n\n\n let liquidity_supply_balance =\n\n get_token_balance(&mut banks_client, usdc_test_reserve.liquidity_supply_pubkey).await;\n\n assert_eq!(\n\n liquidity_supply_balance,\n\n initial_liquidity_supply_balance + USDC_LIQUIDATION_AMOUNT_FRACTIONAL\n\n );\n\n\n", "file_path": "token-lending/program/tests/liquidate_obligation.rs", "rank": 52, "score": 152196.1031481665 }, { "content": " config: reserve_config,\n\n mark_fresh: true,\n\n ..AddReserveArgs::default()\n\n },\n\n );\n\n\n\n let usdc_mint = add_usdc_mint(&mut test);\n\n let usdc_oracle = add_usdc_oracle(&mut test);\n\n let usdc_test_reserve = add_reserve(\n\n &mut test,\n\n &lending_market,\n\n &usdc_oracle,\n\n &user_accounts_owner,\n\n AddReserveArgs {\n\n borrow_amount: USDC_BORROW_AMOUNT_FRACTIONAL,\n\n user_liquidity_amount: USDC_BORROW_AMOUNT_FRACTIONAL,\n\n liquidity_amount: USDC_RESERVE_LIQUIDITY_FRACTIONAL,\n\n liquidity_mint_pubkey: usdc_mint.pubkey,\n\n liquidity_mint_decimals: usdc_mint.decimals,\n\n config: reserve_config,\n", "file_path": "token-lending/program/tests/liquidate_obligation.rs", "rank": 53, "score": 152192.4856801069 }, { "content": " let mut test = ProgramTest::new(\n\n \"spl_token_lending\",\n\n spl_token_lending::id(),\n\n processor!(process_instruction),\n\n );\n\n\n\n // limit to track compute unit increase\n\n test.set_bpf_compute_max_units(68_000);\n\n\n\n // 100 PANO collateral\n\n const PANO_DEPOSIT_AMOUNT_LAMPORTS: u64 = 100 * LAMPORTS_TO_PANO * INITIAL_COLLATERAL_RATIO;\n\n // 100 PANO * 80% LTV -> 80 PANO * 20 USDC -> 1600 USDC borrow\n\n const USDC_BORROW_AMOUNT_FRACTIONAL: u64 = 1_600 * FRACTIONAL_TO_USDC;\n\n // 1600 USDC * 50% -> 800 USDC liquidation\n\n const USDC_LIQUIDATION_AMOUNT_FRACTIONAL: u64 = USDC_BORROW_AMOUNT_FRACTIONAL / 2;\n\n // 800 USDC / 20 USDC per PANO -> 40 PANO + 10% bonus -> 44 PANO\n\n const PANO_LIQUIDATION_AMOUNT_LAMPORTS: u64 = 44 * LAMPORTS_TO_PANO * INITIAL_COLLATERAL_RATIO;\n\n\n\n const PANO_RESERVE_COLLATERAL_LAMPORTS: u64 = 2 * PANO_DEPOSIT_AMOUNT_LAMPORTS;\n\n const USDC_RESERVE_LIQUIDITY_FRACTIONAL: u64 = 2 * USDC_BORROW_AMOUNT_FRACTIONAL;\n", "file_path": "token-lending/program/tests/liquidate_obligation.rs", "rank": 54, "score": 152189.66466513494 }, { "content": "\n\n let user_accounts_owner = Keypair::new();\n\n let user_transfer_authority = Keypair::new();\n\n let lending_market = add_lending_market(&mut test);\n\n\n\n let mut reserve_config = TEST_RESERVE_CONFIG;\n\n reserve_config.loan_to_value_ratio = 50;\n\n reserve_config.liquidation_threshold = 80;\n\n reserve_config.liquidation_bonus = 10;\n\n\n\n let sol_oracle = add_sol_oracle(&mut test);\n\n let sol_test_reserve = add_reserve(\n\n &mut test,\n\n &lending_market,\n\n &sol_oracle,\n\n &user_accounts_owner,\n\n AddReserveArgs {\n\n collateral_amount: PANO_RESERVE_COLLATERAL_LAMPORTS,\n\n liquidity_mint_pubkey: spl_token::native_mint::id(),\n\n liquidity_mint_decimals: 9,\n", "file_path": "token-lending/program/tests/liquidate_obligation.rs", "rank": 55, "score": 152189.6160165621 }, { "content": " test_obligation.pubkey,\n\n vec![sol_test_reserve.pubkey, usdc_test_reserve.pubkey],\n\n ),\n\n liquidate_obligation(\n\n spl_token_lending::id(),\n\n USDC_LIQUIDATION_AMOUNT_FRACTIONAL,\n\n usdc_test_reserve.user_liquidity_pubkey,\n\n sol_test_reserve.user_collateral_pubkey,\n\n usdc_test_reserve.pubkey,\n\n usdc_test_reserve.liquidity_supply_pubkey,\n\n sol_test_reserve.pubkey,\n\n sol_test_reserve.collateral_supply_pubkey,\n\n test_obligation.pubkey,\n\n lending_market.pubkey,\n\n user_transfer_authority.pubkey(),\n\n ),\n\n ],\n\n Some(&payer.pubkey()),\n\n );\n\n\n", "file_path": "token-lending/program/tests/liquidate_obligation.rs", "rank": 56, "score": 152187.9748488296 }, { "content": " ) {\n\n let mut transaction = Transaction::new_with_payer(\n\n &[refresh_reserve(\n\n spl_token_lending::id(),\n\n reserve.pubkey,\n\n reserve.liquidity_oracle_pubkey,\n\n )],\n\n Some(&payer.pubkey()),\n\n );\n\n\n\n let recent_blockhash = banks_client.get_recent_blockhash().await.unwrap();\n\n transaction.sign(&[payer], recent_blockhash);\n\n\n\n assert_matches!(banks_client.process_transaction(transaction).await, Ok(()));\n\n }\n\n\n\n pub async fn deposit(\n\n &self,\n\n banks_client: &mut BanksClient,\n\n user_accounts_owner: &Keypair,\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 57, "score": 152016.86859972603 }, { "content": " .await\n\n .unwrap()\n\n .unwrap();\n\n Obligation::unpack(&obligation_account.data[..]).unwrap()\n\n }\n\n\n\n pub async fn validate_state(&self, banks_client: &mut BanksClient) {\n\n let obligation = self.get_state(banks_client).await;\n\n assert_eq!(obligation.version, PROGRAM_VERSION);\n\n assert_eq!(obligation.lending_market, self.lending_market);\n\n assert_eq!(obligation.owner, self.owner);\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct TestObligationCollateral {\n\n pub obligation_pubkey: Pubkey,\n\n pub deposit_reserve: Pubkey,\n\n pub deposited_amount: u64,\n\n}\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 58, "score": 152016.28040998036 }, { "content": " Some(&payer.pubkey()),\n\n );\n\n\n\n let recent_blockhash = banks_client.get_recent_blockhash().await.unwrap();\n\n transaction.sign(\n\n &[&payer, &user_accounts_owner, &user_transfer_authority],\n\n recent_blockhash,\n\n );\n\n assert!(banks_client.process_transaction(transaction).await.is_ok());\n\n }\n\n\n\n pub async fn borrow(\n\n &self,\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n args: BorrowArgs<'_>,\n\n ) {\n\n let BorrowArgs {\n\n liquidity_amount,\n\n obligation,\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 59, "score": 152016.17041807694 }, { "content": " payer: &Keypair,\n\n reserve: &TestReserve,\n\n liquidity_amount: u64,\n\n ) {\n\n let user_transfer_authority = Keypair::new();\n\n let mut transaction = Transaction::new_with_payer(\n\n &[\n\n approve(\n\n &spl_token::id(),\n\n &reserve.user_liquidity_pubkey,\n\n &user_transfer_authority.pubkey(),\n\n &user_accounts_owner.pubkey(),\n\n &[],\n\n liquidity_amount,\n\n )\n\n .unwrap(),\n\n deposit_reserve_liquidity(\n\n spl_token_lending::id(),\n\n liquidity_amount,\n\n reserve.user_liquidity_pubkey,\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 60, "score": 152015.91307541187 }, { "content": "\n\nimpl TestObligationCollateral {\n\n pub async fn get_state(&self, banks_client: &mut BanksClient) -> Obligation {\n\n let obligation_account: Account = banks_client\n\n .get_account(self.obligation_pubkey)\n\n .await\n\n .unwrap()\n\n .unwrap();\n\n Obligation::unpack(&obligation_account.data[..]).unwrap()\n\n }\n\n\n\n pub async fn validate_state(&self, banks_client: &mut BanksClient) {\n\n let obligation = self.get_state(banks_client).await;\n\n assert_eq!(obligation.version, PROGRAM_VERSION);\n\n\n\n let (collateral, _) = obligation\n\n .find_collateral_in_deposits(self.deposit_reserve)\n\n .unwrap();\n\n assert_eq!(collateral.deposited_amount, self.deposited_amount);\n\n }\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 61, "score": 152015.78167738736 }, { "content": "}\n\n\n\n#[derive(Debug)]\n\npub struct TestObligationLiquidity {\n\n pub obligation_pubkey: Pubkey,\n\n pub borrow_reserve: Pubkey,\n\n pub borrowed_amount_wads: Decimal,\n\n}\n\n\n\nimpl TestObligationLiquidity {\n\n pub async fn get_state(&self, banks_client: &mut BanksClient) -> Obligation {\n\n let obligation_account: Account = banks_client\n\n .get_account(self.obligation_pubkey)\n\n .await\n\n .unwrap()\n\n .unwrap();\n\n Obligation::unpack(&obligation_account.data[..]).unwrap()\n\n }\n\n\n\n pub async fn validate_state(&self, banks_client: &mut BanksClient) {\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 62, "score": 152015.23315065718 }, { "content": " Some(&payer.pubkey()),\n\n );\n\n\n\n let recent_blockhash = banks_client.get_recent_blockhash().await.unwrap();\n\n transaction.sign(\n\n &vec![payer, &obligation_keypair, user_accounts_owner],\n\n recent_blockhash,\n\n );\n\n\n\n banks_client\n\n .process_transaction(transaction)\n\n .await\n\n .map_err(|e| e.unwrap())?;\n\n\n\n Ok(obligation)\n\n }\n\n\n\n pub async fn get_state(&self, banks_client: &mut BanksClient) -> Obligation {\n\n let obligation_account: Account = banks_client\n\n .get_account(self.pubkey)\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 63, "score": 152014.57901135582 }, { "content": " pub lending_market: Pubkey,\n\n pub owner: Pubkey,\n\n pub deposits: Vec<TestObligationCollateral>,\n\n pub borrows: Vec<TestObligationLiquidity>,\n\n}\n\n\n\nimpl TestObligation {\n\n #[allow(clippy::too_many_arguments)]\n\n pub async fn init(\n\n banks_client: &mut BanksClient,\n\n lending_market: &TestLendingMarket,\n\n user_accounts_owner: &Keypair,\n\n payer: &Keypair,\n\n ) -> Result<Self, TransactionError> {\n\n let obligation_keypair = Keypair::new();\n\n let obligation = TestObligation {\n\n pubkey: obligation_keypair.pubkey(),\n\n lending_market: lending_market.pubkey,\n\n owner: user_accounts_owner.pubkey(),\n\n deposits: vec![],\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 64, "score": 152013.7802023443 }, { "content": " authorized,\n\n lockup,\n\n lamports,\n\n ),\n\n Some(&payer.pubkey()),\n\n &[payer, stake],\n\n *recent_blockhash,\n\n );\n\n banks_client.process_transaction(transaction).await.unwrap();\n\n\n\n lamports\n\n}\n\n\n\npub async fn create_blank_stake_account(\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n recent_blockhash: &Hash,\n\n stake: &Keypair,\n\n) -> u64 {\n\n let rent = banks_client.get_rent().await.unwrap();\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 65, "score": 152013.52727510632 }, { "content": " Some(&payer.pubkey()),\n\n );\n\n\n\n let recent_blockhash = banks_client.get_recent_blockhash().await.unwrap();\n\n transaction.sign(&[&payer, &token_keypair], recent_blockhash);\n\n\n\n assert_matches!(banks_client.process_transaction(transaction).await, Ok(()));\n\n\n\n token_pubkey\n\n}\n\n\n\npub async fn mint_to(\n\n banks_client: &mut BanksClient,\n\n mint_pubkey: Pubkey,\n\n payer: &Keypair,\n\n account_pubkey: Pubkey,\n\n authority: &Keypair,\n\n amount: u64,\n\n) {\n\n let mut transaction = Transaction::new_with_payer(\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 66, "score": 152013.29260970687 }, { "content": " 0,\n\n )\n\n .unwrap(),\n\n ],\n\n Some(&payer.pubkey()),\n\n );\n\n transaction.sign(&[payer, pool_mint], *recent_blockhash);\n\n banks_client.process_transaction(transaction).await?;\n\n Ok(())\n\n}\n\n\n\npub async fn transfer(\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n recent_blockhash: &Hash,\n\n recipient: &Pubkey,\n\n amount: u64,\n\n) {\n\n let transaction = Transaction::new_signed_with_payer(\n\n &[system_instruction::transfer(\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 67, "score": 152012.78658303322 }, { "content": "}\n\n\n\nimpl TestReserve {\n\n #[allow(clippy::too_many_arguments)]\n\n pub async fn init(\n\n name: String,\n\n banks_client: &mut BanksClient,\n\n lending_market: &TestLendingMarket,\n\n oracle: &TestOracle,\n\n liquidity_amount: u64,\n\n config: ReserveConfig,\n\n liquidity_mint_pubkey: Pubkey,\n\n user_liquidity_pubkey: Pubkey,\n\n payer: &Keypair,\n\n user_accounts_owner: &Keypair,\n\n ) -> Result<Self, TransactionError> {\n\n let reserve_keypair = Keypair::new();\n\n let reserve_pubkey = reserve_keypair.pubkey();\n\n let collateral_mint_keypair = Keypair::new();\n\n let collateral_supply_keypair = Keypair::new();\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 68, "score": 152012.46406271568 }, { "content": " borrows: vec![],\n\n };\n\n\n\n let rent = banks_client.get_rent().await.unwrap();\n\n let mut transaction = Transaction::new_with_payer(\n\n &[\n\n create_account(\n\n &payer.pubkey(),\n\n &obligation_keypair.pubkey(),\n\n rent.minimum_balance(Obligation::LEN),\n\n Obligation::LEN as u64,\n\n &spl_token_lending::id(),\n\n ),\n\n init_obligation(\n\n spl_token_lending::id(),\n\n obligation.pubkey,\n\n lending_market.pubkey,\n\n user_accounts_owner.pubkey(),\n\n ),\n\n ],\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 69, "score": 152012.02785486775 }, { "content": " banks_client.process_transaction(transaction).await.unwrap();\n\n}\n\n\n\npub async fn create_independent_stake_account(\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n recent_blockhash: &Hash,\n\n stake: &Keypair,\n\n authorized: &stake_program::Authorized,\n\n lockup: &stake_program::Lockup,\n\n stake_amount: u64,\n\n) -> u64 {\n\n let rent = banks_client.get_rent().await.unwrap();\n\n let lamports =\n\n rent.minimum_balance(std::mem::size_of::<stake_program::StakeState>()) + stake_amount;\n\n\n\n let transaction = Transaction::new_signed_with_payer(\n\n &stake_program::create_account(\n\n &payer.pubkey(),\n\n &stake.pubkey(),\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 70, "score": 152011.55689707637 }, { "content": " }\n\n transaction.sign(&signers, *recent_blockhash);\n\n banks_client.process_transaction(transaction).await?;\n\n Ok(())\n\n}\n\n\n\npub async fn create_vote(\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n recent_blockhash: &Hash,\n\n validator: &Keypair,\n\n vote: &Keypair,\n\n) {\n\n let rent = banks_client.get_rent().await.unwrap();\n\n let rent_voter = rent.minimum_balance(VoteState::size_of());\n\n\n\n let mut instructions = vec![system_instruction::create_account(\n\n &payer.pubkey(),\n\n &validator.pubkey(),\n\n 42,\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 71, "score": 152011.13848181826 }, { "content": " let liquidity_supply_keypair = Keypair::new();\n\n let liquidity_fee_receiver_keypair = Keypair::new();\n\n let liquidity_host_keypair = Keypair::new();\n\n let user_collateral_token_keypair = Keypair::new();\n\n let user_transfer_authority_keypair = Keypair::new();\n\n\n\n let liquidity_mint_account = banks_client\n\n .get_account(liquidity_mint_pubkey)\n\n .await\n\n .unwrap()\n\n .unwrap();\n\n let liquidity_mint = Mint::unpack(&liquidity_mint_account.data[..]).unwrap();\n\n\n\n let rent = banks_client.get_rent().await.unwrap();\n\n let mut transaction = Transaction::new_with_payer(\n\n &[\n\n approve(\n\n &spl_token::id(),\n\n &user_liquidity_pubkey,\n\n &user_transfer_authority_keypair.pubkey(),\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 72, "score": 152010.95405043612 }, { "content": " &[spl_token::instruction::mint_to(\n\n &spl_token::id(),\n\n &mint_pubkey,\n\n &account_pubkey,\n\n &authority.pubkey(),\n\n &[],\n\n amount,\n\n )\n\n .unwrap()],\n\n Some(&payer.pubkey()),\n\n );\n\n\n\n let recent_blockhash = banks_client.get_recent_blockhash().await.unwrap();\n\n transaction.sign(&[payer, authority], recent_blockhash);\n\n\n\n assert_matches!(banks_client.process_transaction(transaction).await, Ok(()));\n\n}\n\n\n\npub async fn get_token_balance(banks_client: &mut BanksClient, pubkey: Pubkey) -> u64 {\n\n let token: Account = banks_client.get_account(pubkey).await.unwrap().unwrap();\n\n\n\n spl_token::state::Account::unpack(&token.data[..])\n\n .unwrap()\n\n .amount\n\n}\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 73, "score": 152010.75173473242 }, { "content": " );\n\n\n\n let recent_blockhash = banks_client.get_recent_blockhash().await.unwrap();\n\n transaction.sign(&[&payer, &lending_market_keypair], recent_blockhash);\n\n assert_matches!(banks_client.process_transaction(transaction).await, Ok(()));\n\n\n\n TestLendingMarket {\n\n owner: lending_market_owner,\n\n pubkey: lending_market_pubkey,\n\n authority: lending_market_authority,\n\n quote_currency: QUOTE_CURRENCY,\n\n oracle_program_id,\n\n }\n\n }\n\n\n\n pub async fn refresh_reserve(\n\n &self,\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n reserve: &TestReserve,\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 74, "score": 152010.133838361 }, { "content": " borrow_reserve,\n\n user_accounts_owner,\n\n } = args;\n\n\n\n let mut transaction = Transaction::new_with_payer(\n\n &[borrow_obligation_liquidity(\n\n spl_token_lending::id(),\n\n liquidity_amount,\n\n borrow_reserve.liquidity_supply_pubkey,\n\n borrow_reserve.user_liquidity_pubkey,\n\n borrow_reserve.pubkey,\n\n borrow_reserve.liquidity_fee_receiver_pubkey,\n\n obligation.pubkey,\n\n self.pubkey,\n\n obligation.owner,\n\n Some(borrow_reserve.liquidity_host_pubkey),\n\n )],\n\n Some(&payer.pubkey()),\n\n );\n\n\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 75, "score": 152009.90744709212 }, { "content": " pub async fn liquidate(\n\n &self,\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n args: LiquidateArgs<'_>,\n\n ) {\n\n let LiquidateArgs {\n\n liquidity_amount,\n\n obligation,\n\n repay_reserve,\n\n withdraw_reserve,\n\n user_accounts_owner,\n\n } = args;\n\n\n\n let user_transfer_authority = Keypair::new();\n\n let mut transaction = Transaction::new_with_payer(\n\n &[\n\n approve(\n\n &spl_token::id(),\n\n &repay_reserve.user_liquidity_pubkey,\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 76, "score": 152009.86258576525 }, { "content": " borrow_obligation_liquidity, deposit_reserve_liquidity, init_lending_market,\n\n init_obligation, init_reserve, liquidate_obligation, refresh_reserve,\n\n },\n\n math::{Decimal, Rate, TryAdd, TryMul},\n\n pyth,\n\n state::{\n\n InitLendingMarketParams, InitObligationParams, InitReserveParams, LendingMarket,\n\n NewReserveCollateralParams, NewReserveLiquidityParams, Obligation, ObligationCollateral,\n\n ObligationLiquidity, Reserve, ReserveCollateral, ReserveConfig, ReserveFees,\n\n ReserveLiquidity, INITIAL_COLLATERAL_RATIO, PROGRAM_VERSION,\n\n },\n\n};\n\nuse std::{convert::TryInto, str::FromStr};\n\n\n\npub const QUOTE_CURRENCY: [u8; 32] =\n\n *b\"USD\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n\n\npub const LAMPORTS_TO_PANO: u64 = 1_000_000_000;\n\npub const FRACTIONAL_TO_USDC: u64 = 1_000_000;\n\n\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 77, "score": 152009.30258222335 }, { "content": " stake_pool_accounts.deposit_authority_keypair = Some(deposit_authority);\n\n stake_pool_accounts\n\n }\n\n\n\n pub fn calculate_fee(&self, amount: u64) -> u64 {\n\n amount * self.fee.numerator / self.fee.denominator\n\n }\n\n\n\n pub fn calculate_withdrawal_fee(&self, pool_tokens: u64) -> u64 {\n\n pool_tokens * self.withdrawal_fee.numerator / self.withdrawal_fee.denominator\n\n }\n\n\n\n pub async fn initialize_stake_pool(\n\n &self,\n\n mut banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n recent_blockhash: &Hash,\n\n reserve_lamports: u64,\n\n ) -> Result<(), TransportError> {\n\n create_mint(\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 78, "score": 152008.9660182018 }, { "content": " );\n\n banks_client.process_transaction(transaction).await.unwrap();\n\n}\n\n\n\npub async fn delegate_stake_account(\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n recent_blockhash: &Hash,\n\n stake: &Pubkey,\n\n authorized: &Keypair,\n\n vote: &Pubkey,\n\n) {\n\n let mut transaction = Transaction::new_with_payer(\n\n &[stake_program::delegate_stake(\n\n &stake,\n\n &authorized.pubkey(),\n\n &vote,\n\n )],\n\n Some(&payer.pubkey()),\n\n );\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 79, "score": 152008.91549387499 }, { "content": " &payer.pubkey(),\n\n recipient,\n\n amount,\n\n )],\n\n Some(&payer.pubkey()),\n\n &[payer],\n\n *recent_blockhash,\n\n );\n\n banks_client.process_transaction(transaction).await.unwrap();\n\n}\n\n\n\npub async fn create_token_account(\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n recent_blockhash: &Hash,\n\n account: &Keypair,\n\n pool_mint: &Pubkey,\n\n manager: &Pubkey,\n\n) -> Result<(), TransportError> {\n\n let rent = banks_client.get_rent().await.unwrap();\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 80, "score": 152008.8183176085 }, { "content": " &mint_authority.pubkey(),\n\n &[],\n\n amount,\n\n )\n\n .unwrap()],\n\n Some(&payer.pubkey()),\n\n &[payer, mint_authority],\n\n *recent_blockhash,\n\n );\n\n banks_client.process_transaction(transaction).await?;\n\n Ok(())\n\n}\n\n\n\npub async fn burn_tokens(\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n recent_blockhash: &Hash,\n\n mint: &Pubkey,\n\n account: &Pubkey,\n\n authority: &Keypair,\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 81, "score": 152007.31822936528 }, { "content": " transaction.sign(&[payer, authorized], *recent_blockhash);\n\n banks_client.process_transaction(transaction).await.unwrap();\n\n}\n\n\n\npub async fn authorize_stake_account(\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n recent_blockhash: &Hash,\n\n stake: &Pubkey,\n\n authorized: &Keypair,\n\n new_authorized: &Pubkey,\n\n stake_authorize: stake_program::StakeAuthorize,\n\n) {\n\n let mut transaction = Transaction::new_with_payer(\n\n &[stake_program::authorize(\n\n &stake,\n\n &authorized.pubkey(),\n\n &new_authorized,\n\n stake_authorize,\n\n )],\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 82, "score": 152007.25518283973 }, { "content": " collateral.deposited_amount = *collateral_amount;\n\n\n\n (\n\n collateral,\n\n TestObligationCollateral {\n\n obligation_pubkey,\n\n deposit_reserve: deposit_reserve.pubkey,\n\n deposited_amount: *collateral_amount,\n\n },\n\n )\n\n })\n\n .unzip();\n\n\n\n let (obligation_borrows, test_borrows) = borrows\n\n .iter()\n\n .map(|(borrow_reserve, liquidity_amount)| {\n\n let borrowed_amount_wads = Decimal::from(*liquidity_amount);\n\n\n\n let mut liquidity = ObligationLiquidity::new(borrow_reserve.pubkey);\n\n liquidity.borrowed_amount_wads = borrowed_amount_wads;\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 83, "score": 152006.8742518104 }, { "content": "\n\n let rent = banks_client.get_rent().await.unwrap();\n\n let lamports = rent.minimum_balance(Token::LEN) + native_amount.unwrap_or_default();\n\n let mut transaction = Transaction::new_with_payer(\n\n &[\n\n create_account(\n\n &payer.pubkey(),\n\n &token_pubkey,\n\n lamports,\n\n Token::LEN as u64,\n\n &spl_token::id(),\n\n ),\n\n spl_token::instruction::initialize_account(\n\n &spl_token::id(),\n\n &token_pubkey,\n\n &mint_pubkey,\n\n &authority_pubkey,\n\n )\n\n .unwrap(),\n\n ],\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 84, "score": 152006.73394446855 }, { "content": " );\n\n transaction.sign(&[payer, account], *recent_blockhash);\n\n banks_client.process_transaction(transaction).await?;\n\n Ok(())\n\n}\n\n\n\npub async fn mint_tokens(\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n recent_blockhash: &Hash,\n\n mint: &Pubkey,\n\n account: &Pubkey,\n\n mint_authority: &Keypair,\n\n amount: u64,\n\n) -> Result<(), TransportError> {\n\n let transaction = Transaction::new_signed_with_payer(\n\n &[spl_token::instruction::mint_to(\n\n &spl_token::id(),\n\n mint,\n\n account,\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 85, "score": 152006.49961944215 }, { "content": " let recent_blockhash = banks_client.get_recent_blockhash().await.unwrap();\n\n transaction.sign(&vec![payer, user_accounts_owner], recent_blockhash);\n\n\n\n assert_matches!(banks_client.process_transaction(transaction).await, Ok(()));\n\n }\n\n\n\n pub async fn get_state(&self, banks_client: &mut BanksClient) -> LendingMarket {\n\n let lending_market_account: Account = banks_client\n\n .get_account(self.pubkey)\n\n .await\n\n .unwrap()\n\n .unwrap();\n\n LendingMarket::unpack(&lending_market_account.data[..]).unwrap()\n\n }\n\n\n\n pub async fn validate_state(&self, banks_client: &mut BanksClient) {\n\n let lending_market = self.get_state(banks_client).await;\n\n assert_eq!(lending_market.version, PROGRAM_VERSION);\n\n assert_eq!(lending_market.owner, self.owner.pubkey());\n\n assert_eq!(lending_market.quote_currency, self.quote_currency);\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 86, "score": 152006.3578710653 }, { "content": " let lamports = rent.minimum_balance(std::mem::size_of::<stake_program::StakeState>()) + 1;\n\n\n\n let transaction = Transaction::new_signed_with_payer(\n\n &[system_instruction::create_account(\n\n &payer.pubkey(),\n\n &stake.pubkey(),\n\n lamports,\n\n std::mem::size_of::<stake_program::StakeState>() as u64,\n\n &stake_program::id(),\n\n )],\n\n Some(&payer.pubkey()),\n\n &[payer, stake],\n\n *recent_blockhash,\n\n );\n\n banks_client.process_transaction(transaction).await.unwrap();\n\n\n\n lamports\n\n}\n\n\n\npub async fn create_validator_stake_account(\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 87, "score": 152006.28709590717 }, { "content": "pub async fn get_token_balance(banks_client: &mut BanksClient, token: &Pubkey) -> u64 {\n\n let token_account = banks_client.get_account(*token).await.unwrap().unwrap();\n\n let account_info: spl_token::state::Account =\n\n spl_token::state::Account::unpack_from_slice(token_account.data.as_slice()).unwrap();\n\n account_info.amount\n\n}\n\n\n\npub async fn get_token_supply(banks_client: &mut BanksClient, mint: &Pubkey) -> u64 {\n\n let mint_account = banks_client.get_account(*mint).await.unwrap().unwrap();\n\n let account_info =\n\n spl_token::state::Mint::unpack_from_slice(mint_account.data.as_slice()).unwrap();\n\n account_info.supply\n\n}\n\n\n\npub async fn delegate_tokens(\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n recent_blockhash: &Hash,\n\n account: &Pubkey,\n\n manager: &Keypair,\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 88, "score": 152006.06401692703 }, { "content": " &self.deposit_authority_keypair,\n\n &self.fee,\n\n &self.withdrawal_fee,\n\n self.max_validators,\n\n )\n\n .await?;\n\n Ok(())\n\n }\n\n\n\n #[allow(clippy::too_many_arguments)]\n\n pub async fn deposit_stake(\n\n &self,\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n recent_blockhash: &Hash,\n\n stake: &Pubkey,\n\n pool_account: &Pubkey,\n\n validator_stake_account: &Pubkey,\n\n current_staker: &Keypair,\n\n ) -> Option<TransportError> {\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 89, "score": 152006.05708630744 }, { "content": " delegate: &Pubkey,\n\n amount: u64,\n\n) {\n\n let transaction = Transaction::new_signed_with_payer(\n\n &[spl_token::instruction::approve(\n\n &spl_token::id(),\n\n &account,\n\n &delegate,\n\n &manager.pubkey(),\n\n &[],\n\n amount,\n\n )\n\n .unwrap()],\n\n Some(&payer.pubkey()),\n\n &[payer, manager],\n\n *recent_blockhash,\n\n );\n\n banks_client.process_transaction(transaction).await.unwrap();\n\n}\n\n\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 90, "score": 152005.94110685628 }, { "content": " *recent_blockhash,\n\n );\n\n banks_client.process_transaction(transaction).await.err()\n\n }\n\n\n\n pub async fn increase_validator_stake(\n\n &self,\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n recent_blockhash: &Hash,\n\n transient_stake: &Pubkey,\n\n validator: &Pubkey,\n\n lamports: u64,\n\n ) -> Option<TransportError> {\n\n let transaction = Transaction::new_signed_with_payer(\n\n &[instruction::increase_validator_stake(\n\n &id(),\n\n &self.stake_pool.pubkey(),\n\n &self.staker.pubkey(),\n\n &self.withdraw_authority,\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 91, "score": 152005.83344740322 }, { "content": " );\n\n banks_client.process_transaction(transaction).await.err()\n\n }\n\n\n\n pub async fn update_stake_pool_balance(\n\n &self,\n\n banks_client: &mut BanksClient,\n\n payer: &Keypair,\n\n recent_blockhash: &Hash,\n\n ) -> Option<TransportError> {\n\n let transaction = Transaction::new_signed_with_payer(\n\n &[instruction::update_stake_pool_balance(\n\n &id(),\n\n &self.stake_pool.pubkey(),\n\n &self.withdraw_authority,\n\n &self.validator_list.pubkey(),\n\n &self.reserve_stake.pubkey(),\n\n &self.pool_fee_account.pubkey(),\n\n &self.pool_mint.pubkey(),\n\n )],\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 92, "score": 152005.21718263655 }, { "content": " mint_pubkey: collateral_mint_pubkey,\n\n supply_pubkey: collateral_supply_pubkey,\n\n }),\n\n config,\n\n });\n\n reserve.deposit_liquidity(liquidity_amount).unwrap();\n\n reserve.liquidity.borrow(borrow_amount.into()).unwrap();\n\n let borrow_rate_multiplier = Rate::one()\n\n .try_add(Rate::from_percent(initial_borrow_rate))\n\n .unwrap();\n\n reserve.liquidity.cumulative_borrow_rate_wads =\n\n Decimal::one().try_mul(borrow_rate_multiplier).unwrap();\n\n\n\n if mark_fresh {\n\n reserve.last_update.update_slot(current_slot);\n\n }\n\n\n\n test.add_packable_account(\n\n reserve_pubkey,\n\n u32::MAX as u64,\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 93, "score": 152004.95774319884 }, { "content": " reserve_pubkey,\n\n liquidity_mint_pubkey,\n\n liquidity_supply_keypair.pubkey(),\n\n liquidity_fee_receiver_keypair.pubkey(),\n\n collateral_mint_keypair.pubkey(),\n\n collateral_supply_keypair.pubkey(),\n\n oracle.product_pubkey,\n\n oracle.price_pubkey,\n\n lending_market.pubkey,\n\n lending_market.owner.pubkey(),\n\n user_transfer_authority_keypair.pubkey(),\n\n ),\n\n ],\n\n Some(&payer.pubkey()),\n\n );\n\n\n\n let recent_blockhash = banks_client.get_recent_blockhash().await.unwrap();\n\n transaction.sign(\n\n &vec![\n\n payer,\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 94, "score": 152004.90390255308 }, { "content": "\n\n let rent = banks_client.get_rent().await.unwrap();\n\n let mut transaction = Transaction::new_with_payer(\n\n &[\n\n create_account(\n\n &payer.pubkey(),\n\n &lending_market_pubkey,\n\n rent.minimum_balance(LendingMarket::LEN),\n\n LendingMarket::LEN as u64,\n\n &spl_token_lending::id(),\n\n ),\n\n init_lending_market(\n\n spl_token_lending::id(),\n\n lending_market_owner.pubkey(),\n\n QUOTE_CURRENCY,\n\n lending_market_pubkey,\n\n oracle_program_id,\n\n ),\n\n ],\n\n Some(&payer.pubkey()),\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 95, "score": 152004.81055402636 }, { "content": " &id(),\n\n &stake_pool.pubkey(),\n\n &manager.pubkey(),\n\n staker,\n\n &validator_list.pubkey(),\n\n reserve_stake,\n\n pool_mint,\n\n pool_token_account,\n\n &spl_token::id(),\n\n deposit_authority.as_ref().map(|k| k.pubkey()),\n\n *fee,\n\n *withdrawal_fee,\n\n max_validators,\n\n ),\n\n ],\n\n Some(&payer.pubkey()),\n\n );\n\n let mut signers = vec![payer, stake_pool, validator_list, manager];\n\n if let Some(deposit_authority) = deposit_authority.as_ref() {\n\n signers.push(deposit_authority);\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 96, "score": 152004.647186577 }, { "content": " banks_client,\n\n mint_pubkey,\n\n &payer,\n\n Some(authority),\n\n Some(amount),\n\n )\n\n .await\n\n }\n\n}\n\n\n\npub async fn create_token_account(\n\n banks_client: &mut BanksClient,\n\n mint_pubkey: Pubkey,\n\n payer: &Keypair,\n\n authority: Option<Pubkey>,\n\n native_amount: Option<u64>,\n\n) -> Pubkey {\n\n let token_keypair = Keypair::new();\n\n let token_pubkey = token_keypair.pubkey();\n\n let authority_pubkey = authority.unwrap_or_else(|| payer.pubkey());\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 97, "score": 152004.57228478917 }, { "content": " amount: u64,\n\n) -> Result<(), TransportError> {\n\n let transaction = Transaction::new_signed_with_payer(\n\n &[spl_token::instruction::burn(\n\n &spl_token::id(),\n\n account,\n\n mint,\n\n &authority.pubkey(),\n\n &[],\n\n amount,\n\n )\n\n .unwrap()],\n\n Some(&payer.pubkey()),\n\n &[payer, authority],\n\n *recent_blockhash,\n\n );\n\n banks_client.process_transaction(transaction).await?;\n\n Ok(())\n\n}\n\n\n", "file_path": "stake-pool/program/tests/helpers/mod.rs", "rank": 98, "score": 152004.53755969205 }, { "content": "\n\n (\n\n liquidity,\n\n TestObligationLiquidity {\n\n obligation_pubkey,\n\n borrow_reserve: borrow_reserve.pubkey,\n\n borrowed_amount_wads,\n\n },\n\n )\n\n })\n\n .unzip();\n\n\n\n let current_slot = slots_elapsed + 1;\n\n\n\n let mut obligation = Obligation::new(InitObligationParams {\n\n // intentionally wrapped to simulate elapsed slots\n\n current_slot,\n\n lending_market: lending_market.pubkey,\n\n owner: user_accounts_owner.pubkey(),\n\n deposits: obligation_deposits,\n", "file_path": "token-lending/program/tests/helpers/mod.rs", "rank": 99, "score": 152004.3440612978 } ]
Rust
libs/port_io/src/lib.rs
jacob-earle/Theseus
d53038328d1a39c69ffff6e32226394e8c957e33
#![feature(llvm_asm, const_fn_trait_bound)] #![no_std] use core::marker::PhantomData; #[cfg(any(target_arch="x86", target_arch="x86_64"))] mod x86; #[cfg(any(target_arch="x86", target_arch="x86_64"))] pub use x86::{inb, outb, inw, outw, inl, outl}; pub trait PortIn { unsafe fn port_in(port: u16) -> Self; } pub trait PortOut { unsafe fn port_out(port: u16, value: Self); } impl PortOut for u8 { unsafe fn port_out(port: u16, value: Self) { outb(value, port); } } impl PortOut for u16 { unsafe fn port_out(port: u16, value: Self) { outw(value, port); } } impl PortOut for u32 { unsafe fn port_out(port: u16, value: Self) { outl(value, port); } } impl PortIn for u8 { unsafe fn port_in(port: u16) -> Self { inb(port) } } impl PortIn for u16 { unsafe fn port_in(port: u16) -> Self { inw(port) } } impl PortIn for u32 { unsafe fn port_in(port: u16) -> Self { inl(port) } } #[derive(Debug)] pub struct Port<T: PortIn + PortOut> { port: u16, _phantom: PhantomData<T>, } impl<T: PortIn + PortOut> Port<T> { pub const fn new(port: u16) -> Port<T> { Port { port: port, _phantom: PhantomData } } pub const fn port_address(&self) -> u16 { self.port } pub fn read(&self) -> T { unsafe { T::port_in(self.port) } } pub unsafe fn write(&self, value: T) { T::port_out(self.port, value); } } #[derive(Debug)] pub struct PortReadOnly<T: PortIn> { port: u16, _phantom: PhantomData<T>, } impl<T: PortIn> PortReadOnly<T> { pub const fn new(port: u16) -> PortReadOnly<T> { PortReadOnly { port: port, _phantom: PhantomData } } pub const fn port_address(&self) -> u16 { self.port } pub fn read(&self) -> T { unsafe { T::port_in(self.port) } } } #[derive(Debug)] pub struct PortWriteOnly<T: PortOut> { port: u16, _phantom: PhantomData<T>, } impl<T: PortOut> PortWriteOnly<T> { pub const fn new(port: u16) -> PortWriteOnly<T> { PortWriteOnly { port: port, _phantom: PhantomData } } pub const fn port_address(&self) -> u16 { self.port } pub unsafe fn write(&self, value: T) { T::port_out(self.port, value); } }
#![feature(llvm_asm, const_fn_trait_bound)] #![no_std] use core::marker::PhantomData; #[cfg(any(target_arch="x86", target_arch="x86_64"))] mod x86; #[cfg(any(target_arch="x86", target_arch="x86_64"))] pub use x86::{inb, outb, inw, outw, inl, outl}; pub trait PortIn { unsafe fn port_in(port: u16) -> Self; } pub trait PortOut { unsafe fn port_out(port: u16, value: Self); } impl PortOut for u8 { unsafe fn port_out(port: u16, value: Self) { outb(value, port); } } impl PortOut for u16 { unsafe fn port_out(port: u16, value: Self) { outw(value, port); } } impl PortOut for u32 { unsafe fn port_out(port: u16, value: Self) { outl(value, port); } } impl PortIn for u8 { unsafe fn port_in(port: u16) -> Self { inb(port) } } impl PortIn for u16 { unsafe fn port_in(port: u16) -> Self { inw(port) } } impl PortIn for u32 { unsafe fn port_in(port: u16) -> Self { inl(port) } } #[derive(Debug)] pub struct Port<T: PortIn + PortOut> { port: u16, _phantom: PhantomData<T>, } impl<T: PortIn + PortOut> Port<T> { pub const fn new(port: u16) -> Port<T> { Port { port: port, _phantom: PhantomData } } pub const fn port_address(&self) -> u16 { self.port } pub fn read(&self) -> T { unsafe { T::port_in(self.port) } } pub unsafe fn write(&self, value: T) { T::port_out(self.port, value); } } #[derive(Debug)] pub struct PortReadOnly<T: PortIn> { port: u16, _phantom: PhantomData<T>, } impl<T: PortIn> PortReadOnly<T> { pub const fn new(port: u16) -> PortReadOnly<T> { PortReadOnly { port: port, _phantom: PhantomData } } pub const fn port_address(&self) -> u16 { self.port } pub fn read(&self) -> T { unsafe { T::
pub unsafe fn write(&self, value: T) { T::port_out(self.port, value); } }
port_in(self.port) } } } #[derive(Debug)] pub struct PortWriteOnly<T: PortOut> { port: u16, _phantom: PhantomData<T>, } impl<T: PortOut> PortWriteOnly<T> { pub const fn new(port: u16) -> PortWriteOnly<T> { PortWriteOnly { port: port, _phantom: PhantomData } } pub const fn port_address(&self) -> u16 { self.port }
random
[ { "content": "/// write data to the second ps2 data port and return the response\n\npub fn data_to_port2(value: u8) -> u8 {\n\n ps2_write_command(0xD4);\n\n data_to_port1(value)\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 0, "score": 298433.0900723853 }, { "content": "/// write data to the first ps2 data port and return the response\n\npub fn data_to_port1(value: u8) -> u8 {\n\n unsafe { PS2_PORT.lock().write(value) };\n\n let response = ps2_read_data();\n\n response\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 1, "score": 298433.0900723853 }, { "content": "/// Finds the Non-Maskable Interrupt (NMI) entry in the MADT ACPI table (i.e., the given `MadtIter`)\n\n/// corresponding to the given processor. \n\n/// If no entry exists, it returns the default NMI entry value: `(lint = 1, flags = 0)`.\n\npub fn find_nmi_entry_for_processor(processor: u8, madt_iter: MadtIter) -> (u8, u16) {\n\n for madt_entry in madt_iter {\n\n match madt_entry {\n\n MadtEntry::NonMaskableInterrupt(nmi) => {\n\n // NMI entries are based on the \"processor\" id, not the \"apic_id\"\n\n // Return this Nmi entry if it's for the given lapic, or if it's for all lapics\n\n if nmi.processor == processor || nmi.processor == 0xFF {\n\n return (nmi.lint, nmi.flags);\n\n }\n\n }\n\n _ => { }\n\n }\n\n }\n\n\n\n let (lint, flags) = (1, 0);\n\n warn!(\"Couldn't find NMI entry for processor {} (<-- not apic_id). Using default lint {}, flags {}\", processor, lint, flags);\n\n (lint, flags)\n\n}\n", "file_path": "kernel/acpi/madt/src/lib.rs", "rank": 2, "score": 289352.2895844331 }, { "content": "///set LED status of the keyboard\n\n/// parameter :\n\n/// 0: ScrollLock; 1: NumberLock; 2: CapsLock\n\npub fn keyboard_led(value: u8) {\n\n if let Err(_e) = command_to_keyboard(0xED) {\n\n warn!(\"failed to set the keyboard led\");\n\n } else if let Err(_e) = command_to_keyboard(value) {\n\n warn!(\"failed to set the keyboard led\");\n\n }\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 3, "score": 283864.0547400811 }, { "content": "/// write command to the command ps2 port (0x64)\n\npub fn ps2_write_command(value: u8) {\n\n unsafe {\n\n PS2_COMMAND_PORT.lock().write(value);\n\n }\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 6, "score": 279291.9770583431 }, { "content": "/// write the new config to the ps2 command port (0x64)\n\npub fn ps2_write_config(value: u8) {\n\n ps2_write_command(0x60);\n\n unsafe { PS2_PORT.lock().write(value) };\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 7, "score": 279291.91976584494 }, { "content": "/// write data to the second ps2 output buffer\n\npub fn write_to_second_output_buffer(value: u8) {\n\n ps2_write_command(0xD3);\n\n unsafe { PS2_PORT.lock().write(value) };\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 8, "score": 274935.0698156269 }, { "content": "/// write command to the mouse and return the result\n\npub fn command_to_mouse(value: u8) -> Result<(), &'static str> {\n\n // if the mouse doesn't acknowledge the command return error\n\n let response = data_to_port2(value);\n\n if response != 0xFA {\n\n for _x in 0..14 {\n\n let response = ps2_read_data();\n\n\n\n if response == 0xFA {\n\n // info!(\"mouse command is responded !!!!\");\n\n return Ok(());\n\n }\n\n }\n\n warn!(\"mouse command to second port is not accepted\");\n\n return Err(\"mouse command is not responded!!!\");\n\n }\n\n // info!(\"mouse command is responded !!!!\");\n\n Ok(())\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 9, "score": 256607.64022552094 }, { "content": "/// write command to the keyboard and return the result\n\npub fn command_to_keyboard(value: u8) -> Result<(), &'static str> {\n\n let response = data_to_port1(value);\n\n\n\n match response {\n\n 0xFA => {\n\n // keyboard acknowledges the command\n\n Ok(())\n\n }\n\n\n\n 0xFE => {\n\n // keyboard doesn't acknowledge the command\n\n Err(\"Fail to send the command to the keyboard\")\n\n }\n\n\n\n _ => {\n\n for _x in 0..14 {\n\n // wait for response\n\n let response = ps2_read_data();\n\n if response == 0xFA {\n\n return Ok(());\n\n } else if response == 0xfe {\n\n return Err(\"Please resend the command to the keyboard\");\n\n }\n\n }\n\n Err(\"command is not acknowledged\")\n\n }\n\n }\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 10, "score": 256607.64022552094 }, { "content": "/// set the resolution of the mouse\n\n/// parameter :\n\n/// 0x00: 1 count/mm; 0x01 2 count/mm;\n\n/// 0x02 4 count/mm; 0x03 8 count/mm;\n\npub fn mouse_resolution(value: u8) -> Result<(), &'static str> {\n\n if let Err(_e) = command_to_mouse(0xE8) {\n\n warn!(\"command set mouse resolution is not accepted\");\n\n Err(\"set mouse resolution failed!!!\")\n\n } else {\n\n if let Err(_e) = command_to_mouse(value) {\n\n warn!(\"the resolution value is not accepted\");\n\n Err(\"set mouse resolution failed!!!\")\n\n } else {\n\n // info!(\"set mouse resolution succeeded!!!\");\n\n Ok(())\n\n }\n\n }\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 11, "score": 256607.64022552094 }, { "content": "/// set the scancode set of the keyboard\n\n/// 0: get the current set; 1: set 1\n\n/// 2: set 2; 3: set 3\n\npub fn keyboard_scancode_set(value: u8) -> Result<(), &'static str> {\n\n if let Err(_e) = command_to_keyboard(0xF0) {\n\n return Err(\"failed to set the keyboard scancode set\");\n\n } else if let Err(_e) = command_to_keyboard(value) {\n\n return Err(\"failed to set the keyboard scancode set\");\n\n }\n\n Ok(())\n\n}\n\n\n\npub enum KeyboardType {\n\n MF2Keyboard,\n\n MF2KeyboardWithPSControllerTranslator,\n\n AncientATKeyboard,\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 12, "score": 252662.8883756853 }, { "content": "/// set ps2 mouse's sampling rate\n\npub fn set_sampling_rate(value: u8) -> Result<(), &'static str> {\n\n // if command is not acknowledged\n\n if let Err(_e) = command_to_mouse(0xF3) {\n\n Err(\"set mouse sampling rate failled, please try again\")\n\n } else {\n\n // if second byte command is not acknowledged\n\n if let Err(_e) = command_to_mouse(value) {\n\n Err(\"set mouse sampling rate failled, please try again\")\n\n } else {\n\n Ok(())\n\n }\n\n }\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 13, "score": 252662.8883756853 }, { "content": "/// The closure type that can be used within a `WaitCondition`:\n\n/// a parameterless function that returns a bool indicating whether the condition is met.\n\npub trait WaitConditionFn = Fn() -> bool;\n\n\n\n\n\n/// A condition variable that allows multiple `Task`s to wait for a condition to be met,\n\n/// upon which other `Task`s can notify them.\n\n/// This is effectively a convenience wrapper around `WaitQueue::wait_until()`. \n\n/// \n\n/// The condition is specified as an closure that returns a boolean: \n\n/// `true` if the condition has been met, `false` if not. \n\n/// \n\n/// The condition closure must be a regular `Fn` that can be repeatedly executed,\n\n/// and should be cheap and quick to execute. \n\n/// Complicated logic should be kept outside of the condition function. \n\n/// \n\n/// This can be shared across multiple `Task`s by wrapping it in an `Arc`. \n\npub struct WaitCondition<F: WaitConditionFn> {\n\n condition_fn: F,\n\n wait_queue: WaitQueue,\n\n}\n\n\n", "file_path": "kernel/wait_condition/src/lib.rs", "rank": 14, "score": 245511.83184859835 }, { "content": "/// read mouse data packet\n\npub fn handle_mouse_packet() -> u32 {\n\n // since nowadays almost every mouse has scroll, so there is a 4 byte packet\n\n // which means that only mouse with ID 3 or 4 can be applied this function\n\n // because the mouse is initialized to have ID 3 or 4, so this function can\n\n // handle the mouse data packet\n\n\n\n let byte_1 = ps2_read_data() as u32;\n\n let byte_2 = ps2_read_data() as u32;\n\n let byte_3 = ps2_read_data() as u32;\n\n let byte_4 = ps2_read_data() as u32;\n\n let readdata = (byte_4 << 24) | (byte_3 << 16) | (byte_2 << 8) | byte_1;\n\n readdata\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 15, "score": 244947.26399323062 }, { "content": "/// read the config of the ps2 port\n\npub fn ps2_read_config() -> u8 {\n\n ps2_write_command(0x20);\n\n let config = ps2_read_data();\n\n config\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 16, "score": 244176.13016909314 }, { "content": "/// read dat from ps2 data port (0x60)\n\npub fn ps2_read_data() -> u8 {\n\n PS2_PORT.lock().read()\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 17, "score": 244176.01217028277 }, { "content": "/// read the ps2 status register\n\npub fn ps2_status_register() -> u8 {\n\n PS2_COMMAND_PORT.lock().read()\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 18, "score": 244170.071207928 }, { "content": "/// Returns the APIC ID of the currently executing processor core.\n\npub fn get_my_apic_id() -> u8 {\n\n rdmsr(IA32_TSC_AUX) as u8\n\n}\n\n\n\n\n", "file_path": "kernel/apic/src/lib.rs", "rank": 19, "score": 244170.071207928 }, { "content": "pub fn pick_child_core() -> u8 {\n\n\t// try with current core -1\n\n\tlet child_core: u8 = (CPU_ID!() as u8).saturating_sub(1);\n\n\tif nr_tasks_in_rq(child_core) == Some(1) {return child_core;}\n\n\n\n\t// if failed, try from the last to the first\n\n\tfor child_core in (0..apic::core_count() as u8).rev() {\n\n\t\tif nr_tasks_in_rq(child_core) == Some(1) {return child_core;}\n\n\t}\n\n\tdebug!(\"WARNING : Cannot pick a child core because cores are busy\");\n\n\tdebug!(\"WARNING : Selecting current core\");\n\n\treturn child_core;\n\n}\n\n\n", "file_path": "applications/test_downtime/src/lib.rs", "rank": 20, "score": 240748.4591768384 }, { "content": "/// Entry to rust for an AP.\n\n/// The arguments must match the invocation order in \"ap_boot.asm\"\n\npub fn kstart_ap(processor_id: u8, apic_id: u8, \n\n _stack_start: VirtualAddress, _stack_end: VirtualAddress,\n\n nmi_lint: u8, nmi_flags: u16) -> ! \n\n{\n\n info!(\"Booted AP: proc: {}, apic: {}, stack: {:#X} to {:#X}, nmi_lint: {}, nmi_flags: {:#X}\", \n\n processor_id, apic_id, _stack_start, _stack_end, nmi_lint, nmi_flags\n\n );\n\n\n\n // set a flag telling the BSP that this AP has entered Rust code\n\n AP_READY_FLAG.store(true, Ordering::SeqCst);\n\n\n\n // get the stack that was allocated for us (this AP) by the BSP.\n\n let this_ap_stack = AP_STACKS.lock().remove(&apic_id)\n\n .expect(&format!(\"BUG: kstart_ap(): couldn't get stack created for AP with apic_id: {}\", apic_id));\n\n\n\n // initialize interrupts (including TSS/GDT) for this AP\n\n let kernel_mmi_ref = get_kernel_mmi_ref().expect(\"kstart_ap(): kernel_mmi ref was None\");\n\n let (double_fault_stack, privilege_stack) = {\n\n let mut kernel_mmi = kernel_mmi_ref.lock();\n\n (\n", "file_path": "kernel/ap_start/src/lib.rs", "rank": 21, "score": 238036.73972147083 }, { "content": "pub fn init(freq_hertz: u32) {\n\n let divisor = PIT_DEFAULT_DIVIDEND_HZ / freq_hertz;\n\n if divisor > (u16::max_value() as u32) {\n\n panic!(\"The chosen PIT frequency ({} Hz) is too small, it must be {} Hz or greater!\", \n\n freq_hertz, PIT_MINIMUM_FREQ);\n\n }\n\n\n\n // SAFE because we're simply configuring the PIT clock, and the code below is correct.\n\n unsafe {\n\n use x86_64::instructions::port::inb;\n\n PIT_COMMAND.lock().write(0x36); // 0x36: see this: http://www.osdever.net/bkerndev/Docs/pit.htm\n\n\n\n // must write the low byte and then the high byte\n\n PIT_CHANNEL_0.lock().write(divisor as u8);\n\n inb(0x60); //xread from PS/2 port 0x60, i.e., a short delay + acknowledging status register\n\n PIT_CHANNEL_0.lock().write((divisor >> 8) as u8);\n\n }\n\n}\n\n\n\n\n", "file_path": "kernel/pit_clock/src/lib.rs", "rank": 22, "score": 235705.93249084195 }, { "content": "/// clean the PS2 data port (0x60) output buffer\n\n/// also return the vec of data previously in the buffer which may be useful\n\npub fn ps2_clean_buffer() -> Vec<u8> {\n\n let mut buffer_data = Vec::new();\n\n loop {\n\n // if no more data in the output buffer\n\n if ps2_status_register() & 0x01 == 0 {\n\n break;\n\n } else {\n\n buffer_data.push(ps2_read_data());\n\n }\n\n }\n\n buffer_data\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 23, "score": 234976.7072924651 }, { "content": "pub fn get_bsp_id() -> Option<u8> {\n\n BSP_PROCESSOR_ID.get().cloned()\n\n}\n\n\n", "file_path": "kernel/apic/src/lib.rs", "rank": 24, "score": 234965.98501279505 }, { "content": "/// Initialize the IOMMU hardware.\n\n///\n\n/// Currently this just sets up basic structures and prints out information about the IOMMU;\n\n/// it doesn't actually create any I/O device page tables.\n\n///\n\n/// # Arguments\n\n/// * `host_address_width`: number of address bits available for DMA\n\n/// * `pci_segment_number`: PCI segment associated with this IOMMU\n\n/// * `register_base_address`: base address of register set\n\n/// * `page_table`: page table to install mapping\n\npub fn init(host_address_width: u8,\n\n pci_segment_number: u16,\n\n register_base_address: PhysicalAddress,\n\n page_table: &mut PageTable\n\n) -> Result<(), &'static str> {\n\n\n\n info!(\"IOMMU Init stage 1 begin.\");\n\n\n\n // map memory-mapped registers into virtual address space\n\n let mp = {\n\n let frames = allocate_frames_at(register_base_address, 1)?;\n\n let pages = allocate_pages(1).ok_or(\"Unable to find virtual page!\")?;\n\n let flags = EntryFlags::WRITABLE | EntryFlags::NO_CACHE | EntryFlags::NO_EXECUTE;\n\n page_table.map_allocated_pages_to(pages, frames, flags)?\n\n };\n\n\n\n let regs = BoxRefMut::new(Box::new(mp))\n\n .try_map_mut(|mp| mp.as_type_mut::<IntelIommuRegisters>(0))?;\n\n\n\n // get the version number\n", "file_path": "kernel/iommu/src/lib.rs", "rank": 25, "score": 234965.98501279505 }, { "content": "/// set up TSS entry for the given AP core. \n\n/// Returns a reference to a Mutex wrapping the new TSS entry.\n\npub fn create_tss(apic_id: u8, \n\n double_fault_stack_top_unusable: VirtualAddress, \n\n privilege_stack_top_unusable: VirtualAddress) \n\n -> &'static Mutex<TaskStateSegment>\n\n{\n\n let mut tss = TaskStateSegment::new();\n\n // TSS.RSP0 is used in kernel space after a transition from Ring 3 -> Ring 0\n\n tss.privilege_stack_table[0] = x86_64::VirtualAddress(privilege_stack_top_unusable.value());\n\n tss.interrupt_stack_table[DOUBLE_FAULT_IST_INDEX] = x86_64::VirtualAddress(double_fault_stack_top_unusable.value());\n\n\n\n // insert into TSS list\n\n TSS.insert(apic_id, Mutex::new(tss));\n\n let tss_ref = TSS.get(&apic_id).unwrap(); // safe to unwrap since we just added it to the list\n\n // debug!(\"Created TSS for apic {}, TSS: {:?}\", apic_id, tss_ref);\n\n tss_ref\n\n}", "file_path": "kernel/tss/src/lib.rs", "rank": 26, "score": 234965.98501279505 }, { "content": "/// Send an end of interrupt signal, notifying the interrupt chip that\n\n/// the given interrupt request `irq` has been serviced. \n\n/// \n\n/// This function supports all types of interrupt chips -- APIC, x2apic, PIC --\n\n/// and will perform the correct EOI operation based on which chip is currently active.\n\n///\n\n/// The `irq` argument is only used if the `PIC` chip is active,\n\n/// but it doesn't hurt to always provide it.\n\npub fn eoi(irq: Option<u8>) {\n\n match INTERRUPT_CHIP.load() {\n\n InterruptChip::APIC | InterruptChip::X2APIC => {\n\n if let Some(my_apic) = apic::get_my_apic() {\n\n my_apic.write().eoi();\n\n } else {\n\n error!(\"BUG: couldn't get my LocalApic instance to send EOI!\");\n\n }\n\n }\n\n InterruptChip::PIC => {\n\n if let Some(_pic) = PIC.get() {\n\n if let Some(irq) = irq {\n\n _pic.notify_end_of_interrupt(irq);\n\n } else {\n\n error!(\"BUG: missing required IRQ argument for PIC EOI!\");\n\n } \n\n } else {\n\n error!(\"BUG: couldn't get PIC instance to send EOI!\");\n\n } \n\n }\n", "file_path": "kernel/interrupts/src/lib.rs", "rank": 27, "score": 233188.97330117217 }, { "content": "/// Returns the \"least busy\" core\n\npub fn get_least_busy_core() -> Option<u8>{\n\n RunQueue::get_least_busy_core()\n\n}\n\n\n", "file_path": "kernel/runqueue/src/lib.rs", "rank": 28, "score": 231714.07196282083 }, { "content": "pub fn my_mod_func() {\n\n logger::write_fmt(format_args!(\"\\n\\nHello from my_mod_func!\")).unwrap();\n\n}\n", "file_path": "libtheseus/src/my_mod.rs", "rank": 29, "score": 231544.28822512995 }, { "content": "#[inline]\n\npub fn percent_decode(input: &[u8]) -> PercentDecode {\n\n PercentDecode {\n\n bytes: input.iter()\n\n }\n\n}\n\n\n\n/// The return type of `percent_decode()`.\n\n#[derive(Clone, Debug)]\n\npub struct PercentDecode<'a> {\n\n bytes: slice::Iter<'a, u8>,\n\n}\n\n\n", "file_path": "libs/percent_encoding/lib.rs", "rank": 30, "score": 226511.11852460902 }, { "content": "/// Utility function to get Fault type from exception number. \n\npub fn from_exception_number(num: u8) -> FaultType {\n\n match num {\n\n 0x0 => FaultType::DivideByZero,\n\n 0x2 => FaultType::NMI,\n\n 0x4 => FaultType::Overflow,\n\n 0x5 => FaultType::BoundRangeExceeded,\n\n 0x6 => FaultType::InvalidOpCode,\n\n 0x7 => FaultType::DeviceNotAvailable,\n\n 0x8 => FaultType::DoubleFault,\n\n 0xA => FaultType::InvalidTSS,\n\n 0xB => FaultType::SegmentNotPresent,\n\n 0xD => FaultType::GeneralProtectionFault,\n\n 0xE => FaultType::PageFault,\n\n num => FaultType::UnknownException(num),\n\n }\n\n}\n\n\n\n/// The different types of recovery procedures used for the \n\n/// observed fault\n\n#[derive(Debug, Clone, PartialEq)]\n", "file_path": "kernel/fault_log/src/lib.rs", "rank": 31, "score": 223416.5853083646 }, { "content": "/// Returns a reference to the `PciDevice` with the given bus, slot, func identifier.\n\n/// If the PCI bus hasn't been initialized, this initializes the PCI bus & scans it to enumerates devices.\n\npub fn get_pci_device_bsf(bus: u16, slot: u16, func: u16) -> Option<&'static PciDevice> {\n\n for b in get_pci_buses() {\n\n if b.bus_number == bus {\n\n for d in &b.devices {\n\n if d.slot == slot && d.func == func {\n\n return Some(&d);\n\n }\n\n }\n\n }\n\n }\n\n None\n\n}\n\n\n\n\n", "file_path": "kernel/pci/src/lib.rs", "rank": 32, "score": 223206.18710326107 }, { "content": "/// This trait is used to define a page from which objects are allocated\n\n/// in an `SCAllocator`.\n\n///\n\n/// The implementor of this trait needs to provide access to the page meta-data,\n\n/// which consists of:\n\n/// - A bitfield (to track allocations),\n\n/// - `prev` and `next` pointers to insert the page in free lists\n\npub trait AllocablePage {\n\n /// The total size (in bytes) of the page.\n\n ///\n\n /// # Note\n\n /// We also assume that the address of the page will be aligned to `SIZE`.\n\n const SIZE: usize;\n\n\n\n const METADATA_SIZE: usize;\n\n\n\n const HEAP_ID_OFFSET: usize;\n\n\n\n fn clear_metadata(&mut self);\n\n fn set_heap_id(&mut self, heap_id: usize);\n\n fn heap_id(&self) -> usize;\n\n fn bitfield(&self) -> &[AtomicU64; 8];\n\n fn bitfield_mut(&mut self) -> &mut [AtomicU64; 8];\n\n fn prev(&mut self) -> &mut Rawlink<Self>\n\n where\n\n Self: core::marker::Sized;\n\n fn next(&mut self) -> &mut Rawlink<Self>\n", "file_path": "kernel/slabmalloc_unsafe/src/pages.rs", "rank": 33, "score": 222751.05776666876 }, { "content": "/// Initializes the [`SerialPort`] specified by the given [`SerialPortAddress`].\n\n///\n\n/// This function also registers the interrupt handler for this serial port\n\n/// such that it can receive data using interrupts instead of busy-waiting or polling.\n\n///\n\n/// If the given serial port has already been initialized, this does nothing\n\n/// and simply returns a reference to the already-initialized serial port.\n\npub fn init_serial_port(\n\n serial_port_address: SerialPortAddress,\n\n serial_port: SerialPortBasic,\n\n) -> &'static Arc<MutexIrqSafe<SerialPort>> {\n\n static_port_of(&serial_port_address).call_once(|| {\n\n let sp = Arc::new(MutexIrqSafe::new(SerialPort::new(serial_port)));\n\n let (int_num, int_handler) = interrupt_number_handler(&serial_port_address);\n\n SerialPort::register_interrupt_handler(sp.clone(), int_num, int_handler).unwrap();\n\n sp\n\n })\n\n}\n\n\n", "file_path": "kernel/serial_port/src/lib.rs", "rank": 34, "score": 221141.4308983471 }, { "content": "/// Obtains a reference to the [`SerialPort`] specified by the given [`SerialPortAddress`],\n\n/// if it has been initialized (see [`init_serial_port()`]).\n\npub fn get_serial_port(\n\n serial_port_address: SerialPortAddress\n\n) -> Option<&'static Arc<MutexIrqSafe<SerialPort>>> {\n\n static_port_of(&serial_port_address).get()\n\n}\n\n\n", "file_path": "kernel/serial_port/src/lib.rs", "rank": 35, "score": 221137.01664615207 }, { "content": "/// Checks to see if the provided HTTP request can be properly parsed, and returns true if so.\n\npub fn check_http_request(request_bytes: &[u8]) -> bool {\n\n let mut headers = [httparse::EMPTY_HEADER; 64];\n\n let mut request = httparse::Request::new(&mut headers);\n\n request.parse(request_bytes).is_ok() && request_bytes.ends_with(b\"\\r\\n\\r\\n\")\n\n}\n\n\n\n\n\n/// TODO: create a proper HttpRequest type with header creation fields and actual verification\n\npub type HttpRequest = String;\n\n\n\n\n\n/// An HttpResponse that has been fully received from a remote server.\n\n/// \n\n/// TODO: revamp this structure to not store redundant data\n\npub struct HttpResponse {\n\n /// The actual array of raw bytes received from the server, \n\n /// including all of the headers and body.\n\n pub packet: Vec<u8>,\n\n /// The length of all headers\n\n pub header_length: usize,\n", "file_path": "kernel/http_client/src/lib.rs", "rank": 36, "score": 220468.27700331272 }, { "content": "/// Start interrupt process in order to take samples using the PMU. \n\n/// It loads the starting value as such that an overflow will occur at \"event_per_sample\" events. \n\n/// That overflow triggers an interrupt where information about the current running task is sampled.\n\n/// \n\n/// # Arguments\n\n/// * `event_type`: determines type of event that sampling interval is based on\n\n/// * `event_per_sample`: how many of those events should occur between each sample \n\n/// * `task_id`: allows the user to choose to only sample from a specific task by inputting a number or sample from all tasks by inputting None \n\n/// * `sample_count`: specifies how many samples should be recorded. \n\n/// \n\n/// # Note\n\n/// The function clears any previous values from sampling stored for this core, so values must be retrieved before starting a new sampling process.\n\n/// Currently can only sample \"this\" core - core that the function was called on. \n\n/// \n\npub fn start_samples(event_type: EventType, event_per_sample: u32, task_id: Option<usize>, sample_count: u32) -> Result<(),&'static str> { \n\n check_pmu_availability()?;\n\n\n\n // perform checks to ensure that counter is ready to use and that previous results are not being unintentionally discarded\n\n let my_core_id = apic::get_my_apic_id();\n\n\n\n trace!(\"start_samples: the core id is : {}\", my_core_id);\n\n\n\n // If counter 0 is currently in use (false), then return \n\n // PMC0 is always used for sampling, but is not reserved for it.\n\n if !counter_is_available(my_core_id, 0)? {\n\n return Err(\"PMU counter 0 is currently in use and can't be used for sampling. End all other PMU tasks and try again\");\n\n }\n\n\n\n // set the counter as in use\n\n claim_counter(my_core_id, 0)?;\n\n\n\n // check to make sure that sampling is not already in progress on this core\n\n // this should never happen since the counter would not be available for use\n\n if core_is_currently_sampling(my_core_id) {\n", "file_path": "kernel/pmu_x86/src/lib.rs", "rank": 37, "score": 218986.8910391175 }, { "content": "/// Return the percent-encoding of the given bytes.\n\n///\n\n/// This is unconditional, unlike `percent_encode()` which uses an encode set.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use url::percent_encoding::percent_encode_byte;\n\n///\n\n/// assert_eq!(\"foo bar\".bytes().map(percent_encode_byte).collect::<String>(),\n\n/// \"%66%6F%6F%20%62%61%72\");\n\n/// ```\n\npub fn percent_encode_byte(byte: u8) -> &'static str {\n\n let index = usize::from(byte) * 3;\n\n &\"\\\n\n %00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F\\\n\n %10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F\\\n\n %20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2D%2E%2F\\\n\n %30%31%32%33%34%35%36%37%38%39%3A%3B%3C%3D%3E%3F\\\n\n %40%41%42%43%44%45%46%47%48%49%4A%4B%4C%4D%4E%4F\\\n\n %50%51%52%53%54%55%56%57%58%59%5A%5B%5C%5D%5E%5F\\\n\n %60%61%62%63%64%65%66%67%68%69%6A%6B%6C%6D%6E%6F\\\n\n %70%71%72%73%74%75%76%77%78%79%7A%7B%7C%7D%7E%7F\\\n\n %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F\\\n\n %90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F\\\n\n %A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF\\\n\n %B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF\\\n\n %C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF\\\n\n %D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF\\\n\n %E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF\\\n\n %F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF\\\n\n \"[index..index + 3]\n", "file_path": "libs/percent_encoding/lib.rs", "rank": 38, "score": 218715.94815815578 }, { "content": "/// Returns the priority of a given task.\n\n/// This function returns None when a scheduler without priority is loaded.\n\npub fn get_priority(_task: &TaskRef) -> Option<u8> {\n\n #[cfg(priority_scheduler)] {\n\n scheduler_priority::get_priority(_task)\n\n }\n\n #[cfg(not(priority_scheduler))] {\n\n None\n\n }\n\n}\n\n\n\n\n", "file_path": "kernel/scheduler/src/lib.rs", "rank": 39, "score": 218710.19031821564 }, { "content": "/// check the mouse's id\n\npub fn check_mouse_id() -> Result<u8, &'static str> {\n\n // stop the streaming before trying to read the mouse's id\n\n let result = mouse_packet_streaming(false);\n\n match result {\n\n Err(e) => {\n\n warn!(\"check_mouse_id(): please try read the mouse id later, error: {}\", e);\n\n return Err(e);\n\n }\n\n Ok(_buffer_data) => {\n\n let id_num: u8;\n\n // check whether the command is acknowledged\n\n if let Err(e) = command_to_mouse(0xF2) {\n\n warn!(\"check_mouse_id(): command not accepted, please try again.\");\n\n return Err(e);\n\n } else {\n\n id_num = ps2_read_data();\n\n }\n\n // begin streaming again\n\n if let Err(e) = mouse_packet_streaming(true) {\n\n warn!(\"the streaming of mouse is disabled,please open it manually\");\n\n return Err(e);\n\n }\n\n return Ok(id_num);\n\n }\n\n }\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 40, "score": 218710.19031821564 }, { "content": "/// Helper function return the tasks in a given core's runqueue\n\npub fn nr_tasks_in_rq(core: u8) -> Option<usize> {\n\n\tmatch runqueue::get_runqueue(core).map(|rq| rq.read()) {\n\n\t\tSome(rq) => { Some(rq.iter().count()) }\n\n\t\t_ => { None }\n\n\t}\n\n}\n\n\n\n\n", "file_path": "kernel/libtest/src/lib.rs", "rank": 41, "score": 218710.19031821564 }, { "content": "/// Helper function to pick a free child core if possible\n\npub fn pick_free_core() -> Result<u8, &'static str> {\n\n\t// a free core will only have 1 task, the idle task, running on it.\n\n\tconst NUM_TASKS_ON_FREE_CORE: usize = 1;\n\n\n\n\t// try with current core -1\n\n\tlet child_core: u8 = CPU_ID!() as u8 - 1;\n\n\tif nr_tasks_in_rq(child_core) == Some(NUM_TASKS_ON_FREE_CORE) {return Ok(child_core);}\n\n\n\n\t// if failed, iterate through all cores\n\n\tfor lapic in get_lapics().iter() {\n\n\t\tlet child_core = lapic.0;\n\n\t\tif nr_tasks_in_rq(*child_core) == Some(1) {return Ok(*child_core);}\n\n\t}\n\n\n\n\twarn!(\"Cannot pick a free core because cores are busy\");\n\n\tErr(\"Cannot pick a free core because cores are busy\")\n\n}\n\n\n\n\n\n#[inline(always)]\n", "file_path": "kernel/libtest/src/lib.rs", "rank": 42, "score": 218710.19031821564 }, { "content": "/// Takes ownership of the [`SerialPort`] specified by the given [`SerialPortAddress`].\n\n///\n\n/// This function initializes the given serial port if it has not yet been initialized.\n\n/// If the serial port has already been initialized and taken by another crate,\n\n/// this returns `None`.\n\n///\n\n/// The returned [`SerialPort`] will be restored to this crate upon being dropped.\n\npub fn take_serial_port(\n\n serial_port_address: SerialPortAddress\n\n) -> Option<SerialPort> {\n\n let sp = serial_port_address.to_static_port();\n\n let mut locked = sp.lock();\n\n if let TriState::Uninited = &*locked {\n\n *locked = TriState::Inited(SerialPort::new(serial_port_address as u16));\n\n }\n\n locked.take()\n\n}\n\n\n\n// The E9 port can be used with the Bochs emulator for extra debugging info.\n\n// const PORT_E9: u16 = 0xE9; // for use with bochs\n\n// static E9: Port<u8> = Port::new(PORT_E9); // see Bochs's port E9 hack\n\n\n\n\n\n/// A serial port and its various data and control registers.\n\n///\n\n/// TODO: use PortReadOnly and PortWriteOnly to set permissions for each register.\n\npub struct SerialPort {\n", "file_path": "kernel/serial_port_basic/src/lib.rs", "rank": 43, "score": 217896.256675528 }, { "content": "/// Creates a new `RunQueue` for the given core, which is an `apic_id`.\n\npub fn init(which_core: u8) -> Result<(), &'static str>{\n\n RunQueue::init(which_core)\n\n}\n\n\n", "file_path": "kernel/runqueue/src/lib.rs", "rank": 44, "score": 217527.03895479592 }, { "content": "/// Returns the priority of the given task.\n\npub fn get_priority(task: &TaskRef) -> Option<u8> {\n\n RunQueue::get_priority(task)\n\n}\n\n\n", "file_path": "kernel/scheduler_priority/src/lib.rs", "rank": 45, "score": 215761.8820131637 }, { "content": "/// Initializes a new page table and sets up all necessary mappings for the kernel to continue running. \n\n/// Returns the following tuple, if successful:\n\n/// \n\n/// 1. The kernel's new PageTable, which is now currently active,\n\n/// 2. the kernel's text section MappedPages,\n\n/// 3. the kernel's rodata section MappedPages,\n\n/// 4. the kernel's data section MappedPages,\n\n/// 5. a tuple of the stack's underlying guard page (an `AllocatedPages` instance) and the actual `MappedPages` backing it,\n\n/// 6. the `MappedPages` holding the bootloader info,\n\n/// 7. the kernel's list of *other* higher-half MappedPages that needs to be converted to a vector after heap initialization, and which should be kept forever,\n\n/// 8. the kernel's list of identity-mapped MappedPages that needs to be converted to a vector after heap initialization, and which should be dropped before starting the first userspace program. \n\n///\n\n/// Otherwise, it returns a str error message. \n\npub fn init(\n\n boot_info: &multiboot2::BootInformation,\n\n) -> Result<(\n\n PageTable,\n\n MappedPages,\n\n MappedPages,\n\n MappedPages,\n\n (AllocatedPages, MappedPages),\n\n MappedPages,\n\n [Option<MappedPages>; 32],\n\n [Option<MappedPages>; 32]\n\n ), &'static str>\n\n{\n\n let (aggregated_section_memory_bounds, _sections_memory_bounds) = find_section_memory_bounds(boot_info)?;\n\n debug!(\"{:X?}\\n{:X?}\", aggregated_section_memory_bounds, _sections_memory_bounds);\n\n \n\n // bootstrap a PageTable from the currently-loaded page table\n\n let current_active_p4 = frame_allocator::allocate_frames_at(aggregated_section_memory_bounds.page_table.start.1, 1)?;\n\n let mut page_table = PageTable::from_current(current_active_p4)?;\n\n debug!(\"Bootstrapped initial {:?}\", page_table);\n", "file_path": "kernel/memory/src/paging/mod.rs", "rank": 46, "score": 215070.55235773965 }, { "content": "/// Initializes the module management system based on the bootloader-provided modules, \n\n/// and creates and returns the default `CrateNamespace` for kernel crates.\n\npub fn init(\n\n bootloader_modules: Vec<BootloaderModule>,\n\n kernel_mmi: &mut MemoryManagementInfo\n\n) -> Result<&'static Arc<CrateNamespace>, &'static str> {\n\n let (_namespaces_dir, default_kernel_namespace_dir) = parse_bootloader_modules_into_files(bootloader_modules, kernel_mmi)?;\n\n // Create the default CrateNamespace for kernel crates.\n\n let name = default_kernel_namespace_dir.lock().get_name();\n\n let default_namespace = CrateNamespace::new(name, default_kernel_namespace_dir, None);\n\n Ok(INITIAL_KERNEL_NAMESPACE.call_once(|| Arc::new(default_namespace)))\n\n}\n\n\n\n\n", "file_path": "kernel/mod_mgmt/src/lib.rs", "rank": 47, "score": 215070.55235773965 }, { "content": "pub trait FuncWithRegisters = Fn(Registers) -> Result<(), &'static str>;\n", "file_path": "kernel/unwind/src/lib.rs", "rank": 48, "score": 214909.94115740582 }, { "content": "/// Sets the counter bit to indicate it is available\n\nfn free_counter(core_id: u8, counter: u8) {\n\n let pmcs = get_pmcs_available_for_core(core_id).expect(\"Trying to free a PMU counter when the PMU is not initialized\");\n\n\n\n pmcs.fetch_update(\n\n Ordering::SeqCst,\n\n Ordering::SeqCst,\n\n |mut x| {\n\n if !x.get_bit(counter as usize) {\n\n x.set_bit(counter as usize, true);\n\n Some(x)\n\n }\n\n else {\n\n None\n\n }\n\n }\n\n ).unwrap_or_else(|x| { \n\n warn!(\"The counter you are trying to free has been previously freed\"); \n\n x\n\n });\n\n}\n\n\n", "file_path": "kernel/pmu_x86/src/lib.rs", "rank": 49, "score": 214537.12292785806 }, { "content": "/// Returns an iterator over all initialized storage controllers on this system.\n\n/// \n\n/// This function requires allocation, as it currently clones the list of storage controllers,\\\n\n/// effectively a `Vec<Arc<StorageController>>`.\n\npub fn storage_controllers() -> impl Iterator<Item = StorageControllerRef> {\n\n STORAGE_CONTROLLERS.lock().clone().into_iter()\n\n}\n\n\n", "file_path": "kernel/storage_manager/src/lib.rs", "rank": 50, "score": 213671.99643242834 }, { "content": "/// Returns an iterator over all storage devices attached to the storage controllers on this system.\n\n///\n\n/// This function requires allocation, as it currently clones the list of storage devices (lazily)\n\n/// within each storage controller, effectively a `Vec<Arc<Vec<Arc<StorageDevice>>>>`.\n\npub fn storage_devices() -> impl Iterator<Item = StorageDeviceRef> {\n\n storage_controllers()\n\n .flat_map(|c| c.lock()\n\n .devices()\n\n .collect::<Vec<StorageDeviceRef>>()\n\n .into_iter()\n\n )\n\n}\n\n\n\n\n", "file_path": "kernel/storage_manager/src/lib.rs", "rank": 51, "score": 213671.99643242834 }, { "content": "/// Insert a new stack that was allocated for the AP with the given `apic_id`.\n\npub fn insert_ap_stack(apic_id: u8, stack: Stack) {\n\n AP_STACKS.lock().insert(apic_id, stack);\n\n}\n\n\n\n\n", "file_path": "kernel/ap_start/src/lib.rs", "rank": 52, "score": 212949.67356419962 }, { "content": "/// Wait a certain number of microseconds, max 55555 microseconds.\n\n/// Uses a separate PIT clock channel, so it doesn't affect the regular PIT interrupts on PIT channel 0.\n\npub fn pit_wait(microseconds: u32) -> Result<(), &'static str> {\n\n let divisor = PIT_DEFAULT_DIVIDEND_HZ / (1000000/microseconds); \n\n if divisor > (u16::max_value() as u32) {\n\n error!(\"pit_wait(): the chosen wait time {}us is too large, max value is {}!\", microseconds, 1000000/PIT_MINIMUM_FREQ);\n\n return Err(\"microsecond value was too large\");\n\n }\n\n\n\n // SAFE because we're simply configuring the PIT clock, and the code below is correct.\n\n unsafe {\n\n use x86_64::instructions::port::{inb, outb};\n\n // see code example: https://wiki.osdev.org/APIC_timer\n\n let port_61_val = inb(0x61); \n\n outb(0x61, port_61_val & 0xFD | 0x1); // sets the speaker channel 2 to be controlled by PIT hardware\n\n PIT_COMMAND.lock().write(0b10110010); // channel 2, access mode: lobyte/hibyte, hardware-retriggerable one shot mode, 16-bit binary (not BCD)\n\n\n\n // set frequency; must write the low byte first and then the high byte\n\n PIT_CHANNEL_2.lock().write(divisor as u8);\n\n inb(0x60); //xread from PS/2 port 0x60, i.e., a short delay + acknowledging status register\n\n PIT_CHANNEL_2.lock().write((divisor >> 8) as u8);\n\n \n", "file_path": "kernel/pit_clock/src/lib.rs", "rank": 53, "score": 212136.9687161438 }, { "content": "/// return a Mouse Event according to the data\n\npub fn handle_mouse_input(readdata: u32) -> Result<(), &'static str> {\n\n let action = unsafe { &mut BUTTON_ACT };\n\n let mmove = unsafe { &mut MOUSE_MOVE };\n\n let dis = unsafe { &mut DISPLACEMENT };\n\n\n\n mmove.read_from_data(readdata);\n\n action.read_from_data(readdata);\n\n dis.read_from_data(readdata);\n\n\n\n let mouse_event = MouseEvent::new(*action, *mmove, *dis);\n\n // mouse_to_print(&mouse_event); // use this to debug\n\n let event = Event::MouseMovementEvent(mouse_event);\n\n\n\n if let Some(producer) = MOUSE_PRODUCER.get() {\n\n producer.push(event).map_err(|_e| \"Fail to enqueue the mouse event\")\n\n } else {\n\n warn!(\"handle_keyboard_input(): MOUSE_PRODUCER wasn't yet initialized, dropping keyboard event {:?}.\", event);\n\n Err(\"keyboard event queue not ready\")\n\n }\n\n}\n", "file_path": "kernel/mouse/src/lib.rs", "rank": 54, "score": 212131.84628012672 }, { "content": "/// set the mouse ID (3 or 4 ) by magic sequence\n\n/// 3 means that the mouse has scroll\n\n/// 4 means that the mouse has scroll, fourth and fifth buttons\n\npub fn set_mouse_id(id: u8) -> Result<(), &'static str> {\n\n // stop the mouse's streaming before trying to set the ID\n\n // if fail to stop the streaming, return error\n\n if let Err(_e) = mouse_packet_streaming(false) {\n\n warn!(\"fail to stop streaming, before trying to read mouse id\");\n\n return Err(\"fail to set the mouse id!!!\");\n\n } else {\n\n // set the id to 3\n\n if id == 3 {\n\n if let Err(_e) = set_sampling_rate(200) {\n\n warn!(\"fail to stop streaming, before trying to read mouse id\");\n\n return Err(\"fail to set the mouse id!!!\");\n\n }\n\n if let Err(_e) = set_sampling_rate(100) {\n\n warn!(\"fail to stop streaming, before trying to read mouse id\");\n\n return Err(\"fail to set the mouse id!!!\");\n\n }\n\n if let Err(_e) = set_sampling_rate(80) {\n\n warn!(\"fail to stop streaming, before trying to read mouse id\");\n\n return Err(\"fail to set the mouse id!!!\");\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 55, "score": 211484.19743349962 }, { "content": "/// Flushes the whole TLB. \n\npub fn tlb_flush_all() {\n\n tlb::flush_all();\n\n}\n\n\n", "file_path": "kernel/memory_x86_64/src/lib.rs", "rank": 56, "score": 211436.51613081846 }, { "content": "//write a u8 to the CMOS port (0x70)\n\nfn write_cmos(value: u8) {\n\n unsafe{\n\n CMOS_WRITE.lock().write(value)\n\n }\n\n}\n\n\n\n\n", "file_path": "kernel/rtc/src/lib.rs", "rank": 57, "score": 210625.51666162655 }, { "content": "//write a u8 to the CMOS port (0x70)\n\nfn write_cmos(value: u8){\n\n\n\n unsafe{CMOS_WRITE.lock().write(value)}\n\n\n\n}\n\n\n\n\n", "file_path": "kernel/interrupts/src/rtc.rs", "rank": 58, "score": 210625.51666162655 }, { "content": "/// This defines the priority scheduler policy.\n\n/// Returns None if there is no schedule-able task.\n\npub fn select_next_task(apic_id: u8) -> Option<TaskRef> {\n\n let priority_taskref_with_result = select_next_task_priority(apic_id); \n\n match priority_taskref_with_result {\n\n // A task has been selected\n\n Some(task) => {\n\n // If the selected task is idle task we begin a new scheduling epoch\n\n if task.idle_task == true {\n\n assign_tokens(apic_id);\n\n select_next_task_priority(apic_id).and_then(|m| m.taskref)\n\n }\n\n // If the selected task is not idle we return the taskref\n\n else {\n\n task.taskref\n\n }\n\n }\n\n\n\n // If no task is picked we pick a new scheduling epoch\n\n None => {\n\n assign_tokens(apic_id);\n\n select_next_task_priority(apic_id).and_then(|m| m.taskref)\n\n }\n\n }\n\n}\n\n\n", "file_path": "kernel/scheduler_priority/src/lib.rs", "rank": 59, "score": 210264.35361309134 }, { "content": "/// Returns an iterator that iterates over all `PciDevice`s, in no particular guaranteed order. \n\n/// If the PCI bus hasn't been initialized, this initializes the PCI bus & scans it to enumerates devices.\n\npub fn pci_device_iter() -> impl Iterator<Item = &'static PciDevice> {\n\n get_pci_buses().iter().flat_map(|b| b.devices.iter())\n\n}\n\n\n\n\n\n/// A PCI bus, which contains a list of PCI devices on that bus.\n\n#[derive(Debug)]\n\npub struct PciBus {\n\n /// The number identifier of this PCI bus.\n\n pub bus_number: u16,\n\n /// The list of devices attached to this PCI bus.\n\n pub devices: Vec<PciDevice>,\n\n}\n\n\n\n\n", "file_path": "kernel/pci/src/lib.rs", "rank": 60, "score": 209367.3956101477 }, { "content": "/// Returns a reference to the list of IoApics.\n\npub fn get_ioapics() -> &'static AtomicMap<u8, Mutex<IoApic>> {\n\n\t&IOAPICS\n\n}\n\n\n", "file_path": "kernel/ioapic/src/lib.rs", "rank": 61, "score": 208671.9889845355 }, { "content": "/// For swapping of a crate from the identical object file in the disk. \n\n/// Wraps arpund the crate_swap function by creating an appropriate Swap request. \n\n/// Arguments identical to the ones of crate_swap except\n\n/// namespace : Arc to the current namespace\n\n/// Returns a `SwapRanges` struct indicating the old and new `VirtualAddress` range\n\n/// of the swapped crate\n\npub fn do_self_swap(\n\n crate_name : &str, \n\n curr_dir: &DirRef, \n\n override_namespace_crate_dir: Option<NamespaceDir>, \n\n state_transfer_functions: Vec<String>,\n\n namespace: &Arc<CrateNamespace>,\n\n verbose_log: bool\n\n) -> Result<SwapRanges, String> {\n\n\n\n let kernel_mmi_ref = memory::get_kernel_mmi_ref().ok_or_else(|| \"couldn't get kernel_mmi_ref\".to_string())?;\n\n\n\n // Create swap request\n\n let swap_requests = {\n\n let mut requests: Vec<SwapRequest> = Vec::with_capacity(1);\n\n // Check that the new crate file exists. It could be a regular path, or a prefix for a file in the namespace's dir.\n\n // If it's a full path, then we just check that the path points to a valid crate object file. \n\n // Otherwise, we treat it as a prefix for a crate object file name that may be found \n\n let (into_new_crate_file, new_namespace) = {\n\n if let Some(f) = override_namespace_crate_dir.as_ref().and_then(|ns_dir| ns_dir.get_file_starting_with(crate_name)) {\n\n (IntoCrateObjectFile::File(f), None)\n", "file_path": "kernel/fault_crate_swap/src/lib.rs", "rank": 62, "score": 207950.12014469306 }, { "content": "/// A temporary hack to allow the serial port interrupt handler\n\n/// to inform a listener on the other end of this channel\n\n/// that a new connection has been detected on one of the serial ports,\n\n/// i.e., that it received some data on a serial port that \n\n/// didn't expect it or wasn't yet set up to handle incoming data.\n\npub fn set_connection_listener(\n\n sender: Sender<SerialPortAddress>\n\n) -> &'static Sender<SerialPortAddress> {\n\n NEW_CONNECTION_NOTIFIER.call_once(|| sender)\n\n}\n\nstatic NEW_CONNECTION_NOTIFIER: Once<Sender<SerialPortAddress>> = Once::new();\n\n\n\n\n\n// Serial ports cannot be reliably probed (discovered dynamically), thus,\n\n// we ensure they are exposed safely as singletons through the below static instances.\n\nstatic COM1_SERIAL_PORT: Once<Arc<MutexIrqSafe<SerialPort>>> = Once::new();\n\nstatic COM2_SERIAL_PORT: Once<Arc<MutexIrqSafe<SerialPort>>> = Once::new();\n\nstatic COM3_SERIAL_PORT: Once<Arc<MutexIrqSafe<SerialPort>>> = Once::new();\n\nstatic COM4_SERIAL_PORT: Once<Arc<MutexIrqSafe<SerialPort>>> = Once::new();\n\n\n\n\n", "file_path": "kernel/serial_port/src/lib.rs", "rank": 63, "score": 207885.9425611099 }, { "content": "/// Finds and returns the relevant addresses for the kernel image loaded into memory by the bootloader.\n\n///\n\n/// Returns the following tuple, if successful:\n\n/// * The kernel's starting physical address,\n\n/// * the kernel's ending physical address,\n\n/// * the kernel's ending virtual address.\n\npub fn get_kernel_address(\n\n boot_info: &BootInformation,\n\n) -> Result<(PhysicalAddress, PhysicalAddress, VirtualAddress), &'static str> {\n\n let elf_sections_tag = boot_info\n\n .elf_sections_tag()\n\n .ok_or(\"Elf sections tag not found\")?;\n\n\n\n // Our linker script specifies that the kernel will have the .init section starting at 1MB and ending at 1MB + .init size\n\n // and all other kernel sections will start at (KERNEL_OFFSET + 1MB) and end at (KERNEL_OFFSET + 1MB + size).\n\n // So, the start of the kernel is its physical address, but the end of it is its virtual address... confusing, I know\n\n // Thus, kernel_phys_start is the same as kernel_virt_start initially, but we remap them later in paging::init.\n\n let kernel_phys_start = PhysicalAddress::new(\n\n elf_sections_tag\n\n .sections()\n\n .filter(|s| s.is_allocated())\n\n .map(|s| s.start_address())\n\n .min()\n\n .ok_or(\"Couldn't find kernel start (phys) address\")? as usize,\n\n ).ok_or(\"kernel start physical address was invalid\")?;\n\n let kernel_virt_end = VirtualAddress::new(\n", "file_path": "kernel/memory_x86_64/src/lib.rs", "rank": 64, "score": 207830.62780634768 }, { "content": "fn num_general_purpose_counters() -> u8 {\n\n *NUM_PMC\n\n}\n\n\n", "file_path": "kernel/pmu_x86/src/lib.rs", "rank": 65, "score": 207710.70299302172 }, { "content": "/// This defines the round robin scheduler policy.\n\n/// Returns None if there is no schedule-able task\n\npub fn select_next_task(apic_id: u8) -> Option<TaskRef> {\n\n\n\n let mut runqueue_locked = match RunQueue::get_runqueue(apic_id) {\n\n Some(rq) => rq.write(),\n\n _ => {\n\n error!(\"BUG: select_next_task_round_robin(): couldn't get runqueue for core {}\", apic_id); \n\n return None;\n\n }\n\n };\n\n \n\n let mut idle_task_index: Option<usize> = None;\n\n let mut chosen_task_index: Option<usize> = None;\n\n\n\n for (i, t) in runqueue_locked.iter().enumerate() {\n\n // we skip the idle task, and only choose it if no other tasks are runnable\n\n if t.is_an_idle_task {\n\n idle_task_index = Some(i);\n\n continue;\n\n }\n\n\n", "file_path": "kernel/scheduler_round_robin/src/lib.rs", "rank": 66, "score": 207697.52370603755 }, { "content": "/// Adds the given destructor callback to the current task's list of\n\n/// TLS destructors that should be run when that task exits.\n\n/// \n\n/// # Arguments\n\n/// * `a`: the pointer to the object that will be destructed.\n\n/// * `dtor`: the function that should be invoked to destruct the object pointed to by `a`.\n\n/// When the current task exits, this function will be invoked with `a`\n\n/// as its only argument, at which point the `dtor` function should drop `a`.\n\n/// \n\n/// Currently the only value of `dtor` that is used is a type-specific monomorphized\n\n/// version of the above [`fast::destroy_value()`] function.\n\nfn register_dtor(object_ptr: *mut u8, dtor: unsafe extern \"C\" fn(*mut u8)) {\n\n TLS_DESTRUCTORS.borrow_mut().push(TlsObjectDestructor { object_ptr, dtor });\n\n}\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////////////////\n\n//// Everything below here is a modified version of thread_local!() from Rust std ////\n\n//////////////////////////////////////////////////////////////////////////////////////\n\n\n\nuse core::cell::{Cell, UnsafeCell};\n\nuse core::fmt;\n\n#[doc(hidden)]\n\npub use core::option;\n\nuse core::mem;\n\nuse core::hint;\n\nuse alloc::vec::Vec;\n\n\n\n/// A thread-local storage key which owns its contents.\n\n///\n\n/// This TLS object is instantiated the [`thread_local!`] macro and offers \n", "file_path": "kernel/thread_local_macro/src/lib.rs", "rank": 67, "score": 205475.124286137 }, { "content": "/// Gets the physical memory occupied by vga.\n\n/// \n\n/// Returns (start_physical_address, size, entryflags). \n\npub fn get_vga_mem_addr(\n\n) -> Result<(PhysicalAddress, usize, EntryFlags), &'static str> {\n\n const VGA_DISPLAY_PHYS_START: usize = 0xA_0000;\n\n const VGA_DISPLAY_PHYS_END: usize = 0xC_0000;\n\n let vga_size_in_bytes: usize = VGA_DISPLAY_PHYS_END - VGA_DISPLAY_PHYS_START;\n\n let vga_display_flags =\n\n EntryFlags::PRESENT | EntryFlags::WRITABLE | EntryFlags::GLOBAL | EntryFlags::NO_CACHE;\n\n\n\n Ok((\n\n PhysicalAddress::new(VGA_DISPLAY_PHYS_START).ok_or(\"invalid VGA starting physical address\")?,\n\n vga_size_in_bytes,\n\n vga_display_flags,\n\n ))\n\n}\n\n\n", "file_path": "kernel/memory_x86_64/src/lib.rs", "rank": 68, "score": 204408.12549369095 }, { "content": "/// Registers an interrupt handler. \n\n/// The function fails if the interrupt number is already in use. \n\n/// \n\n/// # Arguments \n\n/// * `interrupt_num` - the interrupt (IRQ vector) that is being requested.\n\n/// * `func` - the handler to be registered, which will be invoked when the interrupt occurs.\n\n/// \n\n/// # Return\n\n/// * `Ok(())` if successfully registered, or\n\n/// * `Err(existing_handler_address)` if the given `interrupt_num` was already in use.\n\npub fn register_interrupt(interrupt_num: u8, func: HandlerFunc) -> Result<(), u64> {\n\n let mut idt = IDT.lock();\n\n\n\n // If the existing handler stored in the IDT either missing (has an address of `0`)\n\n // or is the default handler, that signifies the interrupt number is available.\n\n let idt_entry = &mut idt[interrupt_num as usize];\n\n let existing_handler_addr = idt_entry.handler_address();\n\n if existing_handler_addr == 0 || existing_handler_addr == unimplemented_interrupt_handler as u64 {\n\n idt_entry.set_handler_fn(func);\n\n Ok(())\n\n } else {\n\n trace!(\"register_interrupt: the requested interrupt IRQ {} was already in use\", interrupt_num);\n\n Err(existing_handler_addr)\n\n }\n\n} \n\n\n", "file_path": "kernel/interrupts/src/lib.rs", "rank": 69, "score": 202087.34349655217 }, { "content": "/// Returns an interrupt number assigned by the OS and sets its handler function. \n\n/// The function fails if there is no unused interrupt number.\n\n/// \n\n/// # Arguments\n\n/// * `func` - the handler for the assigned interrupt number\n\npub fn register_msi_interrupt(func: HandlerFunc) -> Result<u8, &'static str> {\n\n let mut idt = IDT.lock();\n\n\n\n // try to find an unused interrupt \n\n let interrupt_num = (*idt).find_free_entry(unimplemented_interrupt_handler).ok_or(\"register_msi_interrupt: no available interrupt\")?;\n\n idt[interrupt_num].set_handler_fn(func);\n\n \n\n Ok(interrupt_num as u8)\n\n} \n\n\n", "file_path": "kernel/interrupts/src/lib.rs", "rank": 70, "score": 202081.669072826 }, { "content": "/// Gets the physical memory area occupied by the bootloader information.\n\npub fn get_boot_info_mem_area(\n\n boot_info: &BootInformation,\n\n) -> Result<(PhysicalAddress, PhysicalAddress), &'static str> {\n\n Ok((\n\n PhysicalAddress::new(boot_info.start_address() - KERNEL_OFFSET)\n\n .ok_or(\"boot info start physical address was invalid\")?,\n\n PhysicalAddress::new(boot_info.end_address() - KERNEL_OFFSET)\n\n .ok_or(\"boot info end physical address was invalid\")?,\n\n ))\n\n}\n\n\n\n\n", "file_path": "kernel/memory_x86_64/src/lib.rs", "rank": 71, "score": 201155.36631673924 }, { "content": "/// Parses the nano_core object file that represents the already loaded (and currently running) nano_core code.\n\n///\n\n/// Basically, just searches for global (public) symbols, which are added to the system map and the crate metadata.\n\n/// We consider both `GLOBAL` and `WEAK` symbols to be global public symbols; this is necessary because symbols that are \n\n/// compiler builtins, such as memset, memcpy, etc, are symbols with weak linkage in newer versions of Rust (2021 and later).\n\n/// \n\n/// # Return\n\n/// If successful, this returns a tuple of the following:\n\n/// * `nano_core_crate_ref`: A reference to the newly-created nano_core crate.\n\n/// * `init_symbols`: a map of symbol name to its constant value, which contains assembler and linker constances.\n\n/// * The number of new symbols added to the symbol map (a `usize`).\n\n/// \n\n/// If an error occurs, the returned `Result::Err` contains the passed-in `text_pages`, `rodata_pages`, and `data_pages`\n\n/// because those cannot be dropped, as they hold the currently-running code, and dropping them would cause endless exceptions.\n\npub fn parse_nano_core(\n\n namespace: &Arc<CrateNamespace>,\n\n text_pages: MappedPages, \n\n rodata_pages: MappedPages, \n\n data_pages: MappedPages, \n\n verbose_log: bool\n\n) -> Result<(StrongCrateRef, BTreeMap<String, usize>, usize), (&'static str, [Arc<Mutex<MappedPages>>; 3])> {\n\n\n\n let text_pages = Arc::new(Mutex::new(text_pages));\n\n let rodata_pages = Arc::new(Mutex::new(rodata_pages));\n\n let data_pages = Arc::new(Mutex::new(data_pages));\n\n\n\n let (nano_core_file, real_namespace) = try_mp!(\n\n CrateNamespace::get_crate_object_file_starting_with(namespace, NANO_CORE_FILENAME_PREFIX)\n\n .ok_or(\"couldn't find the expected \\\"nano_core\\\" kernel file\"),\n\n text_pages, rodata_pages, data_pages\n\n );\n\n let nano_core_file_path = Path::new(nano_core_file.lock().get_absolute_path());\n\n debug!(\"parse_nano_core: trying to load and parse the nano_core file: {:?}\", nano_core_file_path);\n\n\n", "file_path": "kernel/mod_mgmt/src/parse_nano_core.rs", "rank": 72, "score": 201004.94121227166 }, { "content": "/// Returns a reference to the list of LocalApics, one per processor core\n\npub fn get_lapics() -> &'static AtomicMap<u8, RwLockIrqSafe<LocalApic>> {\n\n\t&LOCAL_APICS\n\n}\n\n\n", "file_path": "kernel/apic/src/lib.rs", "rank": 73, "score": 200963.8259759803 }, { "content": "/// Returns the current top-level page table address.\n\npub fn get_p4() -> PhysicalAddress {\n\n PhysicalAddress::new_canonical(control_regs::cr3().0 as usize)\n\n}\n", "file_path": "kernel/memory_x86_64/src/lib.rs", "rank": 74, "score": 200329.36507150155 }, { "content": "/// Returns the current top-level (P4) root page table frame.\n\npub fn get_current_p4() -> Frame {\n\n Frame::containing_address(get_p4())\n\n}\n\n\n\n\n", "file_path": "kernel/memory/src/paging/mod.rs", "rank": 75, "score": 200171.9796695264 }, { "content": "/// convenience function for obtaining the ascii value for a raw scancode under the given modifiers\n\npub fn scancode_to_ascii(modifiers: KeyboardModifiers, scan_code: u8) -> Option<char> {\n\n\tKeycode::from_scancode(scan_code).and_then(|k| k.to_ascii(modifiers))\n\n}\n\n\n\n\n\n#[derive(Debug, PartialEq, Clone, Copy)]\n\npub enum Keycode {\n\n OverflowError = 0,\n\n Escape,\n\n Num1,\n\n Num2,\n\n Num3,\n\n Num4,\n\n Num5,\n\n Num6,\n\n Num7,\n\n Num8,\n\n Num9,\n\n Num0,\n\n Minus,\n", "file_path": "libs/keycodes_ascii/src/lib.rs", "rank": 76, "score": 199520.528952329 }, { "content": "/// This function should be called when there was a SIMD-enabled Task\n\n/// removed from the list of Tasks eligible to run on the given core. \n\n/// # Arguments\n\n/// `tasks_on_core` is an Iterator over all of the `TaskRef`s that \n\n/// are eligible to run on the given core `which_core`.\n\npub fn simd_tasks_removed_from_core<'t, I>(tasks_on_core: I, _which_core: u8) \n\n\twhere I: Iterator<Item = &'t TaskRef>\n\n{\n\n\tlet num_simd_tasks = &tasks_on_core\n\n\t\t.filter(|taskref| taskref.simd)\n\n\t\t.count();\n\n\twarn!(\"simd_tasks_removed_from_core(): core {} now has {} SIMD tasks total.\", \n\n\t\t_which_core, num_simd_tasks);\n\n\n\n\tmatch num_simd_tasks {\n\n\t\t0 => {\n\n\t\t\t// Here, we previously had one SIMD Task on this core, but now we have 0.\n\n\t\t\t// Thus, we don't need to do anything because there are no SIMD Tasks to do anything with.\n\n\t\t}\n\n\t\t1 => {\n\n\t\t\t// Here, we previously had 2 or more SIMD tasks, and now we have 1. \n\n\t\t\t// That means that those SIMD Tasks were all using the SIMD Context,\n\n\t\t\t// but now according to this crate's optimization,\n\n\t\t\t// we can now convert that Task to use non-SIMD context.\n\n\t\t\t// TODO FIXME: So, convert that one SIMD Task into a non-SIMD Context\n", "file_path": "kernel/single_simd_task_optimization/src/lib.rs", "rank": 77, "score": 199514.8391657722 }, { "content": "/// This function should be called when there was a new SIMD-enabled Task\n\n/// that was added to the list of Tasks eligible to run on the given core. \n\n/// # Arguments\n\n/// `tasks_on_core` is an Iterator over all of the `TaskRef`s that \n\n/// are eligible to run on the given core `which_core`.\n\npub fn simd_tasks_added_to_core<'t, I>(tasks_on_core: I, _which_core: u8) \n\n\twhere I: Iterator<Item = &'t TaskRef>\n\n{\n\n\tlet num_simd_tasks = &tasks_on_core\n\n\t\t.filter(|taskref| taskref.simd)\n\n\t\t.count();\n\n\twarn!(\"simd_tasks_added_to_core(): core {} now has {} SIMD tasks total.\", \n\n\t\t_which_core, num_simd_tasks);\n\n\n\n\tmatch num_simd_tasks {\n\n\t\t0 => {\n\n\t\t\terror!(\"BUG: simd_tasks_added_to_core(): there were no SIMD tasks on this core.\");\n\n\t\t}\n\n\t\t1 => {\n\n\t\t\t// Here, we previously had 0 SIMD tasks, and now we have 1. \n\n\t\t\t// TODO: So, convert that one SIMD Task into a non-SIMD Context\n\n\t\t\t// We have to do this conversion here because all SIMD Tasks start out\n\n\t\t\t// using the SIMD-enabled Context by default, just to ensure correcntess.\n\n\t\t}\n\n\t\t2 => {\n", "file_path": "kernel/single_simd_task_optimization/src/lib.rs", "rank": 78, "score": 199514.83916577217 }, { "content": "/// If an `IoApic` with the given `id` exists, then lock it (acquire its Mutex)\n\n/// and return the locked `IoApic`.\n\npub fn get_ioapic(ioapic_id: u8) -> Option<MutexGuard<'static, IoApic>> {\n\n\tIOAPICS.get(&ioapic_id).map(|ioapic| ioapic.lock())\n\n}\n\n\n", "file_path": "kernel/ioapic/src/lib.rs", "rank": 79, "score": 199514.83916577217 }, { "content": "/// enable or disable the packet streaming\n\n/// also return the vec of data previously in the buffer which may be useful\n\npub fn mouse_packet_streaming(enable: bool) -> Result<Vec<u8>, &'static str> {\n\n if enable {\n\n if let Err(_e) = command_to_mouse(0xf4) {\n\n warn!(\"enable streaming failed\");\n\n Err(\"enable mouse streaming failed\")\n\n } else {\n\n // info!(\"enable streaming succeeded!!\");\n\n Ok(Vec::new())\n\n }\n\n }\n\n else {\n\n let mut buffer_data = Vec::new();\n\n if data_to_port2(0xf5) != 0xfa {\n\n for x in 0..15 {\n\n if x == 14 {\n\n warn!(\"disable mouse streaming failed\");\n\n return Err(\"disable mouse streaming failed\");\n\n }\n\n let response = ps2_read_data();\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 80, "score": 198508.08789557454 }, { "content": "/// Changes the priority of the given task with the given priority level.\n\n/// Priority values must be between 40 (maximum priority) and 0 (minimum prriority).\n\n/// This function returns an error when a scheduler without priority is loaded. \n\npub fn set_priority(_task: &TaskRef, _priority: u8) -> Result<(), &'static str> {\n\n #[cfg(priority_scheduler)] {\n\n scheduler_priority::set_priority(_task, _priority)\n\n }\n\n #[cfg(not(priority_scheduler))] {\n\n Err(\"no scheduler that uses task priority is currently loaded\")\n\n }\n\n}\n\n\n", "file_path": "kernel/scheduler/src/lib.rs", "rank": 81, "score": 198507.7923663223 }, { "content": "/// Convenience function for converting a byte stream\n\n/// that is delimited by newlines into a list of Strings.\n\npub fn as_lines(bytes: &[u8]) -> Result<Vec<String>, &'static str> {\n\n str::from_utf8(bytes)\n\n .map_err(|_e| \"couldn't convert file into a UTF8 string\")\n\n .map(|files| files.lines().map(|s| String::from(s)).collect())\n\n}\n\n\n\n\n\n/// A representation of an diff file used to define an evolutionary crate swapping update.\n\npub struct Diff {\n\n /// A list of tuples in which the first element is the old crate and the second element is the new crate.\n\n /// If the first element is the empty string, the second element is a new addition (replacing nothing),\n\n /// and if the second element is the empty string, the first element is to be removed without replacement.\n\n pub pairs: Vec<(String, String)>,\n\n /// The list of state transfer functions which should be applied at the end of a crate swapping operation.\n\n pub state_transfer_functions: Vec<String>,\n\n}\n\n\n\n\n", "file_path": "kernel/ota_update_client/src/lib.rs", "rank": 82, "score": 198502.6827001534 }, { "content": "/// Clears the counter bit to show it's in use\n\nfn claim_counter(core_id: u8, counter: u8) -> Result<(), &'static str> {\n\n let pmcs = get_pmcs_available_for_core(core_id)?;\n\n\n\n pmcs.fetch_update(\n\n Ordering::SeqCst,\n\n Ordering::SeqCst,\n\n |mut x| {\n\n if x.get_bit(counter as usize) {\n\n x.set_bit(counter as usize, false);\n\n Some(x)\n\n }\n\n else {\n\n None\n\n }\n\n }\n\n ).map_err(|_e| \"pmu_x86: Could not claim counter because it is already in use\")?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "kernel/pmu_x86/src/lib.rs", "rank": 83, "score": 198445.5257103109 }, { "content": "/// Returns the `RunQueue` of the given core, which is an `apic_id`.\n\npub fn get_runqueue(which_core: u8) -> Option<&'static RwLockIrqSafe<RunQueue>>{\n\n RunQueue::get_runqueue(which_core)\n\n}\n\n\n", "file_path": "kernel/runqueue/src/lib.rs", "rank": 84, "score": 197058.82601537902 }, { "content": "/// the log base 2 of an integer value\n\npub fn log2(value: usize) -> usize {\n\n let mut v = value;\n\n let mut result = 0;\n\n v >>= 1;\n\n while v > 0 {\n\n result += 1;\n\n v >>= 1;\n\n }\n\n\n\n result\n\n}\n\n\n\n\n", "file_path": "libs/util/src/lib.rs", "rank": 85, "score": 196912.53281618864 }, { "content": "/// Changes the priority of the given task with the given priority level.\n\n/// Priority values must be between 40 (maximum priority) and 0 (minimum prriority).\n\npub fn set_priority(task: &TaskRef, priority: u8) -> Result<(), &'static str> {\n\n let priority = core::cmp::min(priority, MAX_PRIORITY);\n\n RunQueue::set_priority(task, priority)\n\n}\n\n\n", "file_path": "kernel/scheduler_priority/src/lib.rs", "rank": 86, "score": 195941.2855774645 }, { "content": "/// returns Ok(()) if everything was handled properly.\n\n/// Otherwise, returns an error string.\n\npub fn handle_keyboard_input(scan_code: u8, extended: bool) -> Result<(), &'static str> {\n\n // SAFE: no real race conditions with keyboard presses\n\n let modifiers = unsafe { &mut KBD_MODIFIERS };\n\n // debug!(\"KBD_MODIFIERS before {}: {:?}\", scan_code, modifiers);\n\n\n\n // first, update the modifier keys\n\n match scan_code {\n\n x if x == Keycode::Control as u8 => { \n\n modifiers.insert(if extended { KeyboardModifiers::CONTROL_RIGHT } else { KeyboardModifiers::CONTROL_LEFT});\n\n }\n\n x if x == Keycode::Alt as u8 => { modifiers.insert(KeyboardModifiers::ALT); }\n\n x if x == Keycode::LeftShift as u8 => { modifiers.insert(KeyboardModifiers::SHIFT_LEFT); }\n\n x if x == Keycode::RightShift as u8 => { modifiers.insert(KeyboardModifiers::SHIFT_RIGHT); }\n\n x if x == Keycode::SuperKeyLeft as u8 => { modifiers.insert(KeyboardModifiers::SUPER_KEY_LEFT); }\n\n x if x == Keycode::SuperKeyRight as u8 => { modifiers.insert(KeyboardModifiers::SUPER_KEY_RIGHT); }\n\n\n\n x if x == Keycode::Control as u8 + KEY_RELEASED_OFFSET => {\n\n modifiers.remove(if extended { KeyboardModifiers::CONTROL_RIGHT } else { KeyboardModifiers::CONTROL_LEFT});\n\n }\n\n x if x == Keycode::Alt as u8 + KEY_RELEASED_OFFSET => { modifiers.remove(KeyboardModifiers::ALT); }\n", "file_path": "kernel/keyboard/src/lib.rs", "rank": 87, "score": 195935.85279309965 }, { "content": "/// Spawns an idle task on the given `core` if specified, otherwise on the current core. \n\n/// Then, it adds adds the new idle task to that core's runqueue.\n\npub fn create_idle_task(core: Option<u8>) -> Result<TaskRef, &'static str> {\n\n let apic_id = core.unwrap_or_else(|| get_my_apic_id());\n\n debug!(\"Spawning a new idle task on core {}\", apic_id);\n\n\n\n new_task_builder(dummy_idle_task, apic_id)\n\n .name(format!(\"idle_task_core_{}\", apic_id))\n\n .idle(apic_id)\n\n .spawn_restartable()\n\n}\n\n\n\n/// Dummy `idle_task` to be used if original `idle_task` crashes.\n\n/// \n\n/// Note: the current spawn API does not support spawning a task with the return type `!`,\n\n/// so we use `()` here instead. \n", "file_path": "kernel/spawn/src/lib.rs", "rank": 88, "score": 195935.85279309962 }, { "content": "/// Returns an interrupt to the system by setting the handler to the default function. \n\n/// The application provides the current interrupt handler as a safety check. \n\n/// The function fails if the current handler and 'func' do not match\n\n/// \n\n/// # Arguments\n\n/// * `interrupt_num` - the interrupt that needs to be deregistered\n\n/// * `func` - the handler that should currently be stored for 'interrupt_num'\n\npub fn deregister_interrupt(interrupt_num: u8, func: HandlerFunc) -> Result<(), &'static str> {\n\n let mut idt = IDT.lock();\n\n\n\n // check if the handler stored is the same as the one provided\n\n // this is to make sure no other application can deregister your interrupt\n\n if idt[interrupt_num as usize].handler_eq(func) {\n\n idt[interrupt_num as usize].set_handler_fn(unimplemented_interrupt_handler);\n\n Ok(())\n\n }\n\n else {\n\n error!(\"deregister_interrupt: Cannot free interrupt due to incorrect handler function\");\n\n Err(\"deregister_interrupt: Cannot free interrupt due to incorrect handler function\")\n\n }\n\n}\n\n\n", "file_path": "kernel/interrupts/src/lib.rs", "rank": 89, "score": 195935.85279309965 }, { "content": "#[inline(never)]\n\npub fn stack_trace_using_frame_pointers(\n\n current_page_table: &PageTable,\n\n on_each_stack_frame: &mut dyn FnMut(usize, VirtualAddress) -> bool,\n\n max_recursion: Option<usize>,\n\n) -> Result<(), &'static str> {\n\n\n\n let mut rbp: usize;\n\n // SAFE: just reading current register value\n\n unsafe {\n\n llvm_asm!(\"\" : \"={rbp}\"(rbp) : : \"memory\" : \"intel\", \"volatile\");\n\n }\n\n\n\n for _i in 0 .. max_recursion.unwrap_or(64) {\n\n // the stack contains the return address (of the caller) right before the current frame pointer\n\n if let Some(rip_ptr) = rbp.checked_add(core::mem::size_of::<usize>()) {\n\n if let (Ok(rbp_vaddr), Ok(rip_ptr)) = (VirtualAddress::new(rbp), VirtualAddress::new(rip_ptr)) {\n\n if current_page_table.translate(rbp_vaddr).is_some() && current_page_table.translate(rip_ptr).is_some() {\n\n // SAFE: the address was checked above using page table walks\n\n let rip = unsafe { *(rip_ptr.value() as *const usize) };\n\n if rip == 0 {\n", "file_path": "kernel/stack_trace_frame_pointers/src/lib.rs", "rank": 90, "score": 195215.01056976477 }, { "content": "/// See the module-level documentation for how this works. \n\n/// \n\n/// # Current Limitations\n\n/// Currently, this does not actually rewrite the existing sections in the nano_core itself\n\n/// to redirect them to depend on the newly-loaded crate instances. \n\n/// All it can do is replace the existing nano_core\n\n/// This is a limitation that we're working to overcome, and is difficult because we need\n\n/// to obtain a list of all linker relocations that were performed by the static linker\n\n/// such that we can properly rewrite the existing dependencies. \n\n/// For simple relocations like RX86_64_64 where the value is just an absolute address,\n\n/// it would be straightforward to simply scan the nano_core's `kernel.bin` binary file \n\n/// for each section's virtual address in order to derive/recover the relocations and dependencies between sections,\n\n/// but it's not always that simple for other relocation types.\n\n/// Perhaps we can ask the linker to emit a list of relocations it performs and then provide \n\n/// that list as input into this function so that it doesn't have to guess when deriving relocations.\n\npub fn replace_nano_core_crates(\n\n namespace: &Arc<CrateNamespace>,\n\n nano_core_crate_ref: StrongCrateRef,\n\n kernel_mmi_ref: &MmiRef,\n\n) -> Result<(), &'static str> {\n\n let nano_core_crate = nano_core_crate_ref.lock_as_ref();\n\n\n\n let mut constituent_crates = BTreeSet::new();\n\n for sec in nano_core_crate.global_sections_iter() {\n\n for n in super::get_containing_crate_name(&sec.name) {\n\n constituent_crates.insert(String::from(n));\n\n }\n\n }\n\n\n\n // For now we just replace the \"memory\" crate. \n\n // More crates can be added later, up to every `constituent_crate` in the nano_core.\n\n let (crate_object_file, _ns) = CrateNamespace::get_crate_object_file_starting_with(namespace, \"memory-\")\n\n .ok_or(\"Failed to find \\\"memory-\\\" crate\")?;\n\n\n\n let _new_crate_ref = load_crate_using_nano_core_data_sections(\n", "file_path": "kernel/mod_mgmt/src/replace_nano_core_crates.rs", "rank": 91, "score": 194967.96095284703 }, { "content": "/// Returns true if the counter is not in use\n\nfn counter_is_available(core_id: u8, counter: u8) -> Result<bool, &'static str> {\n\n let pmcs = get_pmcs_available_for_core(core_id)?;\n\n Ok(pmcs.load(Ordering::SeqCst).get_bit(counter as usize))\n\n}\n\n\n", "file_path": "kernel/pmu_x86/src/lib.rs", "rank": 92, "score": 193664.36327550298 }, { "content": "/// Adds the given `Task` reference to given core's runqueue.\n\npub fn add_task_to_specific_runqueue(which_core: u8, task: TaskRef) -> Result<(), &'static str>{\n\n RunQueue::add_task_to_specific_runqueue(which_core, task)\n\n}\n\n\n", "file_path": "kernel/runqueue/src/lib.rs", "rank": 93, "score": 193479.83964270644 }, { "content": "/// Initialization function that enables the PMU if one is available.\n\n/// We initialize the 3 fixed PMCs and general purpose PMCs. Calling this initialization function again\n\n/// on a core that has already been initialized will do nothing.\n\n/// \n\n/// Currently we support a maximum core ID of 255, and up to 8 general purpose counters per core. \n\n/// A core ID greater than 255 is not supported in Theseus in general since the ID has to fit within a u8.\n\n/// \n\n/// If the core ID limit is changed and we need to update the PMU data structures to support more cores then: \n\n/// - Increase WORDS_IN_BITMAP and CORES_SUPPORTED_BY_PMU as required. For example, the cores supported is 256 so there are 4 64-bit words in the bitmap, one bit per core. \n\n/// - Add additional AtomicU64 variables to the initialization of the CORES_SAMPLING and RESULTS_READY bitmaps. \n\n/// \n\n/// If the general purpose PMC limit is reached then: \n\n/// - Update PMCS_SUPPORTED_BY_PMU to the new PMC limit.\n\n/// - Change the element type in the PMCS_AVAILABLE vector to be larger than AtomicU8 so that there is one bit per counter.\n\n/// - Update INIT_PMCS_AVAILABLE to the new maximum value for the per core bitmap.\n\n/// \n\n/// # Warning\n\n/// This function should only be called after all the cores have been booted up.\n\npub fn init() -> Result<(), &'static str> {\n\n let mut cores_initialized = CORES_INITIALIZED.lock();\n\n let core_id = apic::get_my_apic_id();\n\n\n\n if cores_initialized.contains(&core_id) {\n\n warn!(\"PMU has already been intitialized on core {}\", core_id);\n\n return Ok(());\n\n } \n\n else {\n\n\n\n if *PMU_VERSION >= MIN_PMU_VERSION {\n\n \n\n if greater_core_id_than_expected()? {\n\n return Err(\"pmu_x86: There are larger core ids in this machine than can be handled by the existing structures which store information about the PMU\");\n\n }\n\n\n\n if more_pmcs_than_expected(*NUM_PMC)? {\n\n return Err(\"pmu_x86: There are more general purpose PMCs in this machine than can be handled by the existing structures which store information about the PMU\");\n\n }\n\n\n", "file_path": "kernel/pmu_x86/src/lib.rs", "rank": 94, "score": 193405.04054269788 }, { "content": "fn sampling_results_are_ready(core_id: u8) -> bool {\n\n let (word_num, bit_in_word) = find_word_and_offset_from_bit(core_id);\n\n RESULTS_READY[word_num].load(Ordering::SeqCst).get_bit(bit_in_word)\n\n}\n\n\n", "file_path": "kernel/pmu_x86/src/lib.rs", "rank": 95, "score": 193312.57370200235 }, { "content": "fn core_is_currently_sampling(core_id: u8) -> bool {\n\n let (word_num, bit_in_word) = find_word_and_offset_from_bit(core_id);\n\n CORES_SAMPLING[word_num].load(Ordering::SeqCst).get_bit(bit_in_word)\n\n}\n\n\n", "file_path": "kernel/pmu_x86/src/lib.rs", "rank": 96, "score": 193312.57370200235 }, { "content": "/// An early logger that can only write to a fixed number of [`SerialPort`]s,\n\n/// intended for basic use before dynamic heap allocation is available.\n\nstruct EarlyLogger<const N: usize>([Option<SerialPort>; N]);\n\n\n", "file_path": "kernel/logger/src/lib.rs", "rank": 97, "score": 190434.85407748094 }, { "content": "/// Simple function to print values from SampleResults in a form that the script \"post-mortem pmu analysis.py\" can parse. \n\npub fn print_samples(sample_results: &SampleResults) {\n\n debug!(\"Printing Samples:\");\n\n for results in sample_results.instruction_pointers.iter().zip(sample_results.task_ids.iter()) {\n\n debug!(\"{:x} {}\", results.0, results.1);\n\n }\n\n}\n\n\n", "file_path": "kernel/pmu_x86/src/lib.rs", "rank": 98, "score": 190338.22972016706 }, { "content": "/// Returns the top-level directory that contains all of the namespaces. \n\npub fn get_namespaces_directory() -> Option<DirRef> {\n\n root::get_root().lock().get_dir(NAMESPACES_DIRECTORY_NAME)\n\n}\n\n\n\nlazy_static! {\n\n /// The thread-local storage (TLS) area \"image\" that is used as the initial data for each `Task`.\n\n /// When spawning a new task, the new task will create its own local TLS area\n\n /// with this `TlsInitializer` as the initial data values.\n\n /// \n\n /// # Implementation Notes/Shortcomings\n\n /// Currently, a single system-wide `TlsInitializer` instance is shared across all namespaces.\n\n /// In the future, each namespace should hold its own TLS sections in its TlsInitializer area.\n\n /// \n\n /// However, this is quite complex because each namespace must be aware of the TLS sections\n\n /// in BOTH its underlying recursive namespace AND its (multiple) \"parent\" namespace(s)\n\n /// that recursively depend on it, since no two TLS sections can conflict (have the same offset).\n\n /// \n\n /// Thus, we stick with a singleton `TlsInitializer` instance, which makes sense \n\n /// because it behaves much like an allocator, in that it reserves space (index ranges) in the TLS area.\n\n static ref TLS_INITIALIZER: Mutex<TlsInitializer> = Mutex::new(TlsInitializer::empty());\n\n}\n\n\n\n\n", "file_path": "kernel/mod_mgmt/src/lib.rs", "rank": 99, "score": 190183.0770091606 } ]
Rust
src/app.rs
iamcodemaker/euca
00387b2e368231a3e0e25ebe0e63b951231cf61f
pub mod detach; pub mod model; pub mod dispatch; pub mod side_effect; pub mod application; pub use crate::app::detach::Detach; pub use crate::app::model::{Update, Render}; pub use crate::app::dispatch::Dispatcher; pub use crate::app::side_effect::{SideEffect, Processor, Commands}; pub use crate::app::application::{Application, ScheduledRender}; use web_sys; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use std::rc::Rc; use std::cell::RefCell; use std::fmt; use std::hash::Hash; use crate::diff; use crate::vdom::DomIter; use crate::vdom::Storage; use crate::vdom::WebItem; use crate::route::Route; pub struct AppBuilder<Message, Command, Processor, Router> where Command: SideEffect<Message>, Processor: side_effect::Processor<Message, Command>, Router: Route<Message>, { router: Option<Rc<Router>>, processor: Processor, clear_parent: bool, message: std::marker::PhantomData<Message>, command: std::marker::PhantomData<Command>, } impl<Message, Command> Default for AppBuilder< Message, Command, side_effect::DefaultProcessor<Message, Command>, (), > where Command: SideEffect<Message>, { fn default() -> Self { AppBuilder { router: None, processor: side_effect::DefaultProcessor::default(), clear_parent: false, message: std::marker::PhantomData, command: std::marker::PhantomData, } } } impl<Message, Command, Processor, Router> AppBuilder<Message, Command, Processor, Router> where Command: SideEffect<Message> + 'static, Processor: side_effect::Processor<Message, Command> + 'static, Router: Route<Message> + 'static, { #[must_use] pub fn router<R: Route<Message>>(self, router: R) -> AppBuilder<Message, Command, Processor, R> { let AppBuilder { message, command, processor, clear_parent, router: _router, } = self; AppBuilder { message: message, command: command, processor, clear_parent: clear_parent, router: Some(Rc::new(router)), } } #[must_use] pub(crate) fn processor<P: side_effect::Processor<Message, Command>>(self, processor: P) -> AppBuilder<Message, Command, P, Router> { let AppBuilder { message, command, router, clear_parent, processor: _processor, } = self; AppBuilder { message: message, command: command, processor: processor, router: router, clear_parent: clear_parent, } } #[must_use] pub fn clear(mut self) -> Self { self.clear_parent = true; self } #[must_use] pub(crate) fn create<Model, DomTree, Key>(self, mut model: Model) -> (Rc<RefCell<Box<dyn Application<Message, Command>>>>, Vec<web_sys::Node>) where Model: Update<Message, Command> + Render<DomTree> + 'static, DomTree: DomIter<Message, Command, Key> + 'static, Message: fmt::Debug + Clone + PartialEq + 'static, Command: SideEffect<Message> + fmt::Debug + 'static, Key: Eq + Hash + 'static, { let AppBuilder { router, processor, .. } = self; let mut commands = Commands::default(); if let Some(ref router) = router { let url = web_sys::window() .expect("window") .document() .expect("document") .url() .expect("url"); if let Some(msg) = router.route(&url) { model.update(msg, &mut commands); } } let (app_rc, nodes) = App::create(model, processor); let dispatcher = Dispatcher::from(&app_rc); if let Some(ref router) = router { let window = web_sys::window() .expect("couldn't get window handle"); let document = window.document() .expect("couldn't get document handle"); for event in ["popstate", "hashchange"].iter() { let dispatcher = dispatcher.clone(); let document = document.clone(); let router = router.clone(); let closure = Closure::wrap( Box::new(move |_event| { let url = document.url() .expect_throw("couldn't get document url"); if let Some(msg) = router.route(&url) { dispatcher.dispatch(msg); } }) as Box<dyn FnMut(web_sys::Event)> ); window .add_event_listener_with_callback(event, closure.as_ref().unchecked_ref()) .expect("failed to add event listener"); app_rc.borrow_mut().push_listener((event.to_string(), closure)); } for cmd in commands.immediate { app_rc.borrow().process(cmd, &dispatcher); } for cmd in commands.post_render { app_rc.borrow().process(cmd, &dispatcher); } } (app_rc, nodes) } pub fn attach<Model, DomTree, Key>(self, parent: web_sys::Element, model: Model) -> Rc<RefCell<Box<dyn Application<Message, Command>>>> where Model: Update<Message, Command> + Render<DomTree> + 'static, DomTree: DomIter<Message, Command, Key> + 'static, Message: fmt::Debug + Clone + PartialEq + 'static, Command: SideEffect<Message> + fmt::Debug + 'static, Key: Eq + Hash + 'static, { if self.clear_parent { while let Some(child) = parent.first_child() { parent.remove_child(&child) .expect("failed to remove child of parent element"); } } let (app_rc, nodes) = self.create(model); for node in nodes.iter() { parent.append_child(node) .expect("failed to append child to parent element"); } app_rc } } impl<Model, DomTree, Processor, Message, Command, Key> Application<Message, Command> for App<Model, DomTree, Processor, Message, Command, Key> where Model: Update<Message, Command> + Render<DomTree> + 'static, Command: SideEffect<Message> + fmt::Debug + 'static, Processor: side_effect::Processor<Message, Command> + 'static, Message: fmt::Debug + Clone + PartialEq + 'static, DomTree: DomIter<Message, Command, Key> + 'static, Key: Eq + Hash + 'static, { fn update(&mut self, msg: Message) -> Commands<Command> { let mut commands = Commands::default(); self.model.update(msg, &mut commands); commands } fn get_scheduled_render(&mut self) -> &mut Option<ScheduledRender<Command>> { &mut self.animation_frame_handle } fn set_scheduled_render(&mut self, handle: ScheduledRender<Command>) { self.animation_frame_handle = Some(handle) } fn render(&mut self, app_rc: &Dispatcher<Message, Command>) -> Vec<Command> { let parent = self.node() .expect("empty app?") .parent_element() .expect("app not attached to the dom"); let App { ref mut model, ref mut storage, ref dom, .. } = *self; let new_dom = model.render(); let old = dom.dom_iter(); let new = new_dom.dom_iter(); let patch_set = diff::diff(old, new, storage); self.storage = patch_set.apply(&parent, app_rc); self.dom = new_dom; let commands; if let Some((cmds, _, _)) = self.animation_frame_handle.take() { commands = cmds; } else { commands = vec![]; } commands } fn process(&self, cmd: Command, app: &Dispatcher<Message, Command>) { Processor::process(&self.processor, cmd, app); } fn push_listener(&mut self, listener: (String, Closure<dyn FnMut(web_sys::Event)>)) { self.listeners.push(listener); } fn detach(&mut self, app: &Dispatcher<Message, Command>) { use std::iter; let parent = self.node() .expect("empty app?") .parent_element() .expect("app not attached to the dom"); let App { ref mut storage, ref dom, ref mut listeners, .. } = *self; let window = web_sys::window() .expect("couldn't get window handle"); for (event, listener) in listeners.drain(..) { window .remove_event_listener_with_callback(&event, listener.as_ref().unchecked_ref()) .expect("failed to remove event listener"); } let o = dom.dom_iter(); let patch_set = diff::diff(o, iter::empty(), storage); self.storage = patch_set.apply(&parent, app); } fn node(&self) -> Option<web_sys::Node> { self.storage.first() .and_then(|item| -> Option<web_sys::Node> { match item { WebItem::Element(ref node) => Some(node.clone().into()), WebItem::Text(ref node) => Some(node.clone().into()), WebItem::Component(component) => component.node(), i => panic!("unknown item, expected something with a node in it: {:?}", i) } }) } fn nodes(&self) -> Vec<web_sys::Node> { let mut nodes = vec![]; let mut depth = 0; for item in &self.storage { match item { WebItem::Element(_) | WebItem::Text(_) | WebItem::Component(_) if depth > 0 => { depth += 1; } WebItem::Up => depth -= 1, WebItem::Closure(_) => {} WebItem::Element(ref node) => { nodes.push(node.clone().into()); depth += 1; } WebItem::Text(ref node) => { nodes.push(node.clone().into()); depth += 1; } WebItem::Component(component) => { nodes.extend(component.nodes()); depth += 1; } i => panic!("unexpected item, expected something with a node in it, got : {:?}", i) } } nodes } fn create(&mut self, app: &Dispatcher<Message, Command>) -> Vec<web_sys::Node> { use std::iter; let App { ref mut storage, ref dom, .. } = *self; let n = dom.dom_iter(); let patch_set = diff::diff(iter::empty(), n, storage); let (storage, pending) = patch_set.prepare(app); self.storage = storage; pending } } struct App<Model, DomTree, Processor, Message, Command, Key> where Command: SideEffect<Message>, Processor: side_effect::Processor<Message, Command>, { dom: DomTree, model: Model, storage: Storage<Message>, listeners: Vec<(String, Closure<dyn FnMut(web_sys::Event)>)>, animation_frame_handle: Option<ScheduledRender<Command>>, processor: Processor, command: std::marker::PhantomData<Command>, key: std::marker::PhantomData<Key>, } impl<Model, DomTree, Processor, Message, Command, Key> App<Model, DomTree, Processor, Message, Command, Key> where Command: SideEffect<Message>, Processor: side_effect::Processor<Message, Command> + 'static, { fn create(model: Model, processor: Processor) -> (Rc<RefCell<Box<dyn Application<Message, Command>>>>, Vec<web_sys::Node>) where Model: Update<Message, Command> + Render<DomTree> + 'static, DomTree: DomIter<Message, Command, Key> + 'static, Message: fmt::Debug + Clone + PartialEq + 'static, Command: SideEffect<Message> + fmt::Debug + 'static, Key: Eq + Hash + 'static, { let dom = model.render(); let app = App { dom: dom, model: model, storage: vec![], listeners: vec![], animation_frame_handle: None, processor: processor, command: std::marker::PhantomData, key: std::marker::PhantomData, }; let app_rc = Rc::new(RefCell::new(Box::new(app) as Box<dyn Application<Message, Command>>)); let nodes = Application::create(&mut **app_rc.borrow_mut(), &Dispatcher::from(&app_rc)); (app_rc, nodes) } }
pub mod detach; pub mod model; pub mod dispatch; pub mod side_effect; pub mod application; pub use crate::app::detach::Detach; pub use crate::app::model::{Update, Render}; pub use crate::app::dispatch::Dispatcher; pub use crate::app::side_effect::{SideEffect, Processor, Commands}; pub use crate::app::application::{Application, ScheduledRender}; use web_sys; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use std::rc::Rc; use std::cell::RefCell; use std::fmt; use std::hash::Hash; use crate::diff; use crate::vdom::DomIter; use crate::vdom::Storage; use crate::vdom::WebItem; use crate::route::Route; pub struct AppBuilder<Message, Command, Processor, Router> where Command: SideEffect<Message>, Processor: side_effect::Processor<Message, Command>, Router: Route<Message>, { router: Option<Rc<Router>>, processor: Processor, clear_parent: bool, message: std::marker::PhantomData<Message>, command: std::marker::PhantomData<Command>, } impl<Message, Command> Default for AppBuilder< Message, Command, side_effect::DefaultProcessor<Message, Command>, (), > where Command: SideEffect<Message>, { fn default() -> Self { AppBuilder { router: None, processor: side_effect::DefaultProcessor::default(), clear_parent: false, message: std::marker::PhantomData, command: std::marker::PhantomData, } } } impl<Message, Command, Processor, Router> AppBuilder<Message, Command, Processor, Router> where Command: SideEffect<Message> + 'static, Processor: side_effect::Processor<Message, Command> + 'static, Router: Route<Message> + 'static, { #[must_use] pub fn router<R: Route<Message>>(self, router: R) -> AppBuilder<Message, Command, Processor, R> { let AppBuilder { message, command, processor, clear_parent, router: _router, } = self; AppBuilder { message: message, command: command, processor, clear_parent: clear_parent, router: Some(Rc::new(router)), } } #[must_use] pub(crate) fn processor<P: side_effect::Processor<Message, Command>>(self, processor: P) -> AppBuilder<Message, Command, P, Router> { let AppBuilder { message, command, router, clear_parent, processor: _processor, } = self; AppBuilder { message: message, command: command, processor: processor, router: router, clear_parent: clear_parent, } } #[must_use] pub fn clear(mut self) -> Self { self.clear_parent = true; self } #[must_use] pub(crate) fn create<Model, DomTree, Key>(self, mut model: Model) -> (Rc<RefCell<Box<dyn Application<Message, Command>>>>, Vec<web_sys::Node>) where Model: Update<Message, Command> + Render<DomTree> + 'static, DomTree: DomIter<Message, Command, Key> + 'static, Message: fmt::Debug + Clone + PartialEq + 'static, Command: SideEffect<Message> + fmt::Debug + 'static, Key: Eq + Hash + 'static, { let AppBuilder { router, processor, .. } = self; let mut commands = Commands::default(); if let Some(ref router) = router { let url = web_sys::window() .expect("window") .document() .expect("document") .url() .expect("url"); if let Some(msg) = router.route(&url) { model.update(msg, &mut commands); } } let (app_rc, nodes) = App::create(model, processor); let dispatcher = Dispatcher::from(&app_rc); if let Some(ref router) = router { let window = web_sys::window() .expect("couldn't get window handle"); let document = window.document() .expect("couldn't get document handle"); for event in ["popstate", "hashchange"].iter() { let dispatcher = dispatcher.clone(); let document = document.clone(); let router = router.clone();
window .add_event_listener_with_callback(event, closure.as_ref().unchecked_ref()) .expect("failed to add event listener"); app_rc.borrow_mut().push_listener((event.to_string(), closure)); } for cmd in commands.immediate { app_rc.borrow().process(cmd, &dispatcher); } for cmd in commands.post_render { app_rc.borrow().process(cmd, &dispatcher); } } (app_rc, nodes) } pub fn attach<Model, DomTree, Key>(self, parent: web_sys::Element, model: Model) -> Rc<RefCell<Box<dyn Application<Message, Command>>>> where Model: Update<Message, Command> + Render<DomTree> + 'static, DomTree: DomIter<Message, Command, Key> + 'static, Message: fmt::Debug + Clone + PartialEq + 'static, Command: SideEffect<Message> + fmt::Debug + 'static, Key: Eq + Hash + 'static, { if self.clear_parent { while let Some(child) = parent.first_child() { parent.remove_child(&child) .expect("failed to remove child of parent element"); } } let (app_rc, nodes) = self.create(model); for node in nodes.iter() { parent.append_child(node) .expect("failed to append child to parent element"); } app_rc } } impl<Model, DomTree, Processor, Message, Command, Key> Application<Message, Command> for App<Model, DomTree, Processor, Message, Command, Key> where Model: Update<Message, Command> + Render<DomTree> + 'static, Command: SideEffect<Message> + fmt::Debug + 'static, Processor: side_effect::Processor<Message, Command> + 'static, Message: fmt::Debug + Clone + PartialEq + 'static, DomTree: DomIter<Message, Command, Key> + 'static, Key: Eq + Hash + 'static, { fn update(&mut self, msg: Message) -> Commands<Command> { let mut commands = Commands::default(); self.model.update(msg, &mut commands); commands } fn get_scheduled_render(&mut self) -> &mut Option<ScheduledRender<Command>> { &mut self.animation_frame_handle } fn set_scheduled_render(&mut self, handle: ScheduledRender<Command>) { self.animation_frame_handle = Some(handle) } fn render(&mut self, app_rc: &Dispatcher<Message, Command>) -> Vec<Command> { let parent = self.node() .expect("empty app?") .parent_element() .expect("app not attached to the dom"); let App { ref mut model, ref mut storage, ref dom, .. } = *self; let new_dom = model.render(); let old = dom.dom_iter(); let new = new_dom.dom_iter(); let patch_set = diff::diff(old, new, storage); self.storage = patch_set.apply(&parent, app_rc); self.dom = new_dom; let commands; if let Some((cmds, _, _)) = self.animation_frame_handle.take() { commands = cmds; } else { commands = vec![]; } commands } fn process(&self, cmd: Command, app: &Dispatcher<Message, Command>) { Processor::process(&self.processor, cmd, app); } fn push_listener(&mut self, listener: (String, Closure<dyn FnMut(web_sys::Event)>)) { self.listeners.push(listener); } fn detach(&mut self, app: &Dispatcher<Message, Command>) { use std::iter; let parent = self.node() .expect("empty app?") .parent_element() .expect("app not attached to the dom"); let App { ref mut storage, ref dom, ref mut listeners, .. } = *self; let window = web_sys::window() .expect("couldn't get window handle"); for (event, listener) in listeners.drain(..) { window .remove_event_listener_with_callback(&event, listener.as_ref().unchecked_ref()) .expect("failed to remove event listener"); } let o = dom.dom_iter(); let patch_set = diff::diff(o, iter::empty(), storage); self.storage = patch_set.apply(&parent, app); } fn node(&self) -> Option<web_sys::Node> { self.storage.first() .and_then(|item| -> Option<web_sys::Node> { match item { WebItem::Element(ref node) => Some(node.clone().into()), WebItem::Text(ref node) => Some(node.clone().into()), WebItem::Component(component) => component.node(), i => panic!("unknown item, expected something with a node in it: {:?}", i) } }) } fn nodes(&self) -> Vec<web_sys::Node> { let mut nodes = vec![]; let mut depth = 0; for item in &self.storage { match item { WebItem::Element(_) | WebItem::Text(_) | WebItem::Component(_) if depth > 0 => { depth += 1; } WebItem::Up => depth -= 1, WebItem::Closure(_) => {} WebItem::Element(ref node) => { nodes.push(node.clone().into()); depth += 1; } WebItem::Text(ref node) => { nodes.push(node.clone().into()); depth += 1; } WebItem::Component(component) => { nodes.extend(component.nodes()); depth += 1; } i => panic!("unexpected item, expected something with a node in it, got : {:?}", i) } } nodes } fn create(&mut self, app: &Dispatcher<Message, Command>) -> Vec<web_sys::Node> { use std::iter; let App { ref mut storage, ref dom, .. } = *self; let n = dom.dom_iter(); let patch_set = diff::diff(iter::empty(), n, storage); let (storage, pending) = patch_set.prepare(app); self.storage = storage; pending } } struct App<Model, DomTree, Processor, Message, Command, Key> where Command: SideEffect<Message>, Processor: side_effect::Processor<Message, Command>, { dom: DomTree, model: Model, storage: Storage<Message>, listeners: Vec<(String, Closure<dyn FnMut(web_sys::Event)>)>, animation_frame_handle: Option<ScheduledRender<Command>>, processor: Processor, command: std::marker::PhantomData<Command>, key: std::marker::PhantomData<Key>, } impl<Model, DomTree, Processor, Message, Command, Key> App<Model, DomTree, Processor, Message, Command, Key> where Command: SideEffect<Message>, Processor: side_effect::Processor<Message, Command> + 'static, { fn create(model: Model, processor: Processor) -> (Rc<RefCell<Box<dyn Application<Message, Command>>>>, Vec<web_sys::Node>) where Model: Update<Message, Command> + Render<DomTree> + 'static, DomTree: DomIter<Message, Command, Key> + 'static, Message: fmt::Debug + Clone + PartialEq + 'static, Command: SideEffect<Message> + fmt::Debug + 'static, Key: Eq + Hash + 'static, { let dom = model.render(); let app = App { dom: dom, model: model, storage: vec![], listeners: vec![], animation_frame_handle: None, processor: processor, command: std::marker::PhantomData, key: std::marker::PhantomData, }; let app_rc = Rc::new(RefCell::new(Box::new(app) as Box<dyn Application<Message, Command>>)); let nodes = Application::create(&mut **app_rc.borrow_mut(), &Dispatcher::from(&app_rc)); (app_rc, nodes) } }
let closure = Closure::wrap( Box::new(move |_event| { let url = document.url() .expect_throw("couldn't get document url"); if let Some(msg) = router.route(&url) { dispatcher.dispatch(msg); } }) as Box<dyn FnMut(web_sys::Event)> );
assignment_statement
[ { "content": "/// Some helpers to make testing a model easier.\n\npub trait Model<Message, Command> {\n\n /// Update a model with the given message.\n\n ///\n\n /// This function is a helper function designed to make testing models simpler. Normally during\n\n /// an update to a model, the `Commands` structure must be passed in as an argument. This\n\n /// function automatically does that and returns the resulting `Commands` structure. It's only\n\n /// useful for unit testing.\n\n fn test_update(&mut self, msg: Message) -> Commands<Command>;\n\n}\n\n\n\nimpl<Message, Command, M: Update<Message, Command>> Model<Message, Command> for M {\n\n fn test_update(&mut self, msg: Message) -> Commands<Command> {\n\n let mut cmds = Commands::default();\n\n Update::update(self, msg, &mut cmds);\n\n cmds\n\n }\n\n}\n", "file_path": "src/test.rs", "rank": 1, "score": 149432.0909274555 }, { "content": "/// A processor for commands.\n\npub trait Processor<Message, Command>\n\nwhere\n\n Command: SideEffect<Message>,\n\n{\n\n /// Proccess a command.\n\n fn process(&self, cmd: Command, dispatcher: &Dispatcher<Message, Command>);\n\n}\n\n\n\n/// Default processor for commands, it just executes all side effects.\n\npub struct DefaultProcessor<Message, Command>\n\nwhere\n\n Command: SideEffect<Message>,\n\n{\n\n message: std::marker::PhantomData<Message>,\n\n command: std::marker::PhantomData<Command>,\n\n}\n\n\n\nimpl<Message, Command> Default for DefaultProcessor<Message, Command>\n\nwhere\n\n Command: SideEffect<Message>,\n", "file_path": "src/app/side_effect.rs", "rank": 2, "score": 139695.74773483805 }, { "content": "/// All of the functions one might perform on a wasm application.\n\npub trait Application<Message, Command> {\n\n /// Update the application with a message.\n\n fn update(&mut self, msg: Message) -> Commands<Command>;\n\n /// Tell the application to render itself.\n\n fn render(&mut self, app: &Dispatcher<Message, Command>) -> Vec<Command>;\n\n /// Process side effecting commands.\n\n fn process(&self, cmd: Command, app: &Dispatcher<Message, Command>);\n\n /// Get a reference to any pending rendering.\n\n fn get_scheduled_render(&mut self) -> &mut Option<ScheduledRender<Command>>;\n\n /// Store a reference to any pending rendering.\n\n fn set_scheduled_render(&mut self, handle: ScheduledRender<Command>);\n\n /// Store a listener that will be canceled when the app is detached.\n\n fn push_listener(&mut self, listener: (String, Closure<dyn FnMut(web_sys::Event)>));\n\n /// The first node of app.\n\n fn node(&self) -> Option<web_sys::Node>;\n\n /// Get all the top level nodes of node this app.\n\n fn nodes(&self) -> Vec<web_sys::Node>;\n\n /// Create the dom nodes for this app.\n\n fn create(&mut self, app: &Dispatcher<Message, Command>) -> Vec<web_sys::Node>;\n\n /// Detach the app from the dom.\n", "file_path": "src/app/application.rs", "rank": 3, "score": 137832.34488050162 }, { "content": "struct ComponentProcessor<Message, Command, ParentMessage, ParentCommand> {\n\n parent: Dispatcher<ParentMessage, ParentCommand>,\n\n unmap: fn(Command) -> Option<ParentMessage>,\n\n message: std::marker::PhantomData<Message>,\n\n}\n\n\n\nimpl<Message, Command, ParentMessage, ParentCommand>\n\nComponentProcessor<Message, Command, ParentMessage, ParentCommand>\n\n{\n\n fn new(app: Dispatcher<ParentMessage, ParentCommand>, unmap: fn(Command) -> Option<ParentMessage>) -> Self {\n\n ComponentProcessor {\n\n parent: app,\n\n unmap: unmap,\n\n message: std::marker::PhantomData,\n\n }\n\n }\n\n}\n\n\n\nimpl<Message, Command, ParentMessage, ParentCommand>\n\nside_effect::Processor<Message, Command>\n", "file_path": "src/component.rs", "rank": 4, "score": 131599.0588523045 }, { "content": "fn leaked_closure<Message>() -> &'static mut WebItem<Message> {\n\n Box::leak(Box::new(WebItem::Closure(Closure::wrap(Box::new(|_|{}) as Box<dyn FnMut(web_sys::Event)>))))\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 5, "score": 130890.38804038441 }, { "content": "/// Process a message that updates the model.\n\npub trait Update<Message, Command = ()> {\n\n /// Update the model using the given message. Implement this to describe the behavior of your\n\n /// app.\n\n fn update(&mut self, msg: Message, _commands: &mut Commands<Command>) {\n\n self.simple_update(msg);\n\n }\n\n\n\n /// Update the model using the given message. Implement this if your app does not need to use\n\n /// side effecting commands.\n\n fn simple_update(&mut self, _msg: Message) { }\n\n}\n\n\n\nimpl<M> Update<(), ()> for M { }\n\n\n", "file_path": "src/app/model.rs", "rank": 6, "score": 127862.5112912175 }, { "content": "/// This trait provides a way to iterate over a virtual dom representation.\n\npub trait DomIter<Message: Clone, Command, K> {\n\n /// Return an iterator over the virtual dom.\n\n fn dom_iter<'a>(&'a self) -> Box<dyn Iterator<Item = DomItem<'a, Message, Command, K>> + 'a>;\n\n}\n", "file_path": "src/vdom.rs", "rank": 7, "score": 126783.28228097988 }, { "content": "/// Detach an app from the DOM.\n\npub trait Detach<Message> {\n\n /// Detach an app from the DOM.\n\n fn detach(&self);\n\n}\n", "file_path": "src/app/detach.rs", "rank": 8, "score": 122146.20357342425 }, { "content": "/// Return the series of steps required to move from the given old/existing virtual dom to the\n\n/// given new virtual dom.\n\npub fn diff<'a, Message, Command, O, N, S, K>(\n\n old: O,\n\n new: N,\n\n storage: S,\n\n)\n\n-> PatchSet<'a, Message, Command, K>\n\nwhere\n\n Message: 'a + PartialEq + Clone + fmt::Debug,\n\n O: IntoIterator<Item = DomItem<'a, Message, Command, K>>,\n\n N: IntoIterator<Item = DomItem<'a, Message, Command, K>>,\n\n S: IntoIterator<Item = &'a mut WebItem<Message>>,\n\n K: Eq + Hash,\n\n{\n\n DiffImpl::new(old, new, storage).diff()\n\n}\n\n\n", "file_path": "src/diff.rs", "rank": 9, "score": 112287.0489339653 }, { "content": "fn gen_storage<'a, Message, Command, Key, Iter>(iter: Iter) -> Storage<Message> where\n\n Message: 'a,\n\n Key: 'a,\n\n Iter: Iterator<Item = DomItem<'a, Message, Command, Key>>,\n\n{\n\n iter\n\n // filter items that do not have storage\n\n .filter(|i| {\n\n match i {\n\n DomItem::Element { .. } | DomItem::Text(_) | DomItem::Event { .. }\n\n | DomItem::Component { .. } | DomItem::Up => true,\n\n DomItem::Key(_) | DomItem::Attr { .. } | DomItem::UnsafeInnerHtml(_)\n\n => false,\n\n }\n\n })\n\n .map(|i| {\n\n match i {\n\n DomItem::Element { name: element, .. } => WebItem::Element(e(element)),\n\n DomItem::Text(text) => WebItem::Text(\n\n web_sys::window().expect(\"expected window\")\n", "file_path": "tests/tests.rs", "rank": 10, "score": 111662.50075519725 }, { "content": "/// A wasm application consisting of a model, a virtual dom representation, and the parent element\n\n/// where this app lives in the dom.\n\nstruct ComponentImpl<Message, Command, ParentMessage> {\n\n app: Rc<RefCell<Box<dyn Application<Message, Command>>>>,\n\n map: fn(ParentMessage) -> Option<Message>,\n\n pending: Vec<web_sys::Node>,\n\n}\n\n\n\nimpl<Message, Command, ParentMessage> Component<ParentMessage>\n\nfor ComponentImpl<Message, Command, ParentMessage>\n\nwhere\n\n Message: fmt::Debug + Clone + PartialEq + 'static,\n\n Command: SideEffect<Message> + 'static,\n\n ParentMessage: fmt::Debug + Clone + PartialEq + 'static,\n\n{\n\n fn dispatch(&self, msg: ParentMessage) {\n\n if let Some(msg) = (self.map)(msg) {\n\n Dispatcher::from(&self.app).dispatch(msg);\n\n }\n\n }\n\n\n\n fn detach(&self) {\n", "file_path": "src/component.rs", "rank": 11, "score": 110349.84725194618 }, { "content": "/// Render (or view) the model as a virtual dom.\n\npub trait Render<DomTree> {\n\n /// Render the model as a virtual dom.\n\n fn render(&self) -> DomTree;\n\n}\n", "file_path": "src/app/model.rs", "rank": 12, "score": 108546.78651085391 }, { "content": "#[derive(Default)]\n\nstruct Router {}\n\n\n\nimpl Route<Message> for Router {\n\n fn route(&self, url: &str) -> Option<Message> {\n\n if url.ends_with(\"#/active\") {\n\n Some(Message::ShowActive(false))\n\n }\n\n else if url.ends_with(\"#/completed\") {\n\n Some(Message::ShowCompleted(false))\n\n }\n\n else {\n\n Some(Message::ShowAll(false))\n\n }\n\n }\n\n}\n\n\n", "file_path": "examples/todomvc/src/lib.rs", "rank": 13, "score": 102117.40771717978 }, { "content": "fn leaked_t<Message>(text: &str) -> &mut WebItem<Message> {\n\n Box::leak(Box::new(WebItem::Text(t(text))))\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 14, "score": 94435.80920252526 }, { "content": "fn leaked_e<Message>(name: &str) -> &mut WebItem<Message> {\n\n Box::leak(Box::new(WebItem::Element(e(name))))\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 15, "score": 94435.80920252526 }, { "content": "/// Our model is just an i32.\n\nstruct Model(i32);\n\n\n\nimpl Model {\n\n fn new() -> Self {\n\n Model(0)\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq)]\n\npub enum Msg {\n\n Increment,\n\n Decrement,\n\n}\n\n\n\nimpl Update<Msg> for Model {\n\n fn simple_update(&mut self, msg: Msg) {\n\n match msg {\n\n Msg::Increment => self.0 += 1,\n\n Msg::Decrement => self.0 -= 1,\n\n }\n\n }\n\n}\n\n\n", "file_path": "examples/counter/src/lib.rs", "rank": 16, "score": 92267.09076119924 }, { "content": "struct DiffImpl<'a, Message, Command, O, N, S, K>\n\nwhere\n\n Message: 'a + PartialEq + Clone + fmt::Debug,\n\n O: IntoIterator<Item = DomItem<'a, Message, Command, K>>,\n\n N: IntoIterator<Item = DomItem<'a, Message, Command, K>>,\n\n S: IntoIterator<Item = &'a mut WebItem<Message>>,\n\n K: Eq + Hash,\n\n{\n\n old: O::IntoIter,\n\n new: N::IntoIter,\n\n sto: S::IntoIter,\n\n patch_set: PatchSet<'a, Message, Command, K>,\n\n /// list of old keyed DomItems (and their storage)\n\n old_def: HashMap<&'a K, (Vec<DomItem<'a, Message, Command, K>>, Vec<&'a mut WebItem<Message>>)>,\n\n /// list of new keyed DomItems\n\n new_def: HashMap<&'a K, Vec<DomItem<'a, Message, Command, K>>>,\n\n /// if true (the default), keyed items will be deferred\n\n defer_keyed: bool,\n\n}\n\n\n", "file_path": "src/diff.rs", "rank": 17, "score": 84627.57115129888 }, { "content": "struct NodeStack {\n\n /// Parent nodes in the tree [(parent, [pending children])].\n\n stack: Vec<(web_sys::Node, Vec<web_sys::Node>)>,\n\n pending: Vec<web_sys::Node>,\n\n}\n\n\n\nimpl NodeStack {\n\n fn new() -> Self {\n\n Self {\n\n stack: vec![],\n\n pending: vec![],\n\n }\n\n }\n\n\n\n /// Get the current depth of the tree.\n\n fn depth(&self) -> usize {\n\n self.stack.len()\n\n }\n\n\n\n /// Get the current parent node off the stack, if any.\n", "file_path": "src/patch.rs", "rank": 18, "score": 80712.67597730359 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_keyed_element_move_key() {\n\n let old = Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\"))\n\n .push(Dom::elem(\"div\")\n\n .key(\"yup\")\n\n );\n\n let new = Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .key(\"yup\")\n\n )\n\n .push(Dom::elem(\"div\"));\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n", "file_path": "tests/tests.rs", "rank": 19, "score": 78225.60489394213 }, { "content": "#[wasm_bindgen_test]\n\nfn basic_event_test() {\n\n let gen1 = iter::empty();\n\n let gen2 = Dom::<_, _, &()>::elem(\"button\").event(\"click\", ());\n\n\n\n let parent = e(\"div\");\n\n let messages = Rc::new(RefCell::new(vec![]));\n\n let app = App::dispatcher_with_vec(Rc::clone(&messages));\n\n let mut storage = vec![];\n\n\n\n let o = gen1.into_iter();\n\n let n = gen2.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n storage = patch_set.apply(&parent, &app);\n\n\n\n match storage[0] {\n\n WebItem::Element(ref node) => {\n\n node.dyn_ref::<web_sys::HtmlElement>()\n\n .expect(\"expected html element\")\n\n .click();\n\n },\n\n _ => panic!(\"expected node to be created\"),\n\n }\n\n\n\n assert_eq!(messages.borrow().len(), 1);\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 20, "score": 73810.59842264188 }, { "content": "#[wasm_bindgen_test]\n\nfn assorted_child_nodes() {\n\n let old = Dom::<_, _, &()>::elem(\"div\")\n\n .push(Dom::elem(\"h1\")\n\n .attr(\"id\", \"id\")\n\n .event(\"onclick\", ())\n\n .push(Dom::text(\"h1\"))\n\n )\n\n .push(Dom::elem(\"p\")\n\n .attr(\"class\", \"item\")\n\n .push(Dom::text(\"paragraph1\"))\n\n )\n\n .push(Dom::elem(\"p\")\n\n .attr(\"class\", \"item\")\n\n .push(Dom::text(\"paragraph2\"))\n\n )\n\n .push(Dom::elem(\"p\")\n\n .attr(\"class\", \"item\")\n\n .attr(\"style\", \"\")\n\n .push(Dom::text(\"paragraph3\"))\n\n )\n", "file_path": "tests/tests.rs", "rank": 21, "score": 73737.70067882614 }, { "content": "#[wasm_bindgen_test]\n\nfn new_child_nodes() {\n\n let old = Dom::<_, _, &()>::elem(\"div\");\n\n let new = Dom::elem(\"div\")\n\n .push(Dom::elem(\"b\")\n\n .attr(\"class\", \"item\")\n\n .attr(\"id\", \"id1\")\n\n .event(\"onclick\", ())\n\n )\n\n .push(Dom::elem(\"i\")\n\n .attr(\"class\", \"item\")\n\n .attr(\"id\", \"id2\")\n\n .event(\"onclick\", ())\n\n )\n\n ;\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n", "file_path": "tests/tests.rs", "rank": 22, "score": 73737.70067882614 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_duplicate_key() {\n\n let old = Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .key(\"yup\")\n\n )\n\n .push(Dom::elem(\"span\")\n\n .key(\"yup\")\n\n );\n\n let new = Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\"))\n\n .push(Dom::elem(\"div\")\n\n .key(\"yup\")\n\n )\n\n .push(Dom::elem(\"span\")\n\n .key(\"yup\")\n\n );\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n", "file_path": "tests/tests.rs", "rank": 23, "score": 73708.78278797797 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_keyed_from_empty() {\n\n let new = Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .key(\"yup\")\n\n );\n\n\n\n let o = iter::empty();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, iter::empty());\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CreateElement { element: \"div\" },\n\n Patch::ReferenceKey(&\"yup\"),\n\n Patch::Up,\n\n ],\n\n &\"yup\" => [\n\n Patch::CreateElement { element: \"div\" },\n\n Patch::Up,\n\n ],\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 24, "score": 73708.78278797797 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_keyed_to_empty() {\n\n let old = Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .key(\"yup\")\n\n );\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = iter::empty();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::RemoveElement(leaked_e(\"div\")),\n\n Patch::RemoveElement(leaked_e(\"div\")),\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 25, "score": 73708.78278797797 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() -> Result<(), JsValue> {\n\n init_log();\n\n set_panic_hook();\n\n\n\n let parent = web_sys::window()\n\n .expect(\"couldn't get window handle\")\n\n .document()\n\n .expect(\"couldn't get document handle\")\n\n .query_selector(\"section.todoapp\")\n\n .expect(\"error querying for element\")\n\n .expect(\"expected <section class=\\\"todoapp\\\"></section>\");\n\n\n\n let items = read_items_from_storage();\n\n\n\n let app = AppBuilder::default()\n\n .router(Router::default())\n\n .attach(parent, Todo::with_items(items));\n\n\n\n Command::FocusPending.process(&app.into());\n\n\n", "file_path": "examples/todomvc/src/lib.rs", "rank": 26, "score": 73062.22472405902 }, { "content": "#[wasm_bindgen(start)]\n\npub fn run() -> Result<(), JsValue> {\n\n set_panic_hook();\n\n init_log();\n\n\n\n let parent = web_sys::window()\n\n .expect(\"couldn't get window handle\")\n\n .document()\n\n .expect(\"couldn't get document handle\")\n\n .query_selector(\".app\")\n\n .expect(\"error querying for element\")\n\n .expect(\"expected <section class=\\\"app\\\"></section>\");\n\n\n\n let _ = AppBuilder::default()\n\n .attach(parent, Model::new());\n\n\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "examples/counter/src/lib.rs", "rank": 27, "score": 73062.22472405902 }, { "content": "/// Implement this trait on your router to allow for routing when the URL changes.\n\npub trait Route<Message> {\n\n /// Convert a new url to a message for the app.\n\n fn route(&self, _url: &str) -> Option<Message>;\n\n}\n\n\n\n/// A placeholder router that does nothing and will never be used.\n\n///\n\n/// This serves as the default router for [`AppBuilder`] allowing apps to be constructed without\n\n/// specifying a router.\n\n///\n\n/// [`AppBuilder`]: ../app/struct.AppBuilder.html\n\nimpl<Message> Route<Message> for () {\n\n fn route(&self, _url: &str) -> Option<Message> {\n\n None\n\n }\n\n}\n", "file_path": "src/route.rs", "rank": 28, "score": 71241.29955008357 }, { "content": "/// A self containted component that can live inside another app.\n\npub trait Component<Message> {\n\n /// Dispatch a message to this component.\n\n fn dispatch(&self, message: Message);\n\n\n\n /// Detach the component from the dom.\n\n fn detach(&self);\n\n\n\n /// Get the first web_sys::Node of this component (if any)\n\n fn node(&self) -> Option<web_sys::Node>;\n\n\n\n /// Get the top level web_sys::Nodes of this component (if any)\n\n fn nodes(&self) -> Vec<web_sys::Node>;\n\n\n\n /// Get nodes waiting to attach to the parent.\n\n fn pending(&mut self) -> Vec<web_sys::Node>;\n\n}\n\n\n\n/// A builder for constructing a self contained component app that lives inside of another app.\n\npub struct ComponentBuilder<Message, Command, ParentMessage> {\n\n map: fn(ParentMessage) -> Option<Message>,\n", "file_path": "src/component.rs", "rank": 29, "score": 71237.30290983364 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_remove_event_handler() {\n\n let old = Dom::<_, _, &()>::elem(\"div\")\n\n .event(\"onclick\", ())\n\n .push(\"text\");\n\n let new = Dom::elem(\"div\")\n\n .push(\"text\");\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CopyElement(leaked_e(\"div\")),\n\n Patch::RemoveListener { trigger: \"onclick\", take: leaked_closure() },\n\n Patch::CreateText { text: \"text\".into() },\n\n Patch::Up,\n\n Patch::RemoveText(leaked_t(\"text\")),\n\n Patch::Up,\n\n ]\n\n );\n\n}\n", "file_path": "tests/tests.rs", "rank": 30, "score": 70967.11820162469 }, { "content": "#[wasm_bindgen_test]\n\nfn old_child_nodes_with_element() {\n\n let old = Dom::<_, _, &()>::elem(\"div\")\n\n .push(Dom::elem(\"b\")\n\n .attr(\"class\", \"item\")\n\n .attr(\"id\", \"id\")\n\n .event(\"onclick\", ())\n\n )\n\n .push(Dom::elem(\"i\")\n\n .attr(\"class\", \"item\")\n\n .attr(\"id\", \"id\")\n\n .event(\"onclick\", ())\n\n )\n\n ;\n\n\n\n let new = Dom::elem(\"div\");\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n", "file_path": "tests/tests.rs", "rank": 31, "score": 70898.1502231236 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_keyed_element_not_equal() {\n\n let old = Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .key(\"yup\")\n\n );\n\n let new = Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .key(\"nope\")\n\n );\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CopyElement(leaked_e(\"div\")),\n\n Patch::ReferenceKey(&\"nope\"),\n\n Patch::Up,\n\n Patch::RemoveElement(leaked_e(\"div\")),\n\n ],\n\n &\"nope\" => [\n\n Patch::CreateElement { element: \"div\" },\n\n Patch::Up,\n\n ],\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 32, "score": 70870.7912354524 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_keyed_element_equal() {\n\n let old = Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .key(\"yup\")\n\n );\n\n let new = Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .key(\"yup\")\n\n );\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CopyElement(leaked_e(\"div\")),\n\n Patch::MoveElement(leaked_e(\"div\")),\n\n Patch::Up,\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 33, "score": 70870.7912354524 }, { "content": "#[wasm_bindgen_test]\n\nfn inner_html_remove_parent_node() {\n\n let gen1: DomVec;\n\n let gen2: DomVec;\n\n unsafe {\n\n gen1 = vec![\n\n Dom::elem(\"div\")\n\n .push(Dom::elem(\"p\").push(\"test2\")),\n\n Dom::elem(\"div\")\n\n .inner_html(\"<div><p>test5</p></div>\"),\n\n ].into();\n\n gen2 = vec![\n\n Dom::elem(\"div\")\n\n .push(Dom::elem(\"p\").push(\"test3\")),\n\n ].into();\n\n }\n\n\n\n let parent = e(\"div\");\n\n let app = App::dispatcher();\n\n let mut storage = vec![];\n\n\n", "file_path": "tests/tests.rs", "rank": 34, "score": 68349.08860446277 }, { "content": "#[wasm_bindgen_test]\n\nfn old_child_nodes_with_element_and_child() {\n\n let old = Dom::<_, _, &()>::elem(\"div\")\n\n .push(Dom::elem(\"b\")\n\n .attr(\"class\", \"item\")\n\n .attr(\"id\", \"id\")\n\n .event(\"onclick\", ())\n\n )\n\n .push(Dom::elem(\"i\")\n\n .attr(\"class\", \"item\")\n\n .attr(\"id\", \"id\")\n\n .event(\"onclick\", ())\n\n )\n\n ;\n\n\n\n let new = Dom::elem(\"div\")\n\n .push(Dom::elem(\"i\"))\n\n ;\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n", "file_path": "tests/tests.rs", "rank": 35, "score": 68349.08860446277 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_nested_keyed_element_swap() {\n\n let old = Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .key(\"yup\")\n\n .push(Dom::elem(\"span\")\n\n .key(\"yup yup\")\n\n )\n\n );\n\n let new = Dom::elem(\"div\")\n\n .push(Dom::elem(\"span\")\n\n .key(\"yup yup\")\n\n .push(Dom::elem(\"div\")\n\n .key(\"yup\")\n\n )\n\n );\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n", "file_path": "tests/tests.rs", "rank": 36, "score": 68323.1290426224 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_old_child_nodes_with_new_element() {\n\n let old = Dom::<_, _, &()>::elem(\"span\")\n\n .push(Dom::elem(\"b\")\n\n .attr(\"class\", \"item\")\n\n .attr(\"id\", \"id\")\n\n .event(\"onclick\", ())\n\n )\n\n .push(Dom::elem(\"i\")\n\n .attr(\"class\", \"item\")\n\n .attr(\"id\", \"id\")\n\n .event(\"onclick\", ())\n\n )\n\n ;\n\n\n\n let new = Dom::elem(\"div\");\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n", "file_path": "tests/tests.rs", "rank": 37, "score": 66048.10900696431 }, { "content": "/// The effect of a side-effecting command.\n\npub trait SideEffect<Message> {\n\n /// Process a side-effecting command.\n\n fn process(self, dispatcher: &Dispatcher<Message, Self>) where Self: Sized;\n\n}\n\n\n\nimpl<Message> SideEffect<Message> for () {\n\n fn process(self, _: &Dispatcher<Message, Self>) { }\n\n}\n\n\n", "file_path": "src/app/side_effect.rs", "rank": 38, "score": 63474.99397295853 }, { "content": "#[derive(Default)]\n\nstruct FakeComponent { }\n\n\n\nimpl FakeComponent {\n\n fn new() -> Box<Self> {\n\n Box::new(FakeComponent { })\n\n }\n\n\n\n fn leaked<Message>() -> &'static mut WebItem<Message> {\n\n Box::leak(Box::new(WebItem::Component(Self::new())))\n\n }\n\n\n\n fn create(_: euca::app::dispatch::Dispatcher<Msg, Cmd>)\n\n -> Box<dyn Component<Msg>>\n\n {\n\n Self::new()\n\n }\n\n\n\n fn create2(_: euca::app::dispatch::Dispatcher<Msg, Cmd>)\n\n -> Box<dyn Component<Msg>>\n\n {\n", "file_path": "tests/tests.rs", "rank": 39, "score": 52384.70699127487 }, { "content": "#[derive(Default)]\n\nstruct Todo {\n\n pending_item: String,\n\n items: Vec<Item>,\n\n pending_edit: Option<(usize, String)>,\n\n filter: Filter,\n\n}\n\n\n\nimpl Todo {\n\n fn with_items(items: Vec<Item>) -> Self {\n\n Todo {\n\n items: items,\n\n .. Todo::default()\n\n }\n\n }\n\n}\n\n\n", "file_path": "examples/todomvc/src/lib.rs", "rank": 40, "score": 50772.97391552891 }, { "content": "#[derive(Default,Serialize,Deserialize)]\n\nstruct Item {\n\n #[serde(rename = \"title\")]\n\n text: String,\n\n #[serde(rename = \"completed\")]\n\n is_complete: bool,\n\n}\n\n\n", "file_path": "examples/todomvc/src/lib.rs", "rank": 41, "score": 50772.82561764281 }, { "content": "#[derive(Clone,Debug)]\n\nenum Command {\n\n FocusPending,\n\n FocusEdit,\n\n PushHistory(String),\n\n UpdateStorage(String),\n\n}\n\n\n\nimpl Update<Message, Command> for Todo {\n\n fn update(&mut self, msg: Message, cmds: &mut Commands<Command>) {\n\n use Message::*;\n\n\n\n match msg {\n\n UpdatePending(text) => {\n\n self.pending_item = text\n\n }\n\n AddTodo => {\n\n self.items.push(Item {\n\n text: self.pending_item.trim().to_owned(),\n\n .. Item::default()\n\n });\n", "file_path": "examples/todomvc/src/lib.rs", "rank": 42, "score": 50642.67368357245 }, { "content": "#[wasm_bindgen_test]\n\nfn from_empty() {\n\n let new = Dom::<_, _, &()>::elem(\"div\")\n\n .push(Dom::elem(\"b\")\n\n .attr(\"class\", \"item\")\n\n .attr(\"id\", \"id1\")\n\n .event(\"onclick\", ())\n\n )\n\n .push(Dom::elem(\"i\")\n\n .attr(\"class\", \"item\")\n\n .attr(\"id\", \"id2\")\n\n .event(\"onclick\", ())\n\n )\n\n ;\n\n\n\n let n = new.dom_iter();\n\n let mut storage = vec![];\n\n let patch_set = diff::diff(iter::empty(), n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n", "file_path": "tests/tests.rs", "rank": 43, "score": 50358.2490691667 }, { "content": "#[wasm_bindgen_test]\n\nfn no_difference() {\n\n let old = Dom::<_, _, &()>::elem(\"div\");\n\n let new = Dom::elem(\"div\");\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CopyElement(leaked_e(\"div\")),\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 44, "score": 50358.2490691667 }, { "content": "#[wasm_bindgen_test]\n\nfn to_empty() {\n\n let old = Dom::<_, _, &()>::elem(\"div\")\n\n .push(Dom::elem(\"b\")\n\n .attr(\"class\", \"item\")\n\n .attr(\"id\", \"id1\")\n\n .event(\"onclick\", ())\n\n )\n\n .push(Dom::elem(\"i\")\n\n .attr(\"class\", \"item\")\n\n .attr(\"id\", \"id2\")\n\n .event(\"onclick\", ())\n\n )\n\n ;\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let patch_set = diff::diff(o, iter::empty(), &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::RemoveElement(leaked_e(\"div\")),\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 45, "score": 50358.2490691667 }, { "content": "#[wasm_bindgen_test]\n\nfn listener_copy() {\n\n let gen1 = iter::empty();\n\n let gen2 = Dom::<_, _, &()>::elem(\"button\").event(\"click\", ());\n\n\n\n let parent = e(\"div\");\n\n let messages = Rc::new(RefCell::new(vec![]));\n\n let app = App::dispatcher_with_vec(Rc::clone(&messages));\n\n let mut storage = vec![];\n\n\n\n let o = gen1.into_iter();\n\n let n = gen2.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n storage = patch_set.apply(&parent, &app);\n\n\n\n match storage[0] {\n\n WebItem::Element(ref node) => {\n\n node.dyn_ref::<web_sys::HtmlElement>()\n\n .expect(\"expected html element\")\n\n .click();\n\n },\n", "file_path": "tests/tests.rs", "rank": 46, "score": 48588.19638751847 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_attributes() {\n\n let old = Dom::<_, _, &()>::elem(\"div\").attr(\"name\", \"value\");\n\n let new = Dom::elem(\"div\").attr(\"name\", \"new value\");\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CopyElement(leaked_e(\"div\")),\n\n Patch::SetAttribute { name: \"name\", value: \"new value\" },\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 47, "score": 48588.19638751847 }, { "content": "#[wasm_bindgen_test]\n\nfn to_empty_vec() {\n\n let old: DomVec<_, _, &()> = vec![\n\n Dom::elem(\"b\")\n\n .attr(\"class\", \"item\")\n\n .attr(\"id\", \"id1\")\n\n .event(\"onclick\", ()),\n\n Dom::elem(\"i\")\n\n .attr(\"class\", \"item\")\n\n .attr(\"id\", \"id2\")\n\n .event(\"onclick\", ()),\n\n ].into();\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let patch_set = diff::diff(o, iter::empty(), &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::RemoveElement(leaked_e(\"b\")),\n\n Patch::RemoveElement(leaked_e(\"i\")),\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 48, "score": 48588.19638751847 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_checked() {\n\n let old = Dom::<_, _, &()>::elem(\"input\").attr(\"checked\", \"false\");\n\n let new = Dom::elem(\"input\").attr(\"checked\", \"false\");\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CopyElement(leaked_e(\"input\")),\n\n Patch::SetAttribute { name: \"checked\", value: \"false\" },\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 49, "score": 48588.19638751847 }, { "content": "#[test]\n\nfn basic_diff() {\n\n let old = iter::empty();\n\n let mut storage = vec![];\n\n\n\n let new = Dom::<_, _, &()>::elem(\"span\");\n\n\n\n let o = old.into_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CreateElement { element: \"span\".into() },\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 50, "score": 48588.19638751847 }, { "content": "#[wasm_bindgen_test]\n\nfn basic_patch_with_element() {\n\n let gen1 = iter::empty();\n\n let gen2 = Dom::<_, Cmd>::elem(\"div\");\n\n let gen3 = Dom::elem(\"div\");\n\n\n\n let parent = e(\"div\");\n\n let app = App::dispatcher();\n\n let mut storage = vec![];\n\n\n\n // first gen create element\n\n let o = gen1.into_iter();\n\n let n = gen2.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n storage = patch_set.apply(&parent, &app);\n\n\n\n match storage[0] {\n\n WebItem::Element(_) => {}\n\n _ => panic!(\"expected node to be created\"),\n\n }\n\n\n", "file_path": "tests/tests.rs", "rank": 51, "score": 47019.85736443008 }, { "content": "#[wasm_bindgen_test]\n\nfn basic_diff_with_element() {\n\n let old = Dom::<_, _, &()>::elem(\"div\");\n\n let new = Dom::elem(\"span\");\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::RemoveElement(leaked_e(\"div\")),\n\n Patch::CreateElement { element: \"span\".into() },\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 52, "score": 47019.85736443008 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_two_components() {\n\n\n\n let old = Dom::<_, _, &()>::elem(\"div\")\n\n .push(Dom::component((), FakeComponent::create));\n\n let new = Dom::elem(\"div\")\n\n .push(Dom::component((), FakeComponent::create2));\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CopyElement(leaked_e(\"div\")),\n\n Patch::RemoveComponent(FakeComponent::leaked()),\n\n Patch::CreateComponent { msg: (), create: FakeComponent::create2 },\n\n Patch::Up,\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 53, "score": 47019.85736443008 }, { "content": "#[wasm_bindgen_test]\n\nfn inner_html_replace() {\n\n let old;\n\n unsafe {\n\n old = Dom::<_, _, &()>::elem(\"div\")\n\n .inner_html(\"html\");\n\n }\n\n let new = Dom::elem(\"div\")\n\n .push(Dom::text(\"html\"));\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CopyElement(leaked_e(\"div\")),\n\n Patch::UnsetInnerHtml,\n\n Patch::CreateText { text: \"html\" },\n\n Patch::Up,\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 54, "score": 47019.85736443008 }, { "content": "#[test]\n\nfn diff_add_text() {\n\n let old = iter::empty();\n\n let mut storage = vec![];\n\n\n\n let new = Dom::<_, _, &()>::elem(\"div\")\n\n .push(Dom::text(\"text\"))\n\n ;\n\n\n\n let o = old.into_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CreateElement { element: \"div\".into() },\n\n Patch::CreateText { text: \"text\".into() },\n\n Patch::Up,\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 55, "score": 47019.85736443008 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_basic_component() {\n\n\n\n let old = Dom::<_, _, &()>::elem(\"div\");\n\n let new = Dom::elem(\"div\")\n\n .push(Dom::component((), FakeComponent::create));\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CopyElement(leaked_e(\"div\")),\n\n Patch::CreateComponent { msg: (), create: FakeComponent::create },\n\n Patch::Up,\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 56, "score": 47019.85736443008 }, { "content": "#[wasm_bindgen_test]\n\nfn inner_html_add() {\n\n let old = Dom::<_, _, &()>::elem(\"div\");\n\n let new;\n\n unsafe {\n\n new = Dom::elem(\"div\")\n\n .inner_html(\"html\");\n\n }\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CopyElement(leaked_e(\"div\")),\n\n Patch::SetInnerHtml(\"html\"),\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 57, "score": 47019.85736443008 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_remove_attr() {\n\n let old = Dom::<_, _, &()>::elem(\"div\")\n\n .attr(\"name\", \"value\")\n\n .push(\"text\");\n\n let new = Dom::elem(\"div\")\n\n .push(\"text\");\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CopyElement(leaked_e(\"div\")),\n\n Patch::RemoveAttribute(\"name\"),\n\n Patch::CreateText { text: \"text\".into() },\n\n Patch::Up,\n\n Patch::RemoveText(leaked_t(\"text\")),\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 58, "score": 47019.85736443008 }, { "content": "#[wasm_bindgen_test]\n\nfn replace_text_with_element() {\n\n let old = Dom::<_, _, &()>::text(\"div\");\n\n let new = Dom::elem(\"div\");\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::RemoveText(leaked_t(\"div\")),\n\n Patch::CreateElement { element: \"div\".into() },\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 59, "score": 47019.85736443008 }, { "content": "#[wasm_bindgen_test]\n\nfn replace_element_with_text() {\n\n let old = Dom::<_, _, &()>::elem(\"div\");\n\n let new = Dom::text(\"div\");\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::RemoveElement(leaked_e(\"div\")),\n\n Patch::CreateText { text: \"div\".into() },\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 60, "score": 47019.85736443008 }, { "content": "#[wasm_bindgen_test]\n\nfn inner_html_remove() {\n\n let old;\n\n unsafe {\n\n old = Dom::<_, _, &()>::elem(\"div\")\n\n .inner_html(\"html\");\n\n }\n\n let new = Dom::elem(\"div\");\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CopyElement(leaked_e(\"div\")),\n\n Patch::UnsetInnerHtml,\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 61, "score": 47019.85736443008 }, { "content": "#[wasm_bindgen_test]\n\nfn inner_html_change() {\n\n let old;\n\n let new;\n\n unsafe {\n\n old = Dom::<_, _, &()>::elem(\"div\")\n\n .inner_html(\"toml\");\n\n new = Dom::elem(\"div\")\n\n .inner_html(\"html\");\n\n }\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CopyElement(leaked_e(\"div\")),\n\n Patch::SetInnerHtml(\"html\"),\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 62, "score": 47019.85736443008 }, { "content": "#[wasm_bindgen_test]\n\nfn inner_html_noop() {\n\n let old;\n\n let new;\n\n unsafe {\n\n old = Dom::<_, _, &()>::elem(\"div\")\n\n .inner_html(\"html\");\n\n new = Dom::elem(\"div\")\n\n .inner_html(\"html\");\n\n }\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CopyElement(leaked_e(\"div\")),\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 63, "score": 47019.85736443008 }, { "content": "#[wasm_bindgen_test]\n\nfn null_patch_with_element() {\n\n let old = Dom::<_, Cmd>::elem(\"div\");\n\n let new = Dom::elem(\"div\");\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n let parent = e(\"div\");\n\n let app = App::dispatcher();\n\n storage = patch_set.apply(&parent, &app);\n\n\n\n match storage[0] {\n\n WebItem::Element(_) => {}\n\n _ => panic!(\"expected node to be created\"),\n\n }\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 64, "score": 47019.85736443008 }, { "content": "#[wasm_bindgen_test]\n\nfn inner_html_replace_children() {\n\n let old;\n\n let new;\n\n unsafe {\n\n old = Dom::<_, _, &()>::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .inner_html(\"html\")\n\n )\n\n ;\n\n new = Dom::elem(\"div\")\n\n .inner_html(\"html\");\n\n }\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CopyElement(leaked_e(\"div\")),\n\n Patch::RemoveElement(leaked_e(\"div\")),\n\n Patch::SetInnerHtml(\"html\"),\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 65, "score": 45620.61011214166 }, { "content": "#[wasm_bindgen_test]\n\nfn inner_html_replace_with_children() {\n\n let old;\n\n let new;\n\n unsafe {\n\n old = Dom::<_, _, &()>::elem(\"div\")\n\n .inner_html(\"html\");\n\n new = Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .inner_html(\"html\")\n\n )\n\n ;\n\n }\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n", "file_path": "tests/tests.rs", "rank": 66, "score": 45620.61011214166 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_add_nested_component() {\n\n let old = Dom::<_, _, &()>::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\"))\n\n .push(Dom::elem(\"div\"))\n\n .push(Dom::elem(\"div\"))\n\n )\n\n .push(Dom::elem(\"div\"));\n\n let new = Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\"))\n\n .push(Dom::elem(\"div\"))\n\n .push(Dom::elem(\"div\"))\n\n .push(Dom::component((), FakeComponent::create))\n\n )\n\n .push(Dom::elem(\"div\"));\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n", "file_path": "tests/tests.rs", "rank": 67, "score": 45620.61011214166 }, { "content": "#[test]\n\nfn diff_empty_create_component() {\n\n let old = iter::empty();\n\n let mut storage = vec![];\n\n\n\n let new = Dom::<_, _, &()>::component((), FakeComponent::create);\n\n\n\n let o = old.into_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n\n compare!(\n\n patch_set,\n\n [\n\n Patch::CreateComponent { msg: (), create: FakeComponent::create },\n\n Patch::Up,\n\n ]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 68, "score": 45620.61011214166 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_remove_nested_component() {\n\n let old = Dom::<_, _, &()>::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\"))\n\n .push(Dom::component((), FakeComponent::create))\n\n .push(Dom::elem(\"div\"))\n\n )\n\n .push(Dom::elem(\"div\"));\n\n let new = Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\"))\n\n .push(Dom::elem(\"div\"))\n\n )\n\n .push(Dom::elem(\"div\"));\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n\n\n", "file_path": "tests/tests.rs", "rank": 69, "score": 45620.61011214166 }, { "content": "#[wasm_bindgen_test]\n\nfn diff_copy_nested_component() {\n\n let old = Dom::<_, _, &()>::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\"))\n\n .push(Dom::component((), FakeComponent::create))\n\n .push(Dom::elem(\"div\"))\n\n )\n\n .push(Dom::elem(\"div\"));\n\n let new = Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\")\n\n .push(Dom::elem(\"div\"))\n\n .push(Dom::component((), FakeComponent::create))\n\n .push(Dom::elem(\"div\"))\n\n )\n\n .push(Dom::elem(\"div\"));\n\n\n\n let mut storage = gen_storage(old.dom_iter());\n\n let o = old.dom_iter();\n\n let n = new.dom_iter();\n\n let patch_set = diff::diff(o, n, &mut storage);\n", "file_path": "tests/tests.rs", "rank": 70, "score": 45620.61011214166 }, { "content": "fn read_items_from_storage() -> Vec<Item> {\n\n let local_storage = web_sys::window()\n\n .expect(\"couldn't get window handle\")\n\n .local_storage()\n\n .expect(\"couldn't get local storage handle\")\n\n .expect_throw(\"local storage not supported?\");\n\n\n\n local_storage.get_item(\"todo-euca\")\n\n .expect_throw(\"error reading from storage\")\n\n .map_or(vec![], |items|\n\n match serde_json::from_str(&items) {\n\n Ok(items) => items,\n\n Err(e) => {\n\n error!(\"error reading items from storage: {}\", e);\n\n vec![]\n\n }\n\n }\n\n )\n\n}\n\n\n", "file_path": "examples/todomvc/src/lib.rs", "rank": 71, "score": 37027.70492301557 }, { "content": "fn compare_patch_vecs<K: fmt::Debug + Eq + ?Sized>(left: &Vec<Patch<Msg, Cmd, &K>>, right: &Vec<Patch<Msg, Cmd, &K>>, dump: &str) {\n\n assert_eq!(left.len(), right.len(), \"lengths don't match\\n{}\", dump);\n\n\n\n for (i, (l, r)) in left.iter().zip(right).enumerate() {\n\n match (l, r) {\n\n (Patch::ReferenceKey(k1), Patch::ReferenceKey(k2)) => {\n\n assert_eq!(k1, k2, \"[{}] ReferenceKey keys don't match\\n{}\", i, dump);\n\n }\n\n (Patch::CreateElement { element: e1 }, Patch::CreateElement { element: e2 }) => {\n\n assert_eq!(e1, e2, \"[{}] unexpected CreateElement\\n{}\", i, dump);\n\n }\n\n (Patch::CopyElement(WebItem::Element(e1)), Patch::CopyElement(WebItem::Element(e2))) => {\n\n assert_eq!(e1.tag_name(), e2.tag_name(), \"[{}] WebItems don't match for CopyElement\\n{}\", i, dump);\n\n }\n\n (Patch::MoveElement(WebItem::Element(e1)), Patch::MoveElement(WebItem::Element(e2))) => {\n\n assert_eq!(e1.tag_name(), e2.tag_name(), \"[{}] WebItems don't match for MoveElement\\n{}\", i, dump);\n\n }\n\n (Patch::SetAttribute { name: n1, value: v1 }, Patch::SetAttribute { name: n2, value: v2 }) => {\n\n assert_eq!(n1, n2, \"[{}] attribute names don't match\\n{}\", i, dump);\n\n assert_eq!(v1, v2, \"[{}] attribute values don't match\\n{}\", i, dump);\n", "file_path": "tests/tests.rs", "rank": 72, "score": 36474.49099076821 }, { "content": "fn e(name: &str) -> web_sys::Element {\n\n web_sys::window().expect(\"expected window\")\n\n .document().expect(\"expected document\")\n\n .create_element(name).expect(\"expected element\")\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 73, "score": 36056.69668873524 }, { "content": "fn t(text: &str) -> web_sys::Text {\n\n web_sys::window().expect(\"expected window\")\n\n .document().expect(\"expected document\")\n\n .create_text_node(text)\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 74, "score": 36056.69668873524 }, { "content": "fn counter(count: i32) -> Dom<Msg> {\n\n Dom::elem(\"div\")\n\n .push(count.to_string())\n\n}\n\n\n\nimpl Render<DomVec<Msg>> for Model {\n\n fn render(&self) -> DomVec<Msg> {\n\n vec![\n\n button(\"+\", Msg::Increment),\n\n counter(self.0),\n\n button(\"-\", Msg::Decrement),\n\n ].into()\n\n }\n\n}\n\n\n\ncfg_if! {\n\n if #[cfg(feature = \"console_error_panic_hook\")] {\n\n fn set_panic_hook() {\n\n console_error_panic_hook::set_once();\n\n }\n", "file_path": "examples/counter/src/lib.rs", "rank": 75, "score": 33894.21550628993 }, { "content": " fn detach(&mut self, app: &Dispatcher<Message, Command>);\n\n}\n\n\n\nimpl<Message, Command> Detach<Message> for Rc<RefCell<Box<dyn Application<Message, Command>>>>\n\nwhere\n\n Message: fmt::Debug + Clone + PartialEq,\n\n Command: SideEffect<Message>,\n\n{\n\n /// Detach the app from the dom.\n\n ///\n\n /// Any elements that were created will be destroyed and event handlers will be removed.\n\n fn detach(&self) {\n\n let mut app = self.borrow_mut();\n\n Application::detach(&mut **app, &self.into());\n\n }\n\n}\n", "file_path": "src/app/application.rs", "rank": 76, "score": 30248.45371841682 }, { "content": "//! Abstraction of a wasm application.\n\n\n\nuse crate::app::dispatch::Dispatcher;\n\nuse crate::app::side_effect::{SideEffect, Commands};\n\nuse crate::app::detach::Detach;\n\n\n\nuse web_sys;\n\nuse wasm_bindgen::prelude::*;\n\nuse std::rc::Rc;\n\nuse std::cell::RefCell;\n\nuse std::fmt;\n\n\n\n/// A pending render.\n\npub type ScheduledRender<Command> = (Vec<Command>, i32, Closure<dyn FnMut(f64)>);\n\n\n\n/// All of the functions one might perform on a wasm application.\n", "file_path": "src/app/application.rs", "rank": 77, "score": 30245.53961095326 }, { "content": "//! Detach an app from the DOM.\n\n\n\n/// Detach an app from the DOM.\n", "file_path": "src/app/detach.rs", "rank": 78, "score": 30241.13194279582 }, { "content": " // request an animation frame for rendering if we don't already have a request out\n\n if let Some((ref mut cmds, _, _)) = Application::get_scheduled_render(&mut **app) {\n\n cmds.extend(post_render);\n\n }\n\n else {\n\n let dispatcher = self.clone();\n\n\n\n let window = web_sys::window()\n\n .expect_throw(\"couldn't get window handle\");\n\n\n\n let closure = Closure::wrap(\n\n Box::new(move |_| {\n\n let mut app = dispatcher.app.borrow_mut();\n\n let commands = Application::render(&mut **app, &dispatcher);\n\n for cmd in commands {\n\n Application::process(&**app, cmd, &dispatcher);\n\n }\n\n }) as Box<dyn FnMut(f64)>\n\n );\n\n\n", "file_path": "src/app/dispatch.rs", "rank": 79, "score": 30201.356245787563 }, { "content": " fn from(app: &Rc<RefCell<Box<dyn Application<Message, Command>>>>) -> Self {\n\n Dispatcher {\n\n app: Rc::clone(app),\n\n pending: Rc::new(RefCell::new(Vec::new())),\n\n }\n\n }\n\n}\n\n\n\nimpl<Message, Command> Dispatcher<Message, Command>\n\nwhere\n\n Command: SideEffect<Message> + 'static,\n\n Message: fmt::Debug + Clone + PartialEq + 'static,\n\n{\n\n /// Dispatch a message to the associated app.\n\n pub fn dispatch(&self, msg: Message) {\n\n // queue the message\n\n self.pending.borrow_mut().push(msg);\n\n\n\n // try to borrow the app\n\n let mut app = match self.app.try_borrow_mut() {\n", "file_path": "src/app/dispatch.rs", "rank": 80, "score": 30199.292433857492 }, { "content": "//! Dispatch messages via a shared app handle.\n\n\n\nuse web_sys;\n\nuse wasm_bindgen::prelude::*;\n\nuse wasm_bindgen::JsCast;\n\n\n\nuse std::rc::Rc;\n\nuse std::cell::RefCell;\n\nuse std::fmt;\n\nuse crate::app::Application;\n\nuse crate::app::side_effect::{SideEffect, Commands};\n\n\n\n/// A shared app handle.\n\n///\n\n/// Since events need to be dispatched from event handlers in the browser, they need a way to relay\n\n/// messages back to the app.\n\npub struct Dispatcher<Message, Command> {\n\n app: Rc<RefCell<Box<dyn Application<Message, Command>>>>,\n\n pending: Rc<RefCell<Vec<Message>>>,\n\n}\n", "file_path": "src/app/dispatch.rs", "rank": 81, "score": 30194.724643429843 }, { "content": "\n\nimpl<Message, Command> Clone for Dispatcher<Message, Command> {\n\n fn clone(&self) -> Self {\n\n Dispatcher {\n\n app: Rc::clone(&self.app),\n\n pending: Rc::clone(&self.pending),\n\n }\n\n }\n\n}\n\n\n\nimpl<Message, Command> From<Rc<RefCell<Box<dyn Application<Message, Command>>>>> for Dispatcher<Message, Command> {\n\n fn from(app: Rc<RefCell<Box<dyn Application<Message, Command>>>>) -> Self {\n\n Dispatcher {\n\n app: app,\n\n pending: Rc::new(RefCell::new(Vec::new())),\n\n }\n\n }\n\n}\n\n\n\nimpl<Message, Command> From<&Rc<RefCell<Box<dyn Application<Message, Command>>>>> for Dispatcher<Message, Command> {\n", "file_path": "src/app/dispatch.rs", "rank": 82, "score": 30193.440293110096 }, { "content": " Ok(app) => app,\n\n // already borrowed, the current borrower will process the queue\n\n Err(_) => return,\n\n };\n\n\n\n // now process queued messages\n\n loop {\n\n // grab the first pending message (if any)\n\n let msg = match self.pending.borrow_mut().pop() {\n\n Some(msg) => msg,\n\n None => break,\n\n };\n\n\n\n let commands = Application::update(&mut **app, msg);\n\n\n\n let Commands {\n\n immediate,\n\n post_render,\n\n } = commands;\n\n\n", "file_path": "src/app/dispatch.rs", "rank": 83, "score": 30188.060652183147 }, { "content": "//! Traits to implement on a model to allow it to interact with an application.\n\n\n\nuse crate::app::side_effect::Commands;\n\n\n\n/// Process a message that updates the model.\n", "file_path": "src/app/model.rs", "rank": 84, "score": 30187.667834619468 }, { "content": " let handle = window.request_animation_frame(closure.as_ref().unchecked_ref())\n\n .expect_throw(\"error with requestion_animation_frame\");\n\n\n\n Application::set_scheduled_render(&mut **app, (post_render, handle, closure));\n\n }\n\n\n\n // execute side effects\n\n for cmd in immediate {\n\n Application::process(&**app, cmd, &self);\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/app/dispatch.rs", "rank": 85, "score": 30186.4867861479 }, { "content": "fn button(text: &str, msg: Msg) -> Dom<Msg> {\n\n Dom::elem(\"button\")\n\n .event(\"click\", msg)\n\n .push(text)\n\n}\n\n\n", "file_path": "examples/counter/src/lib.rs", "rank": 86, "score": 29997.858705345832 }, { "content": "#[derive(PartialEq,Clone,Debug)]\n\nenum Message {\n\n UpdatePending(String),\n\n AddTodo,\n\n RemoveTodo(usize),\n\n ToggleTodo(usize),\n\n EditTodo(usize),\n\n UpdateEdit(String),\n\n SaveEdit,\n\n AbortEdit,\n\n ClearCompleted,\n\n ToggleAll,\n\n ShowAll(bool),\n\n ShowActive(bool),\n\n ShowCompleted(bool),\n\n ItemsChanged,\n\n}\n\n\n", "file_path": "examples/todomvc/src/lib.rs", "rank": 87, "score": 26550.098559971448 }, { "content": "\n\n /// A funciton to optionally map a command from the component to the parent.\n\n #[must_use]\n\n pub fn unmap(mut self, f: fn(Command) -> Option<ParentMessage>) -> Self {\n\n self.unmap = f;\n\n self\n\n }\n\n\n\n /// Create a component from the given app, and it's parent.\n\n #[must_use]\n\n pub fn create<ParentCommand, Model, DomTree, K>(self, model: Model, parent_app: Dispatcher<ParentMessage, ParentCommand>)\n\n -> Box<dyn Component<ParentMessage>>\n\n where\n\n ParentMessage: fmt::Debug + Clone + PartialEq + 'static,\n\n ParentCommand: SideEffect<ParentMessage> + 'static,\n\n Message: fmt::Debug + Clone + PartialEq + 'static,\n\n Command: SideEffect<Message> + fmt::Debug + Clone + 'static,\n\n Model: Update<Message, Command> + Render<DomTree> + 'static,\n\n DomTree: DomIter<Message, Command, K> + 'static,\n\n K: Eq + Hash + 'static,\n", "file_path": "src/component.rs", "rank": 92, "score": 34.11652080064514 }, { "content": " messages: messages,\n\n render: None,\n\n }\n\n ) as Box<dyn Application<Msg, Cmd>>)))\n\n }\n\n}\n\n\n\nimpl Application<Msg, Cmd> for App {\n\n fn update(&mut self, msg: Msg) -> Commands<Cmd> {\n\n self.messages.borrow_mut().push(msg);\n\n Commands::default()\n\n }\n\n fn render(&mut self, _app: &Dispatcher<Msg, Cmd>) -> Vec<Cmd> { vec![] }\n\n fn process(&self, _cmd: Cmd, _app: &Dispatcher<Msg, Cmd>) { }\n\n fn get_scheduled_render(&mut self) -> &mut Option<ScheduledRender<Cmd>> {\n\n &mut self.render\n\n }\n\n fn set_scheduled_render(&mut self, handle: ScheduledRender<Cmd>) {\n\n self.render = Some(handle);\n\n }\n\n fn push_listener(&mut self, _listener: (String, Closure<dyn FnMut(web_sys::Event)>)) { }\n\n fn node(&self) -> Option<web_sys::Node> { None }\n\n fn nodes(&self) -> Vec<web_sys::Node> { vec![] }\n\n fn create(&mut self, _app: &Dispatcher<Msg, Cmd>) -> Vec<web_sys::Node> { vec![] }\n\n fn detach(&mut self, _app: &Dispatcher<Msg, Cmd>) { }\n\n}\n\n\n\n/// Some helpers to make testing a model easier.\n", "file_path": "src/test.rs", "rank": 93, "score": 33.722108373999966 }, { "content": " }\n\n\n\n assert_eq!(node_stack.depth(), 0, \"the stack should be empty\");\n\n node_stack.pop_pending()\n\n }\n\n\n\n /// Prep the given PatchSet by creating any elements in the set and placing them in Storage.\n\n /// While elements will be removed from the given parent, nothing will be attached. Events\n\n /// will be dispatched via the given [`Dispatch`]er.\n\n ///\n\n /// [`Dispatch`]: ../app/trait.Dispatch.html\n\n pub fn prepare(self, app: &Dispatcher<Message, Command>) -> (Storage<Message>, Vec<web_sys::Node>) where\n\n Message: Clone + PartialEq + fmt::Debug + 'static,\n\n Command: SideEffect<Message> + fmt::Debug + 'static,\n\n EventHandler<'a, Message>: Clone,\n\n {\n\n let mut storage = vec![];\n\n let PatchSet { patches, mut keyed } = self;\n\n\n\n let nodes = Self::process_patch_list(patches, &mut keyed, app, &mut storage);\n", "file_path": "src/patch.rs", "rank": 95, "score": 32.04582801731965 }, { "content": " pub events: Vec<Event<Message>>,\n\n /// Children of this node.\n\n pub children: Vec<Dom<Message, Command, Key>>,\n\n}\n\n\n\nimpl<Message, Command, Key> Dom<Message, Command, Key> {\n\n /// Create a new DOM element node.\n\n pub fn elem(element: &'static str) -> Self {\n\n Dom {\n\n element: Node::elem(element),\n\n key: None,\n\n events: vec![],\n\n attributes: vec![],\n\n children: vec![],\n\n inner_html: None,\n\n }\n\n }\n\n\n\n /// Create a new DOM text node.\n\n pub fn text(value: impl Into<String>) -> Self {\n", "file_path": "src/dom.rs", "rank": 96, "score": 30.064006623569277 } ]
Rust
world/src/consensus/ethash.rs
Fantom-foundation/fantom-rust-vm
a68fbe71f63365a8f3d05d2d84990e20a0bce45d
#![allow(dead_code)] #![allow(clippy::many_single_char_names)] use bigint_miner::{H256, H512, H64, U256}; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use sha3::{Digest, Keccak256, Keccak512}; use std::ops::BitXor; use super::miller_rabin::is_prime; const DATASET_BYTES_INIT: usize = 1_073_741_824; const DATASET_BYTES_GROWTH: usize = 8_388_608; const CACHE_BYTES_INIT: usize = 16_777_216; const CACHE_BYTES_GROWTH: usize = 131_072; const CACHE_MULTIPLIER: usize = 1024; const MIX_BYTES: usize = 128; const WORD_BYTES: usize = 4; const HASH_BYTES: usize = 64; const DATASET_PARENTS: usize = 256; const CACHE_ROUNDS: usize = 3; const ACCESSES: usize = 64; pub fn get_cache_size(epoch: usize) -> usize { let mut sz = CACHE_BYTES_INIT + CACHE_BYTES_GROWTH * epoch; sz -= HASH_BYTES; while !is_prime(sz / HASH_BYTES) { sz -= 2 * HASH_BYTES; } sz } pub fn get_full_size(epoch: usize) -> usize { let mut sz = DATASET_BYTES_INIT + DATASET_BYTES_GROWTH * epoch; sz -= MIX_BYTES; while !is_prime(sz / MIX_BYTES) { sz -= 2 * MIX_BYTES } sz } fn fill_sha512(input: &[u8], a: &mut [u8], from_index: usize) { let mut hasher = Keccak512::default(); hasher.input(input); let out = hasher.result(); for i in 0..out.len() { a[from_index + i] = out[i]; } } fn fill_sha256(input: &[u8], a: &mut [u8], from_index: usize) { let mut hasher = Keccak256::default(); hasher.input(input); let out = hasher.result(); for i in 0..out.len() { a[from_index + i] = out[i]; } } pub fn make_cache(cache: &mut [u8], seed: H256) { assert!(cache.len() % HASH_BYTES == 0); let n = cache.len() / HASH_BYTES; fill_sha512(&seed, cache, 0); for i in 1..n { let (last, next) = cache.split_at_mut(i * 64); fill_sha512(&last[(last.len() - 64)..], next, 0); } for _ in 0..CACHE_ROUNDS { for i in 0..n { let v = ((&cache[(i * 64)..]).read_u32::<LittleEndian>().unwrap() as usize) % n; let mut r = [0u8; 64]; for j in 0..64 { let a = cache[((n + i - 1) % n) * 64 + j]; let b = cache[v * 64 + j]; r[j] = a.bitxor(b); } fill_sha512(&r, cache, i * 64); } } } const FNV_PRIME: u32 = 0x0100_0193; fn fnv(v1: u32, v2: u32) -> u32 { let v1 = u64::from(v1); let v2 = u64::from(v2); ((v1 * 0x0100_0000) | (v1 * 0x193) | v2) as u32 } fn fnv64(a: [u8; 64], b: [u8; 64]) -> [u8; 64] { let mut r = [0u8; 64]; for i in 0..(64 / 4) { let j = i * 4; let _a32 = (&a[j..]).read_u32::<LittleEndian>().unwrap(); let _b32 = (&b[j..]).read_u32::<LittleEndian>().unwrap(); let _ = (&mut r[j..]).write_u32::<LittleEndian>(fnv( (&a[j..]).read_u32::<LittleEndian>().unwrap(), (&b[j..]).read_u32::<LittleEndian>().unwrap(), )); } r } fn fnv128(a: [u8; 128], b: [u8; 128]) -> [u8; 128] { let mut r = [0u8; 128]; for i in 0..(128 / 4) { let j = i * 4; let _a32 = (&a[j..]).read_u32::<LittleEndian>().unwrap(); let _b32 = (&b[j..]).read_u32::<LittleEndian>().unwrap(); let _ = (&mut r[j..]).write_u32::<LittleEndian>(fnv( (&a[j..]).read_u32::<LittleEndian>().unwrap(), (&b[j..]).read_u32::<LittleEndian>().unwrap(), )); } r } fn u8s_to_u32(a: &[u8]) -> u32 { let _n = a.len(); (u32::from(a[0]) + u32::from(a[1])) << (8 + u32::from(a[2])) } pub fn calc_dataset_item(cache: &[u8], i: usize) -> H512 { debug_assert!(cache.len() % 64 == 0); let n = cache.len() / 64; let r = HASH_BYTES / WORD_BYTES; let mut mix = [0u8; 64]; for j in 0..64 { mix[j] = cache[(i % n) * 64 + j]; } let mix_first32 = mix.as_ref().read_u32::<LittleEndian>().unwrap().bitxor(i as u32); let _ = mix.as_mut().write_u32::<LittleEndian>(mix_first32); { let mut remix = [0u8; 64]; remix[..64].clone_from_slice(&mix[..64]); fill_sha512(&remix, &mut mix, 0); } for j in 0..DATASET_PARENTS { let cache_index = fnv( (i.bitxor(j) & (u32::max_value() as usize)) as u32, (&mix[(j % r * 4)..]).read_u32::<LittleEndian>().unwrap(), ) as usize; let mut item = [0u8; 64]; let cache_index = cache_index % n; for i in 0..64 { item[i] = cache[cache_index * 64 + i]; } mix = fnv64(mix, item); } let mut z = [0u8; 64]; fill_sha512(&mix, &mut z, 0); H512::from(z) } pub fn make_dataset(dataset: &mut [u8], cache: &[u8]) { let n = dataset.len() / HASH_BYTES; for i in 0..n { let z = calc_dataset_item(cache, i); for j in 0..64 { dataset[i * 64 + j] = z[j]; } } } pub fn hashimoto<F: Fn(usize) -> H512>(header_hash: H256, nonce: H64, full_size: usize, lookup: F) -> (H256, H256) { let n = full_size / HASH_BYTES; let w = MIX_BYTES / WORD_BYTES; const MIXHASHES: usize = MIX_BYTES / HASH_BYTES; let s = { let mut hasher = Keccak512::default(); let mut reversed_nonce: Vec<u8> = nonce.as_ref().into(); reversed_nonce.reverse(); hasher.input(&header_hash); hasher.input(&reversed_nonce); hasher.result() }; let mut mix = [0u8; MIX_BYTES]; for i in 0..MIXHASHES { for j in 0..64 { mix[i * HASH_BYTES + j] = s[j]; } } for i in 0..ACCESSES { let p = (fnv( (i as u32).bitxor(s.as_ref().read_u32::<LittleEndian>().unwrap()), (&mix[(i % w * 4)..]).read_u32::<LittleEndian>().unwrap(), ) as usize) % (n / MIXHASHES) * MIXHASHES; let mut newdata = [0u8; MIX_BYTES]; for j in 0..MIXHASHES { let v = lookup(p + j); for k in 0..64 { newdata[j * 64 + k] = v[k]; } } mix = fnv128(mix, newdata); } let mut cmix = [0u8; MIX_BYTES / 4]; for i in 0..(MIX_BYTES / 4 / 4) { let j = i * 4; let a = fnv( (&mix[(j * 4)..]).read_u32::<LittleEndian>().unwrap(), (&mix[((j + 1) * 4)..]).read_u32::<LittleEndian>().unwrap(), ); let b = fnv(a, (&mix[((j + 2) * 4)..]).read_u32::<LittleEndian>().unwrap()); let c = fnv(b, (&mix[((j + 3) * 4)..]).read_u32::<LittleEndian>().unwrap()); let _ = (&mut cmix[j..]).write_u32::<LittleEndian>(c); } let result = { let mut hasher = Keccak256::default(); hasher.input(&s); hasher.input(&cmix); let r = hasher.result(); let mut z = [0u8; 32]; for i in 0..32 { z[i] = r[i]; } z }; (H256::from(cmix), H256::from(result)) } pub fn hashimoto_light(header_hash: H256, nonce: H64, full_size: usize, cache: &[u8]) -> (H256, H256) { hashimoto(header_hash, nonce, full_size, |i| calc_dataset_item(cache, i)) } pub fn hashimoto_full(header_hash: H256, nonce: H64, full_size: usize, dataset: &[u8]) -> (H256, H256) { hashimoto(header_hash, nonce, full_size, |i| { let mut r = [0u8; 64]; for j in 0..64 { r[j] = dataset[i * 64 + j]; } H512::from(r) }) } pub fn cross_boundary(val: U256) -> U256 { if val <= U256::one() { U256::max_value() } else { ((U256::one() << 255) / val) << 1 } } pub fn mine( header: &block::Header, full_size: usize, dataset: &[u8], nonce_start: H64, difficulty: U256, ) -> (H64, H256) { let target = cross_boundary(difficulty); let header = rlp::encode(header).to_vec(); let mut nonce_current = nonce_start; loop { let (_, result) = hashimoto( H256::from(Keccak256::digest(&header).as_slice()), nonce_current, full_size, |i| { let mut r = [0u8; 64]; for j in 0..64 { r[j] = dataset[i * 64 + j]; } H512::from(r) }, ); let result_cmp: U256 = result.into(); if result_cmp <= target { return (nonce_current, result); } let nonce_u64: u64 = nonce_current.into(); nonce_current = H64::from(nonce_u64 + 1); } } #[allow(clippy::clone_on_copy)] pub fn get_seedhash(epoch: usize) -> H256 { let mut s = [0u8; 32]; for _i in 0..epoch { fill_sha256(&s.clone(), &mut s, 0); } H256::from(s.as_ref()) } #[cfg(test)] mod tests {}
#![allow(dead_code)] #![allow(clippy::many_single_char_names)] use bigint_miner::{H256, H512, H64, U256}; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use sha3::{Digest, Keccak256, Keccak512}; use std::ops::BitXor; use super::miller_rabin::is_prime; const DATASET_BYTES_INIT: usize = 1_073_741_824; const DATASET_BYTES_GROWTH: usize = 8_388_608; const CACHE_BYTES_INIT: usize = 16_777_216; const CACHE_BYTES_GROWTH: usize = 131_072; const CACHE_MULTIPLIER: usize = 1024; const MIX_BYTES: usize = 128; const WORD_BYTES: usize = 4; const HASH_BYTES: usize = 64; const DATASET_PARENTS: usize = 256; const CACHE_ROUNDS: usize = 3; const ACCESSES: usize = 64; pub fn get_cache_size(epoch: usize) -> usize { let mut sz = CACHE_BYTES_INIT + CACHE_BYTES_GROWTH * epoch; sz -= HASH_BYTES; while !is_prime(sz / HASH_BYTES) { sz -= 2 * HASH_BYTES; } sz } pub fn get_full_size(epoch: usize) -> usize { let mut sz = DATASET_BYTES_INIT + DATASET_BYTES_GROWTH * epoch; sz -= MIX_BYTES; while !is_prime(sz / MIX_BYTES) { sz -= 2 * MIX_BYTES } sz } fn fill_sha512(input: &[u8], a: &mut [u8], from_index: usize) { let mut hasher = Keccak512::default(); hasher.input(input); let out = hasher.result(); for i in 0..out.len() { a[from_index + i] = out[i]; } } fn fill_sha256(input: &[u8], a: &mut [u8], from_index: usize) { let mut hasher = Keccak256::default(); hasher.input(input); let out = hasher.result(); for i in 0..out.len() { a[from_index + i] = out[i]; } } pub fn make_cache(cache: &mut [u8], seed: H256) { assert!(cache.len() % HASH_BYTES == 0); let n = cache.len() / HASH_BYTES; fill_sha512(&seed, cache, 0); for i in 1..n { let (last, next) = cache.split_at_mut(i * 64); fill_sha512(&last[(last.len() - 64)..], next, 0); } for _ in 0..CACHE_ROUNDS { for i in 0..n { let v = ((&cache[(i * 64)..]).read_u32::<LittleEndian>().unwrap() as usize) % n; let mut r = [0u8; 64]; for j in 0..64 { let a = cache[((n + i - 1) % n) * 64 + j]; let b = cache[v * 64 + j]; r[j] = a.bitxor(b); } fill_sha512(&r, cache, i * 64); } } } const FNV_PRIME: u32 = 0x0100_0193; fn fnv(v1: u32, v2: u32) -> u32 { let v1 = u64::from(v1); let v2 = u64::from(v2); ((v1 * 0x0100_0000) | (v1 * 0x193) | v2) as u32 } fn fnv64(a: [u8; 64], b: [u8; 64]) -> [u8; 64] { let mut r = [0u8; 64]; for i in 0..(64 / 4) { let j = i * 4; let _a32 = (&a[j..]).read_u32::<LittleEndian>().unwrap(); let _b32 = (&b[j..]).read_u32::<LittleEndian>().unwrap(); let _ = (&mut r[j..]).write_u32::<LittleEndian>(fnv( (&a[j..]).read_u32::<LittleEndian>().unwrap(), (&b[j..]).read_u32::<LittleEndian>().unwrap(), )); } r } fn fnv128(a: [u8; 128], b: [u8; 128]) -> [u8; 128] { let mut r = [0u8; 128]; for i in 0..(128 / 4) { let j = i * 4; let _a32 = (&a[j..]).read_u32::<LittleEndian>().unwrap(); let _b32 = (&b[j..]).read_u32::<LittleEndian>().unwrap(); let _ = (&mut r[j..]).write_u32::<LittleEndian>(fnv( (&a[j..]).read_u32::<LittleEndian>().unwrap(), (&b[j..]).read_u32::<LittleEndian>().unwrap(), )); } r } fn u8s_to_u32(a: &[u8]) -> u32 { let _n = a.len(); (u32::from(a[0]) + u32::from(a[1])) << (8 + u32::from(a[2])) } pub fn calc_dataset_item(cache: &[u8], i: usize) -> H512 { debug_assert!(cache.len() % 64 == 0); let n = cache.len() / 64; let r = HASH_BYTES / WORD_BYTES; let mut mix = [0u8; 64]; for j in 0..64 { mix[j] = cache[(i % n) * 64 + j]; } let mix_first32 = mix.as_ref().read_u32::<LittleEndian>().unwrap().bitxor(i as u32); let _ = mix.as_mut().write_u32::<LittleEndian>(mix_first32); { let mut remix = [0u8; 64]; remix[..64].clone_from_slice(&mix[..64]); fill_sha512(&remix, &mut mix, 0); } for j in 0..DATASET_PARENTS { let cache_index = fnv( (i.bitxor(j) & (u32::max_value() as usize)) as u32, (&mix[(j % r * 4)..]).read_u32::<LittleEndian>().unwrap(), ) as usize; let mut item = [0u8; 64]; let cache_index = cache_index % n; for i in 0..64 { item[i] = cache[cache_index * 64 + i]; } mix = fnv64(mix, item); } let mut z = [0u8; 64]; fill_sha512(&mix, &mut z, 0); H512::from(z) } pub fn make_dataset(dataset: &mut [u8], cache: &[u8]) { let n = dataset.len() / HASH_BYTES; for i in 0..n { let z = calc_dataset_item(cache, i); for j in 0..64 { dataset[i * 64 + j] = z[j]; } } } pub fn hashimoto<F: Fn(usize) -> H512>(header_hash: H256, nonce: H64, full_size: usize, lookup: F) -> (H256, H256) { let n = full_size / HASH_BYTES; let w = MIX_BYTES / WORD_BYTES; const MIXHASHES: usize = MIX_BYTES / HASH_BYTES; let s = { let mut hasher = Keccak512::default(); let mut reversed_nonce: Vec<u8> = nonce.as_ref().into(); reversed_nonce.reverse(); hasher.input(&header_hash); hasher.input(&reversed_nonce); hasher.result() }; let mut mix = [0u8; MIX_BYTES]; for i in 0..MIXHASHES { for j in 0..64 { mix[i * HASH_BYTES + j] = s[j]; } } for i in 0..ACCESSES { let p = (fnv( (i as u32).bitxor(s.as_ref().read_u32::<LittleEndian>().unwrap()), (&mix[(i % w * 4)..]).read_u32::<LittleEndian>().unwrap(), ) as usize) % (n / MIXHASHES) * MIXHASHES; let mut newdata = [0u8; MIX_BYTES]; for j in 0..MIXHASHES { let v = lookup(p + j); for k in 0..64 { newdata[j * 64 + k] = v[k]; } } mix = fnv128(mix, newdata); } let mut cmix = [0u8; MIX_BYTES / 4]; for i in 0..(MIX_BYTES / 4 / 4) { let j = i * 4; let a = fnv( (&mix[(j * 4)..]).read_u32::<LittleEndian>().unwrap(), (&mix[((j + 1) * 4)..]).read_u32::<LittleEndian>().unwrap(), ); let b = fnv(a, (&mix[((j + 2) * 4)..]).read_u32::<LittleEndian>().unwrap()); let c = fnv(b, (&mix[((j + 3) * 4)..]).read_u32::<LittleEndian>().unwrap()); let _ = (&mut cmix[j..]).write_u32::<LittleEndian>(c); } let result = { let mut hasher = Keccak256::default(); hasher.input(&s); hasher.input(&cmix); let r = hasher.result(); let mut z = [0u8; 32]; for i in 0..32 { z[i] = r[i]; } z }; (H256::from(cmix), H256::from(result)) } pub fn hashimoto_light(header_hash: H256, nonce: H64, full_size: usize, cache: &[u8]) -> (H256, H256) { hashimoto(header_hash, nonce, full_size, |i| calc_dataset_item(cache, i)) } pub fn hashimoto_full(header_hash: H256, nonce: H64, full_size: usize, dataset: &[u8]) -> (H256, H256) { hashimoto(header_hash, nonce, full_size, |i| { let mut r = [0u8; 64]; for j in 0..64 { r[j] = dataset[i * 64 + j]; } H512::from(r) }) }
pub fn mine( header: &block::Header, full_size: usize, dataset: &[u8], nonce_start: H64, difficulty: U256, ) -> (H64, H256) { let target = cross_boundary(difficulty); let header = rlp::encode(header).to_vec(); let mut nonce_current = nonce_start; loop { let (_, result) = hashimoto( H256::from(Keccak256::digest(&header).as_slice()), nonce_current, full_size, |i| { let mut r = [0u8; 64]; for j in 0..64 { r[j] = dataset[i * 64 + j]; } H512::from(r) }, ); let result_cmp: U256 = result.into(); if result_cmp <= target { return (nonce_current, result); } let nonce_u64: u64 = nonce_current.into(); nonce_current = H64::from(nonce_u64 + 1); } } #[allow(clippy::clone_on_copy)] pub fn get_seedhash(epoch: usize) -> H256 { let mut s = [0u8; 32]; for _i in 0..epoch { fill_sha256(&s.clone(), &mut s, 0); } H256::from(s.as_ref()) } #[cfg(test)] mod tests {}
pub fn cross_boundary(val: U256) -> U256 { if val <= U256::one() { U256::max_value() } else { ((U256::one() << 255) / val) << 1 } }
function_block-full_function
[ { "content": "fn mod_exp(mut x: usize, mut d: usize, n: usize) -> usize {\n\n let mut ret: usize = 1;\n\n while d != 0 {\n\n if d % 2 == 1 {\n\n ret = mod_mul(ret, x, n)\n\n }\n\n d /= 2;\n\n x = mod_sqr(x, n);\n\n }\n\n ret\n\n}\n\n\n", "file_path": "world/src/consensus/miller_rabin.rs", "rank": 16, "score": 129398.2401063249 }, { "content": "pub fn is_prime(n: usize) -> bool {\n\n const HINT: &[usize] = &[2];\n\n\n\n // we have a strict upper bound, so we can just use the witness\n\n // table of Pomerance, Selfridge & Wagstaff and Jeaschke to be as\n\n // efficient as possible, without having to fall back to\n\n // randomness.\n\n const WITNESSES: &[(usize, &[usize])] = &[\n\n (2_046, HINT),\n\n (1_373_652, &[2, 3]),\n\n (9_080_190, &[31, 73]),\n\n (25_326_000, &[2, 3, 5]),\n\n (4_759_123_140, &[2, 7, 61]),\n\n (1_112_004_669_632, &[2, 13, 23, 1_662_803]),\n\n (2_152_302_898_746, &[2, 3, 5, 7, 11]),\n\n (3_474_749_660_382, &[2, 3, 5, 7, 11, 13]),\n\n (341_550_071_728_320, &[2, 3, 5, 7, 11, 13, 17]),\n\n (0xFFFF_FFFF_FFFF_FFFF, &[2, 3, 5, 7, 11, 13, 17, 19, 23]),\n\n ];\n\n\n", "file_path": "world/src/consensus/miller_rabin.rs", "rank": 17, "score": 117942.82245084507 }, { "content": "/// Prompts the user for a passphrase. They will have to enter this to do anything with\n\n/// their account.\n\npub fn get_passphrase() -> Result<Password, String> {\n\n const STDIN_ERROR: &str = \"Unable to ask for password on non-interactive terminal.\";\n\n print!(\"Enter password: \");\n\n io::stdout().flush().map_err(|_| \"Error flushing stdout\".to_owned())?;\n\n let password = read_password().map_err(|_| STDIN_ERROR.to_owned())?.into();\n\n print!(\"Repeat password: \");\n\n io::stdout().flush().map_err(|_| \"Error flushing stdout\".to_owned())?;\n\n let password_repeat = read_password().map_err(|_| STDIN_ERROR.to_owned())?.into();\n\n if password != password_repeat {\n\n return Err(\"Passwords do not match!\".into());\n\n }\n\n Ok(password)\n\n}\n\n\n", "file_path": "client/src/keys/mod.rs", "rank": 18, "score": 115295.12477281861 }, { "content": "/// Creates a temporary DB. Mostly useful for testing.\n\npub fn create_temporary_db() -> Result<(RDB, Store), StoreError> {\n\n let tempdir = TempDir::new(\"testing\").unwrap();\n\n let root = tempdir.path();\n\n let created_arc = Manager::singleton().write().unwrap().get_or_create(root, Rkv::new)?;\n\n if let Ok(k) = created_arc.read() {\n\n if let Ok(a) = k.open_or_create(\"store\") {\n\n return Ok((created_arc.clone(), a));\n\n }\n\n }\n\n Err(StoreError::DirectoryDoesNotExistError(root.into()))\n\n}\n\n\n", "file_path": "world/src/db.rs", "rank": 19, "score": 107024.40679705731 }, { "content": "fn modulo(mut a: U128, m: usize) -> usize {\n\n if a.hi >= m {\n\n a.hi -= (a.hi / m) * m;\n\n }\n\n let mut x = a.hi;\n\n let mut y = a.lo;\n\n for _ in 0..64 {\n\n let t = (x as isize >> 63) as usize;\n\n x = (x << 1) | (y >> 63);\n\n y <<= 1;\n\n if (x | t) >= m {\n\n x = x.wrapping_sub(m);\n\n y += 1;\n\n }\n\n }\n\n x\n\n}\n", "file_path": "world/src/consensus/miller_rabin.rs", "rank": 20, "score": 104019.86503295787 }, { "content": "/// This generates a random public/private keypair, and is used when creating a new account.\n\npub fn generate_random_keypair() -> Result<(PublicKey, SecretKey), Error> {\n\n let context_flag = secp256k1::ContextFlag::Full;\n\n let context = secp256k1::Secp256k1::with_caps(context_flag);\n\n let mut rng = OsRng::new().expect(\"OsRng\");\n\n match context.generate_keypair(&mut rng) {\n\n Ok((secret_key, public_key)) => Ok((public_key, secret_key)),\n\n Err(e) => Err(e),\n\n }\n\n}\n\n\n", "file_path": "client/src/keys/mod.rs", "rank": 21, "score": 103050.91020403881 }, { "content": "/// Read a password from password file.\n\npub fn get_passphrase_file(path: String) -> Result<Password, String> {\n\n let passwords = passwords_from_files(&[path])?;\n\n // use only first password from the file\n\n passwords\n\n .get(0)\n\n .map(Password::clone)\n\n .ok_or_else(|| \"Password file seems to be empty.\".to_owned())\n\n}\n\n\n", "file_path": "client/src/keys/mod.rs", "rank": 22, "score": 101779.13333584036 }, { "content": "/// Reads passwords from files. Treats each line as a separate password.\n\npub fn passwords_from_files(files: &[String]) -> Result<Vec<Password>, String> {\n\n let passwords = files\n\n .iter()\n\n .map(|filename| {\n\n let file = File::open(filename).map_err(|_| {\n\n format!(\n\n \"{} Unable to read password file. Ensure it exists and permissions are correct.\",\n\n filename\n\n )\n\n })?;\n\n let reader = BufReader::new(&file);\n\n let lines = reader\n\n .lines()\n\n .filter_map(|l| l.ok())\n\n .map(|pwd| pwd.trim().to_owned().into())\n\n .collect::<Vec<Password>>();\n\n Ok(lines)\n\n })\n\n .collect::<Result<Vec<Vec<Password>>, String>>();\n\n Ok(passwords?.into_iter().flat_map(|x| x).collect())\n", "file_path": "client/src/keys/mod.rs", "rank": 23, "score": 99012.7266172643 }, { "content": "fn load_genesis_block(path: &str) -> Result<Vec<u8>, std::io::Error> {\n\n let genesis_block_path = path.to_string() + \"/eth/genesis.json\";\n\n match File::open(genesis_block_path) {\n\n Ok(mut fh) => {\n\n let mut buf: Vec<u8> = vec![];\n\n match fh.read_to_end(&mut buf) {\n\n Ok(_bytes) => info!(\"Read genesis block!\"),\n\n Err(_e) => error!(\"Unable to read genesis block\"),\n\n };\n\n Ok(buf)\n\n }\n\n Err(e) => Err(e),\n\n }\n\n}\n\n\n", "file_path": "client/src/main.rs", "rank": 24, "score": 95956.66070722914 }, { "content": "pub fn main() {\n\n env_logger::init();\n\n\n\n let yaml = load_yaml!(\"cli.yml\");\n\n let matches = App::from_yaml(yaml).get_matches();\n\n\n\n // Setup data directories if not present\n\n let base_dir = matches\n\n .value_of(\"data-directory\")\n\n .expect(\"Data directory parameter not found\");\n\n if create_directories(base_dir).is_err() {\n\n error!(\"Unable to create all directories\");\n\n exit(1);\n\n }\n\n\n\n info!(\"All needed directories present\");\n\n\n\n debug!(\"Checking for genesis block...\");\n\n if genesis_block_exists(base_dir) {\n\n debug!(\"Genesis block exists!\");\n", "file_path": "client/src/main.rs", "rank": 25, "score": 95294.3914981928 }, { "content": "/// Gets the cost for a specific Opcode. They are grouped by cost.\n\npub fn get_cost(op: Opcode) -> Option<usize> {\n\n match op {\n\n Opcode::STOP => Some(0),\n\n Opcode::JUMPDEST => Some(1),\n\n\n\n Opcode::ADDRESS\n\n | Opcode::ORIGIN\n\n | Opcode::CALLER\n\n | Opcode::CALLVALUE\n\n | Opcode::CALLDATASIZE\n\n | Opcode::CODESIZE\n\n | Opcode::GASPRICE\n\n | Opcode::RETURNDATASIZE\n\n | Opcode::COINBASE\n\n | Opcode::TIMESTAMP\n\n | Opcode::NUMBER\n\n | Opcode::DIFFICULTY\n\n | Opcode::GASLIMIT\n\n | Opcode::POP\n\n | Opcode::PC\n", "file_path": "fvm/src/gas_prices.rs", "rank": 27, "score": 92964.53382357326 }, { "content": "/// Creates a persistent DB.\n\npub fn create_persistent_db(path: &str, name: &str) -> Result<(RDB, Store), StoreError> {\n\n let root = path.to_string() + name + \"/\";\n\n fs::create_dir_all(root.clone())?;\n\n let root = Path::new(&root);\n\n let created_arc = Manager::singleton().write().unwrap().get_or_create(root, Rkv::new)?;\n\n if let Ok(k) = created_arc.read() {\n\n if let Ok(a) = k.open_or_create(\"store\") {\n\n return Ok((created_arc.clone(), a));\n\n }\n\n }\n\n Err(StoreError::DirectoryDoesNotExistError(root.into()))\n\n}\n\n\n\n/// Core struct that wraps an `rkv` key-value store\n\npub struct DB {\n\n root: H256,\n\n handle: RDB,\n\n database: Store,\n\n}\n\n\n", "file_path": "world/src/db.rs", "rank": 28, "score": 89035.39940984402 }, { "content": "pub fn start_web() {\n\n rocket::ignite().mount(\"/\", routes![handlers::health]).launch();\n\n}\n", "file_path": "client/src/servers/web/mod.rs", "rank": 29, "score": 88910.14457931923 }, { "content": "fn mod_mul(a: usize, b: usize, m: usize) -> usize {\n\n match a.checked_mul(b) {\n\n Some(r) => {\n\n if r >= m {\n\n r % m\n\n } else {\n\n r\n\n }\n\n }\n\n None => mod_mul_(a, b, m),\n\n }\n\n}\n\n\n", "file_path": "world/src/consensus/miller_rabin.rs", "rank": 30, "score": 85857.60273748913 }, { "content": "fn mod_mul_(a: usize, b: usize, m: usize) -> usize {\n\n modulo(mul128(a, b), m)\n\n}\n\n\n", "file_path": "world/src/consensus/miller_rabin.rs", "rank": 31, "score": 85857.60273748913 }, { "content": "fn mul128(u: usize, v: usize) -> U128 {\n\n let u1 = u >> 32;\n\n let u0 = u & (!0 >> 32);\n\n let v1 = v >> 32;\n\n let v0 = v & (!0 >> 32);\n\n\n\n let t = u0 * v0;\n\n let w0 = t & (!0 >> 32);\n\n let k = t >> 32;\n\n\n\n let t = u1 * v0 + k;\n\n let w1 = t & (!0 >> 32);\n\n let w2 = t >> 32;\n\n\n\n let t = u0 * v1 + w1;\n\n let k = t >> 32;\n\n U128 {\n\n lo: (t << 32) + w0,\n\n hi: u1 * v1 + w2 + k,\n\n }\n\n}\n", "file_path": "world/src/consensus/miller_rabin.rs", "rank": 32, "score": 85180.07908229338 }, { "content": "#[get(\"/accounts\")]\n\npub fn accounts() -> String {\n\n \"OK\".to_string()\n\n}\n\n\n\n// #[post(\"/call\", format = \"application/json\", data = \"<input>\")]\n\n// pub fn call(input: T) -> String {\n\n// \"OK\".to_string()\n\n// }\n\n\n\n// #[post(\"/tx\", data = \"<input>\")]\n\n// pub fn tx(input: T) -> String {\n\n// \"OK\".to_string()\n\n// }\n\n\n\n// #[post(\"/rawtx\", data = \"<input>\")]\n\n// pub fn rawtx(input: T) -> String {\n\n// \"OK\".to_string()\n\n// }\n\n\n", "file_path": "client/src/servers/web/handlers/mod.rs", "rank": 33, "score": 82985.39860645293 }, { "content": "#[get(\"/info\")]\n\npub fn info() -> String {\n\n \"OK\".to_string()\n\n}\n\n\n", "file_path": "client/src/servers/web/handlers/mod.rs", "rank": 34, "score": 82985.39860645293 }, { "content": "#[get(\"/html/info\")]\n\npub fn html_info() -> String {\n\n \"OK\".to_string()\n\n}\n", "file_path": "client/src/servers/web/handlers/mod.rs", "rank": 35, "score": 81313.56312650962 }, { "content": "#[get(\"/health\")]\n\npub fn health() -> &'static str {\n\n \"OK\"\n\n}\n\n\n", "file_path": "client/src/servers/web/handlers/mod.rs", "rank": 36, "score": 77937.23412537007 }, { "content": "fn create_directories(path: &str) -> Result<(), io::Error> {\n\n debug!(\"Creating data directories from base: {:?}\", path);\n\n for dir_name in &DIRECTORIES {\n\n match create_directory(path, dir_name) {\n\n Ok(_) => {\n\n debug!(\"Directory {:?} created\", dir_name);\n\n },\n\n Err(e) => {\n\n error!(\"Error creating directory {:?}. Error was: {:?}\", dir_name, e);\n\n }\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "client/src/main.rs", "rank": 37, "score": 74404.23721509433 }, { "content": "#[get(\"/block/<hash>\")]\n\npub fn block(hash: String) -> String {\n\n hash\n\n}\n\n\n", "file_path": "client/src/servers/web/handlers/mod.rs", "rank": 38, "score": 73566.66059622951 }, { "content": "#[get(\"/blockById/<hash>\")]\n\npub fn block_by_id(hash: String) -> String {\n\n hash\n\n}\n\n\n", "file_path": "client/src/servers/web/handlers/mod.rs", "rank": 39, "score": 72119.21085805794 }, { "content": "#[get(\"/transactions/<tx_hash>\")]\n\npub fn transactions(tx_hash: String) -> String {\n\n tx_hash\n\n}\n\n\n", "file_path": "client/src/servers/web/handlers/mod.rs", "rank": 40, "score": 72119.21085805794 }, { "content": "#[get(\"/account/<account_hash>\")]\n\npub fn account(account_hash: String) -> String {\n\n account_hash\n\n}\n\n\n", "file_path": "client/src/servers/web/handlers/mod.rs", "rank": 41, "score": 72119.21085805794 }, { "content": "fn mod_sqr(a: usize, m: usize) -> usize {\n\n if a < (1 << 32) {\n\n let r = a * a;\n\n if r >= m {\n\n r % m\n\n } else {\n\n r\n\n }\n\n } else {\n\n mod_mul_(a, a, m)\n\n }\n\n}\n\n\n", "file_path": "world/src/consensus/miller_rabin.rs", "rank": 42, "score": 71953.21480373615 }, { "content": "#[get(\"/tx/<tx_hash>\")]\n\npub fn get_tx(tx_hash: String) -> String {\n\n tx_hash\n\n}\n\n\n", "file_path": "client/src/servers/web/handlers/mod.rs", "rank": 43, "score": 70767.37846953195 }, { "content": "fn create_directory(path: &str, end: &str) -> Result<(), io::Error> {\n\n fs::create_dir_all(path.to_string() + end)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "client/src/main.rs", "rank": 44, "score": 67395.47344554422 }, { "content": "/// Routes the account-related CLI command to the proper function\n\npub fn handle_cli_command(account_matches: &clap::ArgMatches, base_dir: &str) {\n\n if account_matches.subcommand_matches(\"new\").is_some() {\n\n handle_create_new_account(base_dir);\n\n }\n\n}\n\n\n", "file_path": "client/src/accounts/handler.rs", "rank": 45, "score": 62766.45792563773 }, { "content": "// Convenience wrapper\n\ntype Map<U256, M256> = HashMap<U256, M256>;\n\n\n\n#[derive(Debug, Clone)]\n\n/// Represents durable storage for an Account\n\npub struct Storage {\n\n address: Address,\n\n storage: Map<U256, M256>,\n\n}\n\n\n\nimpl Into<Map<U256, M256>> for Storage {\n\n fn into(self) -> Map<U256, M256> {\n\n self.storage\n\n }\n\n}\n\n\n\nimpl Storage {\n\n /// Create a new storage.\n\n pub fn new(address: Address) -> Storage {\n\n Storage {\n\n address,\n", "file_path": "fvm/src/storage.rs", "rank": 46, "score": 56128.52417403595 }, { "content": "type Gas = u32;\n\n\n\n/// Opcodes supported by the Ethereum VM. https://github.com/trailofbits/evm-opcodes is a good\n\n/// reference for them.\n\n#[derive(PartialEq, Hash, Debug)]\n\npub enum Opcode {\n\n STOP,\n\n ADD,\n\n MUL,\n\n SUB,\n\n DIV,\n\n SDIV,\n\n MOD,\n\n SMOD,\n\n ADDMOD,\n\n MULMOD,\n\n EXP,\n\n SIGNEXTEND,\n\n LT,\n\n GT,\n", "file_path": "fvm/src/opcodes.rs", "rank": 47, "score": 51539.405339487974 }, { "content": "/// Trait for all Memory systems\n\npub trait Memory {\n\n // Read a single u32 at index `index`\n\n fn read(&self, index: M256) -> M256;\n\n // Read a slice of u32s starting at init_off_u of size `init_size_u`\n\n fn read_slice(&self, init_off_u: U256, init_size_u: U256) -> &[u8];\n\n // Reads a single byte at index `index`\n\n fn read_byte(&self, index: M256) -> u8;\n\n // Writes a single u32 at `index`\n\n fn write(&mut self, index: M256, value: M256) -> Result<()>;\n\n // Writes a single `u8` at `index\n\n fn write_byte(&mut self, index: M256, value: u8) -> Result<()>;\n\n // Returns the size of the memory\n\n fn size(&self) -> M256;\n\n // Prints the contents of the memory. Mainly useful for debugging.\n\n fn print(&self) -> String;\n\n // Copies a section of memory starting at `start` and of length `len`\n\n fn copy_from_memory(&self, start: U256, len: U256) -> Vec<u8>;\n\n\n\n fn copy_into_memory(&mut self, values: &[u8], start: U256, value_start: U256, len: U256);\n\n}\n", "file_path": "fvm/src/memory.rs", "rank": 48, "score": 48756.90948916102 }, { "content": "pub trait Patch {\n\n fn epoch_length() -> U256;\n\n}\n\n\n\npub struct EthereumPatch;\n\nimpl Patch for EthereumPatch {\n\n fn epoch_length() -> U256 {\n\n U256::from(30000)\n\n }\n\n}\n\n\n\npub struct LightDAG<P: Patch> {\n\n epoch: usize,\n\n cache: Vec<u8>,\n\n cache_size: usize,\n\n full_size: usize,\n\n _marker: PhantomData<P>,\n\n}\n\n\n\nimpl<P: Patch> LightDAG<P> {\n", "file_path": "world/src/consensus/dag.rs", "rank": 49, "score": 47588.98736097085 }, { "content": "#[test]\n\nfn runs_hello_world() {}\n", "file_path": "fvm/tests/integration_tests.rs", "rank": 50, "score": 46814.81264860372 }, { "content": "// Handles creating a new account\n\nfn handle_create_new_account(base_dir: &str) {\n\n // This handles the user wanting to create a new account\n\n debug!(\"Creating new account\");\n\n // Generate a random public/private key\n\n match keys::generate_random_keypair() {\n\n Ok((public_key, secret_key)) => {\n\n let (ct, iv) = Account::generate_cipher_text(&secret_key);\n\n let address = Account::get_address(public_key);\n\n let new_account = match Account::account_from_passphrase(&iv, &ct, &address, base_dir) {\n\n Ok(account) => account,\n\n Err(e) => {\n\n error!(\"There was an error generating a new account: {:?}\", e);\n\n exit(1);\n\n }\n\n };\n\n let filename = new_account.get_account_filename();\n\n let path = PathBuf::from(base_dir.to_string() + \"keys\");\n\n let account_json = serde_json::to_string(&new_account).unwrap();\n\n match File::create(path) {\n\n Ok(mut fh) => match fh.write_all(account_json.as_bytes()) {\n", "file_path": "client/src/accounts/handler.rs", "rank": 51, "score": 38913.175140376916 }, { "content": "fn data_directory(path: &str) -> PathBuf {\n\n PathBuf::from(path.to_string() + \"data\")\n\n}\n\n\n", "file_path": "client/src/main.rs", "rank": 52, "score": 38887.03474614436 }, { "content": "fn genesis_block_exists(path: &str) -> bool {\n\n let genesis_block_path = path.to_string() + \"/eth/genesis.json\";\n\n std::path::Path::new(&genesis_block_path).exists()\n\n}\n\n\n", "file_path": "client/src/main.rs", "rank": 53, "score": 38887.03474614436 }, { "content": "# Fantom VM\n\n\n\nThis is a register-based virtual machine intended to execute transactions for the Fantom cryptocurrency. In its current state, it can function as an Ethereum VM and full node.\n\n\n\n## Consensus Algorithms\n\n\n\nBy default, the FVM utilizes the ethash consensus algorithm used by Ethereum. The goal is for it to use the Lachesis protocol.\n\n\n\n## Structure\n\n\n\nThis project is structured as a Cargo workspace, with three sub-projects: `client`, `fvm`, and `world`.\n\n\n\n### Client\n\n\n\nThis provides the CLI binary, and is responsible for setting up the various servers over which the FVM will accept requests. It also contains utilities for managing keys and accounts.\n\n\n\n#### CLI Options\n\n\n\nThese are defined in `client/src/cli.yml`, and uses the Rust `clap` library.\n\n\n\n### FVM\n\n\n", "file_path": "README.md", "rank": 54, "score": 38621.346791758115 }, { "content": "fn chain_data_path(base_dir: &str) -> PathBuf {\n\n std::path::PathBuf::from(base_dir.to_string() + \"chaindata\")\n\n}\n", "file_path": "client/src/main.rs", "rank": 55, "score": 37291.70504920856 }, { "content": " pub fn new(number: U256) -> Self {\n\n let epoch = (number / P::epoch_length()).as_usize();\n\n let cache_size = ethash::get_cache_size(epoch);\n\n let full_size = ethash::get_full_size(epoch);\n\n let seed = ethash::get_seedhash(epoch);\n\n\n\n let mut cache: Vec<u8> = Vec::with_capacity(cache_size);\n\n cache.resize(cache_size, 0);\n\n ethash::make_cache(&mut cache, seed);\n\n\n\n Self {\n\n cache,\n\n cache_size,\n\n full_size,\n\n epoch,\n\n _marker: PhantomData,\n\n }\n\n }\n\n\n\n pub fn hashimoto(&self, hash: H256, nonce: H64) -> (H256, H256) {\n\n ethash::hashimoto_light(hash, nonce, self.full_size, &self.cache)\n\n }\n\n\n\n pub fn is_valid_for(&self, number: U256) -> bool {\n\n (number / P::epoch_length()).as_usize() == self.epoch\n\n }\n\n}\n", "file_path": "world/src/consensus/dag.rs", "rank": 56, "score": 29.758778703120324 }, { "content": "use bigint_miner;\n\nuse block;\n\nuse consensus::ethash;\n\n\n\n#[derive(Default)]\n\npub struct Miner;\n\n\n\nimpl Miner {\n\n pub fn new() -> Miner {\n\n Miner {}\n\n }\n\n\n\n pub fn mine(&self, header: &block::Header, epoch: usize) -> (bigint_miner::H64, bigint_miner::H256) {\n\n println!(\"Getting sizes...\");\n\n let full_size = ethash::get_full_size(epoch);\n\n let cache_size = ethash::get_cache_size(epoch);\n\n println!(\"Populating datasets with zeros\");\n\n let mut dataset: Vec<u8> = vec![0; full_size];\n\n let mut cache: Vec<u8> = vec![0; cache_size];\n\n println!(\"Getting seed\");\n", "file_path": "world/src/consensus/miner.rs", "rank": 59, "score": 25.789591441451595 }, { "content": " let seed = ethash::get_seedhash(epoch);\n\n println!(\n\n \"Making cache and dataset. Cache is: {:?}. Dataset is {:?}\",\n\n cache_size, full_size\n\n );\n\n ethash::make_cache(&mut cache, seed);\n\n println!(\"Cache done\");\n\n ethash::make_dataset(&mut dataset, &cache);\n\n println!(\"Dataset done\");\n\n let diff = header.difficulty.as_u32();\n\n let difficulty = bigint_miner::U256::from(diff);\n\n println!(\"Mining difficulty is: {:?}\", difficulty);\n\n ethash::mine(header, full_size, &dataset, bigint_miner::H64::random(), difficulty)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {}\n", "file_path": "world/src/consensus/miner.rs", "rank": 62, "score": 20.260487185449243 }, { "content": " pub value: U256,\n\n /// Data\n\n pub data: Vec<u8>,\n\n /// The standardised V field of the signature.\n\n pub v: U256,\n\n /// The R field of the signature.\n\n pub r: U256,\n\n /// The S field of the signature.\n\n pub s: U256,\n\n}\n\n\n\nimpl Serialize for Transaction {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: Serializer,\n\n {\n\n let mut state = serializer.serialize_struct(\"Transaction\", 9)?;\n\n state.serialize_field(\"nonce\", &self.nonce.as_u64())?;\n\n state.serialize_field(\"gasPrice\", &self.gas_price.as_u64())?;\n\n state.serialize_field(\"startGas\", &self.start_gas.as_u64())?;\n", "file_path": "world/src/transactions/mod.rs", "rank": 63, "score": 17.50069329316496 }, { "content": "#[derive(Default, Debug, Clone, PartialEq)]\n\npub struct Header {\n\n pub parent_hash: H256,\n\n pub ommers_hash: H256,\n\n pub beneficiary: Address,\n\n pub state_root: H256,\n\n pub transactions_root: H256,\n\n pub receipts_root: H256,\n\n pub logs_bloom: LogsBloom,\n\n pub difficulty: U256,\n\n pub number: U256,\n\n pub gas_limit: Gas,\n\n pub gas_used: Gas,\n\n pub timestamp: u64,\n\n pub extra_data: B256,\n\n pub mix_hash: H256,\n\n pub nonce: H64,\n\n}\n\n\n\nimpl Encodable for Block {\n", "file_path": "world/src/blocks/mod.rs", "rank": 64, "score": 17.140795105591085 }, { "content": " number: 0.into(),\n\n gas_limit: self.gas_limit.into(),\n\n gas_used: self.gas_used.into(),\n\n timestamp: self.timestamp,\n\n extra_data: B256::new(&self.extra_data),\n\n mix_hash: H256::from_str(&self.mixhash).unwrap(),\n\n nonce: H64::from(self.nonce),\n\n }\n\n }\n\n}\n", "file_path": "world/src/blocks/genesis.rs", "rank": 65, "score": 17.009791846554215 }, { "content": "use bigint::{Address, Gas, B256, H256, H64, U256};\n\nuse block::Transaction;\n\nuse bloom::LogsBloom;\n\nuse rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp};\n\npub mod genesis;\n\npub mod receipt;\n\n\n\npub type LastHashes = Vec<H256>;\n\n\n\n/// A block, encoded as it is on the block chain.\n\n#[derive(Default, Debug, Clone, PartialEq)]\n\npub struct Block {\n\n /// The header of this block.\n\n pub header: Header,\n\n /// The transactions in this block.\n\n pub transactions: Vec<Transaction>,\n\n /// The uncles of this block.\n\n pub ommers: Vec<Header>,\n\n}\n\n\n", "file_path": "world/src/blocks/mod.rs", "rank": 67, "score": 14.60770113392227 }, { "content": " Ok(passphrase) => { passphrase },\n\n Err(e) => { \n\n return Err(e.into()); \n\n }\n\n };\n\n\n\n let count: u32 = 64000 + rand::thread_rng().gen_range(0, 20000);\n\n let salt: Vec<u8> = generator.gen_iter::<u8>().take(16).collect();\n\n\n\n // Pre-allocate an array to hold the derived key\n\n let mut dk = [0u8; 32];\n\n // Use the KDF to create a hashed string and put it into `dk`\n\n pbkdf2::pbkdf2::<Hmac<Sha256>>(&passphrase.as_bytes(), &salt, count as usize, &mut dk);\n\n\n\n // Now we need the MAC. This verifies authenticity of the signature.\n\n let mut bytes_to_hash: Vec<u8> = vec![];\n\n bytes_to_hash.extend(&dk[16..32]);\n\n bytes_to_hash.extend(ciphertext.bytes());\n\n let mut hasher = Keccak256::new();\n\n hasher.input(&bytes_to_hash);\n", "file_path": "client/src/accounts/account.rs", "rank": 68, "score": 14.572836658273541 }, { "content": "//! Module that contains the VM that executes bytecode\n\n\n\nuse bigint::{Address, H256, M256, MI256, U256};\n\nuse errors::{Result, VMError};\n\nuse eth_log::Log;\n\nuse keccak_hash::keccak;\n\nuse memory::{Memory, SimpleMemory};\n\nuse opcodes::Opcode;\n\nuse storage::Storage;\n\n\n\n/// Core VM struct that executes bytecode\n\npub struct VM {\n\n address: Option<Address>,\n\n registers: [M256; 1024],\n\n memory: Option<Box<Memory>>,\n\n storage: Option<Storage>,\n\n code: Vec<u8>,\n\n pc: usize,\n\n stack_pointer: usize,\n\n logs: Vec<Log>,\n", "file_path": "fvm/src/vm.rs", "rank": 69, "score": 14.510199738960079 }, { "content": " db,\n\n genesis_block,\n\n miner: Miner::new(),\n\n current_block: bigint::U256::from(0),\n\n blocks: vec![],\n\n }\n\n }\n\n\n\n pub fn mine(&mut self) -> (bigint_miner::H64, bigint_miner::H256) {\n\n let tmp_block: block::Header = (*self.genesis_block.clone()).into();\n\n self.miner.mine(&tmp_block, 1)\n\n }\n\n\n\n pub fn get_current_block(&self) -> bigint::U256 {\n\n self.current_block\n\n }\n\n\n\n pub fn num_blocks(&self) -> usize {\n\n self.blocks.len()\n\n }\n", "file_path": "world/src/chain.rs", "rank": 70, "score": 14.022084548793165 }, { "content": "//! Contains the Log data structure\n\n\n\nuse bigint::{Address, Gas, B256, H256, H64, U256};\n\nuse rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp};\n\n\n\n/// A Log entry for the EVM\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub struct Log {\n\n pub address: Address,\n\n pub topics: Vec<H256>,\n\n pub data: Vec<u8>,\n\n}\n\n\n\nimpl Log {\n\n /// Creates and returns a new Log entry\n\n pub fn new(address: Address) -> Log {\n\n Log {\n\n address: address,\n\n topics: vec![],\n\n data: vec![],\n", "file_path": "fvm/src/eth_log.rs", "rank": 71, "score": 13.702904690869305 }, { "content": " fn print(&self) -> String {\n\n String::from(format!(\"{:#?}\", self.memory))\n\n }\n\n\n\n fn copy_from_memory(&self, start: U256, len: U256) -> Vec<u8> {\n\n let mut result: Vec<u8> = Vec::new();\n\n let mut i = start;\n\n while i < start + len {\n\n result.push(self.read_byte(i.into()));\n\n i = i + U256::from(1u64);\n\n }\n\n result\n\n }\n\n\n\n /// Copies a slice of values into memory with a start and end index\n\n fn copy_into_memory(&mut self, values: &[u8], start: U256, value_start: U256, len: U256) {\n\n let value_len = U256::from(values.len());\n\n let mut i = start;\n\n let mut j = value_start;\n\n while i < start + len {\n", "file_path": "fvm/src/memory.rs", "rank": 72, "score": 13.496531926084721 }, { "content": "//! Contains the Transaction module\n\n\n\nuse bigint::{U256, H160};\n\nuse serde::{Serialize, Serializer};\n\nuse serde::ser::SerializeStruct;\n\npub mod pool;\n\n\n\n/// Core data structure for interacting with the EVM\n\n#[derive(Debug, Default, Clone, PartialEq)]\n\npub struct Transaction {\n\n /// Nonce\n\n pub nonce: U256,\n\n /// Gas Price\n\n pub gas_price: U256,\n\n /// Start Gas\n\n pub start_gas: U256,\n\n /// Recipient\n\n /// If None, then this is a contract creation\n\n pub to: Option<H160>,\n\n /// Transferred value\n", "file_path": "world/src/transactions/mod.rs", "rank": 73, "score": 13.016055496680536 }, { "content": " }\n\n\n\n /// Write a value into the storage.\n\n pub fn write(&mut self, index: U256, value: M256) -> Result<(), StorageError> {\n\n if self.storage.contains_key(&index) {\n\n return Err(StorageError::RequireError);\n\n }\n\n self.storage.insert(index, value);\n\n Ok(())\n\n }\n\n\n\n /// Return the number of changed/full items in storage.\n\n pub fn len(&self) -> usize {\n\n self.storage.len()\n\n }\n\n\n\n /// Return true if storage is empty, false otherwise\n\n pub fn is_empty(&self) -> bool {\n\n self.len() == 0\n\n }\n\n}\n", "file_path": "fvm/src/storage.rs", "rank": 74, "score": 12.839326599977356 }, { "content": " if j < value_len {\n\n let ju: usize = j.as_usize();\n\n self.write_byte(i.into(), values[ju]).unwrap();\n\n j = j + U256::from(1u64);\n\n } else {\n\n self.write_byte(i.into(), 0u8).unwrap();\n\n }\n\n i = i + U256::from(1u64);\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n fn gen_simple_mem_with_data() -> SimpleMemory {\n\n let test_value = U256::from(5000);\n\n let mut mem = SimpleMemory {\n\n memory: vec![0; 32],\n", "file_path": "fvm/src/memory.rs", "rank": 75, "score": 12.802407387199338 }, { "content": "#![allow(dead_code)]\n\n\n\nuse bigint_miner::{H256, H64, U256};\n\nuse consensus::ethash;\n\nuse std::marker::PhantomData;\n", "file_path": "world/src/consensus/dag.rs", "rank": 76, "score": 12.636295921606918 }, { "content": "/// Basic Account structure for Fantom system\n\npub struct Account {\n\n /// Public address that can be used to send coins to this account\n\n address: String,\n\n /// A unique ID for the account. This is different from the public address\n\n id: String,\n\n /// What version this account is\n\n version: usize,\n\n /// Struct that contains various crypto options for this account\n\n crypto: AccountCrypto,\n\n /// Contains the base data directory\n\n base_directory: PathBuf\n\n\n\n}\n\n\n\nimpl Account {\n\n /// Creates and returns a new Account\n\n pub fn new(id: String, version: usize, base_directory: PathBuf) -> Result<Account, Box<Error>> {\n\n let secp = secp256k1::Secp256k1::with_caps(secp256k1::ContextFlag::Full);\n\n let mut hasher = Keccak256::new();\n", "file_path": "client/src/accounts/account.rs", "rank": 77, "score": 12.131570586212824 }, { "content": "use std::collections::HashMap;\n\nuse std::fs::File;\n\nuse std::io::prelude::*;\n\nuse std::path::PathBuf;\n\nuse std::str::FromStr;\n\n\n\nuse bigint::{B256, H256, H64};\n\nuse bloom;\n\n\n\n/// Genesis block data structure\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\npub struct Genesis {\n\n #[serde(rename = \"parentHash\")]\n\n parent_hash: String,\n\n #[serde(rename = \"ommersHash\")]\n\n ommers_hash: String,\n\n nonce: u64,\n\n timestamp: u64,\n\n extra_data: Vec<u8>,\n\n #[serde(rename = \"gasLimit\")]\n", "file_path": "world/src/blocks/genesis.rs", "rank": 78, "score": 12.025128133991686 }, { "content": " }\n\n\n\n /// Reads a single byte at the provided index\n\n fn read_byte(&self, index: M256) -> u8 {\n\n self.memory[index.as_usize()].clone()\n\n }\n\n\n\n fn read_slice(&self, init_off_u: U256, init_size_u: U256) -> &[u8] {\n\n let off = init_off_u.low_u64() as usize;\n\n let size = init_size_u.low_u64() as usize;\n\n &self.memory[off..off + size]\n\n }\n\n\n\n /// Writes a `word` at the specified index. This will resize the capacity\n\n /// if needed, and will overwrite any existing bytes if there is overlap.\n\n fn write(&mut self, index: M256, value: M256) -> Result<()> {\n\n let index = index.as_usize();\n\n self.resize_if_needed(index)?;\n\n for i in 0..32 {\n\n let idx = M256::from(index + i);\n", "file_path": "fvm/src/memory.rs", "rank": 79, "score": 11.686768915932618 }, { "content": "\n\n /// Starts the execution loop for the VM\n\n pub fn execute(&mut self) -> Result<()> {\n\n loop {\n\n match self.execute_one() {\n\n Ok(_) => {\n\n continue;\n\n }\n\n Err(e) => {\n\n return Err(e);\n\n }\n\n };\n\n }\n\n }\n\n\n\n /// Executes the next instruction only\n\n pub fn execute_one(&mut self) -> Result<()> {\n\n let opcode = Opcode::from(&self.code[self.pc]);\n\n match opcode {\n\n Opcode::STOP => {\n", "file_path": "fvm/src/vm.rs", "rank": 80, "score": 11.587149213372143 }, { "content": "}\n\n\n\n/// Implements the needed traits for Trie\n\nimpl TrieMut for DB {\n\n fn root(&self) -> H256 {\n\n self.root\n\n }\n\n\n\n fn insert(&mut self, key: &[u8], value: &[u8]) {\n\n match self.handle.read() {\n\n Ok(env_lock) => match env_lock.write() {\n\n Ok(mut writer) => {\n\n let _result = writer.put(self.database, key, &Value::Blob(value));\n\n let _result = writer.commit();\n\n }\n\n Err(_e) => {}\n\n },\n\n Err(_e) => {}\n\n }\n\n }\n", "file_path": "world/src/db.rs", "rank": 81, "score": 11.029308033222932 }, { "content": "use bigint::{Gas, H256};\n\nuse bloom::LogsBloom;\n\nuse fvm::eth_log::Log;\n\nuse rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp};\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq)]\n\npub struct Receipt {\n\n pub state_root: H256,\n\n pub used_gas: Gas,\n\n pub logs_bloom: LogsBloom,\n\n pub logs: Vec<Log>,\n\n}\n\n\n\nimpl Encodable for Receipt {\n\n fn rlp_append(&self, s: &mut RlpStream) {\n\n s.begin_list(4);\n\n s.append(&self.state_root);\n\n s.append(&self.used_gas);\n\n s.append(&self.logs_bloom);\n\n s.append_list(&self.logs);\n", "file_path": "world/src/blocks/receipt.rs", "rank": 82, "score": 10.923465676862376 }, { "content": " + &now.format(\"%Y-%m-%d\").to_string()\n\n + \"T\"\n\n + &now.format(\"%H-%M-%SZ\").to_string()\n\n + \"--\"\n\n + &self.get_id()\n\n + \".json\"\n\n }\n\n\n\n\n\n pub fn account_from_passphrase(iv: &[u8], ciphertext: &str, address: &str, base_directory: &str) -> Result<Box<Account>, Box<Error>> {\n\n // This is the passphrase we'll use to encrypt their secret key, and they will need to\n\n // provide to decrypt it\n\n let mut generator = match OsRng::new() {\n\n Ok(g) => { g },\n\n Err(e) => {\n\n return Err(Box::new(e));\n\n }\n\n };\n\n\n\n let passphrase = match keys::get_passphrase() {\n", "file_path": "client/src/accounts/account.rs", "rank": 83, "score": 10.485986556900876 }, { "content": " }\n\n\n\n /// Part of the Builder, allows setting the KDF (Key Derivation Function)\n\n pub fn with_kdf(mut self, kdf: String) -> Account {\n\n self.crypto.kdf = Some(kdf);\n\n self\n\n }\n\n\n\n /// Part of the Builder, allows setting the MAC of the account\n\n pub fn with_mac(mut self, mac: String) -> Account {\n\n self.crypto.mac = Some(mac);\n\n self\n\n }\n\n\n\n /// Part of the Builder, allows setting the params when using pdkdf2\n\n pub fn with_pdkdf2_params(mut self, dklen: usize, salt: String, prf: String, c: usize) -> Account {\n\n self.crypto.kdfparams.dklen = Some(dklen);\n\n self.crypto.kdfparams.salt = Some(salt);\n\n self.crypto.kdfparams.prf = Some(prf);\n\n self.crypto.kdfparams.c = Some(c);\n", "file_path": "client/src/accounts/account.rs", "rank": 84, "score": 9.839166918533628 }, { "content": "//! This module contains errors related to the Fantom VM itself\n\nuse std::error::Error;\n\nuse std::fmt;\n\n\n\n/// Convenience wrapper around T and a VMError\n\npub type Result<T> = std::result::Result<T, VMError>;\n\n\n\n#[derive(Debug, Clone)]\n\n/// Errors related to the VM\n\npub enum VMError {\n\n // VM has encountered an unknown opcode\n\n UnknownOpcodeError,\n\n // VM has run out of memory\n\n MemoryError,\n\n}\n\n\n\nimpl Error for VMError {}\n\n\n\nimpl fmt::Display for VMError {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n", "file_path": "fvm/src/errors.rs", "rank": 85, "score": 9.74428629667377 }, { "content": "\n\n fn delete(&mut self, key: &[u8]) {\n\n match self.handle.write() {\n\n Ok(env_lock) => match env_lock.write() {\n\n Ok(mut writer) => {\n\n let _result = writer.delete(self.database, key);\n\n let _result = writer.commit();\n\n }\n\n Err(_e) => {}\n\n },\n\n Err(_e) => {}\n\n }\n\n }\n\n fn get(&self, key: &[u8]) -> Option<Vec<u8>> {\n\n match self.handle.read() {\n\n Ok(env_lock) => match env_lock.read() {\n\n Ok(reader) => match reader.get(self.database, key) {\n\n Ok(result) => match result {\n\n Some(r) => {\n\n let final_result: Vec<u8> = r.to_bytes().unwrap();\n", "file_path": "world/src/db.rs", "rank": 86, "score": 9.376593857295116 }, { "content": " storage: Map::new(),\n\n }\n\n }\n\n\n\n /// Commit a value into the storage.\n\n fn commit(&mut self, index: U256, value: M256) -> Result<(), StorageError> {\n\n if self.storage.contains_key(&index) {\n\n return Err(StorageError::AlreadyCommitted);\n\n }\n\n\n\n self.storage.insert(index, value);\n\n Ok(())\n\n }\n\n\n\n /// Read a value from the storage.\n\n pub fn read(&self, index: U256) -> Result<M256, StorageError> {\n\n match self.storage.get(&index) {\n\n Some(&v) => Ok(v),\n\n None => Ok(M256::zero()),\n\n }\n", "file_path": "fvm/src/storage.rs", "rank": 87, "score": 9.196575148358876 }, { "content": "//! Implements the persistent database to store tries\n\n//! Uses `rkv`, more info here: https://github.com/mozilla/rkv\n\n\n\nuse std::fs;\n\nuse std::path::Path;\n\n\n\n// Database imports\n\nuse rkv::{Manager, Rkv, Store, StoreError, Value};\n\nuse tempdir::TempDir;\n\nuse trie::TrieMut;\n\n\n\nuse bigint::H256;\n\n\n\npub type RDB = std::sync::Arc<std::sync::RwLock<rkv::Rkv>>;\n\n\n\n/// Creates a temporary DB. Mostly useful for testing.\n", "file_path": "world/src/db.rs", "rank": 88, "score": 9.130521038888048 }, { "content": " // the expansion count\n\n fn resize_if_needed(&mut self, index: usize) -> Result<()> {\n\n if index >= self.memory.len() {\n\n self.memory.resize(index + 1, 0);\n\n self.expansions += 1;\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl Memory for SimpleMemory {\n\n /// Reads a `word` at the provided index\n\n fn read(&self, index: M256) -> M256 {\n\n let index = index.as_usize();\n\n self.memory[index..index + 32]\n\n .iter()\n\n .map(|v| v.clone())\n\n .collect::<Vec<u8>>()\n\n .as_slice()\n\n .into()\n", "file_path": "fvm/src/memory.rs", "rank": 89, "score": 9.098683919666078 }, { "content": "\n\n/// Simple implementation of memory using Rust Vecs\n\n#[derive(Debug, PartialEq)]\n\npub struct SimpleMemory {\n\n /// Memory is represented as a simple Vector of `u8`s\n\n memory: Vec<u8>,\n\n /// Tracks how many times we've had to expand memory\n\n expansions: usize,\n\n}\n\n\n\nimpl SimpleMemory {\n\n /// Creates and returns a new SimpleMemory\n\n pub fn new() -> SimpleMemory {\n\n SimpleMemory {\n\n memory: Vec::new(),\n\n expansions: 0,\n\n }\n\n }\n\n\n\n // Resizes the memory vector if needed. This will be called automatically, and will increment\n", "file_path": "fvm/src/memory.rs", "rank": 90, "score": 8.847268079760578 }, { "content": "}\n\n\n\n/// So we can get the password as bytes or as a str\n\nimpl Password {\n\n pub fn as_bytes(&self) -> &[u8] {\n\n self.0.as_bytes()\n\n }\n\n\n\n pub fn as_str(&self) -> &str {\n\n self.0.as_str()\n\n }\n\n}\n\n\n\n/// This generates a random public/private keypair, and is used when creating a new account.\n", "file_path": "client/src/keys/mod.rs", "rank": 91, "score": 8.63030333180302 }, { "content": " if self.to.is_none() {\n\n state.serialize_field(\"to\", &0)?;\n\n } else {\n\n state.serialize_field(\"to\", &self.value.as_u64())?;\n\n }\n\n state.serialize_field(\"value\", &self.value.as_u64())?;\n\n state.serialize_field(\"data\", &self.data)?;\n\n state.serialize_field(\"v\", &self.v.as_u64())?;\n\n state.serialize_field(\"r\", &self.r.as_u64())?;\n\n state.serialize_field(\"s\", &self.s.as_u64())?;\n\n state.end()\n\n }\n\n}\n\n\n\n/// A valid transaction is one where:\n\n/// (i) the signature is well-formed (ie. 0 <= v <= 3, 0 <= r < P, 0 <= s < N, 0 <= r < P - N if v >= 2),\n\n/// and (ii) the sending account has enough funds to pay the fee and the value.\n\nimpl Transaction {\n\n pub fn is_valid(&self) -> bool {\n\n unimplemented!()\n\n }\n\n\n\n fn sender_account(&mut self) {\n\n unimplemented!()\n\n }\n\n}", "file_path": "world/src/transactions/mod.rs", "rank": 92, "score": 8.50036110021662 }, { "content": " let (p, s) = keys::generate_random_keypair()?;\n\n let public_vec = p.serialize_vec(&secp, false).to_vec();\n\n hasher.input(public_vec);\n\n let public_result = hasher.result().to_hex().to_string();\n\n let end = public_result.len();\n\n let start = end - 40;\n\n let address = public_result[start..end].to_string();\n\n\n\n Ok(Account {\n\n address: address,\n\n crypto: AccountCrypto::new(p, s),\n\n id,\n\n version,\n\n base_directory\n\n })\n\n }\n\n\n\n /// Gets and returns the ID of the account\n\n pub fn get_id(&self) -> String {\n\n self.id.clone()\n", "file_path": "client/src/accounts/account.rs", "rank": 93, "score": 8.38188783598148 }, { "content": "use rand::os::OsRng;\n\nuse rpassword::read_password;\n\nuse std::{io, io::Write, io::BufRead, io::BufReader};\n\nuse secp256k1;\n\nuse secp256k1::key::{PublicKey, SecretKey};\n\nuse secp256k1::Error;\n\nuse std::{fmt, fs::File};\n\nuse std::string::ToString;\n\n\n\n#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]\n\n/// Wrapper type around a String to represent a password\n\npub struct Password(String);\n\n\n\nimpl fmt::Debug for Password {\n\n /// We do not want to potentially print out passwords in logs, so we implement `fmt` here\n\n /// such that it obfuscates it\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"Password(******)\")\n\n }\n\n}\n", "file_path": "client/src/keys/mod.rs", "rank": 94, "score": 8.132653693343777 }, { "content": "//! Contains the base BlockChain structure\n\nuse bigint;\n\nuse block::Block;\n\nuse blocks::genesis::Genesis;\n\nuse consensus::miner::Miner;\n\nuse db::RDB;\n\n\n\n/// Core data structure that contains the Blocks that make up the chain\n\npub struct BlockChain {\n\n #[allow(dead_code)]\n\n db: RDB,\n\n genesis_block: Box<Genesis>,\n\n pub miner: Miner,\n\n current_block: bigint::U256,\n\n blocks: Vec<Block>,\n\n}\n\n\n\nimpl BlockChain {\n\n pub fn new_from_genesis(db: RDB, genesis_block: Box<Genesis>) -> BlockChain {\n\n BlockChain {\n", "file_path": "world/src/chain.rs", "rank": 95, "score": 8.043951424555427 }, { "content": " self.write_byte(idx, value.index(i))?;\n\n }\n\n Ok(())\n\n }\n\n\n\n /// Writes a single byte to the memory. This will resize the memory if\n\n /// needed.\n\n fn write_byte(&mut self, index: M256, value: u8) -> Result<()> {\n\n let index = index.as_usize();\n\n self.resize_if_needed(index)?;\n\n self.memory[index] = value;\n\n Ok(())\n\n }\n\n\n\n /// Returns the current size of memory in words\n\n fn size(&self) -> M256 {\n\n M256::from(self.memory.len())\n\n }\n\n\n\n /// Prints the contents of memory\n", "file_path": "fvm/src/memory.rs", "rank": 96, "score": 7.878347983116794 }, { "content": " self.stack_pointer -= 1;\n\n let result = (self.registers[self.stack_pointer] * self.registers[self.stack_pointer - 1])\n\n % self.registers[self.stack_pointer - 2];\n\n if result == self.registers[self.stack_pointer - 2] {\n\n self.registers[self.stack_pointer - 2] = result;\n\n } else {\n\n self.registers[self.stack_pointer - 2] = 0.into();\n\n }\n\n }\n\n Opcode::EXP => {\n\n let s1 = self.registers[self.stack_pointer];\n\n let s2 = self.registers[self.stack_pointer - 1];\n\n if s1 > M256::from(32) {\n\n self.registers[self.stack_pointer - 1] = s2;\n\n } else {\n\n let mut ret = M256::zero();\n\n let len: usize = s1.as_usize();\n\n let t: usize = 8 * (len + 1) - 1;\n\n let t_bit_mask = M256::one() << t;\n\n let t_value = (s2 & t_bit_mask) >> t;\n", "file_path": "fvm/src/vm.rs", "rank": 97, "score": 7.858840316105909 }, { "content": " }\n\n}\n\n\n\nimpl Into<block::Header> for Genesis {\n\n fn into(self) -> block::Header {\n\n let mut account_bytes: Vec<u8> = vec![];\n\n for (address, _amt) in self.alloc.unwrap() {\n\n account_bytes.append(&mut address.clone().into_bytes());\n\n }\n\n\n\n let state_root_hash = H256::from_slice(&account_bytes);\n\n block::Header {\n\n parent_hash: H256::from_str(&self.parent_hash).unwrap(),\n\n ommers_hash: H256::from_str(&self.ommers_hash).unwrap(),\n\n beneficiary: 0.into(),\n\n state_root: state_root_hash,\n\n transactions_root: H256::zero(),\n\n receipts_root: H256::zero(),\n\n logs_bloom: bloom::LogsBloom::new(),\n\n difficulty: self.difficulty.into(),\n", "file_path": "world/src/blocks/genesis.rs", "rank": 98, "score": 7.5026397042924975 }, { "content": " gas_limit: u64,\n\n #[serde(rename = \"gasUsed\")]\n\n gas_used: u64,\n\n pub difficulty: u64,\n\n coinbase: String,\n\n mixhash: String,\n\n alloc: Option<HashMap<String, GenesisAlloc>>,\n\n config: GenesisConfig,\n\n}\n\n\n\n/// Simple struct to contain the initial accounts for allocation in\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\npub struct GenesisAlloc {\n\n balance: String,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\npub struct GenesisConfig {\n\n #[serde(rename = \"chainId\")]\n\n chain_id: u64,\n", "file_path": "world/src/blocks/genesis.rs", "rank": 99, "score": 7.420237823062098 } ]
Rust
src/request.rs
auula/poem
b3d15f83e994389b97ccd614d9361d48e3730002
use std::{ any::Any, convert::{TryFrom, TryInto}, sync::Arc, }; use crate::{ body::Body, error::{Error, ErrorBodyHasBeenTaken, Result}, http::{ header::{self, HeaderMap, HeaderName, HeaderValue}, Extensions, Method, Uri, Version, }, route_recognizer::Params, web::CookieJar, }; pub struct RequestParts { method: Method, uri: Uri, version: Version, headers: HeaderMap, extensions: Extensions, } #[derive(Default)] pub(crate) struct RequestState { pub(crate) original_uri: Uri, pub(crate) match_params: Params, pub(crate) cookie_jar: CookieJar, } pub struct Request { method: Method, uri: Uri, version: Version, headers: HeaderMap, extensions: Extensions, body: Option<Body>, state: RequestState, } impl Request { pub(crate) fn from_hyper_request(req: hyper::Request<hyper::Body>) -> Result<Self> { let (parts, body) = req.into_parts(); let mut cookie_jar = ::cookie::CookieJar::new(); for header in parts.headers.get_all(header::COOKIE) { if let Ok(value) = std::str::from_utf8(header.as_bytes()) { for cookie_str in value.split(';').map(str::trim) { if let Ok(cookie) = ::cookie::Cookie::parse_encoded(cookie_str) { cookie_jar.add_original(cookie.into_owned()); } } } } Ok(Self { method: parts.method, uri: parts.uri.clone(), version: parts.version, headers: parts.headers, extensions: parts.extensions, body: Some(Body(body)), state: RequestState { original_uri: parts.uri, match_params: Default::default(), cookie_jar: CookieJar(Arc::new(parking_lot::Mutex::new(cookie_jar))), }, }) } pub fn builder() -> RequestBuilder { RequestBuilder(Ok(RequestParts { method: Method::GET, uri: Default::default(), version: Default::default(), headers: Default::default(), extensions: Default::default(), })) } #[inline] pub fn method(&self) -> &Method { &self.method } #[inline] pub fn set_method(&mut self, method: Method) { self.method = method; } #[inline] pub fn uri(&self) -> &Uri { &self.uri } #[inline] pub fn original_uri(&self) -> &Uri { &self.state.original_uri } #[inline] pub fn set_uri(&mut self, uri: Uri) { self.uri = uri; } #[inline] pub fn version(&self) -> Version { self.version } #[inline] pub fn set_version(&mut self, version: Version) { self.version = version; } #[inline] pub fn headers(&self) -> &HeaderMap { &self.headers } #[inline] pub fn headers_mut(&mut self) -> &mut HeaderMap { &mut self.headers } pub fn content_type(&self) -> Option<&str> { self.headers() .get(header::CONTENT_TYPE) .and_then(|value| value.to_str().ok()) } #[inline] pub fn extensions(&self) -> &Extensions { &self.extensions } #[inline] pub fn extensions_mut(&mut self) -> &mut Extensions { &mut self.extensions } #[inline] pub fn cookie(&self) -> &CookieJar { &self.state.cookie_jar } pub fn set_body(&mut self, body: Body) { self.body = Some(body); } #[inline] pub fn take_body(&mut self) -> Result<Body> { self.body.take().ok_or_else(|| ErrorBodyHasBeenTaken.into()) } #[inline] pub(crate) fn state(&self) -> &RequestState { &self.state } #[inline] pub(crate) fn state_mut(&mut self) -> &mut RequestState { &mut self.state } } pub struct RequestBuilder(Result<RequestParts>); impl RequestBuilder { #[must_use] pub fn method(self, method: Method) -> RequestBuilder { Self(self.0.map(move |parts| RequestParts { method, ..parts })) } #[must_use] pub fn uri<T>(self, uri: T) -> RequestBuilder where T: TryInto<Uri, Error = Error>, { Self(self.0.and_then(move |parts| { Ok(RequestParts { uri: uri.try_into()?, ..parts }) })) } #[must_use] pub fn version(self, version: Version) -> RequestBuilder { Self(self.0.map(move |parts| RequestParts { version, ..parts })) } #[must_use] pub fn header<K, V>(self, key: K, value: V) -> Self where HeaderName: TryFrom<K>, <HeaderName as TryFrom<K>>::Error: Into<Error>, HeaderValue: TryFrom<V>, <HeaderValue as TryFrom<V>>::Error: Into<Error>, { Self(self.0.and_then(move |mut parts| { let key = <HeaderName as TryFrom<K>>::try_from(key).map_err(Into::into)?; let value = <HeaderValue as TryFrom<V>>::try_from(value).map_err(Into::into)?; parts.headers.append(key, value); Ok(parts) })) } #[must_use] pub fn content_type(self, content_type: &str) -> Self { Self(self.0.and_then(move |mut parts| { let value = content_type.parse()?; parts.headers.append(header::CONTENT_TYPE, value); Ok(parts) })) } #[must_use] pub fn extension<T>(self, extension: T) -> Self where T: Any + Send + Sync + 'static, { Self(self.0.map(move |mut parts| { parts.extensions.insert(extension); parts })) } pub fn body(self, body: Body) -> Result<Request> { self.0.map(move |parts| Request { method: parts.method, uri: parts.uri, version: parts.version, headers: parts.headers, extensions: parts.extensions, body: Some(body), state: Default::default(), }) } }
use std::{ any::Any, convert::{TryFrom, TryInto}, sync::Arc, }; use crate::{ body::Body, error::{Error, ErrorBodyHasBeenTaken, Result}, http::{ header::{self, HeaderMap, HeaderName, HeaderValue}, Extensions, Method, Uri, Version, }, route_recognizer::Params, web::CookieJar, }; pub struct RequestParts { method: Method, uri: Uri, version: Version, headers: HeaderMap, extensions: Extensions, } #[derive(Default)] pub(crate) struct RequestState { pub(crate) original_uri: Uri, pub(crate) match_params: Params, pub(crate) cookie_jar: CookieJar, } pub struct Request { method: Method, uri: Uri, version: Version, headers: HeaderMap, extensions: Extensions,
HeaderName: TryFrom<K>, <HeaderName as TryFrom<K>>::Error: Into<Error>, HeaderValue: TryFrom<V>, <HeaderValue as TryFrom<V>>::Error: Into<Error>, { Self(self.0.and_then(move |mut parts| { let key = <HeaderName as TryFrom<K>>::try_from(key).map_err(Into::into)?; let value = <HeaderValue as TryFrom<V>>::try_from(value).map_err(Into::into)?; parts.headers.append(key, value); Ok(parts) })) } #[must_use] pub fn content_type(self, content_type: &str) -> Self { Self(self.0.and_then(move |mut parts| { let value = content_type.parse()?; parts.headers.append(header::CONTENT_TYPE, value); Ok(parts) })) } #[must_use] pub fn extension<T>(self, extension: T) -> Self where T: Any + Send + Sync + 'static, { Self(self.0.map(move |mut parts| { parts.extensions.insert(extension); parts })) } pub fn body(self, body: Body) -> Result<Request> { self.0.map(move |parts| Request { method: parts.method, uri: parts.uri, version: parts.version, headers: parts.headers, extensions: parts.extensions, body: Some(body), state: Default::default(), }) } }
body: Option<Body>, state: RequestState, } impl Request { pub(crate) fn from_hyper_request(req: hyper::Request<hyper::Body>) -> Result<Self> { let (parts, body) = req.into_parts(); let mut cookie_jar = ::cookie::CookieJar::new(); for header in parts.headers.get_all(header::COOKIE) { if let Ok(value) = std::str::from_utf8(header.as_bytes()) { for cookie_str in value.split(';').map(str::trim) { if let Ok(cookie) = ::cookie::Cookie::parse_encoded(cookie_str) { cookie_jar.add_original(cookie.into_owned()); } } } } Ok(Self { method: parts.method, uri: parts.uri.clone(), version: parts.version, headers: parts.headers, extensions: parts.extensions, body: Some(Body(body)), state: RequestState { original_uri: parts.uri, match_params: Default::default(), cookie_jar: CookieJar(Arc::new(parking_lot::Mutex::new(cookie_jar))), }, }) } pub fn builder() -> RequestBuilder { RequestBuilder(Ok(RequestParts { method: Method::GET, uri: Default::default(), version: Default::default(), headers: Default::default(), extensions: Default::default(), })) } #[inline] pub fn method(&self) -> &Method { &self.method } #[inline] pub fn set_method(&mut self, method: Method) { self.method = method; } #[inline] pub fn uri(&self) -> &Uri { &self.uri } #[inline] pub fn original_uri(&self) -> &Uri { &self.state.original_uri } #[inline] pub fn set_uri(&mut self, uri: Uri) { self.uri = uri; } #[inline] pub fn version(&self) -> Version { self.version } #[inline] pub fn set_version(&mut self, version: Version) { self.version = version; } #[inline] pub fn headers(&self) -> &HeaderMap { &self.headers } #[inline] pub fn headers_mut(&mut self) -> &mut HeaderMap { &mut self.headers } pub fn content_type(&self) -> Option<&str> { self.headers() .get(header::CONTENT_TYPE) .and_then(|value| value.to_str().ok()) } #[inline] pub fn extensions(&self) -> &Extensions { &self.extensions } #[inline] pub fn extensions_mut(&mut self) -> &mut Extensions { &mut self.extensions } #[inline] pub fn cookie(&self) -> &CookieJar { &self.state.cookie_jar } pub fn set_body(&mut self, body: Body) { self.body = Some(body); } #[inline] pub fn take_body(&mut self) -> Result<Body> { self.body.take().ok_or_else(|| ErrorBodyHasBeenTaken.into()) } #[inline] pub(crate) fn state(&self) -> &RequestState { &self.state } #[inline] pub(crate) fn state_mut(&mut self) -> &mut RequestState { &mut self.state } } pub struct RequestBuilder(Result<RequestParts>); impl RequestBuilder { #[must_use] pub fn method(self, method: Method) -> RequestBuilder { Self(self.0.map(move |parts| RequestParts { method, ..parts })) } #[must_use] pub fn uri<T>(self, uri: T) -> RequestBuilder where T: TryInto<Uri, Error = Error>, { Self(self.0.and_then(move |parts| { Ok(RequestParts { uri: uri.try_into()?, ..parts }) })) } #[must_use] pub fn version(self, version: Version) -> RequestBuilder { Self(self.0.map(move |parts| RequestParts { version, ..parts })) } #[must_use] pub fn header<K, V>(self, key: K, value: V) -> Self where
random
[]
Rust
datafusion/src/datasource/memory.rs
andts/arrow-datafusion
1c39f5ce865e3e1225b4895196073be560a93e82
use futures::StreamExt; use std::any::Any; use std::sync::Arc; use arrow::datatypes::SchemaRef; use arrow::record_batch::RecordBatch; use async_trait::async_trait; use crate::datasource::TableProvider; use crate::error::{DataFusionError, Result}; use crate::execution::runtime_env::RuntimeEnv; use crate::logical_plan::Expr; use crate::physical_plan::common; use crate::physical_plan::memory::MemoryExec; use crate::physical_plan::ExecutionPlan; use crate::physical_plan::{repartition::RepartitionExec, Partitioning}; pub struct MemTable { schema: SchemaRef, batches: Vec<Vec<RecordBatch>>, } impl MemTable { pub fn try_new(schema: SchemaRef, partitions: Vec<Vec<RecordBatch>>) -> Result<Self> { if partitions .iter() .flatten() .all(|batches| schema.contains(&batches.schema())) { Ok(Self { schema, batches: partitions, }) } else { Err(DataFusionError::Plan( "Mismatch between schema and batches".to_string(), )) } } pub async fn load( t: Arc<dyn TableProvider>, batch_size: usize, output_partitions: Option<usize>, runtime: Arc<RuntimeEnv>, ) -> Result<Self> { let schema = t.schema(); let exec = t.scan(&None, batch_size, &[], None).await?; let partition_count = exec.output_partitioning().partition_count(); let tasks = (0..partition_count) .map(|part_i| { let runtime1 = runtime.clone(); let exec = exec.clone(); tokio::spawn(async move { let stream = exec.execute(part_i, runtime1.clone()).await?; common::collect(stream).await }) }) .collect::<Vec<_>>(); let mut data: Vec<Vec<RecordBatch>> = Vec::with_capacity(exec.output_partitioning().partition_count()); for task in tasks { let result = task.await.expect("MemTable::load could not join task")?; data.push(result); } let exec = MemoryExec::try_new(&data, schema.clone(), None)?; if let Some(num_partitions) = output_partitions { let exec = RepartitionExec::try_new( Arc::new(exec), Partitioning::RoundRobinBatch(num_partitions), )?; let mut output_partitions = vec![]; for i in 0..exec.output_partitioning().partition_count() { let mut stream = exec.execute(i, runtime.clone()).await?; let mut batches = vec![]; while let Some(result) = stream.next().await { batches.push(result?); } output_partitions.push(batches); } return MemTable::try_new(schema.clone(), output_partitions); } MemTable::try_new(schema.clone(), data) } } #[async_trait] impl TableProvider for MemTable { fn as_any(&self) -> &dyn Any { self } fn schema(&self) -> SchemaRef { self.schema.clone() } async fn scan( &self, projection: &Option<Vec<usize>>, _batch_size: usize, _filters: &[Expr], _limit: Option<usize>, ) -> Result<Arc<dyn ExecutionPlan>> { Ok(Arc::new(MemoryExec::try_new( &self.batches.clone(), self.schema(), projection.clone(), )?)) } } #[cfg(test)] mod tests { use super::*; use arrow::array::Int32Array; use arrow::datatypes::{DataType, Field, Schema}; use futures::StreamExt; use std::collections::HashMap; #[tokio::test] async fn test_with_projection() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); let schema = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), Field::new("d", DataType::Int32, true), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), Arc::new(Int32Array::from(vec![None, None, Some(9)])), ], )?; let provider = MemTable::try_new(schema, vec![vec![batch]])?; let exec = provider.scan(&Some(vec![2, 1]), 1024, &[], None).await?; let mut it = exec.execute(0, runtime).await?; let batch2 = it.next().await.unwrap()?; assert_eq!(2, batch2.schema().fields().len()); assert_eq!("c", batch2.schema().field(0).name()); assert_eq!("b", batch2.schema().field(1).name()); assert_eq!(2, batch2.num_columns()); Ok(()) } #[tokio::test] async fn test_without_projection() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); let schema = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; let provider = MemTable::try_new(schema, vec![vec![batch]])?; let exec = provider.scan(&None, 1024, &[], None).await?; let mut it = exec.execute(0, runtime).await?; let batch1 = it.next().await.unwrap()?; assert_eq!(3, batch1.schema().fields().len()); assert_eq!(3, batch1.num_columns()); Ok(()) } #[tokio::test] async fn test_invalid_projection() -> Result<()> { let schema = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; let provider = MemTable::try_new(schema, vec![vec![batch]])?; let projection: Vec<usize> = vec![0, 4]; match provider.scan(&Some(projection), 1024, &[], None).await { Err(DataFusionError::Internal(e)) => { assert_eq!("\"Projection index out of range\"", format!("{:?}", e)) } _ => panic!("Scan should failed on invalid projection"), }; Ok(()) } #[test] fn test_schema_validation_incompatible_column() -> Result<()> { let schema1 = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let schema2 = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Float64, false), Field::new("c", DataType::Int32, false), ])); let batch = RecordBatch::try_new( schema1, vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; match MemTable::try_new(schema2, vec![vec![batch]]) { Err(DataFusionError::Plan(e)) => assert_eq!( "\"Mismatch between schema and batches\"", format!("{:?}", e) ), _ => panic!("MemTable::new should have failed due to schema mismatch"), } Ok(()) } #[test] fn test_schema_validation_different_column_count() -> Result<()> { let schema1 = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let schema2 = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let batch = RecordBatch::try_new( schema1, vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![7, 5, 9])), ], )?; match MemTable::try_new(schema2, vec![vec![batch]]) { Err(DataFusionError::Plan(e)) => assert_eq!( "\"Mismatch between schema and batches\"", format!("{:?}", e) ), _ => panic!("MemTable::new should have failed due to schema mismatch"), } Ok(()) } #[tokio::test] async fn test_merged_schema() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); let mut metadata = HashMap::new(); metadata.insert("foo".to_string(), "bar".to_string()); let schema1 = Schema::new_with_metadata( vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ], metadata, ); let schema2 = Schema::new(vec![ Field::new("a", DataType::Int32, true), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ]); let merged_schema = Schema::try_merge(vec![schema1.clone(), schema2.clone()])?; let batch1 = RecordBatch::try_new( Arc::new(schema1), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; let batch2 = RecordBatch::try_new( Arc::new(schema2), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; let provider = MemTable::try_new(Arc::new(merged_schema), vec![vec![batch1, batch2]])?; let exec = provider.scan(&None, 1024, &[], None).await?; let mut it = exec.execute(0, runtime).await?; let batch1 = it.next().await.unwrap()?; assert_eq!(3, batch1.schema().fields().len()); assert_eq!(3, batch1.num_columns()); Ok(()) } }
use futures::StreamExt; use std::any::Any; use std::sync::Arc; use arrow::datatypes::SchemaRef; use arrow::record_batch::RecordBatch; use async_trait::async_trait; use crate::datasource::TableProvider; use crate::error::{DataFusionError, Result}; use crate::execution::runtime_env::RuntimeEnv; use crate::logical_plan::Expr; use crate::physical_plan::common; use crate::physical_plan::memory::MemoryExec; use crate::physical_plan::ExecutionPlan; use crate::physical_plan::{repartition::RepartitionExec, Partitioning}; pub struct MemTable { schema: SchemaRef, batches: Vec<Vec<RecordBatch>>, } impl MemTable {
pub async fn load( t: Arc<dyn TableProvider>, batch_size: usize, output_partitions: Option<usize>, runtime: Arc<RuntimeEnv>, ) -> Result<Self> { let schema = t.schema(); let exec = t.scan(&None, batch_size, &[], None).await?; let partition_count = exec.output_partitioning().partition_count(); let tasks = (0..partition_count) .map(|part_i| { let runtime1 = runtime.clone(); let exec = exec.clone(); tokio::spawn(async move { let stream = exec.execute(part_i, runtime1.clone()).await?; common::collect(stream).await }) }) .collect::<Vec<_>>(); let mut data: Vec<Vec<RecordBatch>> = Vec::with_capacity(exec.output_partitioning().partition_count()); for task in tasks { let result = task.await.expect("MemTable::load could not join task")?; data.push(result); } let exec = MemoryExec::try_new(&data, schema.clone(), None)?; if let Some(num_partitions) = output_partitions { let exec = RepartitionExec::try_new( Arc::new(exec), Partitioning::RoundRobinBatch(num_partitions), )?; let mut output_partitions = vec![]; for i in 0..exec.output_partitioning().partition_count() { let mut stream = exec.execute(i, runtime.clone()).await?; let mut batches = vec![]; while let Some(result) = stream.next().await { batches.push(result?); } output_partitions.push(batches); } return MemTable::try_new(schema.clone(), output_partitions); } MemTable::try_new(schema.clone(), data) } } #[async_trait] impl TableProvider for MemTable { fn as_any(&self) -> &dyn Any { self } fn schema(&self) -> SchemaRef { self.schema.clone() } async fn scan( &self, projection: &Option<Vec<usize>>, _batch_size: usize, _filters: &[Expr], _limit: Option<usize>, ) -> Result<Arc<dyn ExecutionPlan>> { Ok(Arc::new(MemoryExec::try_new( &self.batches.clone(), self.schema(), projection.clone(), )?)) } } #[cfg(test)] mod tests { use super::*; use arrow::array::Int32Array; use arrow::datatypes::{DataType, Field, Schema}; use futures::StreamExt; use std::collections::HashMap; #[tokio::test] async fn test_with_projection() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); let schema = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), Field::new("d", DataType::Int32, true), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), Arc::new(Int32Array::from(vec![None, None, Some(9)])), ], )?; let provider = MemTable::try_new(schema, vec![vec![batch]])?; let exec = provider.scan(&Some(vec![2, 1]), 1024, &[], None).await?; let mut it = exec.execute(0, runtime).await?; let batch2 = it.next().await.unwrap()?; assert_eq!(2, batch2.schema().fields().len()); assert_eq!("c", batch2.schema().field(0).name()); assert_eq!("b", batch2.schema().field(1).name()); assert_eq!(2, batch2.num_columns()); Ok(()) } #[tokio::test] async fn test_without_projection() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); let schema = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; let provider = MemTable::try_new(schema, vec![vec![batch]])?; let exec = provider.scan(&None, 1024, &[], None).await?; let mut it = exec.execute(0, runtime).await?; let batch1 = it.next().await.unwrap()?; assert_eq!(3, batch1.schema().fields().len()); assert_eq!(3, batch1.num_columns()); Ok(()) } #[tokio::test] async fn test_invalid_projection() -> Result<()> { let schema = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; let provider = MemTable::try_new(schema, vec![vec![batch]])?; let projection: Vec<usize> = vec![0, 4]; match provider.scan(&Some(projection), 1024, &[], None).await { Err(DataFusionError::Internal(e)) => { assert_eq!("\"Projection index out of range\"", format!("{:?}", e)) } _ => panic!("Scan should failed on invalid projection"), }; Ok(()) } #[test] fn test_schema_validation_incompatible_column() -> Result<()> { let schema1 = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let schema2 = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Float64, false), Field::new("c", DataType::Int32, false), ])); let batch = RecordBatch::try_new( schema1, vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; match MemTable::try_new(schema2, vec![vec![batch]]) { Err(DataFusionError::Plan(e)) => assert_eq!( "\"Mismatch between schema and batches\"", format!("{:?}", e) ), _ => panic!("MemTable::new should have failed due to schema mismatch"), } Ok(()) } #[test] fn test_schema_validation_different_column_count() -> Result<()> { let schema1 = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let schema2 = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ])); let batch = RecordBatch::try_new( schema1, vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![7, 5, 9])), ], )?; match MemTable::try_new(schema2, vec![vec![batch]]) { Err(DataFusionError::Plan(e)) => assert_eq!( "\"Mismatch between schema and batches\"", format!("{:?}", e) ), _ => panic!("MemTable::new should have failed due to schema mismatch"), } Ok(()) } #[tokio::test] async fn test_merged_schema() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); let mut metadata = HashMap::new(); metadata.insert("foo".to_string(), "bar".to_string()); let schema1 = Schema::new_with_metadata( vec![ Field::new("a", DataType::Int32, false), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ], metadata, ); let schema2 = Schema::new(vec![ Field::new("a", DataType::Int32, true), Field::new("b", DataType::Int32, false), Field::new("c", DataType::Int32, false), ]); let merged_schema = Schema::try_merge(vec![schema1.clone(), schema2.clone()])?; let batch1 = RecordBatch::try_new( Arc::new(schema1), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; let batch2 = RecordBatch::try_new( Arc::new(schema2), vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(Int32Array::from(vec![4, 5, 6])), Arc::new(Int32Array::from(vec![7, 8, 9])), ], )?; let provider = MemTable::try_new(Arc::new(merged_schema), vec![vec![batch1, batch2]])?; let exec = provider.scan(&None, 1024, &[], None).await?; let mut it = exec.execute(0, runtime).await?; let batch1 = it.next().await.unwrap()?; assert_eq!(3, batch1.schema().fields().len()); assert_eq!(3, batch1.num_columns()); Ok(()) } }
pub fn try_new(schema: SchemaRef, partitions: Vec<Vec<RecordBatch>>) -> Result<Self> { if partitions .iter() .flatten() .all(|batches| schema.contains(&batches.schema())) { Ok(Self { schema, batches: partitions, }) } else { Err(DataFusionError::Plan( "Mismatch between schema and batches".to_string(), )) } }
function_block-full_function
[]
Rust
src/utils/random.rs
xiangminghu/native_spark
f6199cce8ec546b9f16e14b7d098801f28b08018
use std::any::Any; use std::rc::Rc; use downcast_rs::Downcast; use rand::{Rng, SeedableRng}; use rand_distr::{Bernoulli, Distribution, Poisson}; use rand_pcg::Pcg64; use crate::{Data, Deserialize, Serialize}; const DEFAULT_MAX_GAP_SAMPLING_FRACTION: f64 = 0.4; const RNG_EPSILON: f64 = 5e-11; const ROUNDING_EPSILON: f64 = 1e-6; type RSamplerFunc<'a, T> = Box<dyn Fn(Box<dyn Iterator<Item = T>>) -> Vec<T> + 'a>; pub(crate) trait RandomSampler<T: Data>: Send + Sync + Serialize + Deserialize { fn get_sampler(&self) -> RSamplerFunc<T>; } pub(crate) fn get_default_rng() -> Pcg64 { Pcg64::new( 0xcafe_f00d_d15e_a5e5, 0x0a02_bdbf_7bb3_c0a7_ac28_fa16_a64a_bf96, ) } fn get_rng_with_random_seed() -> Pcg64 { Pcg64::seed_from_u64(rand::random::<u64>()) } #[derive(Clone, Serialize, Deserialize)] pub(crate) struct PoissonSampler { fraction: f64, use_gap_sampling_if_possible: bool, prob: f64, } impl PoissonSampler { pub fn new(fraction: f64, use_gap_sampling_if_possible: bool) -> PoissonSampler { let prob = if fraction > 0.0 { fraction } else { 1.0 }; PoissonSampler { fraction, use_gap_sampling_if_possible, prob, } } } impl<T: Data> RandomSampler<T> for PoissonSampler { fn get_sampler(&self) -> RSamplerFunc<T> { Box::new(move |items: Box<dyn Iterator<Item = T>>| -> Vec<T> { if self.fraction <= 0.0 { vec![] } else { let use_gap_sampling = self.use_gap_sampling_if_possible && self.fraction <= DEFAULT_MAX_GAP_SAMPLING_FRACTION; let mut gap_sampling = if use_gap_sampling { Some(GapSamplingReplacement::new(self.fraction, RNG_EPSILON)) } else { None }; let dist = Poisson::new(self.prob).unwrap(); let mut rng = get_rng_with_random_seed(); items .flat_map(move |item| { let count = if use_gap_sampling { gap_sampling.as_mut().unwrap().sample() } else { dist.sample(&mut rng) }; if count != 0 { vec![item; count as usize] } else { vec![] } }) .collect() } }) } } #[derive(Clone, Serialize, Deserialize)] pub(crate) struct BernoulliSampler { fraction: f64, } impl BernoulliSampler { pub fn new(fraction: f64) -> BernoulliSampler { assert!(fraction >= (0.0 - ROUNDING_EPSILON) && fraction <= (1.0 + ROUNDING_EPSILON)); BernoulliSampler { fraction } } fn sample(&self, gap_sampling: Option<&mut GapSamplingReplacement>, rng: &mut Pcg64) -> u64 { match self.fraction { v if v <= 0.0 => 0, v if v >= 1.0 => 1, v if v <= DEFAULT_MAX_GAP_SAMPLING_FRACTION => gap_sampling.unwrap().sample(), v if rng.gen::<f64>() <= v => 1, _ => 0, } } } impl<T: Data> RandomSampler<T> for BernoulliSampler { fn get_sampler(&self) -> RSamplerFunc<T> { Box::new(move |items: Box<dyn Iterator<Item = T>>| -> Vec<T> { let mut gap_sampling = if self.fraction > 0.0 && self.fraction < 1.0 { Some(GapSamplingReplacement::new(self.fraction, RNG_EPSILON)) } else { None }; let mut rng = get_rng_with_random_seed(); items .filter(move |item| self.sample(gap_sampling.as_mut(), &mut rng) > 0) .collect() }) } } struct GapSamplingReplacement { fraction: f64, epsilon: f64, q: f64, rng: rand_pcg::Pcg64, count_for_dropping: u64, } impl GapSamplingReplacement { fn new(fraction: f64, epsilon: f64) -> GapSamplingReplacement { assert!(fraction > 0.0 && fraction < 1.0); assert!(epsilon > 0.0); let mut sampler = GapSamplingReplacement { q: (-fraction).exp(), fraction, epsilon, rng: get_rng_with_random_seed(), count_for_dropping: 0, }; sampler.advance(); sampler } fn sample(&mut self) -> u64 { if self.count_for_dropping > 0 { self.count_for_dropping -= 1; 0 } else { let r = self.poisson_ge1(); self.advance(); r } } fn poisson_ge1(&mut self) -> u64 { let mut pp: f64 = self.q + ((1.0 - self.q) * self.rng.gen::<f64>()); let mut r = 1; pp *= self.rng.gen::<f64>(); while pp > self.q { r += 1; pp *= self.rng.gen::<f64>() } r } fn advance(&mut self) { let u = self.epsilon.max(self.rng.gen::<f64>()); self.count_for_dropping = (u.log(std::f64::consts::E) / (-self.fraction)) as u64; } } pub(crate) fn compute_fraction_for_sample_size( sample_size_lower_bound: u64, total: u64, with_replacement: bool, ) -> f64 { if (with_replacement) { poisson_bounds::get_upper_bound(sample_size_lower_bound as f64) / total as f64 } else { let fraction = sample_size_lower_bound as f64 / total as f64; binomial_bounds::get_upper_bound(1e-4, total, fraction) } } mod poisson_bounds { pub(super) fn get_upper_bound(s: f64) -> f64 { (s + num_std(s) * s.sqrt()).max(1e-10) } #[inline(always)] fn num_std(s: f64) -> f64 { match s { v if v < 6.0 => 12.0, v if v < 16.0 => 9.0, _ => 6.0, } } } mod binomial_bounds { const MIN_SAMPLING_RATE: f64 = 1e-10; pub(super) fn get_upper_bound(delta: f64, n: u64, fraction: f64) -> f64 { let gamma = -delta.log(std::f64::consts::E) / n as f64; let max = MIN_SAMPLING_RATE .max(fraction + gamma + (gamma * gamma + 2.0 * gamma * fraction).sqrt()); max.min(1.0) } }
use std::any::Any; use std::rc::Rc; use downcast_rs::Downcast; use rand::{Rng, SeedableRng}; use rand_distr::{Bernoulli, Distribution, Poisson}; use rand_pcg::Pcg64; use crate::{Data, Deserialize, Serialize}; const DEFAULT_MAX_GAP_SAMPLING_FRACTION: f64 = 0.4; const RNG_EPSILON: f64 = 5e-11; const ROUNDING_EPSILON: f64 = 1e-6; type RSamplerFunc<'a, T> = Box<dyn Fn(Box<dyn Iterator<Item = T>>) -> Vec<T> + 'a>; pub(crate) trait RandomSampler<T: Data>: Send + Sync + Serialize + Deserialize { fn get_sampler(&self) -> RSamplerFunc<T>; } pub(crate) fn get_default_rng() -> Pcg64 { Pcg64::new( 0xcafe_f00d_d15e_a5e5, 0x0a02_bdbf_7bb3_c0a7_ac28_fa16_a64a_bf96, ) } fn get_rng_with_random_seed() -> Pcg64 { Pcg64::seed_from_u64(rand::random::<u64>()) } #[derive(Clone, Serialize, Deserialize)] pub(crate) struct PoissonSampler { fraction: f64, use_gap_sampling_if_possible: bool, prob: f64, } impl PoissonSampler { pub fn new(fraction: f64, use_gap_sampling_if_possible: bool) -> PoissonSampler { let prob = if fraction > 0.0 { fraction } else { 1.0 }; PoissonSampler { fraction, use_gap_sampling_if_possible, prob, } } } impl<T: Data> RandomSampler<T> for PoissonSampler { fn get_sampler(&self) -> RSamplerFunc<T> { Box::new(move |items: Box<dyn Iterator<Item = T>>| -> Vec<T> { if self.fraction <= 0.0 { vec![] } else { let use_gap_sampling = self.use_gap_sampling_if_possible && self.fraction <= DEFAULT_MAX_GAP_SAMPLING_FRACTION; let mut gap_sampling = if use_gap_sampling { Some(GapSamplingReplacement::new(self.fraction, RNG_EPSILON)) } else { None }; let dist = Poisson::new(self.prob).unwrap(); let mut rng = get_rng_with_random_seed(); items .flat_map(move |item| { let count = if use_gap_sampling { gap_sampling.as_mut().unwrap().sample() } else { dist.sample(&mut rng) }; if count != 0 { vec![item; count as usize] } else {
= 1e-10; pub(super) fn get_upper_bound(delta: f64, n: u64, fraction: f64) -> f64 { let gamma = -delta.log(std::f64::consts::E) / n as f64; let max = MIN_SAMPLING_RATE .max(fraction + gamma + (gamma * gamma + 2.0 * gamma * fraction).sqrt()); max.min(1.0) } }
vec![] } }) .collect() } }) } } #[derive(Clone, Serialize, Deserialize)] pub(crate) struct BernoulliSampler { fraction: f64, } impl BernoulliSampler { pub fn new(fraction: f64) -> BernoulliSampler { assert!(fraction >= (0.0 - ROUNDING_EPSILON) && fraction <= (1.0 + ROUNDING_EPSILON)); BernoulliSampler { fraction } } fn sample(&self, gap_sampling: Option<&mut GapSamplingReplacement>, rng: &mut Pcg64) -> u64 { match self.fraction { v if v <= 0.0 => 0, v if v >= 1.0 => 1, v if v <= DEFAULT_MAX_GAP_SAMPLING_FRACTION => gap_sampling.unwrap().sample(), v if rng.gen::<f64>() <= v => 1, _ => 0, } } } impl<T: Data> RandomSampler<T> for BernoulliSampler { fn get_sampler(&self) -> RSamplerFunc<T> { Box::new(move |items: Box<dyn Iterator<Item = T>>| -> Vec<T> { let mut gap_sampling = if self.fraction > 0.0 && self.fraction < 1.0 { Some(GapSamplingReplacement::new(self.fraction, RNG_EPSILON)) } else { None }; let mut rng = get_rng_with_random_seed(); items .filter(move |item| self.sample(gap_sampling.as_mut(), &mut rng) > 0) .collect() }) } } struct GapSamplingReplacement { fraction: f64, epsilon: f64, q: f64, rng: rand_pcg::Pcg64, count_for_dropping: u64, } impl GapSamplingReplacement { fn new(fraction: f64, epsilon: f64) -> GapSamplingReplacement { assert!(fraction > 0.0 && fraction < 1.0); assert!(epsilon > 0.0); let mut sampler = GapSamplingReplacement { q: (-fraction).exp(), fraction, epsilon, rng: get_rng_with_random_seed(), count_for_dropping: 0, }; sampler.advance(); sampler } fn sample(&mut self) -> u64 { if self.count_for_dropping > 0 { self.count_for_dropping -= 1; 0 } else { let r = self.poisson_ge1(); self.advance(); r } } fn poisson_ge1(&mut self) -> u64 { let mut pp: f64 = self.q + ((1.0 - self.q) * self.rng.gen::<f64>()); let mut r = 1; pp *= self.rng.gen::<f64>(); while pp > self.q { r += 1; pp *= self.rng.gen::<f64>() } r } fn advance(&mut self) { let u = self.epsilon.max(self.rng.gen::<f64>()); self.count_for_dropping = (u.log(std::f64::consts::E) / (-self.fraction)) as u64; } } pub(crate) fn compute_fraction_for_sample_size( sample_size_lower_bound: u64, total: u64, with_replacement: bool, ) -> f64 { if (with_replacement) { poisson_bounds::get_upper_bound(sample_size_lower_bound as f64) / total as f64 } else { let fraction = sample_size_lower_bound as f64 / total as f64; binomial_bounds::get_upper_bound(1e-4, total, fraction) } } mod poisson_bounds { pub(super) fn get_upper_bound(s: f64) -> f64 { (s + num_std(s) * s.sqrt()).max(1e-10) } #[inline(always)] fn num_std(s: f64) -> f64 { match s { v if v < 6.0 => 12.0, v if v < 16.0 => 9.0, _ => 6.0, } } } mod binomial_bounds { const MIN_SAMPLING_RATE: f64
random
[ { "content": "pub trait ShuffleDependencyTrait: Serialize + Deserialize + Send + Sync {\n\n fn get_shuffle_id(&self) -> usize;\n\n // fn get_partitioner(&self) -> &dyn PartitionerBox;\n\n fn is_shuffle(&self) -> bool;\n\n fn get_rdd_base(&self) -> Arc<dyn RddBase>;\n\n fn do_shuffle_task(&self, rdd_base: Arc<dyn RddBase>, partition: usize) -> String;\n\n}\n\n\n\nimpl PartialOrd for dyn ShuffleDependencyTrait {\n\n fn partial_cmp(&self, other: &dyn ShuffleDependencyTrait) -> Option<Ordering> {\n\n Some(self.get_shuffle_id().cmp(&other.get_shuffle_id()))\n\n }\n\n}\n\n\n\nimpl PartialEq for dyn ShuffleDependencyTrait {\n\n fn eq(&self, other: &dyn ShuffleDependencyTrait) -> bool {\n\n self.get_shuffle_id() == other.get_shuffle_id()\n\n }\n\n}\n\n\n", "file_path": "src/dependency.rs", "rank": 0, "score": 228938.13808375708 }, { "content": "pub trait NarrowDependencyTrait: Serialize + Deserialize + Send + Sync {\n\n fn get_parents(&self, partition_id: usize) -> Vec<usize>;\n\n fn get_rdd_base(&self) -> Arc<dyn RddBase>;\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Clone)]\n\npub struct OneToOneDependencyVals {\n\n // #[serde(with = \"serde_traitobject\")]\n\n // rdd: Arc<RT>,\n\n #[serde(with = \"serde_traitobject\")]\n\n rdd_base: Arc<dyn RddBase>,\n\n is_shuffle: bool,\n\n // _marker: PhantomData<T>,\n\n}\n\n\n\nimpl OneToOneDependencyVals {\n\n pub fn new(rdd_base: Arc<dyn RddBase>) -> Self {\n\n OneToOneDependencyVals {\n\n rdd_base,\n\n is_shuffle: false,\n\n }\n\n }\n\n}\n", "file_path": "src/dependency.rs", "rank": 1, "score": 228938.13808375708 }, { "content": "pub trait OneToOneDependencyTrait: Serialize + Deserialize + Send + Sync {\n\n fn get_parents(&self, partition_id: i64) -> Vec<i64>;\n\n fn get_rdd_base(&self) -> Arc<dyn RddBase>;\n\n}\n\n\n\nimpl OneToOneDependencyTrait for OneToOneDependencyVals {\n\n fn get_parents(&self, partition_id: i64) -> Vec<i64> {\n\n vec![partition_id]\n\n }\n\n\n\n fn get_rdd_base(&self) -> Arc<dyn RddBase> {\n\n self.rdd_base.clone()\n\n }\n\n}\n\n\n", "file_path": "src/dependency.rs", "rank": 2, "score": 223380.5047631206 }, { "content": "// Due to the lack of HKTs in Rust, it is difficult to have collection of generic data with different types.\n\n// Required for storing multiple RDDs inside dependencies and other places like Tasks, etc.,\n\n// Refactored RDD trait into two traits one having RddBase trait which contains only non generic methods which provide information for dependency lists\n\n// Another separate Rdd containing generic methods like map, etc.,\n\npub trait RddBase: Send + Sync + Serialize + Deserialize {\n\n fn get_rdd_id(&self) -> usize;\n\n fn get_context(&self) -> Arc<Context>;\n\n fn get_dependencies(&self) -> &[Dependency];\n\n fn preferred_locations(&self, split: Box<dyn Split>) -> Vec<Ipv4Addr> {\n\n Vec::new()\n\n }\n\n fn partitioner(&self) -> Option<Box<dyn Partitioner>> {\n\n None\n\n }\n\n fn splits(&self) -> Vec<Box<dyn Split>>;\n\n fn number_of_splits(&self) -> usize {\n\n self.splits().len()\n\n }\n\n // Analyse whether this is required or not. It requires downcasting while executing tasks which could hurt performance.\n\n fn iterator_any(\n\n &self,\n\n split: Box<dyn Split>,\n\n ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>>;\n\n fn cogroup_iterator_any(\n", "file_path": "src/rdd/mod.rs", "rank": 3, "score": 218594.73393550125 }, { "content": "pub trait Partitioner: Send + Sync + objekt::Clone + Serialize + Deserialize {\n\n fn equals(&self, other: &dyn Any) -> bool;\n\n fn get_num_of_partitions(&self) -> usize;\n\n fn get_partition(&self, key: &dyn Any) -> usize;\n\n}\n\nobjekt::clone_trait_object!(Partitioner);\n\n\n", "file_path": "src/partitioner.rs", "rank": 4, "score": 211202.84981765097 }, { "content": "pub trait TaskBase: Downcast + Send + Sync {\n\n fn get_run_id(&self) -> usize;\n\n fn get_stage_id(&self) -> usize;\n\n fn get_task_id(&self) -> usize;\n\n fn preferred_locations(&self) -> Vec<Ipv4Addr> {\n\n Vec::new()\n\n }\n\n fn generation(&self) -> Option<i64> {\n\n None\n\n }\n\n}\n\nimpl_downcast!(TaskBase);\n\n\n\nimpl PartialOrd for dyn TaskBase {\n\n fn partial_cmp(&self, other: &dyn TaskBase) -> Option<Ordering> {\n\n Some(self.get_task_id().cmp(&other.get_task_id()))\n\n }\n\n}\n\n\n\nimpl PartialEq for dyn TaskBase {\n", "file_path": "src/task.rs", "rank": 5, "score": 178955.58978479463 }, { "content": "// Trait containing pair rdd methods. No need of implicit conversion like in Spark version\n\npub trait PairRdd<K: Data + Eq + Hash, V: Data>: Rdd<(K, V)> + Send + Sync {\n\n fn combine_by_key<C: Data>(\n\n &self,\n\n create_combiner: Box<dyn serde_traitobject::Fn(V) -> C + Send + Sync>,\n\n merge_value: Box<dyn serde_traitobject::Fn((C, V)) -> C + Send + Sync>,\n\n merge_combiners: Box<dyn serde_traitobject::Fn((C, C)) -> C + Send + Sync>,\n\n partitioner: Box<dyn Partitioner>,\n\n // ) -> Arc<RddBox<(K, C)>>\n\n ) -> ShuffledRdd<K, V, C, Self>\n\n where\n\n // RT: RddBox<(K, V)>,\n\n Self: Sized + Serialize + Deserialize + 'static,\n\n {\n\n let aggregator = Arc::new(Aggregator::<K, V, C>::new(\n\n create_combiner,\n\n merge_value,\n\n merge_combiners,\n\n ));\n\n ShuffledRdd::new(self.get_rdd(), aggregator, partitioner)\n\n }\n", "file_path": "src/rdd/pair_rdd.rs", "rank": 6, "score": 170410.50725833979 }, { "content": "pub trait Task: TaskBase + Send + Sync + Downcast {\n\n fn run(&self, id: usize) -> serde_traitobject::Box<dyn serde_traitobject::Any + Send + Sync>;\n\n}\n\nimpl_downcast!(Task);\n\n\n", "file_path": "src/task.rs", "rank": 7, "score": 170151.24288408784 }, { "content": "// Data passing through RDD needs to satisfy the following traits.\n\n// Debug is only added here for debugging convenience during development stage but is not necessary.\n\n// Sync is also not necessary I think. Have to look into it.\n\npub trait Data:\n\n Clone\n\n + any::Any\n\n + Send\n\n + Sync\n\n + fmt::Debug\n\n + serde::ser::Serialize\n\n + serde::de::DeserializeOwned\n\n + 'static\n\n{\n\n}\n\nimpl<\n\n T: Clone\n\n + any::Any\n\n + Send\n\n + Sync\n\n + fmt::Debug\n\n + serde::ser::Serialize\n\n + serde::de::DeserializeOwned\n\n + 'static,\n\n > Data for T\n\n{\n\n}\n\n\n", "file_path": "src/serializable_traits.rs", "rank": 8, "score": 169032.87428613543 }, { "content": "pub trait AnyData:\n\n objekt::Clone + any::Any + Send + Sync + fmt::Debug + Serialize + Deserialize + 'static\n\n{\n\n fn as_any(&self) -> &dyn any::Any;\n\n /// Convert to a `&mut std::any::Any`.\n\n fn as_any_mut(&mut self) -> &mut dyn any::Any;\n\n /// Convert to a `std::boxed::Box<dyn std::any::Any>`.\n\n fn into_any(self: boxed::Box<Self>) -> boxed::Box<dyn any::Any>;\n\n /// Convert to a `std::boxed::Box<dyn std::any::Any + Send>`.\n\n fn into_any_send(self: boxed::Box<Self>) -> boxed::Box<dyn any::Any + Send>;\n\n /// Convert to a `std::boxed::Box<dyn std::any::Any + Sync>`.\n\n fn into_any_sync(self: boxed::Box<Self>) -> boxed::Box<dyn any::Any + Sync>;\n\n /// Convert to a `std::boxed::Box<dyn std::any::Any + Send + Sync>`.\n\n fn into_any_send_sync(self: boxed::Box<Self>) -> boxed::Box<dyn any::Any + Send + Sync>;\n\n}\n\n\n\nobjekt::clone_trait_object!(AnyData);\n\n\n\n// Automatically implementing the Data trait for all types which implements the required traits\n\nimpl<\n", "file_path": "src/serializable_traits.rs", "rank": 9, "score": 146508.5970218501 }, { "content": "pub trait Split: Downcast + objekt::Clone + Serialize + Deserialize {\n\n fn get_index(&self) -> usize;\n\n}\n\nimpl_downcast!(Split);\n\nobjekt::clone_trait_object!(Split);\n", "file_path": "src/split.rs", "rank": 10, "score": 136225.38147562166 }, { "content": "pub trait TaskBox: Task + Serialize + Deserialize + 'static + Downcast {}\n\n\n\nimpl<K> TaskBox for K where K: Task + Serialize + Deserialize + 'static {}\n\n\n\nimpl_downcast!(TaskBox);\n\n//#[derive(Serialize, Deserialize)]\n\n//pub struct SerializeableTask {\n\n// #[serde(with = \"serde_traitobject\")]\n\n// pub task: Box<TaskBox>,\n\n//}\n\n//\n\n#[derive(Serialize, Deserialize)]\n\npub enum TaskOption {\n\n #[serde(with = \"serde_traitobject\")]\n\n ResultTask(Box<dyn TaskBox>),\n\n #[serde(with = \"serde_traitobject\")]\n\n ShuffleMapTask(Box<dyn TaskBox>),\n\n}\n\n//\n\n#[derive(Serialize, Deserialize)]\n", "file_path": "src/task.rs", "rank": 11, "score": 132234.72692674233 }, { "content": "// Rdd containing methods associated with processing\n\npub trait Rdd<T: Data>: RddBase {\n\n fn get_rdd(&self) -> Arc<Self>\n\n where\n\n Self: Sized;\n\n fn get_rdd_base(&self) -> Arc<dyn RddBase>;\n\n fn iterator(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = T>>> {\n\n self.compute(split)\n\n }\n\n fn compute(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = T>>>;\n\n\n\n fn map<U: Data, F>(&self, f: F) -> MapperRdd<Self, T, U, F>\n\n where\n\n F: SerFunc(T) -> U,\n\n Self: Sized + 'static,\n\n {\n\n MapperRdd::new(self.get_rdd(), f)\n\n }\n\n\n\n fn flat_map<U: Data, F>(&self, f: F) -> FlatMapperRdd<Self, T, U, F>\n\n where\n", "file_path": "src/rdd/mod.rs", "rank": 12, "score": 130674.93925563144 }, { "content": "pub trait Func<Args>:\n\n ops::Fn<Args> + Serialize + Deserialize + Send + Sync + 'static + objekt::Clone\n\n{\n\n}\n\nimpl<T: ?Sized, Args> Func<Args> for T where\n\n T: ops::Fn<Args> + Serialize + Deserialize + Send + Sync + 'static + objekt::Clone\n\n{\n\n}\n\n\n\nimpl<Args: 'static, Output: 'static> std::clone::Clone\n\n for boxed::Box<dyn Func<Args, Output = Output>>\n\n{\n\n fn clone(&self) -> Self {\n\n objekt::clone_box(&**self)\n\n }\n\n}\n\n\n\nimpl<'a, Args, Output> AsRef<Self> for dyn Func<Args, Output = Output> + 'a {\n\n fn as_ref(&self) -> &Self {\n\n self\n", "file_path": "src/serializable_traits.rs", "rank": 15, "score": 108312.91894169242 }, { "content": "pub trait Scheduler {\n\n fn start(&self);\n\n fn wait_for_register(&self);\n\n fn run_job<T: Data, U: Data, RT, F>(\n\n &self,\n\n rdd: &RT,\n\n func: F,\n\n partitions: Vec<i64>,\n\n allow_local: bool,\n\n ) -> Vec<U>\n\n where\n\n Self: Sized,\n\n RT: Rdd<T>,\n\n F: Fn(Box<dyn Iterator<Item = T>>) -> U;\n\n fn stop(&self);\n\n fn default_parallelism(&self) -> i64;\n\n}\n", "file_path": "src/scheduler.rs", "rank": 16, "score": 107507.45979383495 }, { "content": "pub trait SerFunc<Args>:\n\n Fn<Args>\n\n + Send\n\n + Sync\n\n + Clone\n\n + serde::ser::Serialize\n\n + serde::de::DeserializeOwned\n\n + 'static\n\n + Serialize\n\n + Deserialize\n\n{\n\n}\n\nimpl<Args, T> SerFunc<Args> for T where\n\n T: Fn<Args>\n\n + Send\n\n + Sync\n\n + Clone\n\n + serde::ser::Serialize\n\n + serde::de::DeserializeOwned\n\n + 'static\n\n + Serialize\n\n + Deserialize\n\n{\n\n}\n\n\n", "file_path": "src/serializable_traits.rs", "rank": 17, "score": 105919.00278050362 }, { "content": "pub trait Reduce<T> {\n\n fn reduce<F>(self, f: F) -> Option<T>\n\n where\n\n Self: Sized,\n\n F: FnMut(T, T) -> T;\n\n}\n\n\n\nimpl<T, I> Reduce<T> for I\n\nwhere\n\n I: Iterator<Item = T>,\n\n{\n\n #[inline]\n\n fn reduce<F>(mut self, f: F) -> Option<T>\n\n where\n\n Self: Sized,\n\n F: FnMut(T, T) -> T,\n\n {\n\n self.next().map(|first| self.fold(first, f))\n\n }\n\n}\n", "file_path": "src/rdd/mod.rs", "rank": 18, "score": 98270.75630289825 }, { "content": "/// A collection of objects which can be sliced into partitions with a partitioning function.\n\npub trait Chunkable<D>\n\nwhere\n\n D: Data,\n\n{\n\n fn slice_with_set_parts(self, parts: usize) -> Vec<Arc<Vec<D>>>;\n\n\n\n fn slice(self) -> Vec<Arc<Vec<D>>>\n\n where\n\n Self: Sized,\n\n {\n\n let as_many_parts_as_cpus = num_cpus::get();\n\n self.slice_with_set_parts(as_many_parts_as_cpus)\n\n }\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Clone)]\n\npub struct ParallelCollectionSplit<T> {\n\n rdd_id: i64,\n\n index: usize,\n\n values: Arc<Vec<T>>,\n", "file_path": "src/parallel_collection.rs", "rank": 19, "score": 98270.75630289825 }, { "content": "fn read(file: String) -> Box<dyn Iterator<Item = ((i32, String, i64), (i64, f64))>> {\n\n let file = File::open(&Path::new(&file)).unwrap();\n\n let reader = SerializedFileReader::new(file).unwrap();\n\n let metadata = reader.metadata();\n\n let batch_size = 500_000 as usize;\n\n //let reader = Rc::new(RefCell::new(reader));\n\n let iter = (0..metadata.num_row_groups()).flat_map(move |i| {\n\n //let reader = reader.borrow_mut();\n\n let row_group_reader = reader.get_row_group(i).unwrap();\n\n let mut first_reader =\n\n get_typed_column_reader::<Int32Type>(row_group_reader.get_column_reader(0).unwrap());\n\n let mut second_reader = get_typed_column_reader::<ByteArrayType>(\n\n row_group_reader.get_column_reader(1).unwrap(),\n\n );\n\n let mut bytes_reader =\n\n get_typed_column_reader::<Int64Type>(row_group_reader.get_column_reader(7).unwrap());\n\n let mut time_reader =\n\n get_typed_column_reader::<Int64Type>(row_group_reader.get_column_reader(8).unwrap());\n\n let num_rows = metadata.row_group(i).num_rows() as usize;\n\n println!(\"row group rows {}\", num_rows);\n", "file_path": "examples/parquet_column_read.rs", "rank": 20, "score": 97417.6191786943 }, { "content": "pub trait DAGScheduler: Scheduler {\n\n fn submit_tasks(&self, tasks: Vec<Box<dyn TaskBase>>, run_id: i64) -> ();\n\n fn task_ended(\n\n task: Box<dyn TaskBase>,\n\n reason: TastEndReason,\n\n result: Box<dyn Any>,\n\n accum_updates: HashMap<i64, Box<dyn Any>>,\n\n ) {\n\n unimplemented!()\n\n }\n\n}\n", "file_path": "src/dag_scheduler.rs", "rank": 21, "score": 95747.21322805116 }, { "content": "pub trait ReaderConfiguration<D>\n\nwhere\n\n D: Data,\n\n{\n\n type Reader: Chunkable<D> + Sized;\n\n fn make_reader(self) -> Self::Reader;\n\n}\n", "file_path": "src/io/mod.rs", "rank": 22, "score": 95747.21322805116 }, { "content": "pub trait DAGTask: TaskBase {\n\n fn get_run_id(&self) -> usize;\n\n fn get_stage_id(&self) -> usize;\n\n fn get_gen(&self) -> i64;\n\n fn generation(&self) -> Option<i64> {\n\n Some(self.get_gen())\n\n }\n\n}\n\n\n", "file_path": "src/dag_scheduler.rs", "rank": 23, "score": 93424.17851608511 }, { "content": " trait AnyDataWithEq: AnyData + PartialEq {}\n\n impl<T: AnyData + PartialEq> AnyDataWithEq for T {}\n\n let aggr = Arc::new(\n\n Aggregator::<K, Box<dyn AnyData>, Vec<Box<dyn AnyData>>>::new(\n\n create_combiner,\n\n merge_value,\n\n merge_combiners,\n\n ),\n\n );\n\n let mut deps = Vec::new();\n\n for (index, rdd) in rdds.iter().enumerate() {\n\n let part = part.clone();\n\n if rdd\n\n .partitioner()\n\n .map_or(false, |p| p.equals(&part as &dyn Any))\n\n {\n\n let rdd_base = rdd.clone().into();\n\n deps.push(Dependency::OneToOneDependency(\n\n Arc::new(OneToOneDependencyVals::new(rdd_base))\n\n as Arc<dyn OneToOneDependencyTrait>,\n", "file_path": "src/rdd/co_grouped_rdd.rs", "rank": 24, "score": 81215.19251854463 }, { "content": "fn main() {\n\n capnpc::CompilerCommand::new()\n\n .src_prefix(\"src\")\n\n .file(\"src/capnp/serialized_data.capnp\")\n\n .run()\n\n .expect(\"capnpc compiling issue\");\n\n}\n", "file_path": "build.rs", "rank": 25, "score": 57378.419029814664 }, { "content": "#[derive(Clone, Serialize, Deserialize)]\n\nstruct ShuffledRddSplit {\n\n index: usize,\n\n}\n\nimpl ShuffledRddSplit {\n\n fn new(index: usize) -> Self {\n\n ShuffledRddSplit { index }\n\n }\n\n}\n\n\n\nimpl Split for ShuffledRddSplit {\n\n fn get_index(&self) -> usize {\n\n self.index\n\n }\n\n}\n\n\n\n#[derive(Serialize, Deserialize)]\n\npub struct ShuffledRdd<K: Data + Eq + Hash, V: Data, C: Data, RT: 'static>\n\nwhere\n\n RT: Rdd<(K, V)>,\n\n{\n", "file_path": "src/rdd/shuffled_rdd.rs", "rank": 27, "score": 54344.818249714604 }, { "content": "fn tear_down() {\n\n // Clean up files\n\n let temp_dir = WORK_DIR.join(TEST_DIR);\n\n remove_dir_all(temp_dir).unwrap();\n\n}\n\n\n", "file_path": "tests/test_rdd.rs", "rank": 28, "score": 53902.19721187878 }, { "content": "#[derive(Clone, Serialize, Deserialize)]\n\nstruct CoGroupSplit {\n\n index: usize,\n\n deps: Vec<CoGroupSplitDep>,\n\n}\n\n\n\nimpl CoGroupSplit {\n\n fn new(index: usize, deps: Vec<CoGroupSplitDep>) -> Self {\n\n CoGroupSplit { index, deps }\n\n }\n\n}\n\n\n\nimpl Hasher for CoGroupSplit {\n\n fn finish(&self) -> u64 {\n\n self.index as u64\n\n }\n\n fn write(&mut self, bytes: &[u8]) {\n\n for i in bytes {\n\n self.write_u8(*i);\n\n }\n\n }\n", "file_path": "src/rdd/co_grouped_rdd.rs", "rank": 29, "score": 53172.51274718653 }, { "content": "#[test]\n\nfn test_aggregate() {\n\n let sc = CONTEXT.clone();\n\n let pairs = sc.make_rdd(\n\n vec![\n\n (\"a\".to_owned(), 1_i32),\n\n (\"b\".to_owned(), 2),\n\n (\"a\".to_owned(), 2),\n\n (\"c\".to_owned(), 5),\n\n (\"a\".to_owned(), 3),\n\n ],\n\n 2,\n\n );\n\n use std::collections::{HashMap, HashSet};\n\n type StringMap = HashMap<String, i32>;\n\n let emptyMap = StringMap::new();\n\n let merge_element = Fn!(|mut map: StringMap, pair: (String, i32)| {\n\n *map.entry(pair.0).or_insert(0) += pair.1;\n\n map\n\n });\n\n let merge_maps = Fn!(|mut map1: StringMap, map2: StringMap| {\n", "file_path": "tests/test_rdd.rs", "rank": 30, "score": 52399.2686126869 }, { "content": "#[test]\n\nfn test_first() {\n\n let sc = CONTEXT.clone();\n\n let col1 = vec![1, 2, 3, 4];\n\n let col1_rdd = sc.clone().parallelize(col1, 4);\n\n\n\n let taken_1 = col1_rdd.first();\n\n assert!(taken_1.is_ok());\n\n\n\n let col2: Vec<i32> = vec![];\n\n let col2_rdd = sc.parallelize(col2, 4);\n\n let taken_0 = col2_rdd.first();\n\n assert!(taken_0.is_err());\n\n}\n\n\n", "file_path": "tests/test_rdd.rs", "rank": 31, "score": 52399.2686126869 }, { "content": "#[test]\n\nfn test_fold() {\n\n let sc = CONTEXT.clone();\n\n let rdd = sc.make_rdd((-1000..1000).collect::<Vec<_>>(), 10);\n\n let f = Fn!(|c, x| c + x);\n\n // def op: (Int, Int) => Int = (c: Int, x: Int) => c + x\n\n let sum = rdd.fold(0, f).unwrap();\n\n assert_eq!(sum, -1000)\n\n}\n\n\n", "file_path": "tests/test_rdd.rs", "rank": 32, "score": 52399.2686126869 }, { "content": "#[test]\n\nfn test_take() {\n\n let sc = CONTEXT.clone();\n\n let col1 = vec![1, 2, 3, 4, 5, 6];\n\n let col1_rdd = sc.clone().parallelize(col1, 4);\n\n\n\n let taken_1 = col1_rdd.take(1).unwrap();\n\n assert_eq!(taken_1.len(), 1);\n\n\n\n let taken_3 = col1_rdd.take(3).unwrap();\n\n assert_eq!(taken_3.len(), 3);\n\n\n\n let taken_7 = col1_rdd.take(7).unwrap();\n\n assert_eq!(taken_7.len(), 6);\n\n\n\n let col2: Vec<i32> = vec![];\n\n let col2_rdd = sc.clone().parallelize(col2, 4);\n\n let taken_0 = col2_rdd.take(1).unwrap();\n\n assert!(taken_0.is_empty());\n\n}\n\n\n", "file_path": "tests/test_rdd.rs", "rank": 33, "score": 52399.2686126869 }, { "content": "#[test]\n\nfn test_distinct() {\n\n use std::collections::HashSet;\n\n let sc = CONTEXT.clone();\n\n let rdd = sc\n\n .clone()\n\n .parallelize(vec![1, 2, 2, 2, 3, 3, 3, 4, 4, 5], 3);\n\n assert!(rdd.distinct().collect().unwrap().len() == 5);\n\n assert!(\n\n rdd.distinct()\n\n .collect()\n\n .unwrap()\n\n .into_iter()\n\n .collect::<HashSet<_>>()\n\n == rdd\n\n .distinct()\n\n .collect()\n\n .unwrap()\n\n .into_iter()\n\n .collect::<HashSet<_>>()\n\n );\n", "file_path": "tests/test_rdd.rs", "rank": 34, "score": 52399.2686126869 }, { "content": "fn main() -> Result<()> {\n\n let sc = Context::new(&get_mode())?;\n\n let vec = vec![\n\n (\"x\".to_string(), 1),\n\n (\"x\".to_string(), 2),\n\n (\"x\".to_string(), 3),\n\n (\"x\".to_string(), 4),\n\n (\"x\".to_string(), 5),\n\n (\"x\".to_string(), 6),\n\n (\"x\".to_string(), 7),\n\n (\"y\".to_string(), 1),\n\n (\"y\".to_string(), 2),\n\n (\"y\".to_string(), 3),\n\n (\"y\".to_string(), 4),\n\n (\"y\".to_string(), 5),\n\n (\"y\".to_string(), 6),\n\n (\"y\".to_string(), 7),\n\n (\"y\".to_string(), 8),\n\n ];\n\n let r = sc.make_rdd(vec, 4);\n\n let g = r.group_by_key(4);\n\n let res = g.collect().unwrap();\n\n println!(\"res {:?}\", res);\n\n Ok(())\n\n}\n", "file_path": "examples/group_by.rs", "rank": 35, "score": 51983.80442300072 }, { "content": "fn main() -> Result<()> {\n\n let sc = Context::new(&get_mode())?;\n\n let col1 = vec![\n\n (1, (\"A\".to_string(), \"B\".to_string())),\n\n (2, (\"C\".to_string(), \"D\".to_string())),\n\n (3, (\"E\".to_string(), \"F\".to_string())),\n\n (4, (\"G\".to_string(), \"H\".to_string())),\n\n ];\n\n let col1 = sc.parallelize(col1, 4);\n\n let col2 = vec![\n\n (1, \"A1\".to_string()),\n\n (1, \"A2\".to_string()),\n\n (2, \"B1\".to_string()),\n\n (2, \"B2\".to_string()),\n\n (3, \"C1\".to_string()),\n\n (3, \"C2\".to_string()),\n\n ];\n\n let col2 = sc.parallelize(col2, 4);\n\n let inner_joined_rdd = col2.join(col1.clone(), 4);\n\n let res = inner_joined_rdd.collect().unwrap();\n\n println!(\"res {:?}\", res);\n\n Ok(())\n\n}\n", "file_path": "examples/join.rs", "rank": 36, "score": 51983.80442300072 }, { "content": "#[test]\n\nfn test_join() {\n\n let sc = CONTEXT.clone();\n\n let col1 = vec![\n\n (1, (\"A\".to_string(), \"B\".to_string())),\n\n (2, (\"C\".to_string(), \"D\".to_string())),\n\n (3, (\"E\".to_string(), \"F\".to_string())),\n\n (4, (\"G\".to_string(), \"H\".to_string())),\n\n ];\n\n let col1 = sc.clone().parallelize(col1, 4);\n\n let col2 = vec![\n\n (1, \"A1\".to_string()),\n\n (1, \"A2\".to_string()),\n\n (2, \"B1\".to_string()),\n\n (2, \"B2\".to_string()),\n\n (3, \"C1\".to_string()),\n\n (3, \"C2\".to_string()),\n\n ];\n\n let col2 = sc.clone().parallelize(col2, 4);\n\n let inner_joined_rdd = col2.join(col1.clone(), 4);\n\n let mut res = inner_joined_rdd.collect().unwrap();\n", "file_path": "tests/test_pair_rdd.rs", "rank": 37, "score": 51026.0624629267 }, { "content": "#[test]\n\nfn test_map_partitions() {\n\n let sc = CONTEXT.clone();\n\n let rdd = sc.clone().make_rdd(vec![1, 2, 3, 4], 2);\n\n let partition_sums = rdd\n\n .map_partitions(Fn!(\n\n |iter: Box<dyn Iterator<Item = i64>>| Box::new(std::iter::once(iter.sum::<i64>()))\n\n as Box<dyn Iterator<Item = i64>>\n\n ))\n\n .collect()\n\n .unwrap();\n\n assert_eq!(partition_sums, vec![3, 7]);\n\n assert_eq!(rdd.glom().collect().unwrap(), vec![vec![1, 2], vec![3, 4]]);\n\n}\n\n\n", "file_path": "tests/test_rdd.rs", "rank": 38, "score": 51026.0624629267 }, { "content": "#[test]\n\nfn test_group_by() {\n\n let sc = CONTEXT.clone();\n\n let vec = vec![\n\n (\"x\".to_string(), 1),\n\n (\"x\".to_string(), 2),\n\n (\"x\".to_string(), 3),\n\n (\"x\".to_string(), 4),\n\n (\"x\".to_string(), 5),\n\n (\"x\".to_string(), 6),\n\n (\"x\".to_string(), 7),\n\n (\"y\".to_string(), 1),\n\n (\"y\".to_string(), 2),\n\n (\"y\".to_string(), 3),\n\n (\"y\".to_string(), 4),\n\n (\"y\".to_string(), 5),\n\n (\"y\".to_string(), 6),\n\n (\"y\".to_string(), 7),\n\n (\"y\".to_string(), 8),\n\n ];\n\n let r = sc.clone().make_rdd(vec, 4);\n", "file_path": "tests/test_pair_rdd.rs", "rank": 39, "score": 51026.0624629267 }, { "content": "#[test]\n\nfn test_make_rdd() {\n\n // for distributed mode, use Context::new(\"distributed\")\n\n let sc = CONTEXT.clone();\n\n let col = sc.clone().make_rdd((0..10).collect::<Vec<_>>(), 32);\n\n //Fn! will make the closures serializable. It is necessary. use serde_closure version 0.1.3.\n\n let vec_iter = col.map(Fn!(|i| (0..i).collect::<Vec<_>>()));\n\n col.for_each(Fn!(|i| println!(\"{:?}\", i))).unwrap();\n\n col.for_each_partition(Fn!(|i: Box<Iterator<Item = i64>>| println!(\n\n \"{:?}\",\n\n i.collect::<Vec<_>>()\n\n )))\n\n .unwrap();\n\n let res = vec_iter.collect().unwrap();\n\n\n\n let expected = (0..10)\n\n .map(|i| (0..i).collect::<Vec<_>>())\n\n .collect::<Vec<_>>();\n\n println!(\"{:?}\", res);\n\n assert_eq!(expected, res);\n\n}\n\n\n", "file_path": "tests/test_rdd.rs", "rank": 40, "score": 51026.0624629267 }, { "content": "#[test]\n\nfn test_read_files() {\n\n // Single file test\n\n let file_name = \"test_file_01\";\n\n let file_path = WORK_DIR.join(TEST_DIR).join(file_name);\n\n set_up(file_name);\n\n\n\n let processor = Fn!(|reader: DistributedLocalReader| {\n\n let mut files: Vec<_> = reader.into_iter().collect();\n\n assert_eq!(files.len(), 1);\n\n\n\n // do stuff with the read files ...\n\n let parsed: Vec<_> = String::from_utf8(files.pop().unwrap())\n\n .unwrap()\n\n .lines()\n\n .map(|s| s.to_string())\n\n .collect();\n\n\n\n assert_eq!(parsed.len(), 2);\n\n assert_eq!(parsed[0], \"This is some textual test data.\");\n\n\n", "file_path": "tests/test_rdd.rs", "rank": 41, "score": 51026.0624629267 }, { "content": "#[test]\n\n#[cfg(test)]\n\nfn test_randomize_in_place() {\n\n use rand::SeedableRng;\n\n let mut sample = vec![1_i64, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\n\n\n let mut randomized_samples = vec![];\n\n for seed in 0..10 {\n\n let mut rng = rand_pcg::Pcg64::seed_from_u64(seed);\n\n let mut copied_sample = sample.clone();\n\n randomize_in_place(&mut copied_sample, &mut rng);\n\n randomized_samples.push(copied_sample);\n\n }\n\n randomized_samples.push(sample);\n\n\n\n let equal: u8 = randomized_samples\n\n .iter()\n\n .enumerate()\n\n .map(|(i, v)| {\n\n let cmp1 = &randomized_samples[0..i];\n\n let cmp2 = &randomized_samples[i + 1..];\n\n if cmp1.iter().any(|x| x == v) || cmp2.iter().any(|x| x == v) {\n\n 1\n\n } else {\n\n 0\n\n }\n\n })\n\n .sum();\n\n\n\n assert!(equal == 0);\n\n}\n", "file_path": "src/utils/mod.rs", "rank": 42, "score": 51026.0624629267 }, { "content": "fn main() -> Result<()> {\n\n let sc = Context::new(&get_mode())?;\n\n let files = fs::read_dir(\"csv_folder\")\n\n .unwrap()\n\n .map(|x| x.unwrap().path().to_str().unwrap().to_owned())\n\n .collect::<Vec<_>>();\n\n let len = files.len();\n\n let files = sc.make_rdd(files, len);\n\n let lines = files.flat_map(Fn!(|file| {\n\n let f = fs::File::open(file).expect(\"unable to create file\");\n\n let f = BufReader::new(f);\n\n Box::new(f.lines().map(|line| line.unwrap())) as Box<dyn Iterator<Item = String>>\n\n }));\n\n let line = lines.map(Fn!(|line: String| {\n\n let line = line.split(' ').collect::<Vec<_>>();\n\n let mut time: i64 = line[8].parse::<i64>().unwrap();\n\n time /= 1000;\n\n let time = Utc.timestamp(time, 0).hour();\n\n (\n\n (line[0].to_string(), line[1].to_string(), time),\n\n (line[7].parse::<i64>().unwrap(), 1.0),\n\n )\n\n }));\n\n let sum = line.reduce_by_key(Fn!(|((vl, cl), (vr, cr))| (vl + vr, cl + cr)), 1);\n\n let avg = sum.map(Fn!(|(k, (v, c))| (k, v as f64 / c)));\n\n let res = avg.collect().unwrap();\n\n println!(\"{:?}\", &res[0]);\n\n Ok(())\n\n}\n", "file_path": "examples/file_read.rs", "rank": 43, "score": 50480.87582380884 }, { "content": "fn get_mode() -> String {\n\n let args = std::env::args().skip(1).collect::<Vec<_>>();\n\n match args.get(0) {\n\n Some(val) if val == \"distributed\" => val.to_owned(),\n\n _ => \"local\".to_owned(),\n\n }\n\n}\n\n\n", "file_path": "examples/group_by.rs", "rank": 44, "score": 50480.87582380884 }, { "content": "fn main() -> Result<()> {\n\n let sc = Context::new(&get_mode())?;\n\n let col = sc.make_rdd((0..10).collect::<Vec<_>>(), 32);\n\n //Fn! will make the closures serializable. It is necessary. use serde_closure version 0.1.3.\n\n let vec_iter = col.map(Fn!(|i| (0..i).collect::<Vec<_>>()));\n\n let res = vec_iter.collect().unwrap();\n\n println!(\"result: {:?}\", res);\n\n Ok(())\n\n}\n", "file_path": "examples/make_rdd.rs", "rank": 45, "score": 50480.87582380884 }, { "content": "fn get_mode() -> String {\n\n let args = std::env::args().skip(1).collect::<Vec<_>>();\n\n match args.get(0) {\n\n Some(val) if val == \"distributed\" => val.to_owned(),\n\n _ => \"local\".to_owned(),\n\n }\n\n}\n\n\n", "file_path": "examples/join.rs", "rank": 46, "score": 50480.87582380884 }, { "content": "#[test]\n\nfn test_partition_wise_sampling() {\n\n let sc = CONTEXT.clone();\n\n // w/o replace & num < sample\n\n {\n\n let rdd = sc.clone().parallelize(vec![1, 2, 3, 4, 5], 6);\n\n let result = rdd.take_sample(false, 6, Some(123)).unwrap();\n\n assert!(result.len() == 5);\n\n // guaranteed with this seed:\n\n assert!(result[0] > result[1]);\n\n }\n\n\n\n // replace & Poisson & no-GapSampling\n\n {\n\n // high enough samples param to guarantee drawing >1 times w/ replacement\n\n let rdd = sc.clone().parallelize((0_i32..100).collect::<Vec<_>>(), 5);\n\n let result = rdd.take_sample(true, 80, None).unwrap();\n\n assert!(result.len() == 80);\n\n }\n\n\n\n // no replace & Bernoulli + GapSampling\n\n {\n\n let rdd = sc.clone().parallelize((0_i32..100).collect::<Vec<_>>(), 5);\n\n let result = rdd.take_sample(false, 10, None).unwrap();\n\n assert!(result.len() == 10);\n\n }\n\n}\n", "file_path": "tests/test_rdd.rs", "rank": 47, "score": 49766.47847259443 }, { "content": "fn main() -> Result<()> {\n\n let sc = Context::new(&get_mode())?;\n\n let files = fs::read_dir(\"parquet_file_dir\")\n\n .unwrap()\n\n .map(|x| x.unwrap().path().to_str().unwrap().to_owned())\n\n .collect::<Vec<_>>();\n\n let len = files.len();\n\n let files = sc.make_rdd(files, len);\n\n let read = files.flat_map(Fn!(|file| read(file)));\n\n let sum = read.reduce_by_key(Fn!(|((vl, cl), (vr, cr))| (vl + vr, cl + cr)), 1);\n\n let avg = sum.map(Fn!(|(k, (v, c))| (k, v as f64 / c)));\n\n let res = avg.collect().unwrap();\n\n println!(\"{:?}\", &res[0]);\n\n Ok(())\n\n}\n\n\n", "file_path": "examples/parquet_column_read.rs", "rank": 48, "score": 49107.66967404864 }, { "content": "fn get_mode() -> String {\n\n let args = std::env::args().skip(1).collect::<Vec<_>>();\n\n match args.get(0) {\n\n Some(val) if val == \"distributed\" => val.to_owned(),\n\n _ => \"local\".to_owned(),\n\n }\n\n}\n\n\n", "file_path": "examples/make_rdd.rs", "rank": 49, "score": 49107.66967404864 }, { "content": "fn get_mode() -> String {\n\n let args = std::env::args().skip(1).collect::<Vec<_>>();\n\n match args.get(0) {\n\n Some(val) if val == \"distributed\" => val.to_owned(),\n\n _ => \"local\".to_owned(),\n\n }\n\n}\n\n\n", "file_path": "examples/file_read.rs", "rank": 50, "score": 49107.66967404864 }, { "content": "#[test]\n\nfn test_fold_with_modifying_initial_value() {\n\n let sc = CONTEXT.clone();\n\n let rdd = sc\n\n .make_rdd((-1000..1000).collect::<Vec<i32>>(), 10)\n\n .map(Fn!(|x| vec![x]));\n\n let f = Fn!(|mut c: Vec<i32>, x: Vec<i32>| {\n\n c[0] = c[0] + x[0];\n\n c\n\n });\n\n let sum = rdd.fold(vec![0], f).unwrap();\n\n assert_eq!(sum[0], -1000)\n\n}\n\n\n", "file_path": "tests/test_rdd.rs", "rank": 51, "score": 48606.97485193367 }, { "content": "fn get_mode() -> String {\n\n let args = std::env::args().skip(1).collect::<Vec<_>>();\n\n match args.get(0) {\n\n Some(val) if val == \"distributed\" => val.to_owned(),\n\n _ => \"local\".to_owned(),\n\n }\n\n}\n\n\n", "file_path": "examples/parquet_column_read.rs", "rank": 52, "score": 47848.08568371637 }, { "content": "fn set_up(file_name: &str) {\n\n let temp_dir = WORK_DIR.join(TEST_DIR);\n\n println!(\"Creating tests in dir: {}\", (&temp_dir).to_str().unwrap());\n\n create_dir_all(&temp_dir).unwrap();\n\n\n\n let fixture =\n\n b\"This is some textual test data.\\nCan be converted to strings and there are two lines.\";\n\n\n\n let mut f = File::create(temp_dir.join(file_name)).unwrap();\n\n f.write_all(fixture).unwrap();\n\n}\n\n\n", "file_path": "tests/test_rdd.rs", "rank": 53, "score": 46256.84656797716 }, { "content": "fn initialize_loggers(file_path: String) {\n\n let term_logger = TermLogger::new(LevelFilter::Info, Config::default(), TerminalMode::Mixed);\n\n let file_logger: Box<dyn SharedLogger> = WriteLogger::new(\n\n LevelFilter::Info,\n\n Config::default(),\n\n File::create(file_path).expect(\"not able to create log file\"),\n\n );\n\n let mut combined = vec![file_logger];\n\n if let Some(logger) = term_logger {\n\n let logger: Box<dyn SharedLogger> = logger;\n\n combined.push(logger);\n\n }\n\n CombinedLogger::init(combined);\n\n}\n", "file_path": "src/context.rs", "rank": 54, "score": 46256.84656797716 }, { "content": "fn test_runner<T>(test: T)\n\nwhere\n\n T: FnOnce() -> () + std::panic::UnwindSafe,\n\n{\n\n let result = std::panic::catch_unwind(|| test());\n\n tear_down();\n\n assert!(result.is_ok())\n\n}\n\n\n", "file_path": "tests/test_rdd.rs", "rank": 55, "score": 43756.145770322764 }, { "content": "fn hash<T: Hash>(t: &T) -> u64 {\n\n let mut s: MetroHasher = Default::default();\n\n t.hash(&mut s);\n\n s.finish()\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct HashPartitioner<K: Data + Hash + Eq> {\n\n partitions: usize,\n\n _marker: PhantomData<K>,\n\n}\n\n\n\n// Hash partitioner implementing naive hash function.\n\nimpl<K: Data + Hash + Eq> HashPartitioner<K> {\n\n pub fn new(partitions: usize) -> Self {\n\n HashPartitioner {\n\n partitions,\n\n _marker: PhantomData,\n\n }\n\n }\n", "file_path": "src/partitioner.rs", "rank": 56, "score": 42779.64996387408 }, { "content": "use objekt;\n\nuse serde_traitobject::{deserialize, serialize, Deserialize, Serialize};\n\nuse std::{\n\n any,\n\n borrow::{Borrow, BorrowMut},\n\n boxed, error, fmt, marker,\n\n ops::{self, Deref, DerefMut},\n\n};\n\n\n\n// Data passing through RDD needs to satisfy the following traits.\n\n// Debug is only added here for debugging convenience during development stage but is not necessary.\n\n// Sync is also not necessary I think. Have to look into it.\n", "file_path": "src/serializable_traits.rs", "rank": 57, "score": 34971.936445196356 }, { "content": " T: objekt::Clone + any::Any + Send + Sync + fmt::Debug + Serialize + Deserialize + 'static,\n\n > AnyData for T\n\n{\n\n fn as_any(&self) -> &dyn any::Any {\n\n self\n\n }\n\n fn as_any_mut(&mut self) -> &mut dyn any::Any {\n\n self\n\n }\n\n fn into_any(self: boxed::Box<Self>) -> boxed::Box<dyn any::Any> {\n\n self\n\n }\n\n fn into_any_send(self: boxed::Box<Self>) -> boxed::Box<dyn any::Any + Send> {\n\n self\n\n }\n\n fn into_any_sync(self: boxed::Box<Self>) -> boxed::Box<dyn any::Any + Sync> {\n\n self\n\n }\n\n fn into_any_send_sync(self: boxed::Box<Self>) -> boxed::Box<dyn any::Any + Send + Sync> {\n\n self\n", "file_path": "src/serializable_traits.rs", "rank": 58, "score": 34969.14575487182 }, { "content": " fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: serde::Serializer,\n\n {\n\n serialize(&self, serializer)\n\n }\n\n}\n\nimpl<'de> serde::de::Deserialize<'de> for boxed::Box<dyn AnyData + Send + 'static> {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n\n where\n\n D: serde::Deserializer<'de>,\n\n {\n\n <Box<dyn AnyData + Send + 'static>>::deserialize(deserializer).map(|x| x.0)\n\n }\n\n}\n\n\n\n#[derive(Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]\n\npub struct Box<T: ?Sized>(boxed::Box<T>);\n\nimpl<T> Box<T> {\n\n // Create a new Box wrapper\n", "file_path": "src/serializable_traits.rs", "rank": 59, "score": 34968.69470988223 }, { "content": " }\n\n}\n\n\n\nimpl serde::ser::Serialize for boxed::Box<dyn AnyData + 'static> {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: serde::Serializer,\n\n {\n\n serialize(&self, serializer)\n\n }\n\n}\n\nimpl<'de> serde::de::Deserialize<'de> for boxed::Box<dyn AnyData + 'static> {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n\n where\n\n D: serde::Deserializer<'de>,\n\n {\n\n <Box<dyn AnyData + 'static>>::deserialize(deserializer).map(|x| x.0)\n\n }\n\n}\n\nimpl serde::ser::Serialize for boxed::Box<dyn AnyData + Send + 'static> {\n", "file_path": "src/serializable_traits.rs", "rank": 60, "score": 34967.39926334835 }, { "content": "}\n\nimpl<T: Serialize + ?Sized + 'static> serde::ser::Serialize for Box<T> {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: serde::Serializer,\n\n {\n\n serialize(&self.0, serializer)\n\n }\n\n}\n\nimpl<'de, T: Deserialize + ?Sized + 'static> serde::de::Deserialize<'de> for Box<T> {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n\n where\n\n D: serde::Deserializer<'de>,\n\n {\n\n deserialize(deserializer).map(Self)\n\n }\n\n}\n\n\n", "file_path": "src/serializable_traits.rs", "rank": 61, "score": 34960.46569362114 }, { "content": " }\n\n}\n\n\n\nimpl<Args: 'static, Output: 'static> serde::ser::Serialize for dyn Func<Args, Output = Output> {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: serde::Serializer,\n\n {\n\n serialize(self, serializer)\n\n }\n\n}\n\nimpl<'de, Args: 'static, Output: 'static> serde::de::Deserialize<'de>\n\n for boxed::Box<dyn Func<Args, Output = Output> + 'static>\n\n{\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n\n where\n\n D: serde::Deserializer<'de>,\n\n {\n\n <Box<dyn Func<Args, Output = Output> + 'static>>::deserialize(deserializer).map(|x| x.0)\n\n }\n\n}\n", "file_path": "src/serializable_traits.rs", "rank": 62, "score": 34959.68540657239 }, { "content": " type Output = F::Output;\n\n extern \"rust-call\" fn call_once(self, args: A) -> Self::Output {\n\n self.0.call_once(args)\n\n }\n\n}\n\nimpl<A, F: ?Sized> ops::FnMut<A> for Box<F>\n\nwhere\n\n F: FnMut<A>,\n\n{\n\n extern \"rust-call\" fn call_mut(&mut self, args: A) -> Self::Output {\n\n self.0.call_mut(args)\n\n }\n\n}\n\nimpl<A, F: ?Sized> ops::Fn<A> for Box<F>\n\nwhere\n\n F: Func<A>,\n\n{\n\n extern \"rust-call\" fn call(&self, args: A) -> Self::Output {\n\n self.0.call(args)\n\n }\n", "file_path": "src/serializable_traits.rs", "rank": 63, "score": 34959.28705314246 }, { "content": " error::Error::cause(&**self)\n\n }\n\n fn source(&self) -> Option<&(dyn error::Error + 'static)> {\n\n error::Error::source(&**self)\n\n }\n\n}\n\nimpl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {\n\n self.0.fmt(f)\n\n }\n\n}\n\nimpl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {\n\n self.0.fmt(f)\n\n }\n\n}\n\nimpl<A, F: ?Sized> ops::FnOnce<A> for Box<F>\n\nwhere\n\n F: FnOnce<A>,\n\n{\n", "file_path": "src/serializable_traits.rs", "rank": 64, "score": 34958.18541866867 }, { "content": " pub fn new(t: T) -> Self {\n\n Self(boxed::Box::new(t))\n\n }\n\n}\n\nimpl<T: ?Sized> Box<T> {\n\n // Convert to a regular `std::Boxed::Box<T>`. Coherence rules prevent currently prevent `impl Into<std::boxed::Box<T>> for Box<T>`.\n\n pub fn into_box(self) -> boxed::Box<T> {\n\n self.0\n\n }\n\n}\n\nimpl Box<dyn AnyData> {\n\n // Convert into a `std::boxed::Box<dyn std::any::Any>`.\n\n pub fn into_any(self) -> boxed::Box<dyn any::Any> {\n\n self.0.into_any()\n\n }\n\n}\n\n\n\nimpl<T: ?Sized + marker::Unsize<U>, U: ?Sized> ops::CoerceUnsized<Box<U>> for Box<T> {}\n\nimpl<T: ?Sized> Deref for Box<T> {\n\n type Target = boxed::Box<T>;\n", "file_path": "src/serializable_traits.rs", "rank": 65, "score": 34957.26088405118 }, { "content": " fn as_ref(&self) -> &T {\n\n &*self.0\n\n }\n\n}\n\nimpl<T: ?Sized> AsMut<T> for Box<T> {\n\n fn as_mut(&mut self) -> &mut T {\n\n &mut *self.0\n\n }\n\n}\n\nimpl<T: ?Sized> Borrow<T> for Box<T> {\n\n fn borrow(&self) -> &T {\n\n &*self.0\n\n }\n\n}\n\nimpl<T: ?Sized> BorrowMut<T> for Box<T> {\n\n fn borrow_mut(&mut self) -> &mut T {\n\n &mut *self.0\n\n }\n\n}\n\nimpl<T: ?Sized> From<boxed::Box<T>> for Box<T> {\n", "file_path": "src/serializable_traits.rs", "rank": 66, "score": 34956.33766503972 }, { "content": " fn deref(&self) -> &Self::Target {\n\n &self.0\n\n }\n\n}\n\nimpl<T: ?Sized> DerefMut for Box<T> {\n\n fn deref_mut(&mut self) -> &mut Self::Target {\n\n &mut self.0\n\n }\n\n}\n\nimpl<T: ?Sized> AsRef<boxed::Box<T>> for Box<T> {\n\n fn as_ref(&self) -> &boxed::Box<T> {\n\n &self.0\n\n }\n\n}\n\nimpl<T: ?Sized> AsMut<boxed::Box<T>> for Box<T> {\n\n fn as_mut(&mut self) -> &mut boxed::Box<T> {\n\n &mut self.0\n\n }\n\n}\n\nimpl<T: ?Sized> AsRef<T> for Box<T> {\n", "file_path": "src/serializable_traits.rs", "rank": 67, "score": 34956.1734458259 }, { "content": " fn from(t: boxed::Box<T>) -> Self {\n\n Self(t)\n\n }\n\n}\n\n// impl<T: ?Sized> Into<boxed::Box<T>> for Box<T> {\n\n// \tfn into(self) -> boxed::Box<T> {\n\n// \t\tself.0\n\n// \t}\n\n// }\n\nimpl<T> From<T> for Box<T> {\n\n fn from(t: T) -> Self {\n\n Self(boxed::Box::new(t))\n\n }\n\n}\n\nimpl<T: error::Error> error::Error for Box<T> {\n\n fn description(&self) -> &str {\n\n error::Error::description(&**self)\n\n }\n\n #[allow(deprecated)]\n\n fn cause(&self) -> Option<&dyn error::Error> {\n", "file_path": "src/serializable_traits.rs", "rank": 68, "score": 34950.87302849295 }, { "content": " cache_locs: Arc<Mutex<HashMap<usize, Vec<Vec<Ipv4Addr>>>>>,\n\n master: bool,\n\n framework_name: String,\n\n is_registered: bool, //TODO check if it is necessary\n\n active_jobs: HashMap<usize, Job>,\n\n active_job_queue: Vec<Job>,\n\n taskid_to_jobid: HashMap<String, usize>,\n\n taskid_to_slaveid: HashMap<String, String>,\n\n job_tasks: HashMap<usize, HashSet<String>>,\n\n slaves_with_executors: HashSet<String>,\n\n server_uris: Arc<Mutex<VecDeque<(String, u16)>>>,\n\n port: u16,\n\n map_output_tracker: MapOutputTracker,\n\n}\n\n\n\nimpl DistributedScheduler {\n\n pub fn new(\n\n threads: usize,\n\n max_failures: usize,\n\n master: bool,\n", "file_path": "src/distributed_scheduler.rs", "rank": 69, "score": 34812.17910252054 }, { "content": " })\n\n .collect())\n\n }\n\n\n\n fn submit_stage<T: Data, U: Data, F, RT>(\n\n &self,\n\n stage: Stage,\n\n waiting: &mut BTreeSet<Stage>,\n\n running: &mut BTreeSet<Stage>,\n\n finished: &mut Vec<bool>,\n\n pending_tasks: &mut BTreeMap<Stage, BTreeSet<Box<dyn TaskBase>>>,\n\n output_parts: Vec<usize>,\n\n num_output_parts: usize,\n\n final_stage: Stage,\n\n func: Arc<F>,\n\n final_rdd: Arc<RT>,\n\n run_id: usize,\n\n thread_pool: Arc<ThreadPool>,\n\n ) where\n\n F: SerFunc((TasKContext, Box<dyn Iterator<Item = T>>)) -> U,\n", "file_path": "src/distributed_scheduler.rs", "rank": 70, "score": 34812.13472233595 }, { "content": " let mut missing: BTreeSet<Stage> = BTreeSet::new();\n\n let mut visited: BTreeSet<Arc<dyn RddBase>> = BTreeSet::new();\n\n self.visit_for_missing_parent_stages(&mut missing, &mut visited, stage.get_rdd());\n\n missing.into_iter().collect()\n\n }\n\n\n\n pub fn run_job<T: Data, U: Data, F, RT>(\n\n &self,\n\n func: Arc<F>,\n\n final_rdd: Arc<RT>,\n\n partitions: Vec<usize>,\n\n allow_local: bool,\n\n ) -> Result<Vec<U>>\n\n where\n\n F: SerFunc((TasKContext, Box<dyn Iterator<Item = T>>)) -> U,\n\n RT: Rdd<T> + 'static,\n\n {\n\n info!(\n\n \"shuffle maanger in final rdd of run job {:?}\",\n\n env::env.shuffle_manager\n", "file_path": "src/distributed_scheduler.rs", "rank": 71, "score": 34812.03828490392 }, { "content": " waiting.insert(stage.clone());\n\n }\n\n }\n\n }\n\n\n\n fn submit_missing_tasks<T: Data, U: Data, F, RT>(\n\n &self,\n\n stage: Stage,\n\n finished: &mut Vec<bool>,\n\n pending_tasks: &mut BTreeMap<Stage, BTreeSet<Box<dyn TaskBase>>>,\n\n output_parts: Vec<usize>,\n\n num_output_parts: usize,\n\n final_stage: Stage,\n\n func: Arc<F>,\n\n final_rdd: Arc<RT>,\n\n run_id: usize,\n\n thread_pool: Arc<ThreadPool>,\n\n ) where\n\n F: SerFunc((TasKContext, Box<dyn Iterator<Item = T>>)) -> U,\n\n RT: Rdd<T> + 'static,\n", "file_path": "src/distributed_scheduler.rs", "rank": 72, "score": 34811.60121034218 }, { "content": "use std::thread;\n\nuse std::time;\n\nuse std::time::{Duration, Instant};\n\nuse threadpool::ThreadPool;\n\n\n\n//just for now, creating an entire scheduler functions without dag scheduler trait. Later change it to extend from dag scheduler\n\n#[derive(Clone, Default)]\n\npub struct DistributedScheduler {\n\n threads: usize,\n\n max_failures: usize,\n\n attempt_id: Arc<AtomicUsize>,\n\n resubmit_timeout: u128,\n\n poll_timeout: u64,\n\n event_queues: Arc<Mutex<HashMap<usize, VecDeque<CompletionEvent>>>>,\n\n next_job_id: Arc<AtomicUsize>,\n\n next_run_id: Arc<AtomicUsize>,\n\n next_task_id: Arc<AtomicUsize>,\n\n next_stage_id: Arc<AtomicUsize>,\n\n id_to_stage: Arc<Mutex<HashMap<usize, Stage>>>,\n\n shuffle_to_map_stage: Arc<Mutex<HashMap<usize, Stage>>>,\n", "file_path": "src/distributed_scheduler.rs", "rank": 73, "score": 34809.89771788526 }, { "content": " if let Ok(task_final) = tsk.downcast::<ShuffleMapTask>() {\n\n let task_final = task_final as Box<dyn TaskBase>;\n\n DistributedScheduler::task_ended(\n\n event_queues_clone,\n\n task_final,\n\n TastEndReason::Success,\n\n result.into_any_send_sync(),\n\n );\n\n }\n\n }\n\n };\n\n })\n\n }\n\n }\n\n}\n\n\n\n//TODO Serialize and Deserialize\n", "file_path": "src/distributed_scheduler.rs", "rank": 74, "score": 34809.204004099 }, { "content": "use super::*;\n\n\n\nuse capnp::serialize_packed;\n\n//use chrono::{DateTime, Utc};\n\n//use downcast_rs::Downcast;\n\nuse parking_lot::Mutex;\n\nuse std::any::Any;\n\nuse std::collections::btree_map::BTreeMap;\n\nuse std::collections::btree_set::BTreeSet;\n\nuse std::collections::vec_deque::VecDeque;\n\nuse std::collections::{HashMap, HashSet};\n\n//use std::intrinsics;\n\n//use std::io::prelude::*;\n\n//use std::io::BufReader;\n\nuse std::iter::FromIterator;\n\n//use std::net::TcpListener;\n\nuse std::net::{Ipv4Addr, TcpStream};\n\nuse std::option::Option;\n\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\nuse std::sync::Arc;\n", "file_path": "src/distributed_scheduler.rs", "rank": 75, "score": 34808.7674102903 }, { "content": " let ser_task = task;\n\n\n\n let task_bytes = bincode::serialize(&ser_task).unwrap();\n\n info!(\n\n \"task in executor {} {:?} master\",\n\n server_port,\n\n ser_task.get_task_id()\n\n );\n\n let mut stream =\n\n TcpStream::connect(format!(\"{}:{}\", server_address, server_port)).unwrap();\n\n info!(\n\n \"task in executor {} {} master task len\",\n\n server_port,\n\n task_bytes.len()\n\n );\n\n let mut message = ::capnp::message::Builder::new_default();\n\n let mut task_data = message.init_root::<serialized_data::Builder>();\n\n info!(\"sending data to server\");\n\n task_data.set_msg(&task_bytes);\n\n serialize_packed::write_message(&mut stream, &message);\n", "file_path": "src/distributed_scheduler.rs", "rank": 76, "score": 34807.63861836395 }, { "content": "\n\n let r = ::capnp::message::ReaderOptions {\n\n traversal_limit_in_words: std::u64::MAX,\n\n nesting_limit: 64,\n\n };\n\n let mut stream_r = std::io::BufReader::new(&mut stream);\n\n let message_reader = serialize_packed::read_message(&mut stream_r, r).unwrap();\n\n let task_data = message_reader\n\n .get_root::<serialized_data::Reader>()\n\n .unwrap();\n\n info!(\n\n \"task in executor {} {} master task result len\",\n\n server_port,\n\n task_data.get_msg().unwrap().len()\n\n );\n\n let result: TaskResult =\n\n bincode::deserialize(&task_data.get_msg().unwrap()).unwrap();\n\n match ser_task {\n\n TaskOption::ResultTask(tsk) => {\n\n let result = match result {\n", "file_path": "src/distributed_scheduler.rs", "rank": 77, "score": 34806.662998091495 }, { "content": " }\n\n\n\n fn task_ended(\n\n event_queues: Arc<Mutex<HashMap<usize, VecDeque<CompletionEvent>>>>,\n\n task: Box<dyn TaskBase>,\n\n reason: TastEndReason,\n\n result: Box<dyn Any + Send + Sync>,\n\n //TODO accumvalues needs to be done\n\n ) {\n\n let result = Some(result);\n\n if let Some(queue) = event_queues.lock().get_mut(&(task.get_run_id())) {\n\n queue.push_back(CompletionEvent {\n\n task,\n\n reason,\n\n // result: Some(Box::new(result)),\n\n result,\n\n accum_updates: HashMap::new(),\n\n });\n\n } else {\n\n info!(\"ignoring completion event for DAG Job\");\n", "file_path": "src/distributed_scheduler.rs", "rank": 78, "score": 34805.56773320928 }, { "content": " }\n\n }\n\n }\n\n Vec::new()\n\n }\n\n\n\n fn wait_for_event(&self, run_id: usize, timeout: u64) -> Option<CompletionEvent> {\n\n let end = Instant::now() + Duration::from_millis(timeout);\n\n while self.event_queues.lock().get(&run_id).unwrap().is_empty() {\n\n if Instant::now() > end {\n\n return None;\n\n } else {\n\n thread::sleep(end - Instant::now());\n\n }\n\n }\n\n self.event_queues\n\n .lock()\n\n .get_mut(&run_id)\n\n .unwrap()\n\n .pop_front()\n", "file_path": "src/distributed_scheduler.rs", "rank": 79, "score": 34804.813267869344 }, { "content": " );\n\n let thread_pool = Arc::new(ThreadPool::new(self.threads));\n\n let run_id = self.next_run_id.fetch_add(1, Ordering::SeqCst);\n\n let output_parts = partitions;\n\n let num_output_parts = output_parts.len();\n\n let final_stage = self.new_stage(final_rdd.clone(), None);\n\n let mut results: Vec<Option<U>> = (0..num_output_parts).map(|_| None).collect();\n\n let mut finished: Vec<bool> = (0..num_output_parts).map(|_| false).collect();\n\n let mut num_finished = 0;\n\n let mut waiting: BTreeSet<Stage> = BTreeSet::new();\n\n let mut running: BTreeSet<Stage> = BTreeSet::new();\n\n let mut failed: BTreeSet<Stage> = BTreeSet::new();\n\n let mut pending_tasks: BTreeMap<Stage, BTreeSet<Box<dyn TaskBase>>> = BTreeMap::new();\n\n let mut fetch_failure_duration = Duration::new(0, 0);\n\n\n\n //TODO update cache\n\n //TODO logging\n\n\n\n if allow_local && final_stage.parents.is_empty() && (num_output_parts == 1) {\n\n let split = (final_rdd.splits()[output_parts[0]]).clone();\n", "file_path": "src/distributed_scheduler.rs", "rank": 80, "score": 34804.48467101967 }, { "content": " TaskResult::ResultTask(r) => r,\n\n _ => panic!(\"wrong result type\"),\n\n };\n\n if let Ok(task_final) = tsk.downcast::<ResultTask<T, U, RT, F>>() {\n\n let task_final = task_final as Box<dyn TaskBase>;\n\n DistributedScheduler::task_ended(\n\n event_queues_clone,\n\n task_final,\n\n TastEndReason::Success,\n\n // Can break in future. But actually not needed for distributed scheduler since task runs on different processes.\n\n // Currently using this because local scheduler needs it. It can be solved by refactoring tasks differently for local and distributed scheduler\n\n result.into_any_send_sync(),\n\n );\n\n }\n\n }\n\n TaskOption::ShuffleMapTask(tsk) => {\n\n let result = match result {\n\n TaskResult::ShuffleTask(r) => r,\n\n _ => panic!(\"wrong result type\"),\n\n };\n", "file_path": "src/distributed_scheduler.rs", "rank": 81, "score": 34803.88272620561 }, { "content": " }\n\n\n\n fn submit_task<T: Data, U: Data, RT, F>(\n\n &self,\n\n task: TaskOption,\n\n id_in_job: usize,\n\n thread_pool: Arc<ThreadPool>,\n\n ) where\n\n F: SerFunc((TasKContext, Box<dyn Iterator<Item = T>>)) -> U,\n\n RT: Rdd<T> + 'static,\n\n {\n\n info!(\"inside submit task\");\n\n let my_attempt_id = self.attempt_id.fetch_add(1, Ordering::SeqCst);\n\n let event_queues = self.event_queues.clone();\n\n // let ser_task = SerializeableTask { task };\n\n // let ser_task = task;\n\n //\n\n // let task_bytes = bincode::serialize(&ser_task).unwrap();\n\n //let server_port = self.port;\n\n // server_port = server_port - (server_port % 1000);\n", "file_path": "src/distributed_scheduler.rs", "rank": 82, "score": 34803.298647031595 }, { "content": " servers: Option<Vec<(String, u16)>>,\n\n port: u16,\n\n // map_output_tracker: MapOutputTracker,\n\n ) -> Self {\n\n // unimplemented!()\n\n info!(\n\n \"starting distributed scheduler in client - {} {}\",\n\n master, port\n\n );\n\n DistributedScheduler {\n\n // threads,\n\n threads: 100,\n\n max_failures,\n\n attempt_id: Arc::new(AtomicUsize::new(0)),\n\n resubmit_timeout: 2000,\n\n poll_timeout: 500,\n\n event_queues: Arc::new(Mutex::new(HashMap::new())),\n\n next_job_id: Arc::new(AtomicUsize::new(0)),\n\n next_run_id: Arc::new(AtomicUsize::new(0)),\n\n next_task_id: Arc::new(AtomicUsize::new(0)),\n", "file_path": "src/distributed_scheduler.rs", "rank": 83, "score": 34803.086879607385 }, { "content": " Arc::new(Mutex::new(VecDeque::new()))\n\n },\n\n port,\n\n map_output_tracker: env::env.map_output_tracker.clone(),\n\n }\n\n }\n\n\n\n fn get_cache_locs(&self, rdd: Arc<dyn RddBase>) -> Option<Vec<Vec<Ipv4Addr>>> {\n\n let cache_locs = self.cache_locs.lock();\n\n let locs_opt = cache_locs.get(&rdd.get_rdd_id());\n\n match locs_opt {\n\n Some(locs) => Some(locs.clone()),\n\n None => None,\n\n }\n\n // (self.cache_locs.lock().get(&rdd.get_rdd_id())).clone()\n\n }\n\n\n\n fn update_cache_locs(&self) {\n\n let mut locs = self.cache_locs.lock();\n\n *locs = env::env.cache_tracker.get_location_snapshot();\n", "file_path": "src/distributed_scheduler.rs", "rank": 84, "score": 34802.44730850139 }, { "content": " pending_tasks.get_mut(&stage).unwrap().remove(&evt.task);\n\n use super::dag_scheduler::TastEndReason::*;\n\n match evt.reason {\n\n Success => {\n\n //TODO logging\n\n //TODO add to Accumulator\n\n\n\n // ResultTask alone done now.\n\n // if let Some(result) = evt.get_result::<U>();\n\n let result_type =\n\n evt.task.downcast_ref::<ResultTask<T, U, RT, F>>().is_some();\n\n // println!(\"result task in master {} {:?}\", self.master, result_type);\n\n if result_type {\n\n if let Ok(rt) = evt.task.downcast::<ResultTask<T, U, RT, F>>() {\n\n // println!(\n\n // \"result task result before unwrapping in master {}\",\n\n // self.master\n\n // );\n\n let result = evt\n\n .result\n", "file_path": "src/distributed_scheduler.rs", "rank": 85, "score": 34801.69881764545 }, { "content": " next_stage_id: Arc::new(AtomicUsize::new(0)),\n\n id_to_stage: Arc::new(Mutex::new(HashMap::new())),\n\n shuffle_to_map_stage: Arc::new(Mutex::new(HashMap::new())),\n\n cache_locs: Arc::new(Mutex::new(HashMap::new())),\n\n master,\n\n framework_name: \"spark\".to_string(),\n\n is_registered: true, //TODO check if it is necessary\n\n active_jobs: HashMap::new(),\n\n active_job_queue: Vec::new(),\n\n taskid_to_jobid: HashMap::new(),\n\n taskid_to_slaveid: HashMap::new(),\n\n job_tasks: HashMap::new(),\n\n slaves_with_executors: HashSet::new(),\n\n server_uris: if let Some(servers) = servers {\n\n let mut vec = VecDeque::new();\n\n for (i, j) in servers {\n\n vec.push_front((i, j));\n\n }\n\n Arc::new(Mutex::new(VecDeque::from_iter(vec)))\n\n } else {\n", "file_path": "src/distributed_scheduler.rs", "rank": 86, "score": 34801.39258539171 }, { "content": " let task_context = TasKContext::new(final_stage.id, output_parts[0], 0);\n\n return Ok(vec![func((task_context, final_rdd.iterator(split)?))]);\n\n }\n\n\n\n self.event_queues.lock().insert(run_id, VecDeque::new());\n\n\n\n self.submit_stage(\n\n final_stage.clone(),\n\n &mut waiting,\n\n &mut running,\n\n &mut finished,\n\n &mut pending_tasks,\n\n output_parts.clone(),\n\n num_output_parts,\n\n final_stage.clone(),\n\n func.clone(),\n\n final_rdd.clone(),\n\n run_id,\n\n thread_pool.clone(),\n\n );\n", "file_path": "src/distributed_scheduler.rs", "rank": 87, "score": 34800.78397399802 }, { "content": " Dependency::NarrowDependency(nar_dep) => {\n\n self.visit_for_parent_stages(parents, visited, nar_dep.get_rdd_base())\n\n } //TODO finish range dependency\n\n }\n\n }\n\n }\n\n }\n\n\n\n fn get_parent_stages(&self, rdd: Arc<dyn RddBase>) -> Vec<Stage> {\n\n info!(\"inside get parent stages\");\n\n let mut parents: BTreeSet<Stage> = BTreeSet::new();\n\n let mut visited: BTreeSet<Arc<dyn RddBase>> = BTreeSet::new();\n\n self.visit_for_parent_stages(&mut parents, &mut visited, rdd.clone());\n\n info!(\n\n \"parent stages {:?}\",\n\n parents.iter().map(|x| x.id).collect::<Vec<_>>()\n\n );\n\n parents.into_iter().collect()\n\n }\n\n\n", "file_path": "src/distributed_scheduler.rs", "rank": 88, "score": 34800.30068441072 }, { "content": " }\n\n }\n\n\n\n fn get_shuffle_map_stage(&self, shuf: Arc<dyn ShuffleDependencyTrait>) -> Stage {\n\n info!(\"inside get_shufflemap stage\");\n\n let stage = match self.shuffle_to_map_stage.lock().get(&shuf.get_shuffle_id()) {\n\n Some(s) => Some(s.clone()),\n\n None => None,\n\n };\n\n match stage {\n\n Some(stage) => stage.clone(),\n\n None => {\n\n info!(\"inside get_shufflemap stage before\");\n\n let stage = self.new_stage(shuf.get_rdd_base(), Some(shuf.clone()));\n\n self.shuffle_to_map_stage\n\n .lock()\n\n .insert(shuf.get_shuffle_id(), stage.clone());\n\n info!(\"inside get_shufflemap return\");\n\n stage\n\n }\n", "file_path": "src/distributed_scheduler.rs", "rank": 89, "score": 34799.722812188505 }, { "content": " fn visit_for_missing_parent_stages(\n\n &self,\n\n missing: &mut BTreeSet<Stage>,\n\n visited: &mut BTreeSet<Arc<dyn RddBase>>,\n\n rdd: Arc<dyn RddBase>,\n\n ) {\n\n info!(\n\n \"missing stages {:?}\",\n\n missing.iter().map(|x| x.id).collect::<Vec<_>>()\n\n );\n\n info!(\n\n \"visisted stages {:?}\",\n\n visited.iter().map(|x| x.get_rdd_id()).collect::<Vec<_>>()\n\n );\n\n if !visited.contains(&rdd) {\n\n visited.insert(rdd.clone());\n\n // TODO CacheTracker register\n\n for p in 0..rdd.number_of_splits() {\n\n let locs = self.get_cache_locs(rdd.clone());\n\n info!(\"cache locs {:?}\", locs);\n", "file_path": "src/distributed_scheduler.rs", "rank": 90, "score": 34799.7178035066 }, { "content": " .collect::<Vec<_>>()\n\n );\n\n if self.get_missing_parent_stages(stage.clone()).is_empty() {\n\n newly_runnable.push(stage.clone())\n\n }\n\n }\n\n for stage in &newly_runnable {\n\n waiting.remove(stage);\n\n }\n\n for stage in &newly_runnable {\n\n running.insert(stage.clone());\n\n }\n\n for stage in newly_runnable {\n\n self.submit_missing_tasks(\n\n stage,\n\n &mut finished,\n\n &mut pending_tasks,\n\n output_parts.clone(),\n\n num_output_parts,\n\n final_stage.clone(),\n", "file_path": "src/distributed_scheduler.rs", "rank": 91, "score": 34799.45919219301 }, { "content": " info!(\n\n \"pending stages and tasks {:?}\",\n\n pending_tasks\n\n .iter()\n\n .map(|(k, v)| (k.id, v.iter().map(|x| x.get_task_id()).collect::<Vec<_>>()))\n\n .collect::<Vec<_>>()\n\n );\n\n\n\n while num_finished != num_output_parts {\n\n let event_option = self.wait_for_event(run_id, self.poll_timeout);\n\n let start_time = Instant::now();\n\n\n\n if let Some(mut evt) = event_option {\n\n info!(\"event starting\");\n\n let stage = self.id_to_stage.lock()[&evt.task.get_stage_id()].clone();\n\n info!(\n\n \"removing stage task from pending tasks {} {}\",\n\n stage.id,\n\n evt.task.get_task_id()\n\n );\n", "file_path": "src/distributed_scheduler.rs", "rank": 92, "score": 34798.843807173624 }, { "content": " \"locs for shuffle id {:?} {:?}\",\n\n stage.clone().shuffle_dependency.unwrap().get_shuffle_id(),\n\n locs\n\n );\n\n self.map_output_tracker.register_map_outputs(\n\n stage.shuffle_dependency.unwrap().get_shuffle_id(),\n\n locs,\n\n );\n\n info!(\"here after registering map outputs \");\n\n }\n\n //TODO Cache\n\n self.update_cache_locs();\n\n let mut newly_runnable = Vec::new();\n\n for stage in &waiting {\n\n info!(\n\n \"waiting stage parent stages for stage {} are {:?}\",\n\n stage.id,\n\n self.get_missing_parent_stages(stage.clone())\n\n .iter()\n\n .map(|x| x.id)\n", "file_path": "src/distributed_scheduler.rs", "rank": 93, "score": 34798.09697111996 }, { "content": " // // let result = result.into_any();\n\n // let result: Box<String> =\n\n // Box::<Any>::downcast(result.into_any()).unwrap();\n\n // // let result = result.downcast::<String>().unwrap();\n\n // let result = *result;\n\n // info!(\"result inside queue {:?}\", result);\n\n self.id_to_stage\n\n .lock()\n\n .get_mut(&smt.stage_id)\n\n .unwrap()\n\n .add_output_loc(smt.partition, result);\n\n let stage = self.id_to_stage.lock().clone()[&smt.stage_id].clone();\n\n info!(\n\n \"pending stages {:?}\",\n\n pending_tasks\n\n .iter()\n\n .map(|(x, y)| (\n\n x.id,\n\n y.iter().map(|k| k.get_task_id()).collect::<Vec<_>>()\n\n ))\n", "file_path": "src/distributed_scheduler.rs", "rank": 94, "score": 34798.06205751955 }, { "content": " }\n\n\n\n fn get_preferred_locs(&self, rdd: Arc<dyn RddBase>, partition: usize) -> Vec<Ipv4Addr> {\n\n //TODO have to implement this completely\n\n if let Some(cached) = self.get_cache_locs(rdd.clone()) {\n\n if let Some(cached) = cached.get(partition) {\n\n return cached.clone();\n\n }\n\n }\n\n let rdd_prefs = rdd.preferred_locations(rdd.splits()[partition].clone());\n\n if !rdd_prefs.is_empty() {\n\n return rdd_prefs;\n\n }\n\n for dep in rdd.get_dependencies().iter() {\n\n if let Dependency::NarrowDependency(nar_dep) = dep {\n\n for in_part in nar_dep.get_parents(partition) {\n\n let locs = self.get_preferred_locs(nar_dep.get_rdd_base(), in_part);\n\n if !locs.is_empty() {\n\n return locs;\n\n }\n", "file_path": "src/distributed_scheduler.rs", "rank": 95, "score": 34797.70321041368 }, { "content": " .collect::<Vec<_>>()\n\n );\n\n info!(\n\n \"pending tasks {:?}\",\n\n pending_tasks\n\n .get(&stage)\n\n .unwrap()\n\n .iter()\n\n .map(|x| x.get_task_id())\n\n .collect::<Vec<_>>()\n\n );\n\n info!(\n\n \"running {:?}\",\n\n running.iter().map(|x| x.id).collect::<Vec<_>>()\n\n );\n\n info!(\n\n \"waiting {:?}\",\n\n waiting.iter().map(|x| x.id).collect::<Vec<_>>()\n\n );\n\n\n", "file_path": "src/distributed_scheduler.rs", "rank": 96, "score": 34797.59385542687 }, { "content": " .unwrap()\n\n .clone(),\n\n );\n\n fetch_failure_duration = start_time.elapsed();\n\n }\n\n _ => {\n\n //TODO error handling\n\n }\n\n }\n\n }\n\n if !failed.is_empty() && fetch_failure_duration.as_millis() > self.resubmit_timeout {\n\n self.update_cache_locs();\n\n for stage in &failed {\n\n self.submit_stage(\n\n stage.clone(),\n\n &mut waiting,\n\n &mut running,\n\n &mut finished,\n\n &mut pending_tasks,\n\n output_parts.clone(),\n", "file_path": "src/distributed_scheduler.rs", "rank": 97, "score": 34797.57660223652 }, { "content": " if running.contains(&stage)\n\n && pending_tasks.get(&stage).unwrap().is_empty()\n\n {\n\n info!(\"here before registering map outputs \");\n\n //TODO logging\n\n running.remove(&stage);\n\n if stage.shuffle_dependency.is_some() {\n\n info!(\n\n \"stage output locs before register mapoutput tracker {:?}\",\n\n stage.output_locs\n\n );\n\n let locs = stage\n\n .output_locs\n\n .iter()\n\n .map(|x| match x.get(0) {\n\n Some(s) => Some(s.to_owned()),\n\n None => None,\n\n })\n\n .collect();\n\n info!(\n", "file_path": "src/distributed_scheduler.rs", "rank": 98, "score": 34796.97316469591 }, { "content": " let id = self.next_stage_id.fetch_add(1, Ordering::SeqCst);\n\n info!(\"new stage id {}\", id);\n\n let stage = Stage::new(\n\n id,\n\n rdd_base.clone(),\n\n shuffle_dependency,\n\n self.get_parent_stages(rdd_base),\n\n );\n\n self.id_to_stage.lock().insert(id, stage.clone());\n\n info!(\"new stage stage return\");\n\n stage\n\n }\n\n\n\n fn visit_for_parent_stages(\n\n &self,\n\n parents: &mut BTreeSet<Stage>,\n\n visited: &mut BTreeSet<Arc<dyn RddBase>>,\n\n rdd: Arc<dyn RddBase>,\n\n ) {\n\n info!(\n", "file_path": "src/distributed_scheduler.rs", "rank": 99, "score": 34796.43287481943 } ]
Rust
crates/wast/src/ast/memory.rs
peterhuene/wasm-tools
bb96b2431f01e5a0e7c83fb1f6bcb08ccb8cb073
use crate::ast::{self, kw}; use crate::parser::{Lookahead1, Parse, Parser, Peek, Result}; #[derive(Debug)] pub struct Memory<'a> { pub span: ast::Span, pub id: Option<ast::Id<'a>>, pub name: Option<ast::NameAnnotation<'a>>, pub exports: ast::InlineExport<'a>, pub kind: MemoryKind<'a>, } #[derive(Debug)] pub enum MemoryKind<'a> { #[allow(missing_docs)] Import { import: ast::InlineImport<'a>, ty: ast::MemoryType, }, Normal(ast::MemoryType), Inline { is_32: bool, data: Vec<DataVal<'a>>, }, } impl<'a> Parse<'a> for Memory<'a> { fn parse(parser: Parser<'a>) -> Result<Self> { let span = parser.parse::<kw::memory>()?.0; let id = parser.parse()?; let name = parser.parse()?; let exports = parser.parse()?; let mut l = parser.lookahead1(); let kind = if let Some(import) = parser.parse()? { MemoryKind::Import { import, ty: parser.parse()?, } } else if l.peek::<ast::LParen>() || parser.peek2::<ast::LParen>() { let is_32 = if parser.parse::<Option<kw::i32>>()?.is_some() { true } else if parser.parse::<Option<kw::i64>>()?.is_some() { false } else { true }; let data = parser.parens(|parser| { parser.parse::<kw::data>()?; let mut data = Vec::new(); while !parser.is_empty() { data.push(parser.parse()?); } Ok(data) })?; MemoryKind::Inline { data, is_32 } } else if l.peek::<u32>() || l.peek::<kw::i32>() || l.peek::<kw::i64>() { MemoryKind::Normal(parser.parse()?) } else { return Err(l.error()); }; Ok(Memory { span, id, name, exports, kind, }) } } #[derive(Debug)] pub struct Data<'a> { pub span: ast::Span, pub id: Option<ast::Id<'a>>, pub name: Option<ast::NameAnnotation<'a>>, pub kind: DataKind<'a>, pub data: Vec<DataVal<'a>>, } #[derive(Debug)] pub enum DataKind<'a> { Passive, Active { memory: ast::ItemRef<'a, kw::memory>, offset: ast::Expression<'a>, }, } impl<'a> Parse<'a> for Data<'a> { fn parse(parser: Parser<'a>) -> Result<Self> { let span = parser.parse::<kw::data>()?.0; let id = parser.parse()?; let name = parser.parse()?; let kind = if parser.peek::<kw::passive>() { parser.parse::<kw::passive>()?; DataKind::Passive } else if parser.peek::<&[u8]>() { DataKind::Passive } else { let memory = if let Some(index) = parser.parse::<Option<ast::IndexOrRef<_>>>()? { index.0 } else { ast::ItemRef::Item { kind: kw::memory(parser.prev_span()), idx: ast::Index::Num(0, span), exports: Vec::new(), #[cfg(wast_check_exhaustive)] visited: false, } }; let offset = parser.parens(|parser| { if parser.peek::<kw::offset>() { parser.parse::<kw::offset>()?; parser.parse() } else { let insn = parser.parse()?; if parser.is_empty() { return Ok(ast::Expression { instrs: [insn].into(), }); } let expr: ast::Expression = parser.parse()?; let mut instrs = Vec::from(expr.instrs); instrs.push(insn); Ok(ast::Expression { instrs: instrs.into(), }) } })?; DataKind::Active { memory, offset } }; let mut data = Vec::new(); while !parser.is_empty() { data.push(parser.parse()?); } Ok(Data { span, id, name, kind, data, }) } } #[derive(Debug)] #[allow(missing_docs)] pub enum DataVal<'a> { String(&'a [u8]), Integral(Vec<u8>), } impl DataVal<'_> { pub fn len(&self) -> usize { match self { DataVal::String(s) => s.len(), DataVal::Integral(s) => s.len(), } } pub fn push_onto(&self, dst: &mut Vec<u8>) { match self { DataVal::String(s) => dst.extend_from_slice(s), DataVal::Integral(s) => dst.extend_from_slice(s), } } } impl<'a> Parse<'a> for DataVal<'a> { fn parse(parser: Parser<'a>) -> Result<Self> { if !parser.peek::<ast::LParen>() { return Ok(DataVal::String(parser.parse()?)); } return parser.parens(|p| { let mut result = Vec::new(); let mut lookahead = p.lookahead1(); let l = &mut lookahead; let r = &mut result; if consume::<kw::i8, i8, _>(p, l, r, |u, v| v.push(u as u8))? || consume::<kw::i16, i16, _>(p, l, r, |u, v| v.extend(&u.to_le_bytes()))? || consume::<kw::i32, i32, _>(p, l, r, |u, v| v.extend(&u.to_le_bytes()))? || consume::<kw::i64, i64, _>(p, l, r, |u, v| v.extend(&u.to_le_bytes()))? || consume::<kw::f32, ast::Float32, _>(p, l, r, |u, v| { v.extend(&u.bits.to_le_bytes()) })? || consume::<kw::f64, ast::Float64, _>(p, l, r, |u, v| { v.extend(&u.bits.to_le_bytes()) })? || consume::<kw::v128, ast::V128Const, _>(p, l, r, |u, v| { v.extend(&u.to_le_bytes()) })? { Ok(DataVal::Integral(result)) } else { Err(lookahead.error()) } }); fn consume<'a, T: Peek + Parse<'a>, U: Parse<'a>, F>( parser: Parser<'a>, lookahead: &mut Lookahead1<'a>, dst: &mut Vec<u8>, push: F, ) -> Result<bool> where F: Fn(U, &mut Vec<u8>), { if !lookahead.peek::<T>() { return Ok(false); } parser.parse::<T>()?; while !parser.is_empty() { let val = parser.parse::<U>()?; push(val, dst); } Ok(true) } } }
use crate::ast::{self, kw}; use crate::parser::{Lookahead1, Parse, Parser, Peek, Result}; #[derive(Debug)] pub struct Memory<'a> { pub span: ast::Span, pub id: Option<ast::Id<'a>>, pub name: Option<ast::NameAnnotation<'a>>, pub exports: ast::InlineExport<'a>, pub kind: MemoryKind<'a>, } #[derive(Debug)] pub enum MemoryKind<'a> { #[allow(missing_docs)] Import { import: ast::InlineImport<'a>, ty: ast::MemoryType, }, Normal(ast::MemoryType), Inline { is_32: bool, data: Vec<DataVal<'a>>, }, } impl<'a> Parse<'a> for Memory<'a> { fn parse(parser: Parser<'a>) -> Result<Self> { let span = parser.parse::<kw::memory>()?.0; let id = parser.parse()?; let name = parser.parse()?; let exports = parser.parse()?; let mut l = parser.lookahead1(); let kind = if let Some(import) = parser.parse()? { MemoryKind::Import { import, ty: parser.parse()?, } } else if l.peek::<ast::LParen>() || parser.peek2::<ast::LParen>() { let is_32 = if parser.parse::<Option<kw::i32>>()?.is_some() { true } else if parser.parse::<Option<kw::i64>>()?.is_some() { false } else { true }; let data = parser.parens(|parser| { parser.parse::<kw::data>()?; let mut data = Vec::new(); while !parser.is_empty() { data.push(parser.parse()?); } Ok(data) })?; MemoryKind::Inline { data, is_32 } } else if l.peek::<u32>() || l.peek::<kw::i32>() || l.peek::<kw::i64>() { MemoryKind::Normal(parser.parse()?) } else { return Err(l.error()); }; Ok(Memory { span, id, name, exports, kind, }) } } #[derive(Debug)] pub struct Data<'a> { pub span: ast::Span, pub id: Option<ast::Id<'a>>, pub name: Option<ast::NameAnnotation<'a>>, pub kind: DataKind<'a>, pub data: Vec<DataVal<'a>>, } #[derive(Debug)] pub enum DataKind<'a> { Passive, Active { memory: ast::ItemRef<'a, kw::memory>, offset: ast::Expression<'a>, }, } impl<'a> Parse<'a> for Data<'a> {
} #[derive(Debug)] #[allow(missing_docs)] pub enum DataVal<'a> { String(&'a [u8]), Integral(Vec<u8>), } impl DataVal<'_> { pub fn len(&self) -> usize { match self { DataVal::String(s) => s.len(), DataVal::Integral(s) => s.len(), } } pub fn push_onto(&self, dst: &mut Vec<u8>) { match self { DataVal::String(s) => dst.extend_from_slice(s), DataVal::Integral(s) => dst.extend_from_slice(s), } } } impl<'a> Parse<'a> for DataVal<'a> { fn parse(parser: Parser<'a>) -> Result<Self> { if !parser.peek::<ast::LParen>() { return Ok(DataVal::String(parser.parse()?)); } return parser.parens(|p| { let mut result = Vec::new(); let mut lookahead = p.lookahead1(); let l = &mut lookahead; let r = &mut result; if consume::<kw::i8, i8, _>(p, l, r, |u, v| v.push(u as u8))? || consume::<kw::i16, i16, _>(p, l, r, |u, v| v.extend(&u.to_le_bytes()))? || consume::<kw::i32, i32, _>(p, l, r, |u, v| v.extend(&u.to_le_bytes()))? || consume::<kw::i64, i64, _>(p, l, r, |u, v| v.extend(&u.to_le_bytes()))? || consume::<kw::f32, ast::Float32, _>(p, l, r, |u, v| { v.extend(&u.bits.to_le_bytes()) })? || consume::<kw::f64, ast::Float64, _>(p, l, r, |u, v| { v.extend(&u.bits.to_le_bytes()) })? || consume::<kw::v128, ast::V128Const, _>(p, l, r, |u, v| { v.extend(&u.to_le_bytes()) })? { Ok(DataVal::Integral(result)) } else { Err(lookahead.error()) } }); fn consume<'a, T: Peek + Parse<'a>, U: Parse<'a>, F>( parser: Parser<'a>, lookahead: &mut Lookahead1<'a>, dst: &mut Vec<u8>, push: F, ) -> Result<bool> where F: Fn(U, &mut Vec<u8>), { if !lookahead.peek::<T>() { return Ok(false); } parser.parse::<T>()?; while !parser.is_empty() { let val = parser.parse::<U>()?; push(val, dst); } Ok(true) } } }
fn parse(parser: Parser<'a>) -> Result<Self> { let span = parser.parse::<kw::data>()?.0; let id = parser.parse()?; let name = parser.parse()?; let kind = if parser.peek::<kw::passive>() { parser.parse::<kw::passive>()?; DataKind::Passive } else if parser.peek::<&[u8]>() { DataKind::Passive } else { let memory = if let Some(index) = parser.parse::<Option<ast::IndexOrRef<_>>>()? { index.0 } else { ast::ItemRef::Item { kind: kw::memory(parser.prev_span()), idx: ast::Index::Num(0, span), exports: Vec::new(), #[cfg(wast_check_exhaustive)] visited: false, } }; let offset = parser.parens(|parser| { if parser.peek::<kw::offset>() { parser.parse::<kw::offset>()?; parser.parse() } else { let insn = parser.parse()?; if parser.is_empty() { return Ok(ast::Expression { instrs: [insn].into(), }); } let expr: ast::Expression = parser.parse()?; let mut instrs = Vec::from(expr.instrs); instrs.push(insn); Ok(ast::Expression { instrs: instrs.into(), }) } })?; DataKind::Active { memory, offset } }; let mut data = Vec::new(); while !parser.is_empty() { data.push(parser.parse()?); } Ok(Data { span, id, name, kind, data, }) }
function_block-full_function
[ { "content": "/// Construct a dummy memory for the given memory type.\n\npub fn dummy_memory<T>(store: &mut Store<T>, ty: MemoryType) -> Result<Memory> {\n\n Memory::new(store, ty)\n\n}\n", "file_path": "crates/fuzz-stats/src/dummy.rs", "rank": 0, "score": 415256.02069778426 }, { "content": "pub fn fill<'a>(span: Span, slot: &mut Option<Id<'a>>) -> Id<'a> {\n\n *slot.get_or_insert_with(|| gen(span))\n\n}\n", "file_path": "crates/wast/src/resolve/gensym.rs", "rank": 1, "score": 412064.60378247837 }, { "content": "/// Construct a dummy table for the given table type.\n\npub fn dummy_table<T>(store: &mut Store<T>, ty: TableType) -> Result<Table> {\n\n let init_val = dummy_value(ty.element().clone());\n\n Table::new(store, ty, init_val)\n\n}\n\n\n", "file_path": "crates/fuzz-stats/src/dummy.rs", "rank": 2, "score": 353174.175868036 }, { "content": "/// Construct a dummy `Extern` from its type signature\n\npub fn dummy_extern<T>(store: &mut Store<T>, ty: ExternType) -> Result<Extern> {\n\n Ok(match ty {\n\n ExternType::Func(func_ty) => Extern::Func(dummy_func(store, func_ty)),\n\n ExternType::Global(global_ty) => Extern::Global(dummy_global(store, global_ty)),\n\n ExternType::Table(table_ty) => Extern::Table(dummy_table(store, table_ty)?),\n\n ExternType::Memory(mem_ty) => Extern::Memory(dummy_memory(store, mem_ty)?),\n\n ExternType::Instance(_) => unimplemented!(),\n\n ExternType::Module(_) => unimplemented!(),\n\n })\n\n}\n\n\n", "file_path": "crates/fuzz-stats/src/dummy.rs", "rank": 3, "score": 353174.175868036 }, { "content": "pub fn gen(span: Span) -> Id<'static> {\n\n NEXT.with(|next| {\n\n let gen = next.get() + 1;\n\n next.set(gen);\n\n Id::gensym(span, gen)\n\n })\n\n}\n\n\n", "file_path": "crates/wast/src/resolve/gensym.rs", "rank": 4, "score": 350646.2583233457 }, { "content": "pub fn resolve<'a>(module: &mut Module<'a>) -> Result<Names<'a>, Error> {\n\n let fields = match &mut module.kind {\n\n ModuleKind::Text(fields) => fields,\n\n _ => return Ok(Default::default()),\n\n };\n\n\n\n // Ensure that each resolution of a module is deterministic in the names\n\n // that it generates by resetting our thread-local symbol generator.\n\n gensym::reset();\n\n\n\n // First up, de-inline import/export annotations.\n\n //\n\n // This ensures we only have to deal with inline definitions and to\n\n // calculate exports we only have to look for a particular kind of module\n\n // field.\n\n deinline_import_export::run(fields);\n\n\n\n aliases::run(fields);\n\n\n\n // With a canonical form of imports make sure that imports are all listed\n", "file_path": "crates/wast/src/resolve/mod.rs", "rank": 5, "score": 340885.6754830298 }, { "content": "fn memory_index(u: &mut Unstructured, builder: &CodeBuilder, ty: ValType) -> Result<u32> {\n\n if ty == ValType::I32 {\n\n Ok(*u.choose(&builder.allocs.memory32)?)\n\n } else {\n\n Ok(*u.choose(&builder.allocs.memory64)?)\n\n }\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 6, "score": 327236.32924471365 }, { "content": "pub fn run(fields: &mut Vec<ModuleField>) {\n\n let mut cur = 0;\n\n let mut to_append = Vec::new();\n\n while cur < fields.len() {\n\n let item = &mut fields[cur];\n\n match item {\n\n ModuleField::Func(f) => {\n\n for name in f.exports.names.drain(..) {\n\n to_append.push(export(f.span, name, ExportKind::Func, &mut f.id));\n\n }\n\n match f.kind {\n\n FuncKind::Import(import) => {\n\n *item = ModuleField::Import(Import {\n\n span: f.span,\n\n module: import.module,\n\n field: import.field,\n\n item: ItemSig {\n\n span: f.span,\n\n id: f.id,\n\n name: f.name,\n", "file_path": "crates/wast/src/resolve/deinline_import_export.rs", "rank": 7, "score": 325125.6232346648 }, { "content": "#[inline]\n\nfn have_memory_and_offset(_module: &Module, builder: &mut CodeBuilder) -> bool {\n\n (builder.allocs.memory32.len() > 0 && builder.type_on_stack(ValType::I32))\n\n || (builder.allocs.memory64.len() > 0 && builder.type_on_stack(ValType::I64))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 8, "score": 317474.4618465319 }, { "content": "#[inline]\n\nfn simd_have_memory_and_offset(module: &Module, builder: &mut CodeBuilder) -> bool {\n\n module.config.simd_enabled() && have_memory_and_offset(module, builder)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 9, "score": 313890.8091651121 }, { "content": "/// Create a set of dummy functions/globals/etc for the given imports.\n\npub fn dummy_imports<'module, T>(store: &mut Store<T>, module: &Module) -> Result<Vec<Extern>> {\n\n let mut result = Vec::new();\n\n for import in module.imports() {\n\n result.push(dummy_extern(store, import.ty())?);\n\n }\n\n Ok(result)\n\n}\n\n\n", "file_path": "crates/fuzz-stats/src/dummy.rs", "rank": 10, "score": 312965.2210637282 }, { "content": "fn memory_offset(u: &mut Unstructured, module: &Module, memory_index: u32) -> Result<u64> {\n\n let (a, b, c) = module.config.memory_offset_choices();\n\n assert!(a + b + c != 0);\n\n\n\n let memory_type = &module.memories[memory_index as usize];\n\n let min = memory_type.minimum.saturating_mul(65536);\n\n let max = memory_type\n\n .maximum\n\n .map(|max| max.saturating_mul(65536))\n\n .unwrap_or(u64::MAX);\n\n let (min, max, true_max) = if memory_type.memory64 {\n\n // 64-bit memories can use the limits calculated above as-is\n\n (min, max, u64::MAX)\n\n } else {\n\n // 32-bit memories can't represent a full 4gb offset, so if that's the\n\n // min/max sizes then we need to switch the m to `u32::MAX`.\n\n (\n\n u64::from(u32::try_from(min).unwrap_or(u32::MAX)),\n\n u64::from(u32::try_from(max).unwrap_or(u32::MAX)),\n\n u64::from(u32::MAX),\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 11, "score": 312544.27909869555 }, { "content": "pub fn map_block_type(ty: TypeOrFuncType) -> Result<BlockType> {\n\n match ty {\n\n TypeOrFuncType::FuncType(f) => Ok(BlockType::FunctionType(f)),\n\n TypeOrFuncType::Type(Type::EmptyBlockType) => Ok(BlockType::Empty),\n\n TypeOrFuncType::Type(ty) => Ok(BlockType::Result(map_type(ty)?)),\n\n }\n\n}\n", "file_path": "crates/wasm-mutate/src/module.rs", "rank": 12, "score": 310591.923012604 }, { "content": "#[inline]\n\nfn simd_have_memory_and_offset_and_v128(module: &Module, builder: &mut CodeBuilder) -> bool {\n\n module.config.simd_enabled() && store_valid(module, builder, || ValType::V128)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 13, "score": 310420.8644566808 }, { "content": "fn r#return(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n let results = builder.allocs.controls[0].results.clone();\n\n builder.pop_operands(&results);\n\n Ok(Instruction::Return)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 14, "score": 305914.1633715466 }, { "content": "fn item_ref<'a, K>(kind: K, id: impl Into<Index<'a>>) -> ItemRef<'a, K> {\n\n ItemRef::Item {\n\n kind,\n\n idx: id.into(),\n\n exports: Vec::new(),\n\n #[cfg(wast_check_exhaustive)]\n\n visited: false,\n\n }\n\n}\n", "file_path": "crates/wast/src/resolve/deinline_import_export.rs", "rank": 15, "score": 292455.72490650846 }, { "content": "/// Construct a dummy function for the given function type\n\npub fn dummy_func<T>(store: &mut Store<T>, ty: FuncType) -> Func {\n\n Func::new(store, ty.clone(), move |_, _, results| {\n\n for (ret_ty, result) in ty.results().zip(results) {\n\n *result = dummy_value(ret_ty);\n\n }\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "crates/fuzz-stats/src/dummy.rs", "rank": 16, "score": 288819.27499477984 }, { "content": "/// Construct a dummy global for the given global type.\n\npub fn dummy_global<T>(store: &mut Store<T>, ty: GlobalType) -> Global {\n\n let val = dummy_value(ty.content().clone());\n\n Global::new(store, ty, val).unwrap()\n\n}\n\n\n", "file_path": "crates/fuzz-stats/src/dummy.rs", "rank": 17, "score": 288819.27499477984 }, { "content": "fn table_index(ty: ValType, u: &mut Unstructured, module: &Module) -> Result<u32> {\n\n let tables = module\n\n .tables\n\n .iter()\n\n .enumerate()\n\n .filter(|(_, t)| t.element_type == ty)\n\n .map(|t| t.0 as u32)\n\n .collect::<Vec<_>>();\n\n Ok(*u.choose(&tables)?)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 18, "score": 287336.8406397334 }, { "content": "#[inline]\n\nfn have_data(module: &Module, _: &mut CodeBuilder) -> bool {\n\n module.data.len() > 0\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 19, "score": 278771.4320199257 }, { "content": "#[inline]\n\nfn have_memory(module: &Module, _: &mut CodeBuilder) -> bool {\n\n module.memories.len() > 0\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 20, "score": 278754.972093782 }, { "content": "#[inline]\n\nfn return_valid(_: &Module, builder: &mut CodeBuilder) -> bool {\n\n builder.label_types_on_stack(&builder.allocs.controls[0])\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 21, "score": 275765.23734196863 }, { "content": "fn data_index(u: &mut Unstructured, module: &Module) -> Result<u32> {\n\n let data = module.data.len() as u32;\n\n assert!(data > 0);\n\n if data == 1 {\n\n Ok(0)\n\n } else {\n\n u.int_in_range(0..=data - 1)\n\n }\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 22, "score": 270947.2581875492 }, { "content": "#[inline]\n\nfn data_drop_valid(module: &Module, builder: &mut CodeBuilder) -> bool {\n\n have_data(module, builder) && module.config.bulk_memory_enabled()\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 23, "score": 269892.2180631979 }, { "content": "#[inline]\n\nfn memory_grow_valid(_module: &Module, builder: &mut CodeBuilder) -> bool {\n\n (builder.allocs.memory32.len() > 0 && builder.type_on_stack(ValType::I32))\n\n || (builder.allocs.memory64.len() > 0 && builder.type_on_stack(ValType::I64))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 24, "score": 269876.55416696664 }, { "content": "#[inline]\n\nfn memory_fill_valid(module: &Module, builder: &mut CodeBuilder) -> bool {\n\n module.config.bulk_memory_enabled()\n\n && (builder.allocs.memory32.len() > 0\n\n && builder.types_on_stack(&[ValType::I32, ValType::I32, ValType::I32])\n\n || (builder.allocs.memory64.len() > 0\n\n && builder.types_on_stack(&[ValType::I64, ValType::I32, ValType::I64])))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 25, "score": 269876.55416696664 }, { "content": "#[inline]\n\nfn memory_init_valid(module: &Module, builder: &mut CodeBuilder) -> bool {\n\n module.config.bulk_memory_enabled()\n\n && have_data(module, builder)\n\n && (builder.allocs.memory32.len() > 0\n\n && builder.types_on_stack(&[ValType::I32, ValType::I32, ValType::I32])\n\n || (builder.allocs.memory64.len() > 0\n\n && builder.types_on_stack(&[ValType::I64, ValType::I32, ValType::I32])))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 26, "score": 269876.55416696664 }, { "content": "#[inline]\n\nfn memory_copy_valid(module: &Module, builder: &mut CodeBuilder) -> bool {\n\n if !module.config.bulk_memory_enabled() {\n\n return false;\n\n }\n\n\n\n if builder.types_on_stack(&[ValType::I64, ValType::I64, ValType::I64])\n\n && builder.allocs.memory64.len() > 0\n\n {\n\n return true;\n\n }\n\n if builder.types_on_stack(&[ValType::I32, ValType::I32, ValType::I32])\n\n && builder.allocs.memory32.len() > 0\n\n {\n\n return true;\n\n }\n\n if builder.types_on_stack(&[ValType::I64, ValType::I32, ValType::I32])\n\n && builder.allocs.memory32.len() > 0\n\n && builder.allocs.memory64.len() > 0\n\n {\n\n return true;\n\n }\n\n if builder.types_on_stack(&[ValType::I32, ValType::I64, ValType::I32])\n\n && builder.allocs.memory32.len() > 0\n\n && builder.allocs.memory64.len() > 0\n\n {\n\n return true;\n\n }\n\n false\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 27, "score": 269876.55416696664 }, { "content": "/// A top-level convenience parseing function that parss a `T` from `buf` and\n\n/// requires that all tokens in `buf` are consume.\n\n///\n\n/// This generic parsing function can be used to parse any `T` implementing the\n\n/// [`Parse`] trait. It is not used from [`Parse`] trait implementations.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use wast::Wat;\n\n/// use wast::parser::{self, ParseBuffer};\n\n///\n\n/// # fn foo() -> Result<(), wast::Error> {\n\n/// let wat = \"(module (func))\";\n\n/// let buf = ParseBuffer::new(wat)?;\n\n/// let module = parser::parse::<Wat>(&buf)?;\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n\n///\n\n/// or parsing simply a fragment\n\n///\n\n/// ```\n\n/// use wast::parser::{self, ParseBuffer};\n\n///\n\n/// # fn foo() -> Result<(), wast::Error> {\n\n/// let wat = \"12\";\n\n/// let buf = ParseBuffer::new(wat)?;\n\n/// let val = parser::parse::<u32>(&buf)?;\n\n/// assert_eq!(val, 12);\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n\npub fn parse<'a, T: Parse<'a>>(buf: &'a ParseBuffer<'a>) -> Result<T> {\n\n let parser = buf.parser();\n\n let result = parser.parse()?;\n\n if parser.cursor().advance_token().is_none() {\n\n Ok(result)\n\n } else {\n\n Err(parser.error(\"extra tokens remaining after parse\"))\n\n }\n\n}\n\n\n", "file_path": "crates/wast/src/parser.rs", "rank": 28, "score": 264353.85209018947 }, { "content": "/// Creates a new `BinaryReader` from the given `reader` which will be reading\n\n/// the first `len` bytes.\n\n///\n\n/// This means that `len` bytes must be resident in memory at the time of this\n\n/// reading.\n\nfn subreader<'a>(reader: &mut BinaryReader<'a>, len: u32) -> Result<BinaryReader<'a>> {\n\n let offset = reader.original_position();\n\n let payload = reader.read_bytes(len as usize)?;\n\n Ok(BinaryReader::new_with_offset(payload, offset))\n\n}\n\n\n", "file_path": "crates/wasmparser/src/parser.rs", "rank": 29, "score": 261868.23245021832 }, { "content": "/// Test whether the given buffer contains a valid WebAssembly module,\n\n/// analogous to [`WebAssembly.validate`][js] in the JS API.\n\n///\n\n/// This functions requires the wasm module is entirely resident in memory and\n\n/// is specified by `bytes`. Additionally this validates the given bytes with\n\n/// the default set of WebAssembly features implemented by `wasmparser`.\n\n///\n\n/// For more fine-tuned control over validation it's recommended to review the\n\n/// documentation of [`Validator`].\n\n///\n\n/// [js]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/validate\n\npub fn validate(bytes: &[u8]) -> Result<()> {\n\n Validator::new().validate_all(bytes)\n\n}\n\n\n", "file_path": "crates/wasmparser/src/validator.rs", "rank": 30, "score": 251358.43272468838 }, { "content": "/// Selects a reasonable offset for an element or data segment. This favors\n\n/// having the segment being in-bounds, but it may still generate\n\n/// any offset.\n\nfn arbitrary_offset(u: &mut Unstructured, min: u64, max: u64, size: usize) -> Result<u64> {\n\n let size = u64::try_from(size).unwrap();\n\n\n\n // If the segment is too big for the whole memory, just give it any\n\n // offset.\n\n if size > min {\n\n u.int_in_range(0..=max)\n\n } else {\n\n gradually_grow(u, 0, min - size, max)\n\n }\n\n}\n\n\n\npub(crate) fn arbitrary_loop(\n\n u: &mut Unstructured,\n\n min: usize,\n\n max: usize,\n\n mut f: impl FnMut(&mut Unstructured) -> Result<bool>,\n\n) -> Result<()> {\n\n assert!(max >= min);\n\n for _ in 0..min {\n", "file_path": "crates/wasm-smith/src/lib.rs", "rank": 31, "score": 250921.33567180944 }, { "content": "fn is_name(name: &str, expected: &'static str) -> bool {\n\n name == expected\n\n}\n\n\n", "file_path": "crates/wasmparser/src/binary_reader.rs", "rank": 32, "score": 249904.8113475528 }, { "content": "/// Reads a section that is represented by a single uleb-encoded `u32`.\n\nfn single_u32<'a>(reader: &mut BinaryReader<'a>, len: u32, desc: &str) -> Result<(u32, Range)> {\n\n let range = Range {\n\n start: reader.original_position(),\n\n end: reader.original_position() + len as usize,\n\n };\n\n let mut content = subreader(reader, len)?;\n\n // We can't recover from \"unexpected eof\" here because our entire section is\n\n // already resident in memory, so clear the hint for how many more bytes are\n\n // expected.\n\n let index = content.read_var_u32().map_err(clear_hint)?;\n\n if !content.eof() {\n\n return Err(BinaryReaderError::new(\n\n format!(\"Unexpected content in the {} section\", desc),\n\n content.original_position(),\n\n ));\n\n }\n\n Ok((index, range))\n\n}\n\n\n", "file_path": "crates/wasmparser/src/parser.rs", "rank": 33, "score": 248264.24685669702 }, { "content": "pub fn benchmark_corpus(c: &mut Criterion) {\n\n let mut corpus = Vec::with_capacity(2000);\n\n let entries = std::fs::read_dir(\"./benches/corpus\").expect(\"failed to read dir\");\n\n for e in entries {\n\n let e = e.expect(\"failed to read dir entry\");\n\n let seed = std::fs::read(e.path()).expect(\"failed to read seed file\");\n\n corpus.push(seed);\n\n }\n\n\n\n // Benchmark how long it takes to generate a module for every seed in our\n\n // corpus (taken from the `validate` fuzz target).\n\n c.bench_function(\"corpus\", |b| {\n\n b.iter(|| {\n\n for seed in &corpus {\n\n let seed = black_box(seed);\n\n let mut u = Unstructured::new(seed);\n\n let result = Module::arbitrary(&mut u);\n\n let _ = black_box(result);\n\n }\n\n })\n\n });\n\n}\n\n\n\ncriterion_group!(benches, benchmark_corpus);\n\ncriterion_main!(benches);\n", "file_path": "crates/wasm-smith/benches/corpus.rs", "rank": 34, "score": 247992.00470437974 }, { "content": "fn is_name_prefix(name: &str, prefix: &'static str) -> bool {\n\n name.starts_with(prefix)\n\n}\n\n\n\nconst WASM_MAGIC_NUMBER: &[u8; 4] = b\"\\0asm\";\n\nconst WASM_EXPERIMENTAL_VERSION: u32 = 0xd;\n\nconst WASM_SUPPORTED_VERSION: u32 = 0x1;\n\n\n\n/// Bytecode range in the WebAssembly module.\n\n#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\n\npub struct Range {\n\n /// The start bound of the range.\n\n pub start: usize,\n\n /// The end bound of the range.\n\n pub end: usize,\n\n}\n\n\n\nimpl Range {\n\n /// Constructs a new instance of `Range`.\n\n ///\n", "file_path": "crates/wasmparser/src/binary_reader.rs", "rank": 35, "score": 247689.69258857874 }, { "content": "fn run_test(test: &Path, bless: bool) -> Result<()> {\n\n let wasm = wat::parse_file(test)?;\n\n let assert = test.with_extension(\"wat.dump\");\n\n let dump =\n\n wasmparser_dump::dump_wasm(&wasm).with_context(|| format!(\"failed to dump {:?}\", test))?;\n\n if bless {\n\n std::fs::write(assert, &dump)?;\n\n return Ok(());\n\n }\n\n\n\n // Ignore CRLF line ending and force always `\\n`\n\n let assert = std::fs::read_to_string(assert)\n\n .unwrap_or(String::new())\n\n .replace(\"\\r\\n\", \"\\n\");\n\n\n\n let mut bad = false;\n\n let mut result = String::new();\n\n for diff in diff::lines(&assert, &dump) {\n\n match diff {\n\n diff::Result::Left(s) => {\n", "file_path": "tests/dump.rs", "rank": 36, "score": 246981.29452819744 }, { "content": "fn assert_local_name(name: &str, wat: &str) -> anyhow::Result<()> {\n\n let wasm = wat::parse_str(wat)?;\n\n let mut found = false;\n\n for s in get_name_section(&wasm)? {\n\n match s? {\n\n Name::Local(n) => {\n\n let mut reader = n.get_indirect_map()?;\n\n let section = reader.read()?;\n\n let mut map = section.get_map()?;\n\n let naming = map.read()?;\n\n assert_eq!(naming.index, 0);\n\n assert_eq!(naming.name, name);\n\n found = true;\n\n }\n\n _ => {}\n\n }\n\n }\n\n assert!(found);\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/wast/tests/annotations.rs", "rank": 37, "score": 246342.60246160062 }, { "content": "fn assert_func_name(name: &str, wat: &str) -> anyhow::Result<()> {\n\n let wasm = wat::parse_str(wat)?;\n\n let mut found = false;\n\n for s in get_name_section(&wasm)? {\n\n match s? {\n\n Name::Function(n) => {\n\n let mut map = n.get_map()?;\n\n let naming = map.read()?;\n\n assert_eq!(naming.index, 0);\n\n assert_eq!(naming.name, name);\n\n found = true;\n\n }\n\n _ => {}\n\n }\n\n }\n\n assert!(found);\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/wast/tests/annotations.rs", "rank": 38, "score": 246342.60246160062 }, { "content": "fn assert_module_name(name: &str, wat: &str) -> anyhow::Result<()> {\n\n let wasm = wat::parse_str(wat)?;\n\n let mut found = false;\n\n for s in get_name_section(&wasm)? {\n\n match s? {\n\n Name::Module(n) => {\n\n assert_eq!(n.get_name()?, name);\n\n found = true;\n\n }\n\n _ => {}\n\n }\n\n }\n\n assert!(found);\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/wast/tests/annotations.rs", "rank": 39, "score": 246342.60246160062 }, { "content": "pub fn dump_wasm(bytes: &[u8]) -> Result<String> {\n\n let mut d = Dump::new(bytes);\n\n d.run()?;\n\n Ok(d.dst)\n\n}\n\n\n", "file_path": "crates/dump/src/lib.rs", "rank": 40, "score": 242113.20340746763 }, { "content": "/// A trait for types which be used to \"peek\" to see if they're the next token\n\n/// in an input stream of [`Parser`].\n\n///\n\n/// Often when implementing [`Parse`] you'll need to query what the next token\n\n/// in the stream is to figure out what to parse next. This [`Peek`] trait\n\n/// defines the set of types that can be tested whether they're the next token\n\n/// in the input stream.\n\n///\n\n/// Implementations of [`Peek`] should only be present on types that consume\n\n/// exactly one token (not zero, not more, exactly one). Types implementing\n\n/// [`Peek`] should also typically implement [`Parse`] should also typically\n\n/// implement [`Parse`].\n\n///\n\n/// See the documentation of [`Parser::peek`] for example usage.\n\npub trait Peek {\n\n /// Tests to see whether this token is the first token within the [`Cursor`]\n\n /// specified.\n\n ///\n\n /// Returns `true` if [`Parse`] for this type is highly likely to succeed\n\n /// failing no other error conditions happening (like an integer literal\n\n /// being too big).\n\n fn peek(cursor: Cursor<'_>) -> bool;\n\n\n\n /// The same as `peek`, except it checks the token immediately following\n\n /// the current token.\n\n fn peek2(mut cursor: Cursor<'_>) -> bool {\n\n if cursor.advance_token().is_some() {\n\n Self::peek(cursor)\n\n } else {\n\n false\n\n }\n\n }\n\n\n\n /// Returns a human-readable name of this token to display when generating\n", "file_path": "crates/wast/src/parser.rs", "rank": 41, "score": 242011.40761152154 }, { "content": "fn export<'a>(\n\n span: Span,\n\n name: &'a str,\n\n kind: ExportKind,\n\n id: &mut Option<Id<'a>>,\n\n) -> ModuleField<'a> {\n\n let id = gensym::fill(span, id);\n\n ModuleField::Export(Export {\n\n span,\n\n name,\n\n index: item_ref(kind, id),\n\n })\n\n}\n\n\n", "file_path": "crates/wast/src/resolve/deinline_import_export.rs", "rank": 42, "score": 240519.76013781555 }, { "content": "pub fn run(fields: &mut Vec<ModuleField>) {\n\n let mut cur = 0;\n\n let mut cx = Expander::default();\n\n\n\n // Note that insertion here is somewhat tricky. We're injecting aliases\n\n // which will affect the index spaces for each kind of item being aliased.\n\n // In the final binary aliases will come before all locally defined items,\n\n // notably via the sorting in binary emission of this crate. To account for\n\n // this index space behavior we need to ensure that aliases all appear at\n\n // the right place in the module.\n\n //\n\n // The general algorithm here is that aliases discovered in the \"header\" of\n\n // the module, e.g. imports/aliases/types/etc, are all inserted preceding\n\n // the field that the alias is found within. After the header, however, the\n\n // position of the header is recorded and all future aliases will be\n\n // inserted at that location.\n\n //\n\n // This ends up meaning that aliases found in globals/functions/tables/etc\n\n // will precede all of those definitions, being positioned at a point that\n\n // should come after all the instances that are defined as well. Overall\n", "file_path": "crates/wast/src/resolve/aliases.rs", "rank": 43, "score": 238958.67622503423 }, { "content": "pub fn map_type(tpe: Type) -> Result<ValType> {\n\n match tpe {\n\n Type::I32 => Ok(ValType::I32),\n\n Type::I64 => Ok(ValType::I64),\n\n Type::F32 => Ok(ValType::F32),\n\n Type::F64 => Ok(ValType::F64),\n\n Type::V128 => Ok(ValType::V128),\n\n Type::FuncRef => Ok(ValType::FuncRef),\n\n Type::ExternRef => Ok(ValType::ExternRef),\n\n _ => Err(Error::unsupported(format!(\n\n \"{:?} is not supported in `wasm-encoder`\",\n\n tpe\n\n ))),\n\n }\n\n}\n\n\n", "file_path": "crates/wasm-mutate/src/module.rs", "rank": 44, "score": 237290.3530417148 }, { "content": "fn unreachable(_: &mut Unstructured, _: &Module, _: &mut CodeBuilder) -> Result<Instruction> {\n\n Ok(Instruction::Unreachable)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 45, "score": 237269.15115667848 }, { "content": "fn nop(_: &mut Unstructured, _: &Module, _: &mut CodeBuilder) -> Result<Instruction> {\n\n Ok(Instruction::Nop)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 46, "score": 237269.15115667848 }, { "content": "fn delegate(u: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n // There will always be at least the function's return frame and try\n\n // control frame if we are emitting delegate\n\n let n = builder.allocs.controls.iter().count();\n\n debug_assert!(n >= 2);\n\n // Delegate must target an outer control from the try block, and is\n\n // encoded with relative depth from the outer control\n\n let target_relative_from_last = u.int_in_range(1..=n - 1)?;\n\n let target_relative_from_outer = target_relative_from_last - 1;\n\n // Delegate ends the try block\n\n builder.allocs.controls.pop();\n\n Ok(Instruction::Delegate(target_relative_from_outer as u32))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 47, "score": 235250.14299082628 }, { "content": "fn rethrow(u: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n let n = builder\n\n .allocs\n\n .controls\n\n .iter()\n\n .filter(|l| l.kind == ControlKind::Catch || l.kind == ControlKind::CatchAll)\n\n .count();\n\n debug_assert!(n > 0);\n\n let i = u.int_in_range(0..=n - 1)?;\n\n let (target, _) = builder\n\n .allocs\n\n .controls\n\n .iter()\n\n .rev()\n\n .enumerate()\n\n .filter(|(_, l)| l.kind == ControlKind::Catch || l.kind == ControlKind::CatchAll)\n\n .nth(i)\n\n .unwrap();\n\n Ok(Instruction::Rethrow(target as u32))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 48, "score": 235250.14299082628 }, { "content": "fn i32_and(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I32, ValType::I32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I32And)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 49, "score": 235250.14299082628 }, { "content": "fn i32_or(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I32, ValType::I32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I32Or)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 50, "score": 235250.14299082628 }, { "content": "fn catch_all(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n let control = builder.allocs.controls.pop().unwrap();\n\n // Pop the results for the previous try or catch\n\n builder.pop_operands(&control.results);\n\n builder.allocs.controls.push(Control {\n\n kind: ControlKind::CatchAll,\n\n ..control\n\n });\n\n Ok(Instruction::CatchAll)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 51, "score": 235250.14299082628 }, { "content": "fn i64_or(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I64, ValType::I64]);\n\n builder.push_operands(&[ValType::I64]);\n\n Ok(Instruction::I64Or)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 52, "score": 235250.14299082628 }, { "content": "fn br(u: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n let n = builder\n\n .allocs\n\n .controls\n\n .iter()\n\n .filter(|l| builder.label_types_on_stack(l))\n\n .count();\n\n debug_assert!(n > 0);\n\n let i = u.int_in_range(0..=n - 1)?;\n\n let (target, _) = builder\n\n .allocs\n\n .controls\n\n .iter()\n\n .rev()\n\n .enumerate()\n\n .filter(|(_, l)| builder.label_types_on_stack(l))\n\n .nth(i)\n\n .unwrap();\n\n let control = &builder.allocs.controls[builder.allocs.controls.len() - 1 - target];\n\n let tys = control.label_types().to_vec();\n\n builder.pop_operands(&tys);\n\n Ok(Instruction::Br(target as u32))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 53, "score": 235250.14299082628 }, { "content": "fn i64_and(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I64, ValType::I64]);\n\n builder.push_operands(&[ValType::I64]);\n\n Ok(Instruction::I64And)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 54, "score": 235250.14299082628 }, { "content": "fn br_if(u: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I32]);\n\n\n\n let n = builder\n\n .allocs\n\n .controls\n\n .iter()\n\n .filter(|l| builder.label_types_on_stack(l))\n\n .count();\n\n debug_assert!(n > 0);\n\n let i = u.int_in_range(0..=n - 1)?;\n\n let (target, _) = builder\n\n .allocs\n\n .controls\n\n .iter()\n\n .rev()\n\n .enumerate()\n\n .filter(|(_, l)| builder.label_types_on_stack(l))\n\n .nth(i)\n\n .unwrap();\n\n Ok(Instruction::BrIf(target as u32))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 55, "score": 235250.14299082628 }, { "content": "fn select(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.allocs.operands.pop();\n\n let t = builder.allocs.operands.pop().unwrap();\n\n let u = builder.allocs.operands.pop().unwrap();\n\n let ty = t.or(u);\n\n builder.allocs.operands.push(ty);\n\n match ty {\n\n Some(ty @ ValType::ExternRef) | Some(ty @ ValType::FuncRef) => {\n\n Ok(Instruction::TypedSelect(ty))\n\n }\n\n Some(ValType::I32) | Some(ValType::I64) | Some(ValType::F32) | Some(ValType::F64)\n\n | Some(ValType::V128) | None => Ok(Instruction::Select),\n\n }\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 56, "score": 235250.14299082628 }, { "content": "fn end(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.allocs.controls.pop();\n\n Ok(Instruction::End)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 57, "score": 235250.14299082628 }, { "content": "fn drop(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.allocs.operands.pop();\n\n Ok(Instruction::Drop)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 58, "score": 235250.14299082628 }, { "content": "/// Build RecExpr from tree information\n\npub fn build_expr(root: Id, id_to_node: &[Lang], operands: &[Vec<Id>]) -> RecExpr<Lang> {\n\n let mut expr = RecExpr::default();\n\n build_expr_inner(root, id_to_node, operands, &mut expr);\n\n expr\n\n}\n\n\n\npub(crate) fn build_expr_inner(\n\n root: Id,\n\n id_to_node: &[Lang],\n\n operands: &[Vec<Id>],\n\n expr: &mut RecExpr<Lang>,\n\n) -> Id {\n\n // A map from the `Id`s we assigned to each sub-expression when extracting a\n\n // random expression to the `Id`s assigned to each sub-expression by the\n\n // `RecExpr`.\n\n let mut node_to_id: HashMap<Id, Id> = Default::default();\n\n\n\n let mut to_visit = vec![(TraversalEvent::Exit, root), (TraversalEvent::Enter, root)];\n\n while let Some((event, node)) = to_visit.pop() {\n\n match event {\n", "file_path": "crates/wasm-mutate/src/mutators/peephole/eggsy/encoder/rebuild.rs", "rank": 59, "score": 234161.17063572118 }, { "content": "fn i64_ge_s(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I64, ValType::I64]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I64GeS)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 60, "score": 233288.60437864365 }, { "content": "fn local_set(u: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n let n = builder\n\n .func_ty\n\n .params\n\n .iter()\n\n .chain(builder.locals.iter())\n\n .filter(|ty| builder.type_on_stack(**ty))\n\n .count();\n\n debug_assert!(n > 0);\n\n let i = u.int_in_range(0..=n - 1)?;\n\n let (j, _) = builder\n\n .func_ty\n\n .params\n\n .iter()\n\n .chain(builder.locals.iter())\n\n .enumerate()\n\n .filter(|(_, ty)| builder.type_on_stack(**ty))\n\n .nth(i)\n\n .unwrap();\n\n builder.allocs.operands.pop();\n\n Ok(Instruction::LocalSet(j as u32))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 61, "score": 233288.60437864365 }, { "content": "fn i32_gt_s(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I32, ValType::I32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I32GtS)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 62, "score": 233288.60437864365 }, { "content": "fn i32_neq(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I32, ValType::I32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I32Neq)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 63, "score": 233288.60437864365 }, { "content": "fn i64_eq(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I64, ValType::I64]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I64Eq)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 64, "score": 233288.60437864365 }, { "content": "fn i32_lt_s(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I32, ValType::I32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I32LtS)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 65, "score": 233288.60437864365 }, { "content": "fn throw(u: &mut Unstructured, module: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n let candidates = builder\n\n .allocs\n\n .tags\n\n .iter()\n\n .filter(|(k, _)| builder.types_on_stack(k))\n\n .flat_map(|(_, v)| v.iter().copied())\n\n .collect::<Vec<_>>();\n\n assert!(candidates.len() > 0);\n\n let i = u.int_in_range(0..=candidates.len() - 1)?;\n\n let (tag_idx, tag_type) = module.tags().nth(candidates[i] as usize).unwrap();\n\n // Tags have no results, throwing cannot return\n\n assert!(tag_type.func_type.results.len() == 0);\n\n builder.pop_operands(&tag_type.func_type.params);\n\n Ok(Instruction::Throw(tag_idx as u32))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 66, "score": 233288.60437864365 }, { "content": "fn i32_ge_u(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I32, ValType::I32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I32GeU)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 67, "score": 233288.60437864365 }, { "content": "fn f32_ge(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::F32, ValType::F32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::F32Ge)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 68, "score": 233288.60437864365 }, { "content": "fn i32_lt_u(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I32, ValType::I32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I32LtU)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 69, "score": 233288.60437864365 }, { "content": "fn i32_le_s(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I32, ValType::I32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I32LeS)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 70, "score": 233288.60437864365 }, { "content": "fn i64_eqz(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I64]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I64Eqz)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 71, "score": 233288.60437864365 }, { "content": "fn i32_const(u: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n let x = u.arbitrary()?;\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I32Const(x))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 72, "score": 233288.60437864365 }, { "content": "fn br_table(u: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I32]);\n\n\n\n let n = builder\n\n .allocs\n\n .controls\n\n .iter()\n\n .filter(|l| builder.label_types_on_stack(l))\n\n .count();\n\n debug_assert!(n > 0);\n\n\n\n let i = u.int_in_range(0..=n - 1)?;\n\n let (default_target, _) = builder\n\n .allocs\n\n .controls\n\n .iter()\n\n .rev()\n\n .enumerate()\n\n .filter(|(_, l)| builder.label_types_on_stack(l))\n\n .nth(i)\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 73, "score": 233288.60437864365 }, { "content": "fn local_get(u: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n let num_params = builder.func_ty.params.len();\n\n let n = num_params + builder.locals.len();\n\n debug_assert!(n > 0);\n\n let i = u.int_in_range(0..=n - 1)?;\n\n builder.allocs.operands.push(Some(if i < num_params {\n\n builder.func_ty.params[i]\n\n } else {\n\n builder.locals[i - num_params]\n\n }));\n\n Ok(Instruction::LocalGet(i as u32))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 74, "score": 233288.60437864365 }, { "content": "fn i32_gt_u(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I32, ValType::I32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I32GtU)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 75, "score": 233288.60437864365 }, { "content": "fn f64_const(u: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n let x = u.arbitrary()?;\n\n builder.push_operands(&[ValType::F64]);\n\n Ok(Instruction::F64Const(x))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 76, "score": 233288.60437864365 }, { "content": "fn i32_le_u(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I32, ValType::I32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I32LeU)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 77, "score": 233288.60437864365 }, { "content": "fn i64_lt_u(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I64, ValType::I64]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I64LtU)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 78, "score": 233288.60437864365 }, { "content": "fn i32_eq(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I32, ValType::I32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I32Eq)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 79, "score": 233288.60437864365 }, { "content": "fn global_set(u: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n let candidates = builder\n\n .allocs\n\n .mutable_globals\n\n .iter()\n\n .find(|(ty, _)| builder.type_on_stack(**ty))\n\n .unwrap()\n\n .1;\n\n let i = u.int_in_range(0..=candidates.len() - 1)?;\n\n builder.allocs.operands.pop();\n\n Ok(Instruction::GlobalSet(candidates[i]))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 80, "score": 233288.60437864365 }, { "content": "fn i64_lt_s(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I64, ValType::I64]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I64LtS)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 81, "score": 233288.60437864365 }, { "content": "fn f32_neq(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::F32, ValType::F32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::F32Neq)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 82, "score": 233288.60437864365 }, { "content": "fn i64_neq(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I64, ValType::I64]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I64Neq)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 83, "score": 233288.60437864365 }, { "content": "fn i32_eqz(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I32Eqz)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 84, "score": 233288.60437864365 }, { "content": "fn f32_le(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::F32, ValType::F32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::F32Le)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 85, "score": 233288.60437864365 }, { "content": "fn f32_gt(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::F32, ValType::F32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::F32Gt)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 86, "score": 233288.60437864365 }, { "content": "fn f32_const(u: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n let x = u.arbitrary()?;\n\n builder.push_operands(&[ValType::F32]);\n\n Ok(Instruction::F32Const(x))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 87, "score": 233288.60437864365 }, { "content": "fn i64_gt_u(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I64, ValType::I64]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I64GtU)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 88, "score": 233288.60437864365 }, { "content": "fn i32_ge_s(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I32, ValType::I32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I32GeS)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 89, "score": 233288.60437864365 }, { "content": "fn block(u: &mut Unstructured, module: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n let block_ty = builder.arbitrary_block_type(u, module)?;\n\n let (params, results) = module.params_results(&block_ty);\n\n let height = builder.allocs.operands.len() - params.len();\n\n builder.allocs.controls.push(Control {\n\n kind: ControlKind::Block,\n\n params,\n\n results,\n\n height,\n\n });\n\n Ok(Instruction::Block(block_ty))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 90, "score": 233288.60437864365 }, { "content": "fn i64_le_u(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I64, ValType::I64]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I64LeU)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 91, "score": 233288.60437864365 }, { "content": "fn local_tee(u: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n let n = builder\n\n .func_ty\n\n .params\n\n .iter()\n\n .chain(builder.locals.iter())\n\n .filter(|ty| builder.type_on_stack(**ty))\n\n .count();\n\n debug_assert!(n > 0);\n\n let i = u.int_in_range(0..=n - 1)?;\n\n let (j, _) = builder\n\n .func_ty\n\n .params\n\n .iter()\n\n .chain(builder.locals.iter())\n\n .enumerate()\n\n .filter(|(_, ty)| builder.type_on_stack(**ty))\n\n .nth(i)\n\n .unwrap();\n\n Ok(Instruction::LocalTee(j as u32))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 92, "score": 233288.60437864365 }, { "content": "fn i64_const(u: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n let x = u.arbitrary()?;\n\n builder.push_operands(&[ValType::I64]);\n\n Ok(Instruction::I64Const(x))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 93, "score": 233288.60437864365 }, { "content": "fn f32_lt(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::F32, ValType::F32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::F32Lt)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 94, "score": 233288.60437864365 }, { "content": "fn f32_eq(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::F32, ValType::F32]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::F32Eq)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 95, "score": 233288.60437864365 }, { "content": "fn i64_ge_u(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I64, ValType::I64]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I64GeU)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 96, "score": 233288.60437864365 }, { "content": "fn i64_gt_s(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I64, ValType::I64]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I64GtS)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 97, "score": 233288.60437864365 }, { "content": "fn i64_le_s(_: &mut Unstructured, _: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n builder.pop_operands(&[ValType::I64, ValType::I64]);\n\n builder.push_operands(&[ValType::I32]);\n\n Ok(Instruction::I64LeS)\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 98, "score": 233288.60437864365 }, { "content": "fn catch(u: &mut Unstructured, module: &Module, builder: &mut CodeBuilder) -> Result<Instruction> {\n\n let tag_idx = u.int_in_range(0..=(module.tags.len() - 1))?;\n\n let tag_type = &module.tags[tag_idx];\n\n let control = builder.allocs.controls.pop().unwrap();\n\n // Pop the results for the previous try or catch\n\n builder.pop_operands(&control.results);\n\n // Push the params of the tag we're catching\n\n builder.push_operands(&tag_type.func_type.params);\n\n builder.allocs.controls.push(Control {\n\n kind: ControlKind::Catch,\n\n ..control\n\n });\n\n Ok(Instruction::Catch(tag_idx as u32))\n\n}\n\n\n", "file_path": "crates/wasm-smith/src/code_builder.rs", "rank": 99, "score": 233288.60437864365 } ]
Rust
http/src/request/channel/invite/create_invite.rs
dawn-rs/dawn
294f80cc0ab556925c53bb6cf8d1297e150f49bc
use crate::{ client::Client, error::Error as HttpError, request::{self, AuditLogReason, Request, TryIntoRequest}, response::ResponseFuture, routing::Route, }; use serde::Serialize; use twilight_model::{ id::{ marker::{ApplicationMarker, ChannelMarker, UserMarker}, Id, }, invite::{Invite, TargetType}, }; use twilight_validate::request::{ audit_reason as validate_audit_reason, invite_max_age as validate_invite_max_age, invite_max_uses as validate_invite_max_uses, ValidationError, }; #[derive(Serialize)] struct CreateInviteFields { #[serde(skip_serializing_if = "Option::is_none")] max_age: Option<u32>, #[serde(skip_serializing_if = "Option::is_none")] max_uses: Option<u16>, #[serde(skip_serializing_if = "Option::is_none")] temporary: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] target_application_id: Option<Id<ApplicationMarker>>, #[serde(skip_serializing_if = "Option::is_none")] target_user_id: Option<Id<UserMarker>>, #[serde(skip_serializing_if = "Option::is_none")] target_type: Option<TargetType>, #[serde(skip_serializing_if = "Option::is_none")] unique: Option<bool>, } #[must_use = "requests must be configured and executed"] pub struct CreateInvite<'a> { channel_id: Id<ChannelMarker>, fields: CreateInviteFields, http: &'a Client, reason: Option<&'a str>, } impl<'a> CreateInvite<'a> { pub(crate) const fn new(http: &'a Client, channel_id: Id<ChannelMarker>) -> Self { Self { channel_id, fields: CreateInviteFields { max_age: None, max_uses: None, temporary: None, target_application_id: None, target_user_id: None, target_type: None, unique: None, }, http, reason: None, } } pub const fn max_age(mut self, max_age: u32) -> Result<Self, ValidationError> { if let Err(source) = validate_invite_max_age(max_age) { return Err(source); } self.fields.max_age = Some(max_age); Ok(self) } pub const fn max_uses(mut self, max_uses: u16) -> Result<Self, ValidationError> { if let Err(source) = validate_invite_max_uses(max_uses) { return Err(source); } self.fields.max_uses = Some(max_uses); Ok(self) } pub const fn target_application_id( mut self, target_application_id: Id<ApplicationMarker>, ) -> Self { self.fields.target_application_id = Some(target_application_id); self } pub const fn target_user_id(mut self, target_user_id: Id<UserMarker>) -> Self { self.fields.target_user_id = Some(target_user_id); self } pub const fn target_type(mut self, target_type: TargetType) -> Self { self.fields.target_type = Some(target_type); self } pub const fn temporary(mut self, temporary: bool) -> Self { self.fields.temporary = Some(temporary); self } pub const fn unique(mut self, unique: bool) -> Self { self.fields.unique = Some(unique); self } pub fn exec(self) -> ResponseFuture<Invite> { let http = self.http; match self.try_into_request() { Ok(request) => http.request(request), Err(source) => ResponseFuture::error(source), } } } impl<'a> AuditLogReason<'a> for CreateInvite<'a> { fn reason(mut self, reason: &'a str) -> Result<Self, ValidationError> { validate_audit_reason(reason)?; self.reason.replace(reason); Ok(self) } } impl TryIntoRequest for CreateInvite<'_> { fn try_into_request(self) -> Result<Request, HttpError> { let mut request = Request::builder(&Route::CreateInvite { channel_id: self.channel_id.get(), }); request = request.json(&self.fields)?; if let Some(reason) = self.reason { let header = request::audit_header(reason)?; request = request.headers(header); } Ok(request.build()) } } #[cfg(test)] mod tests { use super::CreateInvite; use crate::Client; use std::error::Error; use twilight_model::id::Id; #[test] fn max_age() -> Result<(), Box<dyn Error>> { let client = Client::new("foo".to_owned()); let mut builder = CreateInvite::new(&client, Id::new(1)).max_age(0)?; assert_eq!(Some(0), builder.fields.max_age); builder = builder.max_age(604_800)?; assert_eq!(Some(604_800), builder.fields.max_age); assert!(builder.max_age(604_801).is_err()); Ok(()) } #[test] fn max_uses() -> Result<(), Box<dyn Error>> { let client = Client::new("foo".to_owned()); let mut builder = CreateInvite::new(&client, Id::new(1)).max_uses(0)?; assert_eq!(Some(0), builder.fields.max_uses); builder = builder.max_uses(100)?; assert_eq!(Some(100), builder.fields.max_uses); assert!(builder.max_uses(101).is_err()); Ok(()) } }
use crate::{ client::Client, error::Error as HttpError, request::{self, AuditLogReason, Request, TryIntoRequest}, response::ResponseFuture, routing::Route, }; use serde::Serialize; use twilight_model::{ id::{ marker::{ApplicationMarker, ChannelMarker, UserMarker}, Id, }, invite::{Invite, TargetType}, }; use twilight_validate::request::{ audit_reason as validate_audit_reason, invite_max_age as validate_invite_max_age, invite_max_uses as validate_invite_max_uses, ValidationError, }; #[derive(Serialize)] struct CreateInviteFields { #[serde(skip_serializing_if = "Option::is_none")] max_age: Option<u32>, #[serde(skip_serializing_if = "Option::is_none")] max_uses: Option<u16>, #[serde(skip_serializing_if = "Option::is_none")] temporary: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] target_application_id: Option<Id<ApplicationMarker>>, #[serde(skip_serializing_if = "Option::is_none")] target_user_id: Option<Id<UserMarker>>, #[serde(skip_serializing_if = "Option::is_
lidationError> { if let Err(source) = validate_invite_max_age(max_age) { return Err(source); } self.fields.max_age = Some(max_age); Ok(self) } pub const fn max_uses(mut self, max_uses: u16) -> Result<Self, ValidationError> { if let Err(source) = validate_invite_max_uses(max_uses) { return Err(source); } self.fields.max_uses = Some(max_uses); Ok(self) } pub const fn target_application_id( mut self, target_application_id: Id<ApplicationMarker>, ) -> Self { self.fields.target_application_id = Some(target_application_id); self } pub const fn target_user_id(mut self, target_user_id: Id<UserMarker>) -> Self { self.fields.target_user_id = Some(target_user_id); self } pub const fn target_type(mut self, target_type: TargetType) -> Self { self.fields.target_type = Some(target_type); self } pub const fn temporary(mut self, temporary: bool) -> Self { self.fields.temporary = Some(temporary); self } pub const fn unique(mut self, unique: bool) -> Self { self.fields.unique = Some(unique); self } pub fn exec(self) -> ResponseFuture<Invite> { let http = self.http; match self.try_into_request() { Ok(request) => http.request(request), Err(source) => ResponseFuture::error(source), } } } impl<'a> AuditLogReason<'a> for CreateInvite<'a> { fn reason(mut self, reason: &'a str) -> Result<Self, ValidationError> { validate_audit_reason(reason)?; self.reason.replace(reason); Ok(self) } } impl TryIntoRequest for CreateInvite<'_> { fn try_into_request(self) -> Result<Request, HttpError> { let mut request = Request::builder(&Route::CreateInvite { channel_id: self.channel_id.get(), }); request = request.json(&self.fields)?; if let Some(reason) = self.reason { let header = request::audit_header(reason)?; request = request.headers(header); } Ok(request.build()) } } #[cfg(test)] mod tests { use super::CreateInvite; use crate::Client; use std::error::Error; use twilight_model::id::Id; #[test] fn max_age() -> Result<(), Box<dyn Error>> { let client = Client::new("foo".to_owned()); let mut builder = CreateInvite::new(&client, Id::new(1)).max_age(0)?; assert_eq!(Some(0), builder.fields.max_age); builder = builder.max_age(604_800)?; assert_eq!(Some(604_800), builder.fields.max_age); assert!(builder.max_age(604_801).is_err()); Ok(()) } #[test] fn max_uses() -> Result<(), Box<dyn Error>> { let client = Client::new("foo".to_owned()); let mut builder = CreateInvite::new(&client, Id::new(1)).max_uses(0)?; assert_eq!(Some(0), builder.fields.max_uses); builder = builder.max_uses(100)?; assert_eq!(Some(100), builder.fields.max_uses); assert!(builder.max_uses(101).is_err()); Ok(()) } }
none")] target_type: Option<TargetType>, #[serde(skip_serializing_if = "Option::is_none")] unique: Option<bool>, } #[must_use = "requests must be configured and executed"] pub struct CreateInvite<'a> { channel_id: Id<ChannelMarker>, fields: CreateInviteFields, http: &'a Client, reason: Option<&'a str>, } impl<'a> CreateInvite<'a> { pub(crate) const fn new(http: &'a Client, channel_id: Id<ChannelMarker>) -> Self { Self { channel_id, fields: CreateInviteFields { max_age: None, max_uses: None, temporary: None, target_application_id: None, target_user_id: None, target_type: None, unique: None, }, http, reason: None, } } pub const fn max_age(mut self, max_age: u32) -> Result<Self, Va
random
[ { "content": "struct PresenceVisitor(Id<GuildMarker>);\n\n\n\nimpl<'de> Visitor<'de> for PresenceVisitor {\n\n type Value = Presence;\n\n\n\n fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.write_str(\"Presence struct\")\n\n }\n\n\n\n fn visit_map<M: MapAccess<'de>>(self, map: M) -> Result<Self::Value, M::Error> {\n\n let deser = MapAccessDeserializer::new(map);\n\n let presence = PresenceIntermediary::deserialize(deser)?;\n\n\n\n Ok(Presence {\n\n activities: presence.activities,\n\n client_status: presence.client_status,\n\n guild_id: presence.guild_id.unwrap_or(self.0),\n\n status: presence.status,\n\n user: presence.user,\n\n })\n", "file_path": "model/src/gateway/presence/mod.rs", "rank": 0, "score": 152790.72842744208 }, { "content": "struct MemberListVisitor(Id<GuildMarker>);\n\n\n\nimpl<'de> Visitor<'de> for MemberListVisitor {\n\n type Value = Vec<Member>;\n\n\n\n fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.write_str(\"a sequence of members\")\n\n }\n\n\n\n fn visit_seq<S: SeqAccess<'de>>(self, mut seq: S) -> Result<Self::Value, S::Error> {\n\n let mut list = seq.size_hint().map_or_else(Vec::new, Vec::with_capacity);\n\n\n\n while let Some(member) = seq.next_element_seed(MemberDeserializer(self.0))? {\n\n list.push(member);\n\n }\n\n\n\n Ok(list)\n\n }\n\n}\n\n\n", "file_path": "model/src/guild/member.rs", "rank": 1, "score": 152790.72842744208 }, { "content": "struct OptionalMemberVisitor(Id<GuildMarker>);\n\n\n\nimpl<'de> Visitor<'de> for OptionalMemberVisitor {\n\n type Value = Option<Member>;\n\n\n\n fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.write_str(\"an optional member\")\n\n }\n\n\n\n fn visit_none<E: DeError>(self) -> Result<Self::Value, E> {\n\n Ok(None)\n\n }\n\n\n\n fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {\n\n Ok(Some(deserializer.deserialize_map(MemberVisitor(self.0))?))\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, Eq, PartialEq)]\n\npub struct MemberListDeserializer(Id<GuildMarker>);\n\n\n\nimpl MemberListDeserializer {\n\n /// Create a new deserializer for a map of members when you know the\n\n /// Guild ID but the payload probably doesn't contain it.\n\n pub const fn new(guild_id: Id<GuildMarker>) -> Self {\n\n Self(guild_id)\n\n }\n\n}\n\n\n", "file_path": "model/src/guild/member.rs", "rank": 2, "score": 152790.72842744208 }, { "content": "struct PresenceListDeserializerVisitor(Id<GuildMarker>);\n\n\n\nimpl<'de> Visitor<'de> for PresenceListDeserializerVisitor {\n\n type Value = Vec<Presence>;\n\n\n\n fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.write_str(\"a sequence of presences\")\n\n }\n\n\n\n fn visit_seq<S: SeqAccess<'de>>(self, mut seq: S) -> Result<Self::Value, S::Error> {\n\n let mut list = seq.size_hint().map_or_else(Vec::new, Vec::with_capacity);\n\n\n\n while let Some(presence) = seq.next_element_seed(PresenceDeserializer(self.0))? {\n\n list.push(presence);\n\n }\n\n\n\n Ok(list)\n\n }\n\n}\n\n\n", "file_path": "model/src/gateway/presence/mod.rs", "rank": 3, "score": 148727.77273741807 }, { "content": "struct GetGuildFields {\n\n with_counts: bool,\n\n}\n\n\n\n/// Get information about a guild.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct GetGuild<'a> {\n\n fields: GetGuildFields,\n\n guild_id: Id<GuildMarker>,\n\n http: &'a Client,\n\n}\n\n\n\nimpl<'a> GetGuild<'a> {\n\n pub(crate) const fn new(http: &'a Client, guild_id: Id<GuildMarker>) -> Self {\n\n Self {\n\n fields: GetGuildFields { with_counts: false },\n\n guild_id,\n\n http,\n\n }\n\n }\n", "file_path": "http/src/request/guild/get_guild.rs", "rank": 4, "score": 130558.81570753685 }, { "content": "#[derive(Serialize)]\n\nstruct CommandBorrowed<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub application_id: Option<Id<ApplicationMarker>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub default_member_permissions: Option<Permissions>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub dm_permission: Option<bool>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub description: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub description_localizations: Option<&'a HashMap<String, String>>,\n\n #[serde(rename = \"type\")]\n\n pub kind: CommandType,\n\n pub name: &'a str,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub name_localizations: Option<&'a HashMap<String, String>>,\n\n #[serde(default)]\n\n pub options: Option<&'a [CommandOption]>,\n\n}\n\n\n", "file_path": "http/src/request/application/command/mod.rs", "rank": 5, "score": 129649.48368535076 }, { "content": "struct GetBansFields {\n\n after: Option<Id<UserMarker>>,\n\n before: Option<Id<UserMarker>>,\n\n limit: Option<u16>,\n\n}\n\n\n\n/// Retrieve the bans for a guild.\n\n///\n\n/// # Examples\n\n///\n\n/// Retrieve the first 25 bans of a guild after a particular user ID:\n\n///\n\n/// ```no_run\n\n/// use std::env;\n\n/// use twilight_http::Client;\n\n/// use twilight_model::id::Id;\n\n///\n\n/// # #[tokio::main]\n\n/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n/// let client = Client::new(env::var(\"DISCORD_TOKEN\")?);\n", "file_path": "http/src/request/guild/ban/get_bans.rs", "rank": 6, "score": 128421.00357548654 }, { "content": "struct GetInviteFields {\n\n with_counts: bool,\n\n with_expiration: bool,\n\n}\n\n\n\n/// Get information about an invite by its code.\n\n///\n\n/// If [`with_counts`] is called, the returned invite will contain approximate\n\n/// member counts. If [`with_expiration`] is called, it will contain the\n\n/// expiration date.\n\n///\n\n/// # Examples\n\n///\n\n/// ```no_run\n\n/// use twilight_http::Client;\n\n///\n\n/// # #[tokio::main]\n\n/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n/// let client = Client::new(\"my token\".to_owned());\n\n///\n", "file_path": "http/src/request/channel/invite/get_invite.rs", "rank": 8, "score": 128421.00357548654 }, { "content": "struct GetReactionsFields {\n\n after: Option<Id<UserMarker>>,\n\n limit: Option<u16>,\n\n}\n\n\n\n/// Get a list of users that reacted to a message with an `emoji`.\n\n///\n\n/// This endpoint is limited to 100 users maximum, so if a message has more than 100 reactions,\n\n/// requests must be chained until all reactions are retrieved.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct GetReactions<'a> {\n\n channel_id: Id<ChannelMarker>,\n\n emoji: &'a RequestReactionType<'a>,\n\n fields: GetReactionsFields,\n\n http: &'a Client,\n\n message_id: Id<MessageMarker>,\n\n}\n\n\n\nimpl<'a> GetReactions<'a> {\n\n pub(crate) const fn new(\n", "file_path": "http/src/request/channel/reaction/get_reactions.rs", "rank": 9, "score": 128421.00357548654 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateChannelFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n bitrate: Option<u32>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n name: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n nsfw: Option<bool>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n parent_id: Option<Nullable<Id<ChannelMarker>>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n permission_overwrites: Option<&'a [PermissionOverwrite]>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n position: Option<u64>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n rate_limit_per_user: Option<u16>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n topic: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n user_limit: Option<u16>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n", "file_path": "http/src/request/channel/update_channel.rs", "rank": 10, "score": 127413.6586684632 }, { "content": "#[derive(Serialize)]\n\nstruct CreateTemplateFields<'a> {\n\n name: &'a str,\n\n description: Option<&'a str>,\n\n}\n\n\n\n/// Create a template from the current state of the guild.\n\n///\n\n/// Requires the `MANAGE_GUILD` permission. The name must be at least 1 and at\n\n/// most 100 characters in length.\n\n///\n\n/// # Errors\n\n///\n\n/// Returns an error of type [`TemplateName`] if the name length is too short or\n\n/// too long.\n\n///\n\n/// [`TemplateName`]: twilight_validate::request::ValidationErrorType::TemplateName\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct CreateTemplate<'a> {\n\n fields: CreateTemplateFields<'a>,\n\n guild_id: Id<GuildMarker>,\n", "file_path": "http/src/request/template/create_template.rs", "rank": 11, "score": 127413.6586684632 }, { "content": "#[derive(Serialize)]\n\nstruct EntityMetadataFields<'a> {\n\n location: Option<&'a str>,\n\n}\n", "file_path": "http/src/request/scheduled_event/mod.rs", "rank": 12, "score": 127413.6586684632 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateGuildFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n afk_channel_id: Option<Nullable<Id<ChannelMarker>>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n afk_timeout: Option<u64>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n banner: Option<Nullable<&'a str>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n default_message_notifications: Option<Nullable<DefaultMessageNotificationLevel>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n discovery_splash: Option<Nullable<&'a str>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n explicit_content_filter: Option<Nullable<ExplicitContentFilter>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n features: Option<&'a [&'a str]>,\n\n #[serde(\n\n serialize_with = \"request::serialize_optional_nullable_image\",\n\n skip_serializing_if = \"Option::is_none\"\n\n )]\n\n icon: Option<Nullable<&'a [u8]>>,\n", "file_path": "http/src/request/guild/update_guild.rs", "rank": 13, "score": 127413.6586684632 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateTemplateFields<'a> {\n\n name: Option<&'a str>,\n\n description: Option<&'a str>,\n\n}\n\n\n\n/// Update the template's metadata, by ID and code.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct UpdateTemplate<'a> {\n\n fields: UpdateTemplateFields<'a>,\n\n guild_id: Id<GuildMarker>,\n\n http: &'a Client,\n\n template_code: &'a str,\n\n}\n\n\n\nimpl<'a> UpdateTemplate<'a> {\n\n pub(crate) const fn new(\n\n http: &'a Client,\n\n guild_id: Id<GuildMarker>,\n\n template_code: &'a str,\n\n ) -> Self {\n", "file_path": "http/src/request/template/update_template.rs", "rank": 14, "score": 127413.6586684632 }, { "content": "#[derive(Serialize)]\n\nstruct FollowNewsChannelFields {\n\n webhook_channel_id: Id<ChannelMarker>,\n\n}\n\n\n\n/// Follow a news channel by [`Id<ChannelMarker>`]s.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct FollowNewsChannel<'a> {\n\n channel_id: Id<ChannelMarker>,\n\n fields: FollowNewsChannelFields,\n\n http: &'a Client,\n\n}\n\n\n\nimpl<'a> FollowNewsChannel<'a> {\n\n pub(crate) const fn new(\n\n http: &'a Client,\n\n channel_id: Id<ChannelMarker>,\n\n webhook_channel_id: Id<ChannelMarker>,\n\n ) -> Self {\n\n Self {\n\n channel_id,\n", "file_path": "http/src/request/channel/follow_news_channel.rs", "rank": 15, "score": 126374.89760996719 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateChannelPermissionFields {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n allow: Option<Permissions>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n deny: Option<Permissions>,\n\n #[serde(rename = \"type\")]\n\n kind: PermissionOverwriteType,\n\n}\n\n\n\n/// Update the permissions for a role or a user in a channel.\n\n///\n\n/// # Examples:\n\n///\n\n/// Create permission overrides for a role to view the channel, but not send\n\n/// messages:\n\n///\n\n/// ```no_run\n\n/// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n/// # use twilight_http::Client;\n\n/// # let client = Client::new(\"my token\".to_owned());\n", "file_path": "http/src/request/channel/update_channel_permission.rs", "rank": 16, "score": 126374.89760996719 }, { "content": "struct GetAuditLogFields {\n\n action_type: Option<AuditLogEventType>,\n\n before: Option<u64>,\n\n limit: Option<u16>,\n\n user_id: Option<Id<UserMarker>>,\n\n}\n\n\n\n/// Get the audit log for a guild.\n\n///\n\n/// # Examples\n\n///\n\n/// ```no_run\n\n/// use twilight_http::Client;\n\n/// use twilight_model::id::Id;\n\n///\n\n/// # #[tokio::main]\n\n/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n/// let client = Client::new(\"token\".to_owned());\n\n///\n\n/// let guild_id = Id::new(101);\n", "file_path": "http/src/request/guild/get_audit_log.rs", "rank": 17, "score": 126374.89760996719 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateGuildWidgetFields {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n channel_id: Option<Nullable<Id<ChannelMarker>>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n enabled: Option<bool>,\n\n}\n\n\n\n/// Modify the guild widget.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct UpdateGuildWidget<'a> {\n\n fields: UpdateGuildWidgetFields,\n\n guild_id: Id<GuildMarker>,\n\n http: &'a Client,\n\n}\n\n\n\nimpl<'a> UpdateGuildWidget<'a> {\n\n pub(crate) const fn new(http: &'a Client, guild_id: Id<GuildMarker>) -> Self {\n\n Self {\n\n fields: UpdateGuildWidgetFields {\n\n channel_id: None,\n", "file_path": "http/src/request/guild/update_guild_widget.rs", "rank": 18, "score": 126374.89760996719 }, { "content": "#[derive(Serialize)]\n\nstruct CreatePrivateChannelFields {\n\n recipient_id: Id<UserMarker>,\n\n}\n\n\n\n/// Create a group DM.\n\n///\n\n/// This endpoint is limited to 10 active group DMs.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct CreatePrivateChannel<'a> {\n\n fields: CreatePrivateChannelFields,\n\n http: &'a Client,\n\n}\n\n\n\nimpl<'a> CreatePrivateChannel<'a> {\n\n pub(crate) const fn new(http: &'a Client, recipient_id: Id<UserMarker>) -> Self {\n\n Self {\n\n fields: CreatePrivateChannelFields { recipient_id },\n\n http,\n\n }\n\n }\n", "file_path": "http/src/request/user/create_private_channel.rs", "rank": 19, "score": 126374.89760996719 }, { "content": "#[derive(Serialize)]\n\nstruct DeleteMessagesFields<'a> {\n\n messages: &'a [Id<MessageMarker>],\n\n}\n\n\n\n/// Delete messages by [`Id<ChannelMarker>`] and a list of [`Id<MessageMarker>`]s.\n\n///\n\n/// The number of message IDs must be between 2 and 100. If the supplied message\n\n/// IDs are invalid, they still count towards the lower and upper limits. This\n\n/// method will not delete messages older than two weeks. See\n\n/// [Discord Docs/Bulk Delete Messages].\n\n///\n\n/// [Discord Docs/Bulk Delete Messages]: https://discord.com/developers/docs/resources/channel#bulk-delete-messages\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct DeleteMessages<'a> {\n\n channel_id: Id<ChannelMarker>,\n\n fields: DeleteMessagesFields<'a>,\n\n http: &'a Client,\n\n reason: Option<&'a str>,\n\n}\n\n\n", "file_path": "http/src/request/channel/message/delete_messages.rs", "rank": 20, "score": 125275.8465364129 }, { "content": "#[derive(Serialize)]\n\nstruct CreateFollowupFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n allowed_mentions: Option<Nullable<&'a AllowedMentions>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n attachments: Option<Vec<PartialAttachment<'a>>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n components: Option<&'a [Component]>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n content: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n embeds: Option<&'a [Embed]>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n payload_json: Option<&'a [u8]>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n tts: Option<bool>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n flags: Option<MessageFlags>,\n\n}\n\n\n\n/// Create a followup message to an interaction, by its token.\n", "file_path": "http/src/request/application/interaction/create_followup.rs", "rank": 21, "score": 125275.8465364129 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateMessageFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n allowed_mentions: Option<Nullable<&'a AllowedMentions>>,\n\n /// List of attachments to keep, and new attachments to add.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n attachments: Option<Nullable<Vec<PartialAttachment<'a>>>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n components: Option<Nullable<&'a [Component]>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n content: Option<Nullable<&'a str>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n embeds: Option<Nullable<&'a [Embed]>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n flags: Option<MessageFlags>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n payload_json: Option<&'a [u8]>,\n\n}\n\n\n\n/// Update a message by [`Id<ChannelMarker>`] and [`Id<MessageMarker>`].\n\n///\n", "file_path": "http/src/request/channel/message/update_message.rs", "rank": 22, "score": 125275.8465364129 }, { "content": "struct CreateBanFields<'a> {\n\n delete_message_days: Option<u16>,\n\n reason: Option<&'a str>,\n\n}\n\n\n\n/// Bans a user from a guild, optionally with the number of days' worth of\n\n/// messages to delete and the reason.\n\n///\n\n/// # Examples\n\n///\n\n/// Ban user `200` from guild `100`, deleting\n\n/// 1 day's worth of messages, for the reason `\"memes\"`:\n\n///\n\n/// ```no_run\n\n/// use twilight_http::{request::AuditLogReason, Client};\n\n/// use twilight_model::id::Id;\n\n///\n\n/// # #[tokio::main]\n\n/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n/// let client = Client::new(\"my token\".to_owned());\n", "file_path": "http/src/request/guild/ban/create_ban.rs", "rank": 23, "score": 125275.8465364129 }, { "content": "#[derive(Serialize)]\n\nstruct CreateEmojiFields<'a> {\n\n #[serde(serialize_with = \"request::serialize_image\")]\n\n image: &'a [u8],\n\n name: &'a str,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n roles: Option<&'a [Id<RoleMarker>]>,\n\n}\n\n\n\n/// Create an emoji in a guild.\n\n///\n\n/// The emoji must be a Data URI, in the form of\n\n/// `data:image/{type};base64,{data}` where `{type}` is the image MIME type and\n\n/// `{data}` is the base64-encoded image. See [Discord Docs/Image Data].\n\n///\n\n/// [Discord Docs/Image Data]: https://discord.com/developers/docs/reference#image-data\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct CreateEmoji<'a> {\n\n fields: CreateEmojiFields<'a>,\n\n guild_id: Id<GuildMarker>,\n\n http: &'a Client,\n", "file_path": "http/src/request/guild/emoji/create_emoji.rs", "rank": 24, "score": 125275.8465364129 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateEmojiFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n name: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n roles: Option<&'a [Id<RoleMarker>]>,\n\n}\n\n\n\n/// Update an emoji in a guild, by id.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct UpdateEmoji<'a> {\n\n emoji_id: Id<EmojiMarker>,\n\n fields: UpdateEmojiFields<'a>,\n\n guild_id: Id<GuildMarker>,\n\n http: &'a Client,\n\n reason: Option<&'a str>,\n\n}\n\n\n\nimpl<'a> UpdateEmoji<'a> {\n\n pub(crate) const fn new(\n\n http: &'a Client,\n", "file_path": "http/src/request/guild/emoji/update_emoji.rs", "rank": 25, "score": 125275.8465364129 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateThreadFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n archived: Option<bool>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n auto_archive_duration: Option<AutoArchiveDuration>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n invitable: Option<bool>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n locked: Option<bool>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n name: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n rate_limit_per_user: Option<u16>,\n\n}\n\n\n\n/// Update a thread.\n\n///\n\n/// All fields are optional. The minimum length of the name is 1 UTF-16\n\n/// characters and the maximum is 100 UTF-16 characters.\n\n#[must_use = \"requests must be configured and executed\"]\n", "file_path": "http/src/request/channel/thread/update_thread.rs", "rank": 26, "score": 125275.8465364129 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateRoleFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n color: Option<Nullable<u32>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n hoist: Option<bool>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n icon: Option<&'a [u8]>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n mentionable: Option<bool>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n name: Option<Nullable<&'a str>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n permissions: Option<Permissions>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n unicode_emoji: Option<&'a str>,\n\n}\n\n\n\n/// Update a role by guild id and its id.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct UpdateRole<'a> {\n", "file_path": "http/src/request/guild/role/update_role.rs", "rank": 27, "score": 125275.8465364129 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateFollowupFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n allowed_mentions: Option<Nullable<&'a AllowedMentions>>,\n\n /// List of attachments to keep, and new attachments to add.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n attachments: Option<Nullable<Vec<PartialAttachment<'a>>>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n components: Option<Nullable<&'a [Component]>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n content: Option<Nullable<&'a str>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n embeds: Option<Nullable<&'a [Embed]>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n payload_json: Option<&'a [u8]>,\n\n}\n\n\n\n/// Edit a followup message of an interaction, by its token and the message ID.\n\n///\n\n/// You can pass [`None`] to any of the methods to remove the associated field.\n\n/// Pass [`None`] to [`content`] to remove the content. You must ensure that the\n", "file_path": "http/src/request/application/interaction/update_followup.rs", "rank": 28, "score": 125275.8465364129 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateWebhookFields<'a> {\n\n #[serde(\n\n serialize_with = \"request::serialize_optional_nullable_image\",\n\n skip_serializing_if = \"Option::is_none\"\n\n )]\n\n avatar: Option<Nullable<&'a [u8]>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n channel_id: Option<Id<ChannelMarker>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n name: Option<Nullable<&'a str>>,\n\n}\n\n\n\n/// Update a webhook by ID.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct UpdateWebhook<'a> {\n\n fields: UpdateWebhookFields<'a>,\n\n http: &'a Client,\n\n webhook_id: Id<WebhookMarker>,\n\n reason: Option<&'a str>,\n\n}\n", "file_path": "http/src/request/channel/webhook/update_webhook.rs", "rank": 29, "score": 125275.8465364129 }, { "content": "#[derive(Serialize)]\n\nstruct CreateThreadFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n auto_archive_duration: Option<AutoArchiveDuration>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n invitable: Option<bool>,\n\n #[serde(rename = \"type\")]\n\n kind: ChannelType,\n\n name: &'a str,\n\n}\n\n\n\n/// Start a thread that is not connected to a message.\n\n///\n\n/// To make a [`GuildPrivateThread`], the guild must also have the\n\n/// `PRIVATE_THREADS` feature.\n\n///\n\n/// [`GuildPrivateThread`]: twilight_model::channel::ChannelType::GuildPrivateThread\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct CreateThread<'a> {\n\n channel_id: Id<ChannelMarker>,\n\n fields: CreateThreadFields<'a>,\n", "file_path": "http/src/request/channel/thread/create_thread.rs", "rank": 30, "score": 125275.8465364129 }, { "content": "struct GetWebhookFields<'a> {\n\n token: Option<&'a str>,\n\n}\n\n\n\n/// Get a webhook by ID.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct GetWebhook<'a> {\n\n fields: GetWebhookFields<'a>,\n\n http: &'a Client,\n\n id: Id<WebhookMarker>,\n\n}\n\n\n\nimpl<'a> GetWebhook<'a> {\n\n pub(crate) const fn new(http: &'a Client, id: Id<WebhookMarker>) -> Self {\n\n Self {\n\n fields: GetWebhookFields { token: None },\n\n http,\n\n id,\n\n }\n\n }\n", "file_path": "http/src/request/channel/webhook/get_webhook.rs", "rank": 31, "score": 125275.8465364129 }, { "content": "#[derive(Serialize)]\n\nstruct CreateGuildFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n afk_channel_id: Option<Id<ChannelMarker>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n afk_timeout: Option<u64>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n channels: Option<Vec<GuildChannelFields>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n default_message_notifications: Option<DefaultMessageNotificationLevel>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n explicit_content_filter: Option<ExplicitContentFilter>,\n\n #[serde(\n\n serialize_with = \"crate::request::serialize_optional_image\",\n\n skip_serializing_if = \"Option::is_none\"\n\n )]\n\n icon: Option<&'a [u8]>,\n\n name: String,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n roles: Option<Vec<RoleFields>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n", "file_path": "http/src/request/guild/create_guild/mod.rs", "rank": 32, "score": 125275.8465364129 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateResponseFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n allowed_mentions: Option<Nullable<&'a AllowedMentions>>,\n\n /// List of attachments to keep, and new attachments to add.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n attachments: Option<Nullable<Vec<PartialAttachment<'a>>>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n components: Option<Nullable<&'a [Component]>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n content: Option<Nullable<&'a str>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n embeds: Option<Nullable<&'a [Embed]>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n payload_json: Option<&'a [u8]>,\n\n}\n\n\n\n/// Edit the original message, by its token.\n\n///\n\n/// You can pass [`None`] to any of the methods to remove the associated field.\n\n/// Pass [`None`] to [`content`] to remove the content. You must ensure that the\n", "file_path": "http/src/request/application/interaction/update_response.rs", "rank": 33, "score": 125275.8465364129 }, { "content": "struct DeleteWebhookParams<'a> {\n\n token: Option<&'a str>,\n\n}\n\n\n\n/// Delete a webhook by its ID.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct DeleteWebhook<'a> {\n\n fields: DeleteWebhookParams<'a>,\n\n http: &'a Client,\n\n id: Id<WebhookMarker>,\n\n reason: Option<&'a str>,\n\n}\n\n\n\nimpl<'a> DeleteWebhook<'a> {\n\n pub(crate) const fn new(http: &'a Client, id: Id<WebhookMarker>) -> Self {\n\n Self {\n\n fields: DeleteWebhookParams { token: None },\n\n http,\n\n id,\n\n reason: None,\n", "file_path": "http/src/request/channel/webhook/delete_webhook.rs", "rank": 34, "score": 125275.8465364129 }, { "content": "#[derive(Serialize)]\n\nstruct CreateWebhookFields<'a> {\n\n #[serde(\n\n serialize_with = \"request::serialize_optional_image\",\n\n skip_serializing_if = \"Option::is_none\"\n\n )]\n\n avatar: Option<&'a [u8]>,\n\n name: &'a str,\n\n}\n\n\n\n/// Create a webhook in a channel.\n\n///\n\n/// # Examples\n\n///\n\n/// ```no_run\n\n/// use twilight_http::Client;\n\n/// use twilight_model::id::Id;\n\n///\n\n/// # #[tokio::main]\n\n/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n/// let client = Client::new(\"my token\".to_owned());\n", "file_path": "http/src/request/channel/webhook/create_webhook.rs", "rank": 35, "score": 125275.8465364129 }, { "content": "#[derive(Serialize)]\n\nstruct CreateRoleFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n color: Option<u32>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n hoist: Option<bool>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n icon: Option<&'a [u8]>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n mentionable: Option<bool>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n name: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n permissions: Option<Permissions>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n unicode_emoji: Option<&'a str>,\n\n}\n\n\n\n/// Create a role in a guild.\n\n///\n\n/// # Examples\n", "file_path": "http/src/request/guild/role/create_role.rs", "rank": 36, "score": 125275.8465364129 }, { "content": "#[derive(Serialize)]\n\nstruct Nullable<T>(Option<T>);\n\n\n", "file_path": "http/src/request/mod.rs", "rank": 37, "score": 124868.80331215056 }, { "content": "struct GetGuildMembersFields {\n\n after: Option<Id<UserMarker>>,\n\n limit: Option<u16>,\n\n presences: Option<bool>,\n\n}\n\n\n\n/// Get the members of a guild, by id.\n\n///\n\n/// The upper limit to this request is 1000. If more than 1000 members are needed, the requests\n\n/// must be chained. Discord defaults the limit to 1.\n\n///\n\n/// # Examples\n\n///\n\n/// Get the first 500 members of guild `100` after user ID `3000`:\n\n///\n\n/// ```no_run\n\n/// use twilight_http::Client;\n\n/// use twilight_model::id::Id;\n\n///\n\n/// # #[tokio::main]\n", "file_path": "http/src/request/guild/member/get_guild_members.rs", "rank": 38, "score": 124414.72081211412 }, { "content": "struct GetChannelMessagesFields {\n\n limit: Option<u16>,\n\n}\n\n\n\n/// Get channel messages, by [`Id<ChannelMarker>`].\n\n///\n\n/// Only one of [`after`], [`around`], and [`before`] can be specified at a time.\n\n/// Once these are specified, the type returned is [`GetChannelMessagesConfigured`].\n\n///\n\n/// If [`limit`] is unspecified, the default set by Discord is 50.\n\n///\n\n/// # Examples\n\n///\n\n/// ```no_run\n\n/// use twilight_http::Client;\n\n/// use twilight_model::id::Id;\n\n///\n\n/// # #[tokio::main]\n\n/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n/// let client = Client::new(\"my token\".to_owned());\n", "file_path": "http/src/request/channel/message/get_channel_messages.rs", "rank": 39, "score": 124414.72081211412 }, { "content": "struct CreateGuildPruneFields<'a> {\n\n compute_prune_count: Option<bool>,\n\n days: Option<u16>,\n\n include_roles: &'a [Id<RoleMarker>],\n\n}\n\n\n\n/// Begin a guild prune.\n\n///\n\n/// See [Discord Docs/Begin Guild Prune].\n\n///\n\n/// [Discord Docs/Begin Guild Prune]: https://discord.com/developers/docs/resources/guild#begin-guild-prune\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct CreateGuildPrune<'a> {\n\n fields: CreateGuildPruneFields<'a>,\n\n guild_id: Id<GuildMarker>,\n\n http: &'a Client,\n\n reason: Option<&'a str>,\n\n}\n\n\n\nimpl<'a> CreateGuildPrune<'a> {\n", "file_path": "http/src/request/guild/create_guild_prune.rs", "rank": 40, "score": 123229.74057089354 }, { "content": "#[derive(Serialize)]\n\nstruct CreateGuildChannelFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n bitrate: Option<u32>,\n\n #[serde(rename = \"type\", skip_serializing_if = \"Option::is_none\")]\n\n kind: Option<ChannelType>,\n\n name: &'a str,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n nsfw: Option<bool>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n parent_id: Option<Id<ChannelMarker>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n permission_overwrites: Option<&'a [PermissionOverwrite]>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n position: Option<u64>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n rate_limit_per_user: Option<u16>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n topic: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n user_limit: Option<u16>,\n", "file_path": "http/src/request/guild/create_guild_channel.rs", "rank": 41, "score": 123229.74057089354 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateCurrentMemberFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n nick: Option<&'a str>,\n\n}\n\n\n\n/// Update the user's member in a guild.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct UpdateCurrentMember<'a> {\n\n fields: UpdateCurrentMemberFields<'a>,\n\n guild_id: Id<GuildMarker>,\n\n http: &'a Client,\n\n reason: Option<&'a str>,\n\n}\n\n\n\nimpl<'a> UpdateCurrentMember<'a> {\n\n pub(crate) const fn new(http: &'a Client, guild_id: Id<GuildMarker>) -> Self {\n\n Self {\n\n fields: UpdateCurrentMemberFields { nick: None },\n\n guild_id,\n\n http,\n", "file_path": "http/src/request/guild/update_current_member.rs", "rank": 42, "score": 123229.74057089354 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateCurrentUserFields<'a> {\n\n #[serde(\n\n serialize_with = \"request::serialize_optional_nullable_image\",\n\n skip_serializing_if = \"Option::is_none\"\n\n )]\n\n avatar: Option<Nullable<&'a [u8]>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n username: Option<&'a str>,\n\n}\n\n\n\n/// Update the current user.\n\n///\n\n/// All parameters are optional. If the username is changed, it may cause the discriminator to be\n\n/// randomized.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct UpdateCurrentUser<'a> {\n\n fields: UpdateCurrentUserFields<'a>,\n\n http: &'a Client,\n\n reason: Option<&'a str>,\n\n}\n", "file_path": "http/src/request/user/update_current_user.rs", "rank": 43, "score": 123229.74057089354 }, { "content": "#[derive(Serialize)]\n\nstruct CreateGuildFromTemplateFields<'a> {\n\n name: &'a str,\n\n #[serde(serialize_with = \"crate::request::serialize_optional_image\")]\n\n icon: Option<&'a [u8]>,\n\n}\n\n\n\n/// Create a new guild based on a template.\n\n///\n\n/// This endpoint can only be used by bots in less than 10 guilds.\n\n///\n\n/// # Errors\n\n///\n\n/// Returns an error of type [`GuildName`] if the name length is too short or\n\n/// too long.\n\n///\n\n/// [`GuildName`]: twilight_validate::request::ValidationErrorType::GuildName\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct CreateGuildFromTemplate<'a> {\n\n fields: CreateGuildFromTemplateFields<'a>,\n\n http: &'a Client,\n", "file_path": "http/src/request/template/create_guild_from_template.rs", "rank": 44, "score": 123229.74057089354 }, { "content": "struct GetCurrentUserGuildsFields {\n\n after: Option<Id<GuildMarker>>,\n\n before: Option<Id<GuildMarker>>,\n\n limit: Option<u16>,\n\n}\n\n\n\n/// Returns a list of guilds for the current user.\n\n///\n\n/// # Examples\n\n///\n\n/// Get the first 25 guilds with an ID after `300` and before\n\n/// `400`:\n\n///\n\n/// ```no_run\n\n/// use twilight_http::Client;\n\n/// use twilight_model::id::Id;\n\n///\n\n/// # #[tokio::main]\n\n/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n/// let client = Client::new(\"my token\".to_owned());\n", "file_path": "http/src/request/user/get_current_user_guilds.rs", "rank": 45, "score": 122535.17143049189 }, { "content": "#[derive(Serialize)]\n\nstruct CreateThreadFromMessageFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n auto_archive_duration: Option<AutoArchiveDuration>,\n\n name: &'a str,\n\n}\n\n\n\n/// Create a new thread from an existing message.\n\n///\n\n/// When called on a [`GuildText`] channel, this creates a\n\n/// [`GuildPublicThread`].\n\n///\n\n/// When called on a [`GuildNews`] channel, this creates a [`GuildNewsThread`].\n\n///\n\n/// To use auto archive durations of [`ThreeDays`] or [`Week`], the guild must\n\n/// be boosted.\n\n///\n\n/// The thread's ID will be the same as its parent message. This ensures only\n\n/// one thread can be created per message.\n\n///\n\n/// [`GuildNewsThread`]: twilight_model::channel::ChannelType::GuildNewsThread\n", "file_path": "http/src/request/channel/thread/create_thread_from_message.rs", "rank": 46, "score": 121269.56377304047 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateGuildStickerFields<'a> {\n\n description: Option<&'a str>,\n\n name: Option<&'a str>,\n\n tags: Option<&'a str>,\n\n}\n\n\n\n/// Updates a sticker in a guild, and returns the updated sticker.\n\n///\n\n/// # Examples\n\n///\n\n/// ```no_run\n\n/// use twilight_http::Client;\n\n/// use twilight_model::id::Id;\n\n///\n\n/// # #[tokio::main]\n\n/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n/// let client = Client::new(\"my token\".to_owned());\n\n///\n\n/// let guild_id = Id::new(1);\n\n/// let sticker_id = Id::new(2);\n", "file_path": "http/src/request/guild/sticker/update_guild_sticker.rs", "rank": 47, "score": 121269.56377304047 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateWebhookWithTokenFields<'a> {\n\n #[serde(\n\n serialize_with = \"crate::request::serialize_optional_nullable_image\",\n\n skip_serializing_if = \"Option::is_none\"\n\n )]\n\n avatar: Option<Nullable<&'a [u8]>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n name: Option<Nullable<&'a str>>,\n\n}\n\n\n\n/// Update a webhook, with a token, by ID.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct UpdateWebhookWithToken<'a> {\n\n fields: UpdateWebhookWithTokenFields<'a>,\n\n http: &'a Client,\n\n token: &'a str,\n\n webhook_id: Id<WebhookMarker>,\n\n}\n\n\n\nimpl<'a> UpdateWebhookWithToken<'a> {\n", "file_path": "http/src/request/channel/webhook/update_webhook_with_token.rs", "rank": 48, "score": 121269.56377304047 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateStageInstanceFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n privacy_level: Option<PrivacyLevel>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n topic: Option<&'a str>,\n\n}\n\n\n\n/// Update fields of an existing stage instance.\n\n///\n\n/// Requires the user to be a moderator of the stage channel.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct UpdateStageInstance<'a> {\n\n channel_id: Id<ChannelMarker>,\n\n fields: UpdateStageInstanceFields<'a>,\n\n http: &'a Client,\n\n}\n\n\n\nimpl<'a> UpdateStageInstance<'a> {\n\n pub(crate) const fn new(http: &'a Client, channel_id: Id<ChannelMarker>) -> Self {\n\n Self {\n", "file_path": "http/src/request/channel/stage/update_stage_instance.rs", "rank": 49, "score": 121269.56377304047 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateWebhookMessageFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n allowed_mentions: Option<Nullable<&'a AllowedMentions>>,\n\n /// List of attachments to keep, and new attachments to add.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n attachments: Option<Nullable<Vec<PartialAttachment<'a>>>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n components: Option<Nullable<&'a [Component]>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n content: Option<Nullable<&'a str>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n embeds: Option<Nullable<&'a [Embed]>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n payload_json: Option<&'a [u8]>,\n\n}\n\n\n\n/// Update a message created by a webhook.\n\n///\n\n/// You can pass [`None`] to any of the methods to remove the associated field.\n\n/// Pass [`None`] to [`content`] to remove the content. You must ensure that the\n", "file_path": "http/src/request/channel/webhook/update_webhook_message.rs", "rank": 50, "score": 121269.56377304047 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateGuildCommandFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n description: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n name: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n options: Option<&'a [CommandOption]>,\n\n}\n\n\n\n/// Edit a command in a guild, by ID.\n\n///\n\n/// You must specify a name and description. See\n\n/// [Discord Docs/Edit Guild Application Command].\n\n///\n\n/// [Discord Docs/Edit Guild Application Command]: https://discord.com/developers/docs/interactions/application-commands#edit-guild-application-command\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct UpdateGuildCommand<'a> {\n\n fields: UpdateGuildCommandFields<'a>,\n\n application_id: Id<ApplicationMarker>,\n\n command_id: Id<CommandMarker>,\n", "file_path": "http/src/request/application/command/update_guild_command.rs", "rank": 51, "score": 121269.56377304047 }, { "content": "#[derive(Serialize)]\n\nstruct CreateStageInstanceFields<'a> {\n\n channel_id: Id<ChannelMarker>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n privacy_level: Option<PrivacyLevel>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n send_start_notification: Option<bool>,\n\n topic: &'a str,\n\n}\n\n\n\n/// Create a new stage instance associated with a stage channel.\n\n///\n\n/// Requires the user to be a moderator of the stage channel.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct CreateStageInstance<'a> {\n\n fields: CreateStageInstanceFields<'a>,\n\n http: &'a Client,\n\n}\n\n\n\nimpl<'a> CreateStageInstance<'a> {\n\n pub(crate) fn new(\n", "file_path": "http/src/request/channel/stage/create_stage_instance.rs", "rank": 52, "score": 121269.56377304047 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateCommandPermissionsFields<'a> {\n\n pub permissions: &'a [CommandPermissions],\n\n}\n\n\n\n/// Update command permissions for a single command in a guild.\n\n///\n\n/// # Note:\n\n///\n\n/// This overwrites the command permissions so the full set of permissions\n\n/// have to be sent every time.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct UpdateCommandPermissions<'a> {\n\n application_id: Id<ApplicationMarker>,\n\n command_id: Id<CommandMarker>,\n\n guild_id: Id<GuildMarker>,\n\n fields: UpdateCommandPermissionsFields<'a>,\n\n http: &'a Client,\n\n}\n\n\n\nimpl<'a> UpdateCommandPermissions<'a> {\n", "file_path": "http/src/request/application/command/update_command_permissions.rs", "rank": 53, "score": 121269.56377304047 }, { "content": "#[derive(Serialize)]\n\nstruct AddGuildMemberFields<'a> {\n\n pub access_token: &'a str,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub deaf: Option<bool>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub mute: Option<bool>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub nick: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub roles: Option<&'a [Id<RoleMarker>]>,\n\n}\n\n\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct AddGuildMember<'a> {\n\n fields: AddGuildMemberFields<'a>,\n\n guild_id: Id<GuildMarker>,\n\n http: &'a Client,\n\n user_id: Id<UserMarker>,\n\n}\n\n\n", "file_path": "http/src/request/guild/member/add_guild_member.rs", "rank": 54, "score": 121269.56377304047 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateGlobalCommandFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n description: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n name: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n options: Option<&'a [CommandOption]>,\n\n}\n\n\n\n/// Edit a global command, by ID.\n\n///\n\n/// You must specify a name and description. See\n\n/// [Discord Docs/Edit Global Application Command].\n\n///\n\n/// [Discord Docs/Edit Global Application Command]: https://discord.com/developers/docs/interactions/application-commands#edit-global-application-command\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct UpdateGlobalCommand<'a> {\n\n fields: UpdateGlobalCommandFields<'a>,\n\n command_id: Id<CommandMarker>,\n\n application_id: Id<ApplicationMarker>,\n", "file_path": "http/src/request/application/command/update_global_command.rs", "rank": 55, "score": 121269.56377304047 }, { "content": "struct SearchGuildMembersFields<'a> {\n\n query: &'a str,\n\n limit: Option<u16>,\n\n}\n\n\n\n/// Search the members of a specific guild by a query.\n\n///\n\n/// The upper limit to this request is 1000. Discord defaults the limit to 1.\n\n///\n\n/// # Examples\n\n///\n\n/// Get the first 10 members of guild `100` matching `Wumpus`:\n\n///\n\n/// ```no_run\n\n/// use twilight_http::Client;\n\n/// use twilight_model::id::Id;\n\n///\n\n/// # #[tokio::main]\n\n/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n/// let client = Client::new(\"my token\".to_owned());\n", "file_path": "http/src/request/guild/member/search_guild_members.rs", "rank": 56, "score": 121269.56377304047 }, { "content": "struct CreateGuildStickerFields<'a> {\n\n description: &'a str,\n\n file: &'a [u8],\n\n name: &'a str,\n\n tags: &'a str,\n\n}\n\n\n\n/// Creates a sticker in a guild, and returns the created sticker.\n\n///\n\n/// # Examples\n\n///\n\n/// ```no_run\n\n/// use twilight_http::Client;\n\n/// use twilight_model::id::Id;\n\n///\n\n/// # #[tokio::main]\n\n/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n/// let client = Client::new(\"my token\".to_owned());\n\n///\n\n/// let guild_id = Id::new(1);\n", "file_path": "http/src/request/guild/sticker/create_guild_sticker.rs", "rank": 57, "score": 121269.56377304047 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateGuildMemberFields<'a> {\n\n #[allow(clippy::option_option)]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n channel_id: Option<Nullable<Id<ChannelMarker>>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n communication_disabled_until: Option<Nullable<Timestamp>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n deaf: Option<bool>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n mute: Option<bool>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n nick: Option<Nullable<&'a str>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n roles: Option<&'a [Id<RoleMarker>]>,\n\n}\n\n\n\n/// Update a guild member.\n\n///\n\n/// All fields are optional. See [Discord Docs/Modify Guild Member].\n\n///\n", "file_path": "http/src/request/guild/member/update_guild_member.rs", "rank": 58, "score": 121269.56377304047 }, { "content": "struct GetChannelMessagesConfiguredFields {\n\n limit: Option<u16>,\n\n}\n\n\n\n/// This struct is returned when one of `after`, `around`, or `before` is specified in\n\n/// [`GetChannelMessages`].\n\n///\n\n/// [`GetChannelMessages`]: super::GetChannelMessages\n\n// nb: after, around, and before are mutually exclusive, so we use this\n\n// \"configured\" request to utilize the type system to prevent these from being\n\n// set in combination.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct GetChannelMessagesConfigured<'a> {\n\n after: Option<Id<MessageMarker>>,\n\n around: Option<Id<MessageMarker>>,\n\n before: Option<Id<MessageMarker>>,\n\n channel_id: Id<ChannelMarker>,\n\n fields: GetChannelMessagesConfiguredFields,\n\n http: &'a Client,\n\n}\n", "file_path": "http/src/request/channel/message/get_channel_messages_configured.rs", "rank": 59, "score": 120731.37507537314 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateUserVoiceStateFields {\n\n channel_id: Id<ChannelMarker>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n suppress: Option<bool>,\n\n}\n\n\n\n/// Update another user's voice state.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct UpdateUserVoiceState<'a> {\n\n fields: UpdateUserVoiceStateFields,\n\n guild_id: Id<GuildMarker>,\n\n http: &'a Client,\n\n user_id: Id<UserMarker>,\n\n}\n\n\n\nimpl<'a> UpdateUserVoiceState<'a> {\n\n pub(crate) const fn new(\n\n http: &'a Client,\n\n guild_id: Id<GuildMarker>,\n\n user_id: Id<UserMarker>,\n", "file_path": "http/src/request/guild/user/update_user_voice_state.rs", "rank": 60, "score": 120731.37507537314 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateGuildWelcomeScreenFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n description: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n enabled: Option<bool>,\n\n #[serde(skip_serializing_if = \"<[_]>::is_empty\")]\n\n welcome_channels: &'a [WelcomeScreenChannel],\n\n}\n\n\n\n/// Update the guild's welcome screen.\n\n///\n\n/// Requires the [`MANAGE_GUILD`] permission.\n\n///\n\n/// [`MANAGE_GUILD`]: twilight_model::guild::Permissions::MANAGE_GUILD\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct UpdateGuildWelcomeScreen<'a> {\n\n fields: UpdateGuildWelcomeScreenFields<'a>,\n\n guild_id: Id<GuildMarker>,\n\n http: &'a Client,\n\n}\n", "file_path": "http/src/request/guild/update_guild_welcome_screen.rs", "rank": 61, "score": 119390.01439141824 }, { "content": "struct GetGuildPruneCountFields<'a> {\n\n days: Option<u16>,\n\n include_roles: &'a [Id<RoleMarker>],\n\n}\n\n\n\n/// Get the counts of guild members to be pruned.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct GetGuildPruneCount<'a> {\n\n fields: GetGuildPruneCountFields<'a>,\n\n guild_id: Id<GuildMarker>,\n\n http: &'a Client,\n\n}\n\n\n\nimpl<'a> GetGuildPruneCount<'a> {\n\n pub(crate) const fn new(http: &'a Client, guild_id: Id<GuildMarker>) -> Self {\n\n Self {\n\n fields: GetGuildPruneCountFields {\n\n days: None,\n\n include_roles: &[],\n\n },\n", "file_path": "http/src/request/guild/get_guild_prune_count.rs", "rank": 62, "score": 119390.01439141824 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateGuildScheduledEventFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n channel_id: Option<Nullable<Id<ChannelMarker>>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n description: Option<Nullable<&'a str>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n entity_metadata: Option<EntityMetadataFields<'a>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n entity_type: Option<EntityType>,\n\n #[serde(\n\n serialize_with = \"crate::request::serialize_optional_nullable_image\",\n\n skip_serializing_if = \"Option::is_none\"\n\n )]\n\n image: Option<Nullable<&'a [u8]>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n name: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n privacy_level: Option<PrivacyLevel>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n scheduled_end_time: Option<Nullable<&'a Timestamp>>,\n", "file_path": "http/src/request/scheduled_event/update_guild_scheduled_event.rs", "rank": 63, "score": 117586.2180362995 }, { "content": "#[derive(Serialize)]\n\nstruct CreateGuildScheduledEventFields<'a> {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n channel_id: Option<Id<ChannelMarker>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n description: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n entity_metadata: Option<EntityMetadataFields<'a>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n entity_type: Option<EntityType>,\n\n #[serde(\n\n serialize_with = \"crate::request::serialize_optional_image\",\n\n skip_serializing_if = \"Option::is_none\"\n\n )]\n\n image: Option<&'a [u8]>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n name: Option<&'a str>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n privacy_level: Option<PrivacyLevel>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n scheduled_end_time: Option<&'a Timestamp>,\n", "file_path": "http/src/request/scheduled_event/create_guild_scheduled_event/mod.rs", "rank": 64, "score": 115853.68546950308 }, { "content": "#[derive(Serialize)]\n\nstruct UpdateCurrentUserVoiceStateFields<'a> {\n\n channel_id: Id<ChannelMarker>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n suppress: Option<bool>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n request_to_speak_timestamp: Option<Nullable<&'a str>>,\n\n}\n\n\n\n/// Update the current user's voice state.\n\n#[must_use = \"requests must be configured and executed\"]\n\npub struct UpdateCurrentUserVoiceState<'a> {\n\n fields: UpdateCurrentUserVoiceStateFields<'a>,\n\n guild_id: Id<GuildMarker>,\n\n http: &'a Client,\n\n}\n\n\n\nimpl<'a> UpdateCurrentUserVoiceState<'a> {\n\n pub(crate) const fn new(\n\n http: &'a Client,\n\n guild_id: Id<GuildMarker>,\n", "file_path": "http/src/request/guild/user/update_current_user_voice_state.rs", "rank": 65, "score": 114188.27530019628 }, { "content": "/// Extend the buffer with the digits of the integer `id`.\n\n///\n\n/// The reason for this is to get around a allocation by for example using\n\n/// `format!(\"files[{id}]\")`.\n\nfn push_digits(mut id: u64, buf: &mut Vec<u8>) {\n\n // The largest 64 bit integer is 20 digits.\n\n let mut inner_buf = [0_u8; 20];\n\n // Amount of digits written to the inner buffer.\n\n let mut i = 0;\n\n\n\n // While the number have more than one digit we print the last digit by\n\n // taking the rest after modulo 10. We then divide with 10 to truncate the\n\n // number from the right and then loop\n\n while id >= 10 {\n\n // To go from the integer to the ascii value we add the ascii value of\n\n // '0'.\n\n //\n\n // (id % 10) will always be less than 10 so truncation cannot happen.\n\n #[allow(clippy::cast_possible_truncation)]\n\n let ascii = (id % 10) as u8 + ASCII_NUMBER;\n\n inner_buf[i] = ascii;\n\n id /= 10;\n\n i += 1;\n\n }\n", "file_path": "http/src/request/attachment.rs", "rank": 66, "score": 109591.50432110857 }, { "content": "pub fn member(id: Id<UserMarker>, guild_id: Id<GuildMarker>) -> Member {\n\n let joined_at = Timestamp::from_secs(1_632_072_645).expect(\"non zero\");\n\n\n\n Member {\n\n avatar: None,\n\n communication_disabled_until: None,\n\n deaf: false,\n\n guild_id,\n\n joined_at,\n\n mute: false,\n\n nick: None,\n\n pending: false,\n\n premium_since: None,\n\n roles: Vec::new(),\n\n user: user(id),\n\n }\n\n}\n\n\n", "file_path": "cache/in-memory/src/test.rs", "rank": 67, "score": 102507.4876289999 }, { "content": "pub fn user(id: Id<UserMarker>) -> User {\n\n let banner_hash = b\"16ed037ab6dae5e1739f15c745d12454\";\n\n let banner = ImageHash::parse(banner_hash).expect(\"valid hash\");\n\n\n\n User {\n\n accent_color: None,\n\n avatar: None,\n\n banner: Some(banner),\n\n bot: false,\n\n discriminator: 1,\n\n email: None,\n\n flags: None,\n\n id,\n\n locale: None,\n\n mfa_enabled: None,\n\n name: \"user\".to_owned(),\n\n premium_type: None,\n\n public_flags: None,\n\n system: None,\n\n verified: None,\n\n }\n\n}\n\n\n", "file_path": "cache/in-memory/src/test.rs", "rank": 68, "score": 93544.67148768886 }, { "content": "pub fn role(id: Id<RoleMarker>) -> Role {\n\n Role {\n\n color: 0,\n\n hoist: false,\n\n icon: None,\n\n id,\n\n managed: false,\n\n mentionable: false,\n\n name: \"test\".to_owned(),\n\n permissions: Permissions::empty(),\n\n position: 0,\n\n tags: None,\n\n unicode_emoji: None,\n\n }\n\n}\n\n\n\npub const fn sticker(id: Id<StickerMarker>, guild_id: Id<GuildMarker>) -> Sticker {\n\n Sticker {\n\n available: false,\n\n description: None,\n", "file_path": "cache/in-memory/src/test.rs", "rank": 69, "score": 93544.67148768886 }, { "content": "/// Ensure that an audit reason is correct.\n\n///\n\n/// The length must be at most [`AUDIT_REASON_MAX`]. This is based on\n\n/// [this documentation entry].\n\n///\n\n/// # Errors\n\n///\n\n/// Returns an error of type [`AuditReason`] if the length is invalid.\n\n///\n\n/// [`AuditReason`]: ValidationErrorType::AuditReason\n\n/// [this documentation entry]: https://discord.com/developers/docs/resources/audit-log#audit-log-entry-object-audit-log-entry-structure\n\npub fn audit_reason(audit_reason: impl AsRef<str>) -> Result<(), ValidationError> {\n\n let len = audit_reason.as_ref().chars().count();\n\n\n\n if len <= AUDIT_REASON_MAX {\n\n Ok(())\n\n } else {\n\n Err(ValidationError {\n\n kind: ValidationErrorType::AuditReason { len },\n\n })\n\n }\n\n}\n\n\n\n/// Ensure that the delete message days amount for the Create Guild Ban request\n\n/// is correct.\n\n///\n\n/// The days must be at most [`CREATE_GUILD_BAN_DELETE_MESSAGE_DAYS_MAX`]. This\n\n/// is based on [this documentation entry].\n\n///\n\n/// # Errors\n\n///\n", "file_path": "validate/src/request.rs", "rank": 70, "score": 93250.79674598938 }, { "content": "/// Convert a typed request builder into a raw [`Request`].\n\n///\n\n/// Converting a typed request builder into a raw request may be preferable in\n\n/// order to verify whether a request is valid prior to passing it to\n\n/// [`Client::request`].\n\n///\n\n/// Creating raw requests is useful for unit tests and debugging.\n\n///\n\n/// # Examples\n\n///\n\n/// Convert a [`CreateMessage`] builder into a [`Request`], inspect its body\n\n/// and route, and then send the request:\n\n///\n\n/// ```no_run\n\n/// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n/// use std::{env, str};\n\n/// use twilight_http::{client::Client, request::TryIntoRequest};\n\n/// use twilight_model::{channel::Message, id::Id};\n\n///\n\n/// let client = Client::new(env::var(\"DISCORD_TOKEN\")?);\n\n/// let channel_id = Id::new(1);\n\n/// let builder = client.create_message(channel_id)\n\n/// .content(\"This is a test message!\")?\n\n/// .tts(false);\n\n///\n\n/// let request = builder.try_into_request()?;\n\n///\n\n/// println!(\"{:?} {}\", request.method(), request.path());\n\n///\n\n/// if let Some(body) = request.body() {\n\n/// println!(\"{}\", str::from_utf8(body)?);\n\n/// }\n\n///\n\n/// // Because a raw request is being performed, the output type must be\n\n/// // explicit.\n\n/// let response = client.request::<Message>(request).await?;\n\n/// # Ok(()) }\n\n/// ```\n\n///\n\n/// [`Client::request`]: crate::client::Client::request\n\n/// [`CreateMessage`]: super::channel::message::CreateMessage\n\npub trait TryIntoRequest: private::Sealed {\n\n /// Try to convert a request builder into a raw [`Request`].\n\n ///\n\n /// # Errors\n\n ///\n\n /// Not all typed request builder conversions return an error and may\n\n /// instead always succeed. Refer to the documentation for each\n\n /// implementation for clarification.\n\n ///\n\n /// Requests may return an error type of [`ErrorType::CreatingHeader`] if\n\n /// creating an audit log header value fails.\n\n ///\n\n /// Requests may return an error type of [`ErrorType::Json`] if serializing\n\n /// a request body fails.\n\n ///\n\n /// [`ErrorType::CreatingHeader`]: crate::error::ErrorType::CreatingHeader\n\n /// [`ErrorType::Json`]: crate::error::ErrorType::Json\n\n fn try_into_request(self) -> Result<Request, Error>;\n\n}\n\n\n", "file_path": "http/src/request/try_into_request.rs", "rank": 71, "score": 92807.4513960206 }, { "content": "pub fn guild_channel_text() -> (Id<GuildMarker>, Id<ChannelMarker>, Channel) {\n\n let guild_id = Id::new(1);\n\n let channel_id = Id::new(2);\n\n let channel = Channel {\n\n application_id: None,\n\n bitrate: None,\n\n default_auto_archive_duration: None,\n\n guild_id: Some(guild_id),\n\n icon: None,\n\n id: channel_id,\n\n invitable: None,\n\n kind: ChannelType::GuildText,\n\n last_message_id: None,\n\n last_pin_timestamp: None,\n\n member: None,\n\n member_count: None,\n\n message_count: None,\n\n name: Some(\"test\".to_owned()),\n\n newly_created: None,\n\n nsfw: Some(false),\n", "file_path": "cache/in-memory/src/test.rs", "rank": 72, "score": 88824.99833212743 }, { "content": "struct Connection {\n\n config: NodeConfig,\n\n connection: WebSocketStream<MaybeTlsStream<TcpStream>>,\n\n node_from: UnboundedReceiver<OutgoingEvent>,\n\n node_to: UnboundedSender<IncomingEvent>,\n\n players: PlayerManager,\n\n stats: BiLock<Stats>,\n\n}\n\n\n\nimpl Connection {\n\n async fn connect(\n\n config: NodeConfig,\n\n players: PlayerManager,\n\n stats: BiLock<Stats>,\n\n ) -> Result<\n\n (\n\n Self,\n\n UnboundedSender<OutgoingEvent>,\n\n UnboundedReceiver<IncomingEvent>,\n\n ),\n", "file_path": "lavalink/src/node.rs", "rank": 73, "score": 88709.2718917265 }, { "content": "struct InFlight {\n\n future: Pin<Box<Timeout<HyperResponseFuture>>>,\n\n guild_id: Option<Id<GuildMarker>>,\n\n invalid_token: Option<Arc<AtomicBool>>,\n\n tx: Option<TicketSender>,\n\n}\n\n\n\nimpl InFlight {\n\n fn poll<T>(mut self, cx: &mut Context<'_>) -> InnerPoll<T> {\n\n let resp = match Pin::new(&mut self.future).poll(cx) {\n\n Poll::Ready(Ok(Ok(resp))) => resp,\n\n Poll::Ready(Ok(Err(source))) => {\n\n return InnerPoll::Ready(Err(Error {\n\n kind: ErrorType::RequestError,\n\n source: Some(Box::new(source)),\n\n }))\n\n }\n\n Poll::Ready(Err(source)) => {\n\n return InnerPoll::Ready(Err(Error {\n\n kind: ErrorType::RequestTimedOut,\n", "file_path": "http/src/response/future.rs", "rank": 74, "score": 87338.52322294652 }, { "content": "struct Failed {\n\n source: Error,\n\n}\n\n\n\nimpl Failed {\n\n fn poll<T>(self, _: &mut Context<'_>) -> InnerPoll<T> {\n\n InnerPoll::Ready(Err(self.source))\n\n }\n\n}\n\n\n", "file_path": "http/src/response/future.rs", "rank": 75, "score": 87338.52322294652 }, { "content": "struct Chunking {\n\n future: Pin<Box<dyn Future<Output = Result<Vec<u8>, Error>> + Send + Sync + 'static>>,\n\n status: HyperStatusCode,\n\n}\n\n\n\nimpl Chunking {\n\n fn poll<T>(mut self, cx: &mut Context<'_>) -> InnerPoll<T> {\n\n let bytes = match Pin::new(&mut self.future).poll(cx) {\n\n Poll::Ready(Ok(bytes)) => bytes,\n\n Poll::Ready(Err(source)) => return InnerPoll::Ready(Err(source)),\n\n Poll::Pending => return InnerPoll::Pending(ResponseFutureStage::Chunking(self)),\n\n };\n\n\n\n let error = match crate::json::from_bytes::<ApiError>(&bytes) {\n\n Ok(error) => error,\n\n Err(source) => {\n\n return InnerPoll::Ready(Err(Error {\n\n kind: ErrorType::Parsing { body: bytes },\n\n source: Some(Box::new(source)),\n\n }));\n", "file_path": "http/src/response/future.rs", "rank": 76, "score": 87338.52322294652 }, { "content": "pub fn emoji(id: Id<EmojiMarker>, user: Option<User>) -> Emoji {\n\n Emoji {\n\n animated: false,\n\n available: true,\n\n id,\n\n managed: false,\n\n name: \"test\".to_owned(),\n\n require_colons: true,\n\n roles: Vec::new(),\n\n user,\n\n }\n\n}\n\n\n", "file_path": "cache/in-memory/src/test.rs", "rank": 77, "score": 86916.28920021052 }, { "content": "pub fn guild(id: Id<GuildMarker>, member_count: Option<u64>) -> Guild {\n\n Guild {\n\n afk_channel_id: None,\n\n afk_timeout: 0,\n\n application_id: None,\n\n approximate_member_count: None,\n\n approximate_presence_count: None,\n\n banner: None,\n\n channels: Vec::new(),\n\n default_message_notifications: DefaultMessageNotificationLevel::Mentions,\n\n description: None,\n\n discovery_splash: None,\n\n emojis: Vec::new(),\n\n explicit_content_filter: ExplicitContentFilter::None,\n\n features: Vec::new(),\n\n icon: None,\n\n id,\n\n joined_at: None,\n\n large: false,\n\n max_members: None,\n", "file_path": "cache/in-memory/src/test.rs", "rank": 78, "score": 86151.64439908702 }, { "content": "/// Ensure that the amount of stickers in a message is correct.\n\n///\n\n/// There must be at most [`STICKER_MAX`] stickers. This is based on [this\n\n/// documentation entry].\n\n///\n\n/// # Errors\n\n///\n\n/// Returns an error of type [`StickersInvalid`] if the length is invalid.\n\n///\n\n/// [`StickersInvalid`]: MessageValidationErrorType::StickersInvalid\n\n/// [this documentation entry]: https://discord.com/developers/docs/resources/channel#create-message-jsonform-params\n\npub fn sticker_ids(sticker_ids: &[Id<StickerMarker>]) -> Result<(), MessageValidationError> {\n\n let len = sticker_ids.len();\n\n\n\n if len <= STICKER_MAX {\n\n Ok(())\n\n } else {\n\n Err(MessageValidationError {\n\n kind: MessageValidationErrorType::StickersInvalid { len },\n\n source: None,\n\n })\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn attachment_allowed_filename() {\n\n assert!(attachment_filename(\"one.jpg\").is_ok());\n", "file_path": "validate/src/message.rs", "rank": 79, "score": 86043.10070507429 }, { "content": "#[derive(Debug)]\n\nstruct StateRef {\n\n http: HttpClient,\n\n lavalink: Lavalink,\n\n hyper: HyperClient<HttpConnector>,\n\n shard: Shard,\n\n standby: Standby,\n\n}\n\n\n", "file_path": "examples/lavalink-basic-bot.rs", "rank": 80, "score": 86033.63938454016 }, { "content": "/// Member's roles' permissions and the guild's `@everyone` role's permissions.\n\nstruct MemberRoles {\n\n /// User's roles and their permissions.\n\n assigned: Vec<(Id<RoleMarker>, Permissions)>,\n\n /// Permissions of the guild's `@everyone` role.\n\n everyone: Permissions,\n\n}\n\n\n\n/// Calculate the permissions of a member with information from the cache.\n\n#[derive(Clone, Debug)]\n\n#[must_use = \"has no effect if unused\"]\n\npub struct InMemoryCachePermissions<'a> {\n\n cache: &'a InMemoryCache,\n\n check_member_communication_disabled: bool,\n\n}\n\n\n\nimpl<'a> InMemoryCachePermissions<'a> {\n\n pub(super) const fn new(cache: &'a InMemoryCache) -> Self {\n\n Self {\n\n cache,\n\n check_member_communication_disabled: true,\n", "file_path": "cache/in-memory/src/permission.rs", "rank": 81, "score": 86033.63938454016 }, { "content": "struct PermissionsVisitor;\n\n\n\nimpl<'de> Visitor<'de> for PermissionsVisitor {\n\n type Value = Permissions;\n\n\n\n fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.write_str(\"integer or string permissions\")\n\n }\n\n\n\n fn visit_u64<E: DeError>(self, v: u64) -> Result<Self::Value, E> {\n\n Ok(Permissions::from_bits_truncate(v))\n\n }\n\n\n\n fn visit_str<E: DeError>(self, v: &str) -> Result<Self::Value, E> {\n\n #[allow(clippy::map_err_ignore)]\n\n let num = v\n\n .parse()\n\n .map_err(|_| DeError::custom(\"permissions is not valid bitflags\"))?;\n\n\n\n self.visit_u64(num)\n", "file_path": "model/src/guild/permissions.rs", "rank": 82, "score": 86033.63938454016 }, { "content": "#[derive(Debug, Deserialize, Serialize)]\n\nstruct Hello {\n\n heartbeat_interval: u64,\n\n}\n\n\n\n/// A deserializer that deserializes into a `GatewayEvent` by cloning some bits\n\n/// of scanned information before the actual deserialization.\n\n///\n\n/// This is the owned version of [`GatewayEventDeserializer`].\n\n///\n\n/// You should use this if you're using a mutable deserialization library\n\n/// like `simd-json`.\n\n#[derive(Clone, Debug, Eq, PartialEq)]\n\npub struct GatewayEventDeserializerOwned {\n\n event_type: Option<String>,\n\n op: u8,\n\n sequence: Option<u64>,\n\n}\n\n\n\nimpl GatewayEventDeserializerOwned {\n\n /// Create a new owned gateway event deserializer when you already know the\n", "file_path": "model/src/gateway/event/gateway.rs", "rank": 83, "score": 86033.63938454016 }, { "content": "struct ReactionVisitor;\n\n\n\nimpl<'de> Visitor<'de> for ReactionVisitor {\n\n type Value = Reaction;\n\n\n\n fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.write_str(\"struct Reaction\")\n\n }\n\n\n\n fn visit_map<V: MapAccess<'de>>(self, mut map: V) -> Result<Self::Value, V::Error> {\n\n let mut channel_id = None;\n\n let mut emoji = None;\n\n let mut guild_id = None;\n\n let mut member = None;\n\n let mut message_id = None;\n\n let mut user_id = None;\n\n\n\n let span = tracing::trace_span!(\"deserializing reaction\");\n\n let _span_enter = span.enter();\n\n\n", "file_path": "model/src/channel/reaction.rs", "rank": 84, "score": 86033.63938454016 }, { "content": "struct RatelimitQueue {\n\n guild_id: Option<Id<GuildMarker>>,\n\n invalid_token: Option<Arc<AtomicBool>>,\n\n response_future: HyperResponseFuture,\n\n timeout: Duration,\n\n pre_flight_check: Option<Box<dyn FnOnce() -> bool + Send + 'static>>,\n\n wait_for_sender: WaitForTicketFuture,\n\n}\n\n\n\nimpl RatelimitQueue {\n\n fn poll<T>(mut self, cx: &mut Context<'_>) -> InnerPoll<T> {\n\n let tx = match Pin::new(&mut self.wait_for_sender).poll(cx) {\n\n Poll::Ready(Ok(tx)) => tx,\n\n Poll::Ready(Err(source)) => {\n\n return InnerPoll::Ready(Err(Error {\n\n kind: ErrorType::RatelimiterTicket,\n\n source: Some(source),\n\n }))\n\n }\n\n Poll::Pending => return InnerPoll::Pending(ResponseFutureStage::RatelimitQueue(self)),\n", "file_path": "http/src/response/future.rs", "rank": 85, "score": 86033.63938454016 }, { "content": "#[derive(Debug)]\n\nstruct ProcessError {\n\n kind: ProcessErrorType,\n\n source: Option<Box<dyn Error + Send + Sync>>,\n\n}\n\n\n\nimpl ProcessError {\n\n const fn fatal(&self) -> bool {\n\n matches!(\n\n self.kind,\n\n ProcessErrorType::SendingClose { .. } | ProcessErrorType::SessionSend { .. }\n\n )\n\n }\n\n}\n\n\n\nimpl Display for ProcessError {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n match &self.kind {\n\n ProcessErrorType::EventTypeUnknown { event_type, op } => {\n\n f.write_str(\"provided event type (\")?;\n\n Debug::fmt(event_type, f)?;\n", "file_path": "gateway/src/shard/processor/impl.rs", "rank": 86, "score": 84789.9845201904 }, { "content": "struct InteractionVisitor;\n\n\n\nimpl<'de> Visitor<'de> for InteractionVisitor {\n\n type Value = Interaction;\n\n\n\n fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.write_str(\"enum Interaction\")\n\n }\n\n\n\n #[allow(clippy::too_many_lines)]\n\n fn visit_map<V: MapAccess<'de>>(self, mut map: V) -> Result<Self::Value, V::Error> {\n\n let mut application_id: Option<Id<ApplicationMarker>> = None;\n\n let mut channel_id: Option<Id<ChannelMarker>> = None;\n\n let mut data: Option<Value> = None;\n\n let mut guild_id: Option<Option<Id<GuildMarker>>> = None;\n\n let mut guild_locale: Option<Option<String>> = None;\n\n let mut id: Option<Id<InteractionMarker>> = None;\n\n let mut member: Option<Option<PartialMember>> = None;\n\n let mut message: Option<Message> = None;\n\n let mut token: Option<String> = None;\n", "file_path": "model/src/application/interaction/mod.rs", "rank": 87, "score": 84789.9845201904 }, { "content": "#[derive(Deserialize)]\n\nstruct ReadyMinimal {\n\n d: Ready,\n\n}\n\n\n\n/// Runs in the background and processes incoming events, and then broadcasts\n\n/// to all listeners.\n\n#[derive(Debug)]\n\npub struct ShardProcessor {\n\n pub config: Arc<Config>,\n\n pub emitter: Emitter,\n\n pub rx: UnboundedReceiver<Message>,\n\n pub session: Arc<Session>,\n\n compression: Compression,\n\n url: Box<str>,\n\n resume: Option<(u64, Box<str>)>,\n\n wtx: WatchSender<Arc<Session>>,\n\n}\n\n\n\nimpl ShardProcessor {\n\n pub async fn new(\n", "file_path": "gateway/src/shard/processor/impl.rs", "rank": 88, "score": 84789.9845201904 }, { "content": "struct ComponentVisitor;\n\n\n\nimpl<'de> Visitor<'de> for ComponentVisitor {\n\n type Value = Component;\n\n\n\n fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.write_str(\"struct Component\")\n\n }\n\n\n\n #[allow(clippy::too_many_lines)]\n\n fn visit_map<V: MapAccess<'de>>(self, mut map: V) -> Result<Self::Value, V::Error> {\n\n // Required fields.\n\n let mut components: Option<Vec<Component>> = None;\n\n let mut kind: Option<ComponentType> = None;\n\n let mut options: Option<Vec<SelectMenuOption>> = None;\n\n let mut style: Option<Value> = None;\n\n\n\n // Liminal fields.\n\n let mut custom_id: Option<Option<Value>> = None;\n\n let mut label: Option<Option<String>> = None;\n", "file_path": "model/src/application/component/mod.rs", "rank": 89, "score": 84789.9845201904 }, { "content": "struct OptionVisitor;\n\n\n\nimpl<'de> Visitor<'de> for OptionVisitor {\n\n type Value = CommandOption;\n\n\n\n fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.write_str(\"struct CommandOption\")\n\n }\n\n\n\n #[allow(clippy::too_many_lines)]\n\n fn visit_map<V: MapAccess<'de>>(self, mut map: V) -> Result<Self::Value, V::Error> {\n\n let mut autocomplete: Option<bool> = None;\n\n let mut channel_types: Option<Option<Vec<ChannelType>>> = None;\n\n let mut choices: Option<Option<Vec<CommandOptionChoice>>> = None;\n\n let mut description: Option<String> = None;\n\n let mut description_localizations: Option<Option<HashMap<String, String>>> = None;\n\n let mut kind: Option<CommandOptionType> = None;\n\n let mut max_value: Option<Option<CommandOptionValue>> = None;\n\n let mut min_value: Option<Option<CommandOptionValue>> = None;\n\n let mut name: Option<String> = None;\n", "file_path": "model/src/application/command/option.rs", "rank": 90, "score": 84789.9845201904 }, { "content": "/// Registration for a caller to wait for an event based on a predicate\n\n/// function.\n\nstruct Bystander<T> {\n\n /// Predicate check to perform on an event.\n\n func: Box<dyn Fn(&T) -> bool + Send + Sync>,\n\n /// [`Sender::Future`]s consume themselves once upon sending so the sender\n\n /// needs to be able to be taken out separately.\n\n sender: Option<Sender<T>>,\n\n}\n\n\n\nimpl<T: Debug> Debug for Bystander<T> {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.debug_struct(\"Bystander\")\n\n .field(\"sender\", &self.sender)\n\n .finish()\n\n }\n\n}\n\n\n\n/// The `Standby` struct, used by the main event loop to process events and by\n\n/// tasks to wait for an event.\n\n///\n\n/// Refer to the crate-level documentation for more information.\n", "file_path": "standby/src/lib.rs", "rank": 91, "score": 84193.36618387287 }, { "content": "struct VoiceStateVisitor;\n\n\n\nimpl<'de> Visitor<'de> for VoiceStateVisitor {\n\n type Value = VoiceState;\n\n\n\n fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.write_str(\"struct VoiceState\")\n\n }\n\n\n\n #[allow(clippy::too_many_lines)]\n\n fn visit_map<V: MapAccess<'de>>(self, mut map: V) -> Result<Self::Value, V::Error> {\n\n let mut channel_id = None;\n\n let mut deaf = None;\n\n let mut guild_id = None;\n\n let mut member = None;\n\n let mut mute = None;\n\n let mut self_deaf = None;\n\n let mut self_mute = None;\n\n let mut self_stream = None;\n\n let mut self_video = None;\n", "file_path": "model/src/voice/voice_state.rs", "rank": 92, "score": 83603.34785644361 }, { "content": "#[derive(Deserialize, Serialize)]\n\nstruct CommandPermissionsData {\n\n id: Id<GenericMarker>,\n\n #[serde(rename = \"type\")]\n\n kind: CommandPermissionsDataType,\n\n permission: bool,\n\n}\n\n\n", "file_path": "model/src/application/command/permissions.rs", "rank": 93, "score": 83603.34785644361 }, { "content": "struct ActivityButtonVisitor;\n\n\n\nimpl<'de> Visitor<'de> for ActivityButtonVisitor {\n\n type Value = ActivityButton;\n\n\n\n fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.write_str(\"activity button struct or string\")\n\n }\n\n\n\n fn visit_string<E: DeError>(self, v: String) -> Result<Self::Value, E> {\n\n Ok(ActivityButton::Text(ActivityButtonText { label: v }))\n\n }\n\n\n\n fn visit_str<E: DeError>(self, v: &str) -> Result<Self::Value, E> {\n\n Ok(ActivityButton::Text(ActivityButtonText {\n\n label: v.to_owned(),\n\n }))\n\n }\n\n\n\n fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {\n", "file_path": "model/src/gateway/presence/activity_button.rs", "rank": 94, "score": 82469.89607233217 }, { "content": "struct ActivityButtonTextVisitor;\n\n\n\nimpl<'de> Visitor<'de> for ActivityButtonTextVisitor {\n\n type Value = ActivityButtonText;\n\n\n\n fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.write_str(\"activity button string\")\n\n }\n\n\n\n fn visit_string<E: DeError>(self, v: String) -> Result<Self::Value, E> {\n\n Ok(ActivityButtonText { label: v })\n\n }\n\n\n\n fn visit_str<E: DeError>(self, v: &str) -> Result<Self::Value, E> {\n\n Ok(ActivityButtonText {\n\n label: v.to_owned(),\n\n })\n\n }\n\n}\n\n\n", "file_path": "model/src/gateway/presence/activity_button.rs", "rank": 95, "score": 81386.13193298076 }, { "content": "struct MemberChunkVisitor;\n\n\n\nimpl<'de> Visitor<'de> for MemberChunkVisitor {\n\n type Value = MemberChunk;\n\n\n\n fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.write_str(\"struct MemberChunk\")\n\n }\n\n\n\n #[allow(clippy::too_many_lines)]\n\n fn visit_map<V: MapAccess<'de>>(self, mut map: V) -> Result<Self::Value, V::Error> {\n\n let mut chunk_count = None;\n\n let mut chunk_index = None;\n\n let mut guild_id = None;\n\n let mut members = None;\n\n let mut nonce = None;\n\n let mut not_found = None;\n\n let mut presences = None;\n\n\n\n let span = tracing::trace_span!(\"deserializing member chunk\");\n", "file_path": "model/src/gateway/payload/incoming/member_chunk.rs", "rank": 96, "score": 81386.13193298076 }, { "content": "struct TypingStartVisitor;\n\n\n\nimpl<'de> Visitor<'de> for TypingStartVisitor {\n\n type Value = TypingStart;\n\n\n\n fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.write_str(\"struct TypingStart\")\n\n }\n\n\n\n fn visit_map<V: MapAccess<'de>>(self, mut map: V) -> Result<Self::Value, V::Error> {\n\n let mut channel_id = None;\n\n let mut guild_id = None::<Option<_>>;\n\n let mut member = None::<Member>;\n\n let mut timestamp = None;\n\n let mut user_id = None;\n\n\n\n let span = tracing::trace_span!(\"deserializing typing start\");\n\n let _span_enter = span.enter();\n\n\n\n loop {\n", "file_path": "model/src/gateway/payload/incoming/typing_start.rs", "rank": 97, "score": 81386.13193298076 }, { "content": "fn connect_request(state: &NodeConfig) -> Result<Request<()>, NodeError> {\n\n let mut builder = Request::get(format!(\"ws://{}\", state.address));\n\n builder = builder.header(\"Authorization\", &state.authorization);\n\n builder = builder.header(\"Num-Shards\", state.shard_count);\n\n builder = builder.header(\"Sec-WebSocket-Key\", generate_key());\n\n builder = builder.header(\"User-Id\", state.user_id.get());\n\n\n\n if state.resume.is_some() {\n\n builder = builder.header(\"Resume-Key\", state.address.to_string());\n\n }\n\n\n\n builder.body(()).map_err(|source| NodeError {\n\n kind: NodeErrorType::BuildingConnectionRequest,\n\n source: Some(Box::new(source)),\n\n })\n\n}\n\n\n\nasync fn reconnect(\n\n config: &NodeConfig,\n\n) -> Result<WebSocketStream<MaybeTlsStream<TcpStream>>, NodeError> {\n", "file_path": "lavalink/src/node.rs", "rank": 98, "score": 81381.8110448864 }, { "content": "#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq)]\n\nstruct ThreadMembersUpdateIntermediary {\n\n /// ThreadMembers without the guild ID.\n\n #[serde(default)]\n\n pub added_members: Vec<ThreadMemberIntermediary>,\n\n pub guild_id: Id<GuildMarker>,\n\n pub id: Id<ChannelMarker>,\n\n /// Max value of 50.\n\n pub member_count: u8,\n\n #[serde(default)]\n\n pub removed_member_ids: Vec<Id<UserMarker>>,\n\n}\n\n\n\nimpl ThreadMembersUpdateIntermediary {\n\n fn into_thread_members_update(self) -> ThreadMembersUpdate {\n\n let guild_id = self.guild_id;\n\n let added_members = self\n\n .added_members\n\n .into_iter()\n\n .map(|tm| tm.into_thread_member(guild_id))\n\n .collect();\n", "file_path": "model/src/gateway/payload/incoming/thread_members_update.rs", "rank": 99, "score": 79355.1463632242 } ]
Rust
src/cli/src/cluster/install/tls.rs
simlay/fluvio
a42283200e667223d3a52b217d266db8927db4eb
use std::path::PathBuf; use tracing::debug; use structopt::StructOpt; use fluvio::config::{TlsPolicy, TlsPaths}; use std::convert::TryFrom; use crate::CliError; #[derive(Debug, StructOpt)] pub struct TlsOpt { #[structopt(long)] pub tls: bool, #[structopt(long)] pub domain: Option<String>, #[structopt(long, parse(from_os_str))] pub ca_cert: Option<PathBuf>, #[structopt(long, parse(from_os_str))] pub client_cert: Option<PathBuf>, #[structopt(long, parse(from_os_str))] pub client_key: Option<PathBuf>, #[structopt(long, parse(from_os_str))] pub server_cert: Option<PathBuf>, #[structopt(long, parse(from_os_str))] pub server_key: Option<PathBuf>, } impl TryFrom<TlsOpt> for (TlsPolicy, TlsPolicy) { type Error = CliError; fn try_from(opt: TlsOpt) -> Result<Self, Self::Error> { if !opt.tls { debug!("no optional tls"); return Ok((TlsPolicy::Disabled, TlsPolicy::Disabled)); } let policies = (|| -> Option<(TlsPolicy, TlsPolicy)> { let domain = opt.domain?; let ca_cert = opt.ca_cert?; let client_cert = opt.client_cert?; let client_key = opt.client_key?; let server_cert = opt.server_cert?; let server_key = opt.server_key?; let server_policy = TlsPolicy::from(TlsPaths { domain: domain.clone(), ca_cert: ca_cert.clone(), cert: server_cert, key: server_key, }); let client_policy = TlsPolicy::from(TlsPaths { domain, ca_cert, cert: client_cert, key: client_key, }); Some((client_policy, server_policy)) })(); policies.ok_or_else(|| { CliError::Other( "Missing required args after --tls:\ --domain, --ca-cert, --client-cert, --client-key, --server-cert, --server-key" .to_string(), ) }) } } #[cfg(test)] mod tests { use super::*; use std::convert::TryInto; #[test] fn test_from_opt() { let tls_opt = TlsOpt::from_iter(vec![ "test", "--tls", "--domain", "fluvio.io", "--ca-cert", "/tmp/certs/ca.crt", "--client-cert", "/tmp/certs/client.crt", "--client-key", "/tmp/certs/client.key", "--server-cert", "/tmp/certs/server.crt", "--server-key", "/tmp/certs/server.key", ]); let (client, server): (TlsPolicy, TlsPolicy) = tls_opt.try_into().unwrap(); use fluvio::config::{TlsPolicy::*, TlsConfig::*}; match (client, server) { (Verified(Files(client_paths)), Verified(Files(server_paths))) => { assert_eq!(client_paths.domain, "fluvio.io"); assert_eq!(client_paths.ca_cert, PathBuf::from("/tmp/certs/ca.crt")); assert_eq!(client_paths.cert, PathBuf::from("/tmp/certs/client.crt")); assert_eq!(client_paths.key, PathBuf::from("/tmp/certs/client.key")); assert_eq!(server_paths.domain, "fluvio.io"); assert_eq!(server_paths.ca_cert, PathBuf::from("/tmp/certs/ca.crt")); assert_eq!(server_paths.cert, PathBuf::from("/tmp/certs/server.crt")); assert_eq!(server_paths.key, PathBuf::from("/tmp/certs/server.key")); } _ => panic!("Failed to parse TlsProfiles from TlsOpt"), } } #[test] fn test_missing_opts() { let tls_opt: TlsOpt = TlsOpt::from_iter(vec![ "test", "--tls", ]); let result: Result<(TlsPolicy, TlsPolicy), _> = tls_opt.try_into(); assert!(result.is_err()); } }
use std::path::PathBuf; use tracing::debug; use structopt::StructOpt; use fluvio::config::{TlsPolicy, TlsPaths}; use std::convert::TryFrom; use crate::CliError; #[derive(Debug, StructOpt)] pub struct TlsOpt { #[structopt(long)] pub tls: bool, #[structopt(long)] pub domain: Option<String>, #[structopt(long, parse(from_os_str))] pub ca_cert: Option<PathBuf>, #[structopt(long, parse(from_os_str))] pub client_cert: Option<PathBuf>, #[structopt(long, parse(from_os_str))] pub client_key: Option<PathBuf>, #[structopt(long, parse(from_os_str))] pub server_cert: Option<PathBuf>, #[structopt(long, parse(from_os_str))] pub server_key
d, TlsPolicy::Disabled)); } let policies = (|| -> Option<(TlsPolicy, TlsPolicy)> { let domain = opt.domain?; let ca_cert = opt.ca_cert?; let client_cert = opt.client_cert?; let client_key = opt.client_key?; let server_cert = opt.server_cert?; let server_key = opt.server_key?; let server_policy = TlsPolicy::from(TlsPaths { domain: domain.clone(), ca_cert: ca_cert.clone(), cert: server_cert, key: server_key, }); let client_policy = TlsPolicy::from(TlsPaths { domain, ca_cert, cert: client_cert, key: client_key, }); Some((client_policy, server_policy)) })(); policies.ok_or_else(|| { CliError::Other( "Missing required args after --tls:\ --domain, --ca-cert, --client-cert, --client-key, --server-cert, --server-key" .to_string(), ) }) } } #[cfg(test)] mod tests { use super::*; use std::convert::TryInto; #[test] fn test_from_opt() { let tls_opt = TlsOpt::from_iter(vec![ "test", "--tls", "--domain", "fluvio.io", "--ca-cert", "/tmp/certs/ca.crt", "--client-cert", "/tmp/certs/client.crt", "--client-key", "/tmp/certs/client.key", "--server-cert", "/tmp/certs/server.crt", "--server-key", "/tmp/certs/server.key", ]); let (client, server): (TlsPolicy, TlsPolicy) = tls_opt.try_into().unwrap(); use fluvio::config::{TlsPolicy::*, TlsConfig::*}; match (client, server) { (Verified(Files(client_paths)), Verified(Files(server_paths))) => { assert_eq!(client_paths.domain, "fluvio.io"); assert_eq!(client_paths.ca_cert, PathBuf::from("/tmp/certs/ca.crt")); assert_eq!(client_paths.cert, PathBuf::from("/tmp/certs/client.crt")); assert_eq!(client_paths.key, PathBuf::from("/tmp/certs/client.key")); assert_eq!(server_paths.domain, "fluvio.io"); assert_eq!(server_paths.ca_cert, PathBuf::from("/tmp/certs/ca.crt")); assert_eq!(server_paths.cert, PathBuf::from("/tmp/certs/server.crt")); assert_eq!(server_paths.key, PathBuf::from("/tmp/certs/server.key")); } _ => panic!("Failed to parse TlsProfiles from TlsOpt"), } } #[test] fn test_missing_opts() { let tls_opt: TlsOpt = TlsOpt::from_iter(vec![ "test", "--tls", ]); let result: Result<(TlsPolicy, TlsPolicy), _> = tls_opt.try_into(); assert!(result.is_err()); } }
: Option<PathBuf>, } impl TryFrom<TlsOpt> for (TlsPolicy, TlsPolicy) { type Error = CliError; fn try_from(opt: TlsOpt) -> Result<Self, Self::Error> { if !opt.tls { debug!("no optional tls"); return Ok((TlsPolicy::Disable
random
[ { "content": "#[derive(Debug, StructOpt)]\n\nstruct VersionCmd {}\n\n\n", "file_path": "src/cli/src/root_cli.rs", "rank": 0, "score": 78096.27395499004 }, { "content": "#[derive(Debug, StructOpt)]\n\nstruct CompletionOpt {\n\n #[structopt(long, default_value = \"fluvio\")]\n\n name: String,\n\n}\n\n\n", "file_path": "src/cli/src/root_cli.rs", "rank": 1, "score": 78096.27395499004 }, { "content": "#[derive(Debug, StructOpt, Default)]\n\nstruct TlsConfig {\n\n /// enable tls\n\n #[structopt(long)]\n\n pub tls: bool,\n\n\n\n /// TLS: path to server certificate\n\n #[structopt(long)]\n\n pub server_cert: Option<String>,\n\n #[structopt(long)]\n\n /// TLS: path to server private key\n\n pub server_key: Option<String>,\n\n /// TLS: enable client cert\n\n #[structopt(long)]\n\n pub enable_client_cert: bool,\n\n /// TLS: path to ca cert, required when client cert is enabled\n\n #[structopt(long)]\n\n pub ca_cert: Option<String>,\n\n\n\n #[structopt(long)]\n\n /// TLS: address of non tls public service, required\n\n pub bind_non_tls_public: Option<String>,\n\n}\n", "file_path": "src/spu/src/config/cli.rs", "rank": 2, "score": 78096.21484537437 }, { "content": "struct CreateServicePermission;\n\n\n\n#[async_trait]\n\nimpl InstallCheck for CreateServicePermission {\n\n async fn perform_check(&self) -> Result<StatusCheck, CheckError> {\n\n check_permission(RESOURCE_SERVICE)\n\n }\n\n}\n\n\n", "file_path": "src/cluster/src/check.rs", "rank": 3, "score": 78090.5941679333 }, { "content": "struct CreateCrdPermission;\n\n\n\n#[async_trait]\n\nimpl InstallCheck for CreateCrdPermission {\n\n async fn perform_check(&self) -> Result<StatusCheck, CheckError> {\n\n check_permission(RESOURCE_CRD)\n\n }\n\n}\n\n\n", "file_path": "src/cluster/src/check.rs", "rank": 4, "score": 78090.5941679333 }, { "content": "struct PrintTerminal {}\n\n\n\nimpl PrintTerminal {\n\n fn new() -> Self {\n\n Self {}\n\n }\n\n}\n\n\n\nimpl Terminal for PrintTerminal {\n\n fn print(&self, msg: &str) {\n\n print!(\"{}\", msg);\n\n }\n\n\n\n fn println(&self, msg: &str) {\n\n println!(\"{}\", msg);\n\n }\n\n}\n\n\n", "file_path": "src/cli/src/root_cli.rs", "rank": 5, "score": 78090.5941679333 }, { "content": "struct SpuSocket {\n\n config: ClientConfig,\n\n socket: SharedAllMultiplexerSocket,\n\n versions: Versions,\n\n}\n\n\n\nimpl SpuSocket {\n\n async fn create_serial_socket(&mut self) -> VersionedSerialSocket {\n\n VersionedSerialSocket::new(\n\n self.socket.clone(),\n\n self.config.clone(),\n\n self.versions.clone(),\n\n )\n\n }\n\n\n\n async fn create_stream<R: Request>(\n\n &mut self,\n\n request: R,\n\n ) -> Result<AsyncResponse<R>, FluvioError> {\n\n let req_msg = RequestMessage::new_request(request);\n", "file_path": "src/client/src/spu/spu_pool.rs", "rank": 6, "score": 76853.68547971777 }, { "content": "struct CreateServiceAccountPermission;\n\n\n\n#[async_trait]\n\nimpl InstallCheck for CreateServiceAccountPermission {\n\n async fn perform_check(&self) -> Result<StatusCheck, CheckError> {\n\n check_permission(RESOURCE_SERVICE_ACCOUNT)\n\n }\n\n}\n\n\n\npub(crate) struct LoadBalancer;\n\n\n\n#[async_trait]\n\nimpl InstallCheck for LoadBalancer {\n\n async fn perform_check(&self) -> Result<StatusCheck, CheckError> {\n\n check_load_balancer_status().await\n\n }\n\n}\n\n\n\n/// Client to manage cluster check operations\n\n#[derive(Debug)]\n", "file_path": "src/cluster/src/check.rs", "rank": 7, "score": 76853.68547971777 }, { "content": "struct SimplePolicy {}\n\n\n\nimpl SimplePolicy {\n\n fn new() -> Self {\n\n SimplePolicy {}\n\n }\n\n}\n\n\n\nimpl ElectionPolicy for SimplePolicy {\n\n fn potential_leader_score(\n\n &self,\n\n replica_status: &ReplicaStatus,\n\n leader: &ReplicaStatus,\n\n ) -> ElectionScoring {\n\n let lag = leader.leo - replica_status.leo;\n\n if lag < 4 {\n\n ElectionScoring::Score(lag as u16)\n\n } else {\n\n ElectionScoring::NotSuitable\n\n }\n", "file_path": "src/sc/src/controllers/partitions/reducer.rs", "rank": 8, "score": 76853.68547971777 }, { "content": "struct ReplicationTest {}\n\n\n\nimpl ScTest for ReplicationTest {\n\n type ResponseFuture = BoxFuture<'static, Result<(), FlvSocketError>>;\n\n\n\n fn env_configuration(&self) -> TestGenerator {\n\n TestGenerator::default()\n\n .set_base_id(7000)\n\n .set_base_port(7000)\n\n .set_total_spu(2)\n\n .set_init_spu(2)\n\n }\n\n\n\n fn topics(&self) -> Vec<(String, Vec<Vec<SpuId>>)> {\n\n vec![(\"test\".to_owned(), vec![vec![7000, 7001]])]\n\n }\n\n\n\n /// spin up spu and down.\n\n fn main_test(&self, _runner: Arc<ScTestRunner<ReplicationTest>>) -> Self::ResponseFuture {\n\n async move {\n", "file_path": "src/sc/src/tests/suite/partition_test.rs", "rank": 9, "score": 75683.90513756822 }, { "content": "struct SpuOnlineStatus {\n\n online: bool,\n\n // last time status was known\n\n time: Instant,\n\n}\n\n\n\nimpl SpuOnlineStatus {\n\n fn new() -> Self {\n\n Self {\n\n online: false,\n\n time: Instant::now(),\n\n }\n\n }\n\n}\n\n\n\n/// Keep track of SPU status\n\n/// if SPU has not send heart beat within a period, it is considered down\n\npub struct SpuController {\n\n spus: StoreContext<SpuSpec>,\n\n health_receiver: Receiver<SpuAction>,\n", "file_path": "src/sc/src/controllers/spus/controller.rs", "rank": 10, "score": 75683.90513756822 }, { "content": "struct ScServerCtx {\n\n ctx: SharedScContext,\n\n sender: Sender<bool>,\n\n}\n\n\n\npub struct SpuTestRunner<T> {\n\n client_id: String,\n\n spu_server_specs: Vec<SpuServer>,\n\n spu_server_ctx: Vec<DefaultSharedGlobalContext>,\n\n spu_senders: Vec<Sender<bool>>,\n\n sc_ctx: RwLock<Option<ScServerCtx>>,\n\n test: T,\n\n}\n\n\n\nimpl<T> SpuTestRunner<T>\n\nwhere\n\n T: SpuTest + Send + Sync + 'static,\n\n{\n\n pub async fn run(client_id: String, test: T) -> Result<(), FlvSocketError> {\n\n debug!(\"starting test harnerss\");\n", "file_path": "src/spu/src/tests/fixture/test_runner.rs", "rank": 11, "score": 74575.93282140976 }, { "content": "struct ScServerCtx {\n\n ctx: SharedScContext,\n\n sender: Sender<bool>,\n\n}\n", "file_path": "src/spu/src/tests/fixture/spu_client.rs", "rank": 12, "score": 74575.93282140976 }, { "content": "struct SimpleInternalTest {}\n\n\n\nimpl ScTest for SimpleInternalTest {\n\n type ResponseFuture = BoxFuture<'static, Result<(), FlvSocketError>>;\n\n\n\n fn env_configuration(&self) -> TestGenerator {\n\n TestGenerator::default()\n\n .set_base_id(BASE_ID)\n\n .set_base_port(BASE_ID as u16)\n\n .set_total_spu(1)\n\n }\n\n\n\n fn topics(&self) -> Vec<(String, Vec<Vec<SpuId>>)> {\n\n vec![(\"test\".to_owned(), vec![vec![BASE_ID]])]\n\n }\n\n\n\n /// spin up spu and down.\n\n fn main_test(&self, runner: Arc<ScTestRunner<SimpleInternalTest>>) -> Self::ResponseFuture {\n\n let generator = runner.generator();\n\n let (ctx, mut spu0_terminator) = generator.run_server_with_index(0, runner.clone()); // 7000\n", "file_path": "src/sc/src/tests/suite/conn_test.rs", "rank": 13, "score": 74575.93282140976 }, { "content": "struct OffsetsFetchTest {}\n\n\n\nasync fn test_fetch(runner: Arc<SpuTestRunner<OffsetsFetchTest>>) -> Result<(), FlvSocketError> {\n\n // verify invalid request\n\n let mut request = FlvFetchOffsetsRequest::default();\n\n let mut topic = FetchOffsetTopic::default();\n\n topic.name = \"dummy\".into();\n\n let mut partition = FetchOffsetPartition::default();\n\n partition.partition_index = PARTITION_ID;\n\n topic.partitions.push(partition);\n\n request.topics.push(topic);\n\n let req_msg = RequestMessage::new_request(request).set_client_id(\"offset fetch tester\");\n\n let produce_resp = runner\n\n .leader()\n\n .send_to_public_server(&req_msg)\n\n .await\n\n .expect(\"offset fetch\");\n\n let topic_responses = produce_resp.response.topics;\n\n assert_eq!(topic_responses.len(), 1);\n\n let topic_response = &topic_responses[0];\n", "file_path": "src/spu/src/tests/suites/test_offsets.rs", "rank": 14, "score": 74575.93282140976 }, { "content": "struct FollowReplicationTest {\n\n replicas: usize,\n\n base: u16,\n\n}\n\n\n\nimpl FollowReplicationTest {\n\n fn new(replicas: usize, base: u16) -> Self {\n\n Self { replicas, base }\n\n }\n\n}\n\n\n\n// simple replication to a sigle follower\n\nasync fn inner_test(\n\n runner: Arc<SpuTestRunner<FollowReplicationTest>>,\n\n) -> Result<(), FlvSocketError> {\n\n let leader_spu = runner.leader_spec();\n\n let leader_gtx = runner.leader_gtx();\n\n let _replica = test_repl_id();\n\n\n\n // wait until all follower has sync up\n", "file_path": "src/spu/src/tests/suites/test_replication.rs", "rank": 15, "score": 74575.93282140976 }, { "content": "struct SimpleFetchTest {}\n\n\n\nasync fn test_fetch(runner: Arc<SpuTestRunner<SimpleFetchTest>>) -> Result<(), FlvSocketError> {\n\n let _replica = test_repl_id();\n\n // runner.send_metadata_to_all(&replica).await.expect(\"send metadata\");\n\n\n\n let produce_req_msg = runner.create_producer_msg(\"message\", TOPIC_ID, PARTITION_ID);\n\n let produce_resp = runner\n\n .leader()\n\n .send_to_public_server(&produce_req_msg)\n\n .await?;\n\n let response = produce_resp.response;\n\n let topic_responses = response.responses;\n\n assert_eq!(topic_responses.len(), 1);\n\n let topic_response = &topic_responses[0];\n\n assert_eq!(topic_response.name, TOPIC_ID);\n\n let partition_responses = &topic_response.partitions;\n\n assert_eq!(partition_responses.len(), 1);\n\n assert_eq!(partition_responses[0].base_offset, 0);\n\n\n", "file_path": "src/spu/src/tests/suites/test_fetch.rs", "rank": 16, "score": 74575.93282140976 }, { "content": "#[async_trait]\n\npub trait Authorization {\n\n type Stream: AsyncRead + AsyncWrite + Unpin + Send;\n\n type Context: AuthContext;\n\n\n\n /// create auth context\n\n async fn create_auth_context(\n\n &self,\n\n socket: &mut InnerFlvSocket<Self::Stream>,\n\n ) -> Result<Self::Context, AuthError>;\n\n}\n", "file_path": "src/auth/src/policy.rs", "rank": 17, "score": 72546.48565221122 }, { "content": "pub trait Spec {\n\n const LABEL: &'static str;\n\n type Key: Ord + Clone + ToString;\n\n\n\n fn key(&self) -> &Self::Key;\n\n\n\n fn key_owned(&self) -> Self::Key;\n\n}\n\n\n\n#[derive(Debug, PartialEq, Clone)]\n\npub enum SpecChange<S> {\n\n Add(S),\n\n Mod(S, S), // new, old\n\n Delete(S),\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct LocalStore<S>(SimpleConcurrentBTreeMap<S::Key, S>)\n\nwhere\n\n S: Spec;\n", "file_path": "src/spu/src/core/store.rs", "rank": 18, "score": 71243.53572627797 }, { "content": "/// create server and spin up services, but don't run server\n\npub fn create_services(\n\n local_spu: SpuConfig,\n\n internal: bool,\n\n public: bool,\n\n) -> (\n\n DefaultSharedGlobalContext,\n\n Option<InternalApiServer>,\n\n Option<PublicApiServer>,\n\n) {\n\n let ctx = FileReplicaContext::new_shared_context(local_spu);\n\n\n\n let public_ep_addr = ctx.config().public_socket_addr().to_owned();\n\n let private_ep_addr = ctx.config().private_socket_addr().to_owned();\n\n\n\n let public_server = if public {\n\n Some(create_public_server(public_ep_addr, ctx.clone()))\n\n } else {\n\n None\n\n };\n\n\n", "file_path": "src/spu/src/start.rs", "rank": 19, "score": 71243.53572627797 }, { "content": "pub trait Records {}\n\n\n\n#[derive(Default)]\n\npub struct DefaultAsyncBuffer(Option<Vec<u8>>);\n\n\n\nimpl DefaultAsyncBuffer {\n\n pub fn new(val: Option<Vec<u8>>) -> Self {\n\n DefaultAsyncBuffer(val)\n\n }\n\n\n\n pub fn inner_value(self) -> Option<Vec<u8>> {\n\n self.0\n\n }\n\n\n\n pub fn inner_value_ref(&self) -> &Option<Vec<u8>> {\n\n &self.0\n\n }\n\n\n\n pub fn len(&self) -> usize {\n\n if self.0.is_some() {\n", "file_path": "src/dataplane-protocol/src/record.rs", "rank": 20, "score": 71243.53572627797 }, { "content": "#[async_trait]\n\npub trait AuthContext {\n\n /// check if any allow type specific action can be allowed\n\n async fn allow_type_action(\n\n &self,\n\n ty: ObjectType,\n\n action: TypeAction,\n\n ) -> Result<bool, AuthError>;\n\n\n\n /// check if specific instance of action can be permitted\n\n async fn allow_instance_action(\n\n &self,\n\n ty: ObjectType,\n\n action: InstanceAction,\n\n key: &str,\n\n ) -> Result<bool, AuthError>;\n\n}\n\n\n", "file_path": "src/auth/src/policy.rs", "rank": 21, "score": 71243.53572627797 }, { "content": " /// for deleting objects\n\n pub trait Removable {\n\n type DeleteKey;\n\n }\n\n\n", "file_path": "src/stream-model/src/core.rs", "rank": 22, "score": 71243.53572627797 }, { "content": " /// marker trait for creating\n\n pub trait Creatable {}\n\n\n\n /// Represents some metadata object\n\n pub struct MetadataObj<S, P>\n\n where\n\n P: MetadataStoreDriver,\n\n S: Spec,\n\n {\n\n pub name: String,\n\n pub metadata: P::Metadata,\n\n pub spec: S,\n\n pub status: S::Status,\n\n }\n\n}\n", "file_path": "src/stream-model/src/core.rs", "rank": 23, "score": 71243.53572627797 }, { "content": "pub trait ReplicaStorage {\n\n /// high water mark offset (records that has been replicated)\n\n fn get_hw(&self) -> Offset;\n\n\n\n /// log end offset ( records that has been stored)\n\n fn get_leo(&self) -> Offset;\n\n}\n", "file_path": "src/storage/src/lib.rs", "rank": 24, "score": 71243.53572627797 }, { "content": "#[allow(dead_code)]\n\nstruct Dispatcher<C>(C);\n\n\n\n#[allow(dead_code)]\n\nimpl<S> Dispatcher<C>\n\nwhere\n\n C: Controller + Send + Sync + 'static,\n\n C::Action: Send + Sync + 'static,\n\n{\n\n /// start the controller with ctx and receiver\n\n pub fn run<K>(controller: C, receiver: Receiver<Actions<C::Action>>, kv_service: K)\n\n where\n\n K: WSUpdateService + Send + Sync + 'static,\n\n {\n\n spawn(Self::request_loop(receiver, kv_service, controller).await);\n\n }\n\n\n\n async fn request_loop<K>(\n\n mut receiver: Receiver<Actions<C::Action>>,\n\n _kv_service: K,\n\n mut _controller: C,\n", "file_path": "src/sc/src/core/common/dispatcher.rs", "rank": 25, "score": 70769.0161060087 }, { "content": "pub trait Captures<'a> {}\n\nimpl<'a, T: ?Sized> Captures<'a> for T {}\n\n\n", "file_path": "src/storage/src/lib.rs", "rank": 26, "score": 70570.32714201469 }, { "content": "/// Offset information about Partition\n\npub trait PartitionOffset {\n\n /// last offset that was committed\n\n fn last_stable_offset(&self) -> i64;\n\n\n\n // beginning offset for the partition\n\n fn start_offset(&self) -> i64;\n\n}\n\n\n", "file_path": "src/dataplane-protocol/src/common.rs", "rank": 27, "score": 70013.27061540075 }, { "content": "pub trait Controller {\n\n type Spec: Spec;\n\n type Status: Status;\n\n type Action: Debug;\n\n}\n\n\n", "file_path": "src/sc/src/core/common/dispatcher.rs", "rank": 28, "score": 70013.27061540075 }, { "content": " #[async_trait]\n\n pub trait TestDriver {\n\n /// run tester\n\n async fn run(&self);\n\n }\n\n}\n\n\n\n/// select runner based on option\n\nmod driver {\n\n\n\n use crate::TestOption;\n\n use crate::tests::smoke::SmokeTestRunner;\n\n\n\n use super::TestDriver;\n\n\n\n pub fn create_test_driver(option: TestOption) -> Box<dyn TestDriver> {\n\n Box::new(SmokeTestRunner::new(option))\n\n }\n\n}\n", "file_path": "tests/runner/src/tests/mod.rs", "rank": 29, "score": 70013.27061540075 }, { "content": " #[async_trait]\n\n pub trait EnvironmentDriver {\n\n /// remove cluster\n\n async fn remove_cluster(&self);\n\n\n\n /// install cluster\n\n async fn install_cluster(&self);\n\n\n\n fn set_tls(&self, option: &TestOption, cmd: &mut Command) {\n\n use crate::tls::Cert;\n\n\n\n if option.tls() {\n\n let client_dir = Cert::load_client(&option.tls_user);\n\n\n\n cmd.arg(\"--tls\")\n\n .arg(\"--domain\")\n\n .arg(\"fluvio.local\")\n\n .arg(\"--ca-cert\")\n\n .arg(client_dir.ca.as_os_str())\n\n .arg(\"--client-cert\")\n\n .arg(client_dir.cert.as_os_str())\n", "file_path": "tests/runner/src/environment/mod.rs", "rank": 30, "score": 70013.27061540075 }, { "content": "/// output from storage is represented as slice\n\npub trait SlicePartitionResponse {\n\n fn set_hw(&mut self, offset: i64);\n\n\n\n fn set_last_stable_offset(&mut self, offset: i64);\n\n\n\n fn set_log_start_offset(&mut self, offset: i64);\n\n\n\n fn set_slice(&mut self, slice: AsyncFileSlice);\n\n\n\n fn set_error_code(&mut self, error: ErrorCode);\n\n}\n\n\n\nimpl SlicePartitionResponse for FilePartitionResponse {\n\n fn set_hw(&mut self, offset: i64) {\n\n self.high_watermark = offset;\n\n }\n\n\n\n fn set_last_stable_offset(&mut self, offset: i64) {\n\n self.last_stable_offset = offset;\n\n }\n", "file_path": "src/storage/src/lib.rs", "rank": 31, "score": 70013.27061540075 }, { "content": "pub trait CommandUtil {\n\n fn inherit(&mut self);\n\n\n\n // wait and check\n\n fn wait_and_check(&mut self);\n\n\n\n // just wait\n\n fn wait(&mut self);\n\n\n\n fn print(&mut self) -> &mut Self;\n\n\n\n fn rust_log(&mut self, log_option: Option<&str>) -> &mut Self;\n\n}\n\n\n\nimpl CommandUtil for Command {\n\n fn rust_log(&mut self, log_option: Option<&str>) -> &mut Self {\n\n if let Some(log) = log_option {\n\n println!(\"setting rust log: {}\", log);\n\n self.env(\"RUST_LOG\", log);\n\n }\n", "file_path": "tests/runner/src/util/cmd.rs", "rank": 32, "score": 70013.27061540075 }, { "content": " #[async_trait]\n\n pub trait RenderContext {\n\n async fn render_on<O: Terminal>(&self, out: Arc<O>);\n\n }\n\n}\n\n\n\n#[allow(clippy::module_inception)]\n\nmod output {\n\n\n\n use std::sync::Arc;\n\n\n\n use structopt::clap::arg_enum;\n\n use serde::Serialize;\n\n use prettytable::format;\n\n use prettytable::Table;\n\n use prettytable::row;\n\n use prettytable::cell;\n\n\n\n use crate::CliError;\n\n\n\n use super::TableOutputHandler;\n", "file_path": "src/cli/src/output/mod.rs", "rank": 33, "score": 70013.27061540075 }, { "content": "/// slice that can works in Async Context\n\npub trait AsyncBuffer {\n\n fn len(&self) -> usize;\n\n}\n\n\n", "file_path": "src/dataplane-protocol/src/record.rs", "rank": 34, "score": 70013.27061540075 }, { "content": " pub trait CommandUtil {\n\n // wait and check\n\n fn wait(&mut self);\n\n\n\n fn wait_check(&mut self);\n\n\n\n fn print(&mut self) -> &mut Self;\n\n\n\n /// inherit stdout from parent and check for success\n\n fn inherit(&mut self);\n\n }\n\n\n\n use std::process::Command;\n\n\n\n impl CommandUtil for Command {\n\n fn inherit(&mut self) {\n\n use std::io;\n\n use std::io::Write;\n\n use std::process::Stdio;\n\n\n", "file_path": "src/cli/src/cluster/util.rs", "rank": 35, "score": 70013.27061540075 }, { "content": "pub trait TableOutputHandler {\n\n fn header(&self) -> Row;\n\n fn content(&self) -> Vec<Row>;\n\n fn errors(&self) -> Vec<String>;\n\n}\n\n\n\npub struct TableRenderer<O>(Arc<O>);\n\n\n\nimpl<O> TableRenderer<O>\n\nwhere\n\n O: Terminal,\n\n{\n\n pub fn new(out: Arc<O>) -> Self {\n\n Self(out)\n\n }\n\n\n\n pub fn render<T>(&self, list: &T, indent: bool)\n\n where\n\n T: TableOutputHandler,\n\n {\n", "file_path": "src/cli/src/output/table.rs", "rank": 36, "score": 68849.77329660286 }, { "content": "pub trait ElectionPolicy {\n\n /// compute potential leade score against leader\n\n fn potential_leader_score(\n\n &self,\n\n replica_status: &ReplicaStatus,\n\n leader: &ReplicaStatus,\n\n ) -> ElectionScoring;\n\n}\n", "file_path": "src/controlplane-metadata/src/partition/policy.rs", "rank": 37, "score": 68849.77329660286 }, { "content": "/// marker trait\n\npub trait ListFilter {}\n\n\n\n/// filter by name\n\npub type NameFilter = String;\n\n\n\nimpl ListFilter for NameFilter {}\n\n\n", "file_path": "src/sc-schema/src/objects/list.rs", "rank": 38, "score": 68849.77329660286 }, { "content": " /// metadata driver\n\n pub trait MetadataStoreDriver {\n\n type Metadata;\n\n }\n\n\n", "file_path": "src/stream-model/src/core.rs", "rank": 39, "score": 68849.77329660286 }, { "content": "pub trait DescribeObjectHandler {\n\n fn is_ok(&self) -> bool;\n\n fn is_error(&self) -> bool;\n\n fn validate(&self) -> Result<(), CliError>;\n\n\n\n fn label() -> &'static str;\n\n fn label_plural() -> &'static str;\n\n}\n\n\n\n// -----------------------------------\n\n// Data Structures\n\n// -----------------------------------\n\n\n\npub struct DescribeObjectRender<O>(Arc<O>);\n\n\n\nimpl<O> DescribeObjectRender<O> {\n\n pub fn new(out: Arc<O>) -> Self {\n\n Self(out)\n\n }\n\n}\n", "file_path": "src/cli/src/output/describe.rs", "rank": 40, "score": 68849.77329660286 }, { "content": "pub trait ControllerAction {}\n\n\n", "file_path": "src/sc/src/core/common/dispatcher.rs", "rank": 41, "score": 68849.77329660286 }, { "content": "/// If header has error, format and return\n\npub fn error_in_header(\n\n topic_name: &str,\n\n r_partition: &FetchablePartitionResponse<RecordSet>,\n\n) -> Option<String> {\n\n if r_partition.error_code.is_error() {\n\n Some(format!(\n\n \"topic '{}/{}': {}\",\n\n topic_name,\n\n r_partition.partition_index,\n\n r_partition.error_code.to_sentence()\n\n ))\n\n } else {\n\n None\n\n }\n\n}\n", "file_path": "src/cli/src/consume/logs_output.rs", "rank": 42, "score": 68849.77329660286 }, { "content": "struct WatchController<T, S>\n\nwhere\n\n S: Spec,\n\n{\n\n response_sink: InnerExclusiveFlvSink<T>,\n\n store: StoreContext<S>,\n\n epoch: Epoch,\n\n header: RequestHeader,\n\n end_event: Arc<Event>,\n\n}\n\n\n\nimpl<T, S> WatchController<T, S>\n\nwhere\n\n T: AsyncWrite + AsyncRead + Unpin + Send + ZeroCopyWrite + 'static,\n\n S: Spec + Debug + 'static + Send + Sync + Encoder + Decoder,\n\n S::IndexKey: ToString,\n\n <S as Spec>::Status: Sync + Send + Encoder + Decoder,\n\n <S as Spec>::IndexKey: Sync + Send,\n\n MetadataUpdate<S>: Into<WatchResponse>,\n\n{\n", "file_path": "src/sc/src/services/public_api/watch.rs", "rank": 43, "score": 68610.10693136315 }, { "content": " pub trait Terminal: Sized {\n\n fn print(&self, msg: &str);\n\n fn println(&self, msg: &str);\n\n\n\n fn render_list<T>(self: Arc<Self>, list: &T, mode: OutputType) -> Result<(), CliError>\n\n where\n\n T: TableOutputHandler + Serialize,\n\n {\n\n if mode.is_table() {\n\n let render = TableRenderer::new(self);\n\n render.render(list, false);\n\n } else {\n\n let render = SerdeRenderer::new(self);\n\n render.render(&list, mode.into())?;\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n fn render_table<T: TableOutputHandler>(self: Arc<Self>, val: &T, indent: bool) {\n", "file_path": "src/cli/src/output/mod.rs", "rank": 44, "score": 68037.11210520423 }, { "content": "pub trait OffsetPosition: Sized {\n\n /// convert to be endian\n\n fn to_be(self) -> Self;\n\n\n\n fn offset(&self) -> Size;\n\n\n\n fn position(&self) -> Size;\n\n}\n\n\n\nimpl OffsetPosition for (Size, Size) {\n\n fn to_be(self) -> Self {\n\n let (offset, pos) = self;\n\n (offset.to_be(), pos.to_be())\n\n }\n\n\n\n #[inline(always)]\n\n fn offset(&self) -> Size {\n\n self.0.to_be()\n\n }\n\n\n", "file_path": "src/storage/src/index.rs", "rank": 45, "score": 68037.11210520423 }, { "content": "pub trait ReadToBuf: Sized {\n\n fn read_from<B>(buf: &mut B) -> Self\n\n where\n\n B: Buf;\n\n\n\n fn write_to<B>(&mut self, buf: &mut B)\n\n where\n\n B: BufMut;\n\n}\n\n\n\nimpl ReadToBuf for u64 {\n\n fn read_from<B>(buf: &mut B) -> Self\n\n where\n\n B: Buf,\n\n {\n\n buf.get_u64()\n\n }\n\n\n\n fn write_to<B>(&mut self, buf: &mut B)\n\n where\n", "file_path": "src/storage/src/checkpoint.rs", "rank": 46, "score": 68037.11210520423 }, { "content": "/// Generates a random authorization secret\n\npub fn generate_secret() -> String {\n\n const CHARSET: &[u8] = b\"abcdefghijklmnopqrstuvwxyz\\\n\n 0123456789\";\n\n\n\n const SECRET_SIZE: usize = 16;\n\n let secret: String = (0..SECRET_SIZE)\n\n .map(|_| {\n\n let idx = thread_rng().gen_range(0, CHARSET.len());\n\n // This is safe because `idx` is in range of `CHARSET`\n\n char::from(unsafe { *CHARSET.get_unchecked(idx) })\n\n })\n\n .collect();\n\n\n\n secret\n\n}\n\n\n\n#[allow(dead_code)]\n", "file_path": "src/utils/src/generators.rs", "rank": 47, "score": 68037.11210520423 }, { "content": "pub trait KeyValOutputHandler {\n\n fn key_values(&self) -> Vec<(String, Option<String>)>;\n\n}\n\n\n\nmod context {\n\n\n\n use std::sync::Arc;\n\n\n\n use async_trait::async_trait;\n\n use crate::Terminal;\n\n\n", "file_path": "src/cli/src/output/mod.rs", "rank": 48, "score": 67747.75202585402 }, { "content": "/// convert SpuGroup to Statefulset\n\npub fn convert_cluster_to_statefulset(\n\n group_spec: &K8SpuGroupSpec,\n\n metadata: &ObjectMeta,\n\n group_name: &str,\n\n group_svc_name: String,\n\n namespace: &str,\n\n tls: Option<&TlsConfig>,\n\n) -> InputK8Obj<StatefulSetSpec> {\n\n let statefulset_name = format!(\"flv-spg-{}\", group_name);\n\n let spec = generate_stateful(group_spec, group_name, group_svc_name, namespace, tls);\n\n let owner_ref = metadata.make_owner_reference::<K8SpuGroupSpec>();\n\n\n\n InputK8Obj {\n\n api_version: StatefulSetSpec::api_version(),\n\n kind: StatefulSetSpec::kind(),\n\n metadata: InputObjectMeta {\n\n name: statefulset_name,\n\n namespace: metadata.namespace().to_string(),\n\n owner_references: vec![owner_ref],\n\n ..Default::default()\n\n },\n\n spec,\n\n ..Default::default()\n\n }\n\n}\n\n\n", "file_path": "src/sc/src/k8/operator/conversion.rs", "rank": 49, "score": 67747.75202585402 }, { "content": "pub trait ScConfigBuilder {\n\n fn to_sc_config(self) -> Result<ScConfig, IoError>;\n\n}\n\n\n\n/// streaming controller configuration file\n\n#[derive(Debug, Clone, PartialEq)]\n\npub struct ScConfig {\n\n pub public_endpoint: String,\n\n pub private_endpoint: String,\n\n pub run_k8_dispatchers: bool,\n\n pub namespace: String,\n\n pub x509_auth_scopes: Option<PathBuf>,\n\n}\n\n\n\nimpl ::std::default::Default for ScConfig {\n\n fn default() -> Self {\n\n Self {\n\n public_endpoint: format!(\"0.0.0.0:{}\", SC_PUBLIC_PORT),\n\n private_endpoint: format!(\"0.0.0.0:{}\", SC_PRIVATE_PORT),\n\n run_k8_dispatchers: true,\n\n namespace: \"default\".to_owned(),\n\n x509_auth_scopes: None,\n\n }\n\n }\n\n}\n", "file_path": "src/sc/src/config/sc_config.rs", "rank": 50, "score": 67747.75202585402 }, { "content": "pub fn run_k8_operators(\n\n namespace: String,\n\n k8_client: SharedK8Client,\n\n ctx: SharedContext,\n\n tls: Option<TlsConfig>,\n\n) {\n\n SpgOperator::new(k8_client.clone(), namespace.clone(), ctx.clone(), tls).run();\n\n\n\n let svc_ctx: StoreContext<SpuServicespec> = StoreContext::new();\n\n\n\n K8ClusterStateDispatcher::<SpuServicespec, _>::start(namespace, k8_client, svc_ctx.clone());\n\n SpuServiceController::start(ctx, svc_ctx);\n\n}\n", "file_path": "src/sc/src/k8/operator/mod.rs", "rank": 51, "score": 67747.75202585402 }, { "content": "/// Traverse all partition batches and parse records to json format\n\npub fn partition_to_json_records(\n\n partition: &FetchablePartitionResponse<RecordSet>,\n\n suppress: bool,\n\n) -> Vec<Value> {\n\n let mut json_records: Vec<Value> = vec![];\n\n\n\n // convert all batches to json records\n\n for batch in &partition.records.batches {\n\n for record in &batch.records {\n\n if let Some(batch_record) = record.get_value().inner_value_ref() {\n\n match serde_json::from_slice(&batch_record) {\n\n Ok(value) => json_records.push(value),\n\n Err(_) => {\n\n if !suppress {\n\n json_records.push(serde_json::json!({\n\n \"error\": record.get_value().describe()\n\n }));\n\n }\n\n }\n\n }\n\n }\n\n }\n\n }\n\n\n\n json_records\n\n}\n\n\n", "file_path": "src/cli/src/consume/logs_output.rs", "rank": 52, "score": 67747.75202585402 }, { "content": "#[async_trait]\n\npub trait SpuValidation {\n\n fn is_already_valid(&self) -> bool;\n\n async fn is_conflict_with(&self, spu_store: &SpuAdminStore) -> Option<SpuId>;\n\n}\n\n\n\n#[async_trait]\n\nimpl SpuValidation for SpuGroupObj {\n\n /// check if I am already been validated\n\n fn is_already_valid(&self) -> bool {\n\n self.status.is_already_valid()\n\n }\n\n\n\n /// check if my group's id is conflict with my spu local store\n\n async fn is_conflict_with(&self, spu_store: &SpuAdminStore) -> Option<SpuId> {\n\n if self.is_already_valid() {\n\n return None;\n\n }\n\n\n\n let min_id = self.spec.min_id as SpuId;\n\n\n\n is_conflict(\n\n spu_store,\n\n self.metadata.uid.clone(),\n\n min_id,\n\n min_id + self.spec.replicas as SpuId,\n\n )\n\n .await\n\n }\n\n}\n", "file_path": "src/sc/src/k8/operator/spg_group.rs", "rank": 53, "score": 67747.75202585402 }, { "content": " pub trait SpecExt: Spec {\n\n const OBJECT_TYPE: ObjectType;\n\n }\n\n}\n", "file_path": "src/controlplane-metadata/src/lib.rs", "rank": 54, "score": 66873.61478640631 }, { "content": " pub trait AdminRequest: Request {}\n\n}\n", "file_path": "src/sc-schema/src/lib.rs", "rank": 55, "score": 66873.61478640631 }, { "content": "/// Generate a random client group key (50001 to 65535)\n\npub fn generate_group_id() -> String {\n\n format!(\"fluvio-consumer-{}\", thread_rng().gen_range(50001, 65535))\n\n}\n\n\n\n#[allow(dead_code)]\n", "file_path": "src/utils/src/generators.rs", "rank": 56, "score": 66873.61478640631 }, { "content": "/// Generate a random session id\n\npub fn rand_session_id() -> i32 {\n\n thread_rng().gen_range(1024, i32::MAX)\n\n}\n\n\n\n#[allow(dead_code)]\n", "file_path": "src/utils/src/generators.rs", "rank": 57, "score": 66873.61478640631 }, { "content": "pub fn cert_dir() -> PathBuf {\n\n std::env::current_dir().unwrap().join(\"tls\").join(\"certs\")\n\n}\n\n\n\npub struct Cert {\n\n pub ca: PathBuf,\n\n pub cert: PathBuf,\n\n pub key: PathBuf,\n\n}\n\n\n\nimpl Cert {\n\n pub fn load_client(client_user: &str) -> Self {\n\n let cert_dir = cert_dir();\n\n Cert {\n\n ca: cert_dir.join(\"ca.crt\"),\n\n cert: cert_dir.join(format!(\"client-{}.crt\", client_user)),\n\n key: cert_dir.join(format!(\"client-{}.key\", client_user)),\n\n }\n\n }\n\n\n\n pub fn load_server() -> Self {\n\n let cert_dir = cert_dir();\n\n Cert {\n\n ca: cert_dir.join(\"ca.crt\"),\n\n cert: cert_dir.join(\"server.crt\"),\n\n key: cert_dir.join(\"server.key\"),\n\n }\n\n }\n\n}\n", "file_path": "tests/runner/src/tls.rs", "rank": 58, "score": 66873.61478640631 }, { "content": "/// Generates a random key\n\npub fn generate_random_key() -> String {\n\n const CHARSET: &[u8] = b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\\\n\n abcdefghijklmnopqrstuvwxyz\\\n\n 0123456789)(*&^%$#@!~\";\n\n const SIZE: usize = 32;\n\n let key: String = (0..SIZE)\n\n .map(|_| {\n\n let idx = thread_rng().gen_range(0, CHARSET.len());\n\n // This is safe because `idx` is in range of `CHARSET`\n\n char::from(unsafe { *CHARSET.get_unchecked(idx) })\n\n })\n\n .collect();\n\n\n\n key\n\n}\n", "file_path": "src/utils/src/generators.rs", "rank": 59, "score": 66873.61478640631 }, { "content": "/// Generate a random correlation_id (0 to 65535)\n\npub fn rand_correlation_id() -> i32 {\n\n thread_rng().gen_range(0, 65535)\n\n}\n\n\n", "file_path": "src/utils/src/generators.rs", "rank": 60, "score": 66873.61478640631 }, { "content": "pub fn create_batch() -> DefaultBatch {\n\n create_batch_with_producer(12, 2)\n\n}\n\n\n", "file_path": "src/storage/src/fixture.rs", "rank": 61, "score": 66873.61478640631 }, { "content": " pub trait PartitionLoad: Sized {\n\n fn file_decode<T: AsRef<Path>>(path: T) -> Result<Self, IoError>;\n\n }\n\n\n\n impl PartitionLoad for PartitionMaps {\n\n /// Read and decode the json file into Replica Assignment map\n\n fn file_decode<T: AsRef<Path>>(path: T) -> Result<Self, IoError> {\n\n let file_str: String = read_to_string(path)?;\n\n serde_json::from_str(&file_str)\n\n .map_err(|err| IoError::new(ErrorKind::InvalidData, format!(\"{}\", err)))\n\n }\n\n }\n\n}\n", "file_path": "src/cli/src/topic/create.rs", "rank": 62, "score": 66873.61478640631 }, { "content": "pub trait DualDiff {\n\n /// check if another is different from myself\n\n fn diff(&self, another: &Self) -> MetadataChange;\n\n}\n\n\n\n/// What has been changed between two metadata\n\npub struct MetadataChange {\n\n pub spec: bool,\n\n pub status: bool,\n\n}\n\n\n\nimpl MetadataChange {\n\n /// create change that change both spec and status\n\n #[cfg(test)]\n\n pub fn full_change() -> Self {\n\n Self {\n\n spec: true,\n\n status: true,\n\n }\n\n }\n", "file_path": "src/stream-model/src/epoch/dual_epoch_map.rs", "rank": 63, "score": 66702.4598688421 }, { "content": "pub trait ListSpec: Spec {\n\n /// filter type\n\n type Filter: ListFilter;\n\n\n\n /// convert to list request with filters\n\n fn into_list_request(filters: Vec<Self::Filter>) -> ListRequest;\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum ListRequest {\n\n Topic(Vec<NameFilter>),\n\n Spu(Vec<NameFilter>),\n\n SpuGroup(Vec<NameFilter>),\n\n CustomSpu(Vec<NameFilter>),\n\n Partition(Vec<NameFilter>),\n\n}\n\n\n\nimpl Default for ListRequest {\n\n fn default() -> Self {\n\n Self::Spu(vec![])\n", "file_path": "src/sc-schema/src/objects/list.rs", "rank": 64, "score": 65771.59351565747 }, { "content": "/// Customize System Test\n\npub trait ScTest: Sized {\n\n type ResponseFuture: Send + Future<Output = Result<(), FlvSocketError>>;\n\n\n\n /// environment configuration\n\n fn env_configuration(&self) -> TestGenerator;\n\n\n\n fn topics(&self) -> Vec<(String, Vec<Vec<SpuId>>)>;\n\n\n\n /// main entry point\n\n fn main_test(&self, runner: Arc<ScTestRunner<Self>>) -> Self::ResponseFuture;\n\n}\n", "file_path": "src/sc/src/tests/fixture/mod.rs", "rank": 65, "score": 65771.59351565747 }, { "content": "/// Customize System Test\n\npub trait SpuTest: Sized {\n\n type ResponseFuture: Send + Future<Output = Result<(), FlvSocketError>>;\n\n\n\n /// environment configuration\n\n fn env_configuration(&self) -> TestGenerator;\n\n\n\n /// number of followers\n\n fn followers(&self) -> usize;\n\n\n\n /// replicas. by default, it's empty\n\n fn replicas(&self) -> Vec<ReplicaKey> {\n\n vec![]\n\n }\n\n\n\n /// main entry point\n\n fn main_test(&self, runner: Arc<SpuTestRunner<Self>>) -> Self::ResponseFuture;\n\n}\n", "file_path": "src/spu/src/tests/fixture/mod.rs", "rank": 66, "score": 65771.59351565747 }, { "content": "/// marker trait for List\n\npub trait WatchSpec: Spec {\n\n /// convert to list request with filters\n\n fn into_list_request(epoch: Epoch) -> WatchRequest;\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum WatchRequest {\n\n Topic(Epoch),\n\n Spu(Epoch),\n\n SpuGroup(Epoch),\n\n Partition(Epoch),\n\n}\n\n\n\nimpl Default for WatchRequest {\n\n fn default() -> Self {\n\n Self::Spu(0)\n\n }\n\n}\n\n\n\nimpl Request for WatchRequest {\n", "file_path": "src/sc-schema/src/objects/watch.rs", "rank": 67, "score": 65771.59351565747 }, { "content": "pub fn process_delete_cluster<O>(\n\n _out: std::sync::Arc<O>,\n\n opt: DeleteClusterOpt,\n\n) -> Result<String, CliError>\n\nwhere\n\n O: Terminal,\n\n{\n\n let cluster_name = opt.cluster_name;\n\n\n\n let mut config_file = match ConfigFile::load(None) {\n\n Ok(config_file) => config_file,\n\n Err(e) => {\n\n println!(\"No config can be found: {}\", e);\n\n return Ok(\"\".to_string());\n\n }\n\n };\n\n\n\n let config = config_file.mut_config();\n\n\n\n // Check if the named cluster exists\n", "file_path": "src/cli/src/profile/mod.rs", "rank": 68, "score": 65771.59351565747 }, { "content": "pub trait DeleteSpec: Removable {\n\n /// convert delete key into request\n\n fn into_request<K>(key: K) -> DeleteRequest\n\n where\n\n K: Into<Self::DeleteKey>;\n\n}\n\n\n\n// This can be auto generated by enum derive later\n\n#[derive(Debug)]\n\npub enum DeleteRequest {\n\n Topic(String),\n\n CustomSpu(CustomSpuKey),\n\n SpuGroup(String),\n\n}\n\n\n\nimpl Default for DeleteRequest {\n\n fn default() -> Self {\n\n DeleteRequest::CustomSpu(CustomSpuKey::Id(0))\n\n }\n\n}\n", "file_path": "src/sc-schema/src/objects/delete.rs", "rank": 69, "score": 65771.59351565747 }, { "content": "/// Encode all partitions for a topic in Kf format.\n\npub fn topic_partitions_to_kf_partitions(\n\n partitions: &PartitionLocalStore,\n\n topic: &String,\n\n) -> Vec<MetadataResponsePartition> {\n\n let mut kf_partitions = vec![];\n\n\n\n for (idx, partition) in partitions.topic_partitions(topic).iter().enumerate() {\n\n kf_partitions.push(MetadataResponsePartition {\n\n error_code: KfErrorCode::None,\n\n partition_index: idx as i32,\n\n leader_id: partition.spec.leader,\n\n leader_epoch: 0,\n\n replica_nodes: partition.spec.replicas.clone(),\n\n isr_nodes: partition.status.live_replicas().clone(),\n\n offline_replicas: partition.status.offline_replicas(),\n\n })\n\n }\n\n\n\n kf_partitions\n\n}\n", "file_path": "src/sc/src/services/public_api/metadata/fetch.rs", "rank": 70, "score": 64765.399122423616 }, { "content": "/// Print records based on their type\n\npub fn print_dynamic_records<O>(\n\n out: std::sync::Arc<O>,\n\n topic_name: &str,\n\n response_partitions: &[FetchablePartitionResponse<RecordSet>],\n\n) where\n\n O: Terminal,\n\n{\n\n for r_partition in response_partitions {\n\n if let Some(err) = error_in_header(topic_name, r_partition) {\n\n t_print_cli_err!(out, err);\n\n continue;\n\n }\n\n\n\n for batch in &r_partition.records.batches {\n\n for record in &batch.records {\n\n if let Some(batch_record) = record.get_value().inner_value_ref() {\n\n // TODO: this should be refactored\n\n if let Some(bytes) = record.get_value().inner_value_ref() {\n\n debug!(\"len: {}\", bytes.len());\n\n }\n", "file_path": "src/cli/src/consume/logs_output.rs", "rank": 71, "score": 64726.301358645556 }, { "content": "/// parse message and generate log records\n\npub fn generate_json_records<O>(\n\n out: std::sync::Arc<O>,\n\n topic_name: &str,\n\n response_partitions: &[FetchablePartitionResponse<RecordSet>],\n\n suppress: bool,\n\n) -> Vec<Value>\n\nwhere\n\n O: Terminal,\n\n{\n\n let mut json_records: Vec<Value> = vec![];\n\n\n\n for r_partition in response_partitions {\n\n if let Some(err) = error_in_header(topic_name, r_partition) {\n\n t_print_cli_err!(out, err);\n\n continue;\n\n }\n\n\n\n let mut new_records = partition_to_json_records(&r_partition, suppress);\n\n json_records.append(&mut new_records);\n\n }\n\n\n\n json_records\n\n}\n\n\n", "file_path": "src/cli/src/consume/logs_output.rs", "rank": 72, "score": 64726.301358645556 }, { "content": "pub fn default_convert_from_k8<S>(\n\n k8_obj: K8Obj<S::K8Spec>,\n\n) -> Result<MetadataStoreObject<S, K8MetaItem>, K8ConvertError<S::K8Spec>>\n\nwhere\n\n S: K8ExtendedSpec,\n\n S::IndexKey: TryFrom<String> + Display,\n\n <S::IndexKey as TryFrom<String>>::Error: Debug,\n\n <<S as K8ExtendedSpec>::K8Spec as K8Spec>::Status: Into<S::Status>,\n\n S::K8Spec: Into<S>,\n\n{\n\n let k8_name = k8_obj.metadata.name.clone();\n\n let result: Result<S::IndexKey, _> = k8_name.try_into();\n\n match result {\n\n Ok(key) => {\n\n // convert K8 Spec/Status into Metadata Spec/Status\n\n let local_spec = k8_obj.spec.into();\n\n let local_status = k8_obj.status.into();\n\n\n\n let ctx_item_result: Result<K8MetaItem, _> = k8_obj.metadata.try_into();\n\n match ctx_item_result {\n", "file_path": "src/stream-model/src/store/k8.rs", "rank": 73, "score": 64726.301358645556 }, { "content": "/// parse message and generate partition records\n\npub fn print_binary_records<O>(\n\n out: std::sync::Arc<O>,\n\n topic_name: &str,\n\n response_partitions: &[FetchablePartitionResponse<RecordSet>],\n\n) where\n\n O: Terminal,\n\n{\n\n debug!(\n\n \"printing out binary records: {} records: {}\",\n\n topic_name,\n\n response_partitions.len()\n\n );\n\n let mut printed = false;\n\n for r_partition in response_partitions {\n\n if let Some(err) = error_in_header(topic_name, r_partition) {\n\n t_println!(out, \"{}\", hex_dump_separator());\n\n t_print_cli_err!(out, err);\n\n printed = true;\n\n continue;\n\n }\n", "file_path": "src/cli/src/consume/logs_output.rs", "rank": 74, "score": 64726.301358645556 }, { "content": "/// Return separator for hex dump\n\npub fn hex_dump_separator() -> String {\n\n \"------------------------------------------------------------------------------\\n\".to_owned()\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::bytes_to_hex_dump;\n\n\n\n #[test]\n\n fn test_bytes_to_hex_dump() {\n\n let records: Vec<u8> = vec![\n\n 123, 10, 32, 32, 32, 32, 34, 112, 97, 114, 116, 105, 116, 105, 111, 110, 115, 34, 58,\n\n 32, 91, 10, 32, 32, 32, 32, 32, 32, 32, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, 32,\n\n 32, 32, 32, 32, 34, 105, 100, 34, 58, 32, 48, 44, 10, 32, 32, 32, 32, 32, 32, 32, 32,\n\n 32, 32, 32, 32, 34, 114, 101, 112, 108, 105, 99, 97, 115, 34, 58, 32, 91, 10, 32, 32,\n\n 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 53, 48, 48, 49, 44, 10, 32, 32,\n\n 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 53, 48, 48, 50, 44, 10, 32, 32,\n\n 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 53, 48, 48, 51, 10, 32, 32, 32,\n\n 32, 32, 32, 32, 32, 32, 32, 32, 32, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 125, 10,\n\n 32, 32, 32, 32, 93, 10, 125,\n", "file_path": "src/cli/src/common/hex_dump.rs", "rank": 75, "score": 64726.301358645556 }, { "content": "/// Print records in raw format\n\npub fn print_raw_records<O>(\n\n out: std::sync::Arc<O>,\n\n topic_name: &str,\n\n response_partitions: &[FetchablePartitionResponse<RecordSet>],\n\n) where\n\n O: Terminal,\n\n{\n\n for r_partition in response_partitions {\n\n if let Some(err) = error_in_header(topic_name, r_partition) {\n\n t_print_cli_err!(out, err);\n\n continue;\n\n }\n\n\n\n for batch in &r_partition.records.batches {\n\n for record in &batch.records {\n\n if let Some(value) = record.get_value().inner_value_ref() {\n\n let str_value = std::str::from_utf8(value).unwrap();\n\n t_println!(out, \"{}\", str_value);\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n\n// -----------------------------------\n\n// Utilities\n\n// -----------------------------------\n\n\n", "file_path": "src/cli/src/consume/logs_output.rs", "rank": 76, "score": 64726.301358645556 }, { "content": "/// Process server based on output type\n\npub fn format_spu_response_output<O>(\n\n out: std::sync::Arc<O>,\n\n spus: ListSpus,\n\n output_type: OutputType,\n\n) -> Result<(), CliError>\n\nwhere\n\n O: Terminal,\n\n{\n\n if !spus.is_empty() {\n\n out.render_list(&spus, output_type)?;\n\n } else {\n\n t_println!(out, \"no spu\");\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\nimpl TableOutputHandler for ListSpus {\n\n /// table header implementation\n\n fn header(&self) -> Row {\n", "file_path": "src/cli/src/spu/display.rs", "rank": 77, "score": 64726.301358645556 }, { "content": "/// Print records in text format\n\npub fn print_text_records<O>(\n\n out: std::sync::Arc<O>,\n\n topic_name: &str,\n\n response_partitions: &[FetchablePartitionResponse<RecordSet>],\n\n suppress: bool,\n\n) where\n\n O: Terminal,\n\n{\n\n debug!(\"processing text record: {:#?}\", response_partitions);\n\n\n\n for r_partition in response_partitions {\n\n if let Some(err) = error_in_header(topic_name, r_partition) {\n\n t_print_cli_err!(out, err);\n\n continue;\n\n }\n\n\n\n for batch in &r_partition.records.batches {\n\n for record in &batch.records {\n\n if record.get_value().inner_value_ref().is_some() {\n\n if record.get_value().is_binary() {\n", "file_path": "src/cli/src/consume/logs_output.rs", "rank": 78, "score": 64726.301358645556 }, { "content": "/// trait to convert type object to our spec\n\npub trait K8ExtendedSpec: Spec {\n\n type K8Spec: K8Spec;\n\n type K8Status: K8Status;\n\n\n\n fn convert_from_k8(\n\n k8_obj: K8Obj<Self::K8Spec>,\n\n ) -> Result<MetadataStoreObject<Self, K8MetaItem>, K8ConvertError<Self::K8Spec>>;\n\n}\n\n\n", "file_path": "src/stream-model/src/store/k8.rs", "rank": 79, "score": 64726.301358645556 }, { "content": "/// Generates a random authorization token\n\npub fn generate_auth_token() -> (String, String) {\n\n const CHARSET: &[u8] = b\"abcdefghijklmnopqrstuvwxyz\\\n\n 0123456789\";\n\n\n\n const ID_SIZE: usize = 6;\n\n let token_name: String = (0..ID_SIZE)\n\n .map(|_| {\n\n let idx = thread_rng().gen_range(0, CHARSET.len());\n\n // This is safe because `idx` is in range of `CHARSET`\n\n char::from(unsafe { *CHARSET.get_unchecked(idx) })\n\n })\n\n .collect();\n\n\n\n const SECRET_SIZE: usize = 16;\n\n let token_secret: String = (0..SECRET_SIZE)\n\n .map(|_| {\n\n let idx = thread_rng().gen_range(0, CHARSET.len());\n\n // This is safe because `idx` is in range of `CHARSET`\n\n char::from(unsafe { *CHARSET.get_unchecked(idx) })\n\n })\n\n .collect();\n\n\n\n (token_name, token_secret)\n\n}\n\n\n\n#[allow(dead_code)]\n", "file_path": "src/utils/src/generators.rs", "rank": 80, "score": 64063.721653155764 }, { "content": "pub fn main_loop(opt: SpuOpt) {\n\n use std::time::Duration;\n\n\n\n use fluvio_future::task::run_block_on;\n\n use fluvio_future::timer::sleep;\n\n // parse configuration (program exits on error)\n\n let (spu_config, tls_acceptor_option) = opt.process_spu_cli_or_exit();\n\n\n\n println!(\"starting spu server (id:{})\", spu_config.id);\n\n\n\n run_block_on(async move {\n\n let (_ctx, internal_server, public_server) =\n\n create_services(spu_config.clone(), true, true);\n\n\n\n let _public_shutdown = internal_server.unwrap().run();\n\n let _private_shutdown = public_server.unwrap().run();\n\n\n\n if let Some(tls_config) = tls_acceptor_option {\n\n proxy::start_proxy(spu_config, tls_config).await;\n\n }\n\n\n\n println!(\"SPU Version: {} started successfully\", VERSION);\n\n\n\n // infinite loop\n\n loop {\n\n sleep(Duration::from_secs(60)).await;\n\n }\n\n });\n\n}\n\n\n", "file_path": "src/spu/src/start.rs", "rank": 81, "score": 64063.721653155764 }, { "content": "#[async_trait]\n\npub trait ReplicaLeader: Send + Sync {\n\n type OffsetPartitionResponse: PartitionOffset;\n\n type Client: Client;\n\n\n\n fn config(&self) -> &ReplicaLeaderConfig;\n\n\n\n \n\n fn topic(&self) -> &str {\n\n &self.config().topic()\n\n }\n\n\n\n fn partition(&self) -> i32 {\n\n self.config().partition()\n\n }\n\n\n\n fn addr(&self) -> &str;\n\n\n\n fn mut_client(&mut self) -> &mut Self::Client;\n\n\n\n // fetch offsets for\n", "file_path": "src/client/src/replica/leader.rs", "rank": 82, "score": 64063.721653155764 }, { "content": "#[derive(Debug)]\n\nstruct ScopeBindings(HashMap<String, Vec<String>>);\n\n\n\nimpl ScopeBindings {\n\n pub fn load(scope_binding_file_path: &Path) -> Result<Self, IoError> {\n\n let file = std::fs::read_to_string(scope_binding_file_path)?;\n\n let scope_bindings = Self(serde_json::from_str(&file)?);\n\n debug!(\"scope bindings loaded {:?}\", scope_bindings);\n\n Ok(scope_bindings)\n\n }\n\n pub fn get_scopes(&self, principal: &str) -> Vec<String> {\n\n trace!(\"getting scopes for principal {:?}\", principal);\n\n if let Some(scopes) = self.0.get(principal) {\n\n trace!(\"scopes found for principal {:?}: {:?}\", principal, scopes);\n\n scopes.clone()\n\n } else {\n\n trace!(\"scopes not found for principal {:?}\", principal);\n\n Vec::new()\n\n }\n\n }\n\n}\n", "file_path": "src/auth/src/x509/authenticator.rs", "rank": 83, "score": 63946.701162450874 }, { "content": "#[async_trait]\n\npub trait SpuLocalStorePolicy<C>\n\nwhere\n\n C: MetadataItem,\n\n{\n\n async fn online_status(&self) -> HashSet<SpuId>;\n\n\n\n async fn online_spu_count(&self) -> i32;\n\n\n\n async fn spu_used_for_replica(&self) -> i32;\n\n\n\n async fn online_spu_ids(&self) -> Vec<i32>;\n\n\n\n async fn spu_ids(&self) -> Vec<i32>;\n\n\n\n async fn online_spus(&self) -> Vec<SpuMetadata<C>>;\n\n\n\n async fn custom_spus(&self) -> Vec<SpuMetadata<C>>;\n\n\n\n async fn get_by_id(&self, id: i32) -> Option<SpuMetadata<C>>;\n\n\n", "file_path": "src/controlplane-metadata/src/spu/store.rs", "rank": 84, "score": 63733.46783674272 }, { "content": "#[async_trait]\n\npub trait TopicLocalStorePolicy<C>\n\nwhere\n\n C: MetadataItem,\n\n{\n\n async fn table_fmt(&self) -> String;\n\n}\n\n\n\n#[async_trait]\n\nimpl<C> TopicLocalStorePolicy<C> for TopicLocalStore<C>\n\nwhere\n\n C: MetadataItem + Send + Sync,\n\n{\n\n async fn table_fmt(&self) -> String {\n\n let mut table = String::new();\n\n\n\n let topic_hdr = format!(\n\n \"{n:<18} {t:<8} {p:<5} {s:<5} {g:<8} {l:<14} {m:<10} {r}\\n\",\n\n n = \"TOPIC\",\n\n t = \"TYPE\",\n\n p = \"PART\",\n", "file_path": "src/controlplane-metadata/src/topic/store.rs", "rank": 85, "score": 63733.46783674272 }, { "content": "#[async_trait]\n\npub trait PartitionLocalStorePolicy<C>\n\nwhere\n\n C: MetadataItem,\n\n{\n\n async fn names(&self) -> Vec<ReplicaKey>;\n\n\n\n async fn topic_partitions(&self, topic: &str) -> Vec<PartitionMetadata<C>>;\n\n\n\n /// find all partitions that has spu in the replicas\n\n async fn partition_spec_for_spu(&self, target_spu: i32) -> Vec<(ReplicaKey, PartitionSpec)>;\n\n\n\n async fn count_topic_partitions(&self, topic: &str) -> i32;\n\n\n\n // return partitions that belong to this topic\n\n async fn topic_partitions_list(&self, topic: &str) -> Vec<ReplicaKey>;\n\n\n\n async fn table_fmt(&self) -> String;\n\n\n\n /// replica msg for target spu\n\n async fn replica_for_spu(&self, target_spu: SpuId) -> Vec<Replica>;\n", "file_path": "src/controlplane-metadata/src/partition/store.rs", "rank": 86, "score": 63733.46783674272 }, { "content": "pub trait KeyFilter<V: ?Sized> {\n\n fn filter(&self, value: &V) -> bool;\n\n}\n\n\n\nimpl KeyFilter<str> for str {\n\n fn filter(&self, value: &str) -> bool {\n\n value.contains(self)\n\n }\n\n}\n\n\n\nimpl KeyFilter<str> for Vec<String> {\n\n fn filter(&self, value: &str) -> bool {\n\n if self.is_empty() {\n\n return true;\n\n }\n\n self.iter().filter(|key| key.filter(value)).count() > 0\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/stream-model/src/store/filter.rs", "rank": 87, "score": 63018.42949614384 }, { "content": "#[async_trait]\n\npub trait TopicMd<C: MetadataItem> {\n\n async fn create_new_partitions(\n\n &self,\n\n partition_store: &PartitionLocalStore<C>,\n\n ) -> Vec<PartitionMetadata<C>>;\n\n}\n\n\n\n#[async_trait]\n\nimpl<C: MetadataItem> TopicMd<C> for TopicMetadata<C>\n\nwhere\n\n C: MetadataItem + Send + Sync,\n\n{\n\n /// create new partitions from my replica map if it doesn't exists\n\n /// from partition store\n\n async fn create_new_partitions(\n\n &self,\n\n partition_store: &PartitionLocalStore<C>,\n\n ) -> Vec<PartitionMetadata<C>> {\n\n let mut partitions = vec![];\n\n for (idx, replicas) in self.status.replica_map.iter() {\n", "file_path": "src/controlplane-metadata/src/topic/store.rs", "rank": 88, "score": 62025.595974241005 }, { "content": "pub trait SpuMd<C: MetadataItem> {\n\n fn quick<J>(spu: (J, i32, bool, Option<String>)) -> SpuMetadata<C>\n\n where\n\n J: Into<String>;\n\n}\n\n\n\nimpl<C: MetadataItem> SpuMd<C> for SpuMetadata<C> {\n\n fn quick<J>(spu: (J, i32, bool, Option<String>)) -> SpuMetadata<C>\n\n where\n\n J: Into<String>,\n\n {\n\n let mut spec = SpuSpec::default();\n\n spec.id = spu.1;\n\n spec.rack = spu.3;\n\n\n\n let mut status = SpuStatus::default();\n\n if spu.2 {\n\n status.set_online();\n\n }\n\n\n\n SpuMetadata::new(spu.0.into(), spec, status)\n\n }\n\n}\n\n\n", "file_path": "src/controlplane-metadata/src/spu/store.rs", "rank": 89, "score": 62025.595974241005 }, { "content": "pub trait PartitionMd<C: MetadataItem> {\n\n fn with_replicas(key: ReplicaKey, replicas: Vec<SpuId>) -> Self;\n\n\n\n fn quick<S: Into<String>>(partition: ((S, i32), Vec<i32>)) -> Self;\n\n}\n\n\n\nimpl<C: MetadataItem> PartitionMd<C> for PartitionMetadata<C> {\n\n /// create new partition with replica map.\n\n /// first element of replicas is leader\n\n fn with_replicas(key: ReplicaKey, replicas: Vec<SpuId>) -> Self {\n\n let spec: PartitionSpec = replicas.into();\n\n Self::new(key, spec, PartitionStatus::default())\n\n }\n\n\n\n fn quick<S: Into<String>>(partition: ((S, i32), Vec<i32>)) -> Self {\n\n let (replica_key, replicas) = partition;\n\n Self::with_replicas(replica_key.into(), replicas)\n\n }\n\n}\n\n\n", "file_path": "src/controlplane-metadata/src/partition/store.rs", "rank": 90, "score": 62025.595974241005 }, { "content": "pub fn main_k8_loop(opt: ScOpt) {\n\n use std::time::Duration;\n\n\n\n use fluvio_future::task::run_block_on;\n\n use fluvio_future::timer::sleep;\n\n\n\n use crate::init::start_main_loop;\n\n // parse configuration (program exits on error)\n\n let ((sc_config, auth_policy), k8_config, tls_option) = opt.parse_cli_or_exit();\n\n\n\n println!(\"starting sc server with k8: {}\", VERSION);\n\n\n\n run_block_on(async move {\n\n // init k8 service\n\n let k8_client = new_shared(k8_config).expect(\"problem creating k8 client\");\n\n let namespace = sc_config.namespace.clone();\n\n let ctx = start_main_loop((sc_config.clone(), auth_policy), k8_client.clone()).await;\n\n\n\n run_k8_operators(\n\n namespace.clone(),\n", "file_path": "src/sc/src/k8/mod.rs", "rank": 91, "score": 62025.595974241005 }, { "content": "fn check_create_permission(resource: &str) -> Result<bool, CheckError> {\n\n let check_command = Command::new(\"kubectl\")\n\n .arg(\"auth\")\n\n .arg(\"can-i\")\n\n .arg(\"create\")\n\n .arg(resource)\n\n .output()?;\n\n let res =\n\n String::from_utf8(check_command.stdout).map_err(|_| CheckError::FetchPermissionError)?;\n\n Ok(res.trim() == \"yes\")\n\n}\n", "file_path": "src/cluster/src/check.rs", "rank": 92, "score": 61923.385460352496 }, { "content": "pub fn get_fluvio() -> Result<Command, IoError> {\n\n get_binary(\"fluvio\")\n\n}\n\n\n", "file_path": "src/utils/src/bin.rs", "rank": 93, "score": 61527.68260092933 }, { "content": "/// Detects the target triple of the current build and returns\n\n/// the name of a compatible build target on packages.fluvio.io.\n\n///\n\n/// Returns `Some(Target)` if there is a compatible target, or\n\n/// `None` if this target is unsupported or has no compatible target.\n\npub fn package_target() -> Result<Target, Error> {\n\n let target = PACKAGE_TARGET.parse()?;\n\n Ok(target)\n\n}\n\n\n\n#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]\n\n#[allow(non_camel_case_types)]\n\npub enum Target {\n\n #[serde(rename = \"x86_64-apple-darwin\")]\n\n X86_64AppleDarwin,\n\n #[serde(rename = \"x86_64-unknown-linux-musl\")]\n\n X86_64UnknownLinuxMusl,\n\n}\n\n\n\nimpl Target {\n\n pub fn as_str(&self) -> &str {\n\n match self {\n\n Self::X86_64AppleDarwin => \"x86_64-apple-darwin\",\n\n Self::X86_64UnknownLinuxMusl => \"x86_64-unknown-linux-musl\",\n\n }\n", "file_path": "src/package-index/src/target.rs", "rank": 94, "score": 61527.68260092933 }, { "content": "/// handle watch request by spawning watch controller for each store\n\npub fn handle_watch_request<T, AC>(\n\n request: RequestMessage<WatchRequest>,\n\n auth_ctx: &AuthServiceContext<AC>,\n\n sink: InnerExclusiveFlvSink<T>,\n\n end_event: Arc<Event>,\n\n) where\n\n T: AsyncWrite + AsyncRead + Unpin + Send + ZeroCopyWrite + 'static,\n\n{\n\n debug!(\"handling watch request\");\n\n let (header, req) = request.get_header_request();\n\n\n\n match req {\n\n WatchRequest::Topic(_) => unimplemented!(),\n\n WatchRequest::Spu(epoch) => WatchController::<T, SpuSpec>::update(\n\n epoch,\n\n sink,\n\n end_event,\n\n auth_ctx.global_ctx.spus().clone(),\n\n header,\n\n ),\n", "file_path": "src/sc/src/services/public_api/watch.rs", "rank": 95, "score": 61081.36874972537 }, { "content": "#[allow(unused)]\n\npub fn open_log(prefix: &str) -> (File, File) {\n\n let output = File::create(format!(\"/tmp/flv_{}.out\", prefix)).expect(\"log file\");\n\n let error = File::create(format!(\"/tmp/flv_{}.log\", prefix)).expect(\"err file\");\n\n\n\n (output, error)\n\n}\n\n\n", "file_path": "src/utils/src/bin.rs", "rank": 96, "score": 60215.13007400773 }, { "content": "pub fn start_internal_server(ctx: SharedContext) {\n\n info!(\"starting internal services\");\n\n\n\n let addr = ctx.config().private_endpoint.clone();\n\n let server = FlvApiServer::new(addr, ctx, ScInternalService::new());\n\n server.run();\n\n}\n", "file_path": "src/sc/src/services/private_api/mod.rs", "rank": 97, "score": 60182.26367113434 }, { "content": "#[allow(clippy::needless_range_loop)]\n\npub fn bytes_to_hex_dump(record: &[u8]) -> String {\n\n let cols = 16;\n\n let record_cnt = record.len();\n\n let mut result = String::new();\n\n let mut collector = String::new();\n\n\n\n for row_idx in 0..record_cnt {\n\n // colunn index\n\n if row_idx % cols == 0 {\n\n result.push_str(&format!(\"{:08x}\", row_idx));\n\n }\n\n\n\n // spacing half way\n\n if row_idx % (cols / 2) == 0 {\n\n result.push_str(\" \");\n\n }\n\n\n\n // convert and add character to collector\n\n collector.push_str(&byte_to_string(&record[row_idx]));\n\n\n", "file_path": "src/cli/src/common/hex_dump.rs", "rank": 98, "score": 59590.62185451086 }, { "content": "pub trait BatchRecords: Default + Debug + Encoder + Decoder {\n\n /// how many bytes does record wants to process\n\n fn remainder_bytes(&self, remainder: usize) -> usize {\n\n remainder\n\n }\n\n}\n\n\n\nimpl BatchRecords for DefaultBatchRecords {}\n\n\n\n/// size of the offset and length\n\npub const BATCH_PREAMBLE_SIZE: usize = size_of::<Offset>() // Offset\n\n + size_of::<i32>(); // i32\n\n\n\n#[derive(Default, Debug)]\n\npub struct Batch<R>\n\nwhere\n\n R: BatchRecords,\n\n{\n\n pub base_offset: Offset,\n\n pub batch_len: i32, // only for decoding\n", "file_path": "src/dataplane-protocol/src/batch.rs", "rank": 99, "score": 59222.29655210489 } ]
Rust
eventually-redis/tests/store.rs
J3A/eventually-rs
866a471479a8c2781966339287a4e57ca9838b38
use std::sync::Arc; use eventually::inmemory::Projector; use eventually::store::{Expected, Persisted, Select}; use eventually::sync::RwLock; use eventually::{EventStore, EventSubscriber, Projection}; use eventually_redis::{Builder, EventStore as RedisEventStore}; use async_trait::async_trait; use futures::stream::TryStreamExt; use serde::{Deserialize, Serialize}; use testcontainers::core::Docker; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] enum Event { A, B, C, } #[tokio::test] async fn it_works() { let docker = testcontainers::clients::Cli::default(); let redis_image = testcontainers::images::redis::Redis::default(); let node = docker.run(redis_image); let dsn = format!("redis://127.0.0.1:{}/", node.get_host_port(6379).unwrap()); let client = redis::Client::open(dsn).expect("failed to connect to Redis"); let builder = Builder::new(client) .stream_page_size(128) .source_name("test-stream"); let builder_clone = builder.clone(); tokio::spawn(async move { builder_clone .build_subscriber::<String, Event>() .subscribe_all() .try_for_each(|_event| async { Ok(()) }) .await .unwrap(); }); let mut store: RedisEventStore<String, Event> = builder .build_store() .await .expect("failed to create redis connection"); for chunk in 0..1000 { store .append( "test-source-1".to_owned(), Expected::Any, vec![Event::A, Event::B, Event::C], ) .await .unwrap(); store .append( "test-source-2".to_owned(), Expected::Exact(chunk * 2), vec![Event::B, Event::A], ) .await .unwrap(); } let now = std::time::SystemTime::now(); assert_eq!( 5000usize, store .stream_all(Select::All) .await .unwrap() .try_fold(0usize, |acc, _x| async move { Ok(acc + 1) }) .await .unwrap() ); println!("Stream $all took {:?}", now.elapsed().unwrap()); assert_eq!( 3000usize, store .stream("test-source-1".to_owned(), Select::All) .await .unwrap() .try_fold(0usize, |acc, _x| async move { Ok(acc + 1) }) .await .unwrap() ); assert_eq!( 2000usize, store .stream("test-source-2".to_owned(), Select::All) .await .unwrap() .try_fold(0usize, |acc, _x| async move { Ok(acc + 1) }) .await .unwrap() ); } #[tokio::test] async fn it_creates_persistent_subscription_successfully() { let docker = testcontainers::clients::Cli::default(); let redis_image = testcontainers::images::redis::Redis::default(); let node = docker.run(redis_image); let dsn = format!("redis://127.0.0.1:{}/", node.get_host_port(6379).unwrap()); let client = redis::Client::open(dsn).expect("failed to connect to Redis"); let events_count: usize = 3; let builder = Builder::new(client) .stream_page_size(128) .source_name("test-stream"); let builder_clone = builder.clone(); let subscription = builder .build_persistent_subscription::<String, Event>("subscription") .await .unwrap(); builder .build_persistent_subscription::<String, Event>("subscription") .await .unwrap(); #[derive(Debug, Default)] struct Counter(usize); #[async_trait] impl Projection for Counter { type SourceId = String; type Event = Event; type Error = std::convert::Infallible; async fn project( &mut self, _event: Persisted<Self::SourceId, Self::Event>, ) -> Result<(), Self::Error> { self.0 += 1; Ok(()) } } let counter = Arc::new(RwLock::new(Counter::default())); let mut projector = Projector::new(counter.clone(), subscription); tokio::spawn(async move { projector.run().await.unwrap(); }); let mut store = builder_clone .build_store::<String, Event>() .await .expect("create event store"); for i in 0..events_count { store .append( format!("test-subscription-{}", i), Expected::Any, vec![Event::A, Event::B, Event::C], ) .await .unwrap(); } let size = store .stream_all(Select::All) .await .unwrap() .try_fold(0usize, |acc, _x| async move { Ok(acc + 1) }) .await .unwrap(); tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; assert_eq!(size, counter.read().await.0); }
use std::sync::Arc; use eventually::inmemory::Projector; use eventually::store::{Expected, Persisted, Select}; use eventually::sync::RwLock; use eventually::{EventStore, EventSubscriber, Projection}; use eventually_redis::{Builder, EventStore as RedisEventStore}; use async_trait::async_trait; use futures::stream::TryStreamExt; use serde::{Deserialize, Serialize}; use testcontainers::core::Docker; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] enum Event { A, B, C, } #[tokio::test] async fn it_works() { let docker = testcontainers::clients::Cli::default(); let redis_image = testcontainers::images::redis::Redis::default(); let node = docker.run(redis_image); let dsn = format!("redis://127.0.0.1:{}/", node.get_host_port(6379).unwrap()); let client = redis::Client::open(dsn).expect("failed to connect to Redis"); let builder = Builder::new(client) .stream_page_size(128) .source_name("test-stream"); let builder_clone = builder.clone(); tokio::spawn(async move { builder_clone .build_subscriber::<String, Event>() .subscribe_all() .try_for_each(|_event| async { Ok(()) }) .await .unwrap(); }); let mut store: RedisEventStore<String, Event> = builder .build_store() .await .expect("failed to create redis connection"); for chunk in 0..1000 { store .append( "test-source-1".to_owned(), Expected::Any, vec![Event::A, Event::B, Event::C], ) .await .unwrap(); store .append( "test-source-2".to_owned(), Expected::Exact(chunk * 2), vec![Event::B, Event::A], ) .await .unwrap(); } let now = std::time::SystemTime::now(); assert_eq!( 5000usize, store .stream_all(Select::All) .await .unwrap() .try_fold(0usize, |acc, _x| async move { Ok(acc + 1) }) .await .unwrap() ); println!("Stream $all took {:?}", now.elapsed().unwrap()); assert_eq!( 3000usize, store .stream("test-source-1".to_owned(), Select::All) .await .unwrap() .try_fold(0usize, |acc, _x| async move { Ok(acc + 1) }) .await .unwrap() ); assert_eq!( 2000usize, store .stream("test-source-2".to_owned(), Select::All) .await .unwrap() .try_fold(0usize, |acc, _x| async move { Ok(acc + 1) }) .await .unwrap() ); } #[tokio::test] async fn it_creates_persistent_subscription_successfully() { let docker = testcontainers::clients::Cli::default(); let redis_image = testcontainers::images::redis::Redis::default(); let node = docker.run(redis_image); let dsn = for
mat!("redis://127.0.0.1:{}/", node.get_host_port(6379).unwrap()); let client = redis::Client::open(dsn).expect("failed to connect to Redis"); let events_count: usize = 3; let builder = Builder::new(client) .stream_page_size(128) .source_name("test-stream"); let builder_clone = builder.clone(); let subscription = builder .build_persistent_subscription::<String, Event>("subscription") .await .unwrap(); builder .build_persistent_subscription::<String, Event>("subscription") .await .unwrap(); #[derive(Debug, Default)] struct Counter(usize); #[async_trait] impl Projection for Counter { type SourceId = String; type Event = Event; type Error = std::convert::Infallible; async fn project( &mut self, _event: Persisted<Self::SourceId, Self::Event>, ) -> Result<(), Self::Error> { self.0 += 1; Ok(()) } } let counter = Arc::new(RwLock::new(Counter::default())); let mut projector = Projector::new(counter.clone(), subscription); tokio::spawn(async move { projector.run().await.unwrap(); }); let mut store = builder_clone .build_store::<String, Event>() .await .expect("create event store"); for i in 0..events_count { store .append( format!("test-subscription-{}", i), Expected::Any, vec![Event::A, Event::B, Event::C], ) .await .unwrap(); } let size = store .stream_all(Select::All) .await .unwrap() .try_fold(0usize, |acc, _x| async move { Ok(acc + 1) }) .await .unwrap(); tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; assert_eq!(size, counter.read().await.0); }
function_block-function_prefixed
[ { "content": "#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\n\nenum Event {\n\n A,\n\n B,\n\n C,\n\n}\n\n\n\n#[tokio::test]\n\nasync fn different_types_can_share_id() {\n\n let docker = testcontainers::clients::Cli::default();\n\n let postgres_image = testcontainers::images::postgres::Postgres::default();\n\n let node = docker.run(postgres_image);\n\n\n\n let dsn = format!(\n\n \"postgres://postgres:postgres@localhost:{}/postgres\",\n\n node.get_host_port(5432).unwrap()\n\n );\n\n\n\n let pg_manager =\n\n bb8_postgres::PostgresConnectionManager::new_from_stringlike(&dsn, tokio_postgres::NoTls)\n\n .expect(\"Could not parse the dsn string\");\n", "file_path": "eventually-postgres/tests/store.rs", "rank": 1, "score": 120221.4145516823 }, { "content": "fn into_persisted_events<Id, T>(\n\n last_version: u32,\n\n id: Id,\n\n events: Vec<T>,\n\n) -> Vec<EventBuilderWithVersion<Id, T>>\n\nwhere\n\n Id: Clone,\n\n{\n\n events\n\n .into_iter()\n\n .enumerate()\n\n .map(|(i, event)| Persisted::from(id.clone(), event).version(last_version + (i as u32) + 1))\n\n .collect()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{ConflictError, EventStore as InMemoryStore};\n\n\n\n use std::cell::RefCell;\n", "file_path": "eventually-util/src/inmemory/store.rs", "rank": 2, "score": 110570.68416383068 }, { "content": "#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\n\nenum Event {\n\n A,\n\n B,\n\n C,\n\n}\n\n\n\n#[tokio::test]\n\nasync fn subscribe_all_works() {\n\n let docker = testcontainers::clients::Cli::default();\n\n let postgres_image = testcontainers::images::postgres::Postgres::default();\n\n let node = docker.run(postgres_image);\n\n\n\n let dsn = format!(\n\n \"postgres://postgres:postgres@localhost:{}/postgres\",\n\n node.get_host_port(5432).unwrap()\n\n );\n\n let pg_manager =\n\n bb8_postgres::PostgresConnectionManager::new_from_stringlike(&dsn, tokio_postgres::NoTls)\n\n .expect(\"Could not parse the dsn string\");\n\n let pool = bb8::Pool::builder()\n", "file_path": "eventually-postgres/tests/subscriber.rs", "rank": 3, "score": 93822.49288782704 }, { "content": "CREATE OR REPLACE PROCEDURE append_to_store(\n\n aggregate_type TEXT,\n\n aggregate_id TEXT,\n\n current_version INTEGER,\n\n perform_version_check BOOLEAN,\n\n events JSONB[],\n\n INOUT aggregate_version INTEGER DEFAULT NULL,\n\n INOUT sequence_number BIGINT DEFAULT NULL\n\n) AS $$\n\nDECLARE\n\n \"event\" JSONB;\n\nBEGIN\n\n\n\n -- Retrieve the global offset value from the aggregate_type.\n\n PERFORM FROM aggregate_types WHERE id = aggregate_type;\n\n IF NOT FOUND THEN\n\n RAISE EXCEPTION 'invalid aggregate type provided: %', aggregate_type;\n\n END IF;\n\n\n\n -- Retrieve the latest aggregate version for the specified aggregate id.\n", "file_path": "eventually-postgres/src/migrations/V3__append_to_store.sql", "rank": 4, "score": 85037.4999299143 }, { "content": "local stream_type = KEYS[1]\n\nlocal source_id = KEYS[2]\n\nlocal expected_version = tonumber(ARGV[1])\n\n\n\nlocal source_stream = string.format(\"%s.%s\", stream_type, source_id)\n\nlocal current_version = tonumber(redis.call(\"XLEN\", source_stream))\n\nlocal last_version = current_version\n\nlocal next_sequence_number = redis.call(\"XLEN\", stream_type)\n\n\n\n-- Perform optimistic concurrency check over the expected version\n\n-- specified by the client.\n\nif expected_version > -1 and expected_version ~= current_version then\n\n return redis.error_reply(\"expected version: \" .. expected_version .. \", current version: \" .. current_version)\n\nend\n\n\n\n-- Insert all the events passed to the script.\n\nfor i, event in pairs({unpack(ARGV, 2)}) do\n\n local version = current_version + i -- Versioning starts from 1.\n\n local sequence_number = next_sequence_number + i - 1 -- Sequence number from 0.\n\n\n", "file_path": "eventually-redis/src/append_to_store.lua", "rank": 5, "score": 84068.45981439101 }, { "content": " -- First, it adds the event to the source-related event stream.\n\n redis.call(\n\n \"XADD\",\n\n source_stream,\n\n string.format(\"%d-1\", version),\n\n \"event\", event,\n\n \"sequence_number\", sequence_number\n\n )\n\n\n\n -- Second, it adds the event to the $all event stream.\n\n redis.call(\n\n \"XADD\",\n\n stream_type,\n\n string.format(\"%d-1\", sequence_number),\n\n \"source_id\", source_id,\n\n \"event\", event,\n\n \"version\", version\n\n )\n\n\n\n -- Publish the message of the newly-added event for interested subscribers.\n", "file_path": "eventually-redis/src/append_to_store.lua", "rank": 6, "score": 84068.34415579509 }, { "content": " -- Since \"PUBLISH\" only works with strings, format in JSON string.\n\n redis.call(\n\n \"PUBLISH\",\n\n stream_type,\n\n string.format(\n\n \"{\\\"source_id\\\":\\\"%s\\\",\\\"sequence_number\\\":%d,\\\"version\\\":%d,\\\"event\\\":%s}\",\n\n source_id, sequence_number, version, event -- event is supposed to be JSON already.\n\n )\n\n )\n\n\n\n last_version = version\n\nend\n\n\n\n-- Return the latest version computed for the source.\n\nreturn last_version\n", "file_path": "eventually-redis/src/append_to_store.lua", "rank": 7, "score": 84067.0951283754 }, { "content": "CREATE TABLE events (\n\n aggregate_id TEXT NOT NULL,\n\n aggregate_type TEXT NOT NULL,\n\n \"version\" INTEGER NOT NULL,\n\n sequence_number BIGINT NOT NULL DEFAULT nextval('events_number_seq'),\n\n \"event\" JSONB NOT NULL,\n\n\n\n CONSTRAINT unique_sequence UNIQUE(sequence_number),\n\n PRIMARY KEY (aggregate_id, aggregate_type, \"version\"),\n\n -- Remove all the events of the aggregate in case of delete.\n\n FOREIGN KEY (aggregate_id, aggregate_type) REFERENCES aggregates(id, aggregate_type_id) ON DELETE CASCADE\n\n);\n", "file_path": "eventually-postgres/src/migrations/V1__event_store_tables.sql", "rank": 8, "score": 78762.64525274135 }, { "content": "CREATE SEQUENCE events_number_seq AS BIGINT MINVALUE 0;\n", "file_path": "eventually-postgres/src/migrations/V1__event_store_tables.sql", "rank": 9, "score": 69795.7726067813 }, { "content": "CREATE TABLE aggregates (\n\n id TEXT NOT NULL,\n\n aggregate_type_id TEXT NOT NULL,\n\n \"version\" INTEGER NOT NULL DEFAULT 0,\n\n\n\n PRIMARY KEY (id, aggregate_type_id),\n\n -- Remove all aggregates in case the aggregate type is deleted.\n\n FOREIGN KEY (aggregate_type_id) REFERENCES aggregate_types(id) ON DELETE CASCADE\n\n);\n\n\n", "file_path": "eventually-postgres/src/migrations/V1__event_store_tables.sql", "rank": 10, "score": 69229.68138264048 }, { "content": "CREATE TABLE aggregate_types (\n\n id TEXT PRIMARY KEY,\n\n \"offset\" BIGINT NOT NULL DEFAULT -1\n\n);\n\n\n", "file_path": "eventually-postgres/src/migrations/V1__event_store_tables.sql", "rank": 11, "score": 66765.06026320886 }, { "content": "/// An Event Store is an append-only, ordered list of\n\n/// [`Event`](super::aggregate::Aggregate::Event)s for a certain \"source\" --\n\n/// e.g. an [`Aggregate`](super::aggregate::Aggregate).\n\npub trait EventStore {\n\n /// Type of the Source id, typically an\n\n /// [`AggregateId`](super::aggregate::AggregateId).\n\n type SourceId: Eq;\n\n\n\n /// Event to be stored in the [`EventStore`], typically an\n\n /// [`Aggregate::Event`](super::aggregate::Aggregate::Event).\n\n type Event;\n\n\n\n /// Possible errors returned by the [`EventStore`] when requesting\n\n /// operations.\n\n type Error: AppendError;\n\n\n\n /// Appends a new list of [`Event`](EventStore::Event)s to the Event Store,\n\n /// for the Source entity specified by\n\n /// [`SourceId`](EventStore::SourceId).\n\n ///\n\n /// `append` is a transactional operation: it either appends all the events,\n\n /// or none at all and returns an [`AppendError`].\n\n ///\n", "file_path": "eventually-core/src/store.rs", "rank": 12, "score": 59475.46870015897 }, { "content": "use std::convert::TryFrom;\n\nuse std::fmt::{Debug, Display};\n\n\n\nuse eventually::store::{\n\n AppendError, EventStream as StoreEventStream, Expected, Persisted, Select,\n\n};\n\n\n\nuse futures::future::BoxFuture;\n\nuse futures::stream::{StreamExt, TryStreamExt};\n\n\n\nuse lazy_static::lazy_static;\n\n\n\nuse redis::RedisError;\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::stream;\n\n\n\nstatic APPEND_TO_STORE_SOURCE: &str = std::include_str!(\"append_to_store.lua\");\n\n\n", "file_path": "eventually-redis/src/store.rs", "rank": 21, "score": 57363.6067466769 }, { "content": " Select::All => 0,\n\n Select::From(v) => v as usize,\n\n },\n\n );\n\n\n\n Ok(paginator\n\n .map_err(StoreError::Stream)\n\n .and_then(|entry| async move {\n\n Persisted::<Id, Event>::try_from(stream::ToPersisted::from(entry))\n\n .map_err(StoreError::DecodeEvents)\n\n })\n\n .boxed())\n\n };\n\n\n\n Box::pin(fut)\n\n }\n\n\n\n fn remove(&mut self, _id: Self::SourceId) -> BoxFuture<StoreResult<()>> {\n\n unimplemented!()\n\n }\n\n}\n", "file_path": "eventually-redis/src/store.rs", "rank": 22, "score": 57362.7629862449 }, { "content": " Expected::Exact(v) => v as i64,\n\n })\n\n .arg(events)\n\n .invoke_async(&mut self.conn)\n\n .await\n\n .unwrap())\n\n };\n\n\n\n Box::pin(fut)\n\n }\n\n\n\n fn stream(\n\n &self,\n\n id: Self::SourceId,\n\n select: Select,\n\n ) -> BoxFuture<StoreResult<StoreEventStream<Self>>> {\n\n let fut = async move {\n\n let stream_name = format!(\"{}.{}\", self.stream_name, id.to_string());\n\n\n\n let paginator = stream::into_xrange_stream(\n", "file_path": "eventually-redis/src/store.rs", "rank": 23, "score": 57361.83480568989 }, { "content": " self.conn.clone(),\n\n stream_name,\n\n self.stream_page_size,\n\n match select {\n\n Select::All => 0,\n\n Select::From(v) => v as usize,\n\n },\n\n );\n\n\n\n Ok(paginator\n\n .map_err(StoreError::Stream)\n\n .map(move |res| res.map(|v| (id.clone(), v)))\n\n .and_then(move |(id, entry)| async move {\n\n let event: Vec<u8> = entry.get(\"event\").ok_or(StoreError::NoKey(\"event\"))?;\n\n let event: Event =\n\n serde_json::from_slice(&event).map_err(StoreError::DecodeJSON)?;\n\n\n\n let sequence_number: u32 = entry\n\n .get(\"sequence_number\")\n\n .ok_or(StoreError::NoKey(\"sequence_number\"))?;\n", "file_path": "eventually-redis/src/store.rs", "rank": 24, "score": 57361.517931909504 }, { "content": "\n\n let version = stream::parse_version(&entry.id);\n\n\n\n Ok(Persisted::from(id, event)\n\n .sequence_number(sequence_number)\n\n .version(version as u32))\n\n })\n\n .boxed())\n\n };\n\n\n\n Box::pin(fut)\n\n }\n\n\n\n fn stream_all(&self, select: Select) -> BoxFuture<StoreResult<StoreEventStream<Self>>> {\n\n let fut = async move {\n\n let paginator = stream::into_xrange_stream(\n\n self.conn.clone(),\n\n self.stream_name.to_owned(),\n\n self.stream_page_size,\n\n match select {\n", "file_path": "eventually-redis/src/store.rs", "rank": 25, "score": 57360.73265080026 }, { "content": " type Error = StoreError;\n\n\n\n fn append(\n\n &mut self,\n\n id: Self::SourceId,\n\n version: Expected,\n\n events: Vec<Self::Event>,\n\n ) -> BoxFuture<StoreResult<u32>> {\n\n let fut = async move {\n\n let events = events\n\n .iter()\n\n .map(serde_json::to_string)\n\n .collect::<Result<Vec<_>, _>>()\n\n .map_err(StoreError::EncodeEvents)?;\n\n\n\n Ok(APPEND_TO_STORE_SCRIPT\n\n .key(self.stream_name)\n\n .key(id.to_string())\n\n .arg(match version {\n\n Expected::Any => -1,\n", "file_path": "eventually-redis/src/store.rs", "rank": 27, "score": 57355.1607455146 }, { "content": "///\n\n/// [`eventually::EventStore`]: ../eventually/trait.EventStore.html\n\n#[derive(Clone)]\n\npub struct EventStore<Id, Event> {\n\n pub(crate) stream_name: &'static str,\n\n pub(crate) conn: redis::aio::MultiplexedConnection,\n\n pub(crate) stream_page_size: usize,\n\n pub(crate) id: std::marker::PhantomData<Id>,\n\n pub(crate) event: std::marker::PhantomData<Event>,\n\n}\n\n\n\nimpl<Id, Event> eventually::EventStore for EventStore<Id, Event>\n\nwhere\n\n Id: TryFrom<String> + Display + Eq + Clone + Send + Sync,\n\n <Id as TryFrom<String>>::Error: std::error::Error + Send + Sync + 'static,\n\n Event: Serialize + Send + Sync,\n\n for<'de> Event: Deserialize<'de>,\n\n{\n\n type SourceId = Id;\n\n type Event = Event;\n", "file_path": "eventually-redis/src/store.rs", "rank": 28, "score": 57354.298377057734 }, { "content": "lazy_static! {\n\n static ref APPEND_TO_STORE_SCRIPT: redis::Script = redis::Script::new(APPEND_TO_STORE_SOURCE);\n\n}\n\n\n\n/// Result returning the crate [`StoreError`] type.\n\n///\n\n/// [`StoreError`]: enum.Error.html\n\npub type StoreResult<T> = Result<T, StoreError>;\n\n\n\n/// Error types returned by the [`eventually::EventStore`] implementation\n\n/// on the [`EventStore`] type.\n\n///\n\n/// [`eventually::EventStore`]: ../eventually/trait.EventStore.html\n\n/// [`EventStore`]: struct.EventStore.html\n\n#[derive(Debug, thiserror::Error)]\n\npub enum StoreError {\n\n /// Error returned when failed to encode events to JSON during [`append`].\n\n ///\n\n /// [`append`]: struct.EventStore.html#tymethod.append\n\n #[error(\"failed to encode events: {0}\")]\n", "file_path": "eventually-redis/src/store.rs", "rank": 29, "score": 57350.53952321337 }, { "content": " ///\n\n /// [`stream`]: struct.EventStore.html#tymethod.stream\n\n /// [`stream_all`]: struct.EventStore.html#tymethod.stream_all\n\n #[error(\"failed while reading stream from Redis: {0}\")]\n\n Stream(#[source] RedisError),\n\n\n\n /// Error returned when attempting to read a key from the Redis stream\n\n /// that does not exist.\n\n #[error(\"no key from Redis result: `{0}`\")]\n\n NoKey(&'static str),\n\n}\n\n\n\nimpl AppendError for StoreError {\n\n #[inline]\n\n fn is_conflict_error(&self) -> bool {\n\n false\n\n }\n\n}\n\n\n\n/// Redis backend implementation for [`eventually::EventStore`] trait.\n", "file_path": "eventually-redis/src/store.rs", "rank": 30, "score": 57349.079118712856 }, { "content": " EncodeEvents(#[source] serde_json::Error),\n\n\n\n /// Error returned when failed to decoding events from JSON\n\n /// during either [`stream`] or [`stream_all`].\n\n ///\n\n /// [`stream`]: struct.EventStore.html#tymethod.stream\n\n /// [`stream_all`]: struct.EventStore.html#tymethod.stream_all\n\n #[error(\"failed to decode events: {0}\")]\n\n DecodeEvents(#[source] stream::ToPersistedError),\n\n\n\n /// Error returned when failed to decoding events from JSON\n\n /// during either [`stream`] or [`stream_all`].\n\n ///\n\n /// [`stream`]: struct.EventStore.html#tymethod.stream\n\n /// [`stream_all`]: struct.EventStore.html#tymethod.stream_all\n\n #[error(\"failed to decode from JSON: {0}\")]\n\n DecodeJSON(#[source] serde_json::Error),\n\n\n\n /// Error returned when reading the stream coming from `XRANGE .. COUNT n`\n\n /// during either [`stream`] or [`stream_all`].\n", "file_path": "eventually-redis/src/store.rs", "rank": 31, "score": 57344.657125635655 }, { "content": "ALTER SEQUENCE events_number_seq OWNED BY events.sequence_number;\n", "file_path": "eventually-postgres/src/migrations/V1__event_store_tables.sql", "rank": 32, "score": 52014.585783170056 }, { "content": " SELECT aggregates.\"version\" INTO aggregate_version FROM aggregates WHERE id = aggregate_id AND aggregate_type_id = aggregate_type;\n\n IF NOT FOUND THEN\n\n -- Add the initial aggregate representation inside the `aggregates` table.\n\n INSERT INTO aggregates (id, aggregate_type_id)\n\n VALUES (aggregate_id, aggregate_type);\n\n\n\n -- Make sure to initialize the aggregate version in case\n\n aggregate_version = 0;\n\n END IF;\n\n\n\n -- Perform optimistic concurrency check.\n\n IF perform_version_check AND aggregate_version <> current_version THEN\n\n RAISE EXCEPTION 'invalid aggregate version provided: %, expected: %', current_version, aggregate_version;\n\n END IF;\n\n\n\n SELECT last_value INTO sequence_number from events_number_seq;\n\n\n\n FOREACH \"event\" IN ARRAY events\n\n LOOP\n\n -- Increment the aggregate version prior to inserting the new event.\n", "file_path": "eventually-postgres/src/migrations/V3__append_to_store.sql", "rank": 33, "score": 51101.65635714752 }, { "content": " aggregate_version = aggregate_version + 1;\n\n\n\n -- Insert the event into the events table.\n\n -- Version numbers should start from 1; sequence numbers should start from 0.\n\n INSERT INTO events (aggregate_id, aggregate_type, \"version\", \"event\")\n\n VALUES (aggregate_id, aggregate_type, aggregate_version, \"event\")\n\n RETURNING events.sequence_number INTO sequence_number;\n\n\n\n -- Send a notification to all listeners of the newly added events.\n\n PERFORM pg_notify(aggregate_type, ''\n\n || '{'\n\n || '\"source_id\": \"' || aggregate_id || '\" ,'\n\n || '\"version\": ' || aggregate_version || ', '\n\n || '\"sequence_number\": ' || sequence_number || ', '\n\n || '\"event\": ' || \"event\"::TEXT\n\n || '}');\n\n COMMIT;\n\n\n\n END LOOP;\n\n\n\n -- Update the aggregate with the latest version computed.\n\n UPDATE aggregates SET \"version\" = aggregate_version WHERE id = aggregate_id AND aggregate_type_id = aggregate_type;\n\n\n\n -- Update the global offset with the latest sequence number.\n\n UPDATE aggregate_types SET \"offset\" = sequence_number WHERE id = aggregate_type;\n\n\n\nEND;\n\n$$ LANGUAGE PLPGSQL;\n", "file_path": "eventually-postgres/src/migrations/V3__append_to_store.sql", "rank": 34, "score": 51096.76610234765 }, { "content": "/// Error type returned by [`append`](EventStore::append) in [`EventStore`]\n\n/// implementations.\n\npub trait AppendError: std::error::Error {\n\n /// Returns true if the error is due to a version conflict\n\n /// during [`append`](EventStore::append).\n\n fn is_conflict_error(&self) -> bool;\n\n}\n\n\n\nimpl AppendError for std::convert::Infallible {\n\n fn is_conflict_error(&self) -> bool {\n\n false\n\n }\n\n}\n\n\n", "file_path": "eventually-core/src/store.rs", "rank": 35, "score": 45446.48857788331 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct NotificationPayload<Event> {\n\n source_id: String,\n\n version: u32,\n\n sequence_number: u32,\n\n event: Event,\n\n}\n\n\n\nimpl<SourceId, Event> TryFrom<NotificationPayload<Event>> for Persisted<SourceId, Event>\n\nwhere\n\n SourceId: TryFrom<String>,\n\n <SourceId as TryFrom<String>>::Error: std::error::Error + Send + Sync + 'static,\n\n{\n\n type Error = SubscriberError;\n\n\n\n fn try_from(payload: NotificationPayload<Event>) -> Result<Self> {\n\n let source_id: SourceId = payload.source_id.try_into().map_err(|e| {\n\n SubscriberError::Deserialize(format!(\n\n \"could not deserialize source id from string: {:?}\",\n\n e\n\n ))\n\n })?;\n\n\n\n Ok(Persisted::from(source_id, payload.event)\n\n .version(payload.version)\n\n .sequence_number(payload.sequence_number))\n\n }\n\n}\n", "file_path": "eventually-postgres/src/subscriber.rs", "rank": 36, "score": 41853.79802164204 }, { "content": "#[async_trait]\n\npub trait Projection {\n\n /// Type of the Source id, typically an [`AggregateId`].\n\n ///\n\n /// [`AggregateId`]: ../aggregate/type.AggregateId.html\n\n type SourceId: Eq;\n\n\n\n /// Event to be stored in the `EventStore`, typically an\n\n /// [`Aggregate::Event`].\n\n ///\n\n /// [`Aggregate::Event`]:\n\n /// ../aggregate/trait.Aggregate.html#associatedtype.Event\n\n type Event;\n\n\n\n /// Type of the possible error that might occur when projecting\n\n /// the next state.\n\n type Error;\n\n\n\n /// Updates the next value of the `Projection` using the provided event\n\n /// value.\n\n async fn project(\n\n &mut self,\n\n event: Persisted<Self::SourceId, Self::Event>,\n\n ) -> Result<(), Self::Error>;\n\n}\n", "file_path": "eventually-core/src/projection.rs", "rank": 37, "score": 37466.14178663345 }, { "content": "CREATE OR REPLACE FUNCTION get_or_create_subscription(\n\n name TEXT,\n\n aggregate_type_id TEXT\n\n)\n\nRETURNS subscriptions\n\nAS $$\n\n\n\n INSERT INTO subscriptions (name, aggregate_type_id)\n\n VALUES (name, aggregate_type_id)\n\n ON CONFLICT (name)\n\n DO UPDATE SET name=EXCLUDED.name -- Perform update to force row returning.\n\n RETURNING *;\n\n\n\n$$ LANGUAGE SQL;\n", "file_path": "eventually-postgres/src/migrations/V5__get_or_create_subscription.sql", "rank": 38, "score": 36402.37804213301 }, { "content": "CREATE OR REPLACE FUNCTION create_aggregate_type(aggregate_type TEXT)\n\nRETURNS VOID\n\nAS $$\n\n\n\n INSERT INTO aggregate_types (id) VALUES (aggregate_type)\n\n ON CONFLICT (id)\n\n DO NOTHING;\n\n\n\n$$ LANGUAGE SQL;\n", "file_path": "eventually-postgres/src/migrations/V2__create_aggregate_type.sql", "rank": 39, "score": 34462.77345349812 }, { "content": "//! Contain support for [`Projection`], an optimized read model\n\n//! of an [`Aggregate`] or of a number of `Aggregate`s.\n\n//!\n\n//! More information about projections can be found here:\n\n//! <https://eventstore.com/docs/getting-started/projections/index.html>\n\n//!\n\n//! [`Projection`]: trait.Projection.html\n\n//! [`Aggregate`]: ../aggregate/trait.Aggregate.html\n\n\n\nuse async_trait::async_trait;\n\n\n\nuse crate::store::Persisted;\n\n\n\n/// A `Projection` is an optimized read model (or materialized view)\n\n/// of an [`Aggregate`] model(s), that can be assembled by left-folding\n\n/// its previous state and a number of ordered, consecutive events.\n\n///\n\n/// The events passed to a `Projection` have been persisted onto\n\n/// an [`EventStore`] first.\n\n///\n\n/// [`Aggregate`]: ../aggregate/trait.Aggregate.html\n\n/// [`EventStore`]: ../store/trait.EventStore.html\n\n#[async_trait]\n", "file_path": "eventually-core/src/projection.rs", "rank": 40, "score": 30837.616845685276 }, { "content": "///\n\n/// The same builder instance can be used to build multiple instances of\n\n/// [`EventStore`] and [`EventSubscriber`].\n\n///\n\n/// [`EventStore`]: struct.EventStore.html\n\n/// [`EventSubscriber`]: struct.EventSubscriber.html\n\n#[derive(Clone)]\n\npub struct Builder {\n\n client: redis::Client,\n\n stream_page_size: Option<usize>,\n\n}\n\n\n\nimpl Builder {\n\n /// Creates a new builder instance using the specified Redis client.\n\n pub fn new(client: redis::Client) -> Self {\n\n Self {\n\n client,\n\n stream_page_size: None,\n\n }\n\n }\n", "file_path": "eventually-redis/src/lib.rs", "rank": 41, "score": 29711.62395356281 }, { "content": " }\n\n }\n\n\n\n /// Builds a new named [`PersistentSubscription`] instance.\n\n ///\n\n /// [`PersistentSubscription`]: struct.PersistentSubscription.html\n\n pub async fn build_persistent_subscription<Id, Event>(\n\n &self,\n\n subscription_name: &'static str,\n\n ) -> RedisResult<PersistentSubscription<Id, Event>> {\n\n let mut subscription = PersistentSubscription {\n\n stream: self.source_name,\n\n group_name: subscription_name,\n\n conn: self.client.get_multiplexed_async_connection().await?,\n\n stream_page_size: self.stream_page_size.unwrap_or(STREAM_PAGE_DEFAULT),\n\n id: std::marker::PhantomData,\n\n event: std::marker::PhantomData,\n\n };\n\n\n\n subscription.create_consumer_group().await?;\n\n\n\n Ok(subscription)\n\n }\n\n}\n", "file_path": "eventually-redis/src/lib.rs", "rank": 42, "score": 29711.371925045583 }, { "content": " /// [`EventStore`]: struct.EventStore.html\n\n pub async fn build_store<Id, Event>(&self) -> RedisResult<EventStore<Id, Event>> {\n\n Ok(EventStore {\n\n stream_name: self.source_name,\n\n conn: self.client.get_multiplexed_async_connection().await?,\n\n stream_page_size: self.stream_page_size.unwrap_or(STREAM_PAGE_DEFAULT),\n\n id: std::marker::PhantomData,\n\n event: std::marker::PhantomData,\n\n })\n\n }\n\n\n\n /// Builds a new [`EventSubscriber`] instance.\n\n ///\n\n /// [`EventSubscriber`]: struct.EventSubscriber.html\n\n pub fn build_subscriber<Id, Event>(&self) -> EventSubscriber<Id, Event> {\n\n EventSubscriber {\n\n stream_name: self.source_name,\n\n client: self.client.clone(),\n\n id: std::marker::PhantomData,\n\n event: std::marker::PhantomData,\n", "file_path": "eventually-redis/src/lib.rs", "rank": 43, "score": 29708.585794446237 }, { "content": " event: Event,\n\n }\n\n\n\n let fut = async move {\n\n let mut pubsub = self\n\n .client\n\n .get_async_connection()\n\n .await\n\n .map_err(SubscriberError::Connection)?\n\n .into_pubsub();\n\n\n\n pubsub\n\n .subscribe(self.stream_name)\n\n .await\n\n .map_err(SubscriberError::Subscribe)?;\n\n\n\n Ok(pubsub\n\n .into_on_message()\n\n .map(|msg| msg.get_payload::<Vec<u8>>())\n\n .map_err(SubscriberError::Payload)\n", "file_path": "eventually-redis/src/subscriber.rs", "rank": 44, "score": 29708.154250926153 }, { "content": " pub(crate) stream: &'static str,\n\n pub(crate) group_name: &'static str,\n\n pub(crate) conn: redis::aio::MultiplexedConnection,\n\n pub(crate) stream_page_size: usize,\n\n pub(crate) id: std::marker::PhantomData<Id>,\n\n pub(crate) event: std::marker::PhantomData<Event>,\n\n}\n\n\n\nimpl<Id, Event> PersistentSubscription<Id, Event> {\n\n /// Creates the Consumer Group in order to use `XREADGROUP` during\n\n /// [`resume`] processing.\n\n ///\n\n /// [`resume`]: struct.PersistentSubscription.html#method.resume\n\n pub(crate) async fn create_consumer_group(&mut self) -> RedisResult<()> {\n\n let result: RedisResult<()> = self\n\n .conn\n\n .xgroup_create_mkstream(self.stream, self.group_name, 0)\n\n .await;\n\n\n\n if let Err(ref err) = result {\n", "file_path": "eventually-redis/src/subscription.rs", "rank": 45, "score": 29706.14267110995 }, { "content": "use std::convert::TryFrom;\n\nuse std::error::Error;\n\n\n\nuse eventually::store::Persisted;\n\n\n\nuse futures::stream::Stream;\n\n\n\nuse redis::aio::MultiplexedConnection;\n\nuse redis::streams::{StreamId, StreamKey, StreamRangeReply, StreamReadOptions, StreamReadReply};\n\nuse redis::{AsyncCommands, RedisResult};\n\n\n\nuse serde::Deserialize;\n\n\n\n#[derive(Debug)]\n\npub(crate) struct ToPersisted(StreamId);\n\n\n\nimpl From<StreamId> for ToPersisted {\n\n fn from(stream_id: StreamId) -> Self {\n\n Self(stream_id)\n\n }\n", "file_path": "eventually-redis/src/stream.rs", "rank": 46, "score": 29705.307372858413 }, { "content": " BuilderWithSourceName {\n\n client: self.client.clone(),\n\n stream_page_size: self.stream_page_size,\n\n source_name: name,\n\n }\n\n }\n\n}\n\n\n\n/// Second-step builder type for [`EventStore`] and [`EventSubscriber`] types.\n\n///\n\n/// This particular builder type has a source name (i.e. an aggregate type name)\n\n/// specified from [`Builder::source_name`].\n\n///\n\n/// [`Builder::source_name`]: struct.Builder.html#method.source_name\n\n/// [`EventStore`]: struct.EventStore.html\n\n/// [`EventSubscriber`]: struct.EventSubscriber.html\n\n#[derive(Clone)]\n\npub struct BuilderWithSourceName {\n\n client: redis::Client,\n\n source_name: &'static str,\n", "file_path": "eventually-redis/src/lib.rs", "rank": 47, "score": 29705.26159534415 }, { "content": " if let Some(\"BUSYGROUP\") = err.code() {\n\n // Consumer group has already been created, skip error.\n\n return Ok(());\n\n }\n\n }\n\n\n\n result\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<Id, Event> Subscription for PersistentSubscription<Id, Event>\n\nwhere\n\n Id: TryFrom<String> + Debug + Eq + Clone + Send + Sync,\n\n <Id as TryFrom<String>>::Error: std::error::Error + Send + Sync + 'static,\n\n Event: Debug + Send + Sync,\n\n for<'de> Event: Deserialize<'de>,\n\n{\n\n type SourceId = Id;\n\n type Event = Event;\n", "file_path": "eventually-redis/src/subscription.rs", "rank": 48, "score": 29704.74406773443 }, { "content": "\n\npub use store::*;\n\npub use subscriber::*;\n\npub use subscription::*;\n\n\n\nuse redis::RedisResult;\n\n\n\n/// Default size of a paginated request to Redis `XRANGE .. COUNT n`\n\n/// for the [`EventStore::stream`] and [`EventStore::stream_all`] operations.\n\n///\n\n/// Page size can be overridden through the\n\n/// [`EventStoreBuilder::stream_page_size`] option.\n\n///\n\n/// [`EventStore::stream`]: struct.EventStore.html#tymethod.stream\n\n/// [`EventStore::stream_all`]: struct.EventStore.html#tymethod.stream_all\n\n/// [`EventStoreBuilder::stream_page_size`]:\n\n/// struct.EventStoreBuilder.html#method.stream_page_size\n\npub const STREAM_PAGE_DEFAULT: usize = 128;\n\n\n\n/// Builder type for [`EventStore`] and [`EventSubscriber`] types.\n", "file_path": "eventually-redis/src/lib.rs", "rank": 49, "score": 29703.601899855137 }, { "content": "use std::convert::TryFrom;\n\nuse std::fmt::Debug;\n\n\n\nuse eventually::store::Persisted;\n\nuse eventually::subscription::{Subscription, SubscriptionStream};\n\n\n\nuse async_trait::async_trait;\n\nuse futures::stream::{StreamExt, TryStreamExt};\n\nuse futures::TryFutureExt;\n\n\n\nuse redis::streams::StreamKey;\n\nuse redis::{AsyncCommands, RedisError, RedisResult};\n\n\n\nuse serde::Deserialize;\n\n\n\nuse crate::stream;\n\n\n\n/// Result returning the crate [`SubscriptionError`] type.\n\n///\n\n/// [`SubscriptionError`]: enum.Error.html\n", "file_path": "eventually-redis/src/subscription.rs", "rank": 50, "score": 29703.512903928553 }, { "content": " type Error = SubscriptionError;\n\n\n\n fn resume(&self) -> SubscriptionStream<Self> {\n\n let fut = async move {\n\n let keys_stream = stream::into_xread_stream(\n\n self.conn.clone(),\n\n self.stream.to_owned(),\n\n self.group_name.to_owned(),\n\n self.stream_page_size,\n\n );\n\n\n\n Ok(keys_stream\n\n .map_err(SubscriptionError::Stream)\n\n .and_then(|StreamKey { ids, .. }| async move {\n\n Ok(futures::stream::iter(ids.into_iter().map(Ok)))\n\n })\n\n .try_flatten()\n\n .and_then(|entry| async move {\n\n Persisted::<Id, Event>::try_from(stream::ToPersisted::from(entry))\n\n .map_err(SubscriptionError::DecodeEvents)\n", "file_path": "eventually-redis/src/subscription.rs", "rank": 51, "score": 29703.42969153747 }, { "content": " stream_page_size: Option<usize>,\n\n}\n\n\n\nimpl BuilderWithSourceName {\n\n /// Changes the page size used by the [`Stream`] returned in\n\n /// [`EventStore::stream`] and [`EventStore::stream_all`].\n\n ///\n\n /// [`Stream`]: https://docs.rs/futures/0.3/futures/stream/trait.Stream.html\n\n /// [`EventStore::stream`]: struct.EventStore.html#tymethod.stream\n\n /// [`EventStore::stream_all`]: struct.EventStore.html#tymethod.stream_all\n\n pub fn stream_page_size(mut self, size: usize) -> Self {\n\n self.stream_page_size = Some(size);\n\n self\n\n }\n\n\n\n /// Builds a new [`EventStore`] instance.\n\n ///\n\n /// This method returns an `std::future::Future` completing after a\n\n /// connection with Redis is successfully established.\n\n ///\n", "file_path": "eventually-redis/src/lib.rs", "rank": 52, "score": 29702.25092867578 }, { "content": " }))\n\n };\n\n\n\n fut.try_flatten_stream().boxed()\n\n }\n\n\n\n async fn checkpoint(&self, version: u32) -> SubscriptionResult<()> {\n\n let mut conn = self.conn.clone();\n\n let stream_version = format!(\"{}-1\", version);\n\n\n\n let ok: bool = conn\n\n .xack(self.stream, self.group_name, &[&stream_version])\n\n .await\n\n .map_err(|e| SubscriptionError::CheckpointFromRedis(version, e))?;\n\n\n\n if !ok {\n\n return Err(SubscriptionError::Checkpoint(version));\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "eventually-redis/src/subscription.rs", "rank": 53, "score": 29701.944777648783 }, { "content": "use std::convert::TryFrom;\n\nuse std::fmt::Debug;\n\n\n\nuse eventually::store::Persisted;\n\nuse eventually::subscription::EventStream as SubscriberEventStream;\n\n\n\nuse futures::stream::{StreamExt, TryStreamExt};\n\nuse futures::TryFutureExt;\n\n\n\nuse redis::RedisError;\n\n\n\nuse serde::Deserialize;\n\n\n\n/// Result returning the crate [`SubscriberError`] type.\n\n///\n\n/// [`SubscriberError`]: enum.Error.html\n\npub type SubscriberResult<T> = Result<T, SubscriberError>;\n\n\n\n/// Error types returned by the [`eventually::EventSubscriber`] implementation\n\n/// on the [`EventSubscriber`] type.\n", "file_path": "eventually-redis/src/subscriber.rs", "rank": 54, "score": 29701.72802615447 }, { "content": "\n\n /// Changes the page size used by the [`Stream`] returned in\n\n /// [`EventStore::stream`] and [`EventStore::stream_all`].\n\n ///\n\n /// [`Stream`]: https://docs.rs/futures/0.3/futures/stream/trait.Stream.html\n\n /// [`EventStore::stream`]: struct.EventStore.html#tymethod.stream\n\n /// [`EventStore::stream_all`]: struct.EventStore.html#tymethod.stream_all\n\n pub fn stream_page_size(mut self, size: usize) -> Self {\n\n self.stream_page_size = Some(size);\n\n self\n\n }\n\n\n\n /// Assignes the specified source name to a copy of the current builder\n\n /// instance, in order to create [`EventStore`] and [`EventSubscriber`]\n\n /// for the same source type identifier (e.g. the Aggregate type\n\n /// identifier).\n\n ///\n\n /// [`EventStore`]: struct.EventStore.html\n\n /// [`EventSubscriber`]: struct.EventSubscriber.html\n\n pub fn source_name(&self, name: &'static str) -> BuilderWithSourceName {\n", "file_path": "eventually-redis/src/lib.rs", "rank": 55, "score": 29700.74534547709 }, { "content": " .map_err(ToPersistedError::DecodeSourceId)?;\n\n\n\n let event: Vec<u8> = entry.get(\"event\").ok_or(ToPersistedError::NoKey(\"event\"))?;\n\n let event: Event = serde_json::from_slice(&event).map_err(ToPersistedError::DecodeJSON)?;\n\n\n\n let version: u32 = entry\n\n .get(\"version\")\n\n .ok_or(ToPersistedError::NoKey(\"version\"))?;\n\n\n\n let sequence_number = parse_version(&entry.id);\n\n\n\n Ok(Persisted::from(source_id, event)\n\n .sequence_number(sequence_number as u32)\n\n .version(version))\n\n }\n\n}\n\n\n\n/// Returns a [`futures::Stream`] instance out of a paginated series of\n\n/// requests to read a Redis Stream using `XRANGE`.\n\n///\n", "file_path": "eventually-redis/src/stream.rs", "rank": 56, "score": 29700.048419722538 }, { "content": " DecodeJSON(#[source] serde_json::Error),\n\n}\n\n\n\nimpl<SourceId, Event> TryFrom<ToPersisted> for Persisted<SourceId, Event>\n\nwhere\n\n SourceId: TryFrom<String> + Eq + Clone + Send + Sync,\n\n <SourceId as TryFrom<String>>::Error: Error + Send + Sync + 'static,\n\n for<'de> Event: Deserialize<'de>,\n\n{\n\n type Error = ToPersistedError;\n\n\n\n fn try_from(entry: ToPersisted) -> Result<Self, Self::Error> {\n\n let entry = entry.0;\n\n\n\n let source_id: String = entry\n\n .get(\"source_id\")\n\n .ok_or(ToPersistedError::NoKey(\"source_id\"))?;\n\n\n\n let source_id: SourceId = SourceId::try_from(source_id)\n\n .map_err(anyhow::Error::from)\n", "file_path": "eventually-redis/src/stream.rs", "rank": 57, "score": 29699.761624742656 }, { "content": " /// using `XACK` command, due to an error occurred on Redis server.\n\n #[error(\"failed to checkpoint subscription due to Redis error: version {0}, {1}\")]\n\n CheckpointFromRedis(u32, #[source] RedisError),\n\n\n\n /// Error returned when Redis didn't acknowledge an `XACK` command,\n\n /// likely due to an incorrect version number provided.\n\n #[error(\"checkpoint subscription not acknowledged by Redis, check the version: version {0}\")]\n\n Checkpoint(u32),\n\n}\n\n\n\n/// [`Subscription`] implementation with persistent state over a Redis\n\n/// data source.\n\n///\n\n/// `PersistentSubscription` leverages the [Consumer Group] feature\n\n/// offered by Redis to consume events that have been published\n\n/// on a Stream.\n\n///\n\n/// [Consumer Group]: https://redis.io/commands/xreadgroup#consumer-groups-in-30-seconds\n\n#[derive(Clone)]\n\npub struct PersistentSubscription<Id, Event> {\n", "file_path": "eventually-redis/src/subscription.rs", "rank": 58, "score": 29698.919692679712 }, { "content": " .and_then(|payload| async move {\n\n let msg: SubscribeMessage<Event> =\n\n serde_json::from_slice(&payload).map_err(SubscriberError::DecodeMessage)?;\n\n\n\n let source_id = Id::try_from(msg.source_id)\n\n .map_err(anyhow::Error::from)\n\n .map_err(SubscriberError::DecodeSourceId)?;\n\n\n\n Ok(Persisted::from(source_id, msg.event)\n\n .sequence_number(msg.sequence_number)\n\n .version(msg.version))\n\n }))\n\n };\n\n\n\n fut.try_flatten_stream().boxed()\n\n }\n\n}\n", "file_path": "eventually-redis/src/subscriber.rs", "rank": 59, "score": 29697.078760312183 }, { "content": "//! Redis backend implementation for [`eventually` crate](https://crates.io/crates/eventually).\n\n//!\n\n//! ## Event Store\n\n//!\n\n//! `eventually-redis` supports the [`eventually::EventStore`] trait through\n\n//! the [`EventStore`] type.\n\n//!\n\n//! ## Event Subscriber\n\n//!\n\n//! `eventually-redis` supports the [`eventually::EventSubscriber`] trait\n\n//! through the [`EventSubscriber`] type.\n\n//!\n\n//! [`eventually::EventStore`]: ../eventually/trait.EventStore.html\n\n//! [`EventStore`]: struct.EventStore.html\n\n//! [`EventSubscriber`]: struct.EventSubscriber.html\n\n\n\nmod store;\n\nmod stream;\n\nmod subscriber;\n\nmod subscription;\n", "file_path": "eventually-redis/src/lib.rs", "rank": 60, "score": 29696.81250771907 }, { "content": "\n\n /// Error returned when failed to execute the `SUBSCRIBE` command\n\n /// to receive notification on the stream topic.\n\n #[error(\"failed to subscriber to stream events: {0}\")]\n\n Subscribe(#[source] RedisError),\n\n\n\n /// Error returned when attempting to decode the source id from the\n\n /// notification payload.\n\n #[error(\"failed to decode source_id from published message: {0}\")]\n\n DecodeSourceId(#[source] anyhow::Error),\n\n}\n\n\n\n/// Redis backend implementation for [`eventually::EventSubscriber`] trait.\n\n///\n\n/// [`eventually::EventSubscriber`]: ../eventually/trait.EventSubscriber.html\n\n#[derive(Clone)]\n\npub struct EventSubscriber<Id, Event> {\n\n pub(crate) stream_name: &'static str,\n\n pub(crate) client: redis::Client,\n\n pub(crate) id: std::marker::PhantomData<Id>,\n", "file_path": "eventually-redis/src/subscriber.rs", "rank": 61, "score": 29696.560134653315 }, { "content": "}\n\n\n\n#[derive(Debug, thiserror::Error)]\n\npub enum ToPersistedError {\n\n /// Error returned when attempting to read a key from the Redis stream\n\n /// that does not exist.\n\n #[error(\"no key from Redis result: `{0}`\")]\n\n NoKey(&'static str),\n\n\n\n /// Error returned when attempting to decode the source id of one\n\n /// Redis stream entry.\n\n #[error(\"failed to decode source_id from Redis entry: {0}\")]\n\n DecodeSourceId(#[source] anyhow::Error),\n\n\n\n /// Error returned when failed to decoding events from JSON\n\n /// during either [`stream`] or [`stream_all`].\n\n ///\n\n /// [`stream`]: struct.EventStore.html#tymethod.stream\n\n /// [`stream_all`]: struct.EventStore.html#tymethod.stream_all\n\n #[error(\"failed to decode from JSON: {0}\")]\n", "file_path": "eventually-redis/src/stream.rs", "rank": 62, "score": 29696.429355406894 }, { "content": "///\n\n/// [`eventually::EventSubscriber`]: ../eventually/trait.EventSubscriber.html\n\n/// [`EventSubscriber`]: struct.EventSubscriber.html\n\n#[derive(Debug, thiserror::Error)]\n\npub enum SubscriberError {\n\n /// Error returned when failed to establish a [`PubSub`] connection\n\n /// with Redis.\n\n ///\n\n /// [`PubSub`]: https://docs.rs/redis/0.17.0/redis/aio/struct.PubSub.html\n\n #[error(\"failed to establish connection with Redis: {0}\")]\n\n Connection(#[source] RedisError),\n\n\n\n /// Error returned when failed to get the payload from a `SUBSCRIBE` event.\n\n #[error(\"failed to get payload from message: {0}\")]\n\n Payload(#[source] RedisError),\n\n\n\n /// Error returned when failed to decode the payload received\n\n /// from JSON.\n\n #[error(\"failed to decode published message: {0}\")]\n\n DecodeMessage(#[source] serde_json::Error),\n", "file_path": "eventually-redis/src/subscriber.rs", "rank": 63, "score": 29695.924963524536 }, { "content": "/// Each page is as big as `page_size`; for each page requested,\n\n/// all the entries in [`StreamRangeReply`] are yielded in the stream,\n\n/// until the entries are fully exhausted.\n\n///\n\n/// The stream stop when all entries in the Redis Stream have been returned.\n\n///\n\n/// [`futures::Stream`]: https://docs.rs/futures/0.3/futures/stream/trait.Stream.html\n\n/// [`StreamRangeReply`]: https://docs.rs/redis/0.17.0/redis/streams/struct.StreamRangeReply.html\n\npub(crate) fn into_xrange_stream(\n\n mut conn: MultiplexedConnection,\n\n stream_name: String,\n\n page_size: usize,\n\n from: usize,\n\n) -> impl Stream<Item = RedisResult<StreamId>> + 'static {\n\n async_stream::try_stream! {\n\n let mut from = from;\n\n\n\n loop {\n\n let result: StreamRangeReply = conn\n\n .xrange_count(&stream_name, from, \"+\", page_size)\n", "file_path": "eventually-redis/src/stream.rs", "rank": 64, "score": 29695.636177284076 }, { "content": "pub type SubscriptionResult<T> = Result<T, SubscriptionError>;\n\n\n\n/// Error types returned by the [`eventually::Subscription`] implementation\n\n/// on the [`PersistentSubscription`] type.\n\n///\n\n/// [`eventually::Subscription`]: ../eventually/trait.Subscription.html\n\n/// [`PersistentSubscription`]: struct.PersistentSubscription.html\n\n#[derive(Debug, thiserror::Error)]\n\npub enum SubscriptionError {\n\n /// Error returned when failed to decoding events from JSON\n\n /// from the `XREADGROUP` operation.\n\n #[error(\"failed to decode events: {0}\")]\n\n DecodeEvents(#[source] stream::ToPersistedError),\n\n\n\n /// Error returned when reading the stream coming from the `XREADGROUP`\n\n /// operation.\n\n #[error(\"failed while reading stream from Redis: {0}\")]\n\n Stream(#[source] RedisError),\n\n\n\n /// Error returned when failed to acknowledge one Redis message\n", "file_path": "eventually-redis/src/subscription.rs", "rank": 65, "score": 29695.175456443856 }, { "content": "///\n\n/// Each read block should be as big as `page_size`; for each page requested,\n\n/// all the keys in [`StreamReadReply`] are yielded in the stream,\n\n/// until the entries are fully exhausted.\n\n///\n\n/// The stream won't be closed until **program termination** or **explicitly\n\n/// dropped**.\n\n///\n\n/// [`futures::Stream`]: https://docs.rs/futures/0.3/futures/stream/trait.Stream.html\n\n/// [`StreamReadReply`]: https://docs.rs/redis/0.17.0/redis/streams/struct.StreamReadReply.html\n\npub(crate) fn into_xread_stream(\n\n mut conn: MultiplexedConnection,\n\n stream_name: String,\n\n group_name: String,\n\n page_size: usize,\n\n) -> impl Stream<Item = RedisResult<StreamKey>> + 'static {\n\n async_stream::try_stream! {\n\n loop {\n\n let opts = StreamReadOptions::default()\n\n .count(page_size)\n", "file_path": "eventually-redis/src/stream.rs", "rank": 66, "score": 29694.38412030505 }, { "content": " pub(crate) event: std::marker::PhantomData<Event>,\n\n}\n\n\n\nimpl<Id, Event> eventually::EventSubscriber for EventSubscriber<Id, Event>\n\nwhere\n\n Id: TryFrom<String> + Eq + Send + Sync,\n\n <Id as TryFrom<String>>::Error: std::error::Error + Send + Sync + 'static,\n\n Event: Send + Sync,\n\n for<'de> Event: Deserialize<'de>,\n\n{\n\n type SourceId = Id;\n\n type Event = Event;\n\n type Error = SubscriberError;\n\n\n\n fn subscribe_all(&self) -> SubscriberEventStream<Self> {\n\n #[derive(Deserialize)]\n\n struct SubscribeMessage<Event> {\n\n source_id: String,\n\n sequence_number: u32,\n\n version: u32,\n", "file_path": "eventually-redis/src/subscriber.rs", "rank": 67, "score": 29694.183167506613 }, { "content": " .await?;\n\n\n\n let ids = result.ids;\n\n let size = ids.len();\n\n\n\n for id in ids {\n\n from = parse_version(&id.id) + 1;\n\n yield id;\n\n }\n\n\n\n if size < page_size {\n\n break;\n\n }\n\n }\n\n }\n\n}\n\n\n\n/// Returns a long-running [`futures::Stream`] instance returning\n\n/// the results of reading a Redis Stream using Consumer Groups with\n\n/// `XREADGROUP`.\n", "file_path": "eventually-redis/src/stream.rs", "rank": 68, "score": 29693.766249245597 }, { "content": " // TODO: should the consumer name be configurable?\n\n .group(&group_name, \"eventually-consumer\");\n\n\n\n let result: StreamReadReply = conn\n\n .xread_options(&[&stream_name], &[\">\"], &opts)\n\n .await?;\n\n\n\n for key in result.keys {\n\n yield key;\n\n }\n\n }\n\n }\n\n}\n\n\n\n/// Parses the version component from the Entry ID of a Redis Stream entry.\n\npub(crate) fn parse_version(id: &str) -> usize {\n\n let parts: Vec<&str> = id.split('-').collect();\n\n parts[0].parse().unwrap()\n\n}\n", "file_path": "eventually-redis/src/stream.rs", "rank": 69, "score": 29692.82644094476 }, { "content": "use eventually_core::store::{EventStore, Expected, Persisted, Select};\n\nuse eventually_postgres::EventStoreBuilder;\n\n\n\nuse futures::stream::TryStreamExt;\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse testcontainers::core::Docker;\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\n", "file_path": "eventually-postgres/tests/store.rs", "rank": 70, "score": 27687.39034181354 }, { "content": " .expect(\"failed while appending events\");\n\n\n\n // Select::All returns all the events.\n\n let events: Vec<Persisted<String, Event>> = event_store\n\n .stream_all(Select::All)\n\n .await\n\n .expect(\"failed to create first stream\")\n\n .try_collect()\n\n .await\n\n .expect(\"failed to collect events from subscription\");\n\n\n\n assert_eq!(\n\n vec![\n\n Persisted::from(source_id_1.to_owned(), Event::A)\n\n .version(1)\n\n .sequence_number(0),\n\n Persisted::from(source_id_1.to_owned(), Event::B)\n\n .version(2)\n\n .sequence_number(1),\n\n Persisted::from(source_id_1.to_owned(), Event::C)\n", "file_path": "eventually-postgres/tests/store.rs", "rank": 71, "score": 27680.602430767303 }, { "content": " .expect(\"Could not build the pool\");\n\n\n\n let event_store_builder = EventStoreBuilder::migrate_database(pool.clone())\n\n .await\n\n .expect(\"failed to run database migrations\")\n\n .builder(pool);\n\n\n\n let mut event_store = event_store_builder\n\n .build::<String, Event>(source_name)\n\n .await\n\n .expect(\"failed to create event store\");\n\n\n\n event_store\n\n .append(\n\n source_id.to_owned(),\n\n Expected::Exact(0),\n\n vec![Event::A, Event::B, Event::C],\n\n )\n\n .await\n\n .expect(\"failed while appending events\");\n", "file_path": "eventually-postgres/tests/store.rs", "rank": 72, "score": 27679.397570118537 }, { "content": "\n\n // Select::All returns all the events.\n\n let events: Vec<Persisted<String, Event>> = event_store\n\n .stream(source_id.to_owned(), Select::All)\n\n .await\n\n .expect(\"failed to create first stream\")\n\n .try_collect()\n\n .await\n\n .expect(\"failed to collect events from subscription\");\n\n\n\n assert_eq!(\n\n vec![\n\n Persisted::from(source_id.to_owned(), Event::A)\n\n .version(1)\n\n .sequence_number(0),\n\n Persisted::from(source_id.to_owned(), Event::B)\n\n .version(2)\n\n .sequence_number(1),\n\n Persisted::from(source_id.to_owned(), Event::C)\n\n .version(3)\n", "file_path": "eventually-postgres/tests/store.rs", "rank": 73, "score": 27678.296681590513 }, { "content": " let pool = bb8::Pool::builder()\n\n .build(pg_manager)\n\n .await\n\n .expect(\"Could not build the pool\");\n\n\n\n let event_store_builder = EventStoreBuilder::migrate_database(pool.clone())\n\n .await\n\n .expect(\"failed to run database migrations\")\n\n .builder(pool);\n\n\n\n let event_name = \"first_name\";\n\n let ivent_name = \"second_name\";\n\n\n\n #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\n\n enum Ivent {\n\n A(usize),\n\n }\n\n\n\n let mut event_store = event_store_builder\n\n .build::<String, Event>(event_name)\n", "file_path": "eventually-postgres/tests/store.rs", "rank": 74, "score": 27677.150197084913 }, { "content": "//! Contains an [`EventStore`] implementation using PostgreSQL\n\n//! as a backend data store.\n\n//!\n\n//! [`EventStore`]: ../../eventually-core/store/trait.EventStore.html\n\n\n\nuse std::convert::TryFrom;\n\nuse std::fmt::{Debug, Display};\n\nuse std::ops::DerefMut;\n\n\n\nuse eventually_core::aggregate::{Aggregate, AggregateId};\n\nuse eventually_core::store::{AppendError, EventStream, Expected, Persisted, Select};\n\n\n\nuse futures::future::BoxFuture;\n\nuse futures::stream::{StreamExt, TryStreamExt};\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse tokio_postgres::tls::{MakeTlsConnect, TlsConnect};\n\nuse tokio_postgres::Socket;\n\n\n", "file_path": "eventually-postgres/src/store.rs", "rank": 75, "score": 27676.82758378203 }, { "content": " .sequence_number(2)\n\n ],\n\n events\n\n );\n\n\n\n // Select::From returns a slice of the events by their version.\n\n let events: Vec<Persisted<String, Event>> = event_store\n\n .stream(source_id.to_owned(), Select::From(3))\n\n .await\n\n .expect(\"failed to create second stream\")\n\n .try_collect()\n\n .await\n\n .expect(\"failed to collect events from subscription\");\n\n\n\n assert_eq!(\n\n vec![Persisted::from(source_id.to_owned(), Event::C)\n\n .version(3)\n\n .sequence_number(2)],\n\n events\n\n );\n\n}\n", "file_path": "eventually-postgres/tests/store.rs", "rank": 76, "score": 27676.707165081632 }, { "content": " node.get_host_port(5432).unwrap()\n\n );\n\n\n\n let pg_manager =\n\n bb8_postgres::PostgresConnectionManager::new_from_stringlike(&dsn, tokio_postgres::NoTls)\n\n .expect(\"Could not parse the dsn string\");\n\n let pool = bb8::Pool::builder()\n\n .build(pg_manager)\n\n .await\n\n .expect(\"Could not build the pool\");\n\n\n\n let event_store_builder = EventStoreBuilder::migrate_database(pool.clone())\n\n .await\n\n .expect(\"failed to run database migrations\")\n\n .builder(pool);\n\n let source_name = \"stream_all_test\";\n\n let source_id_1 = \"stream_all_test_1\";\n\n let source_id_2 = \"stream_all_test_2\";\n\n\n\n let mut event_store = event_store_builder\n", "file_path": "eventually-postgres/tests/store.rs", "rank": 77, "score": 27676.542231413285 }, { "content": "//! Contains the Event Store trait for storing and streaming\n\n//! [`Aggregate::Event`](super::aggregate::Aggregate::Event)s.\n\n\n\nuse std::ops::Deref;\n\n\n\nuse futures::future::BoxFuture;\n\nuse futures::stream::BoxStream;\n\n\n\n#[cfg(feature = \"serde\")]\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::versioning::Versioned;\n\n\n\n/// Selection operation for the events to capture in an [`EventStream`].\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n\npub enum Select {\n\n /// To return all the [`Event`](EventStore::Event)s in the [`EventStream`].\n\n All,\n\n\n\n /// To return a slice of the [`EventStream`], starting from\n", "file_path": "eventually-core/src/store.rs", "rank": 78, "score": 27676.510868087942 }, { "content": " .await\n\n .expect(\"Failed to create event store\");\n\n let mut ivent_store = event_store_builder\n\n .build::<String, Ivent>(ivent_name)\n\n .await\n\n .expect(\"Failed to create ivent store\");\n\n let shared_id = \"first!\";\n\n event_store\n\n .append(\n\n shared_id.to_owned(),\n\n Expected::Exact(0),\n\n vec![Event::A, Event::B],\n\n )\n\n .await\n\n .expect(\"Failed appending events\");\n\n ivent_store\n\n .append(shared_id.to_owned(), Expected::Exact(0), vec![Ivent::A(1)])\n\n .await\n\n .expect(\"Failed appending ivents\");\n\n let ivents: Vec<Persisted<String, Ivent>> = ivent_store\n", "file_path": "eventually-postgres/tests/store.rs", "rank": 79, "score": 27676.237947202368 }, { "content": " .stream_all(Select::All)\n\n .await\n\n .expect(\"failed to create first stream\")\n\n .try_collect()\n\n .await\n\n .expect(\"failed to collect ivents from subscription\");\n\n let events: Vec<Persisted<String, Event>> = event_store\n\n .stream_all(Select::All)\n\n .await\n\n .expect(\"failed to create second stream\")\n\n .try_collect()\n\n .await\n\n .expect(\"failed to collect events from subscription\");\n\n assert_eq!(\n\n vec![Persisted::from(shared_id.to_owned(), Ivent::A(1))\n\n .version(1)\n\n .sequence_number(2),],\n\n ivents\n\n );\n\n assert_eq!(\n", "file_path": "eventually-postgres/tests/store.rs", "rank": 80, "score": 27675.560600154502 }, { "content": " .build::<String, Event>(source_name)\n\n .await\n\n .expect(\"failed to create event store\");\n\n\n\n event_store\n\n .append(\n\n source_id_1.to_owned(),\n\n Expected::Exact(0),\n\n vec![Event::A, Event::B, Event::C],\n\n )\n\n .await\n\n .expect(\"failed while appending events\");\n\n\n\n event_store\n\n .append(\n\n source_id_2.to_owned(),\n\n Expected::Exact(0),\n\n vec![Event::C, Event::A, Event::B],\n\n )\n\n .await\n", "file_path": "eventually-postgres/tests/store.rs", "rank": 81, "score": 27674.283177724443 }, { "content": " err,\n\n level = \"debug\",\n\n name = \"EventStore::create_aggregate_type\",\n\n skip(self)\n\n )\n\n )]\n\n async fn create_aggregate_type(&self) -> PoolResult<()> {\n\n let params: Params = &[&self.type_name];\n\n\n\n let client = self.pool.get().await?;\n\n client.execute(CREATE_AGGREGATE_TYPE, params).await?;\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<Id, Event, Tls> EventStore<Id, Event, Tls>\n\nwhere\n\n Id: TryFrom<String> + Display + Eq + Send + Sync,\n\n // This bound is for the translation into an anyhow::Error.\n", "file_path": "eventually-postgres/src/store.rs", "rank": 82, "score": 27673.35674321219 }, { "content": " .version(3)\n\n .sequence_number(2),\n\n Persisted::from(source_id_2.to_owned(), Event::C)\n\n .version(1)\n\n .sequence_number(3),\n\n Persisted::from(source_id_2.to_owned(), Event::A)\n\n .version(2)\n\n .sequence_number(4),\n\n Persisted::from(source_id_2.to_owned(), Event::B)\n\n .version(3)\n\n .sequence_number(5)\n\n ],\n\n events\n\n );\n\n\n\n // Select::From returns a slice of the events by their sequence number,\n\n // in this case it will return only events coming from the second source.\n\n let events: Vec<Persisted<String, Event>> = event_store\n\n .stream_all(Select::From(3))\n\n .await\n", "file_path": "eventually-postgres/tests/store.rs", "rank": 83, "score": 27673.355707006394 }, { "content": " <Id as TryFrom<String>>::Error: std::error::Error + Send + Sync + 'static,\n\n Event: Serialize + Send + Sync + Debug,\n\n for<'de> Event: Deserialize<'de>,\n\n Tls: MakeTlsConnect<Socket> + Clone + Send + Sync + 'static,\n\n <Tls as MakeTlsConnect<Socket>>::Stream: Send + Sync,\n\n <Tls as MakeTlsConnect<Socket>>::TlsConnect: Send,\n\n <<Tls as MakeTlsConnect<Socket>>::TlsConnect as TlsConnect<Socket>>::Future: Send,\n\n{\n\n async fn stream_query(&self, query: &str, params: Params<'_>) -> Result<EventStream<'_, Self>> {\n\n let client = self.pool.get().await?;\n\n Ok(client\n\n .query_raw(query, slice_iter(params))\n\n .await\n\n .map_err(Error::from)?\n\n .map_err(Error::from)\n\n .and_then(|row| async move {\n\n let event: Event = serde_json::from_value(\n\n row.try_get(\"event\")\n\n .map_err(anyhow::Error::from)\n\n .map_err(Error::DecodeEvent)?,\n", "file_path": "eventually-postgres/src/store.rs", "rank": 84, "score": 27672.539007413565 }, { "content": "\n\n Box::pin(fut)\n\n }\n\n\n\n fn stream_all(&self, select: Select) -> BoxFuture<Result<EventStream<Self>>> {\n\n #[cfg(feature = \"with-tracing\")]\n\n let span = tracing::info_span!(\n\n \"EventStore::stream_all\",\n\n select = ?select\n\n );\n\n\n\n let fut = async move {\n\n let from = match select {\n\n Select::All => 0i64,\n\n Select::From(v) => v as i64,\n\n };\n\n\n\n let params: Params = &[&self.type_name, &from];\n\n\n\n self.stream_query(STREAM_ALL, params).await\n", "file_path": "eventually-postgres/src/store.rs", "rank": 85, "score": 27672.06782645111 }, { "content": " &check,\n\n &serialized,\n\n ];\n\n\n\n let client = self.pool.get().await?;\n\n let row = client.query_one(APPEND, params).await?;\n\n\n\n let id: i32 = row.try_get(\"aggregate_version\")?;\n\n Ok(id as u32)\n\n };\n\n\n\n #[cfg(feature = \"with-tracing\")]\n\n let fut = fut.instrument(span);\n\n\n\n Box::pin(fut)\n\n }\n\n\n\n fn stream(&self, id: Self::SourceId, select: Select) -> BoxFuture<Result<EventStream<Self>>> {\n\n #[cfg(feature = \"with-tracing\")]\n\n let span = tracing::info_span!(\n", "file_path": "eventually-postgres/src/store.rs", "rank": 86, "score": 27672.039682206192 }, { "content": " \"EventStore::stream\",\n\n id = %id,\n\n select = ?select,\n\n );\n\n\n\n let fut = async move {\n\n let from = match select {\n\n Select::All => 0i32,\n\n Select::From(v) => v as i32,\n\n };\n\n\n\n let id = id.to_string();\n\n\n\n let params: Params = &[&self.type_name, &id, &from];\n\n\n\n self.stream_query(STREAM, params).await\n\n };\n\n\n\n #[cfg(feature = \"with-tracing\")]\n\n let fut = fut.instrument(span);\n", "file_path": "eventually-postgres/src/store.rs", "rank": 87, "score": 27671.798090474054 }, { "content": " };\n\n\n\n #[cfg(feature = \"with-tracing\")]\n\n let fut = fut.instrument(span);\n\n\n\n Box::pin(fut)\n\n }\n\n\n\n fn remove(&mut self, id: Self::SourceId) -> BoxFuture<Result<()>> {\n\n #[cfg(feature = \"with-tracing\")]\n\n let span = tracing::info_span!(\n\n \"EventStore::remove\",\n\n id = %id,\n\n );\n\n\n\n let fut = async move {\n\n let client = self.pool.get().await?;\n\n Ok(client\n\n .execute(REMOVE, &[&self.type_name, &id.to_string()])\n\n .await\n", "file_path": "eventually-postgres/src/store.rs", "rank": 88, "score": 27670.69001771571 }, { "content": " /// [`EventStore`]: struct.EventStore.html\n\n #[inline]\n\n pub async fn build<Id, Event>(\n\n &self,\n\n type_name: &'static str,\n\n ) -> PoolResult<EventStore<Id, Event, Tls>> {\n\n let store = EventStore {\n\n pool: self.pool.clone(),\n\n type_name,\n\n id: std::marker::PhantomData,\n\n payload: std::marker::PhantomData,\n\n };\n\n\n\n store.create_aggregate_type().await?;\n\n\n\n Ok(store)\n\n }\n\n\n\n /// Creates a new [`EventStore`] for an [`Aggregate`] type.\n\n ///\n", "file_path": "eventually-postgres/src/store.rs", "rank": 89, "score": 27670.27479371746 }, { "content": " .expect(\"failed to create second stream\")\n\n .try_collect()\n\n .await\n\n .expect(\"failed to collect events from subscription\");\n\n\n\n assert_eq!(\n\n vec![\n\n Persisted::from(source_id_2.to_owned(), Event::C)\n\n .version(1)\n\n .sequence_number(3),\n\n Persisted::from(source_id_2.to_owned(), Event::A)\n\n .version(2)\n\n .sequence_number(4),\n\n Persisted::from(source_id_2.to_owned(), Event::B)\n\n .version(3)\n\n .sequence_number(5)\n\n ],\n\n events\n\n );\n\n}\n", "file_path": "eventually-postgres/tests/store.rs", "rank": 90, "score": 27670.091214446325 }, { "content": " pub async fn migrate_database<Tls>(\n\n pool: Pool<PostgresConnectionManager<Tls>>,\n\n ) -> anyhow::Result<Self>\n\n where\n\n Tls: MakeTlsConnect<Socket> + Clone + Send + Sync + 'static,\n\n <Tls as MakeTlsConnect<Socket>>::Stream: Send + Sync,\n\n <Tls as MakeTlsConnect<Socket>>::TlsConnect: Send,\n\n <<Tls as MakeTlsConnect<Socket>>::TlsConnect as TlsConnect<Socket>>::Future: Send,\n\n {\n\n let mut connection = pool.get().await?;\n\n embedded::migrations::runner()\n\n .run_async(connection.deref_mut())\n\n .await?;\n\n\n\n Ok(Self { inner: () })\n\n }\n\n\n\n /// Returns a new builder instance after migrations have been completed.\n\n pub fn builder<Tls>(\n\n self,\n", "file_path": "eventually-postgres/src/store.rs", "rank": 91, "score": 27669.91681902112 }, { "content": "\n\n#[tokio::test]\n\nasync fn stream_works() {\n\n let source_name = \"stream_test\";\n\n let source_id = \"stream_test\";\n\n let docker = testcontainers::clients::Cli::default();\n\n let postgres_image = testcontainers::images::postgres::Postgres::default();\n\n let node = docker.run(postgres_image);\n\n\n\n let dsn = format!(\n\n \"postgres://postgres:postgres@localhost:{}/postgres\",\n\n node.get_host_port(5432).unwrap()\n\n );\n\n\n\n let pg_manager =\n\n bb8_postgres::PostgresConnectionManager::new_from_stringlike(&dsn, tokio_postgres::NoTls)\n\n .expect(\"Could not parse the dsn string\");\n\n let pool = bb8::Pool::builder()\n\n .build(pg_manager)\n\n .await\n", "file_path": "eventually-postgres/tests/store.rs", "rank": 92, "score": 27669.405821698005 }, { "content": " /// back to the application, disregarding the\n\n /// [`SourceId`](EventStore::SourceId) values but using a [`Select`]\n\n /// operation.\n\n ///\n\n /// [`SourceId`](EventStore::SourceId) will be used to request a particular\n\n /// [`EventStream`].\n\n ///\n\n /// [`Select`] specifies the selection strategy for the\n\n /// [`Event`](EventStore::Event)s in the returned [`EventStream`]: take\n\n /// a look at type documentation for all the available options.\n\n fn stream_all(&self, select: Select) -> BoxFuture<Result<EventStream<Self>, Self::Error>>;\n\n\n\n /// Drops all the [`Event`](EventStore::Event)s related to one `Source`,\n\n /// specified by the provided [`SourceId`](EventStore::SourceId).\n\n ///\n\n /// [`Event`]: trait.EventStore.html#associatedtype.Event\n\n fn remove(&mut self, source_id: Self::SourceId) -> BoxFuture<Result<(), Self::Error>>;\n\n}\n\n\n\n/// An [`Event`](EventStore::Event) wrapper for events that have been\n", "file_path": "eventually-core/src/store.rs", "rank": 93, "score": 27669.39073221606 }, { "content": " vec![\n\n Persisted::from(shared_id.to_owned(), Event::A)\n\n .version(1)\n\n .sequence_number(0),\n\n Persisted::from(shared_id.to_owned(), Event::B)\n\n .version(2)\n\n .sequence_number(1),\n\n ],\n\n events\n\n );\n\n}\n\n\n\n#[tokio::test]\n\nasync fn stream_all_works() {\n\n let docker = testcontainers::clients::Cli::default();\n\n let postgres_image = testcontainers::images::postgres::Postgres::default();\n\n let node = docker.run(postgres_image);\n\n\n\n let dsn = format!(\n\n \"postgres://postgres:postgres@localhost:{}/postgres\",\n", "file_path": "eventually-postgres/tests/store.rs", "rank": 94, "score": 27668.55366489293 }, { "content": " }\n\n\n\n /// Returns the [`SourceId`](EventStore::SourceId) of the persisted event.\n\n #[inline]\n\n pub fn source_id(&self) -> &SourceId {\n\n &self.source_id\n\n }\n\n\n\n /// Unwraps the inner [`Event`](EventStore::Event) from the `Persisted`\n\n /// wrapper.\n\n #[inline]\n\n pub fn take(self) -> T {\n\n self.event\n\n }\n\n}\n\n\n\n/// Contains a type-state builder for [`Persisted`] type.\n\npub mod persistent {\n\n /// Creates a new [`Persisted`](super::Persisted) by wrapping an Event\n\n /// value.\n", "file_path": "eventually-core/src/store.rs", "rank": 95, "score": 27668.53233267462 }, { "content": "/// successfully committed to the [`EventStore`].\n\n///\n\n/// [`EventStream`]s are composed of these events.\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\n#[cfg_attr(feature = \"serde\", derive(Serialize, Deserialize))]\n\npub struct Persisted<SourceId, T> {\n\n source_id: SourceId,\n\n version: u32,\n\n sequence_number: u32,\n\n #[cfg_attr(feature = \"serde\", serde(flatten))]\n\n event: T,\n\n}\n\n\n\nimpl<SourceId, T> Versioned for Persisted<SourceId, T> {\n\n #[inline]\n\n fn version(&self) -> u32 {\n\n self.version\n\n }\n\n}\n\n\n", "file_path": "eventually-core/src/store.rs", "rank": 96, "score": 27668.27037002277 }, { "content": " for<'de> Event: Deserialize<'de>,\n\n Tls: MakeTlsConnect<Socket> + Clone + Send + Sync + 'static,\n\n <Tls as MakeTlsConnect<Socket>>::Stream: Send + Sync,\n\n <Tls as MakeTlsConnect<Socket>>::TlsConnect: Send,\n\n <<Tls as MakeTlsConnect<Socket>>::TlsConnect as TlsConnect<Socket>>::Future: Send,\n\n{\n\n type SourceId = Id;\n\n type Event = Event;\n\n type Error = Error;\n\n\n\n fn append(\n\n &mut self,\n\n id: Self::SourceId,\n\n version: Expected,\n\n events: Vec<Self::Event>,\n\n ) -> BoxFuture<Result<u32>> {\n\n #[cfg(feature = \"with-tracing\")]\n\n let span = tracing::info_span!(\n\n \"EventStore::append\",\n\n id = %id,\n", "file_path": "eventually-postgres/src/store.rs", "rank": 97, "score": 27668.044752070447 }, { "content": " pool: Pool<PostgresConnectionManager<Tls>>,\n\n ) -> EventStoreBuilderMigrated<Tls>\n\n where\n\n Tls: MakeTlsConnect<Socket> + Clone + Send + Sync + 'static,\n\n <Tls as MakeTlsConnect<Socket>>::Stream: Send + Sync,\n\n <Tls as MakeTlsConnect<Socket>>::TlsConnect: Send,\n\n <<Tls as MakeTlsConnect<Socket>>::TlsConnect as TlsConnect<Socket>>::Future: Send,\n\n {\n\n EventStoreBuilderMigrated { pool }\n\n }\n\n}\n\n\n\n/// Builder step for [`EventStore`] instances,\n\n/// after the database migration executed from [`EventStoreBuilder`]\n\n/// has been completed.\n\n///\n\n/// [`EventStore`]: struct.EventStore.html\n\n/// [`EventStoreBuilder`]: struct.EventStoreBuilder.html\n\npub struct EventStoreBuilderMigrated<Tls>\n\nwhere\n", "file_path": "eventually-postgres/src/store.rs", "rank": 98, "score": 27667.964175139638 }, { "content": " events: Vec<Self::Event>,\n\n ) -> BoxFuture<Result<u32, Self::Error>>;\n\n\n\n /// Streams a list of [`Event`](EventStore::Event)s from the [`EventStore`]\n\n /// back to the application, by specifying the desired\n\n /// [`SourceId`](EventStore::SourceId) and [`Select`] operation.\n\n ///\n\n /// [`SourceId`](EventStore::SourceId) will be used to request a particular\n\n /// `EventStream`.\n\n ///\n\n /// [`Select`] specifies the selection strategy for the\n\n /// [`Event`](EventStore::Event)s in the returned [`EventStream`]: take\n\n /// a look at type documentation for all the available options.\n\n fn stream(\n\n &self,\n\n source_id: Self::SourceId,\n\n select: Select,\n\n ) -> BoxFuture<Result<EventStream<Self>, Self::Error>>;\n\n\n\n /// Streams a list of [`Event`](EventStore::Event)s from the [`EventStore`]\n", "file_path": "eventually-core/src/store.rs", "rank": 99, "score": 27667.323300930075 } ]